cevro-messenger-sdk 0.1.17 → 0.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/index.js +885 -20
- package/dist/esm/index.js.map +1 -1
- package/dist/types/core/ApiClient.d.ts +24 -1
- package/dist/types/core/ApiClient.d.ts.map +1 -1
- package/dist/types/core/CevroMessenger.d.ts +15 -0
- package/dist/types/core/CevroMessenger.d.ts.map +1 -1
- package/dist/types/i18n/strings.d.ts +11 -0
- package/dist/types/i18n/strings.d.ts.map +1 -1
- package/dist/types/types/index.d.ts +37 -0
- package/dist/types/types/index.d.ts.map +1 -1
- package/dist/types/ui/ChatWindow.d.ts +23 -0
- package/dist/types/ui/ChatWindow.d.ts.map +1 -1
- package/dist/types/ui/ConversationList.d.ts +52 -0
- package/dist/types/ui/ConversationList.d.ts.map +1 -0
- package/dist/types/ui/MessageList.d.ts +39 -1
- package/dist/types/ui/MessageList.d.ts.map +1 -1
- package/dist/types/ui/PastConversation.d.ts +42 -0
- package/dist/types/ui/PastConversation.d.ts.map +1 -0
- package/dist/types/utils/session.d.ts +10 -2
- package/dist/types/utils/session.d.ts.map +1 -1
- package/dist/umd/cevro-messenger.min.js +1 -1
- package/dist/umd/cevro-messenger.min.js.map +1 -1
- package/package.json +1 -1
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=Object.defineProperty,t=(t,i,s)=>((t,i,s)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[i]=s)(t,"symbol"!=typeof i?i+"":i,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i='#cevro-messenger-container{--cevro-primary: #8B5CF6;--cevro-primary-hover: #7C3AED;--cevro-primary-light: #A78BFA;--cevro-bg: #ffffff;--cevro-bg-secondary: #f9fafb;--cevro-bg-input: #ffffff;--cevro-text: #111827;--cevro-text-secondary: #6b7280;--cevro-border: #e5e7eb;--cevro-shadow: 0 10px 40px rgba(0, 0, 0, .15);--cevro-shadow-sm: 0 2px 8px rgba(0, 0, 0, .08);--cevro-radius: 16px;--cevro-radius-sm: 12px;--cevro-radius-md: 8px;--cevro-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;--cevro-transition: .2s ease;--cevro-header-bg: var(--cevro-bg);--cevro-header-text: var(--cevro-text);--cevro-user-msg-bg: var(--cevro-bg);--cevro-user-msg-text: var(--cevro-text);--cevro-launcher-bg: var(--cevro-primary);--cevro-launcher-icon: #ffffff;--cevro-launcher-hover-shadow: rgba(139, 92, 246, .4);--cevro-focus-ring: rgba(139, 92, 246, .2);--cevro-send-btn-bg: var(--cevro-primary);--cevro-send-btn-icon: #ffffff;--cevro-file-btn-bg: var(--cevro-bg);--cevro-file-btn-icon: var(--cevro-text-secondary);--cevro-file-btn-border: var(--cevro-border);--cevro-agent-msg-bg: var(--cevro-primary);--cevro-agent-msg-text: #ffffff}.cevro-launcher{position:fixed;z-index:2147483647;font-family:var(--cevro-font)}.cevro-launcher__button{width:56px;height:56px;border-radius:50%;border:none;background-color:var(--cevro-launcher-bg);color:var(--cevro-launcher-icon);cursor:pointer;box-shadow:var(--cevro-shadow);display:flex;align-items:center;justify-content:center;transition:transform var(--cevro-transition),box-shadow var(--cevro-transition);position:relative}.cevro-launcher__button:hover{transform:scale(1.05);box-shadow:0 12px 48px var(--cevro-launcher-hover-shadow)}.cevro-launcher__button:active{transform:scale(.95)}.cevro-launcher__icon{width:24px;height:24px;transition:opacity var(--cevro-transition),transform var(--cevro-transition)}.cevro-launcher__icon--chat{opacity:1;transform:scale(1)}.cevro-launcher__icon--close{position:absolute;opacity:0;transform:scale(.5)}.cevro-launcher--open .cevro-launcher__icon--chat{opacity:0;transform:scale(.5)}.cevro-launcher--open .cevro-launcher__icon--close{opacity:1;transform:scale(1)}.cevro-launcher__badge{position:absolute;top:-4px;right:-4px;min-width:20px;height:20px;padding:0 6px;background-color:#ef4444;color:#fff;font-size:12px;font-weight:600;border-radius:10px;display:flex;align-items:center;justify-content:center;border:2px solid white}.cevro-chat-window{position:fixed;bottom:96px;right:20px;width:380px;height:600px;max-height:calc(100vh - 100px);background-color:var(--cevro-bg);border-radius:var(--cevro-radius);box-shadow:var(--cevro-shadow);display:flex;flex-direction:column;overflow:hidden;font-family:var(--cevro-font);z-index:2147483646;opacity:0;visibility:hidden;transform:translateY(20px) scale(.95);transition:opacity .25s ease,transform .25s ease,visibility .25s ease}.cevro-chat-window--visible{opacity:1;visibility:visible;transform:translateY(0) scale(1)}.cevro-chat-window--prechat{height:auto;max-height:calc(100vh - 100px);max-height:calc(100dvh - 100px)}@media (max-width: 480px){.cevro-chat-window{width:100%!important;height:100%!important;height:100dvh!important;max-height:100%!important;bottom:0!important;right:0!important;left:0!important;border-radius:0;padding-top:env(safe-area-inset-top);padding-bottom:env(safe-area-inset-bottom)}.cevro-chat-window__input,.cevro-prechat__input,.cevro-csat__feedback,.cevro-csat-inline__feedback{font-size:16px}.cevro-launcher--open{display:none}}@media (max-height: 500px){.cevro-chat-window__footer,.cevro-prechat__powered-by{display:none}}.cevro-chat-window__header{background:var(--cevro-header-bg);color:var(--cevro-header-text);padding:16px 20px;display:flex;align-items:center;gap:12px;flex-shrink:0;border-bottom:1px solid var(--cevro-border)}.cevro-chat-window__logo{width:40px;height:40px;border-radius:8px;overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center}.cevro-chat-window__logo svg{width:100%;height:100%}.cevro-chat-window__title-section{flex:1;min-width:0}.cevro-chat-window__title{margin:0;font-size:16px;font-weight:600}.cevro-chat-window__subtitle{margin:2px 0 0;font-size:12px;color:var(--cevro-text-secondary)}.cevro-chat-window__close{background:none;border:none;color:var(--cevro-text-secondary);cursor:pointer;padding:10px;margin:-10px;min-width:44px;min-height:44px;transition:color var(--cevro-transition);display:flex;align-items:center;justify-content:center}.cevro-chat-window__close:hover{color:var(--cevro-text)}.cevro-messages{flex:1;overflow:hidden;display:flex;flex-direction:column;background-color:var(--cevro-bg)}.cevro-messages--fade-in{animation:cevro-fade-in .3s ease}.cevro-messages__container{flex:1;overflow-y:auto;overflow-x:hidden;padding:16px;display:flex;flex-direction:column;gap:8px}.cevro-message{display:flex;align-items:flex-start;max-width:80%;animation:none}.cevro-message--animate{animation:cevro-message-in .3s ease}@keyframes cevro-message-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.cevro-message--inbound{align-self:flex-start}.cevro-message--outbound{align-self:flex-end}.cevro-message__avatar{width:28px;height:28px;min-width:28px;min-height:28px;border-radius:50%;overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center;align-self:flex-end;margin-right:8px;background:var(--cevro-agent-msg-bg)}.cevro-message__avatar svg{width:18px;height:18px}.cevro-message__avatar-img{width:100%;height:100%;object-fit:cover}.cevro-message__avatar--human{background:#6366f1}.cevro-message__avatar-initials{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;color:#fff;line-height:1}.cevro-message__sender-name{font-size:11px;font-weight:600;color:var(--cevro-text-secondary);margin-bottom:2px;padding-left:2px}.cevro-message__content-wrapper{display:flex;flex-direction:column;gap:4px}.cevro-message--outbound .cevro-message__content-wrapper{align-items:flex-end}.cevro-message__bubble{padding:10px 14px;border-radius:var(--cevro-radius-sm);word-wrap:break-word;overflow-wrap:break-word;word-break:break-word;min-width:0}.cevro-message--inbound .cevro-message__bubble{background-color:var(--cevro-agent-msg-bg);color:var(--cevro-agent-msg-text);border-bottom-left-radius:4px}.cevro-message--outbound .cevro-message__bubble{background-color:var(--cevro-user-msg-bg);color:var(--cevro-user-msg-text);border:1px solid var(--cevro-border);box-shadow:var(--cevro-shadow-sm);border-bottom-right-radius:4px}.cevro-message__text{font-size:14px;line-height:1.5}.cevro-message--inbound .cevro-message__text a{color:inherit;text-decoration:underline;font-weight:500}.cevro-message--outbound .cevro-message__text a{color:var(--cevro-primary);text-decoration:underline}.cevro-message--inbound .cevro-message__text code{background-color:#fff3;padding:2px 4px;border-radius:4px;font-family:monospace;font-size:13px}.cevro-message--outbound .cevro-message__text code{background-color:#0000000d;padding:2px 4px;border-radius:4px;font-family:monospace;font-size:13px}.cevro-message__image-container{position:relative;display:inline-block;max-width:100%}.cevro-message__image{max-width:100%;max-height:300px;border-radius:var(--cevro-radius-sm);display:block}.cevro-file-progress-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:#00000080;border-radius:var(--cevro-radius-sm);display:flex;align-items:center;justify-content:center}.cevro-file-progress-overlay .cevro-file-progress{width:80%;text-align:center}.cevro-file-progress-overlay .cevro-file-progress__bar{background:#ffffff4d}.cevro-file-progress-overlay .cevro-file-progress__fill{background:#fff}.cevro-file-progress-overlay .cevro-file-progress__text{color:#fff;font-size:12px;margin-top:4px;display:block}.cevro-file-card{display:flex;align-items:center;gap:12px;padding:12px;background:#ffffff1a;border-radius:var(--cevro-radius-sm);min-width:200px;max-width:280px;transition:background var(--cevro-transition)}.cevro-message--outbound .cevro-file-card{background:#0000000d}.cevro-file-card:hover{background:#fff3}.cevro-message--outbound .cevro-file-card:hover{background:#00000014}.cevro-file-card__icon{flex-shrink:0;width:40px;height:40px;display:flex;align-items:center;justify-content:center}.cevro-file-card__icon svg{width:36px;height:36px}.cevro-file-card__info{flex:1;min-width:0;overflow:hidden}.cevro-file-card__name{font-size:13px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:inherit}.cevro-file-card__details{font-size:11px;opacity:.7;margin-top:2px}.cevro-file-card__progress{flex-shrink:0;width:60px}.cevro-file-progress{width:100%}.cevro-file-progress__bar{height:4px;background:#0000001a;border-radius:2px;overflow:hidden}.cevro-message--outbound .cevro-file-progress__bar{background:#0000001a}.cevro-message--inbound .cevro-file-progress__bar{background:#fff3}.cevro-file-progress__fill{height:100%;background:var(--cevro-primary);border-radius:2px;transition:width .2s ease}.cevro-message--inbound .cevro-file-progress__fill{background:#fff}.cevro-file-progress__text{font-size:10px;opacity:.7;margin-top:2px;display:block;text-align:right}.cevro-message__attachment{display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none;padding:8px 12px;background-color:#ffffff26;border-radius:var(--cevro-radius-sm);font-size:13px}.cevro-message--outbound .cevro-message__attachment{background-color:#0000000d}.cevro-message__attachment:hover{background-color:#ffffff40}.cevro-message--outbound .cevro-message__attachment:hover{background-color:#00000014}.cevro-message__meta{display:flex;align-items:center;gap:4px;font-size:11px;color:var(--cevro-text-secondary);padding:0 4px}.cevro-message__status{display:flex;align-items:center}.cevro-message__quick-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}.cevro-message__quick-action{padding:8px 16px;background-color:var(--cevro-bg);border:1px solid var(--cevro-border);color:var(--cevro-text);border-radius:20px;font-size:13px;cursor:pointer;transition:all var(--cevro-transition)}.cevro-message__quick-action:hover{background-color:var(--cevro-primary);border-color:var(--cevro-primary);color:#fff}.cevro-typing-indicator{display:flex;gap:8px;align-items:center;padding:8px 0}.cevro-typing-indicator__avatar{display:none}.cevro-typing-indicator__dots{display:flex;gap:4px;padding:12px 16px;background-color:var(--cevro-agent-msg-bg);border-radius:var(--cevro-radius-sm);border-bottom-left-radius:4px}.cevro-typing-indicator__dots span{width:6px;height:6px;background-color:var(--cevro-agent-msg-text);opacity:.85;border-radius:50%;animation:cevro-typing-bounce 1.4s ease-in-out infinite}.cevro-typing-indicator__dots span:nth-child(1){animation-delay:0s}.cevro-typing-indicator__dots span:nth-child(2){animation-delay:.2s}.cevro-typing-indicator__dots span:nth-child(3){animation-delay:.4s}@keyframes cevro-typing-bounce{0%,60%,to{transform:translateY(0)}30%{transform:translateY(-4px)}}.cevro-chat-window__input-wrapper{border-top:1px solid var(--cevro-border);background-color:var(--cevro-bg)}.cevro-chat-window__input-area{display:flex;align-items:center;gap:8px;padding:12px 16px}.cevro-chat-window__file-button{width:36px;height:36px;border:1px solid var(--cevro-file-btn-border);background-color:var(--cevro-file-btn-bg);color:var(--cevro-file-btn-icon);cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--cevro-transition);flex-shrink:0}.cevro-chat-window__file-button:hover{background-color:var(--cevro-bg-secondary);border-color:var(--cevro-primary);color:var(--cevro-primary)}.cevro-chat-window__file-button svg{display:block;width:20px;height:20px;color:var(--cevro-file-btn-icon)}.cevro-chat-window__file-button:hover svg{color:var(--cevro-primary)}.cevro-chat-window__file-input{display:none}.cevro-chat-window__input{flex:1;box-sizing:border-box;border:1px solid var(--cevro-border);border-radius:var(--cevro-radius-sm);padding:8px 14px;font-size:14px;font-family:var(--cevro-font);resize:none;outline:none;background-color:var(--cevro-bg-input);color:var(--cevro-text);max-height:100px;line-height:1.4;transition:border-color var(--cevro-transition);overflow-y:auto;scrollbar-width:none;-ms-overflow-style:none}.cevro-chat-window__input::-webkit-scrollbar{display:none}.cevro-chat-window__input::placeholder{color:var(--cevro-text-secondary)}.cevro-chat-window__input:focus{border-color:var(--cevro-primary);box-shadow:0 0 0 3px var(--cevro-focus-ring)}.cevro-chat-window__send-button{width:36px;height:36px;border:none;background-color:var(--cevro-send-btn-bg);color:var(--cevro-send-btn-icon);cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--cevro-transition);flex-shrink:0}.cevro-chat-window__send-button:hover:not(:disabled){filter:brightness(.9);transform:scale(1.05)}.cevro-chat-window__send-button:disabled{opacity:.5;cursor:not-allowed;transform:scale(.9)}.cevro-chat-window__send-button svg{display:block;width:18px;height:18px;flex-shrink:0}.cevro-chat-window__upload-progress{display:flex;align-items:center;gap:12px;padding:8px 16px;background-color:var(--cevro-bg-secondary);border-bottom:1px solid var(--cevro-border)}.cevro-chat-window__upload-progress-bar{flex:1;height:4px;background-color:var(--cevro-border);border-radius:2px;overflow:hidden}.cevro-chat-window__upload-progress-fill{height:100%;background-color:var(--cevro-primary);border-radius:2px;transition:width .2s ease}.cevro-chat-window__upload-progress-text{font-size:12px;color:var(--cevro-text-secondary);white-space:nowrap}.cevro-chat-window__file-button:disabled{opacity:.5;cursor:not-allowed}.cevro-chat-window__footer{padding:8px 16px;text-align:center;font-size:11px;color:var(--cevro-text-secondary);background-color:var(--cevro-bg)}.cevro-chat-window__footer a{color:var(--cevro-primary);text-decoration:none}.cevro-chat-window__footer a:hover{text-decoration:underline}.cevro-messages__container::-webkit-scrollbar{width:6px}.cevro-messages__container::-webkit-scrollbar-track{background:transparent}.cevro-messages__container::-webkit-scrollbar-thumb{background-color:var(--cevro-border);border-radius:3px}.cevro-messages__container::-webkit-scrollbar-thumb:hover{background-color:var(--cevro-text-secondary)}.cevro-messages__closed-notice{flex:1;display:flex;flex-direction:column;justify-content:flex-end;padding:16px;text-align:center}.cevro-messages__closed-text{font-size:14px;color:var(--cevro-text-secondary);margin:0;line-height:1.5}.cevro-chat-window__closed-footer{padding:16px;background-color:var(--cevro-bg);border-top:1px solid var(--cevro-border);display:flex;flex-direction:column;gap:12px}.cevro-chat-window__new-chat-button{width:100%;background:var(--cevro-primary);color:#fff;border:none;padding:14px 24px;border-radius:var(--cevro-radius-sm);font-size:14px;font-weight:500;cursor:pointer;transition:background var(--cevro-transition),transform var(--cevro-transition);font-family:var(--cevro-font)}.cevro-chat-window__new-chat-button:hover{background:var(--cevro-primary-hover)}.cevro-chat-window__new-chat-button:active{transform:scale(.98)}.cevro-chat-window__powered-by{text-align:center;font-size:11px;color:var(--cevro-text-secondary)}@keyframes cevro-fade-in{0%{opacity:0}to{opacity:1}}.cevro-csat{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:24px;text-align:center;background-color:var(--cevro-bg);position:relative}.cevro-csat__skip{position:absolute;top:12px;right:12px;background:none;border:none;padding:8px;cursor:pointer;color:var(--cevro-text-secondary);border-radius:var(--cevro-radius-sm);transition:background var(--cevro-transition)}.cevro-csat__skip:hover{background:var(--cevro-bg-input)}.cevro-csat__icon{margin-bottom:16px}.cevro-csat__title{font-size:18px;font-weight:600;color:var(--cevro-text);margin:0 0 8px;font-family:var(--cevro-font)}.cevro-csat__subtitle{font-size:14px;color:var(--cevro-text-secondary);margin:0 0 24px;font-family:var(--cevro-font)}.cevro-csat__stars{display:flex;gap:8px;margin-bottom:20px}.cevro-csat__star{background:none;border:none;padding:4px;cursor:pointer;transition:transform var(--cevro-transition)}.cevro-csat__star svg{pointer-events:none}.cevro-csat__star:hover{transform:scale(1.15)}.cevro-csat__star--filled svg{fill:#fbbf24;stroke:#fbbf24}.cevro-csat__feedback{width:100%;padding:12px 14px;border:1px solid var(--cevro-border);border-radius:var(--cevro-radius-sm);font-size:14px;font-family:var(--cevro-font);resize:none;min-height:80px;max-height:120px;background-color:var(--cevro-bg-input);color:var(--cevro-text);margin-bottom:16px}.cevro-csat__feedback:focus{outline:none;border-color:var(--cevro-primary);box-shadow:0 0 0 3px var(--cevro-focus-ring)}.cevro-csat__feedback::placeholder{color:var(--cevro-text-placeholder)}.cevro-csat__submit{width:100%;background:var(--cevro-primary);color:#fff;border:none;padding:14px 24px;border-radius:var(--cevro-radius-sm);font-size:14px;font-weight:500;cursor:pointer;transition:background var(--cevro-transition),transform var(--cevro-transition),opacity var(--cevro-transition);font-family:var(--cevro-font)}.cevro-csat__submit:hover:not(:disabled){background:var(--cevro-primary-hover)}.cevro-csat__submit:active:not(:disabled){transform:scale(.98)}.cevro-csat__submit:disabled{opacity:.5;cursor:not-allowed}.cevro-csat__powered-by{margin-top:auto;padding-top:16px;font-size:11px;color:var(--cevro-text-secondary)}.cevro-csat__powered-by a{color:var(--cevro-text-secondary);text-decoration:none}.cevro-csat__powered-by a:hover{text-decoration:underline}.cevro-csat--thank-you{gap:16px}.cevro-csat--thank-you .cevro-csat__title{margin-bottom:16px}.cevro-csat-inline{display:flex;flex-direction:column;padding:16px 20px;background-color:var(--cevro-bg);border-top:1px solid var(--cevro-border)}.cevro-csat-inline__header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.cevro-csat-inline__title{font-size:14px;font-weight:500;color:var(--cevro-text);font-family:var(--cevro-font)}.cevro-csat-inline__skip{background:none;border:none;padding:4px 8px;cursor:pointer;color:var(--cevro-text-secondary);font-size:12px;font-family:var(--cevro-font);border-radius:var(--cevro-radius-sm);transition:background var(--cevro-transition),color var(--cevro-transition)}.cevro-csat-inline__skip:hover{background:var(--cevro-bg-input);color:var(--cevro-text)}.cevro-csat-inline__stars{display:flex;justify-content:center;gap:8px;margin-bottom:12px}.cevro-csat-inline__star{background:none;border:none;padding:4px;cursor:pointer;transition:transform var(--cevro-transition)}.cevro-csat-inline__star svg{pointer-events:none;width:28px;height:28px}.cevro-csat-inline__star:hover{transform:scale(1.15)}.cevro-csat-inline__star--filled svg{fill:#fbbf24;stroke:#fbbf24}.cevro-csat-inline__feedback{width:100%;margin-top:12px;padding:10px 12px;border:1px solid var(--cevro-border);border-radius:var(--cevro-radius-md);font-size:14px;font-family:var(--cevro-font);resize:none;box-sizing:border-box;background-color:var(--cevro-bg);color:var(--cevro-text);transition:border-color var(--cevro-transition)}.cevro-csat-inline__feedback:focus{outline:none;border-color:var(--cevro-primary)}.cevro-csat-inline__feedback::placeholder{color:var(--cevro-text-secondary)}.cevro-csat-inline__submit{width:100%;margin-top:8px;padding:10px 16px;background-color:var(--cevro-primary);color:#fff;border:none;border-radius:var(--cevro-radius-md);font-size:14px;font-weight:500;font-family:var(--cevro-font);cursor:pointer;transition:background var(--cevro-transition),opacity var(--cevro-transition)}.cevro-csat-inline__submit:hover:not(:disabled){background-color:var(--cevro-primary-hover)}.cevro-csat-inline__submit:disabled{opacity:.7;cursor:not-allowed}.cevro-csat-inline__powered-by{margin-top:12px;font-size:11px;color:var(--cevro-text-secondary);text-align:center;font-family:var(--cevro-font)}.cevro-csat-inline__powered-by a{color:var(--cevro-primary);text-decoration:none}.cevro-csat-inline__powered-by a:hover{text-decoration:underline}.cevro-csat-inline--thank-you{align-items:center;text-align:center}.cevro-csat-inline__thank-you-row{display:flex;align-items:center;gap:8px;margin-bottom:12px}.cevro-csat-inline__check{display:flex;align-items:center}.cevro-csat-inline__message{font-size:14px;font-weight:500;color:var(--cevro-text);font-family:var(--cevro-font)}.cevro-csat-inline__new-chat{width:100%;padding:10px 16px;background-color:var(--cevro-primary);color:#fff;border:none;border-radius:var(--cevro-radius-md);font-size:14px;font-weight:500;font-family:var(--cevro-font);cursor:pointer;margin-bottom:12px;transition:background var(--cevro-transition)}.cevro-csat-inline__new-chat:hover{background-color:var(--cevro-primary-hover)}.cevro-prechat{flex:1;display:flex;flex-direction:column;padding:32px 24px 24px;background-color:var(--cevro-bg);animation:cevro-fade-in .25s ease}.cevro-prechat__title{font-size:18px;font-weight:600;color:var(--cevro-text);margin:0 0 8px;font-family:var(--cevro-font)}.cevro-prechat__subtitle{font-size:14px;color:var(--cevro-text-secondary);margin:0 0 24px;font-family:var(--cevro-font)}.cevro-prechat__form{display:flex;flex-direction:column;gap:16px}.cevro-prechat__field{display:flex;flex-direction:column;gap:6px}.cevro-prechat__label{font-size:13px;font-weight:500;color:var(--cevro-text);font-family:var(--cevro-font)}.cevro-prechat__input{width:100%;padding:12px 14px;border:1px solid var(--cevro-border);border-radius:var(--cevro-radius-sm);font-size:14px;font-family:var(--cevro-font);background-color:var(--cevro-bg);color:var(--cevro-text);transition:border-color var(--cevro-transition),box-shadow var(--cevro-transition);box-sizing:border-box}.cevro-prechat__input:focus{outline:none;border-color:var(--cevro-primary);box-shadow:0 0 0 3px var(--cevro-focus-ring)}.cevro-prechat__input::placeholder{color:var(--cevro-text-secondary)}.cevro-prechat__input--error{border-color:#ef4444}.cevro-prechat__input--error:focus{border-color:#ef4444;box-shadow:0 0 0 3px #ef444426}.cevro-prechat__error{font-size:12px;color:#ef4444;min-height:16px}.cevro-prechat__submit{width:100%;background:var(--cevro-primary);color:#fff;border:none;padding:14px 24px;border-radius:var(--cevro-radius-sm);font-size:14px;font-weight:500;cursor:pointer;transition:background var(--cevro-transition),transform var(--cevro-transition);font-family:var(--cevro-font);margin-top:8px}.cevro-prechat__submit:hover{background:var(--cevro-primary-hover)}.cevro-prechat__submit:active{transform:scale(.98)}.cevro-prechat__powered-by{margin-top:auto;padding-top:24px;text-align:center;font-size:11px;color:var(--cevro-text-secondary)}.cevro-prechat__powered-by a{color:var(--cevro-text-secondary);text-decoration:none}.cevro-prechat__powered-by a:hover{text-decoration:underline}';let s=class{constructor(){t(this,"listeners",new Map),t(this,"onceHandlers",new Map)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const i=s=>{this.onceHandlers.delete(i),this.off(e,i),t(s)};return this.onceHandlers.set(i,t),this.on(e,i)}off(e,t){const i=this.listeners.get(e);i&&(i.delete(t),this.onceHandlers.delete(t))}emit(e,t){const i=this.listeners.get(e);i&&i.forEach(e=>{try{e(t)}catch{}})}removeAllListeners(e){if(e){const t=this.listeners.get(e);t&&t.forEach(e=>{this.onceHandlers.delete(e)}),this.listeners.delete(e)}else this.listeners.clear(),this.onceHandlers.clear()}listenerCount(e){var t;return(null==(t=this.listeners.get(e))?void 0:t.size)||0}};function n(){try{return localStorage.getItem("cevro_visitor_token")}catch{return null}}function r(e){try{localStorage.setItem("cevro_visitor_token",e)}catch{}}function o(){return function(){const e=n();return e?function(e){if(!e)return null;const t=e.lastIndexOf(".");return t<=0?null:e.substring(0,t)}(e):null}()}const a="cevro_active_player";function c(e){const t=function(e){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i)|0;return Math.abs(t).toString(36)}(e);try{const e=localStorage.getItem(a);return localStorage.setItem(a,t),!!e&&e!==t}catch{return!1}}function l(){try{localStorage.removeItem(a)}catch{}}function h(){try{localStorage.removeItem("cevro_session")}catch{}}function d(){try{localStorage.removeItem("cevro_visitor_token")}catch{}}const u=new Set(["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","text/plain","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","audio/mpeg","audio/wav","audio/ogg","video/mp4","video/webm","application/zip","application/x-rar-compressed"]),p=new Set([".exe",".dll",".bat",".cmd",".sh",".bash",".ps1",".psm1",".psd1",".vbs",".vbe",".js",".jse",".ws",".wsf",".wsc",".wsh",".msi",".msp",".mst",".scr",".pif",".com",".hta",".cpl",".msc",".jar",".class",".php",".php3",".php4",".php5",".phtml",".asp",".aspx",".ashx",".asmx",".jsp",".jspx",".py",".pyc",".pyw",".rb",".rbw",".pl",".pm",".cgi",".htaccess",".htpasswd"]),g={maxSizeBytes:26214400,minSizeBytes:1,maxFilenameLength:255};function v(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?"":e.substring(t).toLowerCase()}function m(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(1))+" "+["B","KB","MB","GB"][t]}class f{constructor(e=5,i=6e4){t(this,"uploadTimestamps",[]),t(this,"maxUploads"),t(this,"windowMs"),this.maxUploads=e,this.windowMs=i}canUpload(){const e=Date.now();return this.uploadTimestamps=this.uploadTimestamps.filter(t=>e-t<this.windowMs),this.uploadTimestamps.length<this.maxUploads}recordUpload(){this.uploadTimestamps.push(Date.now())}getRemainingUploads(){const e=Date.now();return this.uploadTimestamps=this.uploadTimestamps.filter(t=>e-t<this.windowMs),Math.max(0,this.maxUploads-this.uploadTimestamps.length)}getTimeUntilNextUpload(){if(this.canUpload())return 0;const e=Math.min(...this.uploadTimestamps);return Math.max(0,this.windowMs-(Date.now()-e))}reset(){this.uploadTimestamps=[]}}class _{constructor(e){t(this,"config"),t(this,"accessToken",null),t(this,"contactId",null),t(this,"currentTicketId",null),t(this,"visitorToken",null),t(this,"currentAgent",null),t(this,"uploadRateLimiter"),this.config=e,this.uploadRateLimiter=new f}updateConfig(e){this.config=e}setVisitorToken(e){this.visitorToken=e}getVisitorToken(){return this.visitorToken}setAccessToken(e){this.accessToken=e}getContactId(){return this.contactId}getCurrentTicketId(){return this.currentTicketId}setCurrentTicketId(e){this.currentTicketId=e}getCurrentAgent(){return this.currentAgent}async request(e,t={}){var i,s;const n=`${this.config.apiBase}${e}`,r={"Content-Type":"application/json",...t.headers||{}};this.config.workspaceId&&(r["X-Workspace-Id"]=this.config.workspaceId),this.config.brandId&&(r["X-Brand-Id"]=this.config.brandId),this.visitorToken&&(r["X-Visitor-Token"]=this.visitorToken),(null==(i=this.config.player)?void 0:i.playerId)&&(r["X-Player-Id"]=this.config.player.playerId),(null==(s=this.config.player)?void 0:s.playerHash)&&(r["X-Player-Hash"]=this.config.player.playerHash),this.accessToken&&(r.Authorization=`Bearer ${this.accessToken}`);const o=await fetch(n,{...t,headers:r});if(!o.ok){const e=await o.json().catch(()=>({message:o.statusText}));throw new Error(e.message||`Request failed: ${o.status}`)}return o.json()}async initSession(e,t,i){var s,n,r,o,a,c,l,h;const d={visitorId:e,session:function(){const e={};if("undefined"==typeof window||"undefined"==typeof navigator)return e;try{e.userAgent=navigator.userAgent,e.language=navigator.language,e.platform=navigator.platform,e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,e.currentPage=window.location.href,e.pageTitle=document.title,e.referrer=document.referrer,e.screenWidth=window.screen.width,e.screenHeight=window.screen.height,e.viewportWidth=window.innerWidth,e.viewportHeight=window.innerHeight,e.devicePixelRatio=window.devicePixelRatio;const t=new URLSearchParams(window.location.search);e.utmSource=t.get("utm_source")||void 0,e.utmMedium=t.get("utm_medium")||void 0,e.utmCampaign=t.get("utm_campaign")||void 0,e.utmContent=t.get("utm_content")||void 0,e.utmTerm=t.get("utm_term")||void 0,e.cookiesEnabled=navigator.cookieEnabled,e.touchSupport="ontouchstart"in window||navigator.maxTouchPoints>0,e.online=navigator.onLine;const i=navigator.connection;i&&(e.connectionType=i.effectiveType)}catch(t){}return e}(),brandId:this.config.brandId,firstName:(null==t?void 0:t.firstName)||(null==(s=this.config.player)?void 0:s.firstName),lastName:null==(n=this.config.player)?void 0:n.lastName,email:(null==t?void 0:t.email)||(null==(r=this.config.player)?void 0:r.email)||void 0,phone:null==(o=this.config.player)?void 0:o.phone,customAttributes:null==(a=this.config.player)?void 0:a.customAttributes,forceNewTicket:null==i?void 0:i.forceNewTicket};(null==(c=this.config.player)?void 0:c.playerId)&&(d.playerId=this.config.player.playerId,d.playerHash=this.config.player.playerHash);const u=await this.request("/api/v1/sdk/session",{method:"POST",body:JSON.stringify(d),headers:e?{"X-Visitor-Id":e}:void 0});return u.requireContactInfo&&(null==(l=u.missingFields)?void 0:l.length)>0?{sessionId:"",contactId:"",ticketId:"",visitorId:u.visitorId||"",isNewSession:!1,isNewTicket:!1,requireContactInfo:u.requireContactInfo,missingFields:u.missingFields}:(this.contactId=u.contactId,this.currentTicketId=u.ticketId,u.agent&&(this.currentAgent=u.agent),{sessionId:u.sessionId,contactId:u.contactId,ticketId:u.ticketId,visitorId:u.visitorId,isNewSession:u.isNewSession,isNewTicket:u.isNewTicket,ticketClosed:u.ticketClosed,ticketClosedReason:u.ticketClosedReason,agent:u.agent,typingConfig:u.typingConfig,messages:null==(h=u.messages)?void 0:h.map(e=>this.normalizeMessage(e)),locale:u.locale,requireContactInfo:u.requireContactInfo})}async sendMessage(e,t){if(!this.contactId||!this.currentTicketId)throw new Error("No active session. Call initSession first.");const i={contactId:this.contactId,ticketId:this.currentTicketId,message:e,assetId:t},s=await this.request("/api/v1/sdk/send",{method:"POST",body:JSON.stringify(i)});return this.normalizeMessage(s.message||s)}async getMessages(e){const t=e||this.currentTicketId;if(!t)throw new Error("No ticket ID available");const i=await this.request(`/api/v1/messages/my-tickets?supportTicketId=${t}`);return(i.results||i.messages||i||[]).map(e=>this.normalizeMessage(e))}async getMyTickets(){const e=await this.request("/api/v1/messages/my-tickets");return(e.results||e.tickets||e||[]).map(e=>this.normalizeConversation(e))}async uploadFile(e,t){if(!this.uploadRateLimiter.canUpload()){const e=Math.ceil(this.uploadRateLimiter.getTimeUntilNextUpload()/1e3);throw new Error(`Too many uploads. Please wait ${e} seconds before uploading again.`)}const i=function(e,t={}){const{maxSizeBytes:i=g.maxSizeBytes,minSizeBytes:s=g.minSizeBytes,allowedMimeTypes:n=u,blockedExtensions:r=p,maxFilenameLength:o=g.maxFilenameLength}=t;if(0===e.size)return{valid:!1,error:"File is empty",errorCode:"EMPTY_FILE"};if(e.size<s)return{valid:!1,error:`File is too small. Minimum size is ${m(s)}`,errorCode:"FILE_TOO_SMALL"};if(e.size>i)return{valid:!1,error:`File is too large. Maximum size is ${m(i)}`,errorCode:"FILE_TOO_LARGE"};if(e.name.length>o)return{valid:!1,error:`Filename is too long. Maximum length is ${o} characters`,errorCode:"FILENAME_TOO_LONG"};const a=v(e.name);if(a&&r.has(a))return{valid:!1,error:`File type "${a}" is not allowed for security reasons`,errorCode:"BLOCKED_EXTENSION"};const c=e.type||"application/octet-stream";return n.has(c)||"application/octet-stream"===c&&a&&!r.has(a)?{valid:!0}:{valid:!1,error:`File type "${c}" is not allowed. Allowed types: images, documents, audio, video`,errorCode:"INVALID_TYPE"}}(e);if(!i.valid)throw new Error(i.error||"File validation failed");const s=function(e){let t=e.replace(/^.*[\\/]/,"");if(t=t.replace(/[\x00-\x1f\x7f]/g,""),t=t.replace(/[<>:"/\\|?*]/g,"_"),t=t.replace(/^[\s.]+|[\s.]+$/g,""),t||(t="unnamed_file"),t.length>g.maxFilenameLength){const e=v(t),i=t.slice(0,-e.length||void 0),s=g.maxFilenameLength-e.length;t=i.slice(0,s)+e}return t}(e.name);this.uploadRateLimiter.recordUpload();const{uploadUrl:n,assetId:r}=await this.request("/api/v1/sdk/upload-url",{method:"POST",body:JSON.stringify({filename:s,contentType:e.type||"application/octet-stream",size:e.size})});return await this.uploadToS3(n,e,t),r}async uploadToS3(e,t,i){return new Promise((s,n)=>{const r=new XMLHttpRequest;r.upload.addEventListener("progress",e=>{if(e.lengthComputable&&i){const t=Math.round(e.loaded/e.total*100);i(t)}}),r.addEventListener("load",()=>{r.status>=200&&r.status<300?s():n(new Error(`Upload failed with status ${r.status}`))}),r.addEventListener("error",()=>{n(new Error("Upload failed"))}),r.open("PUT",e),r.setRequestHeader("Content-Type",t.type||"application/octet-stream"),r.send(t)})}normalizeMessage(e){return{id:e.objectId||e.id,body:e.body||"",inbound:e.inbound||!1,outbound:e.outbound||!e.inbound,createdAt:e.createdAt||(new Date).toISOString(),type:e.type||"text",mediaUrl:e.mediaUrl,mediaType:e.mediaType,status:e.status||"sent",richContent:e.richContent}}normalizeConversation(e){return{id:e.objectId||e.id,conversationId:e.conversationId||e.objectId||e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.resolved?"resolved":e.escalated?"escalated":"open",unreadCount:e.unreadCount||0,lastMessage:e.latestMessage?this.normalizeMessage(e.latestMessage):void 0}}async getConnectionToken(e){var t;const i={workspaceId:this.config.workspaceId,brandId:this.config.brandId};e&&(i.visitorToken=e),(null==(t=this.config.player)?void 0:t.playerId)&&(i.playerId=this.config.player.playerId,i.playerHash=this.config.player.playerHash,i.email=this.config.player.email||void 0,i.firstName=this.config.player.firstName);return await this.request("/api/v1/sdk/token",{method:"POST",body:JSON.stringify(i)})}async refreshConnectionToken(e){return this.getConnectionToken(e)}async submitCSAT(e,t,i,s){await this.request("/api/v1/sdk/csat",{method:"POST",body:JSON.stringify({ticketId:e,contactId:t,rating:i,feedback:s})})}async getWidgetConfig(){try{return await this.request("/api/v1/sdk/widget-config",{method:"GET"})}catch(e){return{}}}clear(){this.accessToken=null,this.contactId=null,this.currentTicketId=null}}function b(e,t,i,s){return new(i||(i=Promise))(function(t,n){function r(e){try{a(s.next(e))}catch(t){n(t)}}function o(e){try{a(s.throw(e))}catch(t){n(t)}}function a(e){var s;e.done?t(e.value):(s=e.value,s instanceof i?s:new i(function(e){e(s)})).then(r,o)}a((s=s.apply(e,[])).next())})}function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var y,x={exports:{}},C="object"==typeof Reflect?Reflect:null,k=C&&"function"==typeof C.apply?C.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};y=C&&"function"==typeof C.ownKeys?C.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var S=Number.isNaN||function(e){return e!=e};function T(){T.init.call(this)}x.exports=T,x.exports.once=function(e,t){return new Promise(function(i,s){function n(i){e.removeListener(t,r),s(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",n),i([].slice.call(arguments))}B(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&B(e,"error",t,i)}(e,n,{once:!0})})},T.EventEmitter=T,T.prototype._events=void 0,T.prototype._eventsCount=0,T.prototype._maxListeners=void 0;var I=10;function E(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function L(e){return void 0===e._maxListeners?T.defaultMaxListeners:e._maxListeners}function M(e,t,i,s){var n,r,o,a;if(E(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),o=r[t]),void 0===o)o=r[t]=i,++e._eventsCount;else if("function"==typeof o?o=r[t]=s?[i,o]:[o,i]:s?o.unshift(i):o.push(i),(n=L(e))>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function P(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function N(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=P.bind(s);return n.listener=i,s.wrapFn=n,n}function A(e,t,i){var s=e._events;if(void 0===s)return[];var n=s[t];return void 0===n?[]:"function"==typeof n?i?[n.listener||n]:[n]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(n):R(n,n.length)}function z(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function R(e,t){for(var i=new Array(t),s=0;s<t;++s)i[s]=e[s];return i}function B(e,t,i,s){if("function"==typeof e.on)s.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function n(r){s.once&&e.removeEventListener(t,n),i(r)})}}Object.defineProperty(T,"defaultMaxListeners",{enumerable:!0,get:function(){return I},set:function(e){if("number"!=typeof e||e<0||S(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");I=e}}),T.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},T.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||S(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},T.prototype.getMaxListeners=function(){return L(this)},T.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var s="error"===e,n=this._events;if(void 0!==n)s=s&&void 0===n.error;else if(!s)return!1;if(s){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var o=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw o.context=r,o}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)k(a,this,t);else{var c=a.length,l=R(a,c);for(i=0;i<c;++i)k(l[i],this,t)}return!0},T.prototype.addListener=function(e,t){return M(this,e,t,!1)},T.prototype.on=T.prototype.addListener,T.prototype.prependListener=function(e,t){return M(this,e,t,!0)},T.prototype.once=function(e,t){return E(t),this.on(e,N(this,e,t)),this},T.prototype.prependOnceListener=function(e,t){return E(t),this.prependListener(e,N(this,e,t)),this},T.prototype.removeListener=function(e,t){var i,s,n,r,o;if(E(t),void 0===(s=this._events))return this;if(void 0===(i=s[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(n=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){o=i[r].listener,n=r;break}if(n<0)return this;0===n?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,n),1===i.length&&(s[e]=i[0]),void 0!==s.removeListener&&this.emit("removeListener",e,o||t)}return this},T.prototype.off=T.prototype.removeListener,T.prototype.removeAllListeners=function(e){var t,i,s;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var n,r=Object.keys(i);for(s=0;s<r.length;++s)"removeListener"!==(n=r[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},T.prototype.listeners=function(e){return A(this,e,!0)},T.prototype.rawListeners=function(e){return A(this,e,!1)},T.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):z.call(e,t)},T.prototype.listenerCount=z,T.prototype.eventNames=function(){return this._eventsCount>0?y(this._events):[]};var H,F,U,O,j,D,V,W,$,q,Z,J,G,Y,X,Q,K=w(x.exports);function ee(e){return null!=e&&"function"==typeof e}function te(e,t,i){e>31&&(e=31);const s=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)}(0,Math.min(i,t*Math.pow(2,e)));return Math.min(i,t+s)}function ie(e){return Math.min(1e3*e,2147483647)}(F=H||(H={}))[F.timeout=1]="timeout",F[F.transportClosed=2]="transportClosed",F[F.clientDisconnected=3]="clientDisconnected",F[F.clientClosed=4]="clientClosed",F[F.clientConnectToken=5]="clientConnectToken",F[F.clientRefreshToken=6]="clientRefreshToken",F[F.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",F[F.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",F[F.subscriptionRefreshToken=9]="subscriptionRefreshToken",F[F.transportWriteError=10]="transportWriteError",F[F.connectionClosed=11]="connectionClosed",F[F.badConfiguration=12]="badConfiguration",(O=U||(U={}))[O.connectCalled=0]="connectCalled",O[O.transportClosed=1]="transportClosed",O[O.noPing=2]="noPing",O[O.subscribeTimeout=3]="subscribeTimeout",O[O.unsubscribeError=4]="unsubscribeError",(D=j||(j={}))[D.disconnectCalled=0]="disconnectCalled",D[D.unauthorized=1]="unauthorized",D[D.badProtocol=2]="badProtocol",D[D.messageSizeLimit=3]="messageSizeLimit",(W=V||(V={}))[W.subscribeCalled=0]="subscribeCalled",W[W.transportClosed=1]="transportClosed",(q=$||($={}))[q.unsubscribeCalled=0]="unsubscribeCalled",q[q.unauthorized=1]="unauthorized",q[q.clientClosed=2]="clientClosed",(J=Z||(Z={}))[J.channelCompaction=1]="channelCompaction",(Y=G||(G={})).Disconnected="disconnected",Y.Connecting="connecting",Y.Connected="connected",(Q=X||(X={})).Unsubscribed="unsubscribed",Q.Subscribing="subscribing",Q.Subscribed="subscribed";class se extends K{constructor(e,t,i){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this.channel=t,this.state=X.Unsubscribed,this._centrifuge=e,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._prevValue=null,this._unsubPromise=Promise.resolve(),this._setOptions(i),this._centrifuge._debugEnabled?(this.on("state",e=>{this._debug("subscription state",t,e.oldState,"->",e.newState)}),this.on("error",e=>{this._debug("subscription error",t,e)})):this.on("error",function(){Function.prototype()})}ready(e){return this.state===X.Unsubscribed?Promise.reject({code:H.subscriptionUnsubscribed,message:this.state}):this.state===X.Subscribed?Promise.resolve():new Promise((t,i)=>{const s={resolve:t,reject:i};e&&(s.timeout=setTimeout(function(){i({code:H.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=s})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(V.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed($.unsubscribeCalled,"unsubscribe called",!0)}publish(e){return b(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.publish(this.channel,e)})}presence(){return b(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return b(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)})}history(e){return b(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,e)})}setTagsFilter(e){if(e&&this._delta)throw new Error("cannot use delta and tagsFilter together");this._tagsFilter=e}setData(e){this._data=e}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:H.subscriptionUnsubscribed,message:this.state}):new Promise((e,t)=>{const i=this._centrifuge._config.timeout,s=setTimeout(()=>{t({code:H.timeout,message:"timeout"})},i);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return!0===this._recover}_isUnsubscribed(){return this.state===X.Unsubscribed}_isSubscribing(){return this.state===X.Subscribing}_isSubscribed(){return this.state===X.Subscribed}_setState(e){if(this.state!==e){const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t,channel:this.channel}),!0}return!1}_usesToken(){return""!==this._token||null!==this._getToken}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout()}_setSubscribed(e){if(!this._isSubscribing())return;this._clearSubscribingState(),e.id&&(this._id=e.id),e.recoverable&&(this._recover=!0,this._offset=e.offset||0,this._epoch=e.epoch||""),e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,this._setState(X.Subscribed);const t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit("subscribed",t),this._resolvePromises();const i=e.publications;if(i&&i.length>0)for(const s in i)i.hasOwnProperty(s)&&this._handlePublication(i[s]);!0===e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ie(e.ttl)))}_setSubscribing(e,t){return b(this,0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState(X.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(yield this._unsubPromise),this._isSubscribing()&&this._subscribe())})}_subscribe(){return this._debug("subscribing on",this.channel),this._isTransportOpen()?this._inflight?null:(this._inflight=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():(this._getSubscriptionToken().then(e=>this._handleTokenResponse(e)).catch(e=>this._handleTokenError(e)),null)):(this._debug("delay subscribe on",this.channel,"till connected"),null)}_isTransportOpen(){return this._centrifuge._transportIsOpen}_canSubscribeWithoutGettingToken(){return!this._usesToken()||!!this._token}_subscribeWithoutToken(){return this._getData?(this._getDataAndSubscribe(this._token),null):this._sendSubscribe(this._token)}_getDataAndSubscribe(e){this._getData?this._getData({channel:this.channel}).then(t=>{this._isSubscribing()?(this._data=t,this._sendSubscribe(e)):this._inflight=!1}).catch(e=>this._handleGetDataError(e)):this._inflight=!1}_handleGetDataError(e){if(this._isSubscribing()){if(e instanceof ve)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:H.badConfiguration,message:(null==e?void 0:e.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_handleTokenResponse(e){if(this._isSubscribing()){if(!e)return this._inflight=!1,void this._failUnauthorized();this._token=e,this._getData?this._getDataAndSubscribe(e):this._sendSubscribe(e)}else this._inflight=!1}_handleTokenError(e){if(this._isSubscribing()){if(e instanceof ve)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:H.subscriptionSubscribeToken,message:(null==e?void 0:e.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_sendSubscribe(e){if(!this._isTransportOpen())return this._inflight=!1,null;const t=this._buildSubscribeCommand(e);return this._centrifuge._call(t).then(e=>{this._inflight=!1;const t=e.reply.subscribe;this._handleSubscribeResponse(t),e.next&&e.next()},e=>{this._inflight=!1,this._handleSubscribeError(e.error),e.next&&e.next()}),t}_buildSubscribeCommand(e){const t={channel:this.channel};if(e&&(t.token=e),this._data&&(t.data=this._data),this._positioned&&(t.positioned=!0),this._recoverable&&(t.recoverable=!0),this._joinLeave&&(t.join_leave=!0),t.flag=Z.channelCompaction,this._needRecover()){t.recover=!0;const e=this._getOffset();e&&(t.offset=e);const i=this._getEpoch();i&&(t.epoch=i)}return this._delta&&(t.delta=this._delta),this._tagsFilter&&(t.tf=this._tagsFilter),{subscribe:t}}_debug(...e){this._centrifuge._debug(...e)}_handleSubscribeError(e){this._isSubscribing()&&(e.code!==H.timeout?this._subscribeError(e):this._centrifuge._disconnect(U.subscribeTimeout,"subscribe timeout",!0))}_handleSubscribeResponse(e){this._isSubscribing()&&this._setSubscribed(e)}_setUnsubscribed(e,t,i){if(this._isUnsubscribed())return Promise.resolve();let s=Promise.resolve();return this._isSubscribed()?(i&&(s=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&i&&(s=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._setState(X.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:H.subscriptionUnsubscribed,message:this.state}),s}_handlePublication(e){if(this._delta&&this._delta_negotiated){const{newData:t,newPrevValue:i}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValue);e.data=t,this._prevValue=i}const t=this._centrifuge._getPublicationContext(this.channel,e);this.emit("publication",t),e.offset&&(this._offset=e.offset)}_handleJoin(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("join",{channel:this.channel,info:t})}_handleLeave(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("leave",{channel:this.channel,info:t})}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}_scheduleResubscribe(){if(!this._isSubscribing())return void this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);const e=this,t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){e._isSubscribing()&&e._subscribe()},t),this._debug("resubscribe scheduled after "+t,this.channel)}_subscribeError(e){if(this._isSubscribing())if(e.code<100||109===e.code||!0===e.temporary){109===e.code&&(this._token="");const t={channel:this.channel,type:"subscribe",error:e};this._centrifuge.state===G.Connected&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){const e=te(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,e}_setOptions(e){if(e){if(e.since&&(this._offset=e.since.offset||0,this._epoch=e.since.epoch||"",this._recover=!0),e.data&&(this._data=e.data),e.getData&&(this._getData=e.getData),void 0!==e.minResubscribeDelay&&(this._minResubscribeDelay=e.minResubscribeDelay),void 0!==e.maxResubscribeDelay&&(this._maxResubscribeDelay=e.maxResubscribeDelay),e.token&&(this._token=e.token),e.getToken&&(this._getToken=e.getToken),!0===e.positioned&&(this._positioned=!0),!0===e.recoverable&&(this._recoverable=!0),!0===e.joinLeave&&(this._joinLeave=!0),e.delta){if("fossil"!==e.delta)throw new Error("unsupported delta format");this._delta=e.delta}if(e.tagsFilter&&(this._tagsFilter=e.tagsFilter),this._tagsFilter&&this._delta)throw new Error("cannot use delta and tagsFilter together")}}_getOffset(){const e=this._offset;return null!==e?e:0}_getEpoch(){const e=this._epoch;return null!==e?e:""}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){null!==this._resubscribeTimeout&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._debug("get subscription token for channel",this.channel);const e={channel:this.channel},t=this._getToken;return null===t?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:H.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new ve(""))):t(e)}_refresh(){this._clearRefreshTimeout();const e=this;this._getSubscriptionToken().then(function(t){if(!e._isSubscribed())return;if(!t)return void e._failUnauthorized();e._token=t;const i={sub_refresh:{channel:e.channel,token:t}};e._centrifuge._call(i).then(t=>{const i=t.reply.sub_refresh;e._refreshResponse(i),t.next&&t.next()},t=>{e._refreshError(t.error),t.next&&t.next()})}).catch(function(t){t instanceof ve?e._failUnauthorized():(e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:H.subscriptionRefreshToken,message:void 0!==t?t.toString():""}}),e._refreshTimeout=setTimeout(()=>e._refresh(),e._getRefreshRetryDelay()))})}_refreshResponse(e){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),!0===e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ie(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||!0===e.temporary?(this.emit("error",{type:"refresh",channel:this.channel,error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._setUnsubscribed(e.code,e.message,!0))}_getRefreshRetryDelay(){return te(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed($.unauthorized,"unauthorized",!0)}}class ne{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return null!==this.options.sockjs}initialize(e,t){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class re{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return void 0!==this.options.websocket&&null!==this.options.websocket}initialize(e,t){let i="";"protobuf"===e&&(i="centrifuge-protobuf"),this._transport=""!==i?new this.options.websocket(this.endpoint,i):new this.options.websocket(this.endpoint),"protobuf"===e&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class oe{constructor(e,t){this.endpoint=e,this.options=t,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(e){if(!e.ok)throw new Error(e.status);return e}_fetchEventTarget(e,t,i){const s=new EventTarget;return(0,e.options.fetch)(t,i).then(e._handleErrors).then(t=>{s.dispatchEvent(new Event("open"));let i="",n=0,r=new Uint8Array;const o=t.body.getReader();return new e.options.readableStream({start:t=>function a(){return o.read().then(({done:o,value:c})=>{if(o)return s.dispatchEvent(new Event("close")),void t.close();try{if("json"===e._protocol)for(i+=e._utf8decoder.decode(c);n<i.length;)if("\n"===i[n]){const e=i.substring(0,n);s.dispatchEvent(new MessageEvent("message",{data:e})),i=i.substring(n+1),n=0}else++n;else{const t=new Uint8Array(r.length+c.length);for(t.set(r),t.set(c,r.length),r=t;;){const t=e.options.decoder.decodeReply(r);if(t.ok){const e=r.slice(0,t.pos);s.dispatchEvent(new MessageEvent("message",{data:e})),r=r.slice(t.pos);continue}break}}}catch(l){return s.dispatchEvent(new Event("error",{detail:l})),s.dispatchEvent(new Event("close")),void t.close()}a()}).catch(function(e){s.dispatchEvent(new Event("error",{detail:e})),s.dispatchEvent(new Event("close")),t.close()})}()})}).catch(e=>{s.dispatchEvent(new Event("error",{detail:e})),s.dispatchEvent(new Event("close"))}),s}supported(){return null!==this.options.fetch&&null!==this.options.readableStream&&"undefined"!=typeof TextDecoder&&"undefined"!=typeof AbortController&&"undefined"!=typeof EventTarget&&"undefined"!=typeof Event&&"undefined"!=typeof MessageEvent&&"undefined"!=typeof Error}initialize(e,t,i){let s,n;this._protocol=e,this._abortController=new AbortController,"json"===e?(s={Accept:"application/json","Content-Type":"application/json"},n=i):(s={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},n=i);const r={method:"POST",headers:s,body:n,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},o=this._fetchEventTarget(this,this.endpoint,r);o.addEventListener("open",()=>{t.onOpen()}),o.addEventListener("error",e=>{this._abortController.abort(),t.onError(e)}),o.addEventListener("close",()=>{this._abortController.abort(),t.onClose({code:4,reason:"connection closed"})}),o.addEventListener("message",e=>{t.onMessage(e.data)})}close(){this._abortController.abort()}send(e,t,i){let s,n;const r={session:t,node:i,data:e};"json"===this._protocol?(s={"Content-Type":"application/json"},n=JSON.stringify(r)):(s={"Content-Type":"application/octet-stream"},n=this.options.encoder.encodeEmulationRequest(r));const o={method:"POST",headers:s,body:n,mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,o)}}class ae{constructor(e,t){this.endpoint=e,this.options=t,this._protocol="json",this._transport=null,this._onClose=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return null!==this.options.eventsource&&null!==this.options.fetch}initialize(e,t,i){let s;s=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),s.searchParams.append("cf_connect",i);const n=new this.options.eventsource(s.toString(),{});this._transport=n;n.onopen=function(){t.onOpen()},n.onerror=function(e){n.close(),t.onError(e),t.onClose({code:4,reason:"connection closed"})},n.onmessage=function(e){t.onMessage(e.data)},this._onClose=function(){t.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),null!==this._onClose&&this._onClose()}send(e,t,i){const s={session:t,node:i,data:e},n={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,n)}}class ce{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"webtransport"}subName(){return"webtransport"}emulation(){return!1}supported(){return void 0!==this.options.webtransport&&null!==this.options.webtransport}initialize(e,t){return b(this,0,void 0,function*(){let i;i=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),"protobuf"===e&&i.searchParams.append("cf_protocol","protobuf"),this._protocol=e;const s=new EventTarget;this._transport=new this.options.webtransport(i.toString()),this._transport.closed.then(()=>{t.onClose({code:4,reason:"connection closed"})}).catch(()=>{t.onClose({code:4,reason:"connection closed"})});try{yield this._transport.ready}catch(r){return void this.close()}let n;try{n=yield this._transport.createBidirectionalStream()}catch(o){return void this.close()}this._stream=n,this._writer=this._stream.writable.getWriter(),s.addEventListener("close",()=>{t.onClose({code:4,reason:"connection closed"})}),s.addEventListener("message",e=>{t.onMessage(e.data)}),this._startReading(s),t.onOpen()})}_startReading(e){return b(this,0,void 0,function*(){const t=this._stream.readable.getReader();let i="",s=0,n=new Uint8Array;try{for(;;){const{done:r,value:o}=yield t.read();if(o.length>0)if("json"===this._protocol)for(i+=this._utf8decoder.decode(o);s<i.length;)if("\n"===i[s]){const t=i.substring(0,s);e.dispatchEvent(new MessageEvent("message",{data:t})),i=i.substring(s+1),s=0}else++s;else{const t=new Uint8Array(n.length+o.length);for(t.set(n),t.set(o,n.length),n=t;;){const t=this.options.decoder.decodeReply(n);if(t.ok){const i=n.slice(0,t.pos);e.dispatchEvent(new MessageEvent("message",{data:i})),n=n.slice(t.pos);continue}break}}if(r)break}}catch(r){e.dispatchEvent(new Event("close"))}})}close(){return b(this,0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}})}send(e){return b(this,0,void 0,function*(){let t;t="json"===this._protocol?(new TextEncoder).encode(e+"\n"):e;try{yield this._writer.write(t)}catch(i){this.close()}})}}const le=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class he{constructor(e){this.a=e,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const e=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e,t=0;for(;this.haveBytes()&&(e=le[127&this.getByte()])>=0;)t=(t<<6)+e;return this.pos--,t>>>0}}class de{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,t,i){for(let s=t;s<i;s++)this.a.push(e[s])}}function ue(e){let t=0,i=0,s=0,n=0,r=0,o=e.length;for(;o>=16;)t=t+e[r+0]|0,i=i+e[r+1]|0,s=s+e[r+2]|0,n=n+e[r+3]|0,t=t+e[r+4]|0,i=i+e[r+5]|0,s=s+e[r+6]|0,n=n+e[r+7]|0,t=t+e[r+8]|0,i=i+e[r+9]|0,s=s+e[r+10]|0,n=n+e[r+11]|0,t=t+e[r+12]|0,i=i+e[r+13]|0,s=s+e[r+14]|0,n=n+e[r+15]|0,r+=16,o-=16;for(;o>=4;)t=t+e[r+0]|0,i=i+e[r+1]|0,s=s+e[r+2]|0,n=n+e[r+3]|0,r+=4,o-=4;switch(n=((n+(s<<8)|0)+(i<<16)|0)+(t<<24)|0,o){case 3:n=n+(e[r+2]<<8)|0;case 2:n=n+(e[r+1]<<16)|0;case 1:n=n+(e[r+0]<<24)|0}return n>>>0}class pe{name(){return"json"}encodeCommands(e){return e.map(e=>JSON.stringify(e)).join("\n")}decodeReplies(e){return e.trim().split("\n").map(e=>JSON.parse(e))}applyDeltaIfNeeded(e,t){let i,s;if(e.delta){const n=function(e,t){let i=0;const s=new he(t),n=e.length,r=t.length,o=s.getInt();if("\n"!==s.getChar())throw new Error("size integer not terminated by '\\n'");const a=new de;for(;s.haveBytes();){const t=s.getInt();let c;switch(s.getChar()){case"@":if(c=s.getInt(),s.haveBytes()&&","!==s.getChar())throw new Error("copy command not terminated by ','");if(i+=t,i>o)throw new Error("copy exceeds output file size");if(c+t>n)throw new Error("copy extends past end of input");a.putArray(e,c,c+t);break;case":":if(i+=t,i>o)throw new Error("insert command gives an output larger than predicted");if(t>r)throw new Error("insert count exceeds size of delta");a.putArray(s.a,s.pos,s.pos+t),s.pos+=t;break;case";":{const s=a.toByteArray(e);if(t!==ue(s))throw new Error("bad checksum");if(i!==o)throw new Error("generated size does not match predicted size");return s}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}(t,(new TextEncoder).encode(e.data));i=JSON.parse((new TextDecoder).decode(n)),s=n}else i=JSON.parse(e.data),s=(new TextEncoder).encode(e.data);return{newData:i,newPrevValue:s}}}const ge={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class ve extends Error{constructor(e){super(e),this.name=this.constructor.name}}class me extends K{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=G.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new pe,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},ge),t),this._configure(),this._debugEnabled?(this.on("state",e=>{this._debug("client state",e.oldState,"->",e.newState)}),this.on("error",e=>{this._debug("client error",e)})):this.on("error",function(){Function.prototype()})}newSubscription(e,t){if(null!==this.getSubscription(e))throw new Error("Subscription to the channel "+e+" already exists");const i=new se(this,e,t);return this._subs[e]=i,i}getSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==X.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}subscriptions(){return this._subs}ready(e){return b(this,0,void 0,function*(){switch(this.state){case G.Disconnected:throw{code:H.clientDisconnected,message:"client disconnected"};case G.Connected:return;default:return new Promise((t,i)=>{const s={resolve:t,reject:i};e&&(s.timeout=setTimeout(()=>{i({code:H.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=s})}})}connect(){this._isConnected()?this._debug("connect called when already connected"):this._isConnecting()?this._debug("connect called when already connecting"):(this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting())}disconnect(){this._disconnect(j.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return b(this,0,void 0,function*(){const t={send:{data:e}};yield this._methodCall();if(!this._transportSendCommands([t]))throw this._createErrorObject(H.transportWriteError,"transport write error")})}rpc(e,t){return b(this,0,void 0,function*(){const i={rpc:{method:e,data:t}};yield this._methodCall();return{data:(yield this._callPromise(i,e=>e.rpc)).data}})}publish(e,t){return b(this,0,void 0,function*(){const i={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}history(e,t){return b(this,0,void 0,function*(){const i={history:this._getHistoryRequest(e,t)};yield this._methodCall();const s=yield this._callPromise(i,e=>e.history),n=[];if(s.publications)for(let t=0;t<s.publications.length;t++)n.push(this._getPublicationContext(e,s.publications[t]));return{publications:n,epoch:s.epoch||"",offset:s.offset||0}})}presence(e){return b(this,0,void 0,function*(){const t={presence:{channel:e}};yield this._methodCall();const i=(yield this._callPromise(t,e=>e.presence)).presence;for(const e in i)if(Object.prototype.hasOwnProperty.call(i,e)){const t=i[e],s=t.conn_info,n=t.chan_info;s&&(t.connInfo=s),n&&(t.chanInfo=n)}return{clients:i}})}presenceStats(e){return b(this,0,void 0,function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const i=yield this._callPromise(t,e=>e.presence_stats);return{numUsers:i.num_users,numClients:i.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&function(e,t){if(globalThis.console){const i=globalThis.console[e];ee(i)&&i.apply(globalThis.console,t)}}("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(null!==this._config.token&&(this._token=this._config.token),null!==this._config.data&&(this._data=this._config.data),this._codec=new pe,this._formatOverride(),(!0===this._config.debug||"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem&&localStorage.getItem("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),"string"==typeof this._endpoint);else{if(!Array.isArray(this._endpoint))throw new Error("unsupported url configuration type: only string or array of objects are supported");this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");const i=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(i)<0)throw new Error("unsupported transport name: "+i)}}}_setState(e){if(this.state!==e){this._reconnecting=!1;const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state===G.Disconnected}_isConnecting(){return this.state===G.Connecting}_isConnected(){return this.state===G.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;null!==this._config.networkEventTarget?e=this._config.networkEventTarget:void 0!==globalThis.addEventListener&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),this.state!==G.Connected&&this.state!==G.Connecting||(this._disconnect(U.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===G.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=te(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const t=this._callbacks[e];clearTimeout(t.timeout);const i=t.errback;if(!i)continue;i({error:this._createErrorObject(H.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const t=this._subs[e];t.state===X.Subscribed&&t._setSubscribing(V.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const t of e){const e=t.id;if(!(e in this._callbacks))continue;const i=this._callbacks[e];clearTimeout(this._callbacks[e].timeout),delete this._callbacks[e];(0,i.errback)({error:this._createErrorObject(H.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_initializeTransport(){let e;null!==this._config.websocket?e=this._config.websocket:"function"!=typeof globalThis.WebSocket&&"object"!=typeof globalThis.WebSocket||(e=globalThis.WebSocket);let t=null;null!==this._config.sockjs?t=this._config.sockjs:void 0!==globalThis.SockJS&&(t=globalThis.SockJS);let i=null;null!==this._config.eventsource?i=this._config.eventsource:void 0!==globalThis.EventSource&&(i=globalThis.EventSource);let s=null;null!==this._config.fetch?s=this._config.fetch:void 0!==globalThis.fetch&&(s=globalThis.fetch);let n=null;if(null!==this._config.readableStream?n=this._config.readableStream:void 0!==globalThis.ReadableStream&&(n=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let r=0;for(;;){if(r>=this._transports.length)throw new Error("no supported transport found");const o=this._transports[this._currentTransportIndex],a=o.transport,c=o.endpoint;if("websocket"===a){if(this._debug("trying websocket transport"),this._transport=new re(c,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,r++;continue}}else if("webtransport"===a){if(this._debug("trying webtransport transport"),this._transport=new ce(c,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,r++;continue}}else if("http_stream"===a){if(this._debug("trying http_stream transport"),this._transport=new oe(c,{fetch:s,readableStream:n,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,r++;continue}}else if("sse"===a){if(this._debug("trying sse transport"),this._transport=new ae(c,{eventsource:i,fetch:s,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,r++;continue}}else{if("sockjs"!==a)throw new Error("unknown transport "+a);if(this._debug("trying sockjs"),this._transport=new ne(c,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,r++;continue}}break}}else{if(r=this._endpoint,o="http",0===r.lastIndexOf(o,0))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new re(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}var r,o;const a=this,c=this._transport,l=this._nextTransportId();a._debug("id of transport",l);let h=!1;const d=[];if(this._transport.emulation()){const e=a._sendConnect(!0);d.push(e)}this._setNetworkEvents();const u=this._codec.encodeCommands(d);let p;this._transportClosed=!1,p=setTimeout(function(){c.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(p&&(clearTimeout(p),p=null),a._transportId!=l)return a._debug("open callback from non-actual transport"),void c.close();h=!0,a._debug(c.subName(),"transport open"),c.emulation()||(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(e){a._transportId==l?a._debug("transport level error",e):a._debug("error callback from non-actual transport")},onClose:function(e){if(p&&(clearTimeout(p),p=null),a._transportId!=l)return void a._debug("close callback from non-actual transport");a._debug(c.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let t="connection closed",i=!0,s=0;if(e&&"code"in e&&e.code&&(s=e.code),e&&e.reason)try{const s=JSON.parse(e.reason);t=s.reason,i=s.reconnect}catch(n){t=e.reason,(s>=3500&&s<4e3||s>=4500&&s<5e3)&&(i=!1)}s<3e3?(1009===s?(s=j.messageSizeLimit,t="message size limit exceeded",i=!1):(s=U.transportClosed,t="transport closed"),a._emulation&&!a._transportWasOpen&&(a._currentTransportIndex++,a._currentTransportIndex>=a._transports.length&&(a._triedAllTransports=!0,a._currentTransportIndex=0))):a._transportWasOpen=!0,a._isConnecting()&&!h&&a.emit("error",{type:"transport",error:{code:H.transportClosed,message:"transport closed"},transport:c.name()}),a._reconnecting=!1,a._disconnect(s,t,i)},onMessage:function(e){a._dataReceived(e)}},u),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),i=this;return this._call(t,e).then(e=>{const t=e.reply.connect;i._connectResponse(t),e.next&&e.next()},e=>{i._connectError(e.error),e.next&&e.next()}),t}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting())return void this._debug("stop reconnecting: client not in connecting state");if(this._reconnecting)return void this._debug("reconnect already in progress, return from reconnect routine");if(!1===this._transportClosed)return void this._debug("waiting for transport close");this._reconnecting=!0;const e=""===this._token;if(!(this._refreshRequired||e&&null!==this._config.getToken))return void(this._config.getData?this._config.getData().then(e=>{this._isConnecting()&&(this._data=e,this._initializeTransport())}).catch(e=>this._handleGetDataError(e)):this._initializeTransport());const t=this;this._getToken().then(function(e){t._isConnecting()&&(null!=e&&null!=e?(t._token=e,t._debug("connection token refreshed"),t._config.getData?t._config.getData().then(function(e){t._isConnecting()&&(t._data=e,t._initializeTransport())}).catch(e=>t._handleGetDataError(e)):t._initializeTransport()):t._failUnauthorized())}).catch(function(e){if(!t._isConnecting())return;if(e instanceof ve)return void t._failUnauthorized();t.emit("error",{type:"connectToken",error:{code:H.clientConnectToken,message:void 0!==e?e.toString():""}});const i=t._getReconnectDelay();t._debug("error on getting connection token, reconnect after "+i+" milliseconds",e),t._reconnecting=!1,t._reconnectTimeout=setTimeout(()=>{t._startReconnecting()},i)})}_handleGetDataError(e){if(e instanceof ve)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:H.badConfiguration,message:(null==e?void 0:e.toString())||""}});const t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state===G.Connecting&&(109===e.code&&(this._refreshRequired=!0),e.code<100||!0===e.temporary||109===e.code?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;!this._emulation||this._transportWasOpen||this._triedAllTransports||(e=!0);let t=this._getReconnectDelay();e&&(t=0),this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const t={};let i=!1;for(const s in this._serverSubs)if(this._serverSubs.hasOwnProperty(s)&&this._serverSubs[s].recoverable){i=!0;const e={recover:!0};this._serverSubs[s].offset&&(e.offset=this._serverSubs[s].offset),this._serverSubs[s].epoch&&(e.epoch=this._serverSubs[s].epoch),t[s]=e}return i&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const i={channel:e};return void 0!==t&&(t.since&&(i.since={offset:t.since.offset},t.since.epoch&&(i.since.epoch=t.since.epoch)),void 0!==t.limit&&(i.limit=t.limit),!0===t.reverse&&(i.reverse=!0)),i}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,t)=>{const i=setTimeout(function(){t({code:H.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:i,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((i,s)=>{this._call(e,!1).then(e=>{var s;const n=t(e.reply);i(n),null===(s=e.next)||void 0===s||s.call(e)},e=>{var t;s(e.error),null===(t=e.next)||void 0===t||t.call(e)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let e;this._dispatchPromise=new Promise(t=>{e=t}),this._dispatchSynchronized(t,e)})}_dispatchSynchronized(e,t){let i=Promise.resolve();for(const s in e)e.hasOwnProperty(s)&&(i=i.then(()=>this._dispatchReply(e[s])));i=i.then(()=>{t()})}_dispatchReply(e){let t;const i=new Promise(e=>{t=e});if(null==e)return this._debug("dispatch: got undefined or null reply"),t(),i;const s=e.id;return s&&s>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),i}_call(e,t){return new Promise((i,s)=>{e.id=this._nextCommandId(),this._registerCall(e.id,i,s),t||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(G.Connecting)&&this.emit("connecting",{code:U.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,i){if(this._isDisconnected())return;this._transportIsOpen=!1;const s=this.state;this._reconnecting=!1;const n={code:e,reason:t};let r=!1;if(i?r=this._setState(G.Connecting):(r=this._setState(G.Disconnected),this._rejectPromises({code:H.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),s===G.Connecting&&this._clearReconnectTimeout(),s===G.Connected&&this._clearConnectedState(),r&&(this._isConnecting()?this.emit("connecting",n):this.emit("disconnected",n)),this._transport){this._debug("closing existing transport");const e=this._transport;this._transport=null,e.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(j.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:H.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new ve("")))}_refresh(){const e=this._client,t=this;this._getToken().then(function(i){if(e!==t._client)return;if(!i)return void t._failUnauthorized();if(t._token=i,t._debug("connection token refreshed"),!t._isConnected())return;const s={refresh:{token:t._token}};t._call(s,!1).then(e=>{const i=e.reply.refresh;t._refreshResponse(i),e.next&&e.next()},e=>{t._refreshError(e.error),e.next&&e.next()})}).catch(function(e){t._isConnected()&&(e instanceof ve?t._failUnauthorized():(t.emit("error",{type:"refreshToken",error:{code:H.clientRefreshToken,message:void 0!==e?e.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())))})}_refreshError(e){e.code<100||!0===e.temporary?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return te(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),ie(e.ttl)))}_removeSubscription(e){null!==e&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const t={unsubscribe:{channel:e.channel}},i=this;return new Promise((e,s)=>{this._call(t,!1).then(t=>{e(),t.next&&t.next()},t=>{e(),t.next&&t.next(),i._disconnect(U.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(const e in this._subs)if(this._subs.hasOwnProperty(e)){const i=this._subs[e];if(i._id===t)return i}return null}const i=this._subs[e];return i||null}_isServerSub(e){return void 0!==this._serverSubs[e]}_sendSubscribeCommands(){const e=[];for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const i=this._subs[t];if(!0!==i._inflight&&i.state===X.Subscribing){const t=i._subscribe();t&&e.push(t)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(G.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ie(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=1e3*e.ping,this._sendPong=!0===e.pong,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const t in e){if(!e.hasOwnProperty(t))continue;const i=e[t];this._serverSubs[t]={offset:i.offset,epoch:i.epoch,recoverable:i.recoverable||!1};const s=this._getSubscribeContext(t,i);this.emit("subscribed",s)}for(const t in e){if(!e.hasOwnProperty(t))continue;const i=e[t];if(i.recovered){const e=i.publications;if(e&&e.length>0)for(const i in e)e.hasOwnProperty(i)&&this._handlePublication(t,e[i])}}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&(e[t]||(this.emit("unsubscribed",{channel:t}),delete this._serverSubs[t]))}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){null!==this._serverPingTimeout&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){0!==this._config.maxServerPingDelay&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(U.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){const i={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};t.recovered&&(i.recovered=!0),t.positioned&&(i.positioned=!0),t.recoverable&&(i.recoverable=!0),t.was_recovering&&(i.wasRecovering=!0);let s="";"epoch"in t&&(s=t.epoch);let n=0;return"offset"in t&&(n=t.offset),(i.positioned||i.recoverable)&&(i.streamPosition={offset:n,epoch:s}),Array.isArray(t.publications)&&t.publications.length>0&&(i.hasRecoveredPublications=!0),t.data&&(i.data=t.data),i}_handleReply(e,t){const i=e.id;if(!(i in this._callbacks))return void t();const s=this._callbacks[i];if(clearTimeout(this._callbacks[i].timeout),delete this._callbacks[i],"error"in(n=e)&&null!==n.error){const i=s.errback;if(!i)return void t();i({error:{code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1},next:t})}else{const i=s.callback;if(!i)return;i({reply:e,next:t})}var n}_handleJoin(e,t,i){const s=this._getSub(e,i);if(s||!e)s._handleJoin(t);else if(this._isServerSub(e)){const i={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",i)}}_handleLeave(e,t,i){const s=this._getSub(e,i);if(s||!e)s._handleLeave(t);else if(this._isServerSub(e)){const i={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",i)}}_handleUnsubscribe(e,t){const i=this._getSub(e,0);i||!e?t.code<2500?i._setUnsubscribed(t.code,t.reason,!1):i._setSubscribing(t.code,t.reason):this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,t))}_handleDisconnect(e){const t=e.code;let i=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(i=!1),this._disconnect(t,e.reason,i)}_getPublicationContext(e,t){const i={channel:e,data:t.data};return t.offset&&(i.offset=t.offset),t.info&&(i.info=this._getJoinLeaveContext(t.info)),t.tags&&(i.tags=t.tags),i}_getJoinLeaveContext(e){const t={client:e.client,user:e.user},i=e.conn_info;i&&(t.connInfo=i);const s=e.chan_info;return s&&(t.chanInfo=s),t}_handlePublication(e,t,i){const s=this._getSub(e,i);if(s||!e)s._handlePublication(t);else if(this._isServerSub(e)){const i=this._getPublicationContext(e,t);this.emit("publication",i),void 0!==t.offset&&(this._serverSubs[e].offset=t.offset)}}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const e={};this._transportSendCommands([e])}e()}_handlePush(e,t){const i=e.channel,s=e.id;e.pub?this._handlePublication(i,e.pub,s):e.message?this._handleMessage(e.message):e.join?this._handleJoin(i,e.join,s):e.leave?this._handleLeave(i,e.leave,s):e.unsubscribe?this._handleUnsubscribe(i,e.unsubscribe):e.subscribe?this._handleSubscribe(i,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,i){const s={code:e,message:t};return i&&(s.temporary=!0),s}_registerCall(e,t,i){this._callbacks[e]={callback:t,errback:i,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],ee(i)&&i({error:this._createErrorObject(H.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}}me.SubscriptionState=X,me.State=G,me.UnauthorizedError=ve;class fe{constructor(e,i){t(this,"config"),t(this,"events"),t(this,"client",null),t(this,"personalSub",null),t(this,"userId",null),t(this,"getTokenCallback",null),this.config=e,this.events=i}updateConfig(e){this.config=e}setTokenRefreshCallback(e){this.getTokenCallback=e}connect(e,t){var i;if("connected"===(null==(i=this.client)?void 0:i.state))return;this.userId=e;const s=this.getWebSocketUrl(),n={token:t};this.getTokenCallback&&(n.getToken=async()=>await this.getTokenCallback()),this.client=new me(s,n),this.setupClientEventListeners(),this.client.connect()}getWebSocketUrl(){if(this.config.centrifugoUrl)return this.config.centrifugoUrl;const e=new URL(this.config.apiBase);return`${"https:"===e.protocol?"wss:":"ws:"}//${e.host}/connection/websocket`}setupClientEventListeners(){this.client&&(this.client.on("connected",e=>{this.events.emit("connection:open",{clientId:e.client}),this.subscribeToPersonalChannel()}),this.client.on("disconnected",e=>{this.events.emit("connection:close",{reason:e.reason,code:e.code})}),this.client.on("error",e=>{var t;this.events.emit("connection:error",{error:(null==(t=e.error)?void 0:t.message)||"Unknown error"})}))}subscribeToPersonalChannel(){if(!this.client||!this.userId)return;const e=`visitor:${this.userId}`,t=this.client.getSubscription(e);if(t)return this.personalSub=t,void("subscribed"!==t.state&&t.subscribe());this.personalSub=this.client.newSubscription(e),this.personalSub.on("publication",e=>{this.handleMessage(e.data)}),this.personalSub.on("error",e=>{var t;this.events.emit("error",{type:"subscription",error:null==(t=e.error)?void 0:t.message})}),this.personalSub.subscribe()}handleMessage(e){const t=e.data||e;switch(e.type){case"new_message":const e={id:t.id,body:t.body,inbound:t.inbound||!1,outbound:t.outbound||!1,createdAt:t.createdAt,type:t.type||"text",mediaUrl:t.mediaUrl,senderType:t.senderType,agentName:t.agentName};this.events.emit("message:received",{ticketId:t.ticketId,message:e});break;case"typing":t.isTyping?this.events.emit("typing:start",{ticketId:t.ticketId,actor:t.senderType||"agent"}):this.events.emit("typing:stop",{ticketId:t.ticketId,actor:t.senderType||"agent"});break;case"ticket_created":this.events.emit("conversation:started",{ticketId:t.ticketId,contactId:t.contactId,createdAt:t.createdAt});break;case"ticket_status":this.events.emit("conversation:updated",{ticketId:t.ticketId,status:t.status,message:t.message,closedAt:t.closedAt,agentName:t.agentName})}}updateToken(e){this.client&&this.client.setToken(e)}disconnect(){this.personalSub&&(this.personalSub.unsubscribe(),this.personalSub=null),this.client&&(this.client.disconnect(),this.client=null),this.userId=null}isConnected(){var e;return"connected"===(null==(e=this.client)?void 0:e.state)}getUserId(){return this.userId}}function _e(e,t,i){const s=document.createElement(e);return t&&Object.entries(t).forEach(([e,t])=>{"className"===e?s.className=t:e.startsWith("data-")||e.startsWith("aria-")?s.setAttribute(e,t):s[e]=t}),i&&i.forEach(e=>{"string"==typeof e?s.appendChild(document.createTextNode(e)):s.appendChild(e)}),s}function be(e){if(!e||"string"!=typeof e)return!1;try{const t=new URL(e,window.location.origin);return["http:","https:","blob:"].includes(t.protocol)}catch{return!1}}function we(e){return function(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>").replace(/\[(.+?)\]\((.+?)\)/g,(e,t,i)=>{const s=function(e){return be(e)?e:""}(i);return s?`<a href="${s}" target="_blank" rel="noopener">${t}</a>`:t}).replace(/\n/g,"<br>")}function ye(e,t=!0){e.scrollTo({top:e.scrollHeight,behavior:t?"smooth":"auto"})}function xe(){return"cevro_"+Math.random().toString(36).substring(2,9)}class Ce{constructor(e,i,s){t(this,"config"),t(this,"element",null),t(this,"unreadBadge",null),t(this,"onClick"),t(this,"bubbleIconUrl"),this.config=e,this.onClick=i,this.bubbleIconUrl=s}render(){this.element=_e("div",{className:"cevro-launcher","data-testid":"launcher"}),this.applyPositioning();const e=_e("button",{className:"cevro-launcher__button","aria-label":"Open chat",type:"button","data-testid":"launcher-button"});if(this.bubbleIconUrl){const t=_e("img",{className:"cevro-launcher__icon cevro-launcher__icon--chat cevro-launcher__icon--custom",src:this.bubbleIconUrl,alt:"Chat"});t.style.width="28px",t.style.height="28px",t.style.objectFit="contain",e.appendChild(t)}else{const t=this.createChatIcon();t.classList.add("cevro-launcher__icon","cevro-launcher__icon--chat"),e.appendChild(t)}const t=this.createCloseIcon();return t.classList.add("cevro-launcher__icon","cevro-launcher__icon--close"),e.appendChild(t),this.unreadBadge=_e("span",{className:"cevro-launcher__badge","data-testid":"unread-badge"}),this.unreadBadge.style.display="none",e.appendChild(this.unreadBadge),e.addEventListener("click",this.onClick),this.element.appendChild(e),this.element}applyPositioning(){if(!this.element)return;const e=this.config.alignment||"right",t=this.config.verticalPadding??20,i=this.config.horizontalPadding??20;this.element.style.bottom=`${t}px`,"left"===e?(this.element.style.left=`${i}px`,this.element.style.right="auto"):(this.element.style.right=`${i}px`,this.element.style.left="auto"),this.config.zIndex&&(this.element.style.zIndex=String(this.config.zIndex))}createChatIcon(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"),e.appendChild(t),e}createCloseIcon(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round");const t=document.createElementNS("http://www.w3.org/2000/svg","line");t.setAttribute("x1","18"),t.setAttribute("y1","6"),t.setAttribute("x2","6"),t.setAttribute("y2","18");const i=document.createElementNS("http://www.w3.org/2000/svg","line");return i.setAttribute("x1","6"),i.setAttribute("y1","6"),i.setAttribute("x2","18"),i.setAttribute("y2","18"),e.appendChild(t),e.appendChild(i),e}setState(e){this.element&&(e?this.element.classList.add("cevro-launcher--open"):this.element.classList.remove("cevro-launcher--open"))}setUnreadCount(e){this.unreadBadge&&(e>0?(this.unreadBadge.textContent=e>99?"99+":String(e),this.unreadBadge.style.display="flex"):this.unreadBadge.style.display="none")}setVisible(e){this.element&&(this.element.style.display=e?"block":"none")}pulse(){this.element&&(this.element.classList.add("cevro-launcher--pulse"),setTimeout(()=>{var e;null==(e=this.element)||e.classList.remove("cevro-launcher--pulse")},1e3))}updateBubbleIcon(e){if(this.bubbleIconUrl=e,!this.element)return;const t=this.element.querySelector(".cevro-launcher__button");if(!t)return;const i=t.querySelector(".cevro-launcher__icon--chat");if(i&&i.remove(),e){const i=document.createElement("img");i.className="cevro-launcher__icon cevro-launcher__icon--chat cevro-launcher__icon--custom",i.src=e,i.alt="Chat",i.style.cssText="width: 28px !important; height: 28px !important; object-fit: contain; border-radius: 4px;",t.insertBefore(i,t.firstChild)}else{const e=this.createChatIcon();e.classList.add("cevro-launcher__icon","cevro-launcher__icon--chat"),t.insertBefore(e,t.firstChild)}}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.unreadBadge=null}}const ke={headerTitle:"Cevro",headerSubtitle:"We typically reply within a few minutes",inputPlaceholder:"How can we help?",preChatTitle:"Start a conversation",preChatSubtitle:"Please provide your contact information to get started.",preChatFirstNameLabel:"First name",preChatFirstNamePlaceholder:"Your first name",preChatEmailLabel:"Email",preChatEmailPlaceholder:"your@email.com",preChatSubmit:"Start Chat",preChatFirstNameRequired:"First name is required",preChatEmailRequired:"Email is required",preChatEmailInvalid:"Please enter a valid email",closedMessage:"The agent closed the chat.",newConversation:"Start New Conversation",csatTitle:"How was your conversation?",csatSubtitle:"Your feedback helps us get better.",csatPlaceholder:"Thank you! What stood out?",csatPlaceholderNegative:"Sorry to hear that. What could we improve?",csatPlaceholderNeutral:"Thanks for your feedback. Anything we could do better?",csatSubmit:"Submit Feedback",csatThankYou:"Thank you for your feedback!",poweredBy:"Powered by Cevro AI"};function Se(e,t){return{...ke,...e,...t}}class Te{constructor(){t(this,"element",null),t(this,"messagesContainer",null),t(this,"messages",new Map),t(this,"onQuickAction",null),t(this,"autoScroll",!0),t(this,"closedMessageElement",null),t(this,"currentAgent",null)}setQuickActionHandler(e){this.onQuickAction=e}setAgent(e){this.currentAgent=e}render(){return this.element||(this.element=_e("div",{className:"cevro-messages",id:xe()}),this.messagesContainer=_e("div",{className:"cevro-messages__container","data-testid":"messages-container"}),this.messagesContainer.addEventListener("scroll",()=>{this.autoScroll=function(e,t=50){return e.scrollHeight-e.scrollTop-e.clientHeight<t}(this.messagesContainer)}),this.element.appendChild(this.messagesContainer)),this.element}addMessage(e,t=!0){if(!this.messagesContainer)return;if(this.messages.has(e.id))return void this.updateMessage(e);const i=this.createMessageElement(e);t&&i.classList.add("cevro-message--animate");const s=this.messagesContainer.querySelector("#cevro-typing-indicator");s?this.messagesContainer.insertBefore(i,s):this.messagesContainer.appendChild(i),this.messages.set(e.id,i),this.autoScroll&&ye(this.messagesContainer)}updateMessage(e,t){const i=t||e.id,s=this.messages.get(i);if(!s||!this.messagesContainer)return;const n=this.createMessageElement(e);this.messagesContainer.replaceChild(n,s),t&&t!==e.id&&this.messages.delete(t),this.messages.set(e.id,n)}updateMessageProgress(e,t){const i=this.messages.get(e);if(!i)return;const s=i.querySelector(".cevro-file-progress__fill"),n=i.querySelector(".cevro-file-progress__text");s&&(s.style.width=`${t}%`),n&&(n.textContent=`${t}%`)}removeMessage(e){const t=this.messages.get(e);t&&(t.remove(),this.messages.delete(e))}createMessageElement(e){var t,i,s,n,r;const o=!0===e.inbound,a=_e("div",{className:"cevro-message "+(o?"cevro-message--outbound":"cevro-message--inbound"),"data-message-id":e.id,"data-testid":`message-${e.id}`});if(!o){const i="human"===e.senderType,s=_e("div",{className:"cevro-message__avatar"+(i?" cevro-message__avatar--human":"")});if(i){const t=(e.agentName||"Support").split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2),i=_e("div",{className:"cevro-message__avatar-initials"});i.textContent=t,s.appendChild(i)}else if((null==(t=this.currentAgent)?void 0:t.avatarUrl)&&be(this.currentAgent.avatarUrl)){const e=_e("img",{className:"cevro-message__avatar-img"});e.src=this.currentAgent.avatarUrl,e.alt=this.currentAgent.name||"Agent",s.appendChild(e)}else s.innerHTML=this.createBotAvatarSvg();a.appendChild(s)}const c=_e("div",{className:"cevro-message__content-wrapper"});if(!o&&"human"===e.senderType&&e.agentName){const t=_e("div",{className:"cevro-message__sender-name"});t.textContent=e.agentName,c.appendChild(t)}const l=_e("div",{className:"cevro-message__bubble"}),h="image"===e.type||"image"===(null==(i=e.attachment)?void 0:i.category);if(h&&e.mediaUrl&&be(e.mediaUrl)){const t=_e("div",{className:"cevro-message__image-container"}),i=_e("img",{className:"cevro-message__image"});if(i.src=e.mediaUrl,i.alt=(null==(s=e.attachment)?void 0:s.filename)||"Image",i.loading="lazy",t.appendChild(i),"sending"===e.status){const e=this.createProgressOverlay();t.appendChild(e)}l.appendChild(t)}else if("file"===e.type||e.attachment&&!h){const t=this.createFileCard(e);l.appendChild(t)}else if("media"===e.type&&e.mediaUrl&&be(e.mediaUrl)){const t=_e("a",{className:"cevro-message__attachment"});t.href=e.mediaUrl,t.target="_blank",t.rel="noopener",t.innerHTML=`\n ${this.getFileIcon("file")}\n <span>Attachment</span>\n `,l.appendChild(t)}if(e.body){const t=_e("div",{className:"cevro-message__text"});t.innerHTML=we(e.body),l.appendChild(t)}if(c.appendChild(l),null==(r=null==(n=e.richContent)?void 0:n.quickActions)?void 0:r.length){const t=_e("div",{className:"cevro-message__quick-actions"});e.richContent.quickActions.forEach(e=>{const i=_e("button",{className:"cevro-message__quick-action"});i.textContent=e.label,i.addEventListener("click",()=>{this.onQuickAction&&this.onQuickAction(e)}),t.appendChild(i)}),c.appendChild(t)}const d=_e("div",{className:"cevro-message__meta"});var u;if(d.textContent=("string"==typeof(u=e.createdAt)?new Date(u):u).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o&&e.status){const t=_e("span",{className:`cevro-message__status cevro-message__status--${e.status}`});t.innerHTML=this.getStatusIcon(e.status),d.appendChild(t)}return c.appendChild(d),a.appendChild(c),a}createProgressOverlay(){const e=_e("div",{className:"cevro-file-progress-overlay"});return e.innerHTML='\n <div class="cevro-file-progress">\n <div class="cevro-file-progress__bar">\n <div class="cevro-file-progress__fill" style="width: 0%"></div>\n </div>\n <span class="cevro-file-progress__text">0%</span>\n </div>\n ',e}createFileCard(e){const t=e.attachment,i=(null==t?void 0:t.category)||"file",s=(null==t?void 0:t.filename)||"File",n=(null==t?void 0:t.size)||0,r="sending"===e.status,o=_e("div",{className:`cevro-file-card cevro-file-card--${i}`}),a=_e("div",{className:"cevro-file-card__icon"});a.innerHTML=this.getFileIcon(i),o.appendChild(a);const c=_e("div",{className:"cevro-file-card__info"}),l=_e("div",{className:"cevro-file-card__name"});l.textContent=this.truncateFilename(s,25),l.title=s,c.appendChild(l);const h=_e("div",{className:"cevro-file-card__details"});if(h.textContent=this.formatFileSize(n),c.appendChild(h),o.appendChild(c),r){const e=_e("div",{className:"cevro-file-card__progress"});e.innerHTML='\n <div class="cevro-file-progress">\n <div class="cevro-file-progress__bar">\n <div class="cevro-file-progress__fill" style="width: 0%"></div>\n </div>\n <span class="cevro-file-progress__text">0%</span>\n </div>\n ',o.appendChild(e)}else e.mediaUrl&&be(e.mediaUrl)&&(o.style.cursor="pointer",o.addEventListener("click",()=>{window.open(e.mediaUrl,"_blank")}));return o}getFileIcon(e){const t={pdf:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#E53935"/>\n <path d="M14 2V8H20" fill="#FFCDD2"/>\n <path d="M9 13H10.5V14.5H9V16H7.5V11H10.5V12.5H9V13Z" fill="white"/>\n <path d="M11.5 11H13.5C14.05 11 14.5 11.45 14.5 12V14C14.5 14.55 14.05 15 13.5 15H12.5V16H11.5V11ZM13 14V12H12.5V14H13Z" fill="white"/>\n <path d="M15.5 11H17V12H16V13H17V14H16V16H15.5V11Z" fill="white"/>\n </svg>',document:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#1976D2"/>\n <path d="M14 2V8H20" fill="#BBDEFB"/>\n <path d="M8 12H16V13H8V12ZM8 15H14V16H8V15Z" fill="white"/>\n </svg>',spreadsheet:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#388E3C"/>\n <path d="M14 2V8H20" fill="#C8E6C9"/>\n <path d="M8 12H10V14H8V12ZM11 12H13V14H11V12ZM14 12H16V14H14V12ZM8 15H10V17H8V15ZM11 15H13V17H11V15Z" fill="white"/>\n </svg>',presentation:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#F57C00"/>\n <path d="M14 2V8H20" fill="#FFE0B2"/>\n <rect x="8" y="12" width="8" height="5" rx="1" fill="white"/>\n </svg>',video:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#7B1FA2"/>\n <path d="M14 2V8H20" fill="#E1BEE7"/>\n <path d="M10 11V17L15 14L10 11Z" fill="white"/>\n </svg>',audio:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#00897B"/>\n <path d="M14 2V8H20" fill="#B2DFDB"/>\n <path d="M12 11C10.9 11 10 11.9 10 13V15C10 16.1 10.9 17 12 17C13.1 17 14 16.1 14 15V13C14 11.9 13.1 11 12 11Z" fill="white"/>\n <path d="M15 14V15C15 16.66 13.66 18 12 18C10.34 18 9 16.66 9 15V14H8V15C8 17.03 9.53 18.71 11.5 18.96V20H10V21H14V20H12.5V18.96C14.47 18.71 16 17.03 16 15V14H15Z" fill="white"/>\n </svg>',archive:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#795548"/>\n <path d="M14 2V8H20" fill="#D7CCC8"/>\n <rect x="10" y="11" width="4" height="2" fill="white"/>\n <rect x="10" y="14" width="4" height="2" fill="white"/>\n <rect x="10" y="17" width="4" height="2" fill="white"/>\n </svg>',text:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#607D8B"/>\n <path d="M14 2V8H20" fill="#CFD8DC"/>\n <path d="M8 12H16V13H8V12ZM8 15H14V16H8V15ZM8 18H16V19H8V18Z" fill="white"/>\n </svg>',image:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#43A047"/>\n <path d="M14 2V8H20" fill="#C8E6C9"/>\n <circle cx="10" cy="13" r="2" fill="white"/>\n <path d="M8 18L10 15L12 17L15 13L17 18H8Z" fill="white"/>\n </svg>',file:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#90A4AE"/>\n <path d="M14 2V8H20" fill="#CFD8DC"/>\n </svg>'};return t[e]||t.file}formatFileSize(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(1))+" "+["B","KB","MB","GB"][t]}truncateFilename(e,t){if(e.length<=t)return e;const i=e.split(".").pop()||"";return e.slice(0,e.length-i.length-1).slice(0,t-i.length-4)+"..."+"."+i}createBotAvatarSvg(){return'\n <svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="14" cy="10" r="4" fill="white"/>\n <path d="M7 22c0-3.866 3.134-7 7-7s7 3.134 7 7" stroke="white" stroke-width="2" stroke-linecap="round"/>\n </svg>\n '}getStatusIcon(e){switch(e){case"sending":return'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';case"sent":case"delivered":return'<svg width="16" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 7 9.5 17 5 12"/><polyline points="23 7 14.5 17 12 14"/></svg>';case"read":return'<svg width="16" height="12" viewBox="0 0 24 24" fill="none" stroke="#8B5CF6" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 7 9.5 17 5 12"/><polyline points="23 7 14.5 17 12 14"/></svg>';case"failed":return'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>';default:return""}}showTypingIndicator(){if(!this.messagesContainer)return;this.hideTypingIndicator();const e=_e("div",{className:"cevro-typing-indicator",id:"cevro-typing-indicator","data-testid":"typing-indicator"});e.innerHTML=`\n <div class="cevro-typing-indicator__avatar">\n ${this.createBotAvatarSvg()}\n </div>\n <div class="cevro-typing-indicator__dots">\n <span></span>\n <span></span>\n <span></span>\n </div>\n `,this.messagesContainer.appendChild(e),this.autoScroll&&ye(this.messagesContainer)}hideTypingIndicator(){var e;const t=null==(e=this.messagesContainer)?void 0:e.querySelector("#cevro-typing-indicator");t&&t.remove()}clear(){this.messagesContainer&&(this.messagesContainer.innerHTML=""),this.messages.clear(),this.closedMessageElement&&(this.closedMessageElement.remove(),this.closedMessageElement=null)}showClosedMessage(e){if(!this.messagesContainer)return;this.hideClosedMessage(),this.closedMessageElement=_e("div",{className:"cevro-messages__closed-notice","data-testid":"closed-chat-message"});const t=e||"The agent closed the chat. If you need assistance please start a new chat.";this.closedMessageElement.innerHTML=`\n <p class="cevro-messages__closed-text">\n ${t}\n </p>\n `,this.messagesContainer.appendChild(this.closedMessageElement),this.autoScroll&&ye(this.messagesContainer)}hideClosedMessage(){this.closedMessageElement&&(this.closedMessageElement.remove(),this.closedMessageElement=null)}scrollToBottom(){this.messagesContainer&&ye(this.messagesContainer,!1)}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.messagesContainer=null,this.messages.clear()}}class Ie{constructor(e,i,s,n){t(this,"config"),t(this,"callbacks"),t(this,"element",null),t(this,"messageList"),t(this,"inputElement",null),t(this,"sendButton",null),t(this,"fileInput",null),t(this,"fileButton",null),t(this,"isVisible",!1),t(this,"logoElement",null),t(this,"brandNameElement",null),t(this,"headerSubtitleElement",null),t(this,"inputWrapper",null),t(this,"closedFooter",null),t(this,"csatContainer",null),t(this,"strings",ke),t(this,"csatRating",0),t(this,"csatFeedback",""),t(this,"csatSubmitting",!1),t(this,"preChatContainer",null),t(this,"preChatCompleted",!1),t(this,"customLogoUrl"),this.config=e,this.callbacks=i,this.strings=s||Se(e.locale),this.customLogoUrl=n,this.messageList=new Te,this.messageList.setQuickActionHandler(e=>{this.callbacks.onQuickAction(e)})}setStrings(e){this.strings=Se(this.config.locale,e),this.updateUIStrings()}updateUIStrings(){this.headerSubtitleElement&&(this.headerSubtitleElement.textContent=this.strings.headerSubtitle),this.inputElement&&(this.inputElement.placeholder=this.strings.inputPlaceholder)}render(){if(this.element)return this.element;this.element=_e("div",{className:"cevro-chat-window",id:xe()}),this.applyPositioning();const e=this.createHeader();this.element.appendChild(e);const t=this.messageList.render();return this.element.appendChild(t),this.inputWrapper=this.createInputArea(),this.element.appendChild(this.inputWrapper),this.element}applyPositioning(){if(!this.element)return;const e=this.config.alignment||"right",t=this.config.verticalPadding??20,i=this.config.horizontalPadding??20;this.element.style.bottom=`${t+70}px`,"left"===e?(this.element.style.left=`${i}px`,this.element.style.right="auto"):(this.element.style.right=`${i}px`,this.element.style.left="auto"),this.config.zIndex&&(this.element.style.zIndex=String(this.config.zIndex-1))}createHeader(){const e=_e("div",{className:"cevro-chat-window__header"});if(this.logoElement=_e("div",{className:"cevro-chat-window__logo","data-testid":"company-logo"}),this.customLogoUrl){const e=_e("img",{src:this.customLogoUrl,alt:"Logo",className:"cevro-chat-window__logo-img"});e.style.width="40px",e.style.height="40px",e.style.objectFit="contain",e.style.borderRadius="8px",this.logoElement.appendChild(e)}else this.logoElement.innerHTML=this.createCompanyLogoSvg();e.appendChild(this.logoElement);const t=_e("div",{className:"cevro-chat-window__title-section"});this.brandNameElement=_e("h2",{className:"cevro-chat-window__title","data-testid":"brand-name"},[this.strings.headerTitle]),this.headerSubtitleElement=_e("p",{className:"cevro-chat-window__subtitle"},[this.strings.headerSubtitle]),t.appendChild(this.brandNameElement),t.appendChild(this.headerSubtitleElement),e.appendChild(t);const i=_e("button",{className:"cevro-chat-window__close","aria-label":"Close chat","data-testid":"close-button"});return i.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <line x1="18" y1="6" x2="6" y2="18"/>\n <line x1="6" y1="6" x2="18" y2="18"/>\n </svg>\n ',i.addEventListener("click",()=>{this.callbacks.onClose()}),e.appendChild(i),e}createCompanyLogoSvg(){return'\n <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">\n <rect width="40" height="40" rx="8" fill="url(#cevro-logo-gradient)"/>\n <svg x="6" y="6" width="28" height="28" viewBox="0 0 512 498">\n <g>\n <path fill="#FFFFFF" d="M298.97,91.19l-32.23-32.23c-6.12-6.12-6.12-16.03,0-22.15l32.23-32.23c6.12-6.12,16.03-6.12,22.15,0\n l30.06,30.06c2.94,2.94,6.92,4.59,11.07,4.59h48.31v17.32h-48.31c-4.15,0-8.14,1.65-11.07,4.59l-30.05,30.06\n C315,97.3,305.09,97.31,298.97,91.19z"/>\n <path fill="#FFFFFF" d="M260.84,157h96.5c4.15,0,8.14,1.65,11.07,4.59l30.05,30.05c6.12,6.12,16.03,6.12,22.15,0l30.06-30.06\n c2.94-2.94,6.92-4.59,11.07-4.59h50.21v-17.32h-50.21c-4.15,0-8.14-1.65-11.07-4.59l-30.06-30.06\n c-6.12-6.12-16.03-6.12-22.15,0l-30.06,30.05c-2.94,2.94-6.92,4.59-11.07,4.59h-96.5c-4.15,0-8.14-1.65-11.07-4.59\n l-30.06-30.05c-6.12-6.12-16.03-6.12-22.15,0l-32.23,32.23c-6.12,6.12-6.12,16.03,0,22.15l32.23,32.23\n c6.12,6.12,16.03,6.12,22.15,0l30.06-30.05C252.7,158.65,256.69,157,260.84,157z"/>\n <path fill="#FFFFFF" d="M260.84,340.58h96.5c4.15,0,8.14-1.65,11.07-4.59l30.06-30.06c6.12-6.12,16.03-6.12,22.15,0L450.67,336\n c2.94,2.94,6.92,4.59,11.07,4.59h50.21v17.32h-50.21c-4.15,0-8.14,1.65-11.07,4.59l-30.05,30.06\n c-6.12,6.12-16.03,6.12-22.15,0l-30.06-30.06c-2.94-2.94-6.92-4.59-11.07-4.59h-96.5c-4.15,0-8.14,1.65-11.07,4.59\n l-30.05,30.06c-6.12,6.12-16.03,6.12-22.15,0l-32.23-32.23c-6.12-6.12-6.12-16.03,0-22.15l32.23-32.23\n c6.12,6.12,16.03-6.12,22.15,0L249.77,336C252.7,338.93,256.69,340.58,260.84,340.58z"/>\n <path fill="#FFFFFF" d="M343.17,259.89l-1.13,1.13l-31.09,31.09c-1.9,1.9-4.16,3.21-6.6,3.92c-3.92,1.19-8.2,0.83-11.83-1.13\n c-0.89-0.54-1.72-1.07-2.56-1.72c-0.42-0.3-0.83-0.65-1.25-1.07l-30.02-30.08h-0.06c-2.91-2.91-6.9-4.58-11.06-4.58h-86.71\n c-2.62,0-5.11,0.65-7.37,1.84c-0.89,0.53-1.72,1.07-2.5,1.72c-0.06-0.06-0.06-0.06-0.06,0c-0.36,0.36-0.71,0.65-1.07,1.01\n l-30.08,30.08h-0.06c-0.36,0.36-0.77,0.71-1.19,1.07c-0.77,0.71-1.66,1.25-2.56,1.72c-3.63,1.9-7.91,2.32-11.83,1.13\n c-0.95-0.3-1.84-0.71-2.73-1.13c-0.06,0-0.06,0-0.06,0c-1.31-0.77-2.56-1.66-3.69-2.79l-30.08-30.08h-0.06\n c-0.71-0.77-1.49-1.37-2.32-1.96c-0.06,0.06-0.06,0.06-0.06,0c-1.31-0.89-2.68-1.55-4.16-1.96\n c-1.49-0.42-3.03-0.65-4.58-0.65H6.3v-17.3h50.12c1.55,0,3.09-0.24,4.58-0.65c1.49-0.42,2.85-1.07,4.16-1.96\n c0-0.06,0-0.06,0.06,0c0.83-0.59,1.61-1.19,2.32-1.96h0.06l30.08-30.08c1.13-1.13,2.38-2.08,3.69-2.79c0,0,0-0.06,0.06,0\n c0.47-0.24,0.95-0.48,1.43-0.65c0.48-0.18,0.95-0.36,1.43-0.48c3.86-1.19,8.08-0.77,11.71,1.13\n c0.89,0.48,1.79,1.01,2.56,1.72c0.42,0.36,0.83,0.71,1.19,1.07h0.06l30.08,30.08c0.36,0.36,0.71,0.65,1.07,1.01\n c0,0.06,0,0.06,0.06,0c0.77,0.65,1.61,1.19,2.5,1.72c2.26,1.19,4.76,1.84,7.37,1.84h86.71c4.16,0,8.14-1.66,11.06-4.58h0.06\n l30.08-30.08c0.36-0.42,0.77-0.77,1.19-1.07c0.83-0.65,1.66-1.25,2.56-1.72c3.63-1.9,7.85-2.32,11.71-1.13\n c0.48,0.12,0.95,0.3,1.43,0.48c1.96,0.71,3.74,1.84,5.29,3.45l32.22,32.22C349.23,243.83,349.23,253.76,343.17,259.89z"/>\n <path fill="#FFFFFF" d="M298.02,406.39l-32.23,32.23c-6.12,6.12-6.12,16.03,0,22.15L298.02,493c6.12,6.12,16.03,6.12,22.15,0\n l30.06-30.06c2.94-2.94,6.92-4.59,11.07-4.59h50.21v-17.32h-50.21c-4.15,0-8.14-1.65-11.07-4.59l-30.06-30.06\n C314.05,400.28,304.13,400.28,298.02,406.39z"/>\n </g>\n </svg>\n <defs>\n <linearGradient id="cevro-logo-gradient" x1="0" y1="0" x2="40" y2="40" gradientUnits="userSpaceOnUse">\n <stop offset="0%" stop-color="#8B5CF6"/>\n <stop offset="100%" stop-color="#7C3AED"/>\n </linearGradient>\n </defs>\n </svg>\n '}setAgent(e){this.messageList.setAgent(e)}createInputArea(){const e=_e("div",{className:"cevro-chat-window__input-wrapper"}),t=_e("div",{className:"cevro-chat-window__input-area"});this.fileButton=_e("button",{className:"cevro-chat-window__file-button","aria-label":"Attach file","data-testid":"file-button"}),this.fileButton.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M16.5 6V17.5C16.5 19.71 14.71 21.5 12.5 21.5C10.29 21.5 8.5 19.71 8.5 17.5V5C8.5 3.62 9.62 2.5 11 2.5C12.38 2.5 13.5 3.62 13.5 5V16.5C13.5 17.05 13.05 17.5 12.5 17.5C11.95 17.5 11.5 17.05 11.5 16.5V6H10V16.5C10 17.88 11.12 19 12.5 19C13.88 19 15 17.88 15 16.5V5C15 2.79 13.21 1 11 1C8.79 1 7 2.79 7 5V17.5C7 20.54 9.46 23 12.5 23C15.54 23 18 20.54 18 17.5V6H16.5Z" fill="currentColor"/>\n </svg>\n ',this.fileInput=_e("input",{className:"cevro-chat-window__file-input"}),this.fileInput.type="file",this.fileInput.accept=function(e=u){const t=[];return e.forEach(e=>{t.push(e)}),t.join(",")}(),this.fileInput.addEventListener("change",()=>{var e,t;(null==(t=null==(e=this.fileInput)?void 0:e.files)?void 0:t.length)&&this.callbacks.onFileUpload&&(this.callbacks.onFileUpload(this.fileInput.files[0]),this.fileInput.value="")}),this.fileButton.addEventListener("click",()=>{var e;null==(e=this.fileInput)||e.click()}),t.appendChild(this.fileButton),t.appendChild(this.fileInput),this.inputElement=_e("textarea",{className:"cevro-chat-window__input","data-testid":"chat-input"}),this.inputElement.placeholder=this.strings.inputPlaceholder,this.inputElement.rows=1,this.inputElement.setAttribute("maxlength","2000"),this.inputElement.addEventListener("input",()=>{this.resizeInput(),this.updateSendButtonState()}),this.inputElement.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.handleSend())}),t.appendChild(this.inputElement),this.sendButton=_e("button",{className:"cevro-chat-window__send-button","aria-label":"Send message","data-testid":"send-button"}),this.sendButton.disabled=!0,this.sendButton.innerHTML='\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M12 19V5M5 12L12 5L19 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',this.sendButton.addEventListener("click",()=>{this.handleSend()}),t.appendChild(this.sendButton),e.appendChild(t);const i=_e("div",{className:"cevro-chat-window__footer"});return i.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,e.appendChild(i),e}handleSend(){if(!this.inputElement)return;const e=this.inputElement.value.trim();e&&(this.callbacks.onSendMessage(e),this.inputElement.value="",this.resizeInput(),this.updateSendButtonState(),this.inputElement.focus({preventScroll:!0}))}updateSendButtonState(){this.sendButton&&this.inputElement&&(this.sendButton.disabled=!this.inputElement.value.trim())}resizeInput(){this.inputElement&&(this.inputElement.style.height="auto",this.inputElement.style.height=Math.min(this.inputElement.scrollHeight,100)+"px")}setDraft(e){if(!this.inputElement)return;const t=Number(this.inputElement.getAttribute("maxlength"))||2e3;this.inputElement.value=e.slice(0,t),this.resizeInput(),this.updateSendButtonState(),this.inputElement.focus({preventScroll:!0})}addMessage(e,t=!0){this.messageList.addMessage(e,t)}updateMessage(e,t){this.messageList.updateMessage(e,t)}updateMessageProgress(e,t){this.messageList.updateMessageProgress(e,t)}removeMessage(e){this.messageList.removeMessage(e)}showTypingIndicator(){this.messageList.showTypingIndicator()}hideTypingIndicator(){this.messageList.hideTypingIndicator()}clearMessages(){this.messageList.clear()}show(){var e;this.element&&(this.element.classList.add("cevro-chat-window--visible"),this.isVisible=!0,null==(e=this.inputElement)||e.focus({preventScroll:!0}),this.messageList.scrollToBottom())}hide(){this.element&&(this.element.classList.remove("cevro-chat-window--visible"),this.isVisible=!1)}isWindowVisible(){return this.isVisible}focusInput(){var e;null==(e=this.inputElement)||e.focus({preventScroll:!0})}setTicketClosed(e,t,i){const s=(null==i?void 0:i.skipCSAT)??!1,n=null==i?void 0:i.ticketId;if(e){this.removeClosedUI(),this.messageList.showClosedMessage(this.strings.closedMessage),this.inputWrapper&&(this.inputWrapper.style.display="none");const e=n&&localStorage.getItem(`cevro_csat_${n}`);s||e?this.showClosedFooter(t):this.showInlineCSATForm(t,n)}else this.removeClosedUI(),this.inputWrapper&&(this.inputWrapper.style.display=""),this.messageList.hideClosedMessage()}showInlineCSATForm(e,t){if(this.removeClosedUI(),this.csatRating=0,this.csatFeedback="",!this.element)return;this.csatContainer=_e("div",{className:"cevro-csat-inline"});const i=_e("div",{className:"cevro-csat-inline__header"}),s=_e("span",{className:"cevro-csat-inline__title"},[this.strings.csatTitle]),n=_e("button",{className:"cevro-csat-inline__skip","aria-label":"Skip feedback"},["Skip"]);n.addEventListener("click",()=>{t&&localStorage.setItem(`cevro_csat_${t}`,"skipped"),this.showClosedFooter(e)}),i.appendChild(s),i.appendChild(n);const r=_e("div",{className:"cevro-csat-inline__stars"});for(let l=1;l<=5;l++){const e=_e("button",{className:"cevro-csat-inline__star","data-rating":String(l),"aria-label":`Rate ${l} stars`});e.innerHTML=this.createStarSvg(!1),e.addEventListener("click",()=>this.selectInlineRating(l,r)),e.addEventListener("mouseenter",()=>this.previewRating(l,r)),e.addEventListener("mouseleave",()=>this.previewRating(this.csatRating,r)),r.appendChild(e)}const o=_e("textarea",{className:"cevro-csat-inline__feedback",placeholder:this.strings.csatPlaceholder});o.rows=2,o.addEventListener("input",()=>{this.csatFeedback=o.value});const a=_e("button",{className:"cevro-csat-inline__submit"},[this.strings.csatSubmit||"Submit"]);a.addEventListener("click",()=>this.submitInlineCSAT(e,t));const c=_e("div",{className:"cevro-csat-inline__powered-by"});c.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.csatContainer.appendChild(i),this.csatContainer.appendChild(r),this.csatContainer.appendChild(o),this.csatContainer.appendChild(a),this.csatContainer.appendChild(c),this.element.appendChild(this.csatContainer)}selectInlineRating(e,t){var i;if(this.csatSubmitting)return;this.csatRating=e,this.updateStars(e,t);const s=null==(i=t.parentElement)?void 0:i.querySelector(".cevro-csat-inline__feedback");s&&(s.placeholder=e<=2?this.strings.csatPlaceholderNegative||this.strings.csatPlaceholder:3===e&&this.strings.csatPlaceholderNeutral||this.strings.csatPlaceholder)}async submitInlineCSAT(e,t){var i;if(this.csatSubmitting||0===this.csatRating)return;this.csatSubmitting=!0;const s=null==(i=this.csatContainer)?void 0:i.querySelector(".cevro-csat-inline__submit");s&&(s.disabled=!0,s.textContent="Submitting...");try{this.callbacks.onCSATSubmit&&await this.callbacks.onCSATSubmit(this.csatRating,this.csatFeedback||void 0),t&&localStorage.setItem(`cevro_csat_${t}`,"1"),this.showInlineThankYou(e)}catch{s&&(s.disabled=!1,s.textContent=this.strings.csatSubmit||"Submit")}finally{this.csatSubmitting=!1}}showInlineThankYou(e){if(this.removeClosedUI(),!this.element)return;this.csatContainer=_e("div",{className:"cevro-csat-inline cevro-csat-inline--thank-you"});const t=_e("div",{className:"cevro-csat-inline__thank-you-row"}),i=_e("span",{className:"cevro-csat-inline__check"});i.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none">\n <circle cx="12" cy="12" r="12" fill="#10B981"/>\n <path d="M7 12L10 15L17 8" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ';const s=_e("span",{className:"cevro-csat-inline__message"},[this.strings.csatThankYou]);t.appendChild(i),t.appendChild(s);const n=_e("button",{className:"cevro-csat-inline__new-chat"},[this.strings.newConversation]);n.addEventListener("click",()=>{e&&e()});const r=_e("div",{className:"cevro-csat-inline__powered-by"});r.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.csatContainer.appendChild(t),this.csatContainer.appendChild(n),this.csatContainer.appendChild(r),this.element.appendChild(this.csatContainer)}showClosedFooter(e){if(this.removeClosedUI(),this.element){this.closedFooter=_e("div",{className:"cevro-chat-window__closed-footer"});const t=_e("button",{className:"cevro-chat-window__new-chat-button"},[this.strings.newConversation]);t.addEventListener("click",()=>{e&&e()});const i=_e("div",{className:"cevro-chat-window__powered-by"});i.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.closedFooter.appendChild(t),this.closedFooter.appendChild(i),this.element.appendChild(this.closedFooter)}}removeClosedUI(){this.csatContainer&&this.csatContainer.parentNode&&(this.csatContainer.parentNode.removeChild(this.csatContainer),this.csatContainer=null),this.closedFooter&&this.closedFooter.parentNode&&(this.closedFooter.parentNode.removeChild(this.closedFooter),this.closedFooter=null)}previewRating(e,t){this.updateStars(e,t)}updateStars(e,t){t.querySelectorAll(".cevro-csat__star, .cevro-csat-inline__star").forEach((t,i)=>{const s=i<e;t.innerHTML=this.createStarSvg(s),t.classList.toggle("cevro-csat__star--filled",s),t.classList.toggle("cevro-csat-inline__star--filled",s)})}createStarSvg(e){return e?'\n <svg width="32" height="32" viewBox="0 0 24 24" fill="#FBBF24" stroke="#FBBF24" stroke-width="1">\n <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>\n </svg>\n ':'\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#D1D5DB" stroke-width="1.5">\n <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>\n </svg>\n '}showPreChatForm(){if(this.preChatCompleted||this.preChatContainer)return;if(!this.element)return;this.element.classList.add("cevro-chat-window--prechat");const e=this.element.querySelector(".cevro-messages");e&&(e.style.display="none"),this.inputWrapper&&(this.inputWrapper.style.display="none"),this.preChatContainer=_e("div",{className:"cevro-prechat"});const t=_e("h3",{className:"cevro-prechat__title"},[this.strings.preChatTitle]),i=_e("p",{className:"cevro-prechat__subtitle"},[this.strings.preChatSubtitle]),s=_e("form",{className:"cevro-prechat__form"}),n=_e("div",{className:"cevro-prechat__field"}),r=_e("label",{className:"cevro-prechat__label",for:"cevro-prechat-firstname"},[this.strings.preChatFirstNameLabel]),o=_e("input",{className:"cevro-prechat__input",id:"cevro-prechat-firstname",type:"text","data-testid":"prechat-firstname"});o.placeholder=this.strings.preChatFirstNamePlaceholder;const a=_e("span",{className:"cevro-prechat__error","data-field":"firstName"});o.addEventListener("blur",()=>{o.classList.toggle("cevro-prechat__input--error",!o.value.trim())}),n.appendChild(r),n.appendChild(o),n.appendChild(a);const c=_e("div",{className:"cevro-prechat__field"}),l=_e("label",{className:"cevro-prechat__label",for:"cevro-prechat-email"},[this.strings.preChatEmailLabel]),h=_e("input",{className:"cevro-prechat__input",id:"cevro-prechat-email",type:"text",autocomplete:"email","data-testid":"prechat-email"});h.placeholder=this.strings.preChatEmailPlaceholder;const d=_e("span",{className:"cevro-prechat__error","data-field":"email"});h.addEventListener("blur",()=>{const e=h.value.trim();h.classList.toggle("cevro-prechat__input--error",!e||!this.isValidEmail(e))}),c.appendChild(l),c.appendChild(h),c.appendChild(d);const u=_e("button",{className:"cevro-prechat__submit",type:"submit","data-testid":"prechat-submit"},[this.strings.preChatSubmit]);s.addEventListener("submit",e=>{e.preventDefault(),a.textContent="",d.textContent="",o.classList.remove("cevro-prechat__input--error"),h.classList.remove("cevro-prechat__input--error");const t=o.value.trim(),i=h.value.trim();let s=!1;t||(a.textContent=this.strings.preChatFirstNameRequired,o.classList.add("cevro-prechat__input--error"),s=!0),i?this.isValidEmail(i)||(d.textContent=this.strings.preChatEmailInvalid,h.classList.add("cevro-prechat__input--error"),s=!0):(d.textContent=this.strings.preChatEmailRequired,h.classList.add("cevro-prechat__input--error"),s=!0),s||(this.preChatCompleted=!0,this.callbacks.onPreChatSubmit&&this.callbacks.onPreChatSubmit({firstName:t,email:i}))}),s.appendChild(n),s.appendChild(c),s.appendChild(u);const p=_e("div",{className:"cevro-prechat__powered-by"});p.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.preChatContainer.appendChild(t),this.preChatContainer.appendChild(i),this.preChatContainer.appendChild(s),this.preChatContainer.appendChild(p),this.element.appendChild(this.preChatContainer),o.focus({preventScroll:!0})}hidePreChatForm(){var e,t;if(this.preChatContainer&&this.preChatContainer.parentNode&&(this.preChatContainer.parentNode.removeChild(this.preChatContainer),this.preChatContainer=null),null==(e=this.element)||e.classList.remove("cevro-chat-window--prechat"),this.element){const e=this.element.querySelector(".cevro-messages");e&&(e.style.display="",e.classList.add("cevro-messages--fade-in"))}this.inputWrapper&&(this.inputWrapper.style.display=""),null==(t=this.inputElement)||t.focus({preventScroll:!0})}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}updateCustomLogo(e){if(this.customLogoUrl=e,this.logoElement)if(this.logoElement.innerHTML="",e){const t=document.createElement("img");t.src=e,t.alt="Logo",t.className="cevro-chat-window__logo-img",t.style.width="40px",t.style.height="40px",t.style.objectFit="contain",t.style.borderRadius="8px",this.logoElement.appendChild(t)}else this.logoElement.innerHTML=this.createCompanyLogoSvg()}destroy(){this.messageList.destroy(),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.inputElement=null,this.sendButton=null,this.fileInput=null,this.fileButton=null,this.closedFooter=null,this.csatContainer=null,this.preChatContainer=null,this.preChatCompleted=!1}}const Ee=class e{constructor(i){t(this,"config"),t(this,"events"),t(this,"api"),t(this,"ws"),t(this,"launcher",null),t(this,"chatWindow",null),t(this,"container",null),t(this,"shadowRoot",null),t(this,"isBooted",!1),t(this,"isVisible",!1),t(this,"unreadCount",0),t(this,"visitorId"),t(this,"isSessionInitialized",!1),t(this,"isInitializingSession",null),t(this,"connectingPromise",null),t(this,"typingCycleTimeout",null),t(this,"isTypingVisible",!1),t(this,"typingConfig",{onDurationMs:7e3,offDurationMs:4e3}),t(this,"escapeHandler",null),t(this,"visitorContactInfo",null),t(this,"widgetAppearance",{}),t(this,"customLauncherHandler",null),t(this,"customLauncherElement",null),t(this,"isDestroyed",!1),this.config=this.normalizeConfig(i),this.events=new s,this.api=new _(this.config),this.ws=new fe(this.config,this.events),this.visitorId=o(),this.ws.setTokenRefreshCallback(async()=>this.refreshConnectionToken()),this.setupEventHandlers(),e.instance=this}static getInstance(){return e.instance}normalizeConfig(e){return{...e,apiBase:e.apiBase.replace(/\/$/,""),alignment:e.alignment||"right",verticalPadding:e.verticalPadding??20,horizontalPadding:e.horizontalPadding??20,zIndex:e.zIndex??2147483647}}setupEventHandlers(){this.events.on("message:received",e=>{this.stopTypingCycle(),this.chatWindow&&this.chatWindow.addMessage(e.message),this.isVisible||this.setUnreadCount(this.unreadCount+1)}),this.events.on("typing:start",e=>{e.ticketId===this.api.getCurrentTicketId()&&this.startTypingCycle()}),this.events.on("typing:stop",()=>{this.stopTypingCycle()}),this.events.on("conversation:updated",e=>{var t,i;if(e.ticketId===this.api.getCurrentTicketId()){if("escalated"===e.status){const i=e.agentName||"Support",s=e.message||`${i} has joined the conversation.`;null==(t=this.chatWindow)||t.addMessage({id:`escalation-${Date.now()}`,body:s,inbound:!1,outbound:!0,createdAt:(new Date).toISOString(),type:"text",senderType:"human",agentName:i})}if("closed"===e.status){const t=!0!==this.widgetAppearance.csatEnabled;null==(i=this.chatWindow)||i.setTicketClosed(!0,()=>this.startNewChat(),{ticketId:e.ticketId,skipCSAT:t})}}})}async boot(){if(this.isBooted)return;if(this.isDestroyed=!1,!this.config.preview)try{this.widgetAppearance=await this.api.getWidgetConfig()}catch{this.widgetAppearance={}}if(this.isBooted||this.isDestroyed)return;const e=document.createElement("div");e.id="cevro-messenger-host",document.body.appendChild(e),this.shadowRoot=e.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=i,this.shadowRoot.appendChild(t),this.container=document.createElement("div"),this.container.id="cevro-messenger-container",this.shadowRoot.appendChild(this.container),this.applyPrimaryColor(),this.config.hideDefaultLauncher||this.createAndMountLauncher();const s=Se(this.config.locale);this.chatWindow=new Ie(this.config,{onClose:()=>this.hide(),onSendMessage:e=>this.sendMessage(e),onQuickAction:e=>this.handleQuickAction(e),onFileUpload:e=>this.handleFileUpload(e),onCSATSubmit:async(e,t)=>this.submitCSAT(e,t),onStartNewChat:()=>this.startNewChat(),onPreChatSubmit:e=>this.handlePreChatSubmit(e)},s,this.widgetAppearance.customLogoUrl),this.container.appendChild(this.chatWindow.render());const n=function(){try{const e=localStorage.getItem("cevro_session");return e?JSON.parse(e):null}catch{return null}}();(null==n?void 0:n.ticketId)&&this.api.setCurrentTicketId(n.ticketId),this.config.customLauncherSelector&&this.bindCustomLauncher(this.config.customLauncherSelector),this.isBooted=!0,this.events.emit("boot"),this.widgetAppearance.autoOpen&&setTimeout(()=>this.show(),100)}applyPrimaryColor(){const e=this.widgetAppearance.primaryColor||this.config.primaryColor;if(e&&this.container){this.container.style.setProperty("--cevro-primary",e);const t=this.adjustColorBrightness(e,-20),i=this.adjustColorBrightness(e,40);this.container.style.setProperty("--cevro-primary-hover",t),this.container.style.setProperty("--cevro-primary-light",i)}this.applyTheme()}applyTheme(){if(!this.container)return;const e=this.widgetAppearance.theme,t=this.config.theme;if(!e&&!t)return;const i={...e,...t};this.applyCustomTheme(i)}applyCustomTheme(e){if(!this.container)return;const t=["--cevro-bg","--cevro-bg-secondary","--cevro-text","--cevro-text-secondary","--cevro-border","--cevro-user-msg-bg","--cevro-user-msg-text","--cevro-header-bg","--cevro-header-text","--cevro-bg-input","--cevro-radius","--cevro-radius-sm","--cevro-shadow","--cevro-shadow-sm","--cevro-launcher-bg","--cevro-launcher-icon","--cevro-launcher-hover-shadow","--cevro-send-btn-bg","--cevro-send-btn-icon","--cevro-file-btn-bg","--cevro-file-btn-icon","--cevro-agent-msg-bg","--cevro-agent-msg-text"];for(const i of t)this.container.style.removeProperty(i);e.backgroundColor&&this.container.style.setProperty("--cevro-bg",e.backgroundColor),e.backgroundSecondaryColor&&this.container.style.setProperty("--cevro-bg-secondary",e.backgroundSecondaryColor),e.textColor&&this.container.style.setProperty("--cevro-text",e.textColor),e.textSecondaryColor&&this.container.style.setProperty("--cevro-text-secondary",e.textSecondaryColor),e.borderColor&&this.container.style.setProperty("--cevro-border",e.borderColor),e.userMessageBackgroundColor&&this.container.style.setProperty("--cevro-user-msg-bg",e.userMessageBackgroundColor),e.userMessageTextColor&&this.container.style.setProperty("--cevro-user-msg-text",e.userMessageTextColor),e.headerBackgroundColor&&this.container.style.setProperty("--cevro-header-bg",e.headerBackgroundColor),e.headerTextColor&&this.container.style.setProperty("--cevro-header-text",e.headerTextColor),e.inputBackgroundColor&&this.container.style.setProperty("--cevro-bg-input",e.inputBackgroundColor),void 0!==e.borderRadius&&(this.container.style.setProperty("--cevro-radius",`${e.borderRadius}px`),this.container.style.setProperty("--cevro-radius-sm",`${Math.max(4,e.borderRadius-4)}px`)),e.shadowColor&&(this.container.style.setProperty("--cevro-shadow",`0 10px 40px ${e.shadowColor}`),this.container.style.setProperty("--cevro-shadow-sm",`0 2px 8px ${e.shadowColor}`)),e.launcherBackgroundColor&&this.container.style.setProperty("--cevro-launcher-bg",e.launcherBackgroundColor),e.launcherIconColor&&this.container.style.setProperty("--cevro-launcher-icon",e.launcherIconColor),e.launcherHoverShadowColor&&this.container.style.setProperty("--cevro-launcher-hover-shadow",e.launcherHoverShadowColor),e.sendButtonBackgroundColor&&this.container.style.setProperty("--cevro-send-btn-bg",e.sendButtonBackgroundColor),e.sendButtonIconColor&&this.container.style.setProperty("--cevro-send-btn-icon",e.sendButtonIconColor),e.fileButtonBackgroundColor&&this.container.style.setProperty("--cevro-file-btn-bg",e.fileButtonBackgroundColor),e.fileButtonIconColor&&this.container.style.setProperty("--cevro-file-btn-icon",e.fileButtonIconColor),e.agentMessageBackgroundColor&&this.container.style.setProperty("--cevro-agent-msg-bg",e.agentMessageBackgroundColor),e.agentMessageTextColor&&this.container.style.setProperty("--cevro-agent-msg-text",e.agentMessageTextColor)}adjustColorBrightness(e,t){e=e.replace(/^#/,"");const i=parseInt(e,16);let s=(i>>16)+t,n=(i>>8&255)+t,r=(255&i)+t;return s=Math.max(0,Math.min(255,s)),n=Math.max(0,Math.min(255,n)),r=Math.max(0,Math.min(255,r)),`#${(s<<16|n<<8|r).toString(16).padStart(6,"0")}`}createAndMountLauncher(){this.container&&(this.launcher=new Ce(this.config,()=>this.toggle(),this.widgetAppearance.bubbleIconUrl),this.container.appendChild(this.launcher.render()))}bindCustomLauncher(e){const t=document.querySelector(e);t?(this.customLauncherHandler=()=>this.toggle(),this.customLauncherElement=t,t.addEventListener("click",this.customLauncherHandler)):console.warn(`[CevroMessenger] customLauncherSelector "${e}" did not match any element`)}async connectWebSocket(){return this.connectingPromise||(this.connectingPromise=this.doConnectWebSocket()),this.connectingPromise}async doConnectWebSocket(){try{const e=n(),t=await this.api.getConnectionToken(e);this.visitorId=t.visitorId,t.visitorToken&&(r(t.visitorToken),this.api.setVisitorToken(t.visitorToken)),this.ws.connect(t.visitorId,t.token),this.events.emit("ready")}catch(e){this.events.emit("ready"),this.events.emit("error",{type:"websocket_connect",error:e})}finally{this.connectingPromise=null}}async refreshConnectionToken(){const e=n(),t=await this.api.getConnectionToken(e);return t.visitorToken&&(r(t.visitorToken),this.api.setVisitorToken(t.visitorToken)),t.token}shutdown(e){var t,i,s;if(this.isDestroyed=!0,!this.isBooted)return void((null==e?void 0:e.clearVisitorData)&&(h(),d(),l(),this.visitorId=null));this.stopTypingCycle(),this.ws.disconnect(),this.customLauncherElement&&this.customLauncherHandler&&(this.customLauncherElement.removeEventListener("click",this.customLauncherHandler),this.customLauncherElement=null,this.customLauncherHandler=null),null==(t=this.launcher)||t.destroy(),null==(i=this.chatWindow)||i.destroy();const n=null==(s=this.shadowRoot)?void 0:s.host;n&&n.parentNode&&n.parentNode.removeChild(n),this.shadowRoot=null,h(),(null==e?void 0:e.clearVisitorData)&&(d(),l(),this.visitorId=null),this.api.clear(),this.launcher=null,this.chatWindow=null,this.container=null,this.isBooted=!1,this.isVisible=!1,this.unreadCount=0,this.isSessionInitialized=!1,this.isInitializingSession=null,this.connectingPromise=null,this.events.emit("shutdown")}async show(){var e;this.isBooted||await this.boot(),this.chatWindow&&(this.chatWindow.show(),this.isVisible=!0,null==(e=this.launcher)||e.setState(!0),this.setUnreadCount(0),this.events.emit("show"),this.escapeHandler||(this.escapeHandler=e=>{"Escape"===e.key&&this.hide()},document.addEventListener("keydown",this.escapeHandler)),this.config.preview||(await this.connectWebSocket(),await this.initializeSession()))}async initializeSession(e=!1){if(e&&(this.isSessionInitialized=!1,this.isInitializingSession=null),this.isSessionInitialized)return;if(this.isInitializingSession)return this.isInitializingSession;const t=this.doInitializeSession().finally(()=>{this.isInitializingSession===t&&(this.isInitializingSession=null)});return this.isInitializingSession=t,t}async doInitializeSession(e){var t,i,s,n;try{const r=await this.api.initSession(this.visitorId,this.visitorContactInfo,e);if(r.requireContactInfo&&r.missingFields&&r.missingFields.length>0)return void(null==(t=this.chatWindow)||t.showPreChatForm());if(function(e,t,i){try{localStorage.setItem("cevro_session",JSON.stringify({sessionId:e,contactId:t,ticketId:i}))}catch{}}(r.sessionId,r.contactId,r.ticketId),this.isSessionInitialized=!0,r.agent&&this.chatWindow&&this.chatWindow.setAgent(r.agent),r.typingConfig&&(this.typingConfig=r.typingConfig),r.locale&&this.chatWindow){const e=Se(this.config.locale,r.locale);this.chatWindow.setStrings(e)}if(r.messages&&r.messages.length>0)for(const e of r.messages)null==(i=this.chatWindow)||i.addMessage(e);if(r.ticketClosed){const e=!0!==this.widgetAppearance.csatEnabled;null==(s=this.chatWindow)||s.setTicketClosed(!0,()=>this.startNewChat(),{ticketId:r.ticketId,skipCSAT:e})}this.events.emit("session:initialized",{sessionId:r.sessionId,contactId:r.contactId,ticketId:r.ticketId,isNewSession:r.isNewSession,isNewTicket:r.isNewTicket,ticketClosed:r.ticketClosed,messageCount:(null==(n=r.messages)?void 0:n.length)||0})}catch(r){throw this.events.emit("error",{type:"session_init",error:r}),r}}async submitCSAT(e,t){const i=this.api.getCurrentTicketId(),s=this.api.getContactId();if(!i||!s)throw new Error("No active session");await this.api.submitCSAT(i,s,e,t)}async startNewChat(){var e,t;null==(e=this.chatWindow)||e.clearMessages(),null==(t=this.chatWindow)||t.setTicketClosed(!1),this.isSessionInitialized=!1,await this.doInitializeSession({forceNewTicket:!0}),this.events.emit("chat:new_started")}hide(){var e;this.chatWindow&&(this.chatWindow.hide(),this.isVisible=!1,null==(e=this.launcher)||e.setState(!1),this.events.emit("hide"),this.escapeHandler&&(document.removeEventListener("keydown",this.escapeHandler),this.escapeHandler=null))}showLauncher(){var e;this.isBooted&&(this.launcher||this.createAndMountLauncher(),null==(e=this.launcher)||e.setVisible(!0))}hideLauncher(){var e;this.isBooted&&(null==(e=this.launcher)||e.setVisible(!1))}toggle(){this.isVisible?this.hide():this.show()}setDraft(e){var t;null==(t=this.chatWindow)||t.setDraft(e)}async sendMessage(t){var i,s,n,r,o,a,c,l,h,d,u,p;if(!t.trim())return;if(t.length>e.MAX_MESSAGE_LENGTH)return void this.events.emit("error",{type:"validation",error:new Error(`Message is too long. Maximum ${e.MAX_MESSAGE_LENGTH} characters allowed.`),message:`Message is too long. Maximum ${e.MAX_MESSAGE_LENGTH} characters allowed.`});const g={id:"temp_"+Date.now(),body:t,inbound:!0,outbound:!1,createdAt:(new Date).toISOString(),type:"text",status:"sending"};if(null==(i=this.chatWindow)||i.addMessage(g),this.config.preview)return g.status="sent",void(null==(s=this.chatWindow)||s.updateMessage(g));try{this.isSessionInitialized||await this.initializeSession();const e=g.id,i=await this.api.sendMessage(t);g.id=i.id,g.status="sent",null==(n=this.chatWindow)||n.updateMessage(g,e),this.events.emit("message:sent",{message:i})}catch(v){if((null==(r=null==v?void 0:v.message)?void 0:r.includes("closed"))||(null==(o=null==v?void 0:v.message)?void 0:o.includes("resolved"))||(null==(a=null==v?void 0:v.message)?void 0:a.includes("escalated"))||(null==(h=null==(l=null==(c=null==v?void 0:v.response)?void 0:c.data)?void 0:l.message)?void 0:h.includes("closed"))){null==(d=this.chatWindow)||d.removeMessage(g.id);const e=this.api.getCurrentTicketId()||void 0;return void(null==(u=this.chatWindow)||u.setTicketClosed(!0,()=>this.startNewChat(),{ticketId:e,skipCSAT:!0!==this.widgetAppearance.csatEnabled}))}g.status="failed",null==(p=this.chatWindow)||p.updateMessage(g),this.events.emit("error",{error:v,type:"send_message"})}}async handleQuickAction(e){"link"===e.type&&e.url?be(e.url)&&window.open(e.url,"_blank"):await this.sendMessage(e.value||e.label)}async handlePreChatSubmit(e){var t;this.visitorContactInfo=e,null==(t=this.chatWindow)||t.hidePreChatForm(),await this.initializeSession()}async handleFileUpload(e){var t,i,s;let n,r;try{this.isSessionInitialized||await this.initializeSession();const s=e.type.startsWith("image/"),o=this.getFileCategory(e.type);n=s?URL.createObjectURL(e):void 0,r="temp_"+Date.now();const a={id:r,body:"",inbound:!0,outbound:!1,createdAt:(new Date).toISOString(),type:s?"image":"file",mediaUrl:n,mediaType:e.type,status:"sending",attachment:{filename:e.name,contentType:e.type||"application/octet-stream",size:e.size,category:o}};null==(t=this.chatWindow)||t.addMessage(a);const c=await this.api.uploadFile(e,e=>{var t;null==(t=this.chatWindow)||t.updateMessageProgress(r,e)}),l=await this.api.sendMessage("",c),h=l.mediaUrl&&be(l.mediaUrl),d={...l,status:"sent",type:s?"image":"file",mediaUrl:h?l.mediaUrl:n,attachment:a.attachment};null==(i=this.chatWindow)||i.updateMessage(d,r),n&&h&&URL.revokeObjectURL(n),this.events.emit("message:sent",{type:o,fileName:e.name})}catch(o){n&&URL.revokeObjectURL(n),r&&(null==(s=this.chatWindow)||s.removeMessage(r));const t=(null==o?void 0:o.message)||"File upload failed",i=t.includes("too large")||t.includes("too small")||t.includes("not allowed")||t.includes("Too many uploads");this.events.emit("error",{error:o,type:i?"file_validation":"file_upload",message:t,fileName:e.name})}}getFileCategory(e){return e.startsWith("image/")?"image":"application/pdf"===e?"pdf":e.includes("word")||e.includes("document")?"document":e.includes("sheet")||e.includes("excel")?"spreadsheet":e.includes("presentation")||e.includes("powerpoint")?"presentation":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":e.includes("zip")||e.includes("archive")||e.includes("compressed")?"archive":e.startsWith("text/")?"text":"file"}setUnreadCount(e){var t;this.unreadCount=e,null==(t=this.launcher)||t.setUnreadCount(e),this.events.emit("unread_count_change",{count:e})}updateAppearance(e){this.widgetAppearance={...this.widgetAppearance,...e},"primaryColor"in e&&this.applyPrimaryColor(),"theme"in e&&this.applyTheme(),"bubbleIconUrl"in e&&this.launcher&&this.launcher.updateBubbleIcon(e.bubbleIconUrl),"customLogoUrl"in e&&this.chatWindow&&this.chatWindow.updateCustomLogo(e.customLogoUrl),this.events.emit("appearance:updated",this.widgetAppearance)}getAppearance(){return{...this.widgetAppearance}}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t)}getUnreadCount(){return this.unreadCount}getVisitorId(){return this.visitorId}update(e){this.config=this.normalizeConfig({...this.config,...e}),this.api.updateConfig(this.config),this.ws.updateConfig(this.config)}async identify(e){var t;this.config.player={...this.config.player,...e};if(!!e.playerId&&c(e.playerId)&&(h(),d()),this.api.updateConfig(this.config),this.ws.updateConfig(this.config),!this.isBooted)return;const i=this.isVisible;this.ws.disconnect(),this.api.clear(),h(),this.isSessionInitialized=!1,this.isInitializingSession=null,this.connectingPromise=null;try{await this.connectWebSocket(),null==(t=this.chatWindow)||t.clearMessages(),await this.initializeSession(!0),i&&this.chatWindow&&this.chatWindow.show(),this.events.emit("identify",{playerId:e.playerId})}catch(s){this.events.emit("error",{type:"identify",error:s})}}addPreviewMessage(e,t=!0){if(!this.config.preview||!this.chatWindow)return;const i={id:"preview_"+Date.now(),body:e,inbound:!t,outbound:t,createdAt:(new Date).toISOString(),type:"text",status:"sent"};this.chatWindow.addMessage(i)}setPreviewTyping(e){this.config.preview&&this.chatWindow&&(e?this.chatWindow.showTypingIndicator():this.chatWindow.hideTypingIndicator())}setPreviewAgent(e,t){this.config.preview&&this.chatWindow&&this.chatWindow.setAgent({name:e,avatarUrl:t})}startTypingCycle(){var e;this.stopTypingCycle();const{onDurationMs:t,offDurationMs:i}=this.typingConfig,s=()=>{var e,n;this.isTypingVisible?(null==(e=this.chatWindow)||e.hideTypingIndicator(),this.isTypingVisible=!1,this.typingCycleTimeout=setTimeout(s,i)):(null==(n=this.chatWindow)||n.showTypingIndicator(),this.isTypingVisible=!0,this.typingCycleTimeout=setTimeout(s,t))};null==(e=this.chatWindow)||e.showTypingIndicator(),this.isTypingVisible=!0,this.typingCycleTimeout=setTimeout(s,t)}stopTypingCycle(){var e;this.typingCycleTimeout&&(clearTimeout(this.typingCycleTimeout),this.typingCycleTimeout=null),this.isTypingVisible&&(null==(e=this.chatWindow)||e.hideTypingIndicator(),this.isTypingVisible=!1)}};t(Ee,"instance",null),t(Ee,"MAX_MESSAGE_LENGTH",2e3);let Le=Ee;"undefined"!=typeof window&&(window.CevroMessenger=Le),exports.CevroMessenger=Le,exports.__styles=i,exports.default=Le;
|
|
1
|
+
"use strict";var e=Object.defineProperty,t=(t,s,i)=>((t,s,i)=>s in t?e(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i)(t,"symbol"!=typeof s?s+"":s,i);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const s='#cevro-messenger-container{--cevro-primary: #8B5CF6;--cevro-primary-hover: #7C3AED;--cevro-primary-light: #A78BFA;--cevro-bg: #ffffff;--cevro-bg-secondary: #f9fafb;--cevro-bg-input: #ffffff;--cevro-text: #111827;--cevro-text-secondary: #6b7280;--cevro-border: #e5e7eb;--cevro-shadow: 0 10px 40px rgba(0, 0, 0, .15);--cevro-shadow-sm: 0 2px 8px rgba(0, 0, 0, .08);--cevro-radius: 16px;--cevro-radius-sm: 12px;--cevro-radius-md: 8px;--cevro-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;--cevro-transition: .2s ease;--cevro-header-bg: var(--cevro-bg);--cevro-header-text: var(--cevro-text);--cevro-user-msg-bg: var(--cevro-bg);--cevro-user-msg-text: var(--cevro-text);--cevro-launcher-bg: var(--cevro-primary);--cevro-launcher-icon: #ffffff;--cevro-launcher-hover-shadow: rgba(139, 92, 246, .4);--cevro-focus-ring: rgba(139, 92, 246, .2);--cevro-send-btn-bg: var(--cevro-primary);--cevro-send-btn-icon: #ffffff;--cevro-file-btn-bg: var(--cevro-bg);--cevro-file-btn-icon: var(--cevro-text-secondary);--cevro-file-btn-border: var(--cevro-border);--cevro-agent-msg-bg: var(--cevro-primary);--cevro-agent-msg-text: #ffffff}.cevro-launcher{position:fixed;z-index:2147483647;font-family:var(--cevro-font)}.cevro-launcher__button{width:56px;height:56px;border-radius:50%;border:none;background-color:var(--cevro-launcher-bg);color:var(--cevro-launcher-icon);cursor:pointer;box-shadow:var(--cevro-shadow);display:flex;align-items:center;justify-content:center;transition:transform var(--cevro-transition),box-shadow var(--cevro-transition);position:relative}.cevro-launcher__button:hover{transform:scale(1.05);box-shadow:0 12px 48px var(--cevro-launcher-hover-shadow)}.cevro-launcher__button:active{transform:scale(.95)}.cevro-launcher__icon{width:24px;height:24px;transition:opacity var(--cevro-transition),transform var(--cevro-transition)}.cevro-launcher__icon--chat{opacity:1;transform:scale(1)}.cevro-launcher__icon--close{position:absolute;opacity:0;transform:scale(.5)}.cevro-launcher--open .cevro-launcher__icon--chat{opacity:0;transform:scale(.5)}.cevro-launcher--open .cevro-launcher__icon--close{opacity:1;transform:scale(1)}.cevro-launcher__badge{position:absolute;top:-4px;right:-4px;min-width:20px;height:20px;padding:0 6px;background-color:#ef4444;color:#fff;font-size:12px;font-weight:600;border-radius:10px;display:flex;align-items:center;justify-content:center;border:2px solid white}.cevro-chat-window{position:fixed;bottom:96px;right:20px;width:380px;height:600px;max-height:calc(100vh - 100px);background-color:var(--cevro-bg);border-radius:var(--cevro-radius);box-shadow:var(--cevro-shadow);display:flex;flex-direction:column;overflow:hidden;font-family:var(--cevro-font);z-index:2147483646;opacity:0;visibility:hidden;transform:translateY(20px) scale(.95);transition:opacity .25s ease,transform .25s ease,visibility .25s ease}.cevro-chat-window--visible{opacity:1;visibility:visible;transform:translateY(0) scale(1)}.cevro-chat-window--prechat{height:auto;max-height:calc(100vh - 100px);max-height:calc(100dvh - 100px)}@media (max-width: 480px){.cevro-chat-window{width:100%!important;height:100%!important;height:100dvh!important;max-height:100%!important;bottom:0!important;right:0!important;left:0!important;border-radius:0;padding-top:env(safe-area-inset-top);padding-bottom:env(safe-area-inset-bottom)}.cevro-chat-window__input,.cevro-prechat__input,.cevro-csat__feedback,.cevro-csat-inline__feedback{font-size:16px}.cevro-launcher--open{display:none}}@media (max-height: 500px){.cevro-chat-window__footer,.cevro-prechat__powered-by{display:none}}.cevro-chat-window__header{background:var(--cevro-header-bg);color:var(--cevro-header-text);padding:16px 20px;display:flex;align-items:center;gap:12px;flex-shrink:0;border-bottom:1px solid var(--cevro-border)}.cevro-chat-window__logo{width:40px;height:40px;border-radius:8px;overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center}.cevro-chat-window__logo svg{width:100%;height:100%}.cevro-chat-window__title-section{flex:1;min-width:0}.cevro-chat-window__title{margin:0;font-size:16px;font-weight:600}.cevro-chat-window__subtitle{margin:2px 0 0;font-size:12px;color:var(--cevro-text-secondary)}.cevro-chat-window__close{background:none;border:none;color:var(--cevro-text-secondary);cursor:pointer;padding:10px;margin:-10px -10px -10px auto;min-width:44px;min-height:44px;transition:color var(--cevro-transition);display:flex;align-items:center;justify-content:center}.cevro-chat-window__close:hover{color:var(--cevro-text)}.cevro-messages{flex:1;overflow:hidden;display:flex;flex-direction:column;background-color:var(--cevro-bg)}.cevro-messages--fade-in{animation:cevro-fade-in .3s ease}.cevro-messages__container{flex:1;overflow-y:auto;overflow-x:hidden;padding:16px;display:flex;flex-direction:column;gap:8px}.cevro-message{display:flex;align-items:flex-start;max-width:80%;animation:none}.cevro-message--animate{animation:cevro-message-in .3s ease}@keyframes cevro-message-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.cevro-message--inbound{align-self:flex-start}.cevro-message--outbound{align-self:flex-end}.cevro-message__avatar{width:28px;height:28px;min-width:28px;min-height:28px;border-radius:50%;overflow:hidden;flex-shrink:0;display:flex;align-items:center;justify-content:center;align-self:flex-end;margin-right:8px;background:var(--cevro-agent-msg-bg)}.cevro-message__avatar svg{width:18px;height:18px}.cevro-message__avatar-img{width:100%;height:100%;object-fit:cover}.cevro-message__avatar--human{background:#6366f1}.cevro-message__avatar-initials{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;color:#fff;line-height:1}.cevro-message__sender-name{font-size:11px;font-weight:600;color:var(--cevro-text-secondary);margin-bottom:2px;padding-left:2px}.cevro-message__content-wrapper{display:flex;flex-direction:column;gap:4px}.cevro-message--outbound .cevro-message__content-wrapper{align-items:flex-end}.cevro-message__bubble{padding:10px 14px;border-radius:var(--cevro-radius-sm);word-wrap:break-word;overflow-wrap:break-word;word-break:break-word;min-width:0}.cevro-message--inbound .cevro-message__bubble{background-color:var(--cevro-agent-msg-bg);color:var(--cevro-agent-msg-text);border-bottom-left-radius:4px}.cevro-message--outbound .cevro-message__bubble{background-color:var(--cevro-user-msg-bg);color:var(--cevro-user-msg-text);border:1px solid var(--cevro-border);box-shadow:var(--cevro-shadow-sm);border-bottom-right-radius:4px}.cevro-message__text{font-size:14px;line-height:1.5}.cevro-message--inbound .cevro-message__text a{color:inherit;text-decoration:underline;font-weight:500}.cevro-message--outbound .cevro-message__text a{color:var(--cevro-primary);text-decoration:underline}.cevro-message--inbound .cevro-message__text code{background-color:#fff3;padding:2px 4px;border-radius:4px;font-family:monospace;font-size:13px}.cevro-message--outbound .cevro-message__text code{background-color:#0000000d;padding:2px 4px;border-radius:4px;font-family:monospace;font-size:13px}.cevro-message__image-container{position:relative;display:inline-block;max-width:100%}.cevro-message__image{max-width:100%;max-height:300px;border-radius:var(--cevro-radius-sm);display:block}.cevro-file-progress-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:#00000080;border-radius:var(--cevro-radius-sm);display:flex;align-items:center;justify-content:center}.cevro-file-progress-overlay .cevro-file-progress{width:80%;text-align:center}.cevro-file-progress-overlay .cevro-file-progress__bar{background:#ffffff4d}.cevro-file-progress-overlay .cevro-file-progress__fill{background:#fff}.cevro-file-progress-overlay .cevro-file-progress__text{color:#fff;font-size:12px;margin-top:4px;display:block}.cevro-file-card{display:flex;align-items:center;gap:12px;padding:12px;background:#ffffff1a;border-radius:var(--cevro-radius-sm);min-width:200px;max-width:280px;transition:background var(--cevro-transition)}.cevro-message--outbound .cevro-file-card{background:#0000000d}.cevro-file-card:hover{background:#fff3}.cevro-message--outbound .cevro-file-card:hover{background:#00000014}.cevro-file-card__icon{flex-shrink:0;width:40px;height:40px;display:flex;align-items:center;justify-content:center}.cevro-file-card__icon svg{width:36px;height:36px}.cevro-file-card__info{flex:1;min-width:0;overflow:hidden}.cevro-file-card__name{font-size:13px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:inherit}.cevro-file-card__details{font-size:11px;opacity:.7;margin-top:2px}.cevro-file-card__progress{flex-shrink:0;width:60px}.cevro-file-progress{width:100%}.cevro-file-progress__bar{height:4px;background:#0000001a;border-radius:2px;overflow:hidden}.cevro-message--outbound .cevro-file-progress__bar{background:#0000001a}.cevro-message--inbound .cevro-file-progress__bar{background:#fff3}.cevro-file-progress__fill{height:100%;background:var(--cevro-primary);border-radius:2px;transition:width .2s ease}.cevro-message--inbound .cevro-file-progress__fill{background:#fff}.cevro-file-progress__text{font-size:10px;opacity:.7;margin-top:2px;display:block;text-align:right}.cevro-message__attachment{display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none;padding:8px 12px;background-color:#ffffff26;border-radius:var(--cevro-radius-sm);font-size:13px}.cevro-message--outbound .cevro-message__attachment{background-color:#0000000d}.cevro-message__attachment:hover{background-color:#ffffff40}.cevro-message--outbound .cevro-message__attachment:hover{background-color:#00000014}.cevro-message__meta{display:flex;align-items:center;gap:4px;font-size:11px;color:var(--cevro-text-secondary);padding:0 4px}.cevro-message__status{display:flex;align-items:center}.cevro-message__quick-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}.cevro-message__quick-action{padding:8px 16px;background-color:var(--cevro-bg);border:1px solid var(--cevro-border);color:var(--cevro-text);border-radius:20px;font-size:13px;cursor:pointer;transition:all var(--cevro-transition)}.cevro-message__quick-action:hover{background-color:var(--cevro-primary);border-color:var(--cevro-primary);color:#fff}.cevro-typing-indicator{display:flex;gap:8px;align-items:center;padding:8px 0}.cevro-typing-indicator__avatar{display:none}.cevro-typing-indicator__dots{display:flex;gap:4px;padding:12px 16px;background-color:var(--cevro-agent-msg-bg);border-radius:var(--cevro-radius-sm);border-bottom-left-radius:4px}.cevro-typing-indicator__dots span{width:6px;height:6px;background-color:var(--cevro-agent-msg-text);opacity:.85;border-radius:50%;animation:cevro-typing-bounce 1.4s ease-in-out infinite}.cevro-typing-indicator__dots span:nth-child(1){animation-delay:0s}.cevro-typing-indicator__dots span:nth-child(2){animation-delay:.2s}.cevro-typing-indicator__dots span:nth-child(3){animation-delay:.4s}@keyframes cevro-typing-bounce{0%,60%,to{transform:translateY(0)}30%{transform:translateY(-4px)}}.cevro-chat-window__input-wrapper{border-top:1px solid var(--cevro-border);background-color:var(--cevro-bg)}.cevro-chat-window__input-area{display:flex;align-items:center;gap:8px;padding:12px 16px}.cevro-chat-window__file-button{width:36px;height:36px;border:1px solid var(--cevro-file-btn-border);background-color:var(--cevro-file-btn-bg);color:var(--cevro-file-btn-icon);cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--cevro-transition);flex-shrink:0}.cevro-chat-window__file-button:hover{background-color:var(--cevro-bg-secondary);border-color:var(--cevro-primary);color:var(--cevro-primary)}.cevro-chat-window__file-button svg{display:block;width:20px;height:20px;color:var(--cevro-file-btn-icon)}.cevro-chat-window__file-button:hover svg{color:var(--cevro-primary)}.cevro-chat-window__file-input{display:none}.cevro-chat-window__input{flex:1;box-sizing:border-box;border:1px solid var(--cevro-border);border-radius:var(--cevro-radius-sm);padding:8px 14px;font-size:14px;font-family:var(--cevro-font);resize:none;outline:none;background-color:var(--cevro-bg-input);color:var(--cevro-text);max-height:100px;line-height:1.4;transition:border-color var(--cevro-transition);overflow-y:auto;scrollbar-width:none;-ms-overflow-style:none}.cevro-chat-window__input::-webkit-scrollbar{display:none}.cevro-chat-window__input::placeholder{color:var(--cevro-text-secondary)}.cevro-chat-window__input:focus{border-color:var(--cevro-primary);box-shadow:0 0 0 3px var(--cevro-focus-ring)}.cevro-chat-window__send-button{width:36px;height:36px;border:none;background-color:var(--cevro-send-btn-bg);color:var(--cevro-send-btn-icon);cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all var(--cevro-transition);flex-shrink:0}.cevro-chat-window__send-button:hover:not(:disabled){filter:brightness(.9);transform:scale(1.05)}.cevro-chat-window__send-button:disabled{opacity:.5;cursor:not-allowed;transform:scale(.9)}.cevro-chat-window__send-button svg{display:block;width:18px;height:18px;flex-shrink:0}.cevro-chat-window__upload-progress{display:flex;align-items:center;gap:12px;padding:8px 16px;background-color:var(--cevro-bg-secondary);border-bottom:1px solid var(--cevro-border)}.cevro-chat-window__upload-progress-bar{flex:1;height:4px;background-color:var(--cevro-border);border-radius:2px;overflow:hidden}.cevro-chat-window__upload-progress-fill{height:100%;background-color:var(--cevro-primary);border-radius:2px;transition:width .2s ease}.cevro-chat-window__upload-progress-text{font-size:12px;color:var(--cevro-text-secondary);white-space:nowrap}.cevro-chat-window__file-button:disabled{opacity:.5;cursor:not-allowed}.cevro-chat-window__footer{padding:8px 16px;text-align:center;font-size:11px;color:var(--cevro-text-secondary);background-color:var(--cevro-bg)}.cevro-chat-window__footer a{color:var(--cevro-primary);text-decoration:none}.cevro-chat-window__footer a:hover{text-decoration:underline}.cevro-messages__container::-webkit-scrollbar{width:6px}.cevro-messages__container::-webkit-scrollbar-track{background:transparent}.cevro-messages__container::-webkit-scrollbar-thumb{background-color:var(--cevro-border);border-radius:3px}.cevro-messages__container::-webkit-scrollbar-thumb:hover{background-color:var(--cevro-text-secondary)}.cevro-messages__closed-notice{flex:1;display:flex;flex-direction:column;justify-content:flex-end;padding:16px;text-align:center}.cevro-messages__closed-text{font-size:14px;color:var(--cevro-text-secondary);margin:0;line-height:1.5}.cevro-chat-window__closed-footer{padding:16px;background-color:var(--cevro-bg);border-top:1px solid var(--cevro-border);display:flex;flex-direction:column;gap:12px}.cevro-chat-window__new-chat-button{width:100%;background:var(--cevro-primary);color:#fff;border:none;padding:14px 24px;border-radius:var(--cevro-radius-sm);font-size:14px;font-weight:500;cursor:pointer;transition:background var(--cevro-transition),transform var(--cevro-transition);font-family:var(--cevro-font)}.cevro-chat-window__new-chat-button:hover{background:var(--cevro-primary-hover)}.cevro-chat-window__new-chat-button:active{transform:scale(.98)}.cevro-chat-window__powered-by{text-align:center;font-size:11px;color:var(--cevro-text-secondary)}@keyframes cevro-fade-in{0%{opacity:0}to{opacity:1}}.cevro-csat{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:24px;text-align:center;background-color:var(--cevro-bg);position:relative}.cevro-csat__skip{position:absolute;top:12px;right:12px;background:none;border:none;padding:8px;cursor:pointer;color:var(--cevro-text-secondary);border-radius:var(--cevro-radius-sm);transition:background var(--cevro-transition)}.cevro-csat__skip:hover{background:var(--cevro-bg-input)}.cevro-csat__icon{margin-bottom:16px}.cevro-csat__title{font-size:18px;font-weight:600;color:var(--cevro-text);margin:0 0 8px;font-family:var(--cevro-font)}.cevro-csat__subtitle{font-size:14px;color:var(--cevro-text-secondary);margin:0 0 24px;font-family:var(--cevro-font)}.cevro-csat__stars{display:flex;gap:8px;margin-bottom:20px}.cevro-csat__star{background:none;border:none;padding:4px;cursor:pointer;transition:transform var(--cevro-transition)}.cevro-csat__star svg{pointer-events:none}.cevro-csat__star:hover{transform:scale(1.15)}.cevro-csat__star--filled svg{fill:#fbbf24;stroke:#fbbf24}.cevro-csat__feedback{width:100%;padding:12px 14px;border:1px solid var(--cevro-border);border-radius:var(--cevro-radius-sm);font-size:14px;font-family:var(--cevro-font);resize:none;min-height:80px;max-height:120px;background-color:var(--cevro-bg-input);color:var(--cevro-text);margin-bottom:16px}.cevro-csat__feedback:focus{outline:none;border-color:var(--cevro-primary);box-shadow:0 0 0 3px var(--cevro-focus-ring)}.cevro-csat__feedback::placeholder{color:var(--cevro-text-placeholder)}.cevro-csat__submit{width:100%;background:var(--cevro-primary);color:#fff;border:none;padding:14px 24px;border-radius:var(--cevro-radius-sm);font-size:14px;font-weight:500;cursor:pointer;transition:background var(--cevro-transition),transform var(--cevro-transition),opacity var(--cevro-transition);font-family:var(--cevro-font)}.cevro-csat__submit:hover:not(:disabled){background:var(--cevro-primary-hover)}.cevro-csat__submit:active:not(:disabled){transform:scale(.98)}.cevro-csat__submit:disabled{opacity:.5;cursor:not-allowed}.cevro-csat__powered-by{margin-top:auto;padding-top:16px;font-size:11px;color:var(--cevro-text-secondary)}.cevro-csat__powered-by a{color:var(--cevro-text-secondary);text-decoration:none}.cevro-csat__powered-by a:hover{text-decoration:underline}.cevro-csat--thank-you{gap:16px}.cevro-csat--thank-you .cevro-csat__title{margin-bottom:16px}.cevro-csat-inline{display:flex;flex-direction:column;padding:16px 20px;background-color:var(--cevro-bg);border-top:1px solid var(--cevro-border)}.cevro-csat-inline__header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.cevro-csat-inline__title{font-size:14px;font-weight:500;color:var(--cevro-text);font-family:var(--cevro-font)}.cevro-csat-inline__skip{background:none;border:none;padding:4px 8px;cursor:pointer;color:var(--cevro-text-secondary);font-size:12px;font-family:var(--cevro-font);border-radius:var(--cevro-radius-sm);transition:background var(--cevro-transition),color var(--cevro-transition)}.cevro-csat-inline__skip:hover{background:var(--cevro-bg-input);color:var(--cevro-text)}.cevro-csat-inline__stars{display:flex;justify-content:center;gap:8px;margin-bottom:12px}.cevro-csat-inline__star{background:none;border:none;padding:4px;cursor:pointer;transition:transform var(--cevro-transition)}.cevro-csat-inline__star svg{pointer-events:none;width:28px;height:28px}.cevro-csat-inline__star:hover{transform:scale(1.15)}.cevro-csat-inline__star--filled svg{fill:#fbbf24;stroke:#fbbf24}.cevro-csat-inline__feedback{width:100%;margin-top:12px;padding:10px 12px;border:1px solid var(--cevro-border);border-radius:var(--cevro-radius-md);font-size:14px;font-family:var(--cevro-font);resize:none;box-sizing:border-box;background-color:var(--cevro-bg);color:var(--cevro-text);transition:border-color var(--cevro-transition)}.cevro-csat-inline__feedback:focus{outline:none;border-color:var(--cevro-primary)}.cevro-csat-inline__feedback::placeholder{color:var(--cevro-text-secondary)}.cevro-csat-inline__submit{width:100%;margin-top:8px;padding:10px 16px;background-color:var(--cevro-primary);color:#fff;border:none;border-radius:var(--cevro-radius-md);font-size:14px;font-weight:500;font-family:var(--cevro-font);cursor:pointer;transition:background var(--cevro-transition),opacity var(--cevro-transition)}.cevro-csat-inline__submit:hover:not(:disabled){background-color:var(--cevro-primary-hover)}.cevro-csat-inline__submit:disabled{opacity:.7;cursor:not-allowed}.cevro-csat-inline__powered-by{margin-top:12px;font-size:11px;color:var(--cevro-text-secondary);text-align:center;font-family:var(--cevro-font)}.cevro-csat-inline__powered-by a{color:var(--cevro-primary);text-decoration:none}.cevro-csat-inline__powered-by a:hover{text-decoration:underline}.cevro-csat-inline--thank-you{align-items:center;text-align:center}.cevro-csat-inline__thank-you-row{display:flex;align-items:center;gap:8px;margin-bottom:12px}.cevro-csat-inline__check{display:flex;align-items:center}.cevro-csat-inline__message{font-size:14px;font-weight:500;color:var(--cevro-text);font-family:var(--cevro-font)}.cevro-csat-inline__new-chat{width:100%;padding:10px 16px;background-color:var(--cevro-primary);color:#fff;border:none;border-radius:var(--cevro-radius-md);font-size:14px;font-weight:500;font-family:var(--cevro-font);cursor:pointer;margin-bottom:12px;transition:background var(--cevro-transition)}.cevro-csat-inline__new-chat:hover{background-color:var(--cevro-primary-hover)}.cevro-prechat{flex:1;display:flex;flex-direction:column;padding:32px 24px 24px;background-color:var(--cevro-bg);animation:cevro-fade-in .25s ease}.cevro-prechat__title{font-size:18px;font-weight:600;color:var(--cevro-text);margin:0 0 8px;font-family:var(--cevro-font)}.cevro-prechat__subtitle{font-size:14px;color:var(--cevro-text-secondary);margin:0 0 24px;font-family:var(--cevro-font)}.cevro-prechat__form{display:flex;flex-direction:column;gap:16px}.cevro-prechat__field{display:flex;flex-direction:column;gap:6px}.cevro-prechat__label{font-size:13px;font-weight:500;color:var(--cevro-text);font-family:var(--cevro-font)}.cevro-prechat__input{width:100%;padding:12px 14px;border:1px solid var(--cevro-border);border-radius:var(--cevro-radius-sm);font-size:14px;font-family:var(--cevro-font);background-color:var(--cevro-bg);color:var(--cevro-text);transition:border-color var(--cevro-transition),box-shadow var(--cevro-transition);box-sizing:border-box}.cevro-prechat__input:focus{outline:none;border-color:var(--cevro-primary);box-shadow:0 0 0 3px var(--cevro-focus-ring)}.cevro-prechat__input::placeholder{color:var(--cevro-text-secondary)}.cevro-prechat__input--error{border-color:#ef4444}.cevro-prechat__input--error:focus{border-color:#ef4444;box-shadow:0 0 0 3px #ef444426}.cevro-prechat__error{font-size:12px;color:#ef4444;min-height:16px}.cevro-prechat__submit{width:100%;background:var(--cevro-primary);color:#fff;border:none;padding:14px 24px;border-radius:var(--cevro-radius-sm);font-size:14px;font-weight:500;cursor:pointer;transition:background var(--cevro-transition),transform var(--cevro-transition);font-family:var(--cevro-font);margin-top:8px}.cevro-prechat__submit:hover{background:var(--cevro-primary-hover)}.cevro-prechat__submit:active{transform:scale(.98)}.cevro-prechat__powered-by{margin-top:auto;padding-top:24px;text-align:center;font-size:11px;color:var(--cevro-text-secondary)}.cevro-prechat__powered-by a{color:var(--cevro-text-secondary);text-decoration:none}.cevro-prechat__powered-by a:hover{text-decoration:underline}.cevro-chat-window__history-button{background:none;border:none;color:var(--cevro-text-secondary);cursor:pointer;padding:10px;margin:-10px -4px -10px -10px;min-width:44px;min-height:44px;transition:color var(--cevro-transition);display:flex;align-items:center;justify-content:center}.cevro-chat-window__history-button:hover{color:var(--cevro-text)}.cevro-conversation-list,.cevro-past-conversation{position:fixed;bottom:96px;right:20px;width:380px;height:600px;max-height:calc(100vh - 100px);background-color:var(--cevro-bg);border-radius:var(--cevro-radius);box-shadow:var(--cevro-shadow);display:flex;flex-direction:column;overflow:hidden;font-family:var(--cevro-font);z-index:2147483646}@media (max-width: 480px){.cevro-conversation-list,.cevro-past-conversation{width:100%!important;height:100%!important;height:100dvh!important;max-height:100%!important;bottom:0!important;right:0!important;left:0!important;border-radius:0;padding-top:env(safe-area-inset-top);padding-bottom:env(safe-area-inset-bottom)}}.cevro-conversation-list{animation:cevro-fade-in .2s ease}.cevro-conversation-list__header{background:var(--cevro-header-bg);color:var(--cevro-header-text);padding:16px 20px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;border-bottom:1px solid var(--cevro-border)}.cevro-conversation-list__title{margin:0;font-size:16px;font-weight:600}.cevro-conversation-list__close{background:none;border:none;color:var(--cevro-text-secondary);cursor:pointer;padding:10px;margin:-10px 0;min-width:44px;min-height:44px;transition:color var(--cevro-transition);display:flex;align-items:center;justify-content:center}.cevro-conversation-list__close:hover{color:var(--cevro-text)}.cevro-conversation-list__items{flex:1;overflow-y:auto;padding:0;display:flex;flex-direction:column;gap:0}.cevro-conversation-list__items::-webkit-scrollbar{width:6px}.cevro-conversation-list__items::-webkit-scrollbar-track{background:transparent}.cevro-conversation-list__items::-webkit-scrollbar-thumb{background-color:var(--cevro-border);border-radius:3px}.cevro-conversation-list__loading{display:flex;align-items:center;justify-content:center;padding:40px 0;color:var(--cevro-text-secondary);font-size:14px}.cevro-conversation-list__load-more{display:block;width:100%;padding:10px;border:none;border-radius:8px;background:transparent;color:var(--cevro-primary, #6b47ed);font-size:13px;font-weight:500;cursor:pointer;transition:background .15s}.cevro-conversation-list__load-more:hover{background:var(--cevro-bg-hover, rgba(0, 0, 0, .04))}.cevro-conversation-list__load-more:disabled{color:var(--cevro-text-secondary);cursor:default}.cevro-conversation-list__empty{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:40px 20px;text-align:center}.cevro-conversation-list__empty-title{margin:0 0 8px;font-size:15px;font-weight:500;color:var(--cevro-text)}.cevro-conversation-list__empty-subtitle{margin:0;font-size:13px;color:var(--cevro-text-secondary)}.cevro-conversation-list__new-conversation,.cevro-past-conversation__new-conversation{display:block;width:calc(100% - 32px);margin:12px 16px;padding:14px 20px;border:none;border-radius:25px;background:var(--cevro-primary, #6b47ed);color:#fff;font-size:15px;font-weight:600;font-family:var(--cevro-font);cursor:pointer;flex-shrink:0;transition:opacity .15s}.cevro-conversation-list__new-conversation:hover,.cevro-past-conversation__new-conversation:hover{opacity:.9}.cevro-conversation-list__footer,.cevro-past-conversation__footer{padding:8px 16px;text-align:center;font-size:11px;color:var(--cevro-text-secondary);background-color:var(--cevro-bg);flex-shrink:0}.cevro-conversation-list__footer a,.cevro-past-conversation__footer a{color:var(--cevro-primary);text-decoration:none}.cevro-conversation-list__footer a:hover,.cevro-past-conversation__footer a:hover{text-decoration:underline}.cevro-conversation-card{display:flex;align-items:center;gap:12px;padding:14px 20px;background-color:var(--cevro-bg);border:none;border-bottom:1px solid var(--cevro-border);border-radius:0;cursor:pointer;transition:background var(--cevro-transition)}.cevro-conversation-card:hover{background-color:var(--cevro-bg-secondary)}.cevro-conversation-card--active{background-color:var(--cevro-bg)}.cevro-conversation-card__content{flex:1;min-width:0}.cevro-conversation-card__title-row{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px}.cevro-conversation-card__title{font-size:14px;font-weight:400;color:var(--cevro-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;min-width:0}.cevro-conversation-card--active .cevro-conversation-card__title{font-weight:600}.cevro-conversation-card--active .cevro-conversation-card__preview{color:var(--cevro-text)}.cevro-conversation-card__date{font-size:12px;color:var(--cevro-text-secondary);white-space:nowrap;flex-shrink:0}.cevro-conversation-card__preview-row{display:flex;align-items:center;gap:8px;margin-top:2px}.cevro-conversation-card__preview-row .cevro-conversation-card__preview{margin-top:0;flex:1;min-width:0}.cevro-conversation-card__unread{min-width:22px;height:22px;padding:0 6px;border-radius:11px;background:var(--cevro-primary, #6b47ed);color:#fff;font-size:12px;font-weight:600;display:flex;align-items:center;justify-content:center;flex-shrink:0;box-sizing:border-box}.cevro-conversation-card--unread .cevro-conversation-card__preview{color:var(--cevro-text);font-weight:600}.cevro-conversation-card__meta{font-size:12px;color:var(--cevro-text-secondary)}.cevro-conversation-card__avatar{width:36px;height:36px;min-width:36px;border-radius:50%;background:var(--cevro-primary);display:flex;align-items:center;justify-content:center;flex-shrink:0}.cevro-conversation-card__avatar-img{width:100%;height:100%;border-radius:50%;object-fit:cover}.cevro-conversation-card__avatar-initials{font-size:14px;font-weight:600;color:#fff;line-height:1}.cevro-conversation-card__preview{font-size:13px;color:var(--cevro-text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px}.cevro-conversation-card__arrow{color:var(--cevro-text-secondary);flex-shrink:0;display:flex;align-items:center}.cevro-past-conversation__header{background:var(--cevro-header-bg);color:var(--cevro-header-text);padding:12px 16px;display:flex;align-items:center;gap:8px;flex-shrink:0;border-bottom:1px solid var(--cevro-border)}.cevro-past-conversation__back{background:none;border:none;color:var(--cevro-text-secondary);cursor:pointer;padding:8px;margin:-8px;min-width:40px;min-height:40px;transition:color var(--cevro-transition);display:flex;align-items:center;justify-content:center}.cevro-past-conversation__back:hover{color:var(--cevro-text)}.cevro-past-conversation__avatar{width:36px;height:36px;min-width:36px;border-radius:8px;overflow:hidden;flex:0 0 auto}.cevro-past-conversation__avatar-img{width:100%;height:100%;object-fit:cover}.cevro-past-conversation__avatar-icon{width:100%;height:100%;padding:8px;color:var(--cevro-text-secondary);box-sizing:border-box}.cevro-past-conversation__title{flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;color:var(--cevro-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cevro-past-conversation__close{background:none;border:none;color:var(--cevro-text-secondary);cursor:pointer;padding:10px;margin:-10px -10px -10px auto;min-width:44px;min-height:44px;transition:color var(--cevro-transition);display:flex;align-items:center;justify-content:center}.cevro-past-conversation__close:hover{color:var(--cevro-text)}';let i=class{constructor(){t(this,"listeners",new Map),t(this,"onceHandlers",new Map)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const s=i=>{this.onceHandlers.delete(s),this.off(e,s),t(i)};return this.onceHandlers.set(s,t),this.on(e,s)}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),this.onceHandlers.delete(t))}emit(e,t){const s=this.listeners.get(e);s&&s.forEach(e=>{try{e(t)}catch{}})}removeAllListeners(e){if(e){const t=this.listeners.get(e);t&&t.forEach(e=>{this.onceHandlers.delete(e)}),this.listeners.delete(e)}else this.listeners.clear(),this.onceHandlers.clear()}listenerCount(e){var t;return(null==(t=this.listeners.get(e))?void 0:t.size)||0}};const n="cevro_visitor_token",o="cevro_session",r="identity";function a(e,t){try{document.cookie=`${e}=${encodeURIComponent(t)};max-age=23328000;path=/;SameSite=Lax`}catch{}}function c(){return new Promise((e,t)=>{const s=indexedDB.open("cevro_sdk",1);s.onupgradeneeded=()=>{const e=s.result;e.objectStoreNames.contains(r)||e.createObjectStore(r)},s.onsuccess=()=>e(s.result),s.onerror=()=>t(s.error)})}function l(){try{const e=localStorage.getItem(n);if(e)return e}catch{}const e=function(e){try{const t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch{return null}}(n);if(e){try{localStorage.setItem(n,e)}catch{}return e}return null}async function h(){const e=l();if(e)return e;try{const e=await(t=n,c().then(e=>new Promise(s=>{const i=e.transaction(r,"readonly"),n=i.objectStore(r).get(t);n.onsuccess=()=>s(n.result??null),n.onerror=()=>s(null),i.oncomplete=()=>e.close(),i.onerror=()=>e.close()})).catch(()=>null));if(e){try{localStorage.setItem(n,e)}catch{}return a(n,e),e}}catch{}var t;return null}function d(e){try{localStorage.setItem(n,e)}catch{}var t,s;a(n,e),t=n,s=e,c().then(e=>{const i=e.transaction(r,"readwrite");i.objectStore(r).put(s,t),i.oncomplete=()=>e.close(),i.onerror=()=>e.close()}).catch(()=>{})}function u(){return function(){const e=l();return e?function(e){if(!e)return null;const t=e.lastIndexOf(".");return t<=0?null:e.substring(0,t)}(e):null}()}const p="cevro_active_player";function v(e){const t=function(e){let t=0;for(let s=0;s<e.length;s++)t=(t<<5)-t+e.charCodeAt(s)|0;return Math.abs(t).toString(36)}(e);try{const e=localStorage.getItem(p);return localStorage.setItem(p,t),!!e&&e!==t}catch{return!1}}function g(){try{localStorage.removeItem(p)}catch{}}function m(){try{localStorage.removeItem(o)}catch{}}function f(){try{localStorage.removeItem(n)}catch{}var e;!function(e){try{document.cookie=`${e}=;max-age=0;path=/;SameSite=Lax`}catch{}}(n),e=n,c().then(t=>{const s=t.transaction(r,"readwrite");s.objectStore(r).delete(e),s.oncomplete=()=>t.close(),s.onerror=()=>t.close()}).catch(()=>{})}const _=new Set(["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","text/plain","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","audio/mpeg","audio/wav","audio/ogg","video/mp4","video/webm","application/zip","application/x-rar-compressed"]),b=new Set([".exe",".dll",".bat",".cmd",".sh",".bash",".ps1",".psm1",".psd1",".vbs",".vbe",".js",".jse",".ws",".wsf",".wsc",".wsh",".msi",".msp",".mst",".scr",".pif",".com",".hta",".cpl",".msc",".jar",".class",".php",".php3",".php4",".php5",".phtml",".asp",".aspx",".ashx",".asmx",".jsp",".jspx",".py",".pyc",".pyw",".rb",".rbw",".pl",".pm",".cgi",".htaccess",".htpasswd"]),w={maxSizeBytes:26214400,minSizeBytes:1,maxFilenameLength:255};function y(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?"":e.substring(t).toLowerCase()}function x(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(1))+" "+["B","KB","MB","GB"][t]}class C{constructor(e=5,s=6e4){t(this,"uploadTimestamps",[]),t(this,"maxUploads"),t(this,"windowMs"),this.maxUploads=e,this.windowMs=s}canUpload(){const e=Date.now();return this.uploadTimestamps=this.uploadTimestamps.filter(t=>e-t<this.windowMs),this.uploadTimestamps.length<this.maxUploads}recordUpload(){this.uploadTimestamps.push(Date.now())}getRemainingUploads(){const e=Date.now();return this.uploadTimestamps=this.uploadTimestamps.filter(t=>e-t<this.windowMs),Math.max(0,this.maxUploads-this.uploadTimestamps.length)}getTimeUntilNextUpload(){if(this.canUpload())return 0;const e=Math.min(...this.uploadTimestamps);return Math.max(0,this.windowMs-(Date.now()-e))}reset(){this.uploadTimestamps=[]}}class k{constructor(e){t(this,"config"),t(this,"accessToken",null),t(this,"contactId",null),t(this,"currentTicketId",null),t(this,"visitorToken",null),t(this,"currentAgent",null),t(this,"uploadRateLimiter"),t(this,"visitorId",null),this.config=e,this.uploadRateLimiter=new C}updateConfig(e){this.config=e}setVisitorToken(e){this.visitorToken=e}getVisitorToken(){return this.visitorToken}setAccessToken(e){this.accessToken=e}getContactId(){return this.contactId}getCurrentTicketId(){return this.currentTicketId}setCurrentTicketId(e){this.currentTicketId=e}getCurrentAgent(){return this.currentAgent}async request(e,t={}){var s,i;const n=`${this.config.apiBase}${e}`,o={"Content-Type":"application/json",...t.headers||{}};this.config.workspaceId&&(o["X-Workspace-Id"]=this.config.workspaceId),this.config.brandId&&(o["X-Brand-Id"]=this.config.brandId),this.visitorToken&&(o["X-Visitor-Token"]=this.visitorToken),(null==(s=this.config.player)?void 0:s.playerId)&&(o["X-Player-Id"]=this.config.player.playerId),(null==(i=this.config.player)?void 0:i.playerHash)&&(o["X-Player-Hash"]=this.config.player.playerHash),this.visitorId&&(o["X-Visitor-Id"]=this.visitorId),this.accessToken&&(o.Authorization=`Bearer ${this.accessToken}`);const r=await fetch(n,{...t,headers:o});if(!r.ok){const e=await r.json().catch(()=>({message:r.statusText}));throw new Error(e.message||`Request failed: ${r.status}`)}return r.json()}async initSession(e,t,s){var i,n,o,r,a,c,l,h;const d={visitorId:e,session:function(){const e={};if("undefined"==typeof window||"undefined"==typeof navigator)return e;try{e.userAgent=navigator.userAgent,e.language=navigator.language,e.platform=navigator.platform,e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,e.currentPage=window.location.href,e.pageTitle=document.title,e.referrer=document.referrer,e.screenWidth=window.screen.width,e.screenHeight=window.screen.height,e.viewportWidth=window.innerWidth,e.viewportHeight=window.innerHeight,e.devicePixelRatio=window.devicePixelRatio;const t=new URLSearchParams(window.location.search);e.utmSource=t.get("utm_source")||void 0,e.utmMedium=t.get("utm_medium")||void 0,e.utmCampaign=t.get("utm_campaign")||void 0,e.utmContent=t.get("utm_content")||void 0,e.utmTerm=t.get("utm_term")||void 0,e.cookiesEnabled=navigator.cookieEnabled,e.touchSupport="ontouchstart"in window||navigator.maxTouchPoints>0,e.online=navigator.onLine;const s=navigator.connection;s&&(e.connectionType=s.effectiveType)}catch(t){}return e}(),brandId:this.config.brandId,firstName:(null==t?void 0:t.firstName)||(null==(i=this.config.player)?void 0:i.firstName),lastName:null==(n=this.config.player)?void 0:n.lastName,email:(null==t?void 0:t.email)||(null==(o=this.config.player)?void 0:o.email)||void 0,phone:null==(r=this.config.player)?void 0:r.phone,customAttributes:null==(a=this.config.player)?void 0:a.customAttributes,forceNewTicket:null==s?void 0:s.forceNewTicket};(null==(c=this.config.player)?void 0:c.playerId)&&(d.playerId=this.config.player.playerId,d.playerHash=this.config.player.playerHash);const u=await this.request("/api/v1/sdk/session",{method:"POST",body:JSON.stringify(d),headers:e?{"X-Visitor-Id":e}:void 0});return u.requireContactInfo&&(null==(l=u.missingFields)?void 0:l.length)>0?{sessionId:"",contactId:"",ticketId:"",visitorId:u.visitorId||"",isNewSession:!1,isNewTicket:!1,requireContactInfo:u.requireContactInfo,missingFields:u.missingFields}:(this.contactId=u.contactId,this.currentTicketId=u.ticketId,u.agent&&(this.currentAgent=u.agent),{sessionId:u.sessionId,contactId:u.contactId,ticketId:u.ticketId,visitorId:u.visitorId,isNewSession:u.isNewSession,isNewTicket:u.isNewTicket,ticketClosed:u.ticketClosed,ticketClosedReason:u.ticketClosedReason,agent:u.agent,typingConfig:u.typingConfig,messages:null==(h=u.messages)?void 0:h.map(e=>this.normalizeMessage(e)),hasMoreMessages:u.hasMoreMessages,cursor:u.cursor,locale:u.locale,requireContactInfo:u.requireContactInfo})}async sendMessage(e,t){if(!this.contactId||!this.currentTicketId)throw new Error("No active session. Call initSession first.");const s={contactId:this.contactId,ticketId:this.currentTicketId,message:e,assetId:t},i=await this.request("/api/v1/sdk/send",{method:"POST",body:JSON.stringify(s)});return this.normalizeMessage(i.message||i)}async getMessages(e){const t=e||this.currentTicketId;if(!t)throw new Error("No ticket ID available");const s=await this.request(`/api/v1/messages/my-tickets?supportTicketId=${t}`);return(s.results||s.messages||s||[]).map(e=>this.normalizeMessage(e))}async getMyTickets(){const e=await this.request("/api/v1/messages/my-tickets");return(e.results||e.tickets||e||[]).map(e=>this.normalizeConversation(e))}async uploadFile(e,t){if(!this.uploadRateLimiter.canUpload()){const e=Math.ceil(this.uploadRateLimiter.getTimeUntilNextUpload()/1e3);throw new Error(`Too many uploads. Please wait ${e} seconds before uploading again.`)}const s=function(e,t={}){const{maxSizeBytes:s=w.maxSizeBytes,minSizeBytes:i=w.minSizeBytes,allowedMimeTypes:n=_,blockedExtensions:o=b,maxFilenameLength:r=w.maxFilenameLength}=t;if(0===e.size)return{valid:!1,error:"File is empty",errorCode:"EMPTY_FILE"};if(e.size<i)return{valid:!1,error:`File is too small. Minimum size is ${x(i)}`,errorCode:"FILE_TOO_SMALL"};if(e.size>s)return{valid:!1,error:`File is too large. Maximum size is ${x(s)}`,errorCode:"FILE_TOO_LARGE"};if(e.name.length>r)return{valid:!1,error:`Filename is too long. Maximum length is ${r} characters`,errorCode:"FILENAME_TOO_LONG"};const a=y(e.name);if(a&&o.has(a))return{valid:!1,error:`File type "${a}" is not allowed for security reasons`,errorCode:"BLOCKED_EXTENSION"};const c=e.type||"application/octet-stream";return n.has(c)||"application/octet-stream"===c&&a&&!o.has(a)?{valid:!0}:{valid:!1,error:`File type "${c}" is not allowed. Allowed types: images, documents, audio, video`,errorCode:"INVALID_TYPE"}}(e);if(!s.valid)throw new Error(s.error||"File validation failed");const i=function(e){let t=e.replace(/^.*[\\/]/,"");if(t=t.replace(/[\x00-\x1f\x7f]/g,""),t=t.replace(/[<>:"/\\|?*]/g,"_"),t=t.replace(/^[\s.]+|[\s.]+$/g,""),t||(t="unnamed_file"),t.length>w.maxFilenameLength){const e=y(t),s=t.slice(0,-e.length||void 0),i=w.maxFilenameLength-e.length;t=s.slice(0,i)+e}return t}(e.name);this.uploadRateLimiter.recordUpload();const{uploadUrl:n,assetId:o}=await this.request("/api/v1/sdk/upload-url",{method:"POST",body:JSON.stringify({filename:i,contentType:e.type||"application/octet-stream",size:e.size})});return await this.uploadToS3(n,e,t),o}async uploadToS3(e,t,s){return new Promise((i,n)=>{const o=new XMLHttpRequest;o.upload.addEventListener("progress",e=>{if(e.lengthComputable&&s){const t=Math.round(e.loaded/e.total*100);s(t)}}),o.addEventListener("load",()=>{o.status>=200&&o.status<300?i():n(new Error(`Upload failed with status ${o.status}`))}),o.addEventListener("error",()=>{n(new Error("Upload failed"))}),o.open("PUT",e),o.setRequestHeader("Content-Type",t.type||"application/octet-stream"),o.send(t)})}normalizeMessage(e){return{id:e.objectId||e.id,body:e.body||"",inbound:e.inbound||!1,outbound:e.outbound||!e.inbound,createdAt:e.createdAt||(new Date).toISOString(),type:e.type||"text",mediaUrl:e.mediaUrl,mediaType:e.mediaType,status:e.status||"sent",richContent:e.richContent}}normalizeConversation(e){return{id:e.objectId||e.id,conversationId:e.conversationId||e.objectId||e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,status:e.resolved?"resolved":e.escalated?"escalated":"open",unreadCount:e.unreadCount||0,lastMessage:e.latestMessage?this.normalizeMessage(e.latestMessage):void 0}}async getConnectionToken(e){var t;const s={workspaceId:this.config.workspaceId,brandId:this.config.brandId};e&&(s.visitorToken=e),(null==(t=this.config.player)?void 0:t.playerId)&&(s.playerId=this.config.player.playerId,s.playerHash=this.config.player.playerHash,s.email=this.config.player.email||void 0,s.firstName=this.config.player.firstName);return await this.request("/api/v1/sdk/token",{method:"POST",body:JSON.stringify(s)})}async refreshConnectionToken(e){return this.getConnectionToken(e)}async submitCSAT(e,t,s,i){await this.request("/api/v1/sdk/csat",{method:"POST",body:JSON.stringify({ticketId:e,contactId:t,rating:s,feedback:i})})}async getConversations(e){const t=new URLSearchParams;e&&t.set("cursor",e);const s=t.toString()?`/api/v1/sdk/conversations?${t.toString()}`:"/api/v1/sdk/conversations",i=await this.request(s);return{conversations:i.conversations||[],hasMore:i.hasMore||!1,cursor:i.cursor}}async getConversationMessages(e,t){const s=new URLSearchParams;t&&s.set("cursor",t);const i=`/api/v1/sdk/conversations/${e}/messages`,n=s.toString()?`${i}?${s.toString()}`:i,o=await this.request(n);return{messages:(o.messages||[]).map(e=>this.normalizeMessage(e)),hasMore:o.hasMore||!1,cursor:o.cursor}}setVisitorId(e){this.visitorId=e}async getWidgetConfig(){try{return await this.request("/api/v1/sdk/widget-config",{method:"GET"})}catch(e){return{}}}clear(){this.accessToken=null,this.contactId=null,this.currentTicketId=null,this.visitorToken=null,this.visitorId=null,this.currentAgent=null}}function S(e,t,s,i){return new(s||(s=Promise))(function(t,n){function o(e){try{a(i.next(e))}catch(t){n(t)}}function r(e){try{a(i.throw(e))}catch(t){n(t)}}function a(e){var i;e.done?t(e.value):(i=e.value,i instanceof s?i:new s(function(e){e(i)})).then(o,r)}a((i=i.apply(e,[])).next())})}function T(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var I,E={exports:{}},L="object"==typeof Reflect?Reflect:null,M=L&&"function"==typeof L.apply?L.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)};I=L&&"function"==typeof L.ownKeys?L.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var N=Number.isNaN||function(e){return e!=e};function P(){P.init.call(this)}E.exports=P,E.exports.once=function(e,t){return new Promise(function(s,i){function n(s){e.removeListener(t,o),i(s)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",n),s([].slice.call(arguments))}D(e,t,o,{once:!0}),"error"!==t&&function(e,t,s){"function"==typeof e.on&&D(e,"error",t,s)}(e,n,{once:!0})})},P.EventEmitter=P,P.prototype._events=void 0,P.prototype._eventsCount=0,P.prototype._maxListeners=void 0;var A=10;function B(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function z(e){return void 0===e._maxListeners?P.defaultMaxListeners:e._maxListeners}function R(e,t,s,i){var n,o,r,a;if(B(s),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),o=e._events),r=o[t]),void 0===r)r=o[t]=s,++e._eventsCount;else if("function"==typeof r?r=o[t]=i?[s,r]:[r,s]:i?r.unshift(s):r.push(s),(n=z(e))>0&&r.length>n&&!r.warned){r.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=r.length,a=c,console&&console.warn&&console.warn(a)}return e}function H(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function U(e,t,s){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:s},n=H.bind(i);return n.listener=s,i.wrapFn=n,n}function F(e,t,s){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?s?[n.listener||n]:[n]:s?function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(n):O(n,n.length)}function j(e){var t=this._events;if(void 0!==t){var s=t[e];if("function"==typeof s)return 1;if(void 0!==s)return s.length}return 0}function O(e,t){for(var s=new Array(t),i=0;i<t;++i)s[i]=e[i];return s}function D(e,t,s,i){if("function"==typeof e.on)i.once?e.once(t,s):e.on(t,s);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function n(o){i.once&&e.removeEventListener(t,n),s(o)})}}Object.defineProperty(P,"defaultMaxListeners",{enumerable:!0,get:function(){return A},set:function(e){if("number"!=typeof e||e<0||N(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");A=e}}),P.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},P.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||N(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},P.prototype.getMaxListeners=function(){return z(this)},P.prototype.emit=function(e){for(var t=[],s=1;s<arguments.length;s++)t.push(arguments[s]);var i="error"===e,n=this._events;if(void 0!==n)i=i&&void 0===n.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var r=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw r.context=o,r}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)M(a,this,t);else{var c=a.length,l=O(a,c);for(s=0;s<c;++s)M(l[s],this,t)}return!0},P.prototype.addListener=function(e,t){return R(this,e,t,!1)},P.prototype.on=P.prototype.addListener,P.prototype.prependListener=function(e,t){return R(this,e,t,!0)},P.prototype.once=function(e,t){return B(t),this.on(e,U(this,e,t)),this},P.prototype.prependOnceListener=function(e,t){return B(t),this.prependListener(e,U(this,e,t)),this},P.prototype.removeListener=function(e,t){var s,i,n,o,r;if(B(t),void 0===(i=this._events))return this;if(void 0===(s=i[e]))return this;if(s===t||s.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(n=-1,o=s.length-1;o>=0;o--)if(s[o]===t||s[o].listener===t){r=s[o].listener,n=o;break}if(n<0)return this;0===n?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,n),1===s.length&&(i[e]=s[0]),void 0!==i.removeListener&&this.emit("removeListener",e,r||t)}return this},P.prototype.off=P.prototype.removeListener,P.prototype.removeAllListeners=function(e){var t,s,i;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var n,o=Object.keys(s);for(i=0;i<o.length;++i)"removeListener"!==(n=o[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},P.prototype.listeners=function(e){return F(this,e,!0)},P.prototype.rawListeners=function(e){return F(this,e,!1)},P.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):j.call(e,t)},P.prototype.listenerCount=j,P.prototype.eventNames=function(){return this._eventsCount>0?I(this._events):[]};var V,W,$,q,Z,J,G,Y,X,Q,K,ee,te,se,ie,ne,oe=T(E.exports);function re(e){return null!=e&&"function"==typeof e}function ae(e,t,s){e>31&&(e=31);const i=function(e,t){return Math.floor(Math.random()*(t-e+1)+e)}(0,Math.min(s,t*Math.pow(2,e)));return Math.min(s,t+i)}function ce(e){return Math.min(1e3*e,2147483647)}(W=V||(V={}))[W.timeout=1]="timeout",W[W.transportClosed=2]="transportClosed",W[W.clientDisconnected=3]="clientDisconnected",W[W.clientClosed=4]="clientClosed",W[W.clientConnectToken=5]="clientConnectToken",W[W.clientRefreshToken=6]="clientRefreshToken",W[W.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",W[W.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",W[W.subscriptionRefreshToken=9]="subscriptionRefreshToken",W[W.transportWriteError=10]="transportWriteError",W[W.connectionClosed=11]="connectionClosed",W[W.badConfiguration=12]="badConfiguration",(q=$||($={}))[q.connectCalled=0]="connectCalled",q[q.transportClosed=1]="transportClosed",q[q.noPing=2]="noPing",q[q.subscribeTimeout=3]="subscribeTimeout",q[q.unsubscribeError=4]="unsubscribeError",(J=Z||(Z={}))[J.disconnectCalled=0]="disconnectCalled",J[J.unauthorized=1]="unauthorized",J[J.badProtocol=2]="badProtocol",J[J.messageSizeLimit=3]="messageSizeLimit",(Y=G||(G={}))[Y.subscribeCalled=0]="subscribeCalled",Y[Y.transportClosed=1]="transportClosed",(Q=X||(X={}))[Q.unsubscribeCalled=0]="unsubscribeCalled",Q[Q.unauthorized=1]="unauthorized",Q[Q.clientClosed=2]="clientClosed",(ee=K||(K={}))[ee.channelCompaction=1]="channelCompaction",(se=te||(te={})).Disconnected="disconnected",se.Connecting="connecting",se.Connected="connected",(ne=ie||(ie={})).Unsubscribed="unsubscribed",ne.Subscribing="subscribing",ne.Subscribed="subscribed";class le extends oe{constructor(e,t,s){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this.channel=t,this.state=ie.Unsubscribed,this._centrifuge=e,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._prevValue=null,this._unsubPromise=Promise.resolve(),this._setOptions(s),this._centrifuge._debugEnabled?(this.on("state",e=>{this._debug("subscription state",t,e.oldState,"->",e.newState)}),this.on("error",e=>{this._debug("subscription error",t,e)})):this.on("error",function(){Function.prototype()})}ready(e){return this.state===ie.Unsubscribed?Promise.reject({code:V.subscriptionUnsubscribed,message:this.state}):this.state===ie.Subscribed?Promise.resolve():new Promise((t,s)=>{const i={resolve:t,reject:s};e&&(i.timeout=setTimeout(function(){s({code:V.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(G.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(X.unsubscribeCalled,"unsubscribe called",!0)}publish(e){return S(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.publish(this.channel,e)})}presence(){return S(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return S(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)})}history(e){return S(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,e)})}setTagsFilter(e){if(e&&this._delta)throw new Error("cannot use delta and tagsFilter together");this._tagsFilter=e}setData(e){this._data=e}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:V.subscriptionUnsubscribed,message:this.state}):new Promise((e,t)=>{const s=this._centrifuge._config.timeout,i=setTimeout(()=>{t({code:V.timeout,message:"timeout"})},s);this._promises[this._nextPromiseId()]={timeout:i,resolve:e,reject:t}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return!0===this._recover}_isUnsubscribed(){return this.state===ie.Unsubscribed}_isSubscribing(){return this.state===ie.Subscribing}_isSubscribed(){return this.state===ie.Subscribed}_setState(e){if(this.state!==e){const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t,channel:this.channel}),!0}return!1}_usesToken(){return""!==this._token||null!==this._getToken}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout()}_setSubscribed(e){if(!this._isSubscribing())return;this._clearSubscribingState(),e.id&&(this._id=e.id),e.recoverable&&(this._recover=!0,this._offset=e.offset||0,this._epoch=e.epoch||""),e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,this._setState(ie.Subscribed);const t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit("subscribed",t),this._resolvePromises();const s=e.publications;if(s&&s.length>0)for(const i in s)s.hasOwnProperty(i)&&this._handlePublication(s[i]);!0===e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ce(e.ttl)))}_setSubscribing(e,t){return S(this,0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState(ie.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(yield this._unsubPromise),this._isSubscribing()&&this._subscribe())})}_subscribe(){return this._debug("subscribing on",this.channel),this._isTransportOpen()?this._inflight?null:(this._inflight=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():(this._getSubscriptionToken().then(e=>this._handleTokenResponse(e)).catch(e=>this._handleTokenError(e)),null)):(this._debug("delay subscribe on",this.channel,"till connected"),null)}_isTransportOpen(){return this._centrifuge._transportIsOpen}_canSubscribeWithoutGettingToken(){return!this._usesToken()||!!this._token}_subscribeWithoutToken(){return this._getData?(this._getDataAndSubscribe(this._token),null):this._sendSubscribe(this._token)}_getDataAndSubscribe(e){this._getData?this._getData({channel:this.channel}).then(t=>{this._isSubscribing()?(this._data=t,this._sendSubscribe(e)):this._inflight=!1}).catch(e=>this._handleGetDataError(e)):this._inflight=!1}_handleGetDataError(e){if(this._isSubscribing()){if(e instanceof ye)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:V.badConfiguration,message:(null==e?void 0:e.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_handleTokenResponse(e){if(this._isSubscribing()){if(!e)return this._inflight=!1,void this._failUnauthorized();this._token=e,this._getData?this._getDataAndSubscribe(e):this._sendSubscribe(e)}else this._inflight=!1}_handleTokenError(e){if(this._isSubscribing()){if(e instanceof ye)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:V.subscriptionSubscribeToken,message:(null==e?void 0:e.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_sendSubscribe(e){if(!this._isTransportOpen())return this._inflight=!1,null;const t=this._buildSubscribeCommand(e);return this._centrifuge._call(t).then(e=>{this._inflight=!1;const t=e.reply.subscribe;this._handleSubscribeResponse(t),e.next&&e.next()},e=>{this._inflight=!1,this._handleSubscribeError(e.error),e.next&&e.next()}),t}_buildSubscribeCommand(e){const t={channel:this.channel};if(e&&(t.token=e),this._data&&(t.data=this._data),this._positioned&&(t.positioned=!0),this._recoverable&&(t.recoverable=!0),this._joinLeave&&(t.join_leave=!0),t.flag=K.channelCompaction,this._needRecover()){t.recover=!0;const e=this._getOffset();e&&(t.offset=e);const s=this._getEpoch();s&&(t.epoch=s)}return this._delta&&(t.delta=this._delta),this._tagsFilter&&(t.tf=this._tagsFilter),{subscribe:t}}_debug(...e){this._centrifuge._debug(...e)}_handleSubscribeError(e){this._isSubscribing()&&(e.code!==V.timeout?this._subscribeError(e):this._centrifuge._disconnect($.subscribeTimeout,"subscribe timeout",!0))}_handleSubscribeResponse(e){this._isSubscribing()&&this._setSubscribed(e)}_setUnsubscribed(e,t,s){if(this._isUnsubscribed())return Promise.resolve();let i=Promise.resolve();return this._isSubscribed()?(s&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&s&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._setState(ie.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:V.subscriptionUnsubscribed,message:this.state}),i}_handlePublication(e){if(this._delta&&this._delta_negotiated){const{newData:t,newPrevValue:s}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValue);e.data=t,this._prevValue=s}const t=this._centrifuge._getPublicationContext(this.channel,e);this.emit("publication",t),e.offset&&(this._offset=e.offset)}_handleJoin(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("join",{channel:this.channel,info:t})}_handleLeave(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("leave",{channel:this.channel,info:t})}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}_scheduleResubscribe(){if(!this._isSubscribing())return void this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);const e=this,t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){e._isSubscribing()&&e._subscribe()},t),this._debug("resubscribe scheduled after "+t,this.channel)}_subscribeError(e){if(this._isSubscribing())if(e.code<100||109===e.code||!0===e.temporary){109===e.code&&(this._token="");const t={channel:this.channel,type:"subscribe",error:e};this._centrifuge.state===te.Connected&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){const e=ae(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,e}_setOptions(e){if(e){if(e.since&&(this._offset=e.since.offset||0,this._epoch=e.since.epoch||"",this._recover=!0),e.data&&(this._data=e.data),e.getData&&(this._getData=e.getData),void 0!==e.minResubscribeDelay&&(this._minResubscribeDelay=e.minResubscribeDelay),void 0!==e.maxResubscribeDelay&&(this._maxResubscribeDelay=e.maxResubscribeDelay),e.token&&(this._token=e.token),e.getToken&&(this._getToken=e.getToken),!0===e.positioned&&(this._positioned=!0),!0===e.recoverable&&(this._recoverable=!0),!0===e.joinLeave&&(this._joinLeave=!0),e.delta){if("fossil"!==e.delta)throw new Error("unsupported delta format");this._delta=e.delta}if(e.tagsFilter&&(this._tagsFilter=e.tagsFilter),this._tagsFilter&&this._delta)throw new Error("cannot use delta and tagsFilter together")}}_getOffset(){const e=this._offset;return null!==e?e:0}_getEpoch(){const e=this._epoch;return null!==e?e:""}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){null!==this._resubscribeTimeout&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._debug("get subscription token for channel",this.channel);const e={channel:this.channel},t=this._getToken;return null===t?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:V.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new ye(""))):t(e)}_refresh(){this._clearRefreshTimeout();const e=this;this._getSubscriptionToken().then(function(t){if(!e._isSubscribed())return;if(!t)return void e._failUnauthorized();e._token=t;const s={sub_refresh:{channel:e.channel,token:t}};e._centrifuge._call(s).then(t=>{const s=t.reply.sub_refresh;e._refreshResponse(s),t.next&&t.next()},t=>{e._refreshError(t.error),t.next&&t.next()})}).catch(function(t){t instanceof ye?e._failUnauthorized():(e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:V.subscriptionRefreshToken,message:void 0!==t?t.toString():""}}),e._refreshTimeout=setTimeout(()=>e._refresh(),e._getRefreshRetryDelay()))})}_refreshResponse(e){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),!0===e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ce(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||!0===e.temporary?(this.emit("error",{type:"refresh",channel:this.channel,error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._setUnsubscribed(e.code,e.message,!0))}_getRefreshRetryDelay(){return ae(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(X.unauthorized,"unauthorized",!0)}}class he{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return null!==this.options.sockjs}initialize(e,t){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class de{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return void 0!==this.options.websocket&&null!==this.options.websocket}initialize(e,t){let s="";"protobuf"===e&&(s="centrifuge-protobuf"),this._transport=""!==s?new this.options.websocket(this.endpoint,s):new this.options.websocket(this.endpoint),"protobuf"===e&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class ue{constructor(e,t){this.endpoint=e,this.options=t,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(e){if(!e.ok)throw new Error(e.status);return e}_fetchEventTarget(e,t,s){const i=new EventTarget;return(0,e.options.fetch)(t,s).then(e._handleErrors).then(t=>{i.dispatchEvent(new Event("open"));let s="",n=0,o=new Uint8Array;const r=t.body.getReader();return new e.options.readableStream({start:t=>function a(){return r.read().then(({done:r,value:c})=>{if(r)return i.dispatchEvent(new Event("close")),void t.close();try{if("json"===e._protocol)for(s+=e._utf8decoder.decode(c);n<s.length;)if("\n"===s[n]){const e=s.substring(0,n);i.dispatchEvent(new MessageEvent("message",{data:e})),s=s.substring(n+1),n=0}else++n;else{const t=new Uint8Array(o.length+c.length);for(t.set(o),t.set(c,o.length),o=t;;){const t=e.options.decoder.decodeReply(o);if(t.ok){const e=o.slice(0,t.pos);i.dispatchEvent(new MessageEvent("message",{data:e})),o=o.slice(t.pos);continue}break}}}catch(l){return i.dispatchEvent(new Event("error",{detail:l})),i.dispatchEvent(new Event("close")),void t.close()}a()}).catch(function(e){i.dispatchEvent(new Event("error",{detail:e})),i.dispatchEvent(new Event("close")),t.close()})}()})}).catch(e=>{i.dispatchEvent(new Event("error",{detail:e})),i.dispatchEvent(new Event("close"))}),i}supported(){return null!==this.options.fetch&&null!==this.options.readableStream&&"undefined"!=typeof TextDecoder&&"undefined"!=typeof AbortController&&"undefined"!=typeof EventTarget&&"undefined"!=typeof Event&&"undefined"!=typeof MessageEvent&&"undefined"!=typeof Error}initialize(e,t,s){let i,n;this._protocol=e,this._abortController=new AbortController,"json"===e?(i={Accept:"application/json","Content-Type":"application/json"},n=s):(i={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},n=s);const o={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},r=this._fetchEventTarget(this,this.endpoint,o);r.addEventListener("open",()=>{t.onOpen()}),r.addEventListener("error",e=>{this._abortController.abort(),t.onError(e)}),r.addEventListener("close",()=>{this._abortController.abort(),t.onClose({code:4,reason:"connection closed"})}),r.addEventListener("message",e=>{t.onMessage(e.data)})}close(){this._abortController.abort()}send(e,t,s){let i,n;const o={session:t,node:s,data:e};"json"===this._protocol?(i={"Content-Type":"application/json"},n=JSON.stringify(o)):(i={"Content-Type":"application/octet-stream"},n=this.options.encoder.encodeEmulationRequest(o));const r={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,r)}}class pe{constructor(e,t){this.endpoint=e,this.options=t,this._protocol="json",this._transport=null,this._onClose=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return null!==this.options.eventsource&&null!==this.options.fetch}initialize(e,t,s){let i;i=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),i.searchParams.append("cf_connect",s);const n=new this.options.eventsource(i.toString(),{});this._transport=n;n.onopen=function(){t.onOpen()},n.onerror=function(e){n.close(),t.onError(e),t.onClose({code:4,reason:"connection closed"})},n.onmessage=function(e){t.onMessage(e.data)},this._onClose=function(){t.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),null!==this._onClose&&this._onClose()}send(e,t,s){const i={session:t,node:s,data:e},n={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,n)}}class ve{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"webtransport"}subName(){return"webtransport"}emulation(){return!1}supported(){return void 0!==this.options.webtransport&&null!==this.options.webtransport}initialize(e,t){return S(this,0,void 0,function*(){let s;s=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),"protobuf"===e&&s.searchParams.append("cf_protocol","protobuf"),this._protocol=e;const i=new EventTarget;this._transport=new this.options.webtransport(s.toString()),this._transport.closed.then(()=>{t.onClose({code:4,reason:"connection closed"})}).catch(()=>{t.onClose({code:4,reason:"connection closed"})});try{yield this._transport.ready}catch(o){return void this.close()}let n;try{n=yield this._transport.createBidirectionalStream()}catch(r){return void this.close()}this._stream=n,this._writer=this._stream.writable.getWriter(),i.addEventListener("close",()=>{t.onClose({code:4,reason:"connection closed"})}),i.addEventListener("message",e=>{t.onMessage(e.data)}),this._startReading(i),t.onOpen()})}_startReading(e){return S(this,0,void 0,function*(){const t=this._stream.readable.getReader();let s="",i=0,n=new Uint8Array;try{for(;;){const{done:o,value:r}=yield t.read();if(r.length>0)if("json"===this._protocol)for(s+=this._utf8decoder.decode(r);i<s.length;)if("\n"===s[i]){const t=s.substring(0,i);e.dispatchEvent(new MessageEvent("message",{data:t})),s=s.substring(i+1),i=0}else++i;else{const t=new Uint8Array(n.length+r.length);for(t.set(n),t.set(r,n.length),n=t;;){const t=this.options.decoder.decodeReply(n);if(t.ok){const s=n.slice(0,t.pos);e.dispatchEvent(new MessageEvent("message",{data:s})),n=n.slice(t.pos);continue}break}}if(o)break}}catch(o){e.dispatchEvent(new Event("close"))}})}close(){return S(this,0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}})}send(e){return S(this,0,void 0,function*(){let t;t="json"===this._protocol?(new TextEncoder).encode(e+"\n"):e;try{yield this._writer.write(t)}catch(s){this.close()}})}}const ge=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class me{constructor(e){this.a=e,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const e=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e,t=0;for(;this.haveBytes()&&(e=ge[127&this.getByte()])>=0;)t=(t<<6)+e;return this.pos--,t>>>0}}class fe{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,t,s){for(let i=t;i<s;i++)this.a.push(e[i])}}function _e(e){let t=0,s=0,i=0,n=0,o=0,r=e.length;for(;r>=16;)t=t+e[o+0]|0,s=s+e[o+1]|0,i=i+e[o+2]|0,n=n+e[o+3]|0,t=t+e[o+4]|0,s=s+e[o+5]|0,i=i+e[o+6]|0,n=n+e[o+7]|0,t=t+e[o+8]|0,s=s+e[o+9]|0,i=i+e[o+10]|0,n=n+e[o+11]|0,t=t+e[o+12]|0,s=s+e[o+13]|0,i=i+e[o+14]|0,n=n+e[o+15]|0,o+=16,r-=16;for(;r>=4;)t=t+e[o+0]|0,s=s+e[o+1]|0,i=i+e[o+2]|0,n=n+e[o+3]|0,o+=4,r-=4;switch(n=((n+(i<<8)|0)+(s<<16)|0)+(t<<24)|0,r){case 3:n=n+(e[o+2]<<8)|0;case 2:n=n+(e[o+1]<<16)|0;case 1:n=n+(e[o+0]<<24)|0}return n>>>0}class be{name(){return"json"}encodeCommands(e){return e.map(e=>JSON.stringify(e)).join("\n")}decodeReplies(e){return e.trim().split("\n").map(e=>JSON.parse(e))}applyDeltaIfNeeded(e,t){let s,i;if(e.delta){const n=function(e,t){let s=0;const i=new me(t),n=e.length,o=t.length,r=i.getInt();if("\n"!==i.getChar())throw new Error("size integer not terminated by '\\n'");const a=new fe;for(;i.haveBytes();){const t=i.getInt();let c;switch(i.getChar()){case"@":if(c=i.getInt(),i.haveBytes()&&","!==i.getChar())throw new Error("copy command not terminated by ','");if(s+=t,s>r)throw new Error("copy exceeds output file size");if(c+t>n)throw new Error("copy extends past end of input");a.putArray(e,c,c+t);break;case":":if(s+=t,s>r)throw new Error("insert command gives an output larger than predicted");if(t>o)throw new Error("insert count exceeds size of delta");a.putArray(i.a,i.pos,i.pos+t),i.pos+=t;break;case";":{const i=a.toByteArray(e);if(t!==_e(i))throw new Error("bad checksum");if(s!==r)throw new Error("generated size does not match predicted size");return i}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}(t,(new TextEncoder).encode(e.data));s=JSON.parse((new TextDecoder).decode(n)),i=n}else s=JSON.parse(e.data),i=(new TextEncoder).encode(e.data);return{newData:s,newPrevValue:i}}}const we={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class ye extends Error{constructor(e){super(e),this.name=this.constructor.name}}class xe extends oe{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=te.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new be,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},we),t),this._configure(),this._debugEnabled?(this.on("state",e=>{this._debug("client state",e.oldState,"->",e.newState)}),this.on("error",e=>{this._debug("client error",e)})):this.on("error",function(){Function.prototype()})}newSubscription(e,t){if(null!==this.getSubscription(e))throw new Error("Subscription to the channel "+e+" already exists");const s=new le(this,e,t);return this._subs[e]=s,s}getSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==ie.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}subscriptions(){return this._subs}ready(e){return S(this,0,void 0,function*(){switch(this.state){case te.Disconnected:throw{code:V.clientDisconnected,message:"client disconnected"};case te.Connected:return;default:return new Promise((t,s)=>{const i={resolve:t,reject:s};e&&(i.timeout=setTimeout(()=>{s({code:V.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}})}connect(){this._isConnected()?this._debug("connect called when already connected"):this._isConnecting()?this._debug("connect called when already connecting"):(this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting())}disconnect(){this._disconnect(Z.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return S(this,0,void 0,function*(){const t={send:{data:e}};yield this._methodCall();if(!this._transportSendCommands([t]))throw this._createErrorObject(V.transportWriteError,"transport write error")})}rpc(e,t){return S(this,0,void 0,function*(){const s={rpc:{method:e,data:t}};yield this._methodCall();return{data:(yield this._callPromise(s,e=>e.rpc)).data}})}publish(e,t){return S(this,0,void 0,function*(){const s={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(s,()=>({})),{}})}history(e,t){return S(this,0,void 0,function*(){const s={history:this._getHistoryRequest(e,t)};yield this._methodCall();const i=yield this._callPromise(s,e=>e.history),n=[];if(i.publications)for(let t=0;t<i.publications.length;t++)n.push(this._getPublicationContext(e,i.publications[t]));return{publications:n,epoch:i.epoch||"",offset:i.offset||0}})}presence(e){return S(this,0,void 0,function*(){const t={presence:{channel:e}};yield this._methodCall();const s=(yield this._callPromise(t,e=>e.presence)).presence;for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){const t=s[e],i=t.conn_info,n=t.chan_info;i&&(t.connInfo=i),n&&(t.chanInfo=n)}return{clients:s}})}presenceStats(e){return S(this,0,void 0,function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const s=yield this._callPromise(t,e=>e.presence_stats);return{numUsers:s.num_users,numClients:s.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&function(e,t){if(globalThis.console){const s=globalThis.console[e];re(s)&&s.apply(globalThis.console,t)}}("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(null!==this._config.token&&(this._token=this._config.token),null!==this._config.data&&(this._data=this._config.data),this._codec=new be,this._formatOverride(),(!0===this._config.debug||"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem&&localStorage.getItem("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),"string"==typeof this._endpoint);else{if(!Array.isArray(this._endpoint))throw new Error("unsupported url configuration type: only string or array of objects are supported");this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");const s=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(s)<0)throw new Error("unsupported transport name: "+s)}}}_setState(e){if(this.state!==e){this._reconnecting=!1;const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state===te.Disconnected}_isConnecting(){return this.state===te.Connecting}_isConnected(){return this.state===te.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;null!==this._config.networkEventTarget?e=this._config.networkEventTarget:void 0!==globalThis.addEventListener&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),this.state!==te.Connected&&this.state!==te.Connecting||(this._disconnect($.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===te.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=ae(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const t=this._callbacks[e];clearTimeout(t.timeout);const s=t.errback;if(!s)continue;s({error:this._createErrorObject(V.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const t=this._subs[e];t.state===ie.Subscribed&&t._setSubscribing(G.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const t of e){const e=t.id;if(!(e in this._callbacks))continue;const s=this._callbacks[e];clearTimeout(this._callbacks[e].timeout),delete this._callbacks[e];(0,s.errback)({error:this._createErrorObject(V.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_initializeTransport(){let e;null!==this._config.websocket?e=this._config.websocket:"function"!=typeof globalThis.WebSocket&&"object"!=typeof globalThis.WebSocket||(e=globalThis.WebSocket);let t=null;null!==this._config.sockjs?t=this._config.sockjs:void 0!==globalThis.SockJS&&(t=globalThis.SockJS);let s=null;null!==this._config.eventsource?s=this._config.eventsource:void 0!==globalThis.EventSource&&(s=globalThis.EventSource);let i=null;null!==this._config.fetch?i=this._config.fetch:void 0!==globalThis.fetch&&(i=globalThis.fetch);let n=null;if(null!==this._config.readableStream?n=this._config.readableStream:void 0!==globalThis.ReadableStream&&(n=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let o=0;for(;;){if(o>=this._transports.length)throw new Error("no supported transport found");const r=this._transports[this._currentTransportIndex],a=r.transport,c=r.endpoint;if("websocket"===a){if(this._debug("trying websocket transport"),this._transport=new de(c,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,o++;continue}}else if("webtransport"===a){if(this._debug("trying webtransport transport"),this._transport=new ve(c,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,o++;continue}}else if("http_stream"===a){if(this._debug("trying http_stream transport"),this._transport=new ue(c,{fetch:i,readableStream:n,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,o++;continue}}else if("sse"===a){if(this._debug("trying sse transport"),this._transport=new pe(c,{eventsource:s,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,o++;continue}}else{if("sockjs"!==a)throw new Error("unknown transport "+a);if(this._debug("trying sockjs"),this._transport=new he(c,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,o++;continue}}break}}else{if(o=this._endpoint,r="http",0===o.lastIndexOf(r,0))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new de(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}var o,r;const a=this,c=this._transport,l=this._nextTransportId();a._debug("id of transport",l);let h=!1;const d=[];if(this._transport.emulation()){const e=a._sendConnect(!0);d.push(e)}this._setNetworkEvents();const u=this._codec.encodeCommands(d);let p;this._transportClosed=!1,p=setTimeout(function(){c.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(p&&(clearTimeout(p),p=null),a._transportId!=l)return a._debug("open callback from non-actual transport"),void c.close();h=!0,a._debug(c.subName(),"transport open"),c.emulation()||(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(e){a._transportId==l?a._debug("transport level error",e):a._debug("error callback from non-actual transport")},onClose:function(e){if(p&&(clearTimeout(p),p=null),a._transportId!=l)return void a._debug("close callback from non-actual transport");a._debug(c.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let t="connection closed",s=!0,i=0;if(e&&"code"in e&&e.code&&(i=e.code),e&&e.reason)try{const i=JSON.parse(e.reason);t=i.reason,s=i.reconnect}catch(n){t=e.reason,(i>=3500&&i<4e3||i>=4500&&i<5e3)&&(s=!1)}i<3e3?(1009===i?(i=Z.messageSizeLimit,t="message size limit exceeded",s=!1):(i=$.transportClosed,t="transport closed"),a._emulation&&!a._transportWasOpen&&(a._currentTransportIndex++,a._currentTransportIndex>=a._transports.length&&(a._triedAllTransports=!0,a._currentTransportIndex=0))):a._transportWasOpen=!0,a._isConnecting()&&!h&&a.emit("error",{type:"transport",error:{code:V.transportClosed,message:"transport closed"},transport:c.name()}),a._reconnecting=!1,a._disconnect(i,t,s)},onMessage:function(e){a._dataReceived(e)}},u),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),s=this;return this._call(t,e).then(e=>{const t=e.reply.connect;s._connectResponse(t),e.next&&e.next()},e=>{s._connectError(e.error),e.next&&e.next()}),t}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting())return void this._debug("stop reconnecting: client not in connecting state");if(this._reconnecting)return void this._debug("reconnect already in progress, return from reconnect routine");if(!1===this._transportClosed)return void this._debug("waiting for transport close");this._reconnecting=!0;const e=""===this._token;if(!(this._refreshRequired||e&&null!==this._config.getToken))return void(this._config.getData?this._config.getData().then(e=>{this._isConnecting()&&(this._data=e,this._initializeTransport())}).catch(e=>this._handleGetDataError(e)):this._initializeTransport());const t=this;this._getToken().then(function(e){t._isConnecting()&&(null!=e&&null!=e?(t._token=e,t._debug("connection token refreshed"),t._config.getData?t._config.getData().then(function(e){t._isConnecting()&&(t._data=e,t._initializeTransport())}).catch(e=>t._handleGetDataError(e)):t._initializeTransport()):t._failUnauthorized())}).catch(function(e){if(!t._isConnecting())return;if(e instanceof ye)return void t._failUnauthorized();t.emit("error",{type:"connectToken",error:{code:V.clientConnectToken,message:void 0!==e?e.toString():""}});const s=t._getReconnectDelay();t._debug("error on getting connection token, reconnect after "+s+" milliseconds",e),t._reconnecting=!1,t._reconnectTimeout=setTimeout(()=>{t._startReconnecting()},s)})}_handleGetDataError(e){if(e instanceof ye)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:V.badConfiguration,message:(null==e?void 0:e.toString())||""}});const t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state===te.Connecting&&(109===e.code&&(this._refreshRequired=!0),e.code<100||!0===e.temporary||109===e.code?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;!this._emulation||this._transportWasOpen||this._triedAllTransports||(e=!0);let t=this._getReconnectDelay();e&&(t=0),this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const t={};let s=!1;for(const i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){s=!0;const e={recover:!0};this._serverSubs[i].offset&&(e.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(e.epoch=this._serverSubs[i].epoch),t[i]=e}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const s={channel:e};return void 0!==t&&(t.since&&(s.since={offset:t.since.offset},t.since.epoch&&(s.since.epoch=t.since.epoch)),void 0!==t.limit&&(s.limit=t.limit),!0===t.reverse&&(s.reverse=!0)),s}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,t)=>{const s=setTimeout(function(){t({code:V.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((s,i)=>{this._call(e,!1).then(e=>{var i;const n=t(e.reply);s(n),null===(i=e.next)||void 0===i||i.call(e)},e=>{var t;i(e.error),null===(t=e.next)||void 0===t||t.call(e)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let e;this._dispatchPromise=new Promise(t=>{e=t}),this._dispatchSynchronized(t,e)})}_dispatchSynchronized(e,t){let s=Promise.resolve();for(const i in e)e.hasOwnProperty(i)&&(s=s.then(()=>this._dispatchReply(e[i])));s=s.then(()=>{t()})}_dispatchReply(e){let t;const s=new Promise(e=>{t=e});if(null==e)return this._debug("dispatch: got undefined or null reply"),t(),s;const i=e.id;return i&&i>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),s}_call(e,t){return new Promise((s,i)=>{e.id=this._nextCommandId(),this._registerCall(e.id,s,i),t||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(te.Connecting)&&this.emit("connecting",{code:$.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,s){if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const n={code:e,reason:t};let o=!1;if(s?o=this._setState(te.Connecting):(o=this._setState(te.Disconnected),this._rejectPromises({code:V.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===te.Connecting&&this._clearReconnectTimeout(),i===te.Connected&&this._clearConnectedState(),o&&(this._isConnecting()?this.emit("connecting",n):this.emit("disconnected",n)),this._transport){this._debug("closing existing transport");const e=this._transport;this._transport=null,e.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Z.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:V.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new ye("")))}_refresh(){const e=this._client,t=this;this._getToken().then(function(s){if(e!==t._client)return;if(!s)return void t._failUnauthorized();if(t._token=s,t._debug("connection token refreshed"),!t._isConnected())return;const i={refresh:{token:t._token}};t._call(i,!1).then(e=>{const s=e.reply.refresh;t._refreshResponse(s),e.next&&e.next()},e=>{t._refreshError(e.error),e.next&&e.next()})}).catch(function(e){t._isConnected()&&(e instanceof ye?t._failUnauthorized():(t.emit("error",{type:"refreshToken",error:{code:V.clientRefreshToken,message:void 0!==e?e.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())))})}_refreshError(e){e.code<100||!0===e.temporary?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return ae(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),ce(e.ttl)))}_removeSubscription(e){null!==e&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const t={unsubscribe:{channel:e.channel}},s=this;return new Promise((e,i)=>{this._call(t,!1).then(t=>{e(),t.next&&t.next()},t=>{e(),t.next&&t.next(),s._disconnect($.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(const e in this._subs)if(this._subs.hasOwnProperty(e)){const s=this._subs[e];if(s._id===t)return s}return null}const s=this._subs[e];return s||null}_isServerSub(e){return void 0!==this._serverSubs[e]}_sendSubscribeCommands(){const e=[];for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const s=this._subs[t];if(!0!==s._inflight&&s.state===ie.Subscribing){const t=s._subscribe();t&&e.push(t)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(te.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ce(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=1e3*e.ping,this._sendPong=!0===e.pong,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];this._serverSubs[t]={offset:s.offset,epoch:s.epoch,recoverable:s.recoverable||!1};const i=this._getSubscribeContext(t,s);this.emit("subscribed",i)}for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];if(s.recovered){const e=s.publications;if(e&&e.length>0)for(const s in e)e.hasOwnProperty(s)&&this._handlePublication(t,e[s])}}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&(e[t]||(this.emit("unsubscribed",{channel:t}),delete this._serverSubs[t]))}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){null!==this._serverPingTimeout&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){0!==this._config.maxServerPingDelay&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect($.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){const s={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};t.recovered&&(s.recovered=!0),t.positioned&&(s.positioned=!0),t.recoverable&&(s.recoverable=!0),t.was_recovering&&(s.wasRecovering=!0);let i="";"epoch"in t&&(i=t.epoch);let n=0;return"offset"in t&&(n=t.offset),(s.positioned||s.recoverable)&&(s.streamPosition={offset:n,epoch:i}),Array.isArray(t.publications)&&t.publications.length>0&&(s.hasRecoveredPublications=!0),t.data&&(s.data=t.data),s}_handleReply(e,t){const s=e.id;if(!(s in this._callbacks))return void t();const i=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],"error"in(n=e)&&null!==n.error){const s=i.errback;if(!s)return void t();s({error:{code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1},next:t})}else{const s=i.callback;if(!s)return;s({reply:e,next:t})}var n}_handleJoin(e,t,s){const i=this._getSub(e,s);if(i||!e)i._handleJoin(t);else if(this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",s)}}_handleLeave(e,t,s){const i=this._getSub(e,s);if(i||!e)i._handleLeave(t);else if(this._isServerSub(e)){const s={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",s)}}_handleUnsubscribe(e,t){const s=this._getSub(e,0);s||!e?t.code<2500?s._setUnsubscribed(t.code,t.reason,!1):s._setSubscribing(t.code,t.reason):this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,t))}_handleDisconnect(e){const t=e.code;let s=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=!1),this._disconnect(t,e.reason,s)}_getPublicationContext(e,t){const s={channel:e,data:t.data};return t.offset&&(s.offset=t.offset),t.info&&(s.info=this._getJoinLeaveContext(t.info)),t.tags&&(s.tags=t.tags),s}_getJoinLeaveContext(e){const t={client:e.client,user:e.user},s=e.conn_info;s&&(t.connInfo=s);const i=e.chan_info;return i&&(t.chanInfo=i),t}_handlePublication(e,t,s){const i=this._getSub(e,s);if(i||!e)i._handlePublication(t);else if(this._isServerSub(e)){const s=this._getPublicationContext(e,t);this.emit("publication",s),void 0!==t.offset&&(this._serverSubs[e].offset=t.offset)}}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const e={};this._transportSendCommands([e])}e()}_handlePush(e,t){const s=e.channel,i=e.id;e.pub?this._handlePublication(s,e.pub,i):e.message?this._handleMessage(e.message):e.join?this._handleJoin(s,e.join,i):e.leave?this._handleLeave(s,e.leave,i):e.unsubscribe?this._handleUnsubscribe(s,e.unsubscribe):e.subscribe?this._handleSubscribe(s,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){const i={code:e,message:t};return s&&(i.temporary=!0),i}_registerCall(e,t,s){this._callbacks[e]={callback:t,errback:s,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],re(s)&&s({error:this._createErrorObject(V.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}}xe.SubscriptionState=ie,xe.State=te,xe.UnauthorizedError=ye;class Ce{constructor(e,s){t(this,"config"),t(this,"events"),t(this,"client",null),t(this,"personalSub",null),t(this,"userId",null),t(this,"getTokenCallback",null),this.config=e,this.events=s}updateConfig(e){this.config=e}setTokenRefreshCallback(e){this.getTokenCallback=e}connect(e,t){var s;if("connected"===(null==(s=this.client)?void 0:s.state))return;this.userId=e;const i=this.getWebSocketUrl(),n={token:t};this.getTokenCallback&&(n.getToken=async()=>await this.getTokenCallback()),this.client=new xe(i,n),this.setupClientEventListeners(),this.client.connect()}getWebSocketUrl(){if(this.config.centrifugoUrl)return this.config.centrifugoUrl;const e=new URL(this.config.apiBase);return`${"https:"===e.protocol?"wss:":"ws:"}//${e.host}/connection/websocket`}setupClientEventListeners(){this.client&&(this.client.on("connected",e=>{this.events.emit("connection:open",{clientId:e.client}),this.subscribeToPersonalChannel()}),this.client.on("disconnected",e=>{this.events.emit("connection:close",{reason:e.reason,code:e.code})}),this.client.on("error",e=>{var t;this.events.emit("connection:error",{error:(null==(t=e.error)?void 0:t.message)||"Unknown error"})}))}subscribeToPersonalChannel(){if(!this.client||!this.userId)return;const e=`visitor:${this.userId}`,t=this.client.getSubscription(e);if(t)return this.personalSub=t,void("subscribed"!==t.state&&t.subscribe());this.personalSub=this.client.newSubscription(e),this.personalSub.on("publication",e=>{this.handleMessage(e.data)}),this.personalSub.on("error",e=>{var t;this.events.emit("error",{type:"subscription",error:null==(t=e.error)?void 0:t.message})}),this.personalSub.subscribe()}handleMessage(e){const t=e.data||e;switch(e.type){case"new_message":const e={id:t.id,body:t.body,inbound:t.inbound||!1,outbound:t.outbound||!1,createdAt:t.createdAt,type:t.type||"text",mediaUrl:t.mediaUrl,senderType:t.senderType,agentName:t.agentName};this.events.emit("message:received",{ticketId:t.ticketId,message:e});break;case"typing":t.isTyping?this.events.emit("typing:start",{ticketId:t.ticketId,actor:t.senderType||"agent"}):this.events.emit("typing:stop",{ticketId:t.ticketId,actor:t.senderType||"agent"});break;case"ticket_created":this.events.emit("conversation:started",{ticketId:t.ticketId,contactId:t.contactId,createdAt:t.createdAt});break;case"ticket_status":this.events.emit("conversation:updated",{ticketId:t.ticketId,status:t.status,message:t.message,closedAt:t.closedAt,agentName:t.agentName})}}updateToken(e){this.client&&this.client.setToken(e)}disconnect(){this.personalSub&&(this.personalSub.unsubscribe(),this.personalSub=null),this.client&&(this.client.disconnect(),this.client=null),this.userId=null}isConnected(){var e;return"connected"===(null==(e=this.client)?void 0:e.state)}getUserId(){return this.userId}}function ke(e,t,s){const i=document.createElement(e);return t&&Object.entries(t).forEach(([e,t])=>{"className"===e?i.className=t:e.startsWith("data-")||e.startsWith("aria-")?i.setAttribute(e,t):i[e]=t}),s&&s.forEach(e=>{"string"==typeof e?i.appendChild(document.createTextNode(e)):i.appendChild(e)}),i}function Se(e){if(!e||"string"!=typeof e)return!1;try{const t=new URL(e,window.location.origin);return["http:","https:","blob:"].includes(t.protocol)}catch{return!1}}function Te(e){return function(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>").replace(/\[(.+?)\]\((.+?)\)/g,(e,t,s)=>{const i=function(e){return Se(e)?e:""}(s);return i?`<a href="${i}" target="_blank" rel="noopener">${t}</a>`:t}).replace(/\n/g,"<br>")}function Ie(e,t=!0){e.scrollTo({top:e.scrollHeight,behavior:t?"smooth":"auto"})}function Ee(){return"cevro_"+Math.random().toString(36).substring(2,9)}class Le{constructor(e,s,i){t(this,"config"),t(this,"element",null),t(this,"unreadBadge",null),t(this,"onClick"),t(this,"bubbleIconUrl"),this.config=e,this.onClick=s,this.bubbleIconUrl=i}render(){this.element=ke("div",{className:"cevro-launcher","data-testid":"launcher"}),this.applyPositioning();const e=ke("button",{className:"cevro-launcher__button","aria-label":"Open chat",type:"button","data-testid":"launcher-button"});if(this.bubbleIconUrl){const t=ke("img",{className:"cevro-launcher__icon cevro-launcher__icon--chat cevro-launcher__icon--custom",src:this.bubbleIconUrl,alt:"Chat"});t.style.width="28px",t.style.height="28px",t.style.objectFit="contain",e.appendChild(t)}else{const t=this.createChatIcon();t.classList.add("cevro-launcher__icon","cevro-launcher__icon--chat"),e.appendChild(t)}const t=this.createCloseIcon();return t.classList.add("cevro-launcher__icon","cevro-launcher__icon--close"),e.appendChild(t),this.unreadBadge=ke("span",{className:"cevro-launcher__badge","data-testid":"unread-badge"}),this.unreadBadge.style.display="none",e.appendChild(this.unreadBadge),e.addEventListener("click",this.onClick),this.element.appendChild(e),this.element}applyPositioning(){if(!this.element)return;const e=this.config.alignment||"right",t=this.config.verticalPadding??20,s=this.config.horizontalPadding??20;this.element.style.bottom=`${t}px`,"left"===e?(this.element.style.left=`${s}px`,this.element.style.right="auto"):(this.element.style.right=`${s}px`,this.element.style.left="auto"),this.config.zIndex&&(this.element.style.zIndex=String(this.config.zIndex))}createChatIcon(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"),e.appendChild(t),e}createCloseIcon(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round");const t=document.createElementNS("http://www.w3.org/2000/svg","line");t.setAttribute("x1","18"),t.setAttribute("y1","6"),t.setAttribute("x2","6"),t.setAttribute("y2","18");const s=document.createElementNS("http://www.w3.org/2000/svg","line");return s.setAttribute("x1","6"),s.setAttribute("y1","6"),s.setAttribute("x2","18"),s.setAttribute("y2","18"),e.appendChild(t),e.appendChild(s),e}setState(e){this.element&&(e?this.element.classList.add("cevro-launcher--open"):this.element.classList.remove("cevro-launcher--open"))}setUnreadCount(e){this.unreadBadge&&(e>0?(this.unreadBadge.textContent=e>99?"99+":String(e),this.unreadBadge.style.display="flex"):this.unreadBadge.style.display="none")}setVisible(e){this.element&&(this.element.style.display=e?"block":"none")}pulse(){this.element&&(this.element.classList.add("cevro-launcher--pulse"),setTimeout(()=>{var e;null==(e=this.element)||e.classList.remove("cevro-launcher--pulse")},1e3))}updateBubbleIcon(e){if(this.bubbleIconUrl=e,!this.element)return;const t=this.element.querySelector(".cevro-launcher__button");if(!t)return;const s=t.querySelector(".cevro-launcher__icon--chat");if(s&&s.remove(),e){const s=document.createElement("img");s.className="cevro-launcher__icon cevro-launcher__icon--chat cevro-launcher__icon--custom",s.src=e,s.alt="Chat",s.style.cssText="width: 28px !important; height: 28px !important; object-fit: contain; border-radius: 4px;",t.insertBefore(s,t.firstChild)}else{const e=this.createChatIcon();e.classList.add("cevro-launcher__icon","cevro-launcher__icon--chat"),t.insertBefore(e,t.firstChild)}}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.unreadBadge=null}}const Me={headerTitle:"Cevro",headerSubtitle:"We typically reply within a few minutes",inputPlaceholder:"How can we help?",preChatTitle:"Start a conversation",preChatSubtitle:"Please provide your contact information to get started.",preChatFirstNameLabel:"First name",preChatFirstNamePlaceholder:"Your first name",preChatEmailLabel:"Email",preChatEmailPlaceholder:"your@email.com",preChatSubmit:"Start Chat",preChatFirstNameRequired:"First name is required",preChatEmailRequired:"Email is required",preChatEmailInvalid:"Please enter a valid email",closedMessage:"The agent closed the chat.",newConversation:"Start New Conversation",conversationsTitle:"Conversations",newConversationButton:"New Conversation",activeConversation:"Active",noConversations:"No conversations yet",noConversationsSubtitle:"Start a new conversation to get help.",loadingConversations:"Loading...",loadMoreConversations:"Load more",messagesCount:"messages",yesterday:"Yesterday",closedStatus:"Closed",defaultConversationTitle:"Conversation",csatTitle:"How was your conversation?",csatSubtitle:"Your feedback helps us get better.",csatPlaceholder:"Thank you! What stood out?",csatPlaceholderNegative:"Sorry to hear that. What could we improve?",csatPlaceholderNeutral:"Thanks for your feedback. Anything we could do better?",csatSubmit:"Submit Feedback",csatThankYou:"Thank you for your feedback!",poweredBy:"Powered by Cevro AI"};function Ne(e,t){return{...Me,...e,...t}}class Pe{constructor(){t(this,"element",null),t(this,"messagesContainer",null),t(this,"messages",new Map),t(this,"onQuickAction",null),t(this,"autoScroll",!0),t(this,"closedMessageElement",null),t(this,"currentAgent",null),t(this,"lastMessageBody"),t(this,"lastMessageAt"),t(this,"onScrollTopCallback",null),t(this,"isLoadingTop",!1),t(this,"suppressScrollEvents",!1)}setQuickActionHandler(e){this.onQuickAction=e}setScrollTopHandler(e){this.onScrollTopCallback=e}finishLoadingTop(){requestAnimationFrame(()=>{this.isLoadingTop=!1})}resetTopLoading(){this.isLoadingTop=!1,this.suppressScrollEvents=!1}setAgent(e){this.currentAgent=e}render(){return this.element||(this.element=ke("div",{className:"cevro-messages",id:Ee()}),this.messagesContainer=ke("div",{className:"cevro-messages__container","data-testid":"messages-container"}),this.messagesContainer.addEventListener("scroll",()=>{if(!this.suppressScrollEvents&&(this.autoScroll=function(e,t=50){return e.scrollHeight-e.scrollTop-e.clientHeight<t}(this.messagesContainer),this.messagesContainer.scrollTop<80&&this.onScrollTopCallback&&!this.isLoadingTop)){const e=this.onScrollTopCallback();e instanceof Promise?(this.isLoadingTop=!0,e.then(e=>{!1===e&&(this.isLoadingTop=!1)}).catch(()=>{this.isLoadingTop=!1})):!1!==e&&(this.isLoadingTop=!0)}}),this.element.appendChild(this.messagesContainer)),this.element}getLastMessageBody(){return this.lastMessageBody}getLastMessageAt(){return this.lastMessageAt}getAgentMessagesSinceLastUserMessage(){if(!this.messagesContainer)return 0;const e=this.messagesContainer.querySelectorAll(".cevro-message");let t=0;for(let s=e.length-1;s>=0;s--){const i=e[s];if(i.classList.contains("cevro-message--outbound"))break;i.classList.contains("cevro-message--inbound")&&t++}return t}addMessage(e,t=!0,s=!1){if(!this.messagesContainer)return;if(e.body&&(this.lastMessageBody=e.body,this.lastMessageAt=e.createdAt),this.messages.has(e.id))return void this.updateMessage(e);const i=this.createMessageElement(e);t&&i.classList.add("cevro-message--animate");const n=this.messagesContainer.querySelector("#cevro-typing-indicator");n?this.messagesContainer.insertBefore(i,n):this.messagesContainer.appendChild(i),this.messages.set(e.id,i),this.autoScroll&&!s&&Ie(this.messagesContainer)}prependMessages(e){if(!this.messagesContainer||0===e.length)return;const t=this.messagesContainer.firstElementChild,s=t?t.offsetTop-this.messagesContainer.scrollTop:0;for(const i of e){if(this.messages.has(i.id))continue;const e=this.createMessageElement(i);this.messagesContainer.insertBefore(e,t),this.messages.set(i.id,e)}t&&(this.suppressScrollEvents=!0,this.messagesContainer.scrollTop=t.offsetTop-s,requestAnimationFrame(()=>{this.suppressScrollEvents=!1}))}prependMessage(e){this.prependMessages([e])}updateMessage(e,t){const s=t||e.id,i=this.messages.get(s);if(!i||!this.messagesContainer)return;const n=this.createMessageElement(e);this.messagesContainer.replaceChild(n,i),t&&t!==e.id&&this.messages.delete(t),this.messages.set(e.id,n)}updateMessageProgress(e,t){const s=this.messages.get(e);if(!s)return;const i=s.querySelector(".cevro-file-progress__fill"),n=s.querySelector(".cevro-file-progress__text");i&&(i.style.width=`${t}%`),n&&(n.textContent=`${t}%`)}removeMessage(e){const t=this.messages.get(e);t&&(t.remove(),this.messages.delete(e))}createMessageElement(e){var t,s,i,n,o;const r=!0===e.inbound,a=ke("div",{className:"cevro-message "+(r?"cevro-message--outbound":"cevro-message--inbound"),"data-message-id":e.id,"data-testid":`message-${e.id}`});if(!r){const s="human"===e.senderType,i=ke("div",{className:"cevro-message__avatar"+(s?" cevro-message__avatar--human":"")});if(s){const t=(e.agentName||"Support").split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2),s=ke("div",{className:"cevro-message__avatar-initials"});s.textContent=t,i.appendChild(s)}else if((null==(t=this.currentAgent)?void 0:t.avatarUrl)&&Se(this.currentAgent.avatarUrl)){const e=ke("img",{className:"cevro-message__avatar-img"});e.src=this.currentAgent.avatarUrl,e.alt=this.currentAgent.name||"Agent",i.appendChild(e)}else i.innerHTML=this.createBotAvatarSvg();a.appendChild(i)}const c=ke("div",{className:"cevro-message__content-wrapper"});if(!r&&"human"===e.senderType&&e.agentName){const t=ke("div",{className:"cevro-message__sender-name"});t.textContent=e.agentName,c.appendChild(t)}const l=ke("div",{className:"cevro-message__bubble"}),h="image"===e.type||"image"===(null==(s=e.attachment)?void 0:s.category);if(h&&e.mediaUrl&&Se(e.mediaUrl)){const t=ke("div",{className:"cevro-message__image-container"}),s=ke("img",{className:"cevro-message__image"});if(s.src=e.mediaUrl,s.alt=(null==(i=e.attachment)?void 0:i.filename)||"Image",s.loading="lazy",t.appendChild(s),"sending"===e.status){const e=this.createProgressOverlay();t.appendChild(e)}l.appendChild(t)}else if("file"===e.type||e.attachment&&!h){const t=this.createFileCard(e);l.appendChild(t)}else if("media"===e.type&&e.mediaUrl&&Se(e.mediaUrl)){const t=ke("a",{className:"cevro-message__attachment"});t.href=e.mediaUrl,t.target="_blank",t.rel="noopener",t.innerHTML=`\n ${this.getFileIcon("file")}\n <span>Attachment</span>\n `,l.appendChild(t)}if(e.body){const t=ke("div",{className:"cevro-message__text"});t.innerHTML=Te(e.body),l.appendChild(t)}if(c.appendChild(l),null==(o=null==(n=e.richContent)?void 0:n.quickActions)?void 0:o.length){const t=ke("div",{className:"cevro-message__quick-actions"});e.richContent.quickActions.forEach(e=>{const s=ke("button",{className:"cevro-message__quick-action"});s.textContent=e.label,s.addEventListener("click",()=>{this.onQuickAction&&this.onQuickAction(e)}),t.appendChild(s)}),c.appendChild(t)}const d=ke("div",{className:"cevro-message__meta"});var u;if(d.textContent=("string"==typeof(u=e.createdAt)?new Date(u):u).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r&&e.status){const t=ke("span",{className:`cevro-message__status cevro-message__status--${e.status}`});t.innerHTML=this.getStatusIcon(e.status),d.appendChild(t)}return c.appendChild(d),a.appendChild(c),a}createProgressOverlay(){const e=ke("div",{className:"cevro-file-progress-overlay"});return e.innerHTML='\n <div class="cevro-file-progress">\n <div class="cevro-file-progress__bar">\n <div class="cevro-file-progress__fill" style="width: 0%"></div>\n </div>\n <span class="cevro-file-progress__text">0%</span>\n </div>\n ',e}createFileCard(e){const t=e.attachment,s=(null==t?void 0:t.category)||"file",i=(null==t?void 0:t.filename)||"File",n=(null==t?void 0:t.size)||0,o="sending"===e.status,r=ke("div",{className:`cevro-file-card cevro-file-card--${s}`}),a=ke("div",{className:"cevro-file-card__icon"});a.innerHTML=this.getFileIcon(s),r.appendChild(a);const c=ke("div",{className:"cevro-file-card__info"}),l=ke("div",{className:"cevro-file-card__name"});l.textContent=this.truncateFilename(i,25),l.title=i,c.appendChild(l);const h=ke("div",{className:"cevro-file-card__details"});if(h.textContent=this.formatFileSize(n),c.appendChild(h),r.appendChild(c),o){const e=ke("div",{className:"cevro-file-card__progress"});e.innerHTML='\n <div class="cevro-file-progress">\n <div class="cevro-file-progress__bar">\n <div class="cevro-file-progress__fill" style="width: 0%"></div>\n </div>\n <span class="cevro-file-progress__text">0%</span>\n </div>\n ',r.appendChild(e)}else e.mediaUrl&&Se(e.mediaUrl)&&(r.style.cursor="pointer",r.addEventListener("click",()=>{window.open(e.mediaUrl,"_blank")}));return r}getFileIcon(e){const t={pdf:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#E53935"/>\n <path d="M14 2V8H20" fill="#FFCDD2"/>\n <path d="M9 13H10.5V14.5H9V16H7.5V11H10.5V12.5H9V13Z" fill="white"/>\n <path d="M11.5 11H13.5C14.05 11 14.5 11.45 14.5 12V14C14.5 14.55 14.05 15 13.5 15H12.5V16H11.5V11ZM13 14V12H12.5V14H13Z" fill="white"/>\n <path d="M15.5 11H17V12H16V13H17V14H16V16H15.5V11Z" fill="white"/>\n </svg>',document:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#1976D2"/>\n <path d="M14 2V8H20" fill="#BBDEFB"/>\n <path d="M8 12H16V13H8V12ZM8 15H14V16H8V15Z" fill="white"/>\n </svg>',spreadsheet:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#388E3C"/>\n <path d="M14 2V8H20" fill="#C8E6C9"/>\n <path d="M8 12H10V14H8V12ZM11 12H13V14H11V12ZM14 12H16V14H14V12ZM8 15H10V17H8V15ZM11 15H13V17H11V15Z" fill="white"/>\n </svg>',presentation:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#F57C00"/>\n <path d="M14 2V8H20" fill="#FFE0B2"/>\n <rect x="8" y="12" width="8" height="5" rx="1" fill="white"/>\n </svg>',video:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#7B1FA2"/>\n <path d="M14 2V8H20" fill="#E1BEE7"/>\n <path d="M10 11V17L15 14L10 11Z" fill="white"/>\n </svg>',audio:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#00897B"/>\n <path d="M14 2V8H20" fill="#B2DFDB"/>\n <path d="M12 11C10.9 11 10 11.9 10 13V15C10 16.1 10.9 17 12 17C13.1 17 14 16.1 14 15V13C14 11.9 13.1 11 12 11Z" fill="white"/>\n <path d="M15 14V15C15 16.66 13.66 18 12 18C10.34 18 9 16.66 9 15V14H8V15C8 17.03 9.53 18.71 11.5 18.96V20H10V21H14V20H12.5V18.96C14.47 18.71 16 17.03 16 15V14H15Z" fill="white"/>\n </svg>',archive:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#795548"/>\n <path d="M14 2V8H20" fill="#D7CCC8"/>\n <rect x="10" y="11" width="4" height="2" fill="white"/>\n <rect x="10" y="14" width="4" height="2" fill="white"/>\n <rect x="10" y="17" width="4" height="2" fill="white"/>\n </svg>',text:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#607D8B"/>\n <path d="M14 2V8H20" fill="#CFD8DC"/>\n <path d="M8 12H16V13H8V12ZM8 15H14V16H8V15ZM8 18H16V19H8V18Z" fill="white"/>\n </svg>',image:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#43A047"/>\n <path d="M14 2V8H20" fill="#C8E6C9"/>\n <circle cx="10" cy="13" r="2" fill="white"/>\n <path d="M8 18L10 15L12 17L15 13L17 18H8Z" fill="white"/>\n </svg>',file:'<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2Z" fill="#90A4AE"/>\n <path d="M14 2V8H20" fill="#CFD8DC"/>\n </svg>'};return t[e]||t.file}formatFileSize(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(1))+" "+["B","KB","MB","GB"][t]}truncateFilename(e,t){if(e.length<=t)return e;const s=e.split(".").pop()||"";return e.slice(0,e.length-s.length-1).slice(0,t-s.length-4)+"..."+"."+s}createBotAvatarSvg(){return'\n <svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="14" cy="10" r="4" fill="white"/>\n <path d="M7 22c0-3.866 3.134-7 7-7s7 3.134 7 7" stroke="white" stroke-width="2" stroke-linecap="round"/>\n </svg>\n '}getStatusIcon(e){switch(e){case"sending":return'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';case"sent":case"delivered":return'<svg width="16" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 7 9.5 17 5 12"/><polyline points="23 7 14.5 17 12 14"/></svg>';case"read":return'<svg width="16" height="12" viewBox="0 0 24 24" fill="none" stroke="#8B5CF6" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="18 7 9.5 17 5 12"/><polyline points="23 7 14.5 17 12 14"/></svg>';case"failed":return'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>';default:return""}}showTypingIndicator(){if(!this.messagesContainer)return;this.hideTypingIndicator();const e=ke("div",{className:"cevro-typing-indicator",id:"cevro-typing-indicator","data-testid":"typing-indicator"});e.innerHTML=`\n <div class="cevro-typing-indicator__avatar">\n ${this.createBotAvatarSvg()}\n </div>\n <div class="cevro-typing-indicator__dots">\n <span></span>\n <span></span>\n <span></span>\n </div>\n `,this.messagesContainer.appendChild(e),this.autoScroll&&Ie(this.messagesContainer)}hideTypingIndicator(){var e;const t=null==(e=this.messagesContainer)?void 0:e.querySelector("#cevro-typing-indicator");t&&t.remove()}clear(){this.messagesContainer&&(this.messagesContainer.innerHTML=""),this.messages.clear(),this.lastMessageBody=void 0,this.lastMessageAt=void 0,this.autoScroll=!0,this.resetTopLoading(),this.closedMessageElement&&(this.closedMessageElement.remove(),this.closedMessageElement=null)}showClosedMessage(e){if(!this.messagesContainer)return;this.hideClosedMessage(),this.closedMessageElement=ke("div",{className:"cevro-messages__closed-notice","data-testid":"closed-chat-message"});const t=e||"The agent closed the chat. If you need assistance please start a new chat.";this.closedMessageElement.innerHTML=`\n <p class="cevro-messages__closed-text">\n ${t}\n </p>\n `,this.messagesContainer.appendChild(this.closedMessageElement),this.autoScroll&&Ie(this.messagesContainer)}hideClosedMessage(){this.closedMessageElement&&(this.closedMessageElement.remove(),this.closedMessageElement=null)}scrollToBottom(){this.messagesContainer&&Ie(this.messagesContainer,!1)}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.messagesContainer=null,this.messages.clear()}}class Ae{constructor(e,s,i,n){t(this,"config"),t(this,"callbacks"),t(this,"element",null),t(this,"messageList"),t(this,"inputElement",null),t(this,"sendButton",null),t(this,"fileInput",null),t(this,"fileButton",null),t(this,"isVisible",!1),t(this,"logoElement",null),t(this,"brandNameElement",null),t(this,"headerSubtitleElement",null),t(this,"inputWrapper",null),t(this,"closedFooter",null),t(this,"csatContainer",null),t(this,"strings",Me),t(this,"csatRating",0),t(this,"csatFeedback",""),t(this,"csatSubmitting",!1),t(this,"preChatContainer",null),t(this,"preChatCompleted",!1),t(this,"customLogoUrl"),this.config=e,this.callbacks=s,this.strings=i||Ne(e.locale),this.customLogoUrl=n,this.messageList=new Pe,this.messageList.setQuickActionHandler(e=>{this.callbacks.onQuickAction(e)})}setStrings(e){this.strings=Ne(this.config.locale,e),this.updateUIStrings()}updateUIStrings(){this.headerSubtitleElement&&(this.headerSubtitleElement.textContent=this.strings.headerSubtitle),this.inputElement&&(this.inputElement.placeholder=this.strings.inputPlaceholder)}render(){if(this.element)return this.element;this.element=ke("div",{className:"cevro-chat-window",id:Ee()}),this.applyPositioning();const e=this.createHeader();this.element.appendChild(e);const t=this.messageList.render();return this.element.appendChild(t),this.inputWrapper=this.createInputArea(),this.element.appendChild(this.inputWrapper),this.element}applyPositioning(){if(!this.element)return;const e=this.config.alignment||"right",t=this.config.verticalPadding??20,s=this.config.horizontalPadding??20;this.element.style.bottom=`${t+70}px`,"left"===e?(this.element.style.left=`${s}px`,this.element.style.right="auto"):(this.element.style.right=`${s}px`,this.element.style.left="auto"),this.config.zIndex&&(this.element.style.zIndex=String(this.config.zIndex-1))}createHeader(){const e=ke("div",{className:"cevro-chat-window__header"});if(this.logoElement=ke("div",{className:"cevro-chat-window__logo","data-testid":"company-logo"}),this.customLogoUrl){const e=ke("img",{src:this.customLogoUrl,alt:"Logo",className:"cevro-chat-window__logo-img"});e.style.width="40px",e.style.height="40px",e.style.objectFit="contain",e.style.borderRadius="8px",this.logoElement.appendChild(e)}else this.logoElement.innerHTML=this.createCompanyLogoSvg();const t=ke("button",{className:"cevro-chat-window__history-button","aria-label":"Conversation history","data-testid":"history-button"});t.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="15 18 9 12 15 6"/>\n </svg>\n ',t.addEventListener("click",()=>{this.callbacks.onShowHistory&&this.callbacks.onShowHistory()}),e.appendChild(t),e.appendChild(this.logoElement);const s=ke("div",{className:"cevro-chat-window__title-section"});this.brandNameElement=ke("h2",{className:"cevro-chat-window__title","data-testid":"brand-name"},[this.strings.headerTitle]),this.headerSubtitleElement=ke("p",{className:"cevro-chat-window__subtitle"},[this.strings.headerSubtitle]),s.appendChild(this.brandNameElement),s.appendChild(this.headerSubtitleElement),e.appendChild(s);const i=ke("button",{className:"cevro-chat-window__close","aria-label":"Close chat","data-testid":"close-button"});return i.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <line x1="18" y1="6" x2="6" y2="18"/>\n <line x1="6" y1="6" x2="18" y2="18"/>\n </svg>\n ',i.addEventListener("click",()=>{this.callbacks.onClose()}),e.appendChild(i),e}createCompanyLogoSvg(){return'\n <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">\n <rect width="40" height="40" rx="8" fill="url(#cevro-logo-gradient)"/>\n <svg x="6" y="6" width="28" height="28" viewBox="0 0 512 498">\n <g>\n <path fill="#FFFFFF" d="M298.97,91.19l-32.23-32.23c-6.12-6.12-6.12-16.03,0-22.15l32.23-32.23c6.12-6.12,16.03-6.12,22.15,0\n l30.06,30.06c2.94,2.94,6.92,4.59,11.07,4.59h48.31v17.32h-48.31c-4.15,0-8.14,1.65-11.07,4.59l-30.05,30.06\n C315,97.3,305.09,97.31,298.97,91.19z"/>\n <path fill="#FFFFFF" d="M260.84,157h96.5c4.15,0,8.14,1.65,11.07,4.59l30.05,30.05c6.12,6.12,16.03,6.12,22.15,0l30.06-30.06\n c2.94-2.94,6.92-4.59,11.07-4.59h50.21v-17.32h-50.21c-4.15,0-8.14-1.65-11.07-4.59l-30.06-30.06\n c-6.12-6.12-16.03-6.12-22.15,0l-30.06,30.05c-2.94,2.94-6.92,4.59-11.07,4.59h-96.5c-4.15,0-8.14-1.65-11.07-4.59\n l-30.06-30.05c-6.12-6.12-16.03-6.12-22.15,0l-32.23,32.23c-6.12,6.12-6.12,16.03,0,22.15l32.23,32.23\n c6.12,6.12,16.03,6.12,22.15,0l30.06-30.05C252.7,158.65,256.69,157,260.84,157z"/>\n <path fill="#FFFFFF" d="M260.84,340.58h96.5c4.15,0,8.14-1.65,11.07-4.59l30.06-30.06c6.12-6.12,16.03-6.12,22.15,0L450.67,336\n c2.94,2.94,6.92,4.59,11.07,4.59h50.21v17.32h-50.21c-4.15,0-8.14,1.65-11.07,4.59l-30.05,30.06\n c-6.12,6.12-16.03,6.12-22.15,0l-30.06-30.06c-2.94-2.94-6.92-4.59-11.07-4.59h-96.5c-4.15,0-8.14,1.65-11.07,4.59\n l-30.05,30.06c-6.12,6.12-16.03,6.12-22.15,0l-32.23-32.23c-6.12-6.12-6.12-16.03,0-22.15l32.23-32.23\n c6.12,6.12,16.03-6.12,22.15,0L249.77,336C252.7,338.93,256.69,340.58,260.84,340.58z"/>\n <path fill="#FFFFFF" d="M343.17,259.89l-1.13,1.13l-31.09,31.09c-1.9,1.9-4.16,3.21-6.6,3.92c-3.92,1.19-8.2,0.83-11.83-1.13\n c-0.89-0.54-1.72-1.07-2.56-1.72c-0.42-0.3-0.83-0.65-1.25-1.07l-30.02-30.08h-0.06c-2.91-2.91-6.9-4.58-11.06-4.58h-86.71\n c-2.62,0-5.11,0.65-7.37,1.84c-0.89,0.53-1.72,1.07-2.5,1.72c-0.06-0.06-0.06-0.06-0.06,0c-0.36,0.36-0.71,0.65-1.07,1.01\n l-30.08,30.08h-0.06c-0.36,0.36-0.77,0.71-1.19,1.07c-0.77,0.71-1.66,1.25-2.56,1.72c-3.63,1.9-7.91,2.32-11.83,1.13\n c-0.95-0.3-1.84-0.71-2.73-1.13c-0.06,0-0.06,0-0.06,0c-1.31-0.77-2.56-1.66-3.69-2.79l-30.08-30.08h-0.06\n c-0.71-0.77-1.49-1.37-2.32-1.96c-0.06,0.06-0.06,0.06-0.06,0c-1.31-0.89-2.68-1.55-4.16-1.96\n c-1.49-0.42-3.03-0.65-4.58-0.65H6.3v-17.3h50.12c1.55,0,3.09-0.24,4.58-0.65c1.49-0.42,2.85-1.07,4.16-1.96\n c0-0.06,0-0.06,0.06,0c0.83-0.59,1.61-1.19,2.32-1.96h0.06l30.08-30.08c1.13-1.13,2.38-2.08,3.69-2.79c0,0,0-0.06,0.06,0\n c0.47-0.24,0.95-0.48,1.43-0.65c0.48-0.18,0.95-0.36,1.43-0.48c3.86-1.19,8.08-0.77,11.71,1.13\n c0.89,0.48,1.79,1.01,2.56,1.72c0.42,0.36,0.83,0.71,1.19,1.07h0.06l30.08,30.08c0.36,0.36,0.71,0.65,1.07,1.01\n c0,0.06,0,0.06,0.06,0c0.77,0.65,1.61,1.19,2.5,1.72c2.26,1.19,4.76,1.84,7.37,1.84h86.71c4.16,0,8.14-1.66,11.06-4.58h0.06\n l30.08-30.08c0.36-0.42,0.77-0.77,1.19-1.07c0.83-0.65,1.66-1.25,2.56-1.72c3.63-1.9,7.85-2.32,11.71-1.13\n c0.48,0.12,0.95,0.3,1.43,0.48c1.96,0.71,3.74,1.84,5.29,3.45l32.22,32.22C349.23,243.83,349.23,253.76,343.17,259.89z"/>\n <path fill="#FFFFFF" d="M298.02,406.39l-32.23,32.23c-6.12,6.12-6.12,16.03,0,22.15L298.02,493c6.12,6.12,16.03,6.12,22.15,0\n l30.06-30.06c2.94-2.94,6.92-4.59,11.07-4.59h50.21v-17.32h-50.21c-4.15,0-8.14-1.65-11.07-4.59l-30.06-30.06\n C314.05,400.28,304.13,400.28,298.02,406.39z"/>\n </g>\n </svg>\n <defs>\n <linearGradient id="cevro-logo-gradient" x1="0" y1="0" x2="40" y2="40" gradientUnits="userSpaceOnUse">\n <stop offset="0%" stop-color="#8B5CF6"/>\n <stop offset="100%" stop-color="#7C3AED"/>\n </linearGradient>\n </defs>\n </svg>\n '}setAgent(e){this.messageList.setAgent(e)}createInputArea(){const e=ke("div",{className:"cevro-chat-window__input-wrapper"}),t=ke("div",{className:"cevro-chat-window__input-area"});this.fileButton=ke("button",{className:"cevro-chat-window__file-button","aria-label":"Attach file","data-testid":"file-button"}),this.fileButton.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M16.5 6V17.5C16.5 19.71 14.71 21.5 12.5 21.5C10.29 21.5 8.5 19.71 8.5 17.5V5C8.5 3.62 9.62 2.5 11 2.5C12.38 2.5 13.5 3.62 13.5 5V16.5C13.5 17.05 13.05 17.5 12.5 17.5C11.95 17.5 11.5 17.05 11.5 16.5V6H10V16.5C10 17.88 11.12 19 12.5 19C13.88 19 15 17.88 15 16.5V5C15 2.79 13.21 1 11 1C8.79 1 7 2.79 7 5V17.5C7 20.54 9.46 23 12.5 23C15.54 23 18 20.54 18 17.5V6H16.5Z" fill="currentColor"/>\n </svg>\n ',this.fileInput=ke("input",{className:"cevro-chat-window__file-input"}),this.fileInput.type="file",this.fileInput.accept=function(e=_){const t=[];return e.forEach(e=>{t.push(e)}),t.join(",")}(),this.fileInput.addEventListener("change",()=>{var e,t;(null==(t=null==(e=this.fileInput)?void 0:e.files)?void 0:t.length)&&this.callbacks.onFileUpload&&(this.callbacks.onFileUpload(this.fileInput.files[0]),this.fileInput.value="")}),this.fileButton.addEventListener("click",()=>{var e;null==(e=this.fileInput)||e.click()}),t.appendChild(this.fileButton),t.appendChild(this.fileInput),this.inputElement=ke("textarea",{className:"cevro-chat-window__input","data-testid":"chat-input"}),this.inputElement.placeholder=this.strings.inputPlaceholder,this.inputElement.rows=1,this.inputElement.setAttribute("maxlength","2000"),this.inputElement.addEventListener("input",()=>{this.resizeInput(),this.updateSendButtonState()}),this.inputElement.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.handleSend())}),t.appendChild(this.inputElement),this.sendButton=ke("button",{className:"cevro-chat-window__send-button","aria-label":"Send message","data-testid":"send-button"}),this.sendButton.disabled=!0,this.sendButton.innerHTML='\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M12 19V5M5 12L12 5L19 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',this.sendButton.addEventListener("click",()=>{this.handleSend()}),t.appendChild(this.sendButton),e.appendChild(t);const s=ke("div",{className:"cevro-chat-window__footer"});return s.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,e.appendChild(s),e}handleSend(){if(!this.inputElement)return;const e=this.inputElement.value.trim();e&&(this.callbacks.onSendMessage(e),this.inputElement.value="",this.resizeInput(),this.updateSendButtonState(),this.inputElement.focus({preventScroll:!0}))}updateSendButtonState(){this.sendButton&&this.inputElement&&(this.sendButton.disabled=!this.inputElement.value.trim())}resizeInput(){this.inputElement&&(this.inputElement.style.height="auto",this.inputElement.style.height=Math.min(this.inputElement.scrollHeight,100)+"px")}setDraft(e){if(!this.inputElement)return;const t=Number(this.inputElement.getAttribute("maxlength"))||2e3;this.inputElement.value=e.slice(0,t),this.resizeInput(),this.updateSendButtonState(),this.inputElement.focus({preventScroll:!0})}setScrollTopHandler(e){this.messageList.setScrollTopHandler(e)}prependMessage(e){this.messageList.prependMessage(e)}prependMessages(e){this.messageList.prependMessages(e)}finishLoadingTop(){this.messageList.finishLoadingTop()}addMessage(e,t=!0){this.messageList.addMessage(e,t)}updateMessage(e,t){this.messageList.updateMessage(e,t)}updateMessageProgress(e,t){this.messageList.updateMessageProgress(e,t)}removeMessage(e){this.messageList.removeMessage(e)}showTypingIndicator(){this.messageList.showTypingIndicator()}hideTypingIndicator(){this.messageList.hideTypingIndicator()}clearMessages(){this.messageList.clear()}show(){var e;this.element&&(this.element.classList.add("cevro-chat-window--visible"),this.isVisible=!0,null==(e=this.inputElement)||e.focus({preventScroll:!0}),this.messageList.scrollToBottom())}hide(){this.element&&(this.element.classList.remove("cevro-chat-window--visible"),this.isVisible=!1)}isWindowVisible(){return this.isVisible}focusInput(){var e;null==(e=this.inputElement)||e.focus({preventScroll:!0})}setTicketClosed(e,t,s){const i=(null==s?void 0:s.skipCSAT)??!1,n=null==s?void 0:s.ticketId;if(e){this.removeClosedUI(),this.messageList.showClosedMessage(this.strings.closedMessage),this.inputWrapper&&(this.inputWrapper.style.display="none");const e=n&&localStorage.getItem(`cevro_csat_${n}`);i||e?this.showClosedFooter(t):this.showInlineCSATForm(t,n)}else this.removeClosedUI(),this.inputWrapper&&(this.inputWrapper.style.display=""),this.messageList.hideClosedMessage()}showInlineCSATForm(e,t){if(this.removeClosedUI(),this.csatRating=0,this.csatFeedback="",!this.element)return;this.csatContainer=ke("div",{className:"cevro-csat-inline"});const s=ke("div",{className:"cevro-csat-inline__header"}),i=ke("span",{className:"cevro-csat-inline__title"},[this.strings.csatTitle]),n=ke("button",{className:"cevro-csat-inline__skip","aria-label":"Skip feedback"},["Skip"]);n.addEventListener("click",()=>{t&&localStorage.setItem(`cevro_csat_${t}`,"skipped"),this.showClosedFooter(e)}),s.appendChild(i),s.appendChild(n);const o=ke("div",{className:"cevro-csat-inline__stars"});for(let l=1;l<=5;l++){const e=ke("button",{className:"cevro-csat-inline__star","data-rating":String(l),"aria-label":`Rate ${l} stars`});e.innerHTML=this.createStarSvg(!1),e.addEventListener("click",()=>this.selectInlineRating(l,o)),e.addEventListener("mouseenter",()=>this.previewRating(l,o)),e.addEventListener("mouseleave",()=>this.previewRating(this.csatRating,o)),o.appendChild(e)}const r=ke("textarea",{className:"cevro-csat-inline__feedback",placeholder:this.strings.csatPlaceholder});r.rows=2,r.addEventListener("input",()=>{this.csatFeedback=r.value});const a=ke("button",{className:"cevro-csat-inline__submit"},[this.strings.csatSubmit||"Submit"]);a.addEventListener("click",()=>this.submitInlineCSAT(e,t));const c=ke("div",{className:"cevro-csat-inline__powered-by"});c.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.csatContainer.appendChild(s),this.csatContainer.appendChild(o),this.csatContainer.appendChild(r),this.csatContainer.appendChild(a),this.csatContainer.appendChild(c),this.element.appendChild(this.csatContainer)}selectInlineRating(e,t){var s;if(this.csatSubmitting)return;this.csatRating=e,this.updateStars(e,t);const i=null==(s=t.parentElement)?void 0:s.querySelector(".cevro-csat-inline__feedback");i&&(i.placeholder=e<=2?this.strings.csatPlaceholderNegative||this.strings.csatPlaceholder:3===e&&this.strings.csatPlaceholderNeutral||this.strings.csatPlaceholder)}async submitInlineCSAT(e,t){var s;if(this.csatSubmitting||0===this.csatRating)return;this.csatSubmitting=!0;const i=null==(s=this.csatContainer)?void 0:s.querySelector(".cevro-csat-inline__submit");i&&(i.disabled=!0,i.textContent="Submitting...");try{this.callbacks.onCSATSubmit&&await this.callbacks.onCSATSubmit(this.csatRating,this.csatFeedback||void 0),t&&localStorage.setItem(`cevro_csat_${t}`,"1"),this.showInlineThankYou(e)}catch{i&&(i.disabled=!1,i.textContent=this.strings.csatSubmit||"Submit")}finally{this.csatSubmitting=!1}}showInlineThankYou(e){if(this.removeClosedUI(),!this.element)return;this.csatContainer=ke("div",{className:"cevro-csat-inline cevro-csat-inline--thank-you"});const t=ke("div",{className:"cevro-csat-inline__thank-you-row"}),s=ke("span",{className:"cevro-csat-inline__check"});s.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none">\n <circle cx="12" cy="12" r="12" fill="#10B981"/>\n <path d="M7 12L10 15L17 8" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ';const i=ke("span",{className:"cevro-csat-inline__message"},[this.strings.csatThankYou]);t.appendChild(s),t.appendChild(i);const n=ke("button",{className:"cevro-csat-inline__new-chat"},[this.strings.newConversation]);n.addEventListener("click",()=>{e&&e()});const o=ke("div",{className:"cevro-csat-inline__powered-by"});o.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.csatContainer.appendChild(t),this.csatContainer.appendChild(n),this.csatContainer.appendChild(o),this.element.appendChild(this.csatContainer)}showClosedFooter(e){if(this.removeClosedUI(),this.element){this.closedFooter=ke("div",{className:"cevro-chat-window__closed-footer"});const t=ke("button",{className:"cevro-chat-window__new-chat-button"},[this.strings.newConversation]);t.addEventListener("click",()=>{e&&e()});const s=ke("div",{className:"cevro-chat-window__powered-by"});s.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.closedFooter.appendChild(t),this.closedFooter.appendChild(s),this.element.appendChild(this.closedFooter)}}removeClosedUI(){this.csatContainer&&this.csatContainer.parentNode&&(this.csatContainer.parentNode.removeChild(this.csatContainer),this.csatContainer=null),this.closedFooter&&this.closedFooter.parentNode&&(this.closedFooter.parentNode.removeChild(this.closedFooter),this.closedFooter=null)}previewRating(e,t){this.updateStars(e,t)}updateStars(e,t){t.querySelectorAll(".cevro-csat__star, .cevro-csat-inline__star").forEach((t,s)=>{const i=s<e;t.innerHTML=this.createStarSvg(i),t.classList.toggle("cevro-csat__star--filled",i),t.classList.toggle("cevro-csat-inline__star--filled",i)})}createStarSvg(e){return e?'\n <svg width="32" height="32" viewBox="0 0 24 24" fill="#FBBF24" stroke="#FBBF24" stroke-width="1">\n <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>\n </svg>\n ':'\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#D1D5DB" stroke-width="1.5">\n <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>\n </svg>\n '}showPreChatForm(){if(this.preChatCompleted||this.preChatContainer)return;if(!this.element)return;this.element.classList.add("cevro-chat-window--prechat");const e=this.element.querySelector(".cevro-messages");e&&(e.style.display="none"),this.inputWrapper&&(this.inputWrapper.style.display="none"),this.preChatContainer=ke("div",{className:"cevro-prechat"});const t=ke("h3",{className:"cevro-prechat__title"},[this.strings.preChatTitle]),s=ke("p",{className:"cevro-prechat__subtitle"},[this.strings.preChatSubtitle]),i=ke("form",{className:"cevro-prechat__form"}),n=ke("div",{className:"cevro-prechat__field"}),o=ke("label",{className:"cevro-prechat__label",for:"cevro-prechat-firstname"},[this.strings.preChatFirstNameLabel]),r=ke("input",{className:"cevro-prechat__input",id:"cevro-prechat-firstname",type:"text","data-testid":"prechat-firstname"});r.placeholder=this.strings.preChatFirstNamePlaceholder;const a=ke("span",{className:"cevro-prechat__error","data-field":"firstName"});r.addEventListener("blur",()=>{r.classList.toggle("cevro-prechat__input--error",!r.value.trim())}),n.appendChild(o),n.appendChild(r),n.appendChild(a);const c=ke("div",{className:"cevro-prechat__field"}),l=ke("label",{className:"cevro-prechat__label",for:"cevro-prechat-email"},[this.strings.preChatEmailLabel]),h=ke("input",{className:"cevro-prechat__input",id:"cevro-prechat-email",type:"text",autocomplete:"email","data-testid":"prechat-email"});h.placeholder=this.strings.preChatEmailPlaceholder;const d=ke("span",{className:"cevro-prechat__error","data-field":"email"});h.addEventListener("blur",()=>{const e=h.value.trim();h.classList.toggle("cevro-prechat__input--error",!e||!this.isValidEmail(e))}),c.appendChild(l),c.appendChild(h),c.appendChild(d);const u=ke("button",{className:"cevro-prechat__submit",type:"submit","data-testid":"prechat-submit"},[this.strings.preChatSubmit]);i.addEventListener("submit",e=>{e.preventDefault(),a.textContent="",d.textContent="",r.classList.remove("cevro-prechat__input--error"),h.classList.remove("cevro-prechat__input--error");const t=r.value.trim(),s=h.value.trim();let i=!1;t||(a.textContent=this.strings.preChatFirstNameRequired,r.classList.add("cevro-prechat__input--error"),i=!0),s?this.isValidEmail(s)||(d.textContent=this.strings.preChatEmailInvalid,h.classList.add("cevro-prechat__input--error"),i=!0):(d.textContent=this.strings.preChatEmailRequired,h.classList.add("cevro-prechat__input--error"),i=!0),i||(this.preChatCompleted=!0,this.callbacks.onPreChatSubmit&&this.callbacks.onPreChatSubmit({firstName:t,email:s}))}),i.appendChild(n),i.appendChild(c),i.appendChild(u);const p=ke("div",{className:"cevro-prechat__powered-by"});p.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.preChatContainer.appendChild(t),this.preChatContainer.appendChild(s),this.preChatContainer.appendChild(i),this.preChatContainer.appendChild(p),this.element.appendChild(this.preChatContainer),r.focus({preventScroll:!0})}hidePreChatForm(){var e,t;if(this.preChatContainer&&this.preChatContainer.parentNode&&(this.preChatContainer.parentNode.removeChild(this.preChatContainer),this.preChatContainer=null),null==(e=this.element)||e.classList.remove("cevro-chat-window--prechat"),this.element){const e=this.element.querySelector(".cevro-messages");e&&(e.style.display="",e.classList.add("cevro-messages--fade-in"))}this.inputWrapper&&(this.inputWrapper.style.display=""),null==(t=this.inputElement)||t.focus({preventScroll:!0})}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}updateCustomLogo(e){if(this.customLogoUrl=e,this.logoElement)if(this.logoElement.innerHTML="",e){const t=document.createElement("img");t.src=e,t.alt="Logo",t.className="cevro-chat-window__logo-img",t.style.width="40px",t.style.height="40px",t.style.objectFit="contain",t.style.borderRadius="8px",this.logoElement.appendChild(t)}else this.logoElement.innerHTML=this.createCompanyLogoSvg()}getLastMessageBody(){return this.messageList.getLastMessageBody()}getLastMessageAt(){return this.messageList.getLastMessageAt()}getAgentMessagesSinceLastUserMessage(){return this.messageList.getAgentMessagesSinceLastUserMessage()}destroy(){this.messageList.destroy(),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.inputElement=null,this.sendButton=null,this.fileInput=null,this.fileButton=null,this.closedFooter=null,this.csatContainer=null,this.preChatContainer=null,this.preChatCompleted=!1}}class Be{constructor(e,s){t(this,"element",null),t(this,"listContainer",null),t(this,"titleElement",null),t(this,"callbacks"),t(this,"strings"),t(this,"activeInfo",null),t(this,"cursor"),t(this,"hasMore",!1),t(this,"loadMoreButton",null),t(this,"isLoadingMore",!1),this.callbacks=e,this.strings=s}setStrings(e){this.strings=e,this.titleElement&&(this.titleElement.textContent=e.conversationsTitle)}setActiveConversation(e){this.activeInfo=e}render(){if(this.element)return this.element;this.element=ke("div",{className:"cevro-conversation-list"});const e=ke("div",{className:"cevro-conversation-list__header"});this.titleElement=ke("h2",{className:"cevro-conversation-list__title"},[this.strings.conversationsTitle]);const t=ke("button",{className:"cevro-conversation-list__close","aria-label":"Close"});t.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <line x1="18" y1="6" x2="6" y2="18"/>\n <line x1="6" y1="6" x2="18" y2="18"/>\n </svg>\n ',t.addEventListener("click",()=>this.callbacks.onClose()),e.appendChild(this.titleElement),e.appendChild(t),this.element.appendChild(e),this.listContainer=ke("div",{className:"cevro-conversation-list__items"}),this.element.appendChild(this.listContainer);const s=ke("button",{className:"cevro-conversation-list__new-conversation"},[this.strings.newConversationButton]);s.addEventListener("click",()=>this.callbacks.onNewConversation()),this.element.appendChild(s);const i=ke("div",{className:"cevro-conversation-list__footer"});return i.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.element.appendChild(i),this.element}async load(){var e;if(!this.listContainer)return;this.cursor=void 0,this.hasMore=!1,this.loadMoreButton=null,this.listContainer.innerHTML="";const t=ke("div",{className:"cevro-conversation-list__loading"},[this.strings.loadingConversations]);this.listContainer.appendChild(t);try{const t=await this.callbacks.onLoadConversations();if(this.listContainer.innerHTML="",this.cursor=t.cursor,this.hasMore=t.hasMore,this.activeInfo){const e=this.createActiveCard();this.listContainer.appendChild(e)}if(0===t.conversations.length&&!this.activeInfo)return void this.showEmptyState();for(const s of t.conversations){if(s.ticketId===(null==(e=this.activeInfo)?void 0:e.ticketId))continue;const t=this.createConversationCard(s);this.listContainer.appendChild(t)}this.renderLoadMoreButton()}catch{if(this.listContainer.innerHTML="",this.activeInfo){const e=this.createActiveCard();this.listContainer.appendChild(e)}this.showEmptyState()}}async loadMore(){var e,t;if(this.listContainer&&this.hasMore&&!this.isLoadingMore){this.isLoadingMore=!0,this.loadMoreButton&&(this.loadMoreButton.textContent=this.strings.loadingConversations,this.loadMoreButton.disabled=!0);try{const s=await this.callbacks.onLoadConversations(this.cursor);this.cursor=s.cursor,this.hasMore=s.hasMore,null==(e=this.loadMoreButton)||e.remove(),this.loadMoreButton=null;for(const e of s.conversations){if(e.ticketId===(null==(t=this.activeInfo)?void 0:t.ticketId))continue;const s=this.createConversationCard(e);this.listContainer.appendChild(s)}this.renderLoadMoreButton()}catch{this.loadMoreButton&&(this.loadMoreButton.textContent=this.strings.loadMoreConversations,this.loadMoreButton.disabled=!1)}finally{this.isLoadingMore=!1}}}renderLoadMoreButton(){this.hasMore&&this.listContainer&&(this.loadMoreButton=ke("button",{className:"cevro-conversation-list__load-more"},[this.strings.loadMoreConversations]),this.loadMoreButton.addEventListener("click",()=>this.loadMore()),this.listContainer.appendChild(this.loadMoreButton))}createActiveCard(){var e,t,s,i;const n=(null==(e=this.activeInfo)?void 0:e.unreadCount)??0,o=ke("div",{className:"cevro-conversation-card cevro-conversation-card--active"+(n>0?" cevro-conversation-card--unread":"")}),r=ke("div",{className:"cevro-conversation-card__content"}),a=ke("div",{className:"cevro-conversation-card__title-row"}),c=ke("span",{className:"cevro-conversation-card__title"},[(null==(t=this.activeInfo)?void 0:t.agentName)||"Support"]),l=ke("span",{className:"cevro-conversation-card__date"},[(null==(s=this.activeInfo)?void 0:s.lastMessageAt)?this.formatDate(this.activeInfo.lastMessageAt):""]);a.appendChild(c),a.appendChild(l);const h=ke("div",{className:"cevro-conversation-card__preview-row"}),d=ke("div",{className:"cevro-conversation-card__preview"},[(null==(i=this.activeInfo)?void 0:i.lastMessageBody)||this.strings.inputPlaceholder]);if(h.appendChild(d),n>0){const e=ke("span",{className:"cevro-conversation-card__unread"},[n>99?"99+":String(n)]);h.appendChild(e)}return r.appendChild(a),r.appendChild(h),o.appendChild(r),o.addEventListener("click",()=>this.callbacks.onSelectActive()),o}createConversationCard(e){const t=ke("div",{className:"cevro-conversation-card"}),s=ke("div",{className:"cevro-conversation-card__content"}),i=ke("div",{className:"cevro-conversation-card__title-row"}),n=ke("span",{className:"cevro-conversation-card__title"},[e.title||this.strings.defaultConversationTitle]),o=ke("span",{className:"cevro-conversation-card__date"},[this.formatDate(e.lastMessageAt||e.createdAt)]);i.appendChild(n),i.appendChild(o);const r=ke("div",{className:"cevro-conversation-card__preview"},[e.lastMessageBody||`${e.messageCount} ${this.strings.messagesCount}`]);return s.appendChild(i),s.appendChild(r),t.appendChild(s),t.addEventListener("click",()=>{this.callbacks.onSelectPast(e.ticketId,e.title)}),t}showEmptyState(){if(!this.listContainer)return;const e=ke("div",{className:"cevro-conversation-list__empty"}),t=ke("p",{className:"cevro-conversation-list__empty-title"},[this.strings.noConversations]),s=ke("p",{className:"cevro-conversation-list__empty-subtitle"},[this.strings.noConversationsSubtitle]);e.appendChild(t),e.appendChild(s),this.listContainer.appendChild(e)}formatDate(e){try{const t=new Date(e),s=(new Date).getTime()-t.getTime(),i=Math.floor(s/864e5);return 0===i?t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):1===i?this.strings.yesterday:i<7?t.toLocaleDateString([],{weekday:"short"}):t.toLocaleDateString([],{month:"short",day:"numeric"})}catch{return""}}show(){this.element&&(this.element.style.display="flex")}hide(){this.element&&(this.element.style.display="none")}destroy(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.listContainer=null}}const ze=class e{constructor(e,s){t(this,"element",null),t(this,"avatarElement",null),t(this,"titleElement",null),t(this,"avatarUrl"),t(this,"messageList"),t(this,"callbacks"),t(this,"strings"),t(this,"currentTicketId",null),t(this,"cursor"),t(this,"hasMore",!1),t(this,"isLoadingMore",!1),this.callbacks=e,this.strings=s,this.messageList=new Pe}setStrings(e){this.strings=e}setAvatarUrl(e){this.avatarUrl=e,this.renderAvatar()}renderAvatar(){this.avatarElement&&(this.avatarUrl?this.avatarElement.innerHTML=`<img src="${this.avatarUrl}" alt="Agent" class="cevro-past-conversation__avatar-img" />`:this.avatarElement.innerHTML=e.DEFAULT_AVATAR_SVG)}render(){if(this.element)return this.element;this.element=ke("div",{className:"cevro-past-conversation"});const e=ke("div",{className:"cevro-past-conversation__header"}),t=ke("button",{className:"cevro-past-conversation__back","aria-label":"Back"});t.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <polyline points="15 18 9 12 15 6"/>\n </svg>\n ',t.addEventListener("click",()=>this.callbacks.onBack()),this.avatarElement=ke("div",{className:"cevro-past-conversation__avatar"}),this.renderAvatar(),this.titleElement=ke("h2",{className:"cevro-past-conversation__title"});const s=ke("button",{className:"cevro-past-conversation__close","aria-label":"Close"});s.innerHTML='\n <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <line x1="18" y1="6" x2="6" y2="18"/>\n <line x1="6" y1="6" x2="18" y2="18"/>\n </svg>\n ',s.addEventListener("click",()=>this.callbacks.onClose()),e.appendChild(t),e.appendChild(this.avatarElement),e.appendChild(this.titleElement),e.appendChild(s),this.element.appendChild(e);const i=this.messageList.render();this.messageList.setScrollTopHandler(()=>this.loadMoreMessages()),this.element.appendChild(i);const n=ke("button",{className:"cevro-past-conversation__new-conversation"},[this.strings.newConversationButton]);n.addEventListener("click",()=>this.callbacks.onNewConversation()),this.element.appendChild(n);const o=ke("div",{className:"cevro-past-conversation__footer"});return o.innerHTML=`${this.strings.poweredBy.replace("Cevro AI",'<a href="https://cevro.ai" target="_blank" rel="noopener">Cevro AI</a>')}`,this.element.appendChild(o),this.element}async loadConversation(e,t){this.titleElement&&(this.titleElement.textContent=t),this.currentTicketId=e,this.cursor=void 0,this.hasMore=!1,this.messageList.clear();try{const t=await this.callbacks.onLoadMessages(e);if(this.currentTicketId!==e)return;this.cursor=t.cursor,this.hasMore=t.hasMore;for(const e of t.messages)this.messageList.addMessage(e,!1,!0);this.messageList.scrollToBottom()}catch(s){console.error("[Cevro] Failed to load conversation messages:",s)}}async loadMoreMessages(){if(!this.currentTicketId||!this.hasMore||this.isLoadingMore)return!1;const e=this.currentTicketId;this.isLoadingMore=!0;try{const t=await this.callbacks.onLoadMessages(e,this.cursor);return this.currentTicketId===e&&(this.cursor=t.cursor,this.hasMore=t.hasMore,this.messageList.prependMessages(t.messages),!0)}catch(t){return console.error("[Cevro] Failed to load more messages:",t),!1}finally{this.isLoadingMore=!1,this.messageList.finishLoadingTop()}}show(){this.element&&(this.element.style.display="flex")}hide(){this.element&&(this.element.style.display="none")}destroy(){this.messageList.destroy(),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.avatarElement=null,this.titleElement=null}};t(ze,"DEFAULT_AVATAR_SVG",'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="cevro-past-conversation__avatar-icon"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>');let Re=ze;const He=class e{constructor(s){t(this,"config"),t(this,"events"),t(this,"api"),t(this,"ws"),t(this,"launcher",null),t(this,"chatWindow",null),t(this,"conversationList",null),t(this,"pastConversation",null),t(this,"currentScreen","chat"),t(this,"container",null),t(this,"shadowRoot",null),t(this,"isBooted",!1),t(this,"isVisible",!1),t(this,"unreadCount",0),t(this,"visitorId"),t(this,"isSessionInitialized",!1),t(this,"isInitializingSession",null),t(this,"connectingPromise",null),t(this,"typingCycleTimeout",null),t(this,"isTypingVisible",!1),t(this,"typingConfig",{onDurationMs:7e3,offDurationMs:4e3}),t(this,"escapeHandler",null),t(this,"visitorContactInfo",null),t(this,"widgetAppearance",{}),t(this,"customLauncherHandler",null),t(this,"customLauncherElement",null),t(this,"isDestroyed",!1),this.config=this.normalizeConfig(s),this.events=new i,this.api=new k(this.config),this.ws=new Ce(this.config,this.events),this.visitorId=u(),this.ws.setTokenRefreshCallback(async()=>this.refreshConnectionToken()),this.setupEventHandlers(),e.instance=this}static getInstance(){return e.instance}normalizeConfig(e){return{...e,apiBase:e.apiBase.replace(/\/$/,""),alignment:e.alignment||"right",verticalPadding:e.verticalPadding??20,horizontalPadding:e.horizontalPadding??20,zIndex:e.zIndex??2147483647}}setupEventHandlers(){this.events.on("message:received",e=>{this.stopTypingCycle(),this.chatWindow&&this.chatWindow.addMessage(e.message),this.isVisible||this.setUnreadCount(this.unreadCount+1)}),this.events.on("typing:start",e=>{e.ticketId===this.api.getCurrentTicketId()&&this.startTypingCycle()}),this.events.on("typing:stop",()=>{this.stopTypingCycle()}),this.events.on("conversation:updated",e=>{var t,s;if(e.ticketId===this.api.getCurrentTicketId()){if("escalated"===e.status){const s=e.agentName||"Support",i=e.message||`${s} has joined the conversation.`;null==(t=this.chatWindow)||t.addMessage({id:`escalation-${Date.now()}`,body:i,inbound:!1,outbound:!0,createdAt:(new Date).toISOString(),type:"text",senderType:"human",agentName:s})}if("closed"===e.status){const t=!0!==this.widgetAppearance.csatEnabled;null==(s=this.chatWindow)||s.setTicketClosed(!0,()=>this.startNewChat(),{ticketId:e.ticketId,skipCSAT:t})}}})}async boot(){if(this.isBooted)return;if(this.isDestroyed=!1,!this.config.preview){const e=await h();e&&this.api.setVisitorToken(e)}if(!this.config.preview)try{this.widgetAppearance=await this.api.getWidgetConfig()}catch{this.widgetAppearance={}}if(this.isBooted||this.isDestroyed)return;const e=document.createElement("div");e.id="cevro-messenger-host",document.body.appendChild(e),this.shadowRoot=e.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=s,this.shadowRoot.appendChild(t),this.container=document.createElement("div"),this.container.id="cevro-messenger-container",this.shadowRoot.appendChild(this.container),this.applyPrimaryColor(),this.config.hideDefaultLauncher||this.createAndMountLauncher();const i=Ne(this.config.locale);this.chatWindow=new Ae(this.config,{onClose:()=>this.hide(),onSendMessage:e=>this.sendMessage(e),onQuickAction:e=>this.handleQuickAction(e),onFileUpload:e=>this.handleFileUpload(e),onCSATSubmit:async(e,t)=>this.submitCSAT(e,t),onStartNewChat:()=>this.startNewChat(),onPreChatSubmit:e=>this.handlePreChatSubmit(e),onShowHistory:()=>this.navigateTo("history")},i,this.widgetAppearance.customLogoUrl),this.container.appendChild(this.chatWindow.render()),this.createConversationList(i),this.createPastConversation(i);const n=function(){try{const e=localStorage.getItem(o);return e?JSON.parse(e):null}catch{return null}}();(null==n?void 0:n.ticketId)&&this.api.setCurrentTicketId(n.ticketId),this.config.customLauncherSelector&&this.bindCustomLauncher(this.config.customLauncherSelector),this.isBooted=!0,this.events.emit("boot"),this.widgetAppearance.autoOpen&&setTimeout(()=>this.show(),100)}applyPrimaryColor(){const e=this.widgetAppearance.primaryColor||this.config.primaryColor;if(e&&this.container){this.container.style.setProperty("--cevro-primary",e);const t=this.adjustColorBrightness(e,-20),s=this.adjustColorBrightness(e,40);this.container.style.setProperty("--cevro-primary-hover",t),this.container.style.setProperty("--cevro-primary-light",s)}this.applyTheme()}applyTheme(){if(!this.container)return;const e=this.widgetAppearance.theme,t=this.config.theme;if(!e&&!t)return;const s={...e,...t};this.applyCustomTheme(s)}applyCustomTheme(e){if(!this.container)return;const t=["--cevro-bg","--cevro-bg-secondary","--cevro-text","--cevro-text-secondary","--cevro-border","--cevro-user-msg-bg","--cevro-user-msg-text","--cevro-header-bg","--cevro-header-text","--cevro-bg-input","--cevro-radius","--cevro-radius-sm","--cevro-shadow","--cevro-shadow-sm","--cevro-launcher-bg","--cevro-launcher-icon","--cevro-launcher-hover-shadow","--cevro-send-btn-bg","--cevro-send-btn-icon","--cevro-file-btn-bg","--cevro-file-btn-icon","--cevro-agent-msg-bg","--cevro-agent-msg-text"];for(const s of t)this.container.style.removeProperty(s);e.backgroundColor&&this.container.style.setProperty("--cevro-bg",e.backgroundColor),e.backgroundSecondaryColor&&this.container.style.setProperty("--cevro-bg-secondary",e.backgroundSecondaryColor),e.textColor&&this.container.style.setProperty("--cevro-text",e.textColor),e.textSecondaryColor&&this.container.style.setProperty("--cevro-text-secondary",e.textSecondaryColor),e.borderColor&&this.container.style.setProperty("--cevro-border",e.borderColor),e.userMessageBackgroundColor&&this.container.style.setProperty("--cevro-user-msg-bg",e.userMessageBackgroundColor),e.userMessageTextColor&&this.container.style.setProperty("--cevro-user-msg-text",e.userMessageTextColor),e.headerBackgroundColor&&this.container.style.setProperty("--cevro-header-bg",e.headerBackgroundColor),e.headerTextColor&&this.container.style.setProperty("--cevro-header-text",e.headerTextColor),e.inputBackgroundColor&&this.container.style.setProperty("--cevro-bg-input",e.inputBackgroundColor),void 0!==e.borderRadius&&(this.container.style.setProperty("--cevro-radius",`${e.borderRadius}px`),this.container.style.setProperty("--cevro-radius-sm",`${Math.max(4,e.borderRadius-4)}px`)),e.shadowColor&&(this.container.style.setProperty("--cevro-shadow",`0 10px 40px ${e.shadowColor}`),this.container.style.setProperty("--cevro-shadow-sm",`0 2px 8px ${e.shadowColor}`)),e.launcherBackgroundColor&&this.container.style.setProperty("--cevro-launcher-bg",e.launcherBackgroundColor),e.launcherIconColor&&this.container.style.setProperty("--cevro-launcher-icon",e.launcherIconColor),e.launcherHoverShadowColor&&this.container.style.setProperty("--cevro-launcher-hover-shadow",e.launcherHoverShadowColor),e.sendButtonBackgroundColor&&this.container.style.setProperty("--cevro-send-btn-bg",e.sendButtonBackgroundColor),e.sendButtonIconColor&&this.container.style.setProperty("--cevro-send-btn-icon",e.sendButtonIconColor),e.fileButtonBackgroundColor&&this.container.style.setProperty("--cevro-file-btn-bg",e.fileButtonBackgroundColor),e.fileButtonIconColor&&this.container.style.setProperty("--cevro-file-btn-icon",e.fileButtonIconColor),e.agentMessageBackgroundColor&&this.container.style.setProperty("--cevro-agent-msg-bg",e.agentMessageBackgroundColor),e.agentMessageTextColor&&this.container.style.setProperty("--cevro-agent-msg-text",e.agentMessageTextColor)}adjustColorBrightness(e,t){e=e.replace(/^#/,"");const s=parseInt(e,16);let i=(s>>16)+t,n=(s>>8&255)+t,o=(255&s)+t;return i=Math.max(0,Math.min(255,i)),n=Math.max(0,Math.min(255,n)),o=Math.max(0,Math.min(255,o)),`#${(i<<16|n<<8|o).toString(16).padStart(6,"0")}`}createAndMountLauncher(){this.container&&(this.launcher=new Le(this.config,()=>this.toggle(),this.widgetAppearance.bubbleIconUrl),this.container.appendChild(this.launcher.render()))}createConversationList(e){if(!this.container)return;this.conversationList=new Be({onClose:()=>this.hide(),onNewConversation:async()=>{this.navigateTo("chat"),await this.startNewChat()},onSelectActive:()=>{this.navigateTo("chat")},onSelectPast:(e,t)=>{var s;this.navigateTo("past-conversation"),null==(s=this.pastConversation)||s.loadConversation(e,t)},onLoadConversations:e=>this.api.getConversations(e)},e);const t=this.conversationList.render();t.style.display="none",this.container.appendChild(t)}createPastConversation(e){if(!this.container)return;this.pastConversation=new Re({onBack:()=>this.navigateTo("history"),onClose:()=>this.hide(),onNewConversation:async()=>{this.navigateTo("chat"),await this.startNewChat()},onLoadMessages:(e,t)=>this.api.getConversationMessages(e,t)},e);const t=this.pastConversation.render();this.pastConversation.setAvatarUrl(this.widgetAppearance.customLogoUrl),t.style.display="none",this.container.appendChild(t)}navigateTo(e){var t,s,i,n,o,r,a,c,l,h,d,u,p;switch(this.currentScreen=e,null==(t=this.chatWindow)||t.hide(),null==(s=this.conversationList)||s.hide(),null==(i=this.pastConversation)||i.hide(),e){case"chat":null==(n=this.chatWindow)||n.show();break;case"history":this.isSessionInitialized&&this.api.getCurrentTicketId()?null==(l=this.conversationList)||l.setActiveConversation({ticketId:this.api.getCurrentTicketId(),lastMessageBody:null==(o=this.chatWindow)?void 0:o.getLastMessageBody(),lastMessageAt:null==(r=this.chatWindow)?void 0:r.getLastMessageAt(),agentName:null==(a=this.api.getCurrentAgent())?void 0:a.name,unreadCount:(null==(c=this.chatWindow)?void 0:c.getAgentMessagesSinceLastUserMessage())??0}):null==(h=this.conversationList)||h.setActiveConversation(null),null==(d=this.conversationList)||d.show(),null==(u=this.conversationList)||u.load();break;case"past-conversation":null==(p=this.pastConversation)||p.show()}}bindCustomLauncher(e){const t=document.querySelector(e);t?(this.customLauncherHandler=()=>this.toggle(),this.customLauncherElement=t,t.addEventListener("click",this.customLauncherHandler)):console.warn(`[CevroMessenger] customLauncherSelector "${e}" did not match any element`)}async connectWebSocket(){return this.connectingPromise||(this.connectingPromise=this.doConnectWebSocket()),this.connectingPromise}async doConnectWebSocket(){try{const e=l(),t=await this.api.getConnectionToken(e);this.visitorId=t.visitorId,t.visitorToken&&(d(t.visitorToken),this.api.setVisitorToken(t.visitorToken)),this.ws.connect(t.visitorId,t.token),this.events.emit("ready")}catch(e){this.events.emit("ready"),this.events.emit("error",{type:"websocket_connect",error:e})}finally{this.connectingPromise=null}}async refreshConnectionToken(){const e=l(),t=await this.api.getConnectionToken(e);return t.visitorToken&&(d(t.visitorToken),this.api.setVisitorToken(t.visitorToken)),t.token}shutdown(e){var t,s,i,n,o;if(this.isDestroyed=!0,!this.isBooted)return void((null==e?void 0:e.clearVisitorData)&&(m(),f(),g(),this.visitorId=null));this.stopTypingCycle(),this.ws.disconnect(),this.customLauncherElement&&this.customLauncherHandler&&(this.customLauncherElement.removeEventListener("click",this.customLauncherHandler),this.customLauncherElement=null,this.customLauncherHandler=null),null==(t=this.launcher)||t.destroy(),null==(s=this.chatWindow)||s.destroy(),null==(i=this.conversationList)||i.destroy(),null==(n=this.pastConversation)||n.destroy();const r=null==(o=this.shadowRoot)?void 0:o.host;r&&r.parentNode&&r.parentNode.removeChild(r),this.shadowRoot=null,m(),(null==e?void 0:e.clearVisitorData)&&(f(),g(),this.visitorId=null),this.api.clear(),this.launcher=null,this.chatWindow=null,this.conversationList=null,this.pastConversation=null,this.currentScreen="chat",this.container=null,this.isBooted=!1,this.isVisible=!1,this.unreadCount=0,this.isSessionInitialized=!1,this.isInitializingSession=null,this.connectingPromise=null,this.events.emit("shutdown")}async show(){var e;this.isBooted||await this.boot(),this.chatWindow&&(this.navigateTo(this.currentScreen),this.isVisible=!0,null==(e=this.launcher)||e.setState(!0),this.setUnreadCount(0),this.events.emit("show"),this.escapeHandler||(this.escapeHandler=e=>{"Escape"===e.key&&this.hide()},document.addEventListener("keydown",this.escapeHandler)),this.config.preview||(await this.connectWebSocket(),this.visitorId&&this.api.setVisitorId(this.visitorId),await this.initializeSession()))}async initializeSession(e=!1){if(e&&(this.isSessionInitialized=!1,this.isInitializingSession=null),this.isSessionInitialized)return;if(this.isInitializingSession)return this.isInitializingSession;const t=this.doInitializeSession().finally(()=>{this.isInitializingSession===t&&(this.isInitializingSession=null)});return this.isInitializingSession=t,t}async doInitializeSession(e){var t,s,i,n,r,a,c,l,h;try{const d=await this.api.initSession(this.visitorId,this.visitorContactInfo,e);if(d.requireContactInfo&&d.missingFields&&d.missingFields.length>0)return void(null==(t=this.chatWindow)||t.showPreChatForm());if(function(e,t,s){try{localStorage.setItem(o,JSON.stringify({sessionId:e,contactId:t,ticketId:s}))}catch{}}(d.sessionId,d.contactId,d.ticketId),this.isSessionInitialized=!0,d.agent&&this.chatWindow&&this.chatWindow.setAgent(d.agent),d.typingConfig&&(this.typingConfig=d.typingConfig),d.locale&&this.chatWindow){const e=Ne(this.config.locale,d.locale);this.chatWindow.setStrings(e),null==(s=this.conversationList)||s.setStrings(e),null==(i=this.pastConversation)||i.setStrings(e)}if(null==(n=this.chatWindow)||n.setScrollTopHandler(null),d.messages&&d.messages.length>0){for(const e of d.messages)null==(r=this.chatWindow)||r.addMessage(e);if(d.ticketId){let e=d.cursor||(null==(a=d.messages[0])?void 0:a.createdAt),t=!1;null==(c=this.chatWindow)||c.setScrollTopHandler(async()=>{var s,i,n;if(!t&&e){t=!0;try{const t=await this.api.getConversationMessages(d.ticketId,e);null==(s=this.chatWindow)||s.prependMessages(t.messages),e=t.hasMore?t.cursor||(null==(i=t.messages[0])?void 0:i.createdAt):void 0}catch(o){console.error("[Cevro] Failed to load older messages:",o)}finally{t=!1,null==(n=this.chatWindow)||n.finishLoadingTop()}}})}}if(d.ticketClosed){const e=!0!==this.widgetAppearance.csatEnabled;null==(l=this.chatWindow)||l.setTicketClosed(!0,()=>this.startNewChat(),{ticketId:d.ticketId,skipCSAT:e})}this.events.emit("session:initialized",{sessionId:d.sessionId,contactId:d.contactId,ticketId:d.ticketId,isNewSession:d.isNewSession,isNewTicket:d.isNewTicket,ticketClosed:d.ticketClosed,messageCount:(null==(h=d.messages)?void 0:h.length)||0})}catch(d){throw this.events.emit("error",{type:"session_init",error:d}),d}}async submitCSAT(e,t){const s=this.api.getCurrentTicketId(),i=this.api.getContactId();if(!s||!i)throw new Error("No active session");await this.api.submitCSAT(s,i,e,t)}async startNewChat(){var e,t;this.navigateTo("chat"),null==(e=this.chatWindow)||e.clearMessages(),null==(t=this.chatWindow)||t.setTicketClosed(!1),this.isSessionInitialized=!1,await this.doInitializeSession({forceNewTicket:!0}),this.events.emit("chat:new_started")}hide(){var e,t,s;this.chatWindow&&(this.chatWindow.hide(),null==(e=this.conversationList)||e.hide(),null==(t=this.pastConversation)||t.hide(),this.isVisible=!1,null==(s=this.launcher)||s.setState(!1),this.events.emit("hide"),this.escapeHandler&&(document.removeEventListener("keydown",this.escapeHandler),this.escapeHandler=null))}showLauncher(){var e;this.isBooted&&(this.launcher||this.createAndMountLauncher(),null==(e=this.launcher)||e.setVisible(!0))}hideLauncher(){var e;this.isBooted&&(null==(e=this.launcher)||e.setVisible(!1))}toggle(){this.isVisible?this.hide():this.show()}setDraft(e){var t;null==(t=this.chatWindow)||t.setDraft(e)}async sendMessage(t){var s,i,n,o,r,a,c,l,h,d,u,p;if(!t.trim())return;if(t.length>e.MAX_MESSAGE_LENGTH)return void this.events.emit("error",{type:"validation",error:new Error(`Message is too long. Maximum ${e.MAX_MESSAGE_LENGTH} characters allowed.`),message:`Message is too long. Maximum ${e.MAX_MESSAGE_LENGTH} characters allowed.`});const v={id:"temp_"+Date.now(),body:t,inbound:!0,outbound:!1,createdAt:(new Date).toISOString(),type:"text",status:"sending"};if(null==(s=this.chatWindow)||s.addMessage(v),this.config.preview)return v.status="sent",void(null==(i=this.chatWindow)||i.updateMessage(v));try{this.isSessionInitialized||await this.initializeSession();const e=v.id,s=await this.api.sendMessage(t);v.id=s.id,v.status="sent",null==(n=this.chatWindow)||n.updateMessage(v,e),this.events.emit("message:sent",{message:s})}catch(g){if((null==(o=null==g?void 0:g.message)?void 0:o.includes("closed"))||(null==(r=null==g?void 0:g.message)?void 0:r.includes("resolved"))||(null==(a=null==g?void 0:g.message)?void 0:a.includes("escalated"))||(null==(h=null==(l=null==(c=null==g?void 0:g.response)?void 0:c.data)?void 0:l.message)?void 0:h.includes("closed"))){null==(d=this.chatWindow)||d.removeMessage(v.id);const e=this.api.getCurrentTicketId()||void 0;return void(null==(u=this.chatWindow)||u.setTicketClosed(!0,()=>this.startNewChat(),{ticketId:e,skipCSAT:!0!==this.widgetAppearance.csatEnabled}))}v.status="failed",null==(p=this.chatWindow)||p.updateMessage(v),this.events.emit("error",{error:g,type:"send_message"})}}async handleQuickAction(e){"link"===e.type&&e.url?Se(e.url)&&window.open(e.url,"_blank"):await this.sendMessage(e.value||e.label)}async handlePreChatSubmit(e){var t;this.visitorContactInfo=e,null==(t=this.chatWindow)||t.hidePreChatForm(),await this.initializeSession()}async handleFileUpload(e){var t,s,i;let n,o;try{this.isSessionInitialized||await this.initializeSession();const i=e.type.startsWith("image/"),r=this.getFileCategory(e.type);n=i?URL.createObjectURL(e):void 0,o="temp_"+Date.now();const a={id:o,body:"",inbound:!0,outbound:!1,createdAt:(new Date).toISOString(),type:i?"image":"file",mediaUrl:n,mediaType:e.type,status:"sending",attachment:{filename:e.name,contentType:e.type||"application/octet-stream",size:e.size,category:r}};null==(t=this.chatWindow)||t.addMessage(a);const c=await this.api.uploadFile(e,e=>{var t;null==(t=this.chatWindow)||t.updateMessageProgress(o,e)}),l=await this.api.sendMessage("",c),h=l.mediaUrl&&Se(l.mediaUrl),d={...l,status:"sent",type:i?"image":"file",mediaUrl:h?l.mediaUrl:n,attachment:a.attachment};null==(s=this.chatWindow)||s.updateMessage(d,o),n&&h&&URL.revokeObjectURL(n),this.events.emit("message:sent",{type:r,fileName:e.name})}catch(r){n&&URL.revokeObjectURL(n),o&&(null==(i=this.chatWindow)||i.removeMessage(o));const t=(null==r?void 0:r.message)||"File upload failed",s=t.includes("too large")||t.includes("too small")||t.includes("not allowed")||t.includes("Too many uploads");this.events.emit("error",{error:r,type:s?"file_validation":"file_upload",message:t,fileName:e.name})}}getFileCategory(e){return e.startsWith("image/")?"image":"application/pdf"===e?"pdf":e.includes("word")||e.includes("document")?"document":e.includes("sheet")||e.includes("excel")?"spreadsheet":e.includes("presentation")||e.includes("powerpoint")?"presentation":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":e.includes("zip")||e.includes("archive")||e.includes("compressed")?"archive":e.startsWith("text/")?"text":"file"}setUnreadCount(e){var t;this.unreadCount=e,null==(t=this.launcher)||t.setUnreadCount(e),this.events.emit("unread_count_change",{count:e})}updateAppearance(e){this.widgetAppearance={...this.widgetAppearance,...e},"primaryColor"in e&&this.applyPrimaryColor(),"theme"in e&&this.applyTheme(),"bubbleIconUrl"in e&&this.launcher&&this.launcher.updateBubbleIcon(e.bubbleIconUrl),"customLogoUrl"in e&&this.chatWindow&&this.chatWindow.updateCustomLogo(e.customLogoUrl),this.events.emit("appearance:updated",this.widgetAppearance)}getAppearance(){return{...this.widgetAppearance}}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t)}getUnreadCount(){return this.unreadCount}getVisitorId(){return this.visitorId}update(e){this.config=this.normalizeConfig({...this.config,...e}),this.api.updateConfig(this.config),this.ws.updateConfig(this.config)}async identify(e){var t;this.config.player={...this.config.player,...e};if(!!e.playerId&&v(e.playerId)&&(m(),f()),this.api.updateConfig(this.config),this.ws.updateConfig(this.config),!this.isBooted)return;const s=this.isVisible;this.ws.disconnect(),this.api.clear(),m(),this.isSessionInitialized=!1,this.isInitializingSession=null,this.connectingPromise=null;try{await this.connectWebSocket(),null==(t=this.chatWindow)||t.clearMessages(),await this.initializeSession(!0),s&&this.chatWindow&&this.chatWindow.show(),this.events.emit("identify",{playerId:e.playerId})}catch(i){this.events.emit("error",{type:"identify",error:i})}}addPreviewMessage(e,t=!0){if(!this.config.preview||!this.chatWindow)return;const s={id:"preview_"+Date.now(),body:e,inbound:!t,outbound:t,createdAt:(new Date).toISOString(),type:"text",status:"sent"};this.chatWindow.addMessage(s)}setPreviewTyping(e){this.config.preview&&this.chatWindow&&(e?this.chatWindow.showTypingIndicator():this.chatWindow.hideTypingIndicator())}setPreviewAgent(e,t){this.config.preview&&this.chatWindow&&this.chatWindow.setAgent({name:e,avatarUrl:t})}startTypingCycle(){var e;this.stopTypingCycle();const{onDurationMs:t,offDurationMs:s}=this.typingConfig,i=()=>{var e,n;this.isTypingVisible?(null==(e=this.chatWindow)||e.hideTypingIndicator(),this.isTypingVisible=!1,this.typingCycleTimeout=setTimeout(i,s)):(null==(n=this.chatWindow)||n.showTypingIndicator(),this.isTypingVisible=!0,this.typingCycleTimeout=setTimeout(i,t))};null==(e=this.chatWindow)||e.showTypingIndicator(),this.isTypingVisible=!0,this.typingCycleTimeout=setTimeout(i,t)}stopTypingCycle(){var e;this.typingCycleTimeout&&(clearTimeout(this.typingCycleTimeout),this.typingCycleTimeout=null),this.isTypingVisible&&(null==(e=this.chatWindow)||e.hideTypingIndicator(),this.isTypingVisible=!1)}};t(He,"instance",null),t(He,"MAX_MESSAGE_LENGTH",2e3);let Ue=He;"undefined"!=typeof window&&(window.CevroMessenger=Ue),exports.CevroMessenger=Ue,exports.__styles=s,exports.default=Ue;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|