cevro-messenger-sdk 0.1.12 → 0.1.13
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 +13 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/types/i18n/strings.d.ts +2 -0
- package/dist/types/i18n/strings.d.ts.map +1 -1
- package/dist/types/ui/ChatWindow.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-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 - 140px);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:none}@media (max-width: 480px){.cevro-chat-window{width:100%;height:100%;max-height:100%;bottom:0;right:0;left:0;border-radius:0}}.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:4px;margin:-4px;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__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__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__text a{color:inherit;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:#ffffffb3;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;border:1px solid var(--cevro-border);border-radius:20px;padding:8px 16px;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)}.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}.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 #8b5cf61a}.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)}.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 #8b5cf61a}.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 #ef44441a}.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}()}function a(){try{localStorage.removeItem("cevro_session")}catch{}}const c=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"]),l=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"]),h={maxSizeBytes:26214400,minSizeBytes:1,maxFilenameLength:255};function d(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?"":e.substring(t).toLowerCase()}function u(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 p{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 g{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 p}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=h.maxSizeBytes,minSizeBytes:s=h.minSizeBytes,allowedMimeTypes:n=c,blockedExtensions:r=l,maxFilenameLength:o=h.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 ${u(s)}`,errorCode:"FILE_TOO_SMALL"};if(e.size>i)return{valid:!1,error:`File is too large. Maximum size is ${u(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=d(e.name);if(a&&r.has(a))return{valid:!1,error:`File type "${a}" is not allowed for security reasons`,errorCode:"BLOCKED_EXTENSION"};const p=e.type||"application/octet-stream";return n.has(p)||"application/octet-stream"===p&&a&&!r.has(a)?{valid:!0}:{valid:!1,error:`File type "${p}" 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>h.maxFilenameLength){const e=d(t),i=t.slice(0,-e.length||void 0),s=h.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 v(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 m(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var f,_={exports:{}},b="object"==typeof Reflect?Reflect:null,w=b&&"function"==typeof b.apply?b.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};f=b&&"function"==typeof b.ownKeys?b.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var y=Number.isNaN||function(e){return e!=e};function C(){C.init.call(this)}_.exports=C,_.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))}A(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&A(e,"error",t,i)}(e,n,{once:!0})})},C.EventEmitter=C,C.prototype._events=void 0,C.prototype._eventsCount=0,C.prototype._maxListeners=void 0;var x=10;function k(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function T(e){return void 0===e._maxListeners?C.defaultMaxListeners:e._maxListeners}function S(e,t,i,s){var n,r,o,a;if(k(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=T(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 I(){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 E(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=I.bind(s);return n.listener=i,s.wrapFn=n,n}function M(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):P(n,n.length)}function L(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 P(e,t){for(var i=new Array(t),s=0;s<t;++s)i[s]=e[s];return i}function A(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(C,"defaultMaxListeners",{enumerable:!0,get:function(){return x},set:function(e){if("number"!=typeof e||e<0||y(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");x=e}}),C.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},C.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||y(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},C.prototype.getMaxListeners=function(){return T(this)},C.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)w(a,this,t);else{var c=a.length,l=P(a,c);for(i=0;i<c;++i)w(l[i],this,t)}return!0},C.prototype.addListener=function(e,t){return S(this,e,t,!1)},C.prototype.on=C.prototype.addListener,C.prototype.prependListener=function(e,t){return S(this,e,t,!0)},C.prototype.once=function(e,t){return k(t),this.on(e,E(this,e,t)),this},C.prototype.prependOnceListener=function(e,t){return k(t),this.prependListener(e,E(this,e,t)),this},C.prototype.removeListener=function(e,t){var i,s,n,r,o;if(k(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},C.prototype.off=C.prototype.removeListener,C.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},C.prototype.listeners=function(e){return M(this,e,!0)},C.prototype.rawListeners=function(e){return M(this,e,!1)},C.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):L.call(e,t)},C.prototype.listenerCount=L,C.prototype.eventNames=function(){return this._eventsCount>0?f(this._events):[]};var N,R,z,B,F,U,H,O,j,V,D,W,$,q,Z,J,G=m(_.exports);function Y(e){return null!=e&&"function"==typeof e}function X(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 Q(e){return Math.min(1e3*e,2147483647)}(R=N||(N={}))[R.timeout=1]="timeout",R[R.transportClosed=2]="transportClosed",R[R.clientDisconnected=3]="clientDisconnected",R[R.clientClosed=4]="clientClosed",R[R.clientConnectToken=5]="clientConnectToken",R[R.clientRefreshToken=6]="clientRefreshToken",R[R.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",R[R.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",R[R.subscriptionRefreshToken=9]="subscriptionRefreshToken",R[R.transportWriteError=10]="transportWriteError",R[R.connectionClosed=11]="connectionClosed",R[R.badConfiguration=12]="badConfiguration",(B=z||(z={}))[B.connectCalled=0]="connectCalled",B[B.transportClosed=1]="transportClosed",B[B.noPing=2]="noPing",B[B.subscribeTimeout=3]="subscribeTimeout",B[B.unsubscribeError=4]="unsubscribeError",(U=F||(F={}))[U.disconnectCalled=0]="disconnectCalled",U[U.unauthorized=1]="unauthorized",U[U.badProtocol=2]="badProtocol",U[U.messageSizeLimit=3]="messageSizeLimit",(O=H||(H={}))[O.subscribeCalled=0]="subscribeCalled",O[O.transportClosed=1]="transportClosed",(V=j||(j={}))[V.unsubscribeCalled=0]="unsubscribeCalled",V[V.unauthorized=1]="unauthorized",V[V.clientClosed=2]="clientClosed",(W=D||(D={}))[W.channelCompaction=1]="channelCompaction",(q=$||($={})).Disconnected="disconnected",q.Connecting="connecting",q.Connected="connected",(J=Z||(Z={})).Unsubscribed="unsubscribed",J.Subscribing="subscribing",J.Subscribed="subscribed";class K extends G{constructor(e,t,i){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this.channel=t,this.state=Z.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===Z.Unsubscribed?Promise.reject({code:N.subscriptionUnsubscribed,message:this.state}):this.state===Z.Subscribed?Promise.resolve():new Promise((t,i)=>{const s={resolve:t,reject:i};e&&(s.timeout=setTimeout(function(){i({code:N.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=s})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(H.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(j.unsubscribeCalled,"unsubscribe called",!0)}publish(e){return v(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.publish(this.channel,e)})}presence(){return v(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return v(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)})}history(e){return v(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:N.subscriptionUnsubscribed,message:this.state}):new Promise((e,t)=>{const i=this._centrifuge._config.timeout,s=setTimeout(()=>{t({code:N.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===Z.Unsubscribed}_isSubscribing(){return this.state===Z.Subscribing}_isSubscribed(){return this.state===Z.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(Z.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(),Q(e.ttl)))}_setSubscribing(e,t){return v(this,0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState(Z.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 de)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:N.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 de)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:N.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=D.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!==N.timeout?this._subscribeError(e):this._centrifuge._disconnect(z.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(Z.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:N.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===$.Connected&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){const e=X(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:N.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new de(""))):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 de?e._failUnauthorized():(e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:N.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(),Q(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 X(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(j.unauthorized,"unauthorized",!0)}}class ee{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 te{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 ie{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 se{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 ne{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 v(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 v(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 v(this,0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}})}send(e){return v(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 re=[-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 oe{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=re[127&this.getByte()])>=0;)t=(t<<6)+e;return this.pos--,t>>>0}}class ae{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 ce(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 le{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 oe(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 ae;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!==ce(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 he={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 de extends Error{constructor(e){super(e),this.name=this.constructor.name}}class ue extends G{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=$.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 le,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({},he),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 K(this,e,t);return this._subs[e]=i,i}getSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==Z.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}subscriptions(){return this._subs}ready(e){return v(this,0,void 0,function*(){switch(this.state){case $.Disconnected:throw{code:N.clientDisconnected,message:"client disconnected"};case $.Connected:return;default:return new Promise((t,i)=>{const s={resolve:t,reject:i};e&&(s.timeout=setTimeout(()=>{i({code:N.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(F.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return v(this,0,void 0,function*(){const t={send:{data:e}};yield this._methodCall();if(!this._transportSendCommands([t]))throw this._createErrorObject(N.transportWriteError,"transport write error")})}rpc(e,t){return v(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 v(this,0,void 0,function*(){const i={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}history(e,t){return v(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 v(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 v(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];Y(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 le,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===$.Disconnected}_isConnecting(){return this.state===$.Connecting}_isConnected(){return this.state===$.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!==$.Connected&&this.state!==$.Connecting||(this._disconnect(z.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===$.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=X(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(N.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===Z.Subscribed&&t._setSubscribing(H.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(N.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 te(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 ne(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 ie(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 se(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 ee(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 te(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=F.messageSizeLimit,t="message size limit exceeded",i=!1):(s=z.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:N.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 de)return void t._failUnauthorized();t.emit("error",{type:"connectToken",error:{code:N.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 de)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:N.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===$.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:N.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($.Connecting)&&this.emit("connecting",{code:z.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($.Connecting):(r=this._setState($.Disconnected),this._rejectPromises({code:N.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),s===$.Connecting&&this._clearReconnectTimeout(),s===$.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(F.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:N.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new de("")))}_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 de?t._failUnauthorized():(t.emit("error",{type:"refreshToken",error:{code:N.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 X(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),Q(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(z.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===Z.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($.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),Q(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(z.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],Y(i)&&i({error:this._createErrorObject(N.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])}}ue.SubscriptionState=Z,ue.State=$,ue.UnauthorizedError=de;class pe{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 ue(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};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})}}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 ge(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 ve(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 me(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 ve(e)?e:""}(i);return s?`<a href="${s}" target="_blank" rel="noopener">${t}</a>`:t}).replace(/\n/g,"<br>")}function fe(e,t=!0){e.scrollTo({top:e.scrollHeight,behavior:t?"smooth":"auto"})}function _e(){return"cevro_"+Math.random().toString(36).substring(2,9)}class be{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=ge("div",{className:"cevro-launcher","data-testid":"launcher"}),this.applyPositioning();const e=ge("button",{className:"cevro-launcher__button","aria-label":"Open chat",type:"button","data-testid":"launcher-button"});if(this.bubbleIconUrl){const t=ge("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=ge("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 we={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?",csatSubmit:"Submit Feedback",csatThankYou:"Thank you for your feedback!",poweredBy:"Powered by Cevro AI"};function ye(e,t){return{...we,...e,...t}}class Ce{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=ge("div",{className:"cevro-messages",id:_e()}),this.messagesContainer=ge("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&&fe(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=ge("div",{className:"cevro-message "+(o?"cevro-message--outbound":"cevro-message--inbound"),"data-message-id":e.id,"data-testid":`message-${e.id}`});if(!o){const e=ge("div",{className:"cevro-message__avatar"});if((null==(t=this.currentAgent)?void 0:t.avatarUrl)&&ve(this.currentAgent.avatarUrl)){const t=ge("img",{className:"cevro-message__avatar-img"});t.src=this.currentAgent.avatarUrl,t.alt=this.currentAgent.name||"Agent",e.appendChild(t)}else e.innerHTML=this.createBotAvatarSvg();a.appendChild(e)}const c=ge("div",{className:"cevro-message__content-wrapper"}),l=ge("div",{className:"cevro-message__bubble"}),h="image"===e.type||"image"===(null==(i=e.attachment)?void 0:i.category);if(h&&e.mediaUrl&&ve(e.mediaUrl)){const t=ge("div",{className:"cevro-message__image-container"}),i=ge("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&&ve(e.mediaUrl)){const t=ge("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=ge("div",{className:"cevro-message__text"});t.innerHTML=me(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=ge("div",{className:"cevro-message__quick-actions"});e.richContent.quickActions.forEach(e=>{const i=ge("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=ge("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=ge("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=ge("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=ge("div",{className:`cevro-file-card cevro-file-card--${i}`}),a=ge("div",{className:"cevro-file-card__icon"});a.innerHTML=this.getFileIcon(i),o.appendChild(a);const c=ge("div",{className:"cevro-file-card__info"}),l=ge("div",{className:"cevro-file-card__name"});l.textContent=this.truncateFilename(s,25),l.title=s,c.appendChild(l);const h=ge("div",{className:"cevro-file-card__details"});if(h.textContent=this.formatFileSize(n),c.appendChild(h),o.appendChild(c),r){const e=ge("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&&ve(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=ge("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&&fe(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=ge("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&&fe(this.messagesContainer)}hideClosedMessage(){this.closedMessageElement&&(this.closedMessageElement.remove(),this.closedMessageElement=null)}scrollToBottom(){this.messagesContainer&&fe(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 xe{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",we),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||ye(e.locale),this.customLogoUrl=n,this.messageList=new Ce,this.messageList.setQuickActionHandler(e=>{this.callbacks.onQuickAction(e)})}setStrings(e){this.strings=ye(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=ge("div",{className:"cevro-chat-window",id:_e()}),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=ge("div",{className:"cevro-chat-window__header"});if(this.logoElement=ge("div",{className:"cevro-chat-window__logo","data-testid":"company-logo"}),this.customLogoUrl){const e=ge("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=ge("div",{className:"cevro-chat-window__title-section"});this.brandNameElement=ge("h2",{className:"cevro-chat-window__title","data-testid":"brand-name"},[this.strings.headerTitle]),this.headerSubtitleElement=ge("p",{className:"cevro-chat-window__subtitle"},[this.strings.headerSubtitle]),t.appendChild(this.brandNameElement),t.appendChild(this.headerSubtitleElement),e.appendChild(t);const i=ge("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=ge("div",{className:"cevro-chat-window__input-wrapper"}),t=ge("div",{className:"cevro-chat-window__input-area"});this.fileButton=ge("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=ge("input",{className:"cevro-chat-window__file-input"}),this.fileInput.type="file",this.fileInput.accept=function(e=c){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=ge("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.inputElement&&(this.inputElement.style.height="auto",this.inputElement.style.height=Math.min(this.inputElement.scrollHeight,100)+"px",this.updateSendButtonState())}),this.inputElement.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.handleSend())}),t.appendChild(this.inputElement),this.sendButton=ge("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=ge("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.inputElement.style.height="auto",this.updateSendButtonState(),this.inputElement.focus({preventScroll:!0}))}updateSendButtonState(){this.sendButton&&this.inputElement&&(this.sendButton.disabled=!this.inputElement.value.trim())}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=ge("div",{className:"cevro-csat-inline"});const i=ge("div",{className:"cevro-csat-inline__header"}),s=ge("span",{className:"cevro-csat-inline__title"},[this.strings.csatTitle]),n=ge("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=ge("div",{className:"cevro-csat-inline__stars"});for(let l=1;l<=5;l++){const e=ge("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=ge("textarea",{className:"cevro-csat-inline__feedback",placeholder:this.strings.csatPlaceholder});o.rows=2,o.addEventListener("input",()=>{this.csatFeedback=o.value});const a=ge("button",{className:"cevro-csat-inline__submit"},[this.strings.csatSubmit||"Submit"]);a.addEventListener("click",()=>this.submitInlineCSAT(e,t));const c=ge("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){this.csatSubmitting||(this.csatRating=e,this.updateStars(e,t))}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=ge("div",{className:"cevro-csat-inline cevro-csat-inline--thank-you"});const t=ge("div",{className:"cevro-csat-inline__thank-you-row"}),i=ge("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=ge("span",{className:"cevro-csat-inline__message"},[this.strings.csatThankYou]);t.appendChild(i),t.appendChild(s);const n=ge("button",{className:"cevro-csat-inline__new-chat"},[this.strings.newConversation]);n.addEventListener("click",()=>{e&&e()});const r=ge("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=ge("div",{className:"cevro-chat-window__closed-footer"});const t=ge("button",{className:"cevro-chat-window__new-chat-button"},[this.strings.newConversation]);t.addEventListener("click",()=>{e&&e()});const i=ge("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=ge("div",{className:"cevro-prechat"});const t=ge("h3",{className:"cevro-prechat__title"},[this.strings.preChatTitle]),i=ge("p",{className:"cevro-prechat__subtitle"},[this.strings.preChatSubtitle]),s=ge("form",{className:"cevro-prechat__form"}),n=ge("div",{className:"cevro-prechat__field"}),r=ge("label",{className:"cevro-prechat__label",for:"cevro-prechat-firstname"},[this.strings.preChatFirstNameLabel]),o=ge("input",{className:"cevro-prechat__input",id:"cevro-prechat-firstname",type:"text","data-testid":"prechat-firstname"});o.placeholder=this.strings.preChatFirstNamePlaceholder;const a=ge("span",{className:"cevro-prechat__error","data-field":"firstName"});n.appendChild(r),n.appendChild(o),n.appendChild(a);const c=ge("div",{className:"cevro-prechat__field"}),l=ge("label",{className:"cevro-prechat__label",for:"cevro-prechat-email"},[this.strings.preChatEmailLabel]),h=ge("input",{className:"cevro-prechat__input",id:"cevro-prechat-email",type:"text",autocomplete:"email","data-testid":"prechat-email"});h.placeholder=this.strings.preChatEmailPlaceholder;const d=ge("span",{className:"cevro-prechat__error","data-field":"email"});c.appendChild(l),c.appendChild(h),c.appendChild(d);const u=ge("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=ge("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="")}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 ke=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,"visitorContactInfo",null),t(this,"widgetAppearance",{}),this.config=this.normalizeConfig(i),this.events=new s,this.api=new g(this.config),this.ws=new pe(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;if(e.ticketId===this.api.getCurrentTicketId()&&"closed"===e.status){const i=!0!==this.widgetAppearance.csatEnabled;null==(t=this.chatWindow)||t.setTicketClosed(!0,()=>this.startNewChat(),{ticketId:e.ticketId,skipCSAT:i})}})}async boot(){if(this.isBooted)return;if(!this.config.preview)try{this.widgetAppearance=await this.api.getWidgetConfig()}catch{this.widgetAppearance={}}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.launcher=new be(this.config,()=>this.toggle(),this.widgetAppearance.bubbleIconUrl),this.container.appendChild(this.launcher.render());const s=ye(this.config.locale);this.chatWindow=new xe(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.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")}`}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.isBooted)return;this.stopTypingCycle(),this.ws.disconnect(),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,a(),(null==e?void 0:e.clearVisitorData)&&(!function(){try{localStorage.removeItem("cevro_visitor_token")}catch{}}(),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.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=ye(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"))}toggle(){this.isVisible?this.hide():this.show()}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?ve(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&&ve(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)}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;if(this.config.player={...this.config.player,...e},this.api.updateConfig(this.config),this.ws.updateConfig(this.config),!this.isBooted)return;const i=this.isVisible;this.ws.disconnect(),this.api.clear(),a(),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(ke,"instance",null),t(ke,"MAX_MESSAGE_LENGTH",2e3);let Te=ke;"undefined"!=typeof window&&(window.CevroMessenger=Te),exports.CevroMessenger=Te,exports.__styles=i,exports.default=Te;
|
|
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-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 - 140px);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:none}@media (max-width: 480px){.cevro-chat-window{width:100%;height:100%;max-height:100%;bottom:0;right:0;left:0;border-radius:0}}.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:4px;margin:-4px;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__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__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__text a{color:inherit;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:#ffffffb3;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;border:1px solid var(--cevro-border);border-radius:20px;padding:8px 16px;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)}.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}.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 #8b5cf61a}.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)}.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 #8b5cf61a}.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 #ef44441a}.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}()}function a(){try{localStorage.removeItem("cevro_session")}catch{}}const c=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"]),l=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"]),h={maxSizeBytes:26214400,minSizeBytes:1,maxFilenameLength:255};function d(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?"":e.substring(t).toLowerCase()}function u(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 p{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 g{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 p}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=h.maxSizeBytes,minSizeBytes:s=h.minSizeBytes,allowedMimeTypes:n=c,blockedExtensions:r=l,maxFilenameLength:o=h.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 ${u(s)}`,errorCode:"FILE_TOO_SMALL"};if(e.size>i)return{valid:!1,error:`File is too large. Maximum size is ${u(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=d(e.name);if(a&&r.has(a))return{valid:!1,error:`File type "${a}" is not allowed for security reasons`,errorCode:"BLOCKED_EXTENSION"};const p=e.type||"application/octet-stream";return n.has(p)||"application/octet-stream"===p&&a&&!r.has(a)?{valid:!0}:{valid:!1,error:`File type "${p}" 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>h.maxFilenameLength){const e=d(t),i=t.slice(0,-e.length||void 0),s=h.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 v(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 m(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var f,_={exports:{}},b="object"==typeof Reflect?Reflect:null,w=b&&"function"==typeof b.apply?b.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};f=b&&"function"==typeof b.ownKeys?b.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var y=Number.isNaN||function(e){return e!=e};function C(){C.init.call(this)}_.exports=C,_.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))}N(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&N(e,"error",t,i)}(e,n,{once:!0})})},C.EventEmitter=C,C.prototype._events=void 0,C.prototype._eventsCount=0,C.prototype._maxListeners=void 0;var x=10;function k(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function S(e){return void 0===e._maxListeners?C.defaultMaxListeners:e._maxListeners}function T(e,t,i,s){var n,r,o,a;if(k(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=S(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 I(){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 E(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=I.bind(s);return n.listener=i,s.wrapFn=n,n}function P(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):L(n,n.length)}function M(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 L(e,t){for(var i=new Array(t),s=0;s<t;++s)i[s]=e[s];return i}function N(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(C,"defaultMaxListeners",{enumerable:!0,get:function(){return x},set:function(e){if("number"!=typeof e||e<0||y(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");x=e}}),C.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},C.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||y(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},C.prototype.getMaxListeners=function(){return S(this)},C.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)w(a,this,t);else{var c=a.length,l=L(a,c);for(i=0;i<c;++i)w(l[i],this,t)}return!0},C.prototype.addListener=function(e,t){return T(this,e,t,!1)},C.prototype.on=C.prototype.addListener,C.prototype.prependListener=function(e,t){return T(this,e,t,!0)},C.prototype.once=function(e,t){return k(t),this.on(e,E(this,e,t)),this},C.prototype.prependOnceListener=function(e,t){return k(t),this.prependListener(e,E(this,e,t)),this},C.prototype.removeListener=function(e,t){var i,s,n,r,o;if(k(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},C.prototype.off=C.prototype.removeListener,C.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},C.prototype.listeners=function(e){return P(this,e,!0)},C.prototype.rawListeners=function(e){return P(this,e,!1)},C.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):M.call(e,t)},C.prototype.listenerCount=M,C.prototype.eventNames=function(){return this._eventsCount>0?f(this._events):[]};var A,R,z,B,F,U,H,O,j,V,D,W,q,$,Z,J,G=m(_.exports);function Y(e){return null!=e&&"function"==typeof e}function X(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 Q(e){return Math.min(1e3*e,2147483647)}(R=A||(A={}))[R.timeout=1]="timeout",R[R.transportClosed=2]="transportClosed",R[R.clientDisconnected=3]="clientDisconnected",R[R.clientClosed=4]="clientClosed",R[R.clientConnectToken=5]="clientConnectToken",R[R.clientRefreshToken=6]="clientRefreshToken",R[R.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",R[R.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",R[R.subscriptionRefreshToken=9]="subscriptionRefreshToken",R[R.transportWriteError=10]="transportWriteError",R[R.connectionClosed=11]="connectionClosed",R[R.badConfiguration=12]="badConfiguration",(B=z||(z={}))[B.connectCalled=0]="connectCalled",B[B.transportClosed=1]="transportClosed",B[B.noPing=2]="noPing",B[B.subscribeTimeout=3]="subscribeTimeout",B[B.unsubscribeError=4]="unsubscribeError",(U=F||(F={}))[U.disconnectCalled=0]="disconnectCalled",U[U.unauthorized=1]="unauthorized",U[U.badProtocol=2]="badProtocol",U[U.messageSizeLimit=3]="messageSizeLimit",(O=H||(H={}))[O.subscribeCalled=0]="subscribeCalled",O[O.transportClosed=1]="transportClosed",(V=j||(j={}))[V.unsubscribeCalled=0]="unsubscribeCalled",V[V.unauthorized=1]="unauthorized",V[V.clientClosed=2]="clientClosed",(W=D||(D={}))[W.channelCompaction=1]="channelCompaction",($=q||(q={})).Disconnected="disconnected",$.Connecting="connecting",$.Connected="connected",(J=Z||(Z={})).Unsubscribed="unsubscribed",J.Subscribing="subscribing",J.Subscribed="subscribed";class K extends G{constructor(e,t,i){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this.channel=t,this.state=Z.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===Z.Unsubscribed?Promise.reject({code:A.subscriptionUnsubscribed,message:this.state}):this.state===Z.Subscribed?Promise.resolve():new Promise((t,i)=>{const s={resolve:t,reject:i};e&&(s.timeout=setTimeout(function(){i({code:A.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=s})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(H.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(j.unsubscribeCalled,"unsubscribe called",!0)}publish(e){return v(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.publish(this.channel,e)})}presence(){return v(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return v(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)})}history(e){return v(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:A.subscriptionUnsubscribed,message:this.state}):new Promise((e,t)=>{const i=this._centrifuge._config.timeout,s=setTimeout(()=>{t({code:A.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===Z.Unsubscribed}_isSubscribing(){return this.state===Z.Subscribing}_isSubscribed(){return this.state===Z.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(Z.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(),Q(e.ttl)))}_setSubscribing(e,t){return v(this,0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState(Z.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 de)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:A.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 de)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:A.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=D.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!==A.timeout?this._subscribeError(e):this._centrifuge._disconnect(z.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(Z.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:A.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===q.Connected&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){const e=X(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:A.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new de(""))):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 de?e._failUnauthorized():(e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:A.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(),Q(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 X(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(j.unauthorized,"unauthorized",!0)}}class ee{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 te{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 ie{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 se{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 ne{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 v(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 v(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 v(this,0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}})}send(e){return v(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 re=[-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 oe{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=re[127&this.getByte()])>=0;)t=(t<<6)+e;return this.pos--,t>>>0}}class ae{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 ce(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 le{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 oe(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 ae;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!==ce(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 he={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 de extends Error{constructor(e){super(e),this.name=this.constructor.name}}class ue extends G{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=q.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 le,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({},he),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 K(this,e,t);return this._subs[e]=i,i}getSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==Z.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}subscriptions(){return this._subs}ready(e){return v(this,0,void 0,function*(){switch(this.state){case q.Disconnected:throw{code:A.clientDisconnected,message:"client disconnected"};case q.Connected:return;default:return new Promise((t,i)=>{const s={resolve:t,reject:i};e&&(s.timeout=setTimeout(()=>{i({code:A.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(F.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return v(this,0,void 0,function*(){const t={send:{data:e}};yield this._methodCall();if(!this._transportSendCommands([t]))throw this._createErrorObject(A.transportWriteError,"transport write error")})}rpc(e,t){return v(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 v(this,0,void 0,function*(){const i={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}history(e,t){return v(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 v(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 v(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];Y(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 le,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===q.Disconnected}_isConnecting(){return this.state===q.Connecting}_isConnected(){return this.state===q.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!==q.Connected&&this.state!==q.Connecting||(this._disconnect(z.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===q.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=X(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(A.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===Z.Subscribed&&t._setSubscribing(H.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(A.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 te(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 ne(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 ie(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 se(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 ee(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 te(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=F.messageSizeLimit,t="message size limit exceeded",i=!1):(s=z.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:A.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 de)return void t._failUnauthorized();t.emit("error",{type:"connectToken",error:{code:A.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 de)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:A.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===q.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:A.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(q.Connecting)&&this.emit("connecting",{code:z.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(q.Connecting):(r=this._setState(q.Disconnected),this._rejectPromises({code:A.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),s===q.Connecting&&this._clearReconnectTimeout(),s===q.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(F.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:A.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new de("")))}_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 de?t._failUnauthorized():(t.emit("error",{type:"refreshToken",error:{code:A.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 X(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),Q(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(z.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===Z.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(q.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),Q(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(z.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],Y(i)&&i({error:this._createErrorObject(A.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])}}ue.SubscriptionState=Z,ue.State=q,ue.UnauthorizedError=de;class pe{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 ue(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};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})}}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 ge(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 ve(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 me(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 ve(e)?e:""}(i);return s?`<a href="${s}" target="_blank" rel="noopener">${t}</a>`:t}).replace(/\n/g,"<br>")}function fe(e,t=!0){e.scrollTo({top:e.scrollHeight,behavior:t?"smooth":"auto"})}function _e(){return"cevro_"+Math.random().toString(36).substring(2,9)}class be{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=ge("div",{className:"cevro-launcher","data-testid":"launcher"}),this.applyPositioning();const e=ge("button",{className:"cevro-launcher__button","aria-label":"Open chat",type:"button","data-testid":"launcher-button"});if(this.bubbleIconUrl){const t=ge("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=ge("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 we={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 ye(e,t){return{...we,...e,...t}}class Ce{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=ge("div",{className:"cevro-messages",id:_e()}),this.messagesContainer=ge("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&&fe(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=ge("div",{className:"cevro-message "+(o?"cevro-message--outbound":"cevro-message--inbound"),"data-message-id":e.id,"data-testid":`message-${e.id}`});if(!o){const e=ge("div",{className:"cevro-message__avatar"});if((null==(t=this.currentAgent)?void 0:t.avatarUrl)&&ve(this.currentAgent.avatarUrl)){const t=ge("img",{className:"cevro-message__avatar-img"});t.src=this.currentAgent.avatarUrl,t.alt=this.currentAgent.name||"Agent",e.appendChild(t)}else e.innerHTML=this.createBotAvatarSvg();a.appendChild(e)}const c=ge("div",{className:"cevro-message__content-wrapper"}),l=ge("div",{className:"cevro-message__bubble"}),h="image"===e.type||"image"===(null==(i=e.attachment)?void 0:i.category);if(h&&e.mediaUrl&&ve(e.mediaUrl)){const t=ge("div",{className:"cevro-message__image-container"}),i=ge("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&&ve(e.mediaUrl)){const t=ge("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=ge("div",{className:"cevro-message__text"});t.innerHTML=me(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=ge("div",{className:"cevro-message__quick-actions"});e.richContent.quickActions.forEach(e=>{const i=ge("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=ge("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=ge("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=ge("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=ge("div",{className:`cevro-file-card cevro-file-card--${i}`}),a=ge("div",{className:"cevro-file-card__icon"});a.innerHTML=this.getFileIcon(i),o.appendChild(a);const c=ge("div",{className:"cevro-file-card__info"}),l=ge("div",{className:"cevro-file-card__name"});l.textContent=this.truncateFilename(s,25),l.title=s,c.appendChild(l);const h=ge("div",{className:"cevro-file-card__details"});if(h.textContent=this.formatFileSize(n),c.appendChild(h),o.appendChild(c),r){const e=ge("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&&ve(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=ge("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&&fe(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=ge("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&&fe(this.messagesContainer)}hideClosedMessage(){this.closedMessageElement&&(this.closedMessageElement.remove(),this.closedMessageElement=null)}scrollToBottom(){this.messagesContainer&&fe(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 xe{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",we),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||ye(e.locale),this.customLogoUrl=n,this.messageList=new Ce,this.messageList.setQuickActionHandler(e=>{this.callbacks.onQuickAction(e)})}setStrings(e){this.strings=ye(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=ge("div",{className:"cevro-chat-window",id:_e()}),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=ge("div",{className:"cevro-chat-window__header"});if(this.logoElement=ge("div",{className:"cevro-chat-window__logo","data-testid":"company-logo"}),this.customLogoUrl){const e=ge("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=ge("div",{className:"cevro-chat-window__title-section"});this.brandNameElement=ge("h2",{className:"cevro-chat-window__title","data-testid":"brand-name"},[this.strings.headerTitle]),this.headerSubtitleElement=ge("p",{className:"cevro-chat-window__subtitle"},[this.strings.headerSubtitle]),t.appendChild(this.brandNameElement),t.appendChild(this.headerSubtitleElement),e.appendChild(t);const i=ge("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=ge("div",{className:"cevro-chat-window__input-wrapper"}),t=ge("div",{className:"cevro-chat-window__input-area"});this.fileButton=ge("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=ge("input",{className:"cevro-chat-window__file-input"}),this.fileInput.type="file",this.fileInput.accept=function(e=c){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=ge("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.inputElement&&(this.inputElement.style.height="auto",this.inputElement.style.height=Math.min(this.inputElement.scrollHeight,100)+"px",this.updateSendButtonState())}),this.inputElement.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.handleSend())}),t.appendChild(this.inputElement),this.sendButton=ge("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=ge("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.inputElement.style.height="auto",this.updateSendButtonState(),this.inputElement.focus({preventScroll:!0}))}updateSendButtonState(){this.sendButton&&this.inputElement&&(this.sendButton.disabled=!this.inputElement.value.trim())}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=ge("div",{className:"cevro-csat-inline"});const i=ge("div",{className:"cevro-csat-inline__header"}),s=ge("span",{className:"cevro-csat-inline__title"},[this.strings.csatTitle]),n=ge("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=ge("div",{className:"cevro-csat-inline__stars"});for(let l=1;l<=5;l++){const e=ge("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=ge("textarea",{className:"cevro-csat-inline__feedback",placeholder:this.strings.csatPlaceholder});o.rows=2,o.addEventListener("input",()=>{this.csatFeedback=o.value});const a=ge("button",{className:"cevro-csat-inline__submit"},[this.strings.csatSubmit||"Submit"]);a.addEventListener("click",()=>this.submitInlineCSAT(e,t));const c=ge("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=ge("div",{className:"cevro-csat-inline cevro-csat-inline--thank-you"});const t=ge("div",{className:"cevro-csat-inline__thank-you-row"}),i=ge("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=ge("span",{className:"cevro-csat-inline__message"},[this.strings.csatThankYou]);t.appendChild(i),t.appendChild(s);const n=ge("button",{className:"cevro-csat-inline__new-chat"},[this.strings.newConversation]);n.addEventListener("click",()=>{e&&e()});const r=ge("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=ge("div",{className:"cevro-chat-window__closed-footer"});const t=ge("button",{className:"cevro-chat-window__new-chat-button"},[this.strings.newConversation]);t.addEventListener("click",()=>{e&&e()});const i=ge("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=ge("div",{className:"cevro-prechat"});const t=ge("h3",{className:"cevro-prechat__title"},[this.strings.preChatTitle]),i=ge("p",{className:"cevro-prechat__subtitle"},[this.strings.preChatSubtitle]),s=ge("form",{className:"cevro-prechat__form"}),n=ge("div",{className:"cevro-prechat__field"}),r=ge("label",{className:"cevro-prechat__label",for:"cevro-prechat-firstname"},[this.strings.preChatFirstNameLabel]),o=ge("input",{className:"cevro-prechat__input",id:"cevro-prechat-firstname",type:"text","data-testid":"prechat-firstname"});o.placeholder=this.strings.preChatFirstNamePlaceholder;const a=ge("span",{className:"cevro-prechat__error","data-field":"firstName"});n.appendChild(r),n.appendChild(o),n.appendChild(a);const c=ge("div",{className:"cevro-prechat__field"}),l=ge("label",{className:"cevro-prechat__label",for:"cevro-prechat-email"},[this.strings.preChatEmailLabel]),h=ge("input",{className:"cevro-prechat__input",id:"cevro-prechat-email",type:"text",autocomplete:"email","data-testid":"prechat-email"});h.placeholder=this.strings.preChatEmailPlaceholder;const d=ge("span",{className:"cevro-prechat__error","data-field":"email"});c.appendChild(l),c.appendChild(h),c.appendChild(d);const u=ge("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=ge("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="")}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 ke=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,"visitorContactInfo",null),t(this,"widgetAppearance",{}),this.config=this.normalizeConfig(i),this.events=new s,this.api=new g(this.config),this.ws=new pe(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;if(e.ticketId===this.api.getCurrentTicketId()&&"closed"===e.status){const i=!0!==this.widgetAppearance.csatEnabled;null==(t=this.chatWindow)||t.setTicketClosed(!0,()=>this.startNewChat(),{ticketId:e.ticketId,skipCSAT:i})}})}async boot(){if(this.isBooted)return;if(!this.config.preview)try{this.widgetAppearance=await this.api.getWidgetConfig()}catch{this.widgetAppearance={}}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.launcher=new be(this.config,()=>this.toggle(),this.widgetAppearance.bubbleIconUrl),this.container.appendChild(this.launcher.render());const s=ye(this.config.locale);this.chatWindow=new xe(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.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")}`}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.isBooted)return;this.stopTypingCycle(),this.ws.disconnect(),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,a(),(null==e?void 0:e.clearVisitorData)&&(!function(){try{localStorage.removeItem("cevro_visitor_token")}catch{}}(),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.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=ye(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"))}toggle(){this.isVisible?this.hide():this.show()}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?ve(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&&ve(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)}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;if(this.config.player={...this.config.player,...e},this.api.updateConfig(this.config),this.ws.updateConfig(this.config),!this.isBooted)return;const i=this.isVisible;this.ws.disconnect(),this.api.clear(),a(),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(ke,"instance",null),t(ke,"MAX_MESSAGE_LENGTH",2e3);let Se=ke;"undefined"!=typeof window&&(window.CevroMessenger=Se),exports.CevroMessenger=Se,exports.__styles=i,exports.default=Se;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|