@chatcops/widget 0.6.0 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +2 -1
  2. package/dist/api/client.d.ts +17 -2
  3. package/dist/api/client.d.ts.map +1 -1
  4. package/dist/api/protocol.d.ts +7 -1
  5. package/dist/api/protocol.d.ts.map +1 -1
  6. package/dist/api/turnstile.d.ts.map +1 -1
  7. package/dist/api/types.d.ts +7 -0
  8. package/dist/api/types.d.ts.map +1 -1
  9. package/dist/chatcops.esm.js +1094 -499
  10. package/dist/chatcops.full.min.js +1 -0
  11. package/dist/chatcops.min.js +1 -1
  12. package/dist/chatcops.panel.js +1 -0
  13. package/dist/chunks/prechat-form-DiHgHUnU.js +1 -0
  14. package/dist/chunks/turnstile-CAnVL3fK.js +1 -0
  15. package/dist/dom/bubble.d.ts +3 -0
  16. package/dist/dom/bubble.d.ts.map +1 -1
  17. package/dist/dom/fab.d.ts +4 -1
  18. package/dist/dom/fab.d.ts.map +1 -1
  19. package/dist/dom/icons.d.ts +4 -0
  20. package/dist/dom/icons.d.ts.map +1 -0
  21. package/dist/dom/input.d.ts +1 -0
  22. package/dist/dom/input.d.ts.map +1 -1
  23. package/dist/dom/messages.d.ts +38 -1
  24. package/dist/dom/messages.d.ts.map +1 -1
  25. package/dist/dom/panel.d.ts +8 -0
  26. package/dist/dom/panel.d.ts.map +1 -1
  27. package/dist/dom/prechat-form.d.ts.map +1 -1
  28. package/dist/dom/shadow.d.ts +10 -1
  29. package/dist/dom/shadow.d.ts.map +1 -1
  30. package/dist/i18n.d.ts +7 -1
  31. package/dist/i18n.d.ts.map +1 -1
  32. package/dist/index.d.ts +41 -5
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/loader/index.d.ts +2 -0
  35. package/dist/loader/index.d.ts.map +1 -0
  36. package/dist/loader/loader.d.ts +71 -0
  37. package/dist/loader/loader.d.ts.map +1 -0
  38. package/dist/locales/ar.d.ts +4 -0
  39. package/dist/locales/ar.d.ts.map +1 -0
  40. package/dist/locales/ar.js +1 -0
  41. package/dist/locales/de.d.ts +4 -0
  42. package/dist/locales/de.d.ts.map +1 -0
  43. package/dist/locales/de.js +1 -0
  44. package/dist/locales/es.d.ts +4 -0
  45. package/dist/locales/es.d.ts.map +1 -0
  46. package/dist/locales/es.js +1 -0
  47. package/dist/locales/fr.d.ts +4 -0
  48. package/dist/locales/fr.d.ts.map +1 -0
  49. package/dist/locales/fr.js +1 -0
  50. package/dist/locales/he.d.ts +4 -0
  51. package/dist/locales/he.d.ts.map +1 -0
  52. package/dist/locales/he.js +1 -0
  53. package/dist/locales/hi.d.ts +4 -0
  54. package/dist/locales/hi.d.ts.map +1 -0
  55. package/dist/locales/hi.js +1 -0
  56. package/dist/locales/it.d.ts +4 -0
  57. package/dist/locales/it.d.ts.map +1 -0
  58. package/dist/locales/it.js +1 -0
  59. package/dist/locales/ja.d.ts +4 -0
  60. package/dist/locales/ja.d.ts.map +1 -0
  61. package/dist/locales/ja.js +1 -0
  62. package/dist/locales/ko.d.ts +4 -0
  63. package/dist/locales/ko.d.ts.map +1 -0
  64. package/dist/locales/ko.js +1 -0
  65. package/dist/locales/nl.d.ts +4 -0
  66. package/dist/locales/nl.d.ts.map +1 -0
  67. package/dist/locales/nl.js +1 -0
  68. package/dist/locales/pt.d.ts +4 -0
  69. package/dist/locales/pt.d.ts.map +1 -0
  70. package/dist/locales/pt.js +1 -0
  71. package/dist/locales/ur.d.ts +4 -0
  72. package/dist/locales/ur.d.ts.map +1 -0
  73. package/dist/locales/ur.js +1 -0
  74. package/dist/locales/zh.d.ts +4 -0
  75. package/dist/locales/zh.d.ts.map +1 -0
  76. package/dist/locales/zh.js +1 -0
  77. package/dist/panel.d.ts +6 -0
  78. package/dist/panel.d.ts.map +1 -0
  79. package/dist/script-config.d.ts +5 -0
  80. package/dist/script-config.d.ts.map +1 -0
  81. package/dist/storage.d.ts +30 -10
  82. package/dist/storage.d.ts.map +1 -1
  83. package/dist/theme.d.ts +15 -0
  84. package/dist/theme.d.ts.map +1 -1
  85. package/dist/version.d.ts +3 -0
  86. package/dist/version.d.ts.map +1 -0
  87. package/dist/widget.d.ts +124 -15
  88. package/dist/widget.d.ts.map +1 -1
  89. package/package.json +7 -3
@@ -0,0 +1 @@
1
+ var ChatCops=function(t){"use strict";const e="chatcops-root",i=new Set(["ar","he","fa","ur"]);function s(t,s={}){const c=document.createElement("div");c.id=function(){if(!document.getElementById(e))return e;let t=2;for(;document.getElementById(`${e}-${t}`);)t+=1;return`${e}-${t}`}(),c.className=e,c.dir=function(t,e){if(t)return t;const s=null==e?void 0:e.toLowerCase().split(/[-_]/)[0];return s&&i.has(s)||"rtl"===(document.dir||document.documentElement.dir)?"rtl":"ltr"}(s.dir,s.locale),s.locale&&(c.lang=s.locale),t?t.appendChild(c):document.body.appendChild(c);const r=c.attachShadow({mode:"open"}),n=document.createElement("style");return n.textContent=':host{--cc-accent: var(--cc-theme-accent, #4f46e5);--cc-accent-hover: var(--cc-theme-accent-hover, #4338ca);--cc-on-accent: var(--cc-theme-on-accent, #ffffff);--cc-accent-contrast: var(--cc-theme-accent-contrast, #4f46e5);--cc-text: #1a1d23;--cc-bg: #ffffff;--cc-bg-surface: #f4f5f7;--cc-bg-input: #ffffff;--cc-border: #d9dce1;--cc-text-secondary: #5b616e;--cc-danger: #c62828;--cc-code-bg: rgb(0 0 0 / .07);--cc-pre-bg: rgb(0 0 0 / .05);--cc-shadow: 0 12px 40px rgb(16 24 40 / .18);--cc-font: system-ui, -apple-system, sans-serif;--cc-radius: 12px;--cc-fab-size: 56px;--cc-panel-width: 400px;--cc-panel-height: 560px;--cc-focus-ring: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-accent);all:initial;color-scheme:light;font-family:var(--cc-font);font-size:14px;line-height:1.5;color:var(--cc-text);-webkit-font-smoothing:antialiased}:host([data-cc-mode="dark"]){--cc-accent: var(--cc-theme-accent-dark, var(--cc-theme-accent, #6366f1));--cc-accent-hover: var(--cc-theme-accent-dark-hover, var(--cc-theme-accent-hover, #4f46e5));--cc-on-accent: var(--cc-theme-on-accent-dark, var(--cc-theme-on-accent, #ffffff));--cc-accent-contrast: var(--cc-theme-accent-dark-contrast, var(--cc-theme-accent-contrast, #6164ec));--cc-text: #ffffff;--cc-bg: #0a0a0a;--cc-bg-surface: #1a1a1a;--cc-bg-input: #2a2a2a;--cc-border: #333333;--cc-text-secondary: #a0a0a0;--cc-danger: #ef4444;--cc-code-bg: rgba(0, 0, 0, .2);--cc-pre-bg: rgba(0, 0, 0, .3);--cc-shadow: 0 8px 32px rgba(0,0,0,.4);color-scheme:dark}@media(prefers-color-scheme:dark){:host(:not([data-cc-mode])),:host([data-cc-mode="auto"]){--cc-accent: var(--cc-theme-accent-dark, var(--cc-theme-accent, #6366f1));--cc-accent-hover: var(--cc-theme-accent-dark-hover, var(--cc-theme-accent-hover, #4f46e5));--cc-on-accent: var(--cc-theme-on-accent-dark, var(--cc-theme-on-accent, #ffffff));--cc-accent-contrast: var(--cc-theme-accent-dark-contrast, var(--cc-theme-accent-contrast, #6164ec));--cc-text: #ffffff;--cc-bg: #0a0a0a;--cc-bg-surface: #1a1a1a;--cc-bg-input: #2a2a2a;--cc-border: #333333;--cc-text-secondary: #a0a0a0;--cc-danger: #ef4444;--cc-code-bg: rgba(0, 0, 0, .2);--cc-pre-bg: rgba(0, 0, 0, .3);--cc-shadow: 0 8px 32px rgba(0,0,0,.4);color-scheme:dark}}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}.cc-fab{position:fixed;bottom:20px;right:20px;width:var(--cc-fab-size);height:var(--cc-fab-size);border-radius:50%;background:var(--cc-accent);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 16px #0000004d;transition:transform .2s,box-shadow .2s;z-index:10000;outline:none}.cc-fab:hover{transform:scale(1.05);box-shadow:0 6px 24px #0006}.cc-fab:active{transform:scale(.95)}.cc-fab.cc-left{right:auto;left:20px}.cc-fab svg{width:24px;height:24px;fill:var(--cc-on-accent);transition:transform .3s}.cc-fab.cc-open svg{transform:rotate(90deg)}.cc-fab-badge{position:absolute;top:-2px;inset-inline-end:-2px;min-width:18px;height:18px;padding:0 4px;border-radius:9px;background:#ef4444;border:2px solid var(--cc-bg);color:#fff;font-size:11px;font-weight:700;line-height:1;display:none;align-items:center;justify-content:center;pointer-events:none}.cc-fab-badge.cc-visible{display:flex}@keyframes cc-pulse{0%,to{box-shadow:0 4px 16px #0000004d}50%{box-shadow:0 4px 16px color-mix(in srgb,var(--cc-accent) 50%,transparent)}}.cc-fab.cc-pulse{animation:cc-pulse 2s ease-in-out 3}.cc-fab:focus-visible{outline:2px solid transparent;box-shadow:var(--cc-focus-ring),0 4px 16px #0000004d;animation:none}@media(prefers-reduced-motion:reduce){.cc-fab.cc-pulse{animation:none}}.cc-panel{position:fixed;bottom:88px;right:20px;width:var(--cc-panel-width);height:var(--cc-panel-height);max-height:calc(100vh - 100px);background:var(--cc-bg);border-radius:var(--cc-radius);box-shadow:var(--cc-shadow);border:1px solid var(--cc-border);display:flex;flex-direction:column;overflow:hidden;z-index:9999;opacity:0;transform:translateY(16px) scale(.95);pointer-events:none;transition:opacity .2s,transform .2s}.cc-panel.cc-visible{opacity:1;transform:translateY(0) scale(1);pointer-events:auto}.cc-panel.cc-left{right:auto;left:20px}.cc-panel.cc-inline{position:relative;bottom:auto;inset-inline:auto;width:100%;height:100%;max-height:100%;z-index:auto;transform:none;transition:none}.cc-panel.cc-inline:not(.cc-visible){visibility:hidden}.cc-header{display:flex;align-items:center;padding:16px;background:var(--cc-bg-surface);border-bottom:1px solid var(--cc-border);flex-shrink:0}.cc-header-avatar,.cc-header-avatar-placeholder{width:36px;height:36px;border-radius:50%;margin-inline-end:12px}.cc-header-avatar{object-fit:cover}.cc-header-avatar-placeholder{background:var(--cc-accent);display:flex;align-items:center;justify-content:center}.cc-header-avatar-placeholder svg{width:20px;height:20px;fill:var(--cc-on-accent)}.cc-header-info{flex:1}.cc-header-name{font-size:15px;font-weight:600;color:var(--cc-text)}.cc-header-subtitle{font-size:12px;color:var(--cc-text-secondary)}.cc-header-close{width:32px;height:32px;border-radius:8px;background:transparent;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s}.cc-header-close:hover{background:var(--cc-bg-input)}.cc-header-close svg{width:16px;height:16px;fill:var(--cc-text-secondary)}.cc-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}.cc-messages::-webkit-scrollbar{width:4px}.cc-messages::-webkit-scrollbar-track{background:transparent}.cc-messages::-webkit-scrollbar-thumb{background:var(--cc-border);border-radius:2px}.cc-message{max-width:85%;padding:10px 14px;border-radius:var(--cc-radius);word-wrap:break-word;overflow-wrap:break-word;font-size:14px;line-height:1.5;display:flex;flex-direction:column;gap:8px}.cc-message-user{align-self:flex-end;background:var(--cc-accent-contrast);color:var(--cc-on-accent);border-end-end-radius:4px}.cc-message-assistant{align-self:flex-start;background:var(--cc-bg-surface);color:var(--cc-text);border-end-start-radius:4px}.cc-suggestions{display:flex;flex-wrap:wrap;gap:8px;padding:0 16px 12px}.cc-suggestion{border:1px solid var(--cc-border);border-radius:var(--cc-radius);padding:8px 12px;background:var(--cc-bg-surface);color:var(--cc-text);cursor:pointer;font:inherit}.cc-suggestion:hover{border-color:var(--cc-accent)}.cc-message a{color:var(--cc-accent);text-decoration:underline}.cc-message-user a{color:var(--cc-on-accent)}.cc-disclosure{margin-block-end:4px;padding:8px 12px;border:1px solid var(--cc-border);border-radius:10px;font-size:12px;color:var(--cc-text-secondary)}.cc-disclosure a{color:inherit;text-decoration:underline}.cc-message-error-note{margin-top:6px;font-size:12px;color:var(--cc-text-secondary)}.cc-message-sources{margin-block-start:8px;font-size:12px;color:var(--cc-text-secondary)}.cc-message-sources ol{margin:0;padding-inline-start:1.2em}.cc-message-sources a{color:var(--cc-text-secondary);text-decoration:underline}.cc-message code{background:var(--cc-code-bg);padding:1px 4px;border-radius:4px;font-family:SF Mono,Cascadia Code,Consolas,monospace;font-size:13px}.cc-message pre{background:var(--cc-pre-bg);padding:8px 12px;border-radius:8px;overflow-x:auto;margin:4px 0}.cc-message pre code{background:transparent;padding:0}.cc-message ul,.cc-message ol{padding-inline-start:20px;margin:4px 0}.cc-message h1,.cc-message h2,.cc-message h3,.cc-message h4,.cc-message h5,.cc-message h6{font-size:15px;font-weight:600;line-height:1.4;margin:4px 0 0}.cc-message-actions{display:flex;align-items:center}.cc-message-retry,.cc-message-regenerate{display:inline-flex;align-items:center;gap:4px;padding:4px 10px;background:transparent;border:1px solid var(--cc-border);border-radius:6px;color:var(--cc-text-secondary);font-family:var(--cc-font);font-size:12px;cursor:pointer;transition:background .15s,color .15s,opacity .15s}.cc-message-retry:hover,.cc-message-regenerate:hover{background:var(--cc-bg-input);color:var(--cc-text)}.cc-message-retry svg,.cc-message-regenerate svg{fill:currentColor}.cc-message-regenerate{opacity:0}.cc-message:hover .cc-message-regenerate{opacity:1}.cc-message:focus-within .cc-message-regenerate,.cc-message-regenerate:focus-visible{opacity:1}@media(hover:none){.cc-message-regenerate{opacity:1}}.cc-message-retry{border-color:var(--cc-danger);color:var(--cc-danger)}.cc-message-retry:hover{background:color-mix(in srgb,var(--cc-danger) 10%,transparent);color:var(--cc-danger)}.cc-typing{display:flex;align-items:center;gap:4px;padding:10px 14px;align-self:flex-start;background:var(--cc-bg-surface);border-radius:var(--cc-radius);border-end-start-radius:4px}.cc-typing-dot{width:6px;height:6px;border-radius:50%;background:var(--cc-text-secondary);animation:cc-bounce 1.2s infinite}.cc-typing-dot:nth-child(2){animation-delay:.2s}.cc-typing-dot:nth-child(3){animation-delay:.4s}@keyframes cc-bounce{0%,60%,to{transform:translateY(0)}30%{transform:translateY(-4px)}}.cc-input-area{display:flex;align-items:flex-end;padding:12px 16px;border-top:1px solid var(--cc-border);background:var(--cc-bg);gap:8px}.cc-input{flex:1;background:var(--cc-bg-input);border:1px solid var(--cc-border);border-radius:8px;padding:8px 12px;color:var(--cc-text);font-family:var(--cc-font);font-size:14px;line-height:1.5;resize:none;outline:none;max-height:96px;overflow-y:auto;transition:border-color .15s}.cc-input:focus{border-color:var(--cc-accent)}.cc-input::placeholder{color:var(--cc-text-secondary)}.cc-send-btn{width:36px;height:36px;border-radius:8px;background:var(--cc-accent);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .15s,opacity .15s}.cc-send-btn:hover{background:var(--cc-accent-hover)}.cc-send-btn:disabled{opacity:.4;cursor:not-allowed}.cc-send-btn svg{width:16px;height:16px;fill:var(--cc-on-accent)}:host([dir="rtl"]) .cc-send-btn svg{transform:scaleX(-1)}.cc-footer{padding:6px 16px;text-align:center;font-size:11px;color:var(--cc-text-secondary);border-top:1px solid var(--cc-border)}.cc-footer a{color:var(--cc-text-secondary);text-decoration:none}.cc-footer a:hover{text-decoration:underline}.cc-bubble{position:fixed;bottom:84px;right:20px;background:var(--cc-bg-surface);color:var(--cc-text);padding:10px 16px;border-radius:var(--cc-radius);box-shadow:var(--cc-shadow);border:1px solid var(--cc-border);max-width:260px;font-size:13px;line-height:1.4;z-index:9998;opacity:0;transform:translateY(8px);pointer-events:none;transition:opacity .3s,transform .3s}.cc-bubble.cc-visible{opacity:1;transform:translateY(0);pointer-events:auto}.cc-bubble.cc-left{right:auto;left:20px}.cc-bubble-trigger{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:block;width:100%;padding:0;margin:0;border:0;background:transparent;color:inherit;font:inherit;line-height:inherit;text-align:start;cursor:pointer}.cc-bubble-close{position:absolute;top:-8px;inset-inline-end:-8px;width:20px;height:20px;border-radius:50%;background:var(--cc-bg);border:1px solid var(--cc-border);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:10px;color:var(--cc-text-secondary)}.cc-hidden{display:none}.cc-sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap}.cc-messages-wrapper{flex:1;display:flex;flex-direction:column;min-height:0}@media(max-width:640px){.cc-fab.cc-open{display:none}.cc-panel:not(.cc-inline){width:100%;height:100%;height:100dvh;max-height:100%;bottom:0;inset-inline:0;border-radius:0;border:none;padding-top:env(safe-area-inset-top);padding-bottom:env(safe-area-inset-bottom)}.cc-panel.cc-left:not(.cc-inline){left:0}.cc-input{font-size:16px}.cc-bubble{bottom:84px;inset-inline:16px;max-width:none}}.cc-header-close:focus-visible,.cc-send-btn:focus-visible,.cc-suggestion:focus-visible,.cc-message-retry:focus-visible,.cc-message-regenerate:focus-visible,.cc-bubble-trigger:focus-visible,.cc-bubble-close:focus-visible,.cc-input:focus-visible{outline:2px solid transparent;box-shadow:var(--cc-focus-ring)}@media(prefers-reduced-motion:reduce){.cc-typing-dot{animation:none}.cc-panel,.cc-bubble{transition:none}}',r.appendChild(n),r}const c='<svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z"/><path d="M7 9h10v2H7zm0-3h10v2H7z"/></svg>',r={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},n=new Set(["http","https","mailto","tel"]);function o(t){let e=t.replace(/[&<>"']/g,t=>r[t]??t);const i=function(t){let e="\0";for(;t.includes(e);)e+="\0";return e}(e),s=[],c=t=>{const e=s.push(t)-1;return`${i}${e}${i}`};e=e.replace(/```(?:\w*)\n?([\s\S]*?)```/g,(t,e)=>c(`<pre><code>${e.trim()}</code></pre>`)),e=e.replace(/`([^`]+)`/g,(t,e)=>c(`<code>${e}</code>`)),e=e.replace(/^(#{1,6}) (.+)$/gm,(t,e,i)=>{const s=e.length;return`<h${s}>${i}</h${s}>`}),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(\S(?:.*?\S)??)\*/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\(((?:[^()]*|\([^()]*\))*)\)/g,(t,e,i)=>function(t){const e=t.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""),i=/^([^:/?#]+):/.exec(e);return!i||n.has(i[1].toLowerCase())}(i)?`<a href="${i}" target="_blank" rel="noopener noreferrer">${e}</a>`:e),e=e.replace(/^[-*+] (.+)$/gm,'<li data-md="ul">$1</li>'),e=e.replace(/^\d+\. (.+)$/gm,'<li data-md="ol">$1</li>'),e=e.replace(/(?:<li data-md="ul">.*?<\/li>\n?)+|(?:<li data-md="ol">.*?<\/li>\n?)+/g,t=>{const e=t.includes('data-md="ol"')?"ol":"ul";return`<${e}>${t.replace(/ data-md="(?:ul|ol)"/g,"").replace(/\n/g,"")}</${e}>`}),e=e.replace(/(<\/h[1-6]>)\n+/g,"$1"),e=e.replace(/\n\n/g,"<br><br>"),e=e.replace(/\n/g,"<br>");for(let r=0;r<s.length;r++)e=e.replace(`${i}${r}${i}`,()=>s[r]);return e}class a{constructor(t,e,i={}){this.streams=new Map,this.t=null,this.i=null,this.o=null,this.actions=e,this.streamIntervalMs=i.streamIntervalMs??50,this.container=document.createElement("div"),this.container.className="cc-messages",this.container.setAttribute("role","log"),this.container.setAttribute("aria-live","polite"),t.appendChild(this.container),this.h=document.createElement("div"),this.h.className="cc-reply-announcement cc-sr-only",this.h.setAttribute("aria-live","polite"),this.h.setAttribute("aria-atomic","true"),t.appendChild(this.h)}beginReply(){this.h.textContent="",this.container.setAttribute("aria-live","off")}finishReply(t){var e,i,s,c;if("assistant"===(null==t?void 0:t.role)&&("complete"===t.status||"error"===t.status)){const r=this.l(t.id),n=(null==(i=null==(e=null==r?void 0:r.querySelector(".cc-message-content"))?void 0:e.textContent)?void 0:i.trim())??"",o=(null==(c=null==(s=null==r?void 0:r.querySelector(".cc-message-error-note"))?void 0:s.textContent)?void 0:c.trim())??"";this.h.textContent=[n,o&&o!==n?o:""].filter(Boolean).join(" ")}this.container.setAttribute("aria-live","polite")}addMessage(t){const e="user"===t.role||this.u();this.removeTyping(),"user"===t.role&&this.removeSuggestions();const i=this.p(t);return this.container.appendChild(i),e&&this.m(),i}updateMessage(t){const e=this.l(t.id);if(!e)return;if("assistant"===t.role&&"streaming"===t.status&&"streaming"===e.dataset.status)return void this.stream(e,t);this.v(t.id);const i=this.u();this.k(e,t),i&&this.m()}stream(t,e){let i=this.streams.get(e.id);if(!i||!function(t,e){if(e.length<t.length)return!1;const i=Math.max(0,t.length-32);return e.slice(i,t.length)===t.slice(i)}(i.text,e.content)){this.v(e.id);const s=t.querySelector(".cc-message-content");if(!s)return;s.innerHTML="";const c=document.createElement("div");return c.className="cc-stream-tail",s.appendChild(c),i={text:e.content,committed:0,tail:c,renderedAt:0},this.streams.set(e.id,i),void this.$(i)}i.text=e.content,void 0===i.frame&&this.schedule(i)}schedule(t){t.frame=h(()=>{t.frame=void 0,performance.now()-t.renderedAt<this.streamIntervalMs?this.schedule(t):this.$(t)})}$(t){t.renderedAt=performance.now();const e=this.u(),i=function(t,e){let i=!1,s=e,c=e;for(;c<t.length;)if(t.startsWith("```",c))i=!i,c+=3;else if(!i&&t.startsWith("\n\n",c)){for(c+=2;"\n"===t[c];)c++;s=c}else c++;return s}(t.text,t.committed);i>t.committed&&(t.tail.insertAdjacentHTML("beforebegin",`<div class="cc-block">${o(t.text.slice(t.committed,i))}</div>`),t.committed=i),t.tail.innerHTML=o(t.text.slice(t.committed)),e&&this.m()}v(t){const e=this.streams.get(t);void 0!==(null==e?void 0:e.frame)&&l(e.frame),this.streams.delete(t)}u(){const{scrollHeight:t,scrollTop:e,clientHeight:i}=this.container;return t-e-i<=48}showTyping(){var t;this.t||(this.t=document.createElement("div"),this.t.className="cc-typing",this.t.innerHTML=`<span class="cc-sr-only">${this.C((null==(t=this.actions)?void 0:t.typingLabel)??"Typing...")}</span><div class="cc-typing-dot" aria-hidden="true"></div><div class="cc-typing-dot" aria-hidden="true"></div><div class="cc-typing-dot" aria-hidden="true"></div>`,this.container.appendChild(this.t),this.m())}removeTyping(){this.t&&(this.t.remove(),this.t=null)}showSuggestions(t,e,i){if(this.removeSuggestions(),0===t.length)return;const s=document.createElement("div");s.className="cc-suggestions",s.setAttribute("role","group"),s.setAttribute("aria-label",e);for(const c of t){const t=document.createElement("button");t.type="button",t.className="cc-suggestion",t.textContent=c,t.addEventListener("click",()=>i(c)),s.appendChild(t)}this.container.appendChild(s),this.i=s}removeSuggestions(){var t;null==(t=this.i)||t.remove(),this.i=null}clear(){for(const t of[...this.streams.keys()])this.v(t);this.container.innerHTML="",this.t=null,this.o&&this.container.prepend(this.o)}setDisclosure(t,e){var i;if(null==(i=this.o)||i.remove(),this.o=null,!t)return;const s=document.createElement("div");if(s.className="cc-disclosure",s.setAttribute("role","note"),s.textContent=t,e&&/^https?:\/\//i.test(e.url)){const t=document.createElement("a");t.href=e.url,t.target="_blank",t.rel="noopener noreferrer",t.textContent=e.label,s.append(" ",t)}this.o=s,this.container.prepend(s)}removeMessage(t){this.v(t);const e=this.l(t);null==e||e.remove()}clearRegenerateButtons(){this.container.querySelectorAll(".cc-message-regenerate").forEach(t=>{t.remove()}),this.M()}showRegenerateButton(t){var e;if(this.clearRegenerateButtons(),!(null==(e=this.actions)?void 0:e.onRegenerate))return;const i=this.l(t);i&&i.classList.contains("cc-message-assistant")&&this.S(i).appendChild(this.T({className:"cc-message-regenerate",label:this.actions.regenerateLabel??"Regenerate",icon:'<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0020 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74A7.93 7.93 0 004 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/></svg>',onClick:()=>{var e,i;return null==(i=null==(e=this.actions)?void 0:e.onRegenerate)?void 0:i.call(e,t)}}))}setVisible(t){this.container.classList.toggle("cc-hidden",!t)}l(t){return Array.from(this.container.children).find(e=>e.dataset.id===t)??null}m(){this.container.scrollTop=this.container.scrollHeight}p(t){const e=document.createElement("div");return this.k(e,t),e}k(t,e){var i;t.className=`cc-message cc-message-${e.role}`,t.dataset.id=e.id,"assistant"===e.role&&"welcome"!==e.id&&(t.dataset.aiGenerated="true"),e.status?t.dataset.status=e.status:delete t.dataset.status,"streaming"===e.status?t.setAttribute("aria-busy","true"):t.removeAttribute("aria-busy"),e.errorType?t.dataset.errorType=e.errorType:delete t.dataset.errorType,t.innerHTML="";const s=document.createElement("div");if(s.className="cc-message-content",s.innerHTML="assistant"===e.role?o(e.content):this.C(e.content),t.appendChild(s),"assistant"===e.role&&Array.isArray(e.sources)&&e.sources.length>0){const s=e.sources.filter(t=>"string"==typeof t.url&&(t.url.startsWith("http://")||t.url.startsWith("https://")));if(s.length>0){const e=document.createElement("nav");e.className="cc-message-sources",e.setAttribute("aria-label",(null==(i=this.actions)?void 0:i.sourcesLabel)??"Sources");const c=document.createElement("ol");for(const t of s){const e=document.createElement("li"),i=document.createElement("a");i.href=t.url,i.target="_blank",i.rel="noopener noreferrer";try{i.textContent=t.title??new URL(t.url).hostname}catch{i.textContent=t.title??t.url}e.appendChild(i),c.appendChild(e)}e.appendChild(c),t.appendChild(e)}}if("error"===e.status&&e.errorText){const i=document.createElement("div");i.className="cc-message-error-note",i.textContent=e.errorText,t.appendChild(i)}const c=this.A(e);c&&t.appendChild(c)}A(t){var e;if("error"!==t.status||!(null==(e=this.actions)?void 0:e.onRetry))return null;const i=document.createElement("div");return i.className="cc-message-actions",i.appendChild(this.T({className:"cc-message-retry",label:this.actions.retryLabel??"Retry",icon:'<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M17.65 6.35A7.96 7.96 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>',onClick:()=>{var e,i;return null==(i=null==(e=this.actions)?void 0:e.onRetry)?void 0:i.call(e,t.id)}})),i}S(t){const e=t.querySelector(".cc-message-actions");if(e)return e;const i=document.createElement("div");return i.className="cc-message-actions",t.appendChild(i),i}M(){this.container.querySelectorAll(".cc-message-actions").forEach(t=>{t.hasChildNodes()||t.remove()})}T(t){const e=document.createElement("button");return e.type="button",e.className=t.className,e.innerHTML=`${t.icon}<span>${this.C(t.label)}</span>`,e.addEventListener("click",t.onClick),e}C(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}}const h=t=>"function"==typeof requestAnimationFrame?requestAnimationFrame(t):setTimeout(t,16),l=t=>"function"==typeof cancelAnimationFrame?cancelAnimationFrame(t):clearTimeout(t);class d{constructor(t,e){this._=e._,this.L=document.createElement("div"),this.L.className="cc-input-area",this.B=document.createElement("textarea"),this.B.className="cc-input",this.B.placeholder=e.placeholder,this.B.setAttribute("aria-label",e.placeholder),this.B.rows=1,this.B.maxLength=1e4,this.B.addEventListener("input",()=>this.O()),this.B.addEventListener("keydown",t=>this.I(t)),this.j=document.createElement("button"),this.j.className="cc-send-btn",this.j.disabled=!0,this.j.setAttribute("aria-label",e.sendLabel),this.j.innerHTML='<svg viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>',this.j.addEventListener("click",()=>this.send()),this.B.addEventListener("input",()=>{this.j.disabled=0===this.B.value.trim().length}),this.L.appendChild(this.B),this.L.appendChild(this.j),t.appendChild(this.L)}setLabels(t,e){this.B.placeholder=t,this.B.setAttribute("aria-label",t),this.j.setAttribute("aria-label",e)}focus(){this.B.focus()}setDisabled(t){this.B.disabled=t,this.j.disabled=t||0===this.B.value.trim().length}clear(){this.B.value="",this.j.disabled=!0,this.O()}setVisible(t){this.L.classList.toggle("cc-hidden",!t)}send(){const t=this.B.value.trim();t&&(this._(t),this.clear())}I(t){t.isComposing||229===t.keyCode||"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.send())}O(){this.B.style.height="auto",this.B.style.height=Math.min(this.B.scrollHeight,96)+"px"}}const u="cc-panel";class p{constructor(t,e){this.D=e.D??!1,this.N=document.createElement("div"),this.N.className="cc-panel",e.D&&this.N.classList.add("cc-inline"),"bottom-left"===e.position&&this.N.classList.add("cc-left"),e.D||(this.N.id=u,this.N.setAttribute("role","dialog"),this.N.setAttribute("aria-modal","true"),this.N.addEventListener("keydown",t=>{if("Escape"===t.key)return void e.onClose();if("Tab"!==t.key||this.N.hasAttribute("inert"))return;const i=Array.from(this.N.querySelectorAll("*")).filter(t=>t.tabIndex>=0&&!t.matches(":disabled")&&!t.closest('[hidden], [inert], [aria-hidden="true"], .cc-hidden'));if(0===i.length)return void t.preventDefault();const s=this.N.getRootNode().activeElement,c=i[0],r=i[i.length-1];!t.shiftKey||s!==c&&this.N.contains(s)?t.shiftKey||s!==r&&this.N.contains(s)||(t.preventDefault(),c.focus()):(t.preventDefault(),r.focus())}),this.R(!0)),this.options=e,this.header=document.createElement("div"),this.header.className="cc-header",this.P(),this.N.appendChild(this.header),e.preChatEnabled?(this.H=document.createElement("div"),this.H.className="cc-messages-wrapper",this.N.appendChild(this.H)):this.H=this.N,this.messages=new a(this.H,e.messageActions),this.input=new d(this.N,{placeholder:e.placeholder,sendLabel:e.sendLabel,_:e._}),this.footer=document.createElement("div"),this.footer.className="cc-footer",this.footer.innerHTML=e.footerText,this.N.appendChild(this.footer),t.appendChild(this.N)}update(t,e){Object.assign(this.options,t),this.options.messageActions&&Object.assign(this.options.messageActions,e),this.P(),this.input.setLabels(t.placeholder,t.sendLabel),this.footer.innerHTML=t.footerText}P(){const{branding:t,F:e,D:i,onClose:s}=this.options,c=this.header.contains(this.N.getRootNode().activeElement);if(this.header.replaceChildren(),i||this.N.setAttribute("aria-label",t.name),t.avatar){const e=document.createElement("img");e.className="cc-header-avatar",e.src=t.avatar,e.alt=t.name,this.header.appendChild(e)}else{const t=document.createElement("div");t.className="cc-header-avatar-placeholder",t.innerHTML='<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/></svg>',this.header.appendChild(t)}const r=document.createElement("div");if(r.className="cc-header-info",r.innerHTML=`<div class="cc-header-name">${this.C(t.name)}</div><div class="cc-header-subtitle">${this.C(t.subtitle)}</div>`,this.header.appendChild(r),!i){const t=document.createElement("button");t.className="cc-header-close",t.setAttribute("aria-label",e),t.innerHTML='<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>',t.addEventListener("click",s),this.header.appendChild(t),c&&t.focus()}}show(){this.N.classList.add("cc-visible"),this.D||(this.R(!1),this.input.focus())}hide(){this.N.classList.remove("cc-visible"),this.D||this.R(!0)}containsFocus(){return this.N.contains(this.N.getRootNode().activeElement)}get isVisible(){return this.N.classList.contains("cc-visible")}addMessage(t){return this.messages.addMessage(t)}hideMessages(){this.messages.setVisible(!1)}showMessages(){this.messages.setVisible(!0)}destroy(){this.N.remove()}R(t){this.N.toggleAttribute("inert",t),t?this.N.setAttribute("aria-hidden","true"):this.N.removeAttribute("aria-hidden")}C(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}}class f{constructor(t,e){this.U=e.U,this.F=e.F,this.q=e.q,this.N=document.createElement("button"),this.N.className="cc-fab cc-pulse",this.N.setAttribute("aria-label",this.U),this.N.setAttribute("aria-expanded","false"),this.N.setAttribute("aria-controls",u),"bottom-left"===e.position&&this.N.classList.add("cc-left"),this.N.innerHTML=c,this.badge=document.createElement("div"),this.badge.className="cc-fab-badge",this.N.appendChild(this.badge),this.N.addEventListener("click",()=>{this.N.classList.remove("cc-pulse"),e.onClick()}),t.appendChild(this.N)}setOpen(t){t&&this.hideBadge(),this.N.innerHTML=t?'<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>':c,t||this.N.appendChild(this.badge),this.N.classList.toggle("cc-open",t),this.N.setAttribute("aria-label",t?this.F:this.U),this.N.setAttribute("aria-expanded",String(t))}setLabels(t,e,i){this.U=t,this.F=e,this.q=i;const s=this.badge.textContent;this.N.setAttribute("aria-label",this.N.classList.contains("cc-open")?e:s?`${t}, ${i.replace("{count}",s)}`:t)}focus(){this.N.focus()}showBadge(t=1){if(t<=0)return void this.hideBadge();const e=t>9?"9+":String(t);if(this.badge.textContent=e,!this.N.classList.contains("cc-open")){const t=this.q.replace("{count}",e);this.N.setAttribute("aria-label",`${this.U}, ${t}`)}this.badge.classList.add("cc-visible")}hideBadge(){this.badge.classList.remove("cc-visible"),this.badge.textContent="",this.N.classList.contains("cc-open")||this.N.setAttribute("aria-label",this.U)}destroy(){this.N.remove()}}const g="chatcops_bubble_shown";class b{constructor(t,e){this.V=null,this.N=document.createElement("div"),this.N.className="cc-bubble","bottom-left"===e.position&&this.N.classList.add("cc-left"),this.R(!0);const i=document.createElement("button");i.type="button",i.className="cc-bubble-trigger",i.textContent=e.text,i.addEventListener("click",()=>{this.hide(),e.onClick()});const s=document.createElement("button");s.type="button",s.className="cc-bubble-close",s.setAttribute("aria-label",e.dismissLabel),s.innerHTML="&times;",s.addEventListener("click",t=>{t.stopPropagation(),this.hide()}),this.N.append(i,s),t.appendChild(this.N),this.V=setTimeout(()=>{if(e.showOnce){if(e.store.get(g))return;e.store.set(g,"1")}this.N.classList.add("cc-visible"),this.R(!1)},e.delay??3e3)}hide(){this.N.classList.remove("cc-visible"),this.R(!0),this.V&&(clearTimeout(this.V),this.V=null)}R(t){this.N.toggleAttribute("inert",t),t?this.N.setAttribute("aria-hidden","true"):this.N.removeAttribute("aria-hidden")}destroy(){this.hide(),this.N.remove()}}const m="chatcops_conversation";function v(t){if("none"===t){const t=new Map;return{get:e=>t.get(e)??null,set:(e,i)=>{t.set(e,i)},remove:e=>{t.delete(e)}}}const e=()=>"local"===t?localStorage:sessionStorage;return{get(t){try{return e().getItem(t)}catch{return null}},set(t,i){try{e().setItem(t,i)}catch{}},remove(t){try{e().removeItem(t)}catch{}}}}class x{constructor(t,e="local",i=30){this.store=v(e),this.key=t?`${m}_${t}`:m,this.Y=864e5*(Number.isFinite(i)&&i>=0?i:30)}load(t=Date.now()){const e=this.store.get(this.key);if(null===e)return null;let i;try{i=JSON.parse(e)}catch{return this.clear(),null}if("object"!=typeof i||null===i||Array.isArray(i)||"string"!=typeof i.id||!Array.isArray(i.messages))return this.clear(),null;const s=i;if("number"==typeof s.updatedAt&&t-s.updatedAt>this.Y)return this.clear(),null;const c=s.messages.flatMap(t=>{if("object"!=typeof t||null===t||Array.isArray(t)||"user"!==t.role&&"assistant"!==t.role||"string"!=typeof t.content)return[];const e=t;let i;if(Array.isArray(e.sources)){const t=e.sources.filter(t=>"object"==typeof t&&null!==t&&!Array.isArray(t)&&"string"==typeof t.url&&(void 0===t.title||"string"==typeof t.title));t.length>0&&(i=t)}return[{...e,sources:i}]}),r=s.userData;return{...s,id:s.id,messages:c,userData:r&&"object"==typeof r&&!Array.isArray(r)?r:void 0,preChatDone:!0===s.preChatDone}}save(t){const e={...t,messages:t.messages.filter(t=>"error"!==t.status).map(({status:t,...e})=>e)};this.store.set(this.key,JSON.stringify(e))}clear(){this.store.remove(this.key)}}class y{constructor(t){this.apiUrl=t.apiUrl,this.turnstileSiteKey=t.turnstileSiteKey,this.userToken=t.userToken,this.timeout=t.timeout??3e4,this.J=`chatcops-session:${t.apiUrl}`,this.store=t.store??v("local")}setUserToken(t){t!==this.userToken&&(this.userToken=t,this.saved={},this.store.remove(this.J))}get identity(){return this.userToken}async*sendMessage(t,e={}){var i;const s=new AbortController,c=e.timeout??this.timeout;let r,n,o=!1;const a=e.signal,h=()=>{clearTimeout(r),s.abort()},l=()=>{clearTimeout(r),s.signal.aborted||(r=setTimeout(()=>{o=!0,s.abort()},c))},d=async()=>{if(clearTimeout(r),null==a||a.removeEventListener("abort",h),n){const t=n;n=void 0;try{await t.cancel()}catch{}finally{t.releaseLock()}}};a&&(a.aborted?s.abort():a.addEventListener("abort",h)),l();try{const e=(t,e,i)=>fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...i&&{Authorization:`Bearer ${i}`}},body:JSON.stringify(e),signal:s.signal});let c=this.saved;if(!c){try{c=JSON.parse(this.store.get(this.J)||"{}")??{}}catch{c={}}this.saved=c}const r=c.conversationId===t.conversationId;let o=await e(this.apiUrl,{protocol:1,...t},r?c.token:void 0);if(401===o.status){const i=await e(this.apiUrl.replace(/\/?(\?.*)?$/,"/session$1"),{conversationId:t.conversationId,previousToken:c.token,userToken:this.userToken,turnstileToken:this.turnstileSiteKey&&!r?await(await Promise.resolve().then(()=>et)).turnstileToken(this.turnstileSiteKey):void 0});if(i.ok){const s=await i.json();this.saved=s,this.store.set(this.J,JSON.stringify(s)),s.conversationId!==t.conversationId&&(t={...t,conversationId:s.conversationId},yield{conversationId:s.conversationId}),o=await e(this.apiUrl,{protocol:1,...t},s.token)}else this.saved={}}if(!o.ok){const{error:t}=await o.json().catch(()=>({}));return await d(),void(yield(null==t?void 0:t.code)?k(t.code,t.retryAfterMs):{error:429===o.status?"rate_limit":`HTTP ${o.status}`})}if(n=null==(i=o.body)?void 0:i.getReader(),!n)return await d(),void(yield{error:"No response body"});const a=new TextDecoder;let h="",u=!1,p=!1;for(;;){const{done:t,value:e}=await n.read();if(t)break;e.byteLength>0&&l(),h+=a.decode(e,{stream:!0});const i=h.split("\n");h=i.pop()??"";for(const s of i){const t=s.trim();if(!t||!t.startsWith("data: "))continue;const e=t.slice(6);if("[DONE]"===e)return await d(),void(yield u&&!p?{error:"cut_off"}:{done:!0});let i;try{i=JSON.parse(e)}catch{continue}if("type"in i){u=!0,"finish"===i.type&&(p=!0);const t=$(i);t&&(yield t)}else yield i}}await d(),yield"data: [DONE]"===h.trim()?{done:!0}:{error:u?"cut_off":"network"}}catch(u){await d(),u instanceof DOMException&&"AbortError"===u.name?yield o?{error:"timeout"}:{error:"aborted"}:yield{error:"network"}}finally{await d()}}}const w={rate_limited:"rate_limit",timeout:"timeout",budget_exceeded:"budget",budget_daily:"budget_daily",provider_unavailable:"unavailable"};function k(t,e){return{error:w[t]??"provider_error",retryAfterMs:e}}function $(t){switch(t.type){case"start":return{messageId:t.messageId};case"text-delta":return{content:t.delta};case"lead-captured":return{leadCaptured:!0,leadData:t.lead};case"source":{const{url:e,title:i}=t;return e.startsWith("http://")||e.startsWith("https://")?{source:{url:e,title:i}}:null}case"error":return k("budget_exceeded"===t.code&&"conversation"!==t.scope?"budget_daily":t.code,t.retryAfterMs);case"finish":return"error"===t.reason||"aborted"===t.reason?null:{done:!0};default:return null}}const C=Symbol.for("chatcops.storageClaims"),M=globalThis;M[C]??(M[C]=new Map);const S=M[C];function z(t){const e=S.get(t);if(!e)return!1;for(const i of e)i()||e.delete(i);return 0===e.size&&S.delete(t),e.size>0}const T=["light","dark","auto"];function A(t,e){const i=t.host,s=function(t){return t.mode&&T.includes(t.mode)?t.mode:t.bgColor?I(t.bgColor)&&j(t.bgColor)>.4?"light":"dark":t.textColor?I(t.textColor)&&j(t.textColor)<.4?"light":"dark":void 0}(e);if(s?i.dataset.ccMode=s:delete i.dataset.ccMode,e.accent&&_(i,"",e.accent),e.accentDark&&_(i,"-dark",e.accentDark),e.textColor&&i.style.setProperty("--cc-text",e.textColor),e.bgColor&&(i.style.setProperty("--cc-bg",e.bgColor),i.style.setProperty("--cc-bg-surface",P(e.bgColor,8)),i.style.setProperty("--cc-bg-input",P(e.bgColor,14))),e.fontFamily&&i.style.setProperty("--cc-font",e.fontFamily),void 0!==e.borderRadius){const t=function(t){if("number"==typeof t&&!Number.isFinite(t))return"";const e=String(t).trim();return/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(e)?`${e}px`:e}(e.borderRadius);t&&i.style.setProperty("--cc-radius",t)}}function _(t,e,i){t.style.setProperty(`--cc-theme-accent${e}`,i),t.style.setProperty(`--cc-theme-accent${e}-hover`,R(i,10));const s=function(t){if(!I(t))return null;const e=t.trim().startsWith("#")?t.trim():`#${t.trim()}`;if(E(L,e)>=O)return{onAccent:L,background:e};if(E(B,e)>=O)return{onAccent:B,background:e};for(let i=2;i<=60;i+=2){const t=R(e,i);if(E(L,t)>=O)return{onAccent:L,background:t}}return{onAccent:L,background:B}}(i);s?(t.style.setProperty(`--cc-theme-on-accent${e}`,s.onAccent),t.style.setProperty(`--cc-theme-accent${e}-contrast`,s.background)):t.style.setProperty(`--cc-theme-accent${e}-contrast`,i)}const L="#ffffff",B="#0a0a0a",O=4.5;function I(t){return/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(t.trim())}function j(t){const e=D(t).map(t=>{const e=t/255;return e<=.03928?e/12.92:((e+.055)/1.055)**2.4});return.2126*e[0]+.7152*e[1]+.0722*e[2]}function E(t,e){const[i,s]=[j(t),j(e)].sort((t,e)=>e-t);return(i+.05)/(s+.05)}function D(t){if(!/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(t))return[0,0,0];const e=t.replace("#",""),i=parseInt(3===e.length?e.split("").map(t=>t+t).join(""):e,16);return[i>>16&255,i>>8&255,255&i]}function N(t,e,i){return"#"+[t,e,i].map(t=>Math.max(0,Math.min(255,t)).toString(16).padStart(2,"0")).join("")}function R(t,e){const[i,s,c]=D(t),r=1-e/100;return N(Math.round(i*r),Math.round(s*r),Math.round(c*r))}function P(t,e){const[i,s,c]=D(t),r=e/100;return N(Math.round(i+(255-i)*r),Math.round(s+(255-s)*r),Math.round(c+(255-c)*r))}const H={welcomeMessage:"How can I help you today?",inputPlaceholder:"Type a message...",sendButton:"Send",closeButton:"Close",openChat:"Open chat",defaultName:"AI Assistant",defaultSubtitle:"Online",greetingWithName:"Hi {name}!",selectPlaceholder:"Select {label}...",dismissBubble:"Dismiss",errorGeneric:"Something went wrong. Please try again.",errorNetwork:"Connection error. Please check your network.",errorRateLimit:"Too many messages. Please wait a moment.",errorRateLimitWait:"Too many messages. Please try again in {seconds} seconds.",errorBudget:"This chat has reached its limit.",errorBudgetDaily:"The assistant has reached its limit for today. Please try again later.",errorUnavailable:"The assistant is unavailable right now. Please try again later.",errorCutOff:"The reply was cut off.",typingIndicator:"Typing...",poweredBy:"Powered by ChatCops",newConversation:"New conversation",welcomeBubbleDefault:"Need help? Chat with us!",preChatTitle:"Before we start...",preChatSubtitle:"Tell us a bit about yourself",preChatSubmit:"Start Chat",preChatRequired:"This field is required",preChatInvalidEmail:"Please enter a valid email",retryButton:"Retry",regenerateButton:"Regenerate",suggestionsLabel:"Suggested questions",unreadCount:"{count} unread",sourcesLabel:"Sources",disclosure:"You're chatting with an AI assistant. It can make mistakes.",disclosureLearnMore:"Learn more"},F={en:H};function U(t,e){const i=F[t]??H;return e?{...i,...e}:i}const q={network:"errorNetwork",timeout:"errorNetwork",provider_error:"errorGeneric",budget:"errorBudget",budget_daily:"errorBudgetDaily",unavailable:"errorUnavailable",cut_off:"errorCutOff"};let V;function Y(){return V??(V=Promise.resolve().then(()=>it).catch(t=>{throw V=void 0,t})),V}class J{constructor(t){if(this.G=!1,this.conversationId=crypto.randomUUID(),this.preChatDone=!1,this.K=!1,this.messages=[],this.W=!1,this.v1=!1,this.X=!1,this.generation=0,this.Z=!1,this.tt=new Map,this.et=new Map,this.it=0,"persistHistory"in t)throw new Error("ChatCops: persistHistory was removed in 1.0. Use persistence: 'none'.");this.config=t,this.st=function(t,e,i){let s=t??"";if(void 0===t&&z("")){s=e;for(let t=2;z(s);t+=1)s=`${e}-${t}`;console.warn(`[chatcops] Another widget on this page already uses the default storage, so this one keeps its conversation under "${s}". Set a \`siteId\` on each widget to name them yourself.`)}else void 0!==t&&z(t)&&console.warn(`[chatcops] Two widgets on this page use the siteId "${t}", so they share one conversation.`);return S.has(s)||S.set(s,new Set),S.get(s).add(i),{siteId:""===s?void 0:s,release(){var t,e;null==(t=S.get(s))||t.delete(i),0===(null==(e=S.get(s))?void 0:e.size)&&S.delete(s)}}}(t.siteId,t.mode??"popup",()=>!this.X&&(!this.G||this.ct.host.isConnected));const e=t.persistence??"local";this.storage=new x(this.st.siteId,e,t.historyTtlDays),this.client=new y({...t,store:this.storage.store}),this.locale=U(t.locale??"en",t.strings)}get isInline(){return"inline"===this.config.mode}rt(){if(!this.config.container)throw new Error('ChatCops: "container" is required when mode is "inline"');if("string"==typeof this.config.container){const t=document.querySelector(this.config.container);if(!t)throw new Error(`ChatCops: container element not found: ${this.config.container}`);return t}return this.config.container}init(){var t,e;!function(t){var e;(null==(e=t.preChatForm)?void 0:e.enabled)&&Y().catch(()=>{})}(this.config),this.isInline?(this.nt=this.rt(),this.ct=s(this.nt,{dir:this.config.dir,locale:this.config.locale})):this.ct=s(void 0,{dir:this.config.dir,locale:this.config.locale}),this.G=!0,this.config.theme&&A(this.ct,this.config.theme);const i=(null==(t=this.config.theme)?void 0:t.position)??"bottom-right";if(this.isInline||(this.ot=new f(this.ct,{position:i,U:this.locale.openChat,F:this.locale.closeButton,q:this.locale.unreadCount,onClick:()=>this.toggle()})),this.ht=new p(this.ct,{position:i,D:this.isInline,preChatEnabled:(null==(e=this.config.preChatForm)?void 0:e.enabled)??!1,...this.lt(),messageActions:{onRetry:t=>{this.dt(t)},onRegenerate:t=>{this.ut(t)},...this.actionLabels()},_:t=>this.ft(t),onClose:()=>this.close()}),!1===this.config.disclosure&&console.info("[chatcops] The AI disclosure is off (disclosure: false). Under the EU AI Act (Article 50), telling visitors they're talking to an AI is then up to you."),this.gt(),this.isInline&&this.hydrate(),!this.isInline&&this.config.welcomeBubble&&(this.bt=new b(this.ct,{text:this.config.welcomeBubble.text,delay:this.config.welcomeBubble.delay,showOnce:this.config.welcomeBubble.showOnce??!0,store:this.storage.store,position:i,dismissLabel:this.locale.dismissBubble,onClick:()=>this.open()})),this.isInline&&this.ht.show(),!this.isInline&&void 0!==this.config.autoOpen&&!1!==this.config.autoOpen){const t="number"==typeof this.config.autoOpen?this.config.autoOpen:0;this.vt=setTimeout(()=>this.open(),t)}}hydrate(){var t,e;if(this.K)return;this.K=!0;const i=this.storage.load();if(i){this.conversationId=i.id,this.preChatDone=i.preChatDone??!1,(null==(t=this.config.preChatForm)?void 0:t.enabled)&&(this.userData=i.userData);for(const t of i.messages)this.messages.push(t),this.ht.addMessage(t)}(null==(e=this.config.preChatForm)?void 0:e.enabled)&&!this.preChatDone&&0===this.messages.length?this.showPreChatForm():this.xt(),this.yt()}open(){var t,e,i,s;this.it=0,this.hydrate(),this.ht.show(),this.isInline||(null==(t=this.ot)||t.setOpen(!0),null==(e=this.bt)||e.hide()),this.wt(),null==(s=(i=this.config).onOpen)||s.call(i),this.emit("open")}close(){var t,e,i,s;const c=this.ht.containsFocus();this.ht.hide(),this.isInline||(null==(t=this.ot)||t.setOpen(!1),c&&(null==(e=this.ot)||e.focus())),this.kt(),null==(s=(i=this.config).onClose)||s.call(i),this.emit("close")}toggle(){this.ht.isVisible?this.close():this.open()}async sendMessage(t,e={}){!1===e.open?this.hydrate():this.open(),await this.ft(t)}newConversation(){this.reset(!1)}clear(){this.reset(!0)}reset(t){var e,i,s;this.generation++,null==(e=this.$t)||e.abort(),this.$t=void 0,this.W=!1,this.tt.clear(),this.messages=[],this.conversationId=crypto.randomUUID(),this.K=!0,t&&(this.userData=void 0,this.preChatDone=!1,this.storage.clear()),null==(i=this.Ct)||i.destroy(),this.Ct=void 0,this.ht.messages.clear(),this.ht.input.setDisabled(!1),(null==(s=this.config.preChatForm)?void 0:s.enabled)&&!this.preChatDone?this.showPreChatForm():this.xt(),t||this.Mt()}setUser(t){const e=this.client.identity,i=null==t?void 0:t.token;if(void 0!==e&&e!==i&&this.clear(),this.client.setUserToken(i),!t)return;const s=Object.fromEntries(Object.entries({name:t.name,email:t.email}).filter(t=>"string"==typeof t[1]&&""!==t[1]));Object.keys(s).length&&(this.userData={...this.userData,...s},this.Z=!0)}setContext(t){this.St=t&&Object.keys(t).length?{...t}:void 0}update(t){var e,i;const s=this.config,c={...s.theme,...t.theme,position:null==(e=s.theme)?void 0:e.position};if(this.config={...s,...t,theme:c,branding:{...s.branding,...t.branding},strings:{...s.strings,...t.strings}},this.locale=U(this.config.locale??"en",this.config.strings),!this.G)return;t.theme&&A(this.ct,c);const r=this.locale;null==(i=this.ot)||i.setLabels(r.openChat,r.closeButton,r.unreadCount),this.ht.update(this.lt(),this.actionLabels()),this.gt(),1===this.messages.length&&"welcome"===this.messages[0].id&&(this.messages=[],this.ht.messages.clear(),this.xt())}lt(){const{branding:t,placeholder:e}=this.config,i=this.locale;return{branding:{name:(null==t?void 0:t.name)??i.defaultName,avatar:null==t?void 0:t.avatar,subtitle:(null==t?void 0:t.subtitle)??i.defaultSubtitle},placeholder:e??i.inputPlaceholder,footerText:i.poweredBy,F:i.closeButton,sendLabel:i.sendButton}}actionLabels(){const t=this.locale;return{retryLabel:t.retryButton,regenerateLabel:t.regenerateButton,typingLabel:t.typingIndicator,sourcesLabel:t.sourcesLabel}}gt(){const{disclosure:t}=this.config;!1===t?this.ht.messages.setDisclosure():this.ht.messages.setDisclosure((null==t?void 0:t.text)??this.locale.disclosure,(null==t?void 0:t.learnMoreUrl)?{url:t.learnMoreUrl,label:this.locale.disclosureLearnMore}:void 0)}zt(t){return this.X||t!==this.generation}destroy(){var t,e,i,s,c;this.X=!0,void 0!==this.vt&&clearTimeout(this.vt),null==(t=this.$t)||t.abort(),this.$t=void 0,this.kt(),null==(e=this.Ct)||e.destroy(),null==(i=this.bt)||i.destroy(),this.ht.destroy(),null==(s=this.ot)||s.destroy(),null==(c=this.ct)||c.host.remove(),this.st.release(),this.et.clear(),this.messages=[],this.userData=void 0}wt(){var t,e;if(void 0===this.Tt&&!this.isInline&&"undefined"!=typeof window&&(null==(e=null==(t=window.matchMedia)?void 0:t.call(window,"(max-width: 640px)"))?void 0:e.matches)){const t=document.documentElement;this.Tt={value:t.style.getPropertyValue("overflow"),priority:t.style.getPropertyPriority("overflow")},t.style.setProperty("overflow","hidden")}}kt(){if(void 0===this.Tt)return;const{value:t,priority:e}=this.Tt;t?document.documentElement.style.setProperty("overflow",t,e):document.documentElement.style.removeProperty("overflow"),this.Tt=void 0}on(t,e){return this.et.has(t)||this.et.set(t,new Set),this.et.get(t).add(e),()=>this.off(t,e)}off(t,e){var i;null==(i=this.et.get(t))||i.delete(e)}emit(t,...e){var i;this.X||null==(i=this.et.get(t))||i.forEach(t=>{t(...e)})}showPreChatForm(){const t=this.config.preChatForm;this.ht.hideMessages(),this.ht.input.setVisible(!1),Y().then(({PreChatForm:e})=>{this.X||this.preChatDone||this.Ct||(this.Ct=new e(this.ht.H,{title:t.title??this.locale.preChatTitle,subtitle:t.subtitle??this.locale.preChatSubtitle,fields:t.fields,submitLabel:t.submitLabel??this.locale.preChatSubmit,locale:this.locale,onSubmit:t=>this.At(t)}))},t=>{console.error("[chatcops] The pre-chat form could not load:",t instanceof Error?t.message:t),this.X||this.preChatDone||(this.preChatDone=!0,this.ht.showMessages(),this.ht.input.setVisible(!0),this.xt())})}At(t){var e,i,s,c;(null==(e=this.config.preChatForm)?void 0:e.enabled)&&(this.hydrate(),this.userData=t,this.preChatDone=!0,this.Mt(),null==(i=this.Ct)||i.destroy(),this.Ct=void 0,this.ht.showMessages(),this.ht.input.setVisible(!0),this.xt(),null==(c=(s=this.config).onPreChatSubmit)||c.call(s,t),this.emit("preChatSubmit",t),t.message&&this.ft(t.message))}xt(){var t;if(0===this.messages.length){const e=null==(t=this.userData)?void 0:t.name,i=this.locale.greetingWithName.replace("{name}",()=>e),s={id:"welcome",role:"assistant",content:e?`${i} ${this.config.welcomeMessage??this.locale.welcomeMessage}`:this.config.welcomeMessage??this.locale.welcomeMessage};this.messages.push(s),this.ht.addMessage(s),this._t()}}_t(t=this.config.suggestions??[]){this.messages.some(t=>"user"===t.role)||this.ht.messages.showSuggestions(t,this.locale.suggestionsLabel,t=>{this.ft(t)})}async ft(t){var e,i;if(this.W)return;this.hydrate();const s={id:crypto.randomUUID(),role:"user",content:t};this.messages.push(s),this.ht.addMessage(s),null==(i=(e=this.config).onMessage)||i.call(e,s),this.emit("message",s),await this.Lt(t,{userMessageId:s.id})}async dt(t){if(this.W)return;const e=this.messages.findIndex(e=>e.id===t);if(-1===e)return;const i=this.tt.get(t);let s=(null==i?void 0:i.userMessageId)?this.messages.find(t=>t.id===i.userMessageId):void 0;if(!s)for(let c=e-1;c>=0;c--)if("user"===this.messages[c].role){s=this.messages[c];break}s&&(this.ht.messages.removeMessage(t),this.tt.delete(t),this.messages=this.messages.filter(e=>e.id!==t),await this.Lt(s.content,{regenerate:null==i?void 0:i.regenerate,userMessageId:(null==i?void 0:i.userMessageId)??s.id}))}async ut(t){if(this.W)return;const e=this.messages.findIndex(e=>e.id===t);if(-1===e)return;if("assistant"!==this.messages[e].role)return;const i=this.Bt(e);i&&(this.ht.messages.clearRegenerateButtons(),this.ht.messages.removeMessage(t),this.tt.delete(t),this.messages=this.messages.filter(e=>e.id!==t),await this.Lt(i.content,{regenerate:!this.v1||{assistantMessageId:t},userMessageId:i.id}))}async Lt(t,e={}){var i,s,c,r,n,o,a,h,l;if(this.W)return;const d=this.generation;this.W=!0,this.ht.input.setDisabled(!0),this.ht.messages.clearRegenerateButtons(),this.ht.messages.beginReply(),this.ht.messages.showTyping();const u={id:crypto.randomUUID(),role:"assistant",content:"",status:"streaming",sources:[]};let p=!0,f=!1,g=!1;const b=new AbortController;this.$t=b;try{for await(const n of this.client.sendMessage(this.Ot(t,e),{signal:b.signal})){if(this.zt(d))break;if(n.error){const t=this.It(n.error);this.jt(u,this.Et(t,n.retryAfterMs)),u.errorType=t,g=!0,this.tt.set(u.id,{regenerate:e.regenerate,userMessageId:e.userMessageId}),this.ht.messages.removeTyping(),p?this.ht.addMessage(u):this.ht.messages.updateMessage(u),this.messages.push(u);const c=new Error(n.error);null==(s=(i=this.config).onError)||s.call(i,c),this.emit("error",c);break}if(n.done){f=!0;break}n.conversationId&&(this.conversationId=n.conversationId),n.messageId&&(u.id=n.messageId,this.v1=!0),n.leadCaptured&&(null==(r=(c=this.config).onLeadCaptured)||r.call(c,n.leadData),this.emit("leadCaptured",n.leadData)),n.source&&(u.sources??(u.sources=[]),u.sources.push(n.source)),n.content&&(p&&(this.ht.messages.removeTyping(),this.ht.addMessage(u),p=!1),u.content+=n.content,this.ht.messages.updateMessage(u))}if(this.zt(d))return;g||f||(f=!0),!g&&p&&this.ht.messages.removeTyping(),!g&&u.content&&(u.status="complete",this.ht.messages.updateMessage(u),this.messages.push(u),null==(o=(n=this.config).onMessage)||o.call(n,u),this.emit("message",u),this.yt(),this.isInline||this.ht.isVisible||(this.it++,null==(a=this.ot)||a.showBadge(this.it)))}catch(m){if(this.zt(d))return;this.jt(u,this.locale.errorGeneric),u.errorType="network",this.tt.set(u.id,{regenerate:e.regenerate,userMessageId:e.userMessageId}),this.ht.messages.removeTyping(),p?this.ht.addMessage(u):this.ht.messages.updateMessage(u),this.messages.push(u);const t=m instanceof Error?m:new Error(String(m));null==(l=(h=this.config).onError)||l.call(h,t),this.emit("error",t)}finally{this.$t===b&&(this.$t=void 0),this.zt(d)||(this.ht.messages.finishReply(u),this.W=!1,this.ht.input.setDisabled(!1),this.ht.input.focus(),this.Mt())}}Ot(t,e){var i;const s=!1!==this.config.pageContext?{url:window.location.href,title:document.title,...this.St?{data:this.St}:{}}:void 0,c=Boolean(((null==(i=this.config.preChatForm)?void 0:i.enabled)||this.Z)&&this.userData&&(!this.v1||this.Dt!==this.conversationId));return c&&(this.Dt=this.conversationId),{conversationId:this.conversationId,message:t,messageId:e.userMessageId,regenerate:e.regenerate,pageContext:s,locale:this.config.locale,...c?{userData:this.userData}:{}}}Bt(t){for(let e=t-1;e>=0;e--)if("user"===this.messages[e].role)return this.messages[e]}Nt(){for(let t=this.messages.length-1;t>=0;t--){const e=this.messages[t];if("welcome"!==e.id){if("assistant"!==e.role||"error"===e.status)return;return e}}}yt(){const t=this.Nt();t?this.ht.messages.showRegenerateButton(t.id):this.ht.messages.clearRegenerateButtons()}It(t){return t in q||"rate_limit"===t?t:"provider_error"}jt(t,e){t.status="error",t.content.trim()?t.errorText=e:t.content=e}Et(t,e){return"rate_limit"===t?e?this.locale.errorRateLimitWait.replace("{seconds}",String(Math.ceil(e/1e3))):this.locale.errorRateLimit:this.locale[q[t]??"errorGeneric"]}Mt(){const t=this.config.maxMessages??50,e=this.messages.filter(t=>"welcome"!==t.id).slice(-t);this.storage.save({id:this.conversationId,messages:e.map(t=>({id:t.id,role:t.role,content:t.content,status:t.status,errorType:t.errorType,timestamp:Date.now(),...t.sources&&t.sources.length>0?{sources:t.sources}:{}})),...this.userData?{userData:this.userData}:{},...this.preChatDone?{preChatDone:!0}:{},updatedAt:Date.now()})}}function G(t){if(void 0!==t)return""===t||"true"===t||"false"!==t&&(/^\d+$/.test(t)?Number(t):void 0)}let K=null;const W=new Map,X={init(t){K&&K.destroy(),K=new J(t);for(const[e,i]of W)for(const t of i)K.on(e,t);return K.init(),K},open(){null==K||K.open()},close(){null==K||K.close()},toggle(){null==K||K.toggle()},sendMessage:(t,e)=>(null==K?void 0:K.sendMessage(t,e))??Promise.resolve(),newConversation(){null==K||K.newConversation()},clear(){null==K||K.clear()},registerLocale(t,e,s){!function(t,e){F[t]={...H,...e}}(t,e),(null==s?void 0:s.dir)&&function(t,e){const s=t.toLowerCase().split(/[-_]/)[0];"rtl"===e?i.add(s):i.delete(s)}(t,s.dir)},setUser(t){null==K||K.setUser(t)},setContext(t){null==K||K.setContext(t)},update(t){null==K||K.update(t)},version:"1.0.0-rc.0",destroy(){null==K||K.destroy(),K=null},on(t,e){let i=W.get(t);return i||(i=new Set,W.set(t,i)),i.add(e),null==K||K.on(t,e),()=>{X.off(t,e)}},off(t,e){var i;null==(i=W.get(t))||i.delete(e),null==K||K.off(t,e)}};function Q(t){const e=t&&function(t){const e=t.dataset.apiUrl;if(!e)return;const i=t.dataset.mode,s=t.dataset.container;return{apiUrl:e,turnstileSiteKey:t.dataset.turnstileSiteKey,userToken:t.dataset.userToken,mode:i||void 0,container:s||void 0,theme:{mode:t.dataset.themeMode||void 0,accent:t.dataset.accent,accentDark:t.dataset.accentDark,textColor:t.dataset.textColor,bgColor:t.dataset.bgColor,fontFamily:t.dataset.fontFamily,borderRadius:t.dataset.borderRadius,position:t.dataset.position||void 0},branding:{name:t.dataset.brandName,avatar:t.dataset.brandAvatar,subtitle:t.dataset.brandSubtitle},welcomeMessage:t.dataset.welcomeMessage,welcomeBubble:t.dataset.welcomeBubble?{text:t.dataset.welcomeBubble,delay:/^\d+$/.test(t.dataset.welcomeBubbleDelay??"")?Number(t.dataset.welcomeBubbleDelay):void 0}:void 0,autoOpen:G(t.dataset.autoOpen),placeholder:t.dataset.placeholder,disclosure:"false"!==t.dataset.disclosure&&{text:t.dataset.disclosureText,learnMoreUrl:t.dataset.disclosureUrl},locale:t.dataset.locale,dir:["ltr","rtl","auto"].find(e=>e===t.dataset.dir),persistence:["local","session","none"].find(e=>e===t.dataset.persistence),historyTtlDays:/^\d+$/.test(t.dataset.historyTtlDays??"")?Number(t.dataset.historyTtlDays):void 0}}(t);e&&X.init(e)}const Z="undefined"!=typeof document?document.currentScript:null;let tt;Z&&Z.dataset.apiUrl&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>Q(Z),{once:!0}):Q(Z)),"undefined"!=typeof window&&(window.ChatCops=X);const et=Object.freeze(Object.defineProperty({__proto__:null,turnstileToken:async function(t){tt??(tt=new Promise((t,e)=>{const i=document.createElement("script");i.src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",i.onload=t,i.onerror=e,document.head.append(i)})),await tt;const e=document.createElement("div");e.style.cssText="position:fixed;bottom:96px;right:24px;z-index:2147483647",document.body.append(e);try{return await new Promise((i,s)=>{window.turnstile.render(e,{sitekey:t,appearance:"interaction-only",callback:i,"error-callback":s})})}finally{e.remove()}}},Symbol.toStringTag,{value:"Module"})),it=Object.freeze(Object.defineProperty({__proto__:null,PreChatForm:class{constructor(t,e){if(this.Rt=new Map,this.Pt=new Map,this.options=e,this.container=document.createElement("div"),this.container.className="cc-prechat",e.title){const t=document.createElement("div");t.className="cc-prechat-title",t.textContent=e.title,this.container.appendChild(t)}if(e.subtitle){const t=document.createElement("div");t.className="cc-prechat-subtitle",t.textContent=e.subtitle,this.container.appendChild(t)}const i=document.createElement("form");i.className="cc-prechat-fields",i.noValidate=!0,i.addEventListener("submit",t=>{t.preventDefault(),this.Ht()});for(const c of e.fields)i.appendChild(this.Ft(c));this.Ut=document.createElement("button"),this.Ut.type="submit",this.Ut.className="cc-prechat-submit",this.Ut.textContent=e.submitLabel,i.appendChild(this.Ut),this.container.appendChild(i),t.appendChild(this.container),function(t){if(!(t instanceof ShadowRoot)||t.querySelector("style[data-cc-prechat]"))return;const e=document.createElement("style");e.dataset.ccPrechat="",e.textContent=".cc-prechat{flex:1;overflow-y:auto;padding:24px 16px;display:flex;flex-direction:column;gap:16px}.cc-prechat-title{font-size:18px;font-weight:600;color:var(--cc-text)}.cc-prechat-subtitle{font-size:13px;color:var(--cc-text-secondary);margin-top:-8px}.cc-prechat-fields{display:flex;flex-direction:column;gap:14px}.cc-prechat-field{display:flex;flex-direction:column;gap:4px}.cc-prechat-label{font-size:13px;font-weight:500;color:var(--cc-text)}.cc-prechat-label .cc-required{color:var(--cc-danger);margin-inline-start:2px}.cc-prechat-input,.cc-prechat-select,.cc-prechat-textarea{background:var(--cc-bg-input);border:1px solid var(--cc-border);border-radius:8px;padding:8px 12px;color:var(--cc-text);font-family:var(--cc-font);font-size:14px;outline:none;transition:border-color .15s}.cc-prechat-input:focus,.cc-prechat-select:focus,.cc-prechat-textarea:focus{border-color:var(--cc-accent)}.cc-prechat-select{-webkit-appearance:auto;-moz-appearance:auto;appearance:auto}.cc-prechat-textarea{resize:none;line-height:1.5}.cc-prechat-error{font-size:12px;color:var(--cc-danger);min-height:0}.cc-prechat-error:empty{display:none}.cc-prechat-submit{background:var(--cc-accent-contrast);color:var(--cc-on-accent);border:none;border-radius:8px;padding:10px 16px;font-family:var(--cc-font);font-size:14px;font-weight:500;cursor:pointer;transition:background .15s;margin-top:8px}.cc-prechat-submit:hover{background:var(--cc-accent-hover)}.cc-prechat-submit:disabled{opacity:.5;cursor:not-allowed}.cc-prechat-input:focus-visible,.cc-prechat-select:focus-visible,.cc-prechat-textarea:focus-visible,.cc-prechat-submit:focus-visible{outline:2px solid transparent;box-shadow:var(--cc-focus-ring)}@media(max-width:640px){.cc-prechat-input,.cc-prechat-select,.cc-prechat-textarea{font-size:16px}}",t.appendChild(e)}(t.getRootNode()),this.qt();const s=this.Rt.values().next().value;s&&setTimeout(()=>s.focus(),100)}Ft(t){const e=document.createElement("div");e.className="cc-prechat-field";const i=`cc-prechat-${t.name}`,s=`cc-prechat-${t.name}-error`,c=document.createElement("label");if(c.className="cc-prechat-label",c.htmlFor=i,c.textContent=t.label,t.required){const t=document.createElement("span");t.className="cc-required",t.textContent="*",c.appendChild(t)}let r;if(e.appendChild(c),"select"===t.type){const e=document.createElement("select");e.className="cc-prechat-select";const i=document.createElement("option");i.value="",i.textContent=t.placeholder??this.options.locale.selectPlaceholder.replace("{label}",t.label.toLowerCase()),i.disabled=!0,i.selected=!0,e.appendChild(i);for(const s of t.options??[]){const t=document.createElement("option");t.value=s,t.textContent=s,e.appendChild(t)}r=e}else if("textarea"===t.type){const e=document.createElement("textarea");e.className="cc-prechat-textarea",e.placeholder=t.placeholder??"",e.rows=3,e.maxLength=500,r=e}else{const e=document.createElement("input");e.type=t.type,e.className="cc-prechat-input",e.maxLength=500,e.placeholder=t.placeholder??"",r=e}r.name=t.name,r.id=i,t.required&&r.setAttribute("aria-required","true"),r.addEventListener("input",()=>{this.Vt(t.name),this.qt()}),r instanceof HTMLSelectElement&&r.addEventListener("change",()=>{this.Vt(t.name),this.qt()}),e.appendChild(r),this.Rt.set(t.name,r);const n=document.createElement("div");return n.className="cc-prechat-error",n.id=s,e.appendChild(n),this.Pt.set(t.name,n),e}qt(){const t=this.options.fields.every(t=>{if(!t.required)return!0;const e=this.Rt.get(t.name);return!!e&&e.value.trim().length>0});this.Ut.disabled=!t}Ht(){const t={};let e=!0;for(const i of this.options.fields){const s=this.Rt.get(i.name);if(!s)continue;const c=s.value.trim();t[i.name]=c,!i.required||c?"email"===i.type&&c&&!this.Yt(c)&&(this.Jt(i.name,this.options.locale.preChatInvalidEmail),e=!1):(this.Jt(i.name,this.options.locale.preChatRequired),e=!1)}e&&this.options.onSubmit(t)}Jt(t,e){const i=this.Pt.get(t);i&&(i.textContent=e);const s=this.Rt.get(t);s&&i&&(s.setAttribute("aria-invalid","true"),s.setAttribute("aria-describedby",i.id))}Vt(t){const e=this.Pt.get(t);e&&(e.textContent="");const i=this.Rt.get(t);i&&e&&(i.getAttribute("aria-describedby")===e.id&&i.removeAttribute("aria-describedby"),"true"===i.getAttribute("aria-invalid")&&i.removeAttribute("aria-invalid"))}Yt(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}destroy(){this.container.remove(),this.Rt.clear(),this.Pt.clear()}}},Symbol.toStringTag,{value:"Module"}));return t.Widget=J,t.default=X,t.parseAutoOpen=G,Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),t}({});"undefined"!=typeof window&&window.ChatCops&&window.ChatCops.default&&Object.assign(window.ChatCops,window.ChatCops.default);
@@ -1 +1 @@
1
- var ChatCops=function(e){"use strict";const t="chatcops-root";function s(e){const s=document.createElement("div");s.id=function(){if(!document.getElementById(t))return t;let e=2;for(;document.getElementById(`${t}-${e}`);)e+=1;return`${t}-${e}`}(),s.className=t,e?e.appendChild(s):document.body.appendChild(s);const a=s.attachShadow({mode:"open"}),i=document.createElement("style");return i.textContent=":host{--cc-accent: #6366f1;--cc-accent-hover: #4f46e5;--cc-on-accent: #ffffff;--cc-accent-contrast: #6164ec;--cc-text: #ffffff;--cc-bg: #0a0a0a;--cc-bg-surface: #1a1a1a;--cc-bg-input: #2a2a2a;--cc-border: #333333;--cc-text-secondary: #a0a0a0;--cc-font: system-ui, -apple-system, sans-serif;--cc-radius: 12px;--cc-shadow: 0 8px 32px rgba(0,0,0,.4);--cc-fab-size: 56px;--cc-panel-width: 400px;--cc-panel-height: 560px;all:initial;font-family:var(--cc-font);font-size:14px;line-height:1.5;color:var(--cc-text);-webkit-font-smoothing:antialiased}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}.cc-fab{position:fixed;bottom:20px;right:20px;width:var(--cc-fab-size);height:var(--cc-fab-size);border-radius:50%;background:var(--cc-accent);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 16px #0000004d;transition:transform .2s,box-shadow .2s;z-index:10000;outline:none}.cc-fab:hover{transform:scale(1.05);box-shadow:0 6px 24px #0006}.cc-fab:active{transform:scale(.95)}.cc-fab.cc-left{right:auto;left:20px}.cc-fab svg{width:24px;height:24px;fill:var(--cc-on-accent);transition:transform .3s}.cc-fab.cc-open svg{transform:rotate(90deg)}.cc-fab-badge{position:absolute;top:-2px;right:-2px;width:12px;height:12px;border-radius:50%;background:#ef4444;border:2px solid var(--cc-bg);display:none}.cc-fab-badge.cc-visible{display:block}@keyframes cc-pulse{0%,to{box-shadow:0 4px 16px #0000004d}50%{box-shadow:0 4px 16px #6366f180}}.cc-fab.cc-pulse{animation:cc-pulse 2s ease-in-out 3}.cc-panel{position:fixed;bottom:88px;right:20px;width:var(--cc-panel-width);height:var(--cc-panel-height);max-height:calc(100vh - 100px);background:var(--cc-bg);border-radius:var(--cc-radius);box-shadow:var(--cc-shadow);border:1px solid var(--cc-border);display:flex;flex-direction:column;overflow:hidden;z-index:9999;opacity:0;transform:translateY(16px) scale(.95);pointer-events:none;transition:opacity .2s,transform .2s}.cc-panel.cc-visible{opacity:1;transform:translateY(0) scale(1);pointer-events:auto}.cc-panel.cc-left{right:auto;left:20px}.cc-panel.cc-inline{position:relative;bottom:auto;right:auto;left:auto;width:100%;height:100%;max-height:100%;z-index:auto;transform:none;transition:none}.cc-panel.cc-inline:not(.cc-visible){visibility:hidden}.cc-panel.cc-inline.cc-visible{transform:none}.cc-header{display:flex;align-items:center;padding:16px;background:var(--cc-bg-surface);border-bottom:1px solid var(--cc-border);flex-shrink:0}.cc-header-avatar{width:36px;height:36px;border-radius:50%;margin-right:12px;object-fit:cover}.cc-header-avatar-placeholder{width:36px;height:36px;border-radius:50%;margin-right:12px;background:var(--cc-accent);display:flex;align-items:center;justify-content:center}.cc-header-avatar-placeholder svg{width:20px;height:20px;fill:var(--cc-on-accent)}.cc-header-info{flex:1}.cc-header-name{font-size:15px;font-weight:600;color:var(--cc-text)}.cc-header-subtitle{font-size:12px;color:var(--cc-text-secondary)}.cc-header-close{width:32px;height:32px;border-radius:8px;background:transparent;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s}.cc-header-close:hover{background:var(--cc-bg-input)}.cc-header-close svg{width:16px;height:16px;fill:var(--cc-text-secondary)}.cc-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}.cc-messages::-webkit-scrollbar{width:4px}.cc-messages::-webkit-scrollbar-track{background:transparent}.cc-messages::-webkit-scrollbar-thumb{background:var(--cc-border);border-radius:2px}.cc-message{max-width:85%;padding:10px 14px;border-radius:var(--cc-radius);word-wrap:break-word;overflow-wrap:break-word;font-size:14px;line-height:1.5;display:flex;flex-direction:column;gap:8px}.cc-message-user{align-self:flex-end;background:var(--cc-accent-contrast);color:var(--cc-on-accent);border-bottom-right-radius:4px}.cc-message-assistant{align-self:flex-start;background:var(--cc-bg-surface);color:var(--cc-text);border-bottom-left-radius:4px}.cc-message a{color:var(--cc-accent);text-decoration:underline}.cc-message-user a{color:var(--cc-on-accent)}.cc-message-error-note{margin-top:6px;font-size:12px;color:var(--cc-text-secondary)}.cc-message code{background:#0003;padding:1px 4px;border-radius:4px;font-family:SF Mono,Cascadia Code,Consolas,monospace;font-size:13px}.cc-message pre{background:#0000004d;padding:8px 12px;border-radius:8px;overflow-x:auto;margin:4px 0}.cc-message pre code{background:transparent;padding:0}.cc-message ul,.cc-message ol{padding-left:20px;margin:4px 0}.cc-message h1,.cc-message h2,.cc-message h3,.cc-message h4,.cc-message h5,.cc-message h6{font-size:15px;font-weight:600;line-height:1.4;margin:4px 0 0}.cc-message-actions{display:flex;align-items:center}.cc-message-retry,.cc-message-regenerate{display:inline-flex;align-items:center;gap:4px;padding:4px 10px;background:transparent;border:1px solid var(--cc-border);border-radius:6px;color:var(--cc-text-secondary);font-family:var(--cc-font);font-size:12px;cursor:pointer;transition:background .15s,color .15s,opacity .15s}.cc-message-retry:hover,.cc-message-regenerate:hover{background:var(--cc-bg-input);color:var(--cc-text)}.cc-message-retry svg,.cc-message-regenerate svg{fill:currentColor}.cc-message-regenerate{opacity:0}.cc-message:hover .cc-message-regenerate{opacity:1}.cc-message:focus-within .cc-message-regenerate,.cc-message-regenerate:focus-visible{opacity:1}@media(hover:none){.cc-message-regenerate{opacity:1}}.cc-message-retry{border-color:#ef4444;color:#ef4444}.cc-message-retry:hover{background:#ef44441a;color:#ef4444}.cc-typing{display:flex;align-items:center;gap:4px;padding:10px 14px;align-self:flex-start;background:var(--cc-bg-surface);border-radius:var(--cc-radius);border-bottom-left-radius:4px}.cc-typing-dot{width:6px;height:6px;border-radius:50%;background:var(--cc-text-secondary);animation:cc-bounce 1.2s infinite}.cc-typing-dot:nth-child(2){animation-delay:.2s}.cc-typing-dot:nth-child(3){animation-delay:.4s}@keyframes cc-bounce{0%,60%,to{transform:translateY(0)}30%{transform:translateY(-4px)}}.cc-input-area{display:flex;align-items:flex-end;padding:12px 16px;border-top:1px solid var(--cc-border);background:var(--cc-bg);gap:8px}.cc-input{flex:1;background:var(--cc-bg-input);border:1px solid var(--cc-border);border-radius:8px;padding:8px 12px;color:var(--cc-text);font-family:var(--cc-font);font-size:14px;line-height:1.5;resize:none;outline:none;max-height:96px;overflow-y:auto;transition:border-color .15s}.cc-input:focus{border-color:var(--cc-accent);outline:2px solid var(--cc-accent);outline-offset:1px}.cc-input::placeholder{color:var(--cc-text-secondary)}.cc-send-btn{width:36px;height:36px;border-radius:8px;background:var(--cc-accent);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .15s,opacity .15s}.cc-send-btn:hover{background:var(--cc-accent-hover)}.cc-send-btn:disabled{opacity:.4;cursor:not-allowed}.cc-send-btn svg{width:16px;height:16px;fill:var(--cc-on-accent)}.cc-footer{padding:6px 16px;text-align:center;font-size:11px;color:var(--cc-text-secondary);border-top:1px solid var(--cc-border)}.cc-footer a{color:var(--cc-text-secondary);text-decoration:none}.cc-footer a:hover{text-decoration:underline}.cc-bubble{position:fixed;bottom:84px;right:20px;background:var(--cc-bg-surface);color:var(--cc-text);padding:10px 16px;border-radius:var(--cc-radius);box-shadow:var(--cc-shadow);border:1px solid var(--cc-border);max-width:260px;font-size:13px;line-height:1.4;z-index:9998;opacity:0;transform:translateY(8px);pointer-events:none;transition:opacity .3s,transform .3s;cursor:pointer}.cc-bubble.cc-visible{opacity:1;transform:translateY(0);pointer-events:auto}.cc-bubble.cc-left{right:auto;left:20px}.cc-bubble-close{position:absolute;top:-8px;right:-8px;width:20px;height:20px;border-radius:50%;background:var(--cc-bg);border:1px solid var(--cc-border);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:10px;color:var(--cc-text-secondary)}.cc-hidden{display:none}.cc-sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap}.cc-messages-wrapper{flex:1;display:flex;flex-direction:column;min-height:0}.cc-prechat{flex:1;overflow-y:auto;padding:24px 16px;display:flex;flex-direction:column;gap:16px}.cc-prechat-title{font-size:18px;font-weight:600;color:var(--cc-text)}.cc-prechat-subtitle{font-size:13px;color:var(--cc-text-secondary);margin-top:-8px}.cc-prechat-fields{display:flex;flex-direction:column;gap:14px}.cc-prechat-field{display:flex;flex-direction:column;gap:4px}.cc-prechat-label{font-size:13px;font-weight:500;color:var(--cc-text)}.cc-prechat-label .cc-required{color:#ef4444;margin-left:2px}.cc-prechat-input,.cc-prechat-select,.cc-prechat-textarea{background:var(--cc-bg-input);border:1px solid var(--cc-border);border-radius:8px;padding:8px 12px;color:var(--cc-text);font-family:var(--cc-font);font-size:14px;outline:none;transition:border-color .15s}.cc-prechat-input:focus,.cc-prechat-select:focus,.cc-prechat-textarea:focus{border-color:var(--cc-accent)}.cc-prechat-select{-webkit-appearance:auto;-moz-appearance:auto;appearance:auto}.cc-prechat-textarea{resize:none;line-height:1.5}.cc-prechat-error{font-size:12px;color:#ef4444;min-height:0}.cc-prechat-error:empty{display:none}.cc-prechat-submit{background:var(--cc-accent-contrast);color:var(--cc-on-accent);border:none;border-radius:8px;padding:10px 16px;font-family:var(--cc-font);font-size:14px;font-weight:500;cursor:pointer;transition:background .15s;margin-top:8px}.cc-prechat-submit:hover{background:var(--cc-accent-hover)}.cc-prechat-submit:disabled{opacity:.5;cursor:not-allowed}@media(max-width:768px){.cc-fab.cc-open{display:none}.cc-panel:not(.cc-inline){width:100%;height:100%;max-height:100%;bottom:0;right:0;left:0;border-radius:0;border:none}.cc-panel.cc-left:not(.cc-inline){left:0}.cc-bubble{bottom:84px;right:16px;left:16px;max-width:none}}.cc-fab:focus-visible,.cc-header-close:focus-visible,.cc-send-btn:focus-visible,.cc-message-retry:focus-visible,.cc-message-regenerate:focus-visible,.cc-bubble-close:focus-visible,.cc-prechat-submit:focus-visible{outline:2px solid var(--cc-accent);outline-offset:3px}@media(prefers-reduced-motion:reduce){.cc-fab.cc-pulse,.cc-typing-dot{animation:none}.cc-panel,.cc-bubble{transition:none}}",a.appendChild(i),a}const a={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};const i=new Set(["http","https","mailto","tel"]);function n(e){let t=e.replace(/[&<>"']/g,e=>a[e]??e);const s=function(e){let t="\0";for(;e.includes(t);)t+="\0";return t}(t),n=[],r=e=>{const t=n.push(e)-1;return`${s}${t}${s}`};t=t.replace(/```(?:\w*)\n?([\s\S]*?)```/g,(e,t)=>r(`<pre><code>${t.trim()}</code></pre>`)),t=t.replace(/`([^`]+)`/g,(e,t)=>r(`<code>${t}</code>`)),t=t.replace(/^(#{1,6}) (.+)$/gm,(e,t,s)=>{const a=t.length;return`<h${a}>${s}</h${a}>`}),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(\S(?:.*?\S)??)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\(((?:[^()]*|\([^()]*\))*)\)/g,(e,t,s)=>function(e){const t=e.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""),s=/^([^:/?#]+):/.exec(t);return!s||i.has(s[1].toLowerCase())}(s)?`<a href="${s}" target="_blank" rel="noopener noreferrer">${t}</a>`:t),t=t.replace(/^[-*+] (.+)$/gm,'<li data-md="ul">$1</li>'),t=t.replace(/^\d+\. (.+)$/gm,'<li data-md="ol">$1</li>'),t=t.replace(/(?:<li data-md="ul">.*?<\/li>\n?)+|(?:<li data-md="ol">.*?<\/li>\n?)+/g,e=>{const t=e.includes('data-md="ol"')?"ol":"ul";return`<${t}>${e.replace(/ data-md="(?:ul|ol)"/g,"").replace(/\n/g,"")}</${t}>`}),t=t.replace(/(<\/h[1-6]>)\n+/g,"$1"),t=t.replace(/\n\n/g,"<br><br>"),t=t.replace(/\n/g,"<br>");for(let a=0;a<n.length;a++)t=t.replace(`${s}${a}${s}`,()=>n[a]);return t}class r{constructor(e,t){this.typingEl=null,this.actions=t,this.container=document.createElement("div"),this.container.className="cc-messages",this.container.setAttribute("role","log"),this.container.setAttribute("aria-live","polite"),e.appendChild(this.container)}addMessage(e){this.removeTyping();const t=this.createMessageElement(e);return this.container.appendChild(t),this.scrollToBottom(),t}updateMessage(e){const t=this.findMessage(e.id);t&&(this.renderMessageElement(t,e),this.scrollToBottom())}showTyping(){var e;this.typingEl||(this.typingEl=document.createElement("div"),this.typingEl.className="cc-typing",this.typingEl.innerHTML=`<span class="cc-sr-only">${this.escapeHtml((null==(e=this.actions)?void 0:e.typingLabel)??"Typing...")}</span><div class="cc-typing-dot" aria-hidden="true"></div><div class="cc-typing-dot" aria-hidden="true"></div><div class="cc-typing-dot" aria-hidden="true"></div>`,this.container.appendChild(this.typingEl),this.scrollToBottom())}removeTyping(){this.typingEl&&(this.typingEl.remove(),this.typingEl=null)}clear(){this.container.innerHTML="",this.typingEl=null}removeMessage(e){const t=this.findMessage(e);null==t||t.remove()}clearRegenerateButtons(){this.container.querySelectorAll(".cc-message-regenerate").forEach(e=>{e.remove()}),this.cleanupEmptyActionContainers()}showRegenerateButton(e){var t;if(this.clearRegenerateButtons(),!(null==(t=this.actions)?void 0:t.onRegenerate))return;const s=this.findMessage(e);if(!s||!s.classList.contains("cc-message-assistant"))return;this.ensureActionsContainer(s).appendChild(this.createActionButton({className:"cc-message-regenerate",label:this.actions.regenerateLabel??"Regenerate",icon:'<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0020 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74A7.93 7.93 0 004 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/></svg>',onClick:()=>{var t,s;return null==(s=null==(t=this.actions)?void 0:t.onRegenerate)?void 0:s.call(t,e)}}))}setVisible(e){this.container.classList.toggle("cc-hidden",!e)}findMessage(e){return Array.from(this.container.children).find(t=>t.dataset.id===e)??null}scrollToBottom(){this.container.scrollTop=this.container.scrollHeight}createMessageElement(e){const t=document.createElement("div");return this.renderMessageElement(t,e),t}renderMessageElement(e,t){e.className=`cc-message cc-message-${t.role}`,e.dataset.id=t.id,"assistant"===t.role&&"welcome"!==t.id&&(e.dataset.aiGenerated="true"),t.status?e.dataset.status=t.status:delete e.dataset.status,"streaming"===t.status?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy"),t.errorType?e.dataset.errorType=t.errorType:delete e.dataset.errorType,e.innerHTML="";const s=document.createElement("div");if(s.className="cc-message-content",s.innerHTML="assistant"===t.role?n(t.content):this.escapeHtml(t.content),e.appendChild(s),"error"===t.status&&t.errorText){const s=document.createElement("div");s.className="cc-message-error-note",s.textContent=t.errorText,e.appendChild(s)}const a=this.createActionsContainer(t);a&&e.appendChild(a)}createActionsContainer(e){var t;if("error"!==e.status||!(null==(t=this.actions)?void 0:t.onRetry))return null;const s=document.createElement("div");return s.className="cc-message-actions",s.appendChild(this.createActionButton({className:"cc-message-retry",label:this.actions.retryLabel??"Retry",icon:'<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M17.65 6.35A7.96 7.96 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>',onClick:()=>{var t,s;return null==(s=null==(t=this.actions)?void 0:t.onRetry)?void 0:s.call(t,e.id)}})),s}ensureActionsContainer(e){const t=e.querySelector(".cc-message-actions");if(t)return t;const s=document.createElement("div");return s.className="cc-message-actions",e.appendChild(s),s}cleanupEmptyActionContainers(){this.container.querySelectorAll(".cc-message-actions").forEach(e=>{e.hasChildNodes()||e.remove()})}createActionButton(e){const t=document.createElement("button");return t.type="button",t.className=e.className,t.innerHTML=`${e.icon}<span>${this.escapeHtml(e.label)}</span>`,t.addEventListener("click",e.onClick),t}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}class o{constructor(e,t){this.onSend=t.onSend,this.area=document.createElement("div"),this.area.className="cc-input-area",this.textarea=document.createElement("textarea"),this.textarea.className="cc-input",this.textarea.placeholder=t.placeholder,this.textarea.setAttribute("aria-label",t.placeholder),this.textarea.rows=1,this.textarea.maxLength=1e4,this.textarea.addEventListener("input",()=>this.autoResize()),this.textarea.addEventListener("keydown",e=>this.handleKeydown(e)),this.sendBtn=document.createElement("button"),this.sendBtn.className="cc-send-btn",this.sendBtn.disabled=!0,this.sendBtn.setAttribute("aria-label",t.sendLabel),this.sendBtn.innerHTML='<svg viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>',this.sendBtn.addEventListener("click",()=>this.send()),this.textarea.addEventListener("input",()=>{this.sendBtn.disabled=0===this.textarea.value.trim().length}),this.area.appendChild(this.textarea),this.area.appendChild(this.sendBtn),e.appendChild(this.area)}focus(){this.textarea.focus()}setDisabled(e){this.textarea.disabled=e,this.sendBtn.disabled=e||0===this.textarea.value.trim().length}clear(){this.textarea.value="",this.sendBtn.disabled=!0,this.autoResize()}setVisible(e){this.area.classList.toggle("cc-hidden",!e)}send(){const e=this.textarea.value.trim();e&&(this.onSend(e),this.clear())}handleKeydown(e){e.isComposing||229===e.keyCode||"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.send())}autoResize(){this.textarea.style.height="auto";this.textarea.style.height=Math.min(this.textarea.scrollHeight,96)+"px"}}const c="cc-panel";class l{constructor(e,t){this.inline=t.inline??!1,this.el=document.createElement("div"),this.el.className="cc-panel",t.inline&&this.el.classList.add("cc-inline"),"bottom-left"===t.position&&this.el.classList.add("cc-left"),t.inline||(this.el.id=c,this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label",t.branding.name),this.el.addEventListener("keydown",e=>{"Escape"===e.key&&t.onClose()}),this.setHidden(!0));const s=document.createElement("div");if(s.className="cc-header",t.branding.avatar){const e=document.createElement("img");e.className="cc-header-avatar",e.src=t.branding.avatar,e.alt=t.branding.name,s.appendChild(e)}else{const e=document.createElement("div");e.className="cc-header-avatar-placeholder",e.innerHTML='<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/></svg>',s.appendChild(e)}const a=document.createElement("div");if(a.className="cc-header-info",a.innerHTML=`<div class="cc-header-name">${this.escapeHtml(t.branding.name)}</div><div class="cc-header-subtitle">${this.escapeHtml(t.branding.subtitle)}</div>`,s.appendChild(a),!t.inline){const e=document.createElement("button");e.className="cc-header-close",e.setAttribute("aria-label",t.closeLabel),e.innerHTML='<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>',e.addEventListener("click",t.onClose),s.appendChild(e)}this.el.appendChild(s),t.preChatEnabled?(this.messagesContainer=document.createElement("div"),this.messagesContainer.className="cc-messages-wrapper",this.el.appendChild(this.messagesContainer)):this.messagesContainer=this.el,this.messages=new r(this.messagesContainer,t.messageActions),this.input=new o(this.el,{placeholder:t.placeholder,sendLabel:t.sendLabel,onSend:t.onSend});const i=document.createElement("div");i.className="cc-footer",i.innerHTML=t.footerText,this.el.appendChild(i),e.appendChild(this.el)}show(){this.el.classList.add("cc-visible"),this.inline||(this.setHidden(!1),this.input.focus())}hide(){this.el.classList.remove("cc-visible"),this.inline||this.setHidden(!0)}containsFocus(){return this.el.contains(this.el.getRootNode().activeElement)}get isVisible(){return this.el.classList.contains("cc-visible")}addMessage(e){return this.messages.addMessage(e)}hideMessages(){this.messages.setVisible(!1)}showMessages(){this.messages.setVisible(!0)}destroy(){this.el.remove()}setHidden(e){this.el.toggleAttribute("inert",e),e?this.el.setAttribute("aria-hidden","true"):this.el.removeAttribute("aria-hidden")}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const d='<svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z"/><path d="M7 9h10v2H7zm0-3h10v2H7z"/></svg>';class h{constructor(e,t){this.openLabel=t.openLabel,this.closeLabel=t.closeLabel,this.el=document.createElement("button"),this.el.className="cc-fab cc-pulse",this.el.setAttribute("aria-label",this.openLabel),this.el.setAttribute("aria-expanded","false"),this.el.setAttribute("aria-controls",c),"bottom-left"===t.position&&this.el.classList.add("cc-left"),this.el.innerHTML=d,this.badge=document.createElement("div"),this.badge.className="cc-fab-badge",this.el.appendChild(this.badge),this.el.addEventListener("click",()=>{this.el.classList.remove("cc-pulse"),t.onClick()}),e.appendChild(this.el)}setOpen(e){this.el.innerHTML=e?'<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>':d,e||this.el.appendChild(this.badge),this.el.classList.toggle("cc-open",e),this.el.setAttribute("aria-label",e?this.closeLabel:this.openLabel),this.el.setAttribute("aria-expanded",String(e))}focus(){this.el.focus()}showBadge(){this.badge.classList.add("cc-visible")}hideBadge(){this.badge.classList.remove("cc-visible")}destroy(){this.el.remove()}}const p="chatcops_bubble_shown";class u{constructor(e,t){this.timerId=null,this.el=document.createElement("div"),this.el.className="cc-bubble","bottom-left"===t.position&&this.el.classList.add("cc-left"),this.el.textContent=t.text,this.setHidden(!0);const s=document.createElement("button");if(s.type="button",s.className="cc-bubble-close",s.setAttribute("aria-label",t.dismissLabel),s.innerHTML="&times;",s.addEventListener("click",e=>{e.stopPropagation(),this.hide()}),this.el.appendChild(s),this.el.addEventListener("click",()=>{this.hide(),t.onClick()}),e.appendChild(this.el),t.showOnce)try{if(sessionStorage.getItem(p))return;sessionStorage.setItem(p,"1")}catch{}this.timerId=setTimeout(()=>{this.el.classList.add("cc-visible"),this.setHidden(!1)},t.delay??3e3)}hide(){this.el.classList.remove("cc-visible"),this.setHidden(!0),this.timerId&&(clearTimeout(this.timerId),this.timerId=null)}setHidden(e){this.el.toggleAttribute("inert",e),e?this.el.setAttribute("aria-hidden","true"):this.el.removeAttribute("aria-hidden")}destroy(){this.hide(),this.el.remove()}}let m;async function g(e){m??(m=new Promise((e,t)=>{const s=document.createElement("script");s.src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",s.onload=e,s.onerror=t,document.head.append(s)})),await m;const t=document.createElement("div");t.style.cssText="position:fixed;bottom:96px;right:24px;z-index:2147483647",document.body.append(t);try{return await new Promise((s,a)=>{window.turnstile.render(t,{sitekey:e,appearance:"interaction-only",callback:s,"error-callback":a})})}finally{t.remove()}}class b{constructor(e){this.saved={},this.apiUrl=e.apiUrl,this.turnstileSiteKey=e.turnstileSiteKey,this.timeout=e.timeout??3e4,this.sessionKey=`chatcops-session:${e.apiUrl}`;try{this.saved=JSON.parse(localStorage.getItem(this.sessionKey)||"{}")}catch{}}async*sendMessage(e,t={}){var s;const a=new AbortController,i=t.timeout??this.timeout;let n,r,o=!1;const c=t.signal,l=()=>{clearTimeout(n),a.abort()},d=()=>{clearTimeout(n),a.signal.aborted||(n=setTimeout(()=>{o=!0,a.abort()},i))},h=async()=>{if(clearTimeout(n),null==c||c.removeEventListener("abort",l),r){const e=r;r=void 0;try{await e.cancel()}catch{}finally{e.releaseLock()}}};c&&(c.aborted?a.abort():c.addEventListener("abort",l)),d();try{const t=(e,t,s)=>fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...s&&{Authorization:`Bearer ${s}`}},body:JSON.stringify(t),signal:a.signal}),i=this.saved,n=i.conversationId===e.conversationId;let o=await t(this.apiUrl,{protocol:1,...e},n?i.token:void 0);if(401===o.status){const s=await t(this.apiUrl.replace(/\/?(\?.*)?$/,"/session$1"),{conversationId:e.conversationId,previousToken:i.token,turnstileToken:this.turnstileSiteKey&&!n?await g(this.turnstileSiteKey):void 0});if(s.ok){const a=await s.json();this.saved=a;try{localStorage.setItem(this.sessionKey,JSON.stringify(a))}catch{}a.conversationId!==e.conversationId&&(e={...e,conversationId:a.conversationId},yield{conversationId:a.conversationId}),o=await t(this.apiUrl,{protocol:1,...e},a.token)}else this.saved={}}if(!o.ok){const{error:e}=await o.json().catch(()=>({}));return await h(),void(yield(null==e?void 0:e.code)?v(e.code,e.retryAfterMs):{error:429===o.status?"rate_limit":`HTTP ${o.status}`})}if(r=null==(s=o.body)?void 0:s.getReader(),!r)return await h(),void(yield{error:"No response body"});const c=new TextDecoder;let l="",p=!1,u=!1;for(;;){const{done:e,value:t}=await r.read();if(e)break;t.byteLength>0&&d(),l+=c.decode(t,{stream:!0});const s=l.split("\n");l=s.pop()??"";for(const a of s){const e=a.trim();if(!e||!e.startsWith("data: "))continue;const t=e.slice(6);if("[DONE]"===t)return await h(),void(yield p&&!u?{error:"cut_off"}:{done:!0});let s;try{s=JSON.parse(t)}catch{continue}if("type"in s){p=!0,"finish"===s.type&&(u=!0);const e=y(s);e&&(yield e)}else yield s}}await h(),yield"data: [DONE]"===l.trim()?{done:!0}:{error:p?"cut_off":"network"}}catch(p){await h(),p instanceof DOMException&&"AbortError"===p.name?yield o?{error:"timeout"}:{error:"aborted"}:yield{error:"network"}}finally{await h()}}}const f={rate_limited:"rate_limit",timeout:"timeout",budget_exceeded:"budget",budget_daily:"budget_daily",provider_unavailable:"unavailable"};function v(e,t){return{error:f[e]??"provider_error",retryAfterMs:t}}function y(e){switch(e.type){case"start":return{messageId:e.messageId};case"text-delta":return{content:e.delta};case"lead-captured":return{leadCaptured:!0,leadData:e.lead};case"error":return v("budget_exceeded"===e.code&&"conversation"!==e.scope?"budget_daily":e.code,e.retryAfterMs);case"finish":return"error"===e.reason||"aborted"===e.reason?null:{done:!0};default:return null}}const x="chatcops_conversation",w="chatcops_session_id";class C{constructor(e){this.key=e?`${x}_${e}`:x,this.sessionKey=e?`${w}_${e}`:w}load(){try{const e=localStorage.getItem(this.key);if(null===e)return null;let t;try{t=JSON.parse(e)}catch{return this.clear(),null}if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.id||!Array.isArray(t.messages))return this.clear(),null;const s=t,a=s.messages.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&("user"===e.role||"assistant"===e.role)&&"string"==typeof e.content);return{...s,id:s.id,messages:a}}catch{return null}}save(e){try{const t={...e,messages:e.messages.filter(e=>"error"!==e.status).map(({status:e,...t})=>t)};localStorage.setItem(this.key,JSON.stringify(t))}catch{}}clear(){try{localStorage.removeItem(this.key)}catch{}}getSessionId(){try{let e=sessionStorage.getItem(this.sessionKey);return e||(e=crypto.randomUUID(),sessionStorage.setItem(this.sessionKey,e)),e}catch{return crypto.randomUUID()}}isPreChatCompleted(e){try{return"true"===sessionStorage.getItem(`chatcops-prechat-${e}`)}catch{return!1}}setPreChatCompleted(e,t){try{sessionStorage.setItem(`chatcops-prechat-${e}`,"true")}catch{}t&&this.setPreChatData(e,t)}getPreChatData(e){try{const t=sessionStorage.getItem(`chatcops-prechat-data-${e}`);if(!t)return null;const s=JSON.parse(t);return"object"!=typeof s||null===s||Array.isArray(s)?null:s}catch{return null}}setPreChatData(e,t){try{sessionStorage.setItem(`chatcops-prechat-data-${e}`,JSON.stringify(t))}catch{}}}const E=Symbol.for("chatcops.storageClaims"),M=globalThis;M[E]??(M[E]=new Map);const S=M[E];function k(e){const t=S.get(e);if(!t)return!1;for(const s of t)s()||t.delete(s);return 0===t.size&&S.delete(e),t.size>0}function L(e,t){const s=e.host;if(t.accent){s.style.setProperty("--cc-accent",t.accent),s.style.setProperty("--cc-accent-hover",z(t.accent,10));const e=function(e){if(!function(e){return/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(e.trim())}(e))return null;const t=e.trim().startsWith("#")?e.trim():`#${e.trim()}`;if(N(I,t)>=A)return{onAccent:I,background:t};if(N(T,t)>=A)return{onAccent:T,background:t};for(let s=2;s<=60;s+=2){const e=z(t,s);if(N(I,e)>=A)return{onAccent:I,background:e}}return{onAccent:I,background:T}}(t.accent);e?(s.style.setProperty("--cc-on-accent",e.onAccent),s.style.setProperty("--cc-accent-contrast",e.background)):s.style.setProperty("--cc-accent-contrast",t.accent)}if(t.textColor&&s.style.setProperty("--cc-text",t.textColor),t.bgColor&&(s.style.setProperty("--cc-bg",t.bgColor),s.style.setProperty("--cc-bg-surface",R(t.bgColor,8)),s.style.setProperty("--cc-bg-input",R(t.bgColor,14))),t.fontFamily&&s.style.setProperty("--cc-font",t.fontFamily),void 0!==t.borderRadius){const e=function(e){if("number"==typeof e&&!Number.isFinite(e))return"";const t=String(e).trim();return/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(t)?`${t}px`:t}(t.borderRadius);e&&s.style.setProperty("--cc-radius",e)}}const I="#ffffff",T="#0a0a0a",A=4.5;function B(e){const t=$(e).map(e=>{const t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return.2126*t[0]+.7152*t[1]+.0722*t[2]}function N(e,t){const[s,a]=[B(e),B(t)].sort((e,t)=>t-e);return(s+.05)/(a+.05)}function $(e){if(!/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(e))return[0,0,0];const t=e.replace("#",""),s=parseInt(3===t.length?t.split("").map(e=>e+e).join(""):t,16);return[s>>16&255,s>>8&255,255&s]}function H(e,t,s){return"#"+[e,t,s].map(e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")).join("")}function z(e,t){const[s,a,i]=$(e),n=1-t/100;return H(Math.round(s*n),Math.round(a*n),Math.round(i*n))}function R(e,t){const[s,a,i]=$(e),n=t/100;return H(Math.round(s+(255-s)*n),Math.round(a+(255-a)*n),Math.round(i+(255-i)*n))}const P={welcomeMessage:"How can I help you today?",inputPlaceholder:"Type a message...",sendButton:"Send",closeButton:"Close",openChat:"Open chat",defaultName:"AI Assistant",defaultSubtitle:"Online",greetingWithName:"Hi {name}!",selectPlaceholder:"Select {label}...",dismissBubble:"Dismiss",errorGeneric:"Something went wrong. Please try again.",errorNetwork:"Connection error. Please check your network.",errorRateLimit:"Too many messages. Please wait a moment.",errorRateLimitWait:"Too many messages. Please try again in {seconds} seconds.",errorBudget:"This chat has reached its limit.",errorBudgetDaily:"The assistant has reached its limit for today. Please try again later.",errorUnavailable:"The assistant is unavailable right now. Please try again later.",errorCutOff:"The reply was cut off.",typingIndicator:"Typing...",poweredBy:"Powered by ChatCops",newConversation:"New conversation",welcomeBubbleDefault:"Need help? Chat with us!",preChatTitle:"Before we start...",preChatSubtitle:"Tell us a bit about yourself",preChatSubmit:"Start Chat",preChatRequired:"This field is required",preChatInvalidEmail:"Please enter a valid email",retryButton:"Retry",regenerateButton:"Regenerate"},D={en:P};class O{constructor(e,t){if(this.fieldElements=new Map,this.errorElements=new Map,this.options=t,this.container=document.createElement("div"),this.container.className="cc-prechat",t.title){const e=document.createElement("div");e.className="cc-prechat-title",e.textContent=t.title,this.container.appendChild(e)}if(t.subtitle){const e=document.createElement("div");e.className="cc-prechat-subtitle",e.textContent=t.subtitle,this.container.appendChild(e)}const s=document.createElement("form");s.className="cc-prechat-fields",s.noValidate=!0,s.addEventListener("submit",e=>{e.preventDefault(),this.handleSubmit()});for(const i of t.fields)s.appendChild(this.createField(i));this.submitBtn=document.createElement("button"),this.submitBtn.type="submit",this.submitBtn.className="cc-prechat-submit",this.submitBtn.textContent=t.submitLabel,s.appendChild(this.submitBtn),this.container.appendChild(s),e.appendChild(this.container),this.updateSubmitState();const a=this.fieldElements.values().next().value;a&&setTimeout(()=>a.focus(),100)}createField(e){const t=document.createElement("div");t.className="cc-prechat-field";const s=`cc-prechat-${e.name}`,a=`cc-prechat-${e.name}-error`,i=document.createElement("label");if(i.className="cc-prechat-label",i.htmlFor=s,i.textContent=e.label,e.required){const e=document.createElement("span");e.className="cc-required",e.textContent="*",i.appendChild(e)}let n;if(t.appendChild(i),"select"===e.type){const t=document.createElement("select");t.className="cc-prechat-select";const s=document.createElement("option");s.value="",s.textContent=e.placeholder??this.options.locale.selectPlaceholder.replace("{label}",e.label.toLowerCase()),s.disabled=!0,s.selected=!0,t.appendChild(s);for(const a of e.options??[]){const e=document.createElement("option");e.value=a,e.textContent=a,t.appendChild(e)}n=t}else if("textarea"===e.type){const t=document.createElement("textarea");t.className="cc-prechat-textarea",t.placeholder=e.placeholder??"",t.rows=3,t.maxLength=500,n=t}else{const t=document.createElement("input");t.type=e.type,t.className="cc-prechat-input",t.maxLength=500,t.placeholder=e.placeholder??"",n=t}n.name=e.name,n.id=s,e.required&&n.setAttribute("aria-required","true"),n.addEventListener("input",()=>{this.clearError(e.name),this.updateSubmitState()}),n instanceof HTMLSelectElement&&n.addEventListener("change",()=>{this.clearError(e.name),this.updateSubmitState()}),t.appendChild(n),this.fieldElements.set(e.name,n);const r=document.createElement("div");return r.className="cc-prechat-error",r.id=a,t.appendChild(r),this.errorElements.set(e.name,r),t}updateSubmitState(){const e=this.options.fields.every(e=>{if(!e.required)return!0;const t=this.fieldElements.get(e.name);return!!t&&t.value.trim().length>0});this.submitBtn.disabled=!e}handleSubmit(){const e={};let t=!0;for(const s of this.options.fields){const a=this.fieldElements.get(s.name);if(!a)continue;const i=a.value.trim();e[s.name]=i,!s.required||i?"email"===s.type&&i&&!this.isValidEmail(i)&&(this.showError(s.name,this.options.locale.preChatInvalidEmail),t=!1):(this.showError(s.name,this.options.locale.preChatRequired),t=!1)}t&&this.options.onSubmit(e)}showError(e,t){const s=this.errorElements.get(e);s&&(s.textContent=t);const a=this.fieldElements.get(e);a&&s&&(a.setAttribute("aria-invalid","true"),a.setAttribute("aria-describedby",s.id))}clearError(e){const t=this.errorElements.get(e);t&&(t.textContent="");const s=this.fieldElements.get(e);s&&t&&(s.getAttribute("aria-describedby")===t.id&&s.removeAttribute("aria-describedby"),"true"===s.getAttribute("aria-invalid")&&s.removeAttribute("aria-invalid"))}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}destroy(){this.container.remove(),this.fieldElements.clear(),this.errorElements.clear()}}const F={network:"errorNetwork",timeout:"errorNetwork",provider_error:"errorGeneric",budget:"errorBudget",budget_daily:"errorBudgetDaily",unavailable:"errorUnavailable",cut_off:"errorCutOff"};class _{constructor(e){this.mounted=!1,this.messages=[],this.isStreaming=!1,this.v1=!1,this.destroyed=!1,this.retryRequests=new Map,this.eventHandlers=new Map,this.config=e,this.client=new b({apiUrl:e.apiUrl,timeout:e.timeout,turnstileSiteKey:e.turnstileSiteKey}),this.namespace=function(e,t,s){let a=e??"";if(void 0===e&&k("")){a=t;for(let e=2;k(a);e+=1)a=`${t}-${e}`;console.warn(`[chatcops] Another widget on this page already uses the default storage, so this one keeps its conversation under "${a}". Set a \`siteId\` on each widget to name them yourself.`)}else void 0!==e&&k(e)&&console.warn(`[chatcops] Two widgets on this page use the siteId "${e}", so they share one conversation.`);return S.has(a)||S.set(a,new Set),S.get(a).add(s),{siteId:""===a?void 0:a,release(){var e,t;null==(e=S.get(a))||e.delete(s),0===(null==(t=S.get(a))?void 0:t.size)&&S.delete(a)}}}(e.siteId,e.mode??"popup",()=>!this.destroyed&&(!this.mounted||this.shadow.host.isConnected)),this.storage=new C(this.namespace.siteId),this.locale=function(e,t){const s=D[e]??P;return t?{...s,...t}:s}(e.locale??"en",e.strings),this.conversationId=this.storage.getSessionId()}get isInline(){return"inline"===this.config.mode}resolveContainer(){if(!this.config.container)throw new Error('ChatCops: "container" is required when mode is "inline"');if("string"==typeof this.config.container){const e=document.querySelector(this.config.container);if(!e)throw new Error(`ChatCops: container element not found: ${this.config.container}`);return e}return this.config.container}init(){var e,t,a,i,n,r,o;this.isInline?(this.containerEl=this.resolveContainer(),this.shadow=s(this.containerEl)):this.shadow=s(),this.mounted=!0,this.config.theme&&L(this.shadow,this.config.theme);const c=(null==(e=this.config.theme)?void 0:e.position)??"bottom-right";if(this.isInline||(this.fab=new h(this.shadow,{position:c,openLabel:this.locale.openChat,closeLabel:this.locale.closeButton,onClick:()=>this.toggle()})),this.panel=new l(this.shadow,{position:c,inline:this.isInline,preChatEnabled:(null==(t=this.config.preChatForm)?void 0:t.enabled)??!1,branding:{name:(null==(a=this.config.branding)?void 0:a.name)??this.locale.defaultName,avatar:null==(i=this.config.branding)?void 0:i.avatar,subtitle:(null==(n=this.config.branding)?void 0:n.subtitle)??this.locale.defaultSubtitle},placeholder:this.config.placeholder??this.locale.inputPlaceholder,footerText:this.locale.poweredBy,closeLabel:this.locale.closeButton,sendLabel:this.locale.sendButton,messageActions:{onRetry:e=>{this.handleRetry(e)},onRegenerate:e=>{this.handleRegenerate(e)},retryLabel:this.locale.retryButton,regenerateLabel:this.locale.regenerateButton,typingLabel:this.locale.typingIndicator},onSend:e=>this.handleSend(e),onClose:()=>this.close()}),!1!==this.config.persistHistory){const e=this.storage.load();if(e){this.conversationId=e.id;for(const t of e.messages)this.messages.push(t),this.panel.addMessage(t)}}if(null==(r=this.config.preChatForm)?void 0:r.enabled){const e=this.storage.getPreChatData(this.conversationId);e&&(this.userData=e)}if((null==(o=this.config.preChatForm)?void 0:o.enabled)&&!this.isPreChatCompleted()&&0===this.messages.length?this.showPreChatForm():this.showChatView(),this.showLatestRegenerateButton(),!this.isInline&&this.config.welcomeBubble&&(this.bubble=new u(this.shadow,{text:this.config.welcomeBubble.text,delay:this.config.welcomeBubble.delay,showOnce:this.config.welcomeBubble.showOnce??!0,position:c,dismissLabel:this.locale.dismissBubble,onClick:()=>this.open()})),this.isInline&&this.panel.show(),!this.isInline&&void 0!==this.config.autoOpen&&!1!==this.config.autoOpen){const e="number"==typeof this.config.autoOpen?this.config.autoOpen:0;this.autoOpenTimer=setTimeout(()=>this.open(),e)}}open(){var e,t,s,a,i;this.panel.show(),this.isInline||(null==(e=this.fab)||e.setOpen(!0),null==(t=this.fab)||t.hideBadge(),null==(s=this.bubble)||s.hide()),null==(i=(a=this.config).onOpen)||i.call(a),this.emit("open")}close(){var e,t,s,a;const i=this.panel.containsFocus();this.panel.hide(),this.isInline||(null==(e=this.fab)||e.setOpen(!1),i&&(null==(t=this.fab)||t.focus())),null==(a=(s=this.config).onClose)||a.call(s),this.emit("close")}toggle(){this.panel.isVisible?this.close():this.open()}destroy(){var e,t,s,a,i;this.destroyed=!0,void 0!==this.autoOpenTimer&&clearTimeout(this.autoOpenTimer),null==(e=this.abortController)||e.abort(),this.abortController=void 0,null==(t=this.preChatFormEl)||t.destroy(),null==(s=this.bubble)||s.destroy(),this.panel.destroy(),null==(a=this.fab)||a.destroy(),null==(i=this.shadow)||i.host.remove(),this.namespace.release(),this.eventHandlers.clear(),this.messages=[],this.userData=void 0}on(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t),()=>this.off(e,t)}off(e,t){var s;null==(s=this.eventHandlers.get(e))||s.delete(t)}emit(e,...t){var s;this.destroyed||null==(s=this.eventHandlers.get(e))||s.forEach(e=>{e(...t)})}isPreChatCompleted(){return this.storage.isPreChatCompleted(this.conversationId)}setPreChatCompleted(e){this.storage.setPreChatCompleted(this.conversationId,e)}showPreChatForm(){const e=this.config.preChatForm;this.panel.hideMessages(),this.panel.input.setVisible(!1),this.preChatFormEl=new O(this.panel.messagesContainer,{title:e.title??this.locale.preChatTitle,subtitle:e.subtitle??this.locale.preChatSubtitle,fields:e.fields,submitLabel:e.submitLabel??this.locale.preChatSubmit,locale:this.locale,onSubmit:e=>this.handlePreChatSubmit(e)})}handlePreChatSubmit(e){var t,s,a,i;(null==(t=this.config.preChatForm)?void 0:t.enabled)&&(this.userData=e,this.setPreChatCompleted(e),null==(s=this.preChatFormEl)||s.destroy(),this.preChatFormEl=void 0,this.panel.showMessages(),this.panel.input.setVisible(!0),this.showChatView(),null==(i=(a=this.config).onPreChatSubmit)||i.call(a,e),this.emit("preChatSubmit",e),e.message&&this.handleSend(e.message))}showChatView(){var e;if(0===this.messages.length){const t=null==(e=this.userData)?void 0:e.name,s=this.locale.greetingWithName.replace("{name}",()=>t),a={id:"welcome",role:"assistant",content:t?`${s} ${this.config.welcomeMessage??this.locale.welcomeMessage}`:this.config.welcomeMessage??this.locale.welcomeMessage};this.messages.push(a),this.panel.addMessage(a)}}async handleSend(e){var t,s;if(this.isStreaming)return;const a={id:crypto.randomUUID(),role:"user",content:e};this.messages.push(a),this.panel.addMessage(a),null==(s=(t=this.config).onMessage)||s.call(t,a),this.emit("message",a),await this.sendToServer(e,{userMessageId:a.id})}async handleRetry(e){if(this.isStreaming)return;const t=this.messages.findIndex(t=>t.id===e);if(-1===t)return;const s=this.retryRequests.get(e);let a=(null==s?void 0:s.userMessageId)?this.messages.find(e=>e.id===s.userMessageId):void 0;if(!a)for(let i=t-1;i>=0;i--)if("user"===this.messages[i].role){a=this.messages[i];break}a&&(this.panel.messages.removeMessage(e),this.retryRequests.delete(e),this.messages=this.messages.filter(t=>t.id!==e),await this.sendToServer(a.content,{regenerate:null==s?void 0:s.regenerate,userMessageId:(null==s?void 0:s.userMessageId)??a.id}))}async handleRegenerate(e){if(this.isStreaming)return;const t=this.messages.findIndex(t=>t.id===e);if(-1===t)return;if("assistant"!==this.messages[t].role)return;const s=this.findUserMessageForAssistant(t);s&&(this.panel.messages.clearRegenerateButtons(),this.panel.messages.removeMessage(e),this.retryRequests.delete(e),this.messages=this.messages.filter(t=>t.id!==e),await this.sendToServer(s.content,{regenerate:!this.v1||{assistantMessageId:e},userMessageId:s.id}))}async sendToServer(e,t={}){var s,a,i,n,r,o,c,l,d;if(this.isStreaming)return;this.isStreaming=!0,this.panel.input.setDisabled(!0),this.panel.messages.clearRegenerateButtons(),this.panel.messages.showTyping();const h={id:crypto.randomUUID(),role:"assistant",content:"",status:"streaming"};let p=!0,u=!1,m=!1;const g=new AbortController;this.abortController=g;try{for await(const r of this.client.sendMessage(this.createRequest(e,t),{signal:g.signal})){if(this.destroyed)break;if(r.error){const e=this.resolveErrorType(r.error);this.markFailed(h,this.getErrorMessage(e,r.retryAfterMs)),h.errorType=e,m=!0,this.retryRequests.set(h.id,{regenerate:t.regenerate,userMessageId:t.userMessageId}),this.panel.messages.removeTyping(),p?this.panel.addMessage(h):this.panel.messages.updateMessage(h),this.messages.push(h);const i=new Error(r.error);null==(a=(s=this.config).onError)||a.call(s,i),this.emit("error",i);break}if(r.done){u=!0;break}r.conversationId&&(this.conversationId=r.conversationId),r.messageId&&(h.id=r.messageId,this.v1=!0),r.leadCaptured&&(null==(n=(i=this.config).onLeadCaptured)||n.call(i,r.leadData),this.emit("leadCaptured",r.leadData)),r.content&&(p&&(this.panel.messages.removeTyping(),this.panel.addMessage(h),p=!1),h.content+=r.content,this.panel.messages.updateMessage(h))}if(this.destroyed)return;m||u||(u=!0),!m&&p&&this.panel.messages.removeTyping(),!m&&h.content&&(h.status="complete",this.panel.messages.updateMessage(h),this.messages.push(h),null==(o=(r=this.config).onMessage)||o.call(r,h),this.emit("message",h),this.showLatestRegenerateButton(),this.isInline||this.panel.isVisible||null==(c=this.fab)||c.showBadge())}catch(b){if(this.destroyed)return;this.markFailed(h,this.locale.errorGeneric),h.errorType="network",this.retryRequests.set(h.id,{regenerate:t.regenerate,userMessageId:t.userMessageId}),this.panel.messages.removeTyping(),p?this.panel.addMessage(h):this.panel.messages.updateMessage(h),this.messages.push(h);const e=b instanceof Error?b:new Error(String(b));null==(d=(l=this.config).onError)||d.call(l,e),this.emit("error",e)}finally{this.abortController===g&&(this.abortController=void 0),this.destroyed||(this.isStreaming=!1,this.panel.input.setDisabled(!1),this.panel.input.focus(),this.saveHistory())}}createRequest(e,t){var s;const a=!1!==this.config.pageContext?{url:window.location.href,title:document.title}:void 0,i=Boolean((null==(s=this.config.preChatForm)?void 0:s.enabled)&&this.userData&&!this.v1);return{conversationId:this.conversationId,message:e,messageId:t.userMessageId,regenerate:t.regenerate,pageContext:a,locale:this.config.locale,...i?{userData:this.userData}:{}}}findUserMessageForAssistant(e){for(let t=e-1;t>=0;t--)if("user"===this.messages[t].role)return this.messages[t]}findLatestRegeneratableAssistant(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if("welcome"!==t.id){if("assistant"!==t.role||"error"===t.status)return;return t}}}showLatestRegenerateButton(){const e=this.findLatestRegeneratableAssistant();e?this.panel.messages.showRegenerateButton(e.id):this.panel.messages.clearRegenerateButtons()}resolveErrorType(e){return e in F||"rate_limit"===e?e:"provider_error"}markFailed(e,t){e.status="error",e.content.trim()?e.errorText=t:e.content=t}getErrorMessage(e,t){return"rate_limit"===e?t?this.locale.errorRateLimitWait.replace("{seconds}",String(Math.ceil(t/1e3))):this.locale.errorRateLimit:this.locale[F[e]??"errorGeneric"]}saveHistory(){if(!1===this.config.persistHistory)return;const e=this.config.maxMessages??50,t=this.messages.filter(e=>"welcome"!==e.id).slice(-e);this.storage.save({id:this.conversationId,messages:t.map(e=>({id:e.id,role:e.role,content:e.content,status:e.status,errorType:e.errorType,timestamp:Date.now()})),updatedAt:Date.now()})}}let q=null;const U=new Map;function V(e){if(void 0!==e)return""===e||"true"===e||"false"!==e&&(/^\d+$/.test(e)?Number(e):void 0)}const j={init(e){q&&q.destroy(),q=new _(e);for(const[t,s]of U)for(const e of s)q.on(t,e);return q.init(),q},open(){null==q||q.open()},close(){null==q||q.close()},destroy(){null==q||q.destroy(),q=null},on(e,t){let s=U.get(e);return s||(s=new Set,U.set(e,s)),s.add(t),null==q||q.on(e,t),()=>{j.off(e,t)}},off(e,t){var s;null==(s=U.get(e))||s.delete(t),null==q||q.off(e,t)}};function K(e){if(!e)return;const t=e.dataset.apiUrl;if(!t)return;const s=e.dataset.mode,a=e.dataset.container;j.init({apiUrl:t,turnstileSiteKey:e.dataset.turnstileSiteKey,mode:s||void 0,container:a||void 0,theme:{accent:e.dataset.accent,textColor:e.dataset.textColor,bgColor:e.dataset.bgColor,fontFamily:e.dataset.fontFamily,borderRadius:e.dataset.borderRadius,position:e.dataset.position||void 0},branding:{name:e.dataset.brandName,avatar:e.dataset.brandAvatar,subtitle:e.dataset.brandSubtitle},welcomeMessage:e.dataset.welcomeMessage,welcomeBubble:e.dataset.welcomeBubble?{text:e.dataset.welcomeBubble,delay:e.dataset.welcomeBubbleDelay?parseInt(e.dataset.welcomeBubbleDelay,10):void 0}:void 0,autoOpen:V(e.dataset.autoOpen),placeholder:e.dataset.placeholder,locale:e.dataset.locale})}const J="undefined"!=typeof document?document.currentScript:null;return J&&J.dataset.apiUrl&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>K(J),{once:!0}):K(J)),"undefined"!=typeof window&&(window.ChatCops=j),e.Widget=_,e.default=j,e.parseAutoOpen=V,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});"undefined"!=typeof window&&window.ChatCops&&window.ChatCops.default&&Object.assign(window.ChatCops,window.ChatCops.default);
1
+ !function(){"use strict";function e(e){if(void 0!==e)return""===e||"true"===e||"false"!==e&&(/^\d+$/.test(e)?Number(e):void 0)}const t="chatcops-root",c=new Set(["ar","he","fa","ur"]);const o=["light","dark","auto"];function n(e,t){const c=e.host,n=function(e){return e.mode&&o.includes(e.mode)?e.mode:e.bgColor?d(e.bgColor)&&l(e.bgColor)>.4?"light":"dark":e.textColor?d(e.textColor)&&l(e.textColor)<.4?"light":"dark":void 0}(t);if(n?c.dataset.ccMode=n:delete c.dataset.ccMode,t.accent&&a(c,"",t.accent),t.accentDark&&a(c,"-dark",t.accentDark),t.textColor&&c.style.setProperty("--cc-text",t.textColor),t.bgColor&&(c.style.setProperty("--cc-bg",t.bgColor),c.style.setProperty("--cc-bg-surface",m(t.bgColor,8)),c.style.setProperty("--cc-bg-input",m(t.bgColor,14))),t.fontFamily&&c.style.setProperty("--cc-font",t.fontFamily),void 0!==t.borderRadius){const e=function(e){if("number"==typeof e&&!Number.isFinite(e))return"";const t=String(e).trim();return/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(t)?`${t}px`:t}(t.borderRadius);e&&c.style.setProperty("--cc-radius",e)}}function a(e,t,c){e.style.setProperty(`--cc-theme-accent${t}`,c),e.style.setProperty(`--cc-theme-accent${t}-hover`,h(c,10));const o=function(e){if(!d(e))return null;const t=e.trim().startsWith("#")?e.trim():`#${e.trim()}`;if(u(r,t)>=i)return{onAccent:r,background:t};if(u(s,t)>=i)return{onAccent:s,background:t};for(let c=2;c<=60;c+=2){const e=h(t,c);if(u(r,e)>=i)return{onAccent:r,background:e}}return{onAccent:r,background:s}}(c);o?(e.style.setProperty(`--cc-theme-on-accent${t}`,o.onAccent),e.style.setProperty(`--cc-theme-accent${t}-contrast`,o.background)):e.style.setProperty(`--cc-theme-accent${t}-contrast`,c)}const r="#ffffff",s="#0a0a0a",i=4.5;function d(e){return/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(e.trim())}function l(e){const t=f(e).map(e=>{const t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return.2126*t[0]+.7152*t[1]+.0722*t[2]}function u(e,t){const[c,o]=[l(e),l(t)].sort((e,t)=>t-e);return(c+.05)/(o+.05)}function f(e){if(!/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(e))return[0,0,0];const t=e.replace("#",""),c=parseInt(3===t.length?t.split("").map(e=>e+e).join(""):t,16);return[c>>16&255,c>>8&255,255&c]}function p(e,t,c){return"#"+[e,t,c].map(e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")).join("")}function h(e,t){const[c,o,n]=f(e),a=1-t/100;return p(Math.round(c*a),Math.round(o*a),Math.round(n*a))}function m(e,t){const[c,o,n]=f(e),a=t/100;return p(Math.round(c+(255-c)*a),Math.round(o+(255-o)*a),Math.round(n+(255-n)*a))}const b="1.0.0-rc.0";const v=document.currentScript,g=function(e,t){const c=new URL(e),o=/\.m?js$/.test(c.pathname)?c.href:`${c.origin}${c.pathname.replace(/\/$/,"")}/dist/`,n=new URL("chatcops.panel.js",o);return n.searchParams.set("v",t),n.href}((null==v?void 0:v.src)||location.href,b),x=function(e,o=()=>{}){let a,r,s,i,d;const l=[],u=new Map,f=new Map,p=new Map;let h,m,v=[];const g=e=>{var t;return e.dir??(e.locale?null==(t=p.get(e.locale))?void 0:t.dir:void 0)};function x(e){const t=e.locale;if(!t)return Promise.resolve(void 0);const c=p.get(t);if(c)return Promise.resolve(c.strings);let n=f.get(t);return n||(n=Promise.resolve(o(t)).then(e=>e&&"object"==typeof e.default?e.default:void 0,e=>{f.delete(t),console.warn(`[chatcops] The "${t}" strings could not load, so the chat is in English:`,e instanceof Error?e.message:e)}),f.set(t,n)),n}function y(t={welcomeBubble:void 0}){const c=a;return c?(s??(s=Promise.all([e(),x(c)]).then(([e,o])=>{if(a!==c)return;const n=new e.Widget({...c,strings:o?{...o,...c.strings}:c.strings,...g(c)?{dir:g(c)}:{},autoOpen:void 0,...t});for(const[t,c]of u)for(const e of c)n.on(t,e);null==i||i.remove(),i=d=void 0,n.init(),void 0!==h&&n.setUser(h),void 0!==m&&n.setContext(m);for(const t of v)n.update(t);return v=[],r=n,n},e=>{var t;if(s=void 0,console.error("[chatcops] The chat could not load:",e instanceof Error?e.message:e),d&&a){const e=(null==(t=a.strings)?void 0:t.errorNetwork)??"Connection error. Please check your network.";d.setAttribute("aria-label",e),d.title=e,d.dataset.state="error"}})),s):Promise.resolve(void 0)}function w(o){var a,r;i=document.createElement("div"),i.id=function(){if(!document.getElementById(t))return t;let e=2;for(;document.getElementById(`${t}-${e}`);)e+=1;return`${t}-${e}`}(),i.className=t,i.dir=function(e,t){if(e)return e;const o=null==t?void 0:t.toLowerCase().split(/[-_]/)[0];return o&&c.has(o)||"rtl"===(document.dir||document.documentElement.dir)?"rtl":"ltr"}(g(o),o.locale),document.body.appendChild(i);const s=i.attachShadow({mode:"open"}),l=document.createElement("style");l.textContent=':host{--cc-accent: var(--cc-theme-accent, #4f46e5);--cc-accent-hover: var(--cc-theme-accent-hover, #4338ca);--cc-on-accent: var(--cc-theme-on-accent, #ffffff);--cc-accent-contrast: var(--cc-theme-accent-contrast, #4f46e5);--cc-text: #1a1d23;--cc-bg: #ffffff;--cc-bg-surface: #f4f5f7;--cc-bg-input: #ffffff;--cc-border: #d9dce1;--cc-text-secondary: #5b616e;--cc-danger: #c62828;--cc-code-bg: rgb(0 0 0 / .07);--cc-pre-bg: rgb(0 0 0 / .05);--cc-shadow: 0 12px 40px rgb(16 24 40 / .18);--cc-font: system-ui, -apple-system, sans-serif;--cc-radius: 12px;--cc-fab-size: 56px;--cc-panel-width: 400px;--cc-panel-height: 560px;--cc-focus-ring: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-accent);all:initial;color-scheme:light;font-family:var(--cc-font);font-size:14px;line-height:1.5;color:var(--cc-text);-webkit-font-smoothing:antialiased}:host([data-cc-mode="dark"]){--cc-accent: var(--cc-theme-accent-dark, var(--cc-theme-accent, #6366f1));--cc-accent-hover: var(--cc-theme-accent-dark-hover, var(--cc-theme-accent-hover, #4f46e5));--cc-on-accent: var(--cc-theme-on-accent-dark, var(--cc-theme-on-accent, #ffffff));--cc-accent-contrast: var(--cc-theme-accent-dark-contrast, var(--cc-theme-accent-contrast, #6164ec));--cc-text: #ffffff;--cc-bg: #0a0a0a;--cc-bg-surface: #1a1a1a;--cc-bg-input: #2a2a2a;--cc-border: #333333;--cc-text-secondary: #a0a0a0;--cc-danger: #ef4444;--cc-code-bg: rgba(0, 0, 0, .2);--cc-pre-bg: rgba(0, 0, 0, .3);--cc-shadow: 0 8px 32px rgba(0,0,0,.4);color-scheme:dark}@media(prefers-color-scheme:dark){:host(:not([data-cc-mode])),:host([data-cc-mode="auto"]){--cc-accent: var(--cc-theme-accent-dark, var(--cc-theme-accent, #6366f1));--cc-accent-hover: var(--cc-theme-accent-dark-hover, var(--cc-theme-accent-hover, #4f46e5));--cc-on-accent: var(--cc-theme-on-accent-dark, var(--cc-theme-on-accent, #ffffff));--cc-accent-contrast: var(--cc-theme-accent-dark-contrast, var(--cc-theme-accent-contrast, #6164ec));--cc-text: #ffffff;--cc-bg: #0a0a0a;--cc-bg-surface: #1a1a1a;--cc-bg-input: #2a2a2a;--cc-border: #333333;--cc-text-secondary: #a0a0a0;--cc-danger: #ef4444;--cc-code-bg: rgba(0, 0, 0, .2);--cc-pre-bg: rgba(0, 0, 0, .3);--cc-shadow: 0 8px 32px rgba(0,0,0,.4);color-scheme:dark}}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}.cc-fab{position:fixed;bottom:20px;right:20px;width:var(--cc-fab-size);height:var(--cc-fab-size);border-radius:50%;background:var(--cc-accent);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 16px #0000004d;transition:transform .2s,box-shadow .2s;z-index:10000;outline:none}.cc-fab:hover{transform:scale(1.05);box-shadow:0 6px 24px #0006}.cc-fab:active{transform:scale(.95)}.cc-fab.cc-left{right:auto;left:20px}.cc-fab svg{width:24px;height:24px;fill:var(--cc-on-accent);transition:transform .3s}.cc-fab.cc-open svg{transform:rotate(90deg)}.cc-fab-badge{position:absolute;top:-2px;inset-inline-end:-2px;min-width:18px;height:18px;padding:0 4px;border-radius:9px;background:#ef4444;border:2px solid var(--cc-bg);color:#fff;font-size:11px;font-weight:700;line-height:1;display:none;align-items:center;justify-content:center;pointer-events:none}.cc-fab-badge.cc-visible{display:flex}@keyframes cc-pulse{0%,to{box-shadow:0 4px 16px #0000004d}50%{box-shadow:0 4px 16px color-mix(in srgb,var(--cc-accent) 50%,transparent)}}.cc-fab.cc-pulse{animation:cc-pulse 2s ease-in-out 3}.cc-fab:focus-visible{outline:2px solid transparent;box-shadow:var(--cc-focus-ring),0 4px 16px #0000004d;animation:none}@media(prefers-reduced-motion:reduce){.cc-fab.cc-pulse{animation:none}}',s.appendChild(l),o.theme&&n(s,o.theme),d=document.createElement("button"),d.className="cc-fab cc-pulse","bottom-left"===(null==(a=o.theme)?void 0:a.position)&&d.classList.add("cc-left"),d.setAttribute("aria-label",(null==(r=o.strings)?void 0:r.openChat)??"Open chat"),d.setAttribute("aria-expanded","false"),d.innerHTML='<svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z"/><path d="M7 9h10v2H7zm0-3h10v2H7z"/></svg>';const u=()=>{x(o),e().then(e=>{var t;return null==(t=e.prefetch)?void 0:t.call(e,o)},()=>{})};d.addEventListener("pointerenter",u,{once:!0}),d.addEventListener("focus",u,{once:!0}),d.addEventListener("click",()=>k.open()),s.appendChild(d)}const k={init(e){if(k.destroy(),a=e,"inline"!==e.mode){if(w(e),void 0!==e.autoOpen&&!1!==e.autoOpen&&l.push(setTimeout(()=>k.open(),!0===e.autoOpen?0:e.autoOpen)),e.welcomeBubble){const t=e.welcomeBubble;l.push(setTimeout(()=>{y({welcomeBubble:{...t,delay:0}})},t.delay??3e3))}}else y()},open(){y().then(e=>null==e?void 0:e.open())},close(){null==r||r.close()},toggle(){r?r.toggle():k.open()},sendMessage:(e,t)=>y().then(c=>null==c?void 0:c.sendMessage(e,t)),newConversation(){y().then(e=>null==e?void 0:e.newConversation())},clear(){y().then(e=>null==e?void 0:e.clear())},registerLocale(e,t,o){p.set(e,{strings:t,...(null==o?void 0:o.dir)?{dir:o.dir}:{}}),(null==o?void 0:o.dir)&&function(e,t){const o=e.toLowerCase().split(/[-_]/)[0];"rtl"===t?c.add(o):c.delete(o)}(e,o.dir)},setUser(e){h=e,null==r||r.setUser(e)},setContext(e){m=e,null==r||r.setContext(e)},update(e){var t;if(r)return void r.update(e);v.push(e);const c=null==i?void 0:i.shadowRoot;e.theme&&c&&n(c,Object.assign({},null==a?void 0:a.theme,...v.map(e=>e.theme))),(null==(t=e.strings)?void 0:t.openChat)&&(null==d||d.setAttribute("aria-label",e.strings.openChat))},version:b,destroy(){for(const e of l.splice(0))clearTimeout(e);null==i||i.remove(),i=d=void 0,null==r||r.destroy(),r=void 0,s=void 0,a=void 0,v=[]},on(e,t){let c=u.get(e);return c||(c=new Set,u.set(e,c)),c.add(t),null==r||r.on(e,t),()=>k.off(e,t)},off(e,t){var c;null==(c=u.get(e))||c.delete(t),null==r||r.off(e,t)}};return k}(()=>import(g),e=>{const t=function(e,t){const c=t.toLowerCase().split(/[-_]/)[0];if("en"===c||!/^[a-z]{2,3}$/.test(c))return;const o=new URL(e),n=new URL(`locales/${c}.js`,o);return n.search=o.search,n.href}(g,e);return t?import(t):void 0});window.ChatCops=x;const y=v&&function(t){const c=t.dataset.apiUrl;if(!c)return;const o=t.dataset.mode,n=t.dataset.container;return{apiUrl:c,turnstileSiteKey:t.dataset.turnstileSiteKey,userToken:t.dataset.userToken,mode:o||void 0,container:n||void 0,theme:{mode:t.dataset.themeMode||void 0,accent:t.dataset.accent,accentDark:t.dataset.accentDark,textColor:t.dataset.textColor,bgColor:t.dataset.bgColor,fontFamily:t.dataset.fontFamily,borderRadius:t.dataset.borderRadius,position:t.dataset.position||void 0},branding:{name:t.dataset.brandName,avatar:t.dataset.brandAvatar,subtitle:t.dataset.brandSubtitle},welcomeMessage:t.dataset.welcomeMessage,welcomeBubble:t.dataset.welcomeBubble?{text:t.dataset.welcomeBubble,delay:/^\d+$/.test(t.dataset.welcomeBubbleDelay??"")?Number(t.dataset.welcomeBubbleDelay):void 0}:void 0,autoOpen:e(t.dataset.autoOpen),placeholder:t.dataset.placeholder,disclosure:"false"!==t.dataset.disclosure&&{text:t.dataset.disclosureText,learnMoreUrl:t.dataset.disclosureUrl},locale:t.dataset.locale,dir:["ltr","rtl","auto"].find(e=>e===t.dataset.dir),persistence:["local","session","none"].find(e=>e===t.dataset.persistence),historyTtlDays:/^\d+$/.test(t.dataset.historyTtlDays??"")?Number(t.dataset.historyTtlDays):void 0}}(v);y&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>x.init(y),{once:!0}):x.init(y))}();
@@ -0,0 +1 @@
1
+ const t={},e=function(e,i,s){let r=Promise.resolve();if(i&&i.length>0){let e=function(t){return Promise.all(t.map(t=>Promise.resolve(t).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),c=(null==s?void 0:s.nonce)||(null==s?void 0:s.getAttribute("nonce"));r=e(i.map(e=>{if((e=function(t){return"/"+t}(e))in t)return;t[e]=!0;const i=e.endsWith(".css"),s=i?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${s}`))return;const r=document.createElement("link");return r.rel=i?"stylesheet":"modulepreload",i||(r.as="script"),r.crossOrigin="",r.href=e,c&&r.setAttribute("nonce",c),document.head.appendChild(r),i?new Promise((t,i)=>{r.addEventListener("load",t),r.addEventListener("error",()=>i(new Error(`Unable to preload CSS for ${e}`)))}):void 0}))}function c(t){const e=new Event("vite:preloadError",{cancelable:!0});if(e.payload=t,window.dispatchEvent(e),!e.defaultPrevented)throw t}return r.then(t=>{for(const e of t||[])"rejected"===e.status&&c(e.reason);return e().catch(c)})},i="chatcops-root",s=new Set(["ar","he","fa","ur"]);function r(t,e={}){const r=document.createElement("div");r.id=function(){if(!document.getElementById(i))return i;let t=2;for(;document.getElementById(`${i}-${t}`);)t+=1;return`${i}-${t}`}(),r.className=i,r.dir=function(t,e){if(t)return t;const i=null==e?void 0:e.toLowerCase().split(/[-_]/)[0];return i&&s.has(i)||"rtl"===(document.dir||document.documentElement.dir)?"rtl":"ltr"}(e.dir,e.locale),e.locale&&(r.lang=e.locale),t?t.appendChild(r):document.body.appendChild(r);const c=r.attachShadow({mode:"open"}),n=document.createElement("style");return n.textContent=':host{--cc-accent: var(--cc-theme-accent, #4f46e5);--cc-accent-hover: var(--cc-theme-accent-hover, #4338ca);--cc-on-accent: var(--cc-theme-on-accent, #ffffff);--cc-accent-contrast: var(--cc-theme-accent-contrast, #4f46e5);--cc-text: #1a1d23;--cc-bg: #ffffff;--cc-bg-surface: #f4f5f7;--cc-bg-input: #ffffff;--cc-border: #d9dce1;--cc-text-secondary: #5b616e;--cc-danger: #c62828;--cc-code-bg: rgb(0 0 0 / .07);--cc-pre-bg: rgb(0 0 0 / .05);--cc-shadow: 0 12px 40px rgb(16 24 40 / .18);--cc-font: system-ui, -apple-system, sans-serif;--cc-radius: 12px;--cc-fab-size: 56px;--cc-panel-width: 400px;--cc-panel-height: 560px;--cc-focus-ring: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-accent);all:initial;color-scheme:light;font-family:var(--cc-font);font-size:14px;line-height:1.5;color:var(--cc-text);-webkit-font-smoothing:antialiased}:host([data-cc-mode="dark"]){--cc-accent: var(--cc-theme-accent-dark, var(--cc-theme-accent, #6366f1));--cc-accent-hover: var(--cc-theme-accent-dark-hover, var(--cc-theme-accent-hover, #4f46e5));--cc-on-accent: var(--cc-theme-on-accent-dark, var(--cc-theme-on-accent, #ffffff));--cc-accent-contrast: var(--cc-theme-accent-dark-contrast, var(--cc-theme-accent-contrast, #6164ec));--cc-text: #ffffff;--cc-bg: #0a0a0a;--cc-bg-surface: #1a1a1a;--cc-bg-input: #2a2a2a;--cc-border: #333333;--cc-text-secondary: #a0a0a0;--cc-danger: #ef4444;--cc-code-bg: rgba(0, 0, 0, .2);--cc-pre-bg: rgba(0, 0, 0, .3);--cc-shadow: 0 8px 32px rgba(0,0,0,.4);color-scheme:dark}@media(prefers-color-scheme:dark){:host(:not([data-cc-mode])),:host([data-cc-mode="auto"]){--cc-accent: var(--cc-theme-accent-dark, var(--cc-theme-accent, #6366f1));--cc-accent-hover: var(--cc-theme-accent-dark-hover, var(--cc-theme-accent-hover, #4f46e5));--cc-on-accent: var(--cc-theme-on-accent-dark, var(--cc-theme-on-accent, #ffffff));--cc-accent-contrast: var(--cc-theme-accent-dark-contrast, var(--cc-theme-accent-contrast, #6164ec));--cc-text: #ffffff;--cc-bg: #0a0a0a;--cc-bg-surface: #1a1a1a;--cc-bg-input: #2a2a2a;--cc-border: #333333;--cc-text-secondary: #a0a0a0;--cc-danger: #ef4444;--cc-code-bg: rgba(0, 0, 0, .2);--cc-pre-bg: rgba(0, 0, 0, .3);--cc-shadow: 0 8px 32px rgba(0,0,0,.4);color-scheme:dark}}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}.cc-fab{position:fixed;bottom:20px;right:20px;width:var(--cc-fab-size);height:var(--cc-fab-size);border-radius:50%;background:var(--cc-accent);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 16px #0000004d;transition:transform .2s,box-shadow .2s;z-index:10000;outline:none}.cc-fab:hover{transform:scale(1.05);box-shadow:0 6px 24px #0006}.cc-fab:active{transform:scale(.95)}.cc-fab.cc-left{right:auto;left:20px}.cc-fab svg{width:24px;height:24px;fill:var(--cc-on-accent);transition:transform .3s}.cc-fab.cc-open svg{transform:rotate(90deg)}.cc-fab-badge{position:absolute;top:-2px;inset-inline-end:-2px;min-width:18px;height:18px;padding:0 4px;border-radius:9px;background:#ef4444;border:2px solid var(--cc-bg);color:#fff;font-size:11px;font-weight:700;line-height:1;display:none;align-items:center;justify-content:center;pointer-events:none}.cc-fab-badge.cc-visible{display:flex}@keyframes cc-pulse{0%,to{box-shadow:0 4px 16px #0000004d}50%{box-shadow:0 4px 16px color-mix(in srgb,var(--cc-accent) 50%,transparent)}}.cc-fab.cc-pulse{animation:cc-pulse 2s ease-in-out 3}.cc-fab:focus-visible{outline:2px solid transparent;box-shadow:var(--cc-focus-ring),0 4px 16px #0000004d;animation:none}@media(prefers-reduced-motion:reduce){.cc-fab.cc-pulse{animation:none}}.cc-panel{position:fixed;bottom:88px;right:20px;width:var(--cc-panel-width);height:var(--cc-panel-height);max-height:calc(100vh - 100px);background:var(--cc-bg);border-radius:var(--cc-radius);box-shadow:var(--cc-shadow);border:1px solid var(--cc-border);display:flex;flex-direction:column;overflow:hidden;z-index:9999;opacity:0;transform:translateY(16px) scale(.95);pointer-events:none;transition:opacity .2s,transform .2s}.cc-panel.cc-visible{opacity:1;transform:translateY(0) scale(1);pointer-events:auto}.cc-panel.cc-left{right:auto;left:20px}.cc-panel.cc-inline{position:relative;bottom:auto;inset-inline:auto;width:100%;height:100%;max-height:100%;z-index:auto;transform:none;transition:none}.cc-panel.cc-inline:not(.cc-visible){visibility:hidden}.cc-header{display:flex;align-items:center;padding:16px;background:var(--cc-bg-surface);border-bottom:1px solid var(--cc-border);flex-shrink:0}.cc-header-avatar,.cc-header-avatar-placeholder{width:36px;height:36px;border-radius:50%;margin-inline-end:12px}.cc-header-avatar{object-fit:cover}.cc-header-avatar-placeholder{background:var(--cc-accent);display:flex;align-items:center;justify-content:center}.cc-header-avatar-placeholder svg{width:20px;height:20px;fill:var(--cc-on-accent)}.cc-header-info{flex:1}.cc-header-name{font-size:15px;font-weight:600;color:var(--cc-text)}.cc-header-subtitle{font-size:12px;color:var(--cc-text-secondary)}.cc-header-close{width:32px;height:32px;border-radius:8px;background:transparent;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s}.cc-header-close:hover{background:var(--cc-bg-input)}.cc-header-close svg{width:16px;height:16px;fill:var(--cc-text-secondary)}.cc-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}.cc-messages::-webkit-scrollbar{width:4px}.cc-messages::-webkit-scrollbar-track{background:transparent}.cc-messages::-webkit-scrollbar-thumb{background:var(--cc-border);border-radius:2px}.cc-message{max-width:85%;padding:10px 14px;border-radius:var(--cc-radius);word-wrap:break-word;overflow-wrap:break-word;font-size:14px;line-height:1.5;display:flex;flex-direction:column;gap:8px}.cc-message-user{align-self:flex-end;background:var(--cc-accent-contrast);color:var(--cc-on-accent);border-end-end-radius:4px}.cc-message-assistant{align-self:flex-start;background:var(--cc-bg-surface);color:var(--cc-text);border-end-start-radius:4px}.cc-suggestions{display:flex;flex-wrap:wrap;gap:8px;padding:0 16px 12px}.cc-suggestion{border:1px solid var(--cc-border);border-radius:var(--cc-radius);padding:8px 12px;background:var(--cc-bg-surface);color:var(--cc-text);cursor:pointer;font:inherit}.cc-suggestion:hover{border-color:var(--cc-accent)}.cc-message a{color:var(--cc-accent);text-decoration:underline}.cc-message-user a{color:var(--cc-on-accent)}.cc-disclosure{margin-block-end:4px;padding:8px 12px;border:1px solid var(--cc-border);border-radius:10px;font-size:12px;color:var(--cc-text-secondary)}.cc-disclosure a{color:inherit;text-decoration:underline}.cc-message-error-note{margin-top:6px;font-size:12px;color:var(--cc-text-secondary)}.cc-message-sources{margin-block-start:8px;font-size:12px;color:var(--cc-text-secondary)}.cc-message-sources ol{margin:0;padding-inline-start:1.2em}.cc-message-sources a{color:var(--cc-text-secondary);text-decoration:underline}.cc-message code{background:var(--cc-code-bg);padding:1px 4px;border-radius:4px;font-family:SF Mono,Cascadia Code,Consolas,monospace;font-size:13px}.cc-message pre{background:var(--cc-pre-bg);padding:8px 12px;border-radius:8px;overflow-x:auto;margin:4px 0}.cc-message pre code{background:transparent;padding:0}.cc-message ul,.cc-message ol{padding-inline-start:20px;margin:4px 0}.cc-message h1,.cc-message h2,.cc-message h3,.cc-message h4,.cc-message h5,.cc-message h6{font-size:15px;font-weight:600;line-height:1.4;margin:4px 0 0}.cc-message-actions{display:flex;align-items:center}.cc-message-retry,.cc-message-regenerate{display:inline-flex;align-items:center;gap:4px;padding:4px 10px;background:transparent;border:1px solid var(--cc-border);border-radius:6px;color:var(--cc-text-secondary);font-family:var(--cc-font);font-size:12px;cursor:pointer;transition:background .15s,color .15s,opacity .15s}.cc-message-retry:hover,.cc-message-regenerate:hover{background:var(--cc-bg-input);color:var(--cc-text)}.cc-message-retry svg,.cc-message-regenerate svg{fill:currentColor}.cc-message-regenerate{opacity:0}.cc-message:hover .cc-message-regenerate{opacity:1}.cc-message:focus-within .cc-message-regenerate,.cc-message-regenerate:focus-visible{opacity:1}@media(hover:none){.cc-message-regenerate{opacity:1}}.cc-message-retry{border-color:var(--cc-danger);color:var(--cc-danger)}.cc-message-retry:hover{background:color-mix(in srgb,var(--cc-danger) 10%,transparent);color:var(--cc-danger)}.cc-typing{display:flex;align-items:center;gap:4px;padding:10px 14px;align-self:flex-start;background:var(--cc-bg-surface);border-radius:var(--cc-radius);border-end-start-radius:4px}.cc-typing-dot{width:6px;height:6px;border-radius:50%;background:var(--cc-text-secondary);animation:cc-bounce 1.2s infinite}.cc-typing-dot:nth-child(2){animation-delay:.2s}.cc-typing-dot:nth-child(3){animation-delay:.4s}@keyframes cc-bounce{0%,60%,to{transform:translateY(0)}30%{transform:translateY(-4px)}}.cc-input-area{display:flex;align-items:flex-end;padding:12px 16px;border-top:1px solid var(--cc-border);background:var(--cc-bg);gap:8px}.cc-input{flex:1;background:var(--cc-bg-input);border:1px solid var(--cc-border);border-radius:8px;padding:8px 12px;color:var(--cc-text);font-family:var(--cc-font);font-size:14px;line-height:1.5;resize:none;outline:none;max-height:96px;overflow-y:auto;transition:border-color .15s}.cc-input:focus{border-color:var(--cc-accent)}.cc-input::placeholder{color:var(--cc-text-secondary)}.cc-send-btn{width:36px;height:36px;border-radius:8px;background:var(--cc-accent);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .15s,opacity .15s}.cc-send-btn:hover{background:var(--cc-accent-hover)}.cc-send-btn:disabled{opacity:.4;cursor:not-allowed}.cc-send-btn svg{width:16px;height:16px;fill:var(--cc-on-accent)}:host([dir="rtl"]) .cc-send-btn svg{transform:scaleX(-1)}.cc-footer{padding:6px 16px;text-align:center;font-size:11px;color:var(--cc-text-secondary);border-top:1px solid var(--cc-border)}.cc-footer a{color:var(--cc-text-secondary);text-decoration:none}.cc-footer a:hover{text-decoration:underline}.cc-bubble{position:fixed;bottom:84px;right:20px;background:var(--cc-bg-surface);color:var(--cc-text);padding:10px 16px;border-radius:var(--cc-radius);box-shadow:var(--cc-shadow);border:1px solid var(--cc-border);max-width:260px;font-size:13px;line-height:1.4;z-index:9998;opacity:0;transform:translateY(8px);pointer-events:none;transition:opacity .3s,transform .3s}.cc-bubble.cc-visible{opacity:1;transform:translateY(0);pointer-events:auto}.cc-bubble.cc-left{right:auto;left:20px}.cc-bubble-trigger{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:block;width:100%;padding:0;margin:0;border:0;background:transparent;color:inherit;font:inherit;line-height:inherit;text-align:start;cursor:pointer}.cc-bubble-close{position:absolute;top:-8px;inset-inline-end:-8px;width:20px;height:20px;border-radius:50%;background:var(--cc-bg);border:1px solid var(--cc-border);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:10px;color:var(--cc-text-secondary)}.cc-hidden{display:none}.cc-sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap}.cc-messages-wrapper{flex:1;display:flex;flex-direction:column;min-height:0}@media(max-width:640px){.cc-fab.cc-open{display:none}.cc-panel:not(.cc-inline){width:100%;height:100%;height:100dvh;max-height:100%;bottom:0;inset-inline:0;border-radius:0;border:none;padding-top:env(safe-area-inset-top);padding-bottom:env(safe-area-inset-bottom)}.cc-panel.cc-left:not(.cc-inline){left:0}.cc-input{font-size:16px}.cc-bubble{bottom:84px;inset-inline:16px;max-width:none}}.cc-header-close:focus-visible,.cc-send-btn:focus-visible,.cc-suggestion:focus-visible,.cc-message-retry:focus-visible,.cc-message-regenerate:focus-visible,.cc-bubble-trigger:focus-visible,.cc-bubble-close:focus-visible,.cc-input:focus-visible{outline:2px solid transparent;box-shadow:var(--cc-focus-ring)}@media(prefers-reduced-motion:reduce){.cc-typing-dot{animation:none}.cc-panel,.cc-bubble{transition:none}}',c.appendChild(n),c}const c='<svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z"/><path d="M7 9h10v2H7zm0-3h10v2H7z"/></svg>',n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},o=new Set(["http","https","mailto","tel"]);function a(t){let e=t.replace(/[&<>"']/g,t=>n[t]??t);const i=function(t){let e="\0";for(;t.includes(e);)e+="\0";return e}(e),s=[],r=t=>{const e=s.push(t)-1;return`${i}${e}${i}`};e=e.replace(/```(?:\w*)\n?([\s\S]*?)```/g,(t,e)=>r(`<pre><code>${e.trim()}</code></pre>`)),e=e.replace(/`([^`]+)`/g,(t,e)=>r(`<code>${e}</code>`)),e=e.replace(/^(#{1,6}) (.+)$/gm,(t,e,i)=>{const s=e.length;return`<h${s}>${i}</h${s}>`}),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(\S(?:.*?\S)??)\*/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\(((?:[^()]*|\([^()]*\))*)\)/g,(t,e,i)=>function(t){const e=t.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""),i=/^([^:/?#]+):/.exec(e);return!i||o.has(i[1].toLowerCase())}(i)?`<a href="${i}" target="_blank" rel="noopener noreferrer">${e}</a>`:e),e=e.replace(/^[-*+] (.+)$/gm,'<li data-md="ul">$1</li>'),e=e.replace(/^\d+\. (.+)$/gm,'<li data-md="ol">$1</li>'),e=e.replace(/(?:<li data-md="ul">.*?<\/li>\n?)+|(?:<li data-md="ol">.*?<\/li>\n?)+/g,t=>{const e=t.includes('data-md="ol"')?"ol":"ul";return`<${e}>${t.replace(/ data-md="(?:ul|ol)"/g,"").replace(/\n/g,"")}</${e}>`}),e=e.replace(/(<\/h[1-6]>)\n+/g,"$1"),e=e.replace(/\n\n/g,"<br><br>"),e=e.replace(/\n/g,"<br>");for(let c=0;c<s.length;c++)e=e.replace(`${i}${c}${i}`,()=>s[c]);return e}class h{constructor(t,e,i={}){this.streams=new Map,this.t=null,this.i=null,this.o=null,this.actions=e,this.streamIntervalMs=i.streamIntervalMs??50,this.container=document.createElement("div"),this.container.className="cc-messages",this.container.setAttribute("role","log"),this.container.setAttribute("aria-live","polite"),t.appendChild(this.container),this.h=document.createElement("div"),this.h.className="cc-reply-announcement cc-sr-only",this.h.setAttribute("aria-live","polite"),this.h.setAttribute("aria-atomic","true"),t.appendChild(this.h)}beginReply(){this.h.textContent="",this.container.setAttribute("aria-live","off")}finishReply(t){var e,i,s,r;if("assistant"===(null==t?void 0:t.role)&&("complete"===t.status||"error"===t.status)){const c=this.l(t.id),n=(null==(i=null==(e=null==c?void 0:c.querySelector(".cc-message-content"))?void 0:e.textContent)?void 0:i.trim())??"",o=(null==(r=null==(s=null==c?void 0:c.querySelector(".cc-message-error-note"))?void 0:s.textContent)?void 0:r.trim())??"";this.h.textContent=[n,o&&o!==n?o:""].filter(Boolean).join(" ")}this.container.setAttribute("aria-live","polite")}addMessage(t){const e="user"===t.role||this.u();this.removeTyping(),"user"===t.role&&this.removeSuggestions();const i=this.p(t);return this.container.appendChild(i),e&&this.v(),i}updateMessage(t){const e=this.l(t.id);if(!e)return;if("assistant"===t.role&&"streaming"===t.status&&"streaming"===e.dataset.status)return void this.stream(e,t);this.m(t.id);const i=this.u();this.k(e,t),i&&this.v()}stream(t,e){let i=this.streams.get(e.id);if(!i||!function(t,e){if(e.length<t.length)return!1;const i=Math.max(0,t.length-32);return e.slice(i,t.length)===t.slice(i)}(i.text,e.content)){this.m(e.id);const s=t.querySelector(".cc-message-content");if(!s)return;s.innerHTML="";const r=document.createElement("div");return r.className="cc-stream-tail",s.appendChild(r),i={text:e.content,committed:0,tail:r,renderedAt:0},this.streams.set(e.id,i),void this.$(i)}i.text=e.content,void 0===i.frame&&this.schedule(i)}schedule(t){t.frame=l(()=>{t.frame=void 0,performance.now()-t.renderedAt<this.streamIntervalMs?this.schedule(t):this.$(t)})}$(t){t.renderedAt=performance.now();const e=this.u(),i=function(t,e){let i=!1,s=e,r=e;for(;r<t.length;)if(t.startsWith("```",r))i=!i,r+=3;else if(!i&&t.startsWith("\n\n",r)){for(r+=2;"\n"===t[r];)r++;s=r}else r++;return s}(t.text,t.committed);i>t.committed&&(t.tail.insertAdjacentHTML("beforebegin",`<div class="cc-block">${a(t.text.slice(t.committed,i))}</div>`),t.committed=i),t.tail.innerHTML=a(t.text.slice(t.committed)),e&&this.v()}m(t){const e=this.streams.get(t);void 0!==(null==e?void 0:e.frame)&&d(e.frame),this.streams.delete(t)}u(){const{scrollHeight:t,scrollTop:e,clientHeight:i}=this.container;return t-e-i<=48}showTyping(){var t;this.t||(this.t=document.createElement("div"),this.t.className="cc-typing",this.t.innerHTML=`<span class="cc-sr-only">${this.C((null==(t=this.actions)?void 0:t.typingLabel)??"Typing...")}</span><div class="cc-typing-dot" aria-hidden="true"></div><div class="cc-typing-dot" aria-hidden="true"></div><div class="cc-typing-dot" aria-hidden="true"></div>`,this.container.appendChild(this.t),this.v())}removeTyping(){this.t&&(this.t.remove(),this.t=null)}showSuggestions(t,e,i){if(this.removeSuggestions(),0===t.length)return;const s=document.createElement("div");s.className="cc-suggestions",s.setAttribute("role","group"),s.setAttribute("aria-label",e);for(const r of t){const t=document.createElement("button");t.type="button",t.className="cc-suggestion",t.textContent=r,t.addEventListener("click",()=>i(r)),s.appendChild(t)}this.container.appendChild(s),this.i=s}removeSuggestions(){var t;null==(t=this.i)||t.remove(),this.i=null}clear(){for(const t of[...this.streams.keys()])this.m(t);this.container.innerHTML="",this.t=null,this.o&&this.container.prepend(this.o)}setDisclosure(t,e){var i;if(null==(i=this.o)||i.remove(),this.o=null,!t)return;const s=document.createElement("div");if(s.className="cc-disclosure",s.setAttribute("role","note"),s.textContent=t,e&&/^https?:\/\//i.test(e.url)){const t=document.createElement("a");t.href=e.url,t.target="_blank",t.rel="noopener noreferrer",t.textContent=e.label,s.append(" ",t)}this.o=s,this.container.prepend(s)}removeMessage(t){this.m(t);const e=this.l(t);null==e||e.remove()}clearRegenerateButtons(){this.container.querySelectorAll(".cc-message-regenerate").forEach(t=>{t.remove()}),this.S()}showRegenerateButton(t){var e;if(this.clearRegenerateButtons(),!(null==(e=this.actions)?void 0:e.onRegenerate))return;const i=this.l(t);i&&i.classList.contains("cc-message-assistant")&&this.M(i).appendChild(this.T({className:"cc-message-regenerate",label:this.actions.regenerateLabel??"Regenerate",icon:'<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0020 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74A7.93 7.93 0 004 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/></svg>',onClick:()=>{var e,i;return null==(i=null==(e=this.actions)?void 0:e.onRegenerate)?void 0:i.call(e,t)}}))}setVisible(t){this.container.classList.toggle("cc-hidden",!t)}l(t){return Array.from(this.container.children).find(e=>e.dataset.id===t)??null}v(){this.container.scrollTop=this.container.scrollHeight}p(t){const e=document.createElement("div");return this.k(e,t),e}k(t,e){var i;t.className=`cc-message cc-message-${e.role}`,t.dataset.id=e.id,"assistant"===e.role&&"welcome"!==e.id&&(t.dataset.aiGenerated="true"),e.status?t.dataset.status=e.status:delete t.dataset.status,"streaming"===e.status?t.setAttribute("aria-busy","true"):t.removeAttribute("aria-busy"),e.errorType?t.dataset.errorType=e.errorType:delete t.dataset.errorType,t.innerHTML="";const s=document.createElement("div");if(s.className="cc-message-content",s.innerHTML="assistant"===e.role?a(e.content):this.C(e.content),t.appendChild(s),"assistant"===e.role&&Array.isArray(e.sources)&&e.sources.length>0){const s=e.sources.filter(t=>"string"==typeof t.url&&(t.url.startsWith("http://")||t.url.startsWith("https://")));if(s.length>0){const e=document.createElement("nav");e.className="cc-message-sources",e.setAttribute("aria-label",(null==(i=this.actions)?void 0:i.sourcesLabel)??"Sources");const r=document.createElement("ol");for(const t of s){const e=document.createElement("li"),i=document.createElement("a");i.href=t.url,i.target="_blank",i.rel="noopener noreferrer";try{i.textContent=t.title??new URL(t.url).hostname}catch{i.textContent=t.title??t.url}e.appendChild(i),r.appendChild(e)}e.appendChild(r),t.appendChild(e)}}if("error"===e.status&&e.errorText){const i=document.createElement("div");i.className="cc-message-error-note",i.textContent=e.errorText,t.appendChild(i)}const r=this.A(e);r&&t.appendChild(r)}A(t){var e;if("error"!==t.status||!(null==(e=this.actions)?void 0:e.onRetry))return null;const i=document.createElement("div");return i.className="cc-message-actions",i.appendChild(this.T({className:"cc-message-retry",label:this.actions.retryLabel??"Retry",icon:'<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M17.65 6.35A7.96 7.96 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>',onClick:()=>{var e,i;return null==(i=null==(e=this.actions)?void 0:e.onRetry)?void 0:i.call(e,t.id)}})),i}M(t){const e=t.querySelector(".cc-message-actions");if(e)return e;const i=document.createElement("div");return i.className="cc-message-actions",t.appendChild(i),i}S(){this.container.querySelectorAll(".cc-message-actions").forEach(t=>{t.hasChildNodes()||t.remove()})}T(t){const e=document.createElement("button");return e.type="button",e.className=t.className,e.innerHTML=`${t.icon}<span>${this.C(t.label)}</span>`,e.addEventListener("click",t.onClick),e}C(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}}const l=t=>"function"==typeof requestAnimationFrame?requestAnimationFrame(t):setTimeout(t,16),d=t=>"function"==typeof cancelAnimationFrame?cancelAnimationFrame(t):clearTimeout(t);class u{constructor(t,e){this._=e._,this.L=document.createElement("div"),this.L.className="cc-input-area",this.B=document.createElement("textarea"),this.B.className="cc-input",this.B.placeholder=e.placeholder,this.B.setAttribute("aria-label",e.placeholder),this.B.rows=1,this.B.maxLength=1e4,this.B.addEventListener("input",()=>this.I()),this.B.addEventListener("keydown",t=>this.O(t)),this.j=document.createElement("button"),this.j.className="cc-send-btn",this.j.disabled=!0,this.j.setAttribute("aria-label",e.sendLabel),this.j.innerHTML='<svg viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>',this.j.addEventListener("click",()=>this.send()),this.B.addEventListener("input",()=>{this.j.disabled=0===this.B.value.trim().length}),this.L.appendChild(this.B),this.L.appendChild(this.j),t.appendChild(this.L)}setLabels(t,e){this.B.placeholder=t,this.B.setAttribute("aria-label",t),this.j.setAttribute("aria-label",e)}focus(){this.B.focus()}setDisabled(t){this.B.disabled=t,this.j.disabled=t||0===this.B.value.trim().length}clear(){this.B.value="",this.j.disabled=!0,this.I()}setVisible(t){this.L.classList.toggle("cc-hidden",!t)}send(){const t=this.B.value.trim();t&&(this._(t),this.clear())}O(t){t.isComposing||229===t.keyCode||"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.send())}I(){this.B.style.height="auto",this.B.style.height=Math.min(this.B.scrollHeight,96)+"px"}}const p="cc-panel";class f{constructor(t,e){this.D=e.D??!1,this.R=document.createElement("div"),this.R.className="cc-panel",e.D&&this.R.classList.add("cc-inline"),"bottom-left"===e.position&&this.R.classList.add("cc-left"),e.D||(this.R.id=p,this.R.setAttribute("role","dialog"),this.R.setAttribute("aria-modal","true"),this.R.addEventListener("keydown",t=>{if("Escape"===t.key)return void e.onClose();if("Tab"!==t.key||this.R.hasAttribute("inert"))return;const i=Array.from(this.R.querySelectorAll("*")).filter(t=>t.tabIndex>=0&&!t.matches(":disabled")&&!t.closest('[hidden], [inert], [aria-hidden="true"], .cc-hidden'));if(0===i.length)return void t.preventDefault();const s=this.R.getRootNode().activeElement,r=i[0],c=i[i.length-1];!t.shiftKey||s!==r&&this.R.contains(s)?t.shiftKey||s!==c&&this.R.contains(s)||(t.preventDefault(),r.focus()):(t.preventDefault(),c.focus())}),this.P(!0)),this.options=e,this.header=document.createElement("div"),this.header.className="cc-header",this.N(),this.R.appendChild(this.header),e.preChatEnabled?(this.H=document.createElement("div"),this.H.className="cc-messages-wrapper",this.R.appendChild(this.H)):this.H=this.R,this.messages=new h(this.H,e.messageActions),this.input=new u(this.R,{placeholder:e.placeholder,sendLabel:e.sendLabel,_:e._}),this.footer=document.createElement("div"),this.footer.className="cc-footer",this.footer.innerHTML=e.footerText,this.R.appendChild(this.footer),t.appendChild(this.R)}update(t,e){Object.assign(this.options,t),this.options.messageActions&&Object.assign(this.options.messageActions,e),this.N(),this.input.setLabels(t.placeholder,t.sendLabel),this.footer.innerHTML=t.footerText}N(){const{branding:t,V:e,D:i,onClose:s}=this.options,r=this.header.contains(this.R.getRootNode().activeElement);if(this.header.replaceChildren(),i||this.R.setAttribute("aria-label",t.name),t.avatar){const e=document.createElement("img");e.className="cc-header-avatar",e.src=t.avatar,e.alt=t.name,this.header.appendChild(e)}else{const t=document.createElement("div");t.className="cc-header-avatar-placeholder",t.innerHTML='<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/></svg>',this.header.appendChild(t)}const c=document.createElement("div");if(c.className="cc-header-info",c.innerHTML=`<div class="cc-header-name">${this.C(t.name)}</div><div class="cc-header-subtitle">${this.C(t.subtitle)}</div>`,this.header.appendChild(c),!i){const t=document.createElement("button");t.className="cc-header-close",t.setAttribute("aria-label",e),t.innerHTML='<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>',t.addEventListener("click",s),this.header.appendChild(t),r&&t.focus()}}show(){this.R.classList.add("cc-visible"),this.D||(this.P(!1),this.input.focus())}hide(){this.R.classList.remove("cc-visible"),this.D||this.P(!0)}containsFocus(){return this.R.contains(this.R.getRootNode().activeElement)}get isVisible(){return this.R.classList.contains("cc-visible")}addMessage(t){return this.messages.addMessage(t)}hideMessages(){this.messages.setVisible(!1)}showMessages(){this.messages.setVisible(!0)}destroy(){this.R.remove()}P(t){this.R.toggleAttribute("inert",t),t?this.R.setAttribute("aria-hidden","true"):this.R.removeAttribute("aria-hidden")}C(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}}class g{constructor(t,e){this.F=e.F,this.V=e.V,this.U=e.U,this.R=document.createElement("button"),this.R.className="cc-fab cc-pulse",this.R.setAttribute("aria-label",this.F),this.R.setAttribute("aria-expanded","false"),this.R.setAttribute("aria-controls",p),"bottom-left"===e.position&&this.R.classList.add("cc-left"),this.R.innerHTML=c,this.badge=document.createElement("div"),this.badge.className="cc-fab-badge",this.R.appendChild(this.badge),this.R.addEventListener("click",()=>{this.R.classList.remove("cc-pulse"),e.onClick()}),t.appendChild(this.R)}setOpen(t){t&&this.hideBadge(),this.R.innerHTML=t?'<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>':c,t||this.R.appendChild(this.badge),this.R.classList.toggle("cc-open",t),this.R.setAttribute("aria-label",t?this.V:this.F),this.R.setAttribute("aria-expanded",String(t))}setLabels(t,e,i){this.F=t,this.V=e,this.U=i;const s=this.badge.textContent;this.R.setAttribute("aria-label",this.R.classList.contains("cc-open")?e:s?`${t}, ${i.replace("{count}",s)}`:t)}focus(){this.R.focus()}showBadge(t=1){if(t<=0)return void this.hideBadge();const e=t>9?"9+":String(t);if(this.badge.textContent=e,!this.R.classList.contains("cc-open")){const t=this.U.replace("{count}",e);this.R.setAttribute("aria-label",`${this.F}, ${t}`)}this.badge.classList.add("cc-visible")}hideBadge(){this.badge.classList.remove("cc-visible"),this.badge.textContent="",this.R.classList.contains("cc-open")||this.R.setAttribute("aria-label",this.F)}destroy(){this.R.remove()}}const b="chatcops_bubble_shown";class v{constructor(t,e){this.q=null,this.R=document.createElement("div"),this.R.className="cc-bubble","bottom-left"===e.position&&this.R.classList.add("cc-left"),this.P(!0);const i=document.createElement("button");i.type="button",i.className="cc-bubble-trigger",i.textContent=e.text,i.addEventListener("click",()=>{this.hide(),e.onClick()});const s=document.createElement("button");s.type="button",s.className="cc-bubble-close",s.setAttribute("aria-label",e.dismissLabel),s.innerHTML="&times;",s.addEventListener("click",t=>{t.stopPropagation(),this.hide()}),this.R.append(i,s),t.appendChild(this.R),this.q=setTimeout(()=>{if(e.showOnce){if(e.store.get(b))return;e.store.set(b,"1")}this.R.classList.add("cc-visible"),this.P(!1)},e.delay??3e3)}hide(){this.R.classList.remove("cc-visible"),this.P(!0),this.q&&(clearTimeout(this.q),this.q=null)}P(t){this.R.toggleAttribute("inert",t),t?this.R.setAttribute("aria-hidden","true"):this.R.removeAttribute("aria-hidden")}destroy(){this.hide(),this.R.remove()}}const m="chatcops_conversation";function x(t){if("none"===t){const t=new Map;return{get:e=>t.get(e)??null,set:(e,i)=>{t.set(e,i)},remove:e=>{t.delete(e)}}}const e=()=>"local"===t?localStorage:sessionStorage;return{get(t){try{return e().getItem(t)}catch{return null}},set(t,i){try{e().setItem(t,i)}catch{}},remove(t){try{e().removeItem(t)}catch{}}}}class y{constructor(t,e="local",i=30){this.store=x(e),this.key=t?`${m}_${t}`:m,this.Y=864e5*(Number.isFinite(i)&&i>=0?i:30)}load(t=Date.now()){const e=this.store.get(this.key);if(null===e)return null;let i;try{i=JSON.parse(e)}catch{return this.clear(),null}if("object"!=typeof i||null===i||Array.isArray(i)||"string"!=typeof i.id||!Array.isArray(i.messages))return this.clear(),null;const s=i;if("number"==typeof s.updatedAt&&t-s.updatedAt>this.Y)return this.clear(),null;const r=s.messages.flatMap(t=>{if("object"!=typeof t||null===t||Array.isArray(t)||"user"!==t.role&&"assistant"!==t.role||"string"!=typeof t.content)return[];const e=t;let i;if(Array.isArray(e.sources)){const t=e.sources.filter(t=>"object"==typeof t&&null!==t&&!Array.isArray(t)&&"string"==typeof t.url&&(void 0===t.title||"string"==typeof t.title));t.length>0&&(i=t)}return[{...e,sources:i}]}),c=s.userData;return{...s,id:s.id,messages:r,userData:c&&"object"==typeof c&&!Array.isArray(c)?c:void 0,preChatDone:!0===s.preChatDone}}save(t){const e={...t,messages:t.messages.filter(t=>"error"!==t.status).map(({status:t,...e})=>e)};this.store.set(this.key,JSON.stringify(e))}clear(){this.store.remove(this.key)}}class w{constructor(t){this.apiUrl=t.apiUrl,this.turnstileSiteKey=t.turnstileSiteKey,this.userToken=t.userToken,this.timeout=t.timeout??3e4,this.J=`chatcops-session:${t.apiUrl}`,this.store=t.store??x("local")}setUserToken(t){t!==this.userToken&&(this.userToken=t,this.saved={},this.store.remove(this.J))}get identity(){return this.userToken}async*sendMessage(t,i={}){var s;const r=new AbortController,c=i.timeout??this.timeout;let n,o,a=!1;const h=i.signal,l=()=>{clearTimeout(n),r.abort()},d=()=>{clearTimeout(n),r.signal.aborted||(n=setTimeout(()=>{a=!0,r.abort()},c))},u=async()=>{if(clearTimeout(n),null==h||h.removeEventListener("abort",l),o){const t=o;o=void 0;try{await t.cancel()}catch{}finally{t.releaseLock()}}};h&&(h.aborted?r.abort():h.addEventListener("abort",l)),d();try{const i=(t,e,i)=>fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...i&&{Authorization:`Bearer ${i}`}},body:JSON.stringify(e),signal:r.signal});let c=this.saved;if(!c){try{c=JSON.parse(this.store.get(this.J)||"{}")??{}}catch{c={}}this.saved=c}const n=c.conversationId===t.conversationId;let a=await i(this.apiUrl,{protocol:1,...t},n?c.token:void 0);if(401===a.status){const s=await i(this.apiUrl.replace(/\/?(\?.*)?$/,"/session$1"),{conversationId:t.conversationId,previousToken:c.token,userToken:this.userToken,turnstileToken:this.turnstileSiteKey&&!n?await(await e(async()=>{const{turnstileToken:t}=await import("./chunks/turnstile-CAnVL3fK.js");return{turnstileToken:t}},[])).turnstileToken(this.turnstileSiteKey):void 0});if(s.ok){const e=await s.json();this.saved=e,this.store.set(this.J,JSON.stringify(e)),e.conversationId!==t.conversationId&&(t={...t,conversationId:e.conversationId},yield{conversationId:e.conversationId}),a=await i(this.apiUrl,{protocol:1,...t},e.token)}else this.saved={}}if(!a.ok){const{error:t}=await a.json().catch(()=>({}));return await u(),void(yield(null==t?void 0:t.code)?$(t.code,t.retryAfterMs):{error:429===a.status?"rate_limit":`HTTP ${a.status}`})}if(o=null==(s=a.body)?void 0:s.getReader(),!o)return await u(),void(yield{error:"No response body"});const h=new TextDecoder;let l="",p=!1,f=!1;for(;;){const{done:t,value:e}=await o.read();if(t)break;e.byteLength>0&&d(),l+=h.decode(e,{stream:!0});const i=l.split("\n");l=i.pop()??"";for(const s of i){const t=s.trim();if(!t||!t.startsWith("data: "))continue;const e=t.slice(6);if("[DONE]"===e)return await u(),void(yield p&&!f?{error:"cut_off"}:{done:!0});let i;try{i=JSON.parse(e)}catch{continue}if("type"in i){p=!0,"finish"===i.type&&(f=!0);const t=C(i);t&&(yield t)}else yield i}}await u(),yield"data: [DONE]"===l.trim()?{done:!0}:{error:p?"cut_off":"network"}}catch(p){await u(),p instanceof DOMException&&"AbortError"===p.name?yield a?{error:"timeout"}:{error:"aborted"}:yield{error:"network"}}finally{await u()}}}const k={rate_limited:"rate_limit",timeout:"timeout",budget_exceeded:"budget",budget_daily:"budget_daily",provider_unavailable:"unavailable"};function $(t,e){return{error:k[t]??"provider_error",retryAfterMs:e}}function C(t){switch(t.type){case"start":return{messageId:t.messageId};case"text-delta":return{content:t.delta};case"lead-captured":return{leadCaptured:!0,leadData:t.lead};case"source":{const{url:e,title:i}=t;return e.startsWith("http://")||e.startsWith("https://")?{source:{url:e,title:i}}:null}case"error":return $("budget_exceeded"===t.code&&"conversation"!==t.scope?"budget_daily":t.code,t.retryAfterMs);case"finish":return"error"===t.reason||"aborted"===t.reason?null:{done:!0};default:return null}}const S=Symbol.for("chatcops.storageClaims"),M=globalThis;M[S]??(M[S]=new Map);const T=M[S];function A(t){const e=T.get(t);if(!e)return!1;for(const i of e)i()||e.delete(i);return 0===e.size&&T.delete(t),e.size>0}const z=["light","dark","auto"];function _(t,e){const i=t.host,s=function(t){return t.mode&&z.includes(t.mode)?t.mode:t.bgColor?O(t.bgColor)&&j(t.bgColor)>.4?"light":"dark":t.textColor?O(t.textColor)&&j(t.textColor)<.4?"light":"dark":void 0}(e);if(s?i.dataset.ccMode=s:delete i.dataset.ccMode,e.accent&&L(i,"",e.accent),e.accentDark&&L(i,"-dark",e.accentDark),e.textColor&&i.style.setProperty("--cc-text",e.textColor),e.bgColor&&(i.style.setProperty("--cc-bg",e.bgColor),i.style.setProperty("--cc-bg-surface",H(e.bgColor,8)),i.style.setProperty("--cc-bg-input",H(e.bgColor,14))),e.fontFamily&&i.style.setProperty("--cc-font",e.fontFamily),void 0!==e.borderRadius){const t=function(t){if("number"==typeof t&&!Number.isFinite(t))return"";const e=String(t).trim();return/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(e)?`${e}px`:e}(e.borderRadius);t&&i.style.setProperty("--cc-radius",t)}}function L(t,e,i){t.style.setProperty(`--cc-theme-accent${e}`,i),t.style.setProperty(`--cc-theme-accent${e}-hover`,N(i,10));const s=function(t){if(!O(t))return null;const e=t.trim().startsWith("#")?t.trim():`#${t.trim()}`;if(D(B,e)>=I)return{onAccent:B,background:e};if(D(E,e)>=I)return{onAccent:E,background:e};for(let i=2;i<=60;i+=2){const t=N(e,i);if(D(B,t)>=I)return{onAccent:B,background:t}}return{onAccent:B,background:E}}(i);s?(t.style.setProperty(`--cc-theme-on-accent${e}`,s.onAccent),t.style.setProperty(`--cc-theme-accent${e}-contrast`,s.background)):t.style.setProperty(`--cc-theme-accent${e}-contrast`,i)}const B="#ffffff",E="#0a0a0a",I=4.5;function O(t){return/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(t.trim())}function j(t){const e=R(t).map(t=>{const e=t/255;return e<=.03928?e/12.92:((e+.055)/1.055)**2.4});return.2126*e[0]+.7152*e[1]+.0722*e[2]}function D(t,e){const[i,s]=[j(t),j(e)].sort((t,e)=>e-t);return(i+.05)/(s+.05)}function R(t){if(!/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(t))return[0,0,0];const e=t.replace("#",""),i=parseInt(3===e.length?e.split("").map(t=>t+t).join(""):e,16);return[i>>16&255,i>>8&255,255&i]}function P(t,e,i){return"#"+[t,e,i].map(t=>Math.max(0,Math.min(255,t)).toString(16).padStart(2,"0")).join("")}function N(t,e){const[i,s,r]=R(t),c=1-e/100;return P(Math.round(i*c),Math.round(s*c),Math.round(r*c))}function H(t,e){const[i,s,r]=R(t),c=e/100;return P(Math.round(i+(255-i)*c),Math.round(s+(255-s)*c),Math.round(r+(255-r)*c))}const V={welcomeMessage:"How can I help you today?",inputPlaceholder:"Type a message...",sendButton:"Send",closeButton:"Close",openChat:"Open chat",defaultName:"AI Assistant",defaultSubtitle:"Online",greetingWithName:"Hi {name}!",selectPlaceholder:"Select {label}...",dismissBubble:"Dismiss",errorGeneric:"Something went wrong. Please try again.",errorNetwork:"Connection error. Please check your network.",errorRateLimit:"Too many messages. Please wait a moment.",errorRateLimitWait:"Too many messages. Please try again in {seconds} seconds.",errorBudget:"This chat has reached its limit.",errorBudgetDaily:"The assistant has reached its limit for today. Please try again later.",errorUnavailable:"The assistant is unavailable right now. Please try again later.",errorCutOff:"The reply was cut off.",typingIndicator:"Typing...",poweredBy:"Powered by ChatCops",newConversation:"New conversation",welcomeBubbleDefault:"Need help? Chat with us!",preChatTitle:"Before we start...",preChatSubtitle:"Tell us a bit about yourself",preChatSubmit:"Start Chat",preChatRequired:"This field is required",preChatInvalidEmail:"Please enter a valid email",retryButton:"Retry",regenerateButton:"Regenerate",suggestionsLabel:"Suggested questions",unreadCount:"{count} unread",sourcesLabel:"Sources",disclosure:"You're chatting with an AI assistant. It can make mistakes.",disclosureLearnMore:"Learn more"},F={en:V};function U(t,e){const i=F[t]??V;return e?{...i,...e}:i}const q={network:"errorNetwork",timeout:"errorNetwork",provider_error:"errorGeneric",budget:"errorBudget",budget_daily:"errorBudgetDaily",unavailable:"errorUnavailable",cut_off:"errorCutOff"};let Y;function J(){return Y??(Y=e(()=>import("./chunks/prechat-form-DiHgHUnU.js"),[]).catch(t=>{throw Y=void 0,t})),Y}function G(t){var e;(null==(e=t.preChatForm)?void 0:e.enabled)&&J().catch(()=>{})}class W{constructor(t){if(this.G=!1,this.conversationId=crypto.randomUUID(),this.preChatDone=!1,this.W=!1,this.messages=[],this.K=!1,this.v1=!1,this.X=!1,this.generation=0,this.Z=!1,this.tt=new Map,this.et=new Map,this.it=0,"persistHistory"in t)throw new Error("ChatCops: persistHistory was removed in 1.0. Use persistence: 'none'.");this.config=t,this.st=function(t,e,i){let s=t??"";if(void 0===t&&A("")){s=e;for(let t=2;A(s);t+=1)s=`${e}-${t}`;console.warn(`[chatcops] Another widget on this page already uses the default storage, so this one keeps its conversation under "${s}". Set a \`siteId\` on each widget to name them yourself.`)}else void 0!==t&&A(t)&&console.warn(`[chatcops] Two widgets on this page use the siteId "${t}", so they share one conversation.`);return T.has(s)||T.set(s,new Set),T.get(s).add(i),{siteId:""===s?void 0:s,release(){var t,e;null==(t=T.get(s))||t.delete(i),0===(null==(e=T.get(s))?void 0:e.size)&&T.delete(s)}}}(t.siteId,t.mode??"popup",()=>!this.X&&(!this.G||this.rt.host.isConnected));const e=t.persistence??"local";this.storage=new y(this.st.siteId,e,t.historyTtlDays),this.client=new w({...t,store:this.storage.store}),this.locale=U(t.locale??"en",t.strings)}get isInline(){return"inline"===this.config.mode}ct(){if(!this.config.container)throw new Error('ChatCops: "container" is required when mode is "inline"');if("string"==typeof this.config.container){const t=document.querySelector(this.config.container);if(!t)throw new Error(`ChatCops: container element not found: ${this.config.container}`);return t}return this.config.container}init(){var t,e;G(this.config),this.isInline?(this.nt=this.ct(),this.rt=r(this.nt,{dir:this.config.dir,locale:this.config.locale})):this.rt=r(void 0,{dir:this.config.dir,locale:this.config.locale}),this.G=!0,this.config.theme&&_(this.rt,this.config.theme);const i=(null==(t=this.config.theme)?void 0:t.position)??"bottom-right";if(this.isInline||(this.ot=new g(this.rt,{position:i,F:this.locale.openChat,V:this.locale.closeButton,U:this.locale.unreadCount,onClick:()=>this.toggle()})),this.ht=new f(this.rt,{position:i,D:this.isInline,preChatEnabled:(null==(e=this.config.preChatForm)?void 0:e.enabled)??!1,...this.lt(),messageActions:{onRetry:t=>{this.dt(t)},onRegenerate:t=>{this.ut(t)},...this.actionLabels()},_:t=>this.ft(t),onClose:()=>this.close()}),!1===this.config.disclosure&&console.info("[chatcops] The AI disclosure is off (disclosure: false). Under the EU AI Act (Article 50), telling visitors they're talking to an AI is then up to you."),this.gt(),this.isInline&&this.hydrate(),!this.isInline&&this.config.welcomeBubble&&(this.bt=new v(this.rt,{text:this.config.welcomeBubble.text,delay:this.config.welcomeBubble.delay,showOnce:this.config.welcomeBubble.showOnce??!0,store:this.storage.store,position:i,dismissLabel:this.locale.dismissBubble,onClick:()=>this.open()})),this.isInline&&this.ht.show(),!this.isInline&&void 0!==this.config.autoOpen&&!1!==this.config.autoOpen){const t="number"==typeof this.config.autoOpen?this.config.autoOpen:0;this.vt=setTimeout(()=>this.open(),t)}}hydrate(){var t,e;if(this.W)return;this.W=!0;const i=this.storage.load();if(i){this.conversationId=i.id,this.preChatDone=i.preChatDone??!1,(null==(t=this.config.preChatForm)?void 0:t.enabled)&&(this.userData=i.userData);for(const t of i.messages)this.messages.push(t),this.ht.addMessage(t)}(null==(e=this.config.preChatForm)?void 0:e.enabled)&&!this.preChatDone&&0===this.messages.length?this.showPreChatForm():this.xt(),this.yt()}open(){var t,e,i,s;this.it=0,this.hydrate(),this.ht.show(),this.isInline||(null==(t=this.ot)||t.setOpen(!0),null==(e=this.bt)||e.hide()),this.wt(),null==(s=(i=this.config).onOpen)||s.call(i),this.emit("open")}close(){var t,e,i,s;const r=this.ht.containsFocus();this.ht.hide(),this.isInline||(null==(t=this.ot)||t.setOpen(!1),r&&(null==(e=this.ot)||e.focus())),this.kt(),null==(s=(i=this.config).onClose)||s.call(i),this.emit("close")}toggle(){this.ht.isVisible?this.close():this.open()}async sendMessage(t,e={}){!1===e.open?this.hydrate():this.open(),await this.ft(t)}newConversation(){this.reset(!1)}clear(){this.reset(!0)}reset(t){var e,i,s;this.generation++,null==(e=this.$t)||e.abort(),this.$t=void 0,this.K=!1,this.tt.clear(),this.messages=[],this.conversationId=crypto.randomUUID(),this.W=!0,t&&(this.userData=void 0,this.preChatDone=!1,this.storage.clear()),null==(i=this.Ct)||i.destroy(),this.Ct=void 0,this.ht.messages.clear(),this.ht.input.setDisabled(!1),(null==(s=this.config.preChatForm)?void 0:s.enabled)&&!this.preChatDone?this.showPreChatForm():this.xt(),t||this.St()}setUser(t){const e=this.client.identity,i=null==t?void 0:t.token;if(void 0!==e&&e!==i&&this.clear(),this.client.setUserToken(i),!t)return;const s=Object.fromEntries(Object.entries({name:t.name,email:t.email}).filter(t=>"string"==typeof t[1]&&""!==t[1]));Object.keys(s).length&&(this.userData={...this.userData,...s},this.Z=!0)}setContext(t){this.Mt=t&&Object.keys(t).length?{...t}:void 0}update(t){var e,i;const s=this.config,r={...s.theme,...t.theme,position:null==(e=s.theme)?void 0:e.position};if(this.config={...s,...t,theme:r,branding:{...s.branding,...t.branding},strings:{...s.strings,...t.strings}},this.locale=U(this.config.locale??"en",this.config.strings),!this.G)return;t.theme&&_(this.rt,r);const c=this.locale;null==(i=this.ot)||i.setLabels(c.openChat,c.closeButton,c.unreadCount),this.ht.update(this.lt(),this.actionLabels()),this.gt(),1===this.messages.length&&"welcome"===this.messages[0].id&&(this.messages=[],this.ht.messages.clear(),this.xt())}lt(){const{branding:t,placeholder:e}=this.config,i=this.locale;return{branding:{name:(null==t?void 0:t.name)??i.defaultName,avatar:null==t?void 0:t.avatar,subtitle:(null==t?void 0:t.subtitle)??i.defaultSubtitle},placeholder:e??i.inputPlaceholder,footerText:i.poweredBy,V:i.closeButton,sendLabel:i.sendButton}}actionLabels(){const t=this.locale;return{retryLabel:t.retryButton,regenerateLabel:t.regenerateButton,typingLabel:t.typingIndicator,sourcesLabel:t.sourcesLabel}}gt(){const{disclosure:t}=this.config;!1===t?this.ht.messages.setDisclosure():this.ht.messages.setDisclosure((null==t?void 0:t.text)??this.locale.disclosure,(null==t?void 0:t.learnMoreUrl)?{url:t.learnMoreUrl,label:this.locale.disclosureLearnMore}:void 0)}Tt(t){return this.X||t!==this.generation}destroy(){var t,e,i,s,r;this.X=!0,void 0!==this.vt&&clearTimeout(this.vt),null==(t=this.$t)||t.abort(),this.$t=void 0,this.kt(),null==(e=this.Ct)||e.destroy(),null==(i=this.bt)||i.destroy(),this.ht.destroy(),null==(s=this.ot)||s.destroy(),null==(r=this.rt)||r.host.remove(),this.st.release(),this.et.clear(),this.messages=[],this.userData=void 0}wt(){var t,e;if(void 0===this.At&&!this.isInline&&"undefined"!=typeof window&&(null==(e=null==(t=window.matchMedia)?void 0:t.call(window,"(max-width: 640px)"))?void 0:e.matches)){const t=document.documentElement;this.At={value:t.style.getPropertyValue("overflow"),priority:t.style.getPropertyPriority("overflow")},t.style.setProperty("overflow","hidden")}}kt(){if(void 0===this.At)return;const{value:t,priority:e}=this.At;t?document.documentElement.style.setProperty("overflow",t,e):document.documentElement.style.removeProperty("overflow"),this.At=void 0}on(t,e){return this.et.has(t)||this.et.set(t,new Set),this.et.get(t).add(e),()=>this.off(t,e)}off(t,e){var i;null==(i=this.et.get(t))||i.delete(e)}emit(t,...e){var i;this.X||null==(i=this.et.get(t))||i.forEach(t=>{t(...e)})}showPreChatForm(){const t=this.config.preChatForm;this.ht.hideMessages(),this.ht.input.setVisible(!1),J().then(({PreChatForm:e})=>{this.X||this.preChatDone||this.Ct||(this.Ct=new e(this.ht.H,{title:t.title??this.locale.preChatTitle,subtitle:t.subtitle??this.locale.preChatSubtitle,fields:t.fields,submitLabel:t.submitLabel??this.locale.preChatSubmit,locale:this.locale,onSubmit:t=>this.zt(t)}))},t=>{console.error("[chatcops] The pre-chat form could not load:",t instanceof Error?t.message:t),this.X||this.preChatDone||(this.preChatDone=!0,this.ht.showMessages(),this.ht.input.setVisible(!0),this.xt())})}zt(t){var e,i,s,r;(null==(e=this.config.preChatForm)?void 0:e.enabled)&&(this.hydrate(),this.userData=t,this.preChatDone=!0,this.St(),null==(i=this.Ct)||i.destroy(),this.Ct=void 0,this.ht.showMessages(),this.ht.input.setVisible(!0),this.xt(),null==(r=(s=this.config).onPreChatSubmit)||r.call(s,t),this.emit("preChatSubmit",t),t.message&&this.ft(t.message))}xt(){var t;if(0===this.messages.length){const e=null==(t=this.userData)?void 0:t.name,i=this.locale.greetingWithName.replace("{name}",()=>e),s={id:"welcome",role:"assistant",content:e?`${i} ${this.config.welcomeMessage??this.locale.welcomeMessage}`:this.config.welcomeMessage??this.locale.welcomeMessage};this.messages.push(s),this.ht.addMessage(s),this._t()}}_t(t=this.config.suggestions??[]){this.messages.some(t=>"user"===t.role)||this.ht.messages.showSuggestions(t,this.locale.suggestionsLabel,t=>{this.ft(t)})}async ft(t){var e,i;if(this.K)return;this.hydrate();const s={id:crypto.randomUUID(),role:"user",content:t};this.messages.push(s),this.ht.addMessage(s),null==(i=(e=this.config).onMessage)||i.call(e,s),this.emit("message",s),await this.Lt(t,{userMessageId:s.id})}async dt(t){if(this.K)return;const e=this.messages.findIndex(e=>e.id===t);if(-1===e)return;const i=this.tt.get(t);let s=(null==i?void 0:i.userMessageId)?this.messages.find(t=>t.id===i.userMessageId):void 0;if(!s)for(let r=e-1;r>=0;r--)if("user"===this.messages[r].role){s=this.messages[r];break}s&&(this.ht.messages.removeMessage(t),this.tt.delete(t),this.messages=this.messages.filter(e=>e.id!==t),await this.Lt(s.content,{regenerate:null==i?void 0:i.regenerate,userMessageId:(null==i?void 0:i.userMessageId)??s.id}))}async ut(t){if(this.K)return;const e=this.messages.findIndex(e=>e.id===t);if(-1===e)return;if("assistant"!==this.messages[e].role)return;const i=this.Bt(e);i&&(this.ht.messages.clearRegenerateButtons(),this.ht.messages.removeMessage(t),this.tt.delete(t),this.messages=this.messages.filter(e=>e.id!==t),await this.Lt(i.content,{regenerate:!this.v1||{assistantMessageId:t},userMessageId:i.id}))}async Lt(t,e={}){var i,s,r,c,n,o,a,h,l;if(this.K)return;const d=this.generation;this.K=!0,this.ht.input.setDisabled(!0),this.ht.messages.clearRegenerateButtons(),this.ht.messages.beginReply(),this.ht.messages.showTyping();const u={id:crypto.randomUUID(),role:"assistant",content:"",status:"streaming",sources:[]};let p=!0,f=!1,g=!1;const b=new AbortController;this.$t=b;try{for await(const n of this.client.sendMessage(this.Et(t,e),{signal:b.signal})){if(this.Tt(d))break;if(n.error){const t=this.It(n.error);this.Ot(u,this.jt(t,n.retryAfterMs)),u.errorType=t,g=!0,this.tt.set(u.id,{regenerate:e.regenerate,userMessageId:e.userMessageId}),this.ht.messages.removeTyping(),p?this.ht.addMessage(u):this.ht.messages.updateMessage(u),this.messages.push(u);const r=new Error(n.error);null==(s=(i=this.config).onError)||s.call(i,r),this.emit("error",r);break}if(n.done){f=!0;break}n.conversationId&&(this.conversationId=n.conversationId),n.messageId&&(u.id=n.messageId,this.v1=!0),n.leadCaptured&&(null==(c=(r=this.config).onLeadCaptured)||c.call(r,n.leadData),this.emit("leadCaptured",n.leadData)),n.source&&(u.sources??(u.sources=[]),u.sources.push(n.source)),n.content&&(p&&(this.ht.messages.removeTyping(),this.ht.addMessage(u),p=!1),u.content+=n.content,this.ht.messages.updateMessage(u))}if(this.Tt(d))return;g||f||(f=!0),!g&&p&&this.ht.messages.removeTyping(),!g&&u.content&&(u.status="complete",this.ht.messages.updateMessage(u),this.messages.push(u),null==(o=(n=this.config).onMessage)||o.call(n,u),this.emit("message",u),this.yt(),this.isInline||this.ht.isVisible||(this.it++,null==(a=this.ot)||a.showBadge(this.it)))}catch(v){if(this.Tt(d))return;this.Ot(u,this.locale.errorGeneric),u.errorType="network",this.tt.set(u.id,{regenerate:e.regenerate,userMessageId:e.userMessageId}),this.ht.messages.removeTyping(),p?this.ht.addMessage(u):this.ht.messages.updateMessage(u),this.messages.push(u);const t=v instanceof Error?v:new Error(String(v));null==(l=(h=this.config).onError)||l.call(h,t),this.emit("error",t)}finally{this.$t===b&&(this.$t=void 0),this.Tt(d)||(this.ht.messages.finishReply(u),this.K=!1,this.ht.input.setDisabled(!1),this.ht.input.focus(),this.St())}}Et(t,e){var i;const s=!1!==this.config.pageContext?{url:window.location.href,title:document.title,...this.Mt?{data:this.Mt}:{}}:void 0,r=Boolean(((null==(i=this.config.preChatForm)?void 0:i.enabled)||this.Z)&&this.userData&&(!this.v1||this.Dt!==this.conversationId));return r&&(this.Dt=this.conversationId),{conversationId:this.conversationId,message:t,messageId:e.userMessageId,regenerate:e.regenerate,pageContext:s,locale:this.config.locale,...r?{userData:this.userData}:{}}}Bt(t){for(let e=t-1;e>=0;e--)if("user"===this.messages[e].role)return this.messages[e]}Rt(){for(let t=this.messages.length-1;t>=0;t--){const e=this.messages[t];if("welcome"!==e.id){if("assistant"!==e.role||"error"===e.status)return;return e}}}yt(){const t=this.Rt();t?this.ht.messages.showRegenerateButton(t.id):this.ht.messages.clearRegenerateButtons()}It(t){return t in q||"rate_limit"===t?t:"provider_error"}Ot(t,e){t.status="error",t.content.trim()?t.errorText=e:t.content=e}jt(t,e){return"rate_limit"===t?e?this.locale.errorRateLimitWait.replace("{seconds}",String(Math.ceil(e/1e3))):this.locale.errorRateLimit:this.locale[q[t]??"errorGeneric"]}St(){const t=this.config.maxMessages??50,e=this.messages.filter(t=>"welcome"!==t.id).slice(-t);this.storage.save({id:this.conversationId,messages:e.map(t=>({id:t.id,role:t.role,content:t.content,status:t.status,errorType:t.errorType,timestamp:Date.now(),...t.sources&&t.sources.length>0?{sources:t.sources}:{}})),...this.userData?{userData:this.userData}:{},...this.preChatDone?{preChatDone:!0}:{},updatedAt:Date.now()})}}export{W as Widget,G as prefetch};
@@ -0,0 +1 @@
1
+ class t{constructor(t,c){if(this.t=new Map,this.i=new Map,this.options=c,this.container=document.createElement("div"),this.container.className="cc-prechat",c.title){const t=document.createElement("div");t.className="cc-prechat-title",t.textContent=c.title,this.container.appendChild(t)}if(c.subtitle){const t=document.createElement("div");t.className="cc-prechat-subtitle",t.textContent=c.subtitle,this.container.appendChild(t)}const e=document.createElement("form");e.className="cc-prechat-fields",e.noValidate=!0,e.addEventListener("submit",t=>{t.preventDefault(),this.o()});for(const i of c.fields)e.appendChild(this.p(i));this.h=document.createElement("button"),this.h.type="submit",this.h.className="cc-prechat-submit",this.h.textContent=c.submitLabel,e.appendChild(this.h),this.container.appendChild(e),t.appendChild(this.container),function(t){if(!(t instanceof ShadowRoot)||t.querySelector("style[data-cc-prechat]"))return;const c=document.createElement("style");c.dataset.ccPrechat="",c.textContent=".cc-prechat{flex:1;overflow-y:auto;padding:24px 16px;display:flex;flex-direction:column;gap:16px}.cc-prechat-title{font-size:18px;font-weight:600;color:var(--cc-text)}.cc-prechat-subtitle{font-size:13px;color:var(--cc-text-secondary);margin-top:-8px}.cc-prechat-fields{display:flex;flex-direction:column;gap:14px}.cc-prechat-field{display:flex;flex-direction:column;gap:4px}.cc-prechat-label{font-size:13px;font-weight:500;color:var(--cc-text)}.cc-prechat-label .cc-required{color:var(--cc-danger);margin-inline-start:2px}.cc-prechat-input,.cc-prechat-select,.cc-prechat-textarea{background:var(--cc-bg-input);border:1px solid var(--cc-border);border-radius:8px;padding:8px 12px;color:var(--cc-text);font-family:var(--cc-font);font-size:14px;outline:none;transition:border-color .15s}.cc-prechat-input:focus,.cc-prechat-select:focus,.cc-prechat-textarea:focus{border-color:var(--cc-accent)}.cc-prechat-select{-webkit-appearance:auto;-moz-appearance:auto;appearance:auto}.cc-prechat-textarea{resize:none;line-height:1.5}.cc-prechat-error{font-size:12px;color:var(--cc-danger);min-height:0}.cc-prechat-error:empty{display:none}.cc-prechat-submit{background:var(--cc-accent-contrast);color:var(--cc-on-accent);border:none;border-radius:8px;padding:10px 16px;font-family:var(--cc-font);font-size:14px;font-weight:500;cursor:pointer;transition:background .15s;margin-top:8px}.cc-prechat-submit:hover{background:var(--cc-accent-hover)}.cc-prechat-submit:disabled{opacity:.5;cursor:not-allowed}.cc-prechat-input:focus-visible,.cc-prechat-select:focus-visible,.cc-prechat-textarea:focus-visible,.cc-prechat-submit:focus-visible{outline:2px solid transparent;box-shadow:var(--cc-focus-ring)}@media(max-width:640px){.cc-prechat-input,.cc-prechat-select,.cc-prechat-textarea{font-size:16px}}",t.appendChild(c)}(t.getRootNode()),this.l();const r=this.t.values().next().value;r&&setTimeout(()=>r.focus(),100)}p(t){const c=document.createElement("div");c.className="cc-prechat-field";const e=`cc-prechat-${t.name}`,r=`cc-prechat-${t.name}-error`,i=document.createElement("label");if(i.className="cc-prechat-label",i.htmlFor=e,i.textContent=t.label,t.required){const t=document.createElement("span");t.className="cc-required",t.textContent="*",i.appendChild(t)}let a;if(c.appendChild(i),"select"===t.type){const c=document.createElement("select");c.className="cc-prechat-select";const e=document.createElement("option");e.value="",e.textContent=t.placeholder??this.options.locale.selectPlaceholder.replace("{label}",t.label.toLowerCase()),e.disabled=!0,e.selected=!0,c.appendChild(e);for(const r of t.options??[]){const t=document.createElement("option");t.value=r,t.textContent=r,c.appendChild(t)}a=c}else if("textarea"===t.type){const c=document.createElement("textarea");c.className="cc-prechat-textarea",c.placeholder=t.placeholder??"",c.rows=3,c.maxLength=500,a=c}else{const c=document.createElement("input");c.type=t.type,c.className="cc-prechat-input",c.maxLength=500,c.placeholder=t.placeholder??"",a=c}a.name=t.name,a.id=e,t.required&&a.setAttribute("aria-required","true"),a.addEventListener("input",()=>{this.u(t.name),this.l()}),a instanceof HTMLSelectElement&&a.addEventListener("change",()=>{this.u(t.name),this.l()}),c.appendChild(a),this.t.set(t.name,a);const o=document.createElement("div");return o.className="cc-prechat-error",o.id=r,c.appendChild(o),this.i.set(t.name,o),c}l(){const t=this.options.fields.every(t=>{if(!t.required)return!0;const c=this.t.get(t.name);return!!c&&c.value.trim().length>0});this.h.disabled=!t}o(){const t={};let c=!0;for(const e of this.options.fields){const r=this.t.get(e.name);if(!r)continue;const i=r.value.trim();t[e.name]=i,!e.required||i?"email"===e.type&&i&&!this.m(i)&&(this.v(e.name,this.options.locale.preChatInvalidEmail),c=!1):(this.v(e.name,this.options.locale.preChatRequired),c=!1)}c&&this.options.onSubmit(t)}v(t,c){const e=this.i.get(t);e&&(e.textContent=c);const r=this.t.get(t);r&&e&&(r.setAttribute("aria-invalid","true"),r.setAttribute("aria-describedby",e.id))}u(t){const c=this.i.get(t);c&&(c.textContent="");const e=this.t.get(t);e&&c&&(e.getAttribute("aria-describedby")===c.id&&e.removeAttribute("aria-describedby"),"true"===e.getAttribute("aria-invalid")&&e.removeAttribute("aria-invalid"))}m(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}destroy(){this.container.remove(),this.t.clear(),this.i.clear()}}export{t as PreChatForm};
@@ -0,0 +1 @@
1
+ let e;async function t(t){e??(e=new Promise((e,t)=>{const n=document.createElement("script");n.src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",n.onload=e,n.onerror=t,document.head.append(n)})),await e;const n=document.createElement("div");n.style.cssText="position:fixed;bottom:96px;right:24px;z-index:2147483647",document.body.append(n);try{return await new Promise((e,i)=>{window.turnstile.render(n,{sitekey:t,appearance:"interaction-only",callback:e,"error-callback":i})})}finally{n.remove()}}export{t as turnstileToken};
@@ -1,5 +1,8 @@
1
+ import type { KeyStore } from '../storage.js';
1
2
  export interface BubbleOptions {
2
3
  text: string;
4
+ /** Where "already shown" is remembered, with the widget's persistence. */
5
+ store: KeyStore;
3
6
  delay?: number;
4
7
  showOnce?: boolean;
5
8
  position: 'bottom-right' | 'bottom-left';
@@ -1 +1 @@
1
- {"version":3,"file":"bubble.d.ts","sourceRoot":"","sources":["../../src/dom/bubble.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,EAAE,cAAc,GAAG,aAAa,CAAC;IACzC,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAID,qBAAa,aAAa;IACxB,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,OAAO,CAA8C;gBAEjD,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,aAAa;IA2CpD,IAAI,IAAI,IAAI;IASZ,OAAO,CAAC,SAAS;IAMjB,OAAO,IAAI,IAAI;CAIhB"}
1
+ {"version":3,"file":"bubble.d.ts","sourceRoot":"","sources":["../../src/dom/bubble.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,0EAA0E;IAC1E,KAAK,EAAE,QAAQ,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,EAAE,cAAc,GAAG,aAAa,CAAC;IACzC,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAID,qBAAa,aAAa;IACxB,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,OAAO,CAA8C;gBAEjD,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,aAAa;IA2CpD,IAAI,IAAI,IAAI;IASZ,OAAO,CAAC,SAAS;IAMjB,OAAO,IAAI,IAAI;CAIhB"}
package/dist/dom/fab.d.ts CHANGED
@@ -2,6 +2,7 @@ export interface FABOptions {
2
2
  position: 'bottom-right' | 'bottom-left';
3
3
  openLabel: string;
4
4
  closeLabel: string;
5
+ unreadLabel: string;
5
6
  onClick: () => void;
6
7
  }
7
8
  export declare class FAB {
@@ -9,10 +10,12 @@ export declare class FAB {
9
10
  private badge;
10
11
  private openLabel;
11
12
  private closeLabel;
13
+ private unreadLabel;
12
14
  constructor(root: ShadowRoot, options: FABOptions);
13
15
  setOpen(open: boolean): void;
16
+ setLabels(openLabel: string, closeLabel: string, unreadLabel: string): void;
14
17
  focus(): void;
15
- showBadge(): void;
18
+ showBadge(count?: number): void;
16
19
  hideBadge(): void;
17
20
  destroy(): void;
18
21
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fab.d.ts","sourceRoot":"","sources":["../../src/dom/fab.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,cAAc,GAAG,aAAa,CAAC;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED,qBAAa,GAAG;IACd,OAAO,CAAC,EAAE,CAAoB;IAC9B,OAAO,CAAC,KAAK,CAAiB;IAC9B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,UAAU,CAAS;gBAEf,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU;IA0BjD,OAAO,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IAQ5B,KAAK,IAAI,IAAI;IAIb,SAAS,IAAI,IAAI;IAIjB,SAAS,IAAI,IAAI;IAIjB,OAAO,IAAI,IAAI;CAGhB"}
1
+ {"version":3,"file":"fab.d.ts","sourceRoot":"","sources":["../../src/dom/fab.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,cAAc,GAAG,aAAa,CAAC;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED,qBAAa,GAAG;IACd,OAAO,CAAC,EAAE,CAAoB;IAC9B,OAAO,CAAC,KAAK,CAAiB;IAC9B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,WAAW,CAAS;gBAEhB,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU;IA2BjD,OAAO,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IAS5B,SAAS,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI;IAW3E,KAAK,IAAI,IAAI;IAIb,SAAS,CAAC,KAAK,SAAI,GAAG,IAAI;IAc1B,SAAS,IAAI,IAAI;IAQjB,OAAO,IAAI,IAAI;CAGhB"}
@@ -0,0 +1,4 @@
1
+ /** Launcher icons, shared by the loader and the full widget. */
2
+ export declare const CHAT_ICON = "<svg viewBox=\"0 0 24 24\"><path d=\"M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z\"/><path d=\"M7 9h10v2H7zm0-3h10v2H7z\"/></svg>";
3
+ export declare const CLOSE_ICON = "<svg viewBox=\"0 0 24 24\"><path d=\"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z\"/></svg>";
4
+ //# sourceMappingURL=icons.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"icons.d.ts","sourceRoot":"","sources":["../../src/dom/icons.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAChE,eAAO,MAAM,SAAS,uLAAiL,CAAC;AACxM,eAAO,MAAM,UAAU,iKAA6J,CAAC"}
@@ -9,6 +9,7 @@ export declare class Input {
9
9
  private sendBtn;
10
10
  private onSend;
11
11
  constructor(parent: HTMLElement, options: InputOptions);
12
+ setLabels(placeholder: string, sendLabel: string): void;
12
13
  focus(): void;
13
14
  setDisabled(disabled: boolean): void;
14
15
  clear(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"input.d.ts","sourceRoot":"","sources":["../../src/dom/input.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,YAAY;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAChC;AAED,qBAAa,KAAK;IAChB,OAAO,CAAC,IAAI,CAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,MAAM,CAAyB;gBAE3B,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,YAAY;IA+BtD,KAAK,IAAI,IAAI;IAIb,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI;IAKpC,KAAK,IAAI,IAAI;IAMb,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAIlC,OAAO,CAAC,IAAI;IAOZ,OAAO,CAAC,aAAa;IAUrB,OAAO,CAAC,UAAU;CAKnB"}
1
+ {"version":3,"file":"input.d.ts","sourceRoot":"","sources":["../../src/dom/input.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,YAAY;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAChC;AAED,qBAAa,KAAK;IAChB,OAAO,CAAC,IAAI,CAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,OAAO,CAAoB;IACnC,OAAO,CAAC,MAAM,CAAyB;gBAE3B,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,YAAY;IA+BtD,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI;IAMvD,KAAK,IAAI,IAAI;IAIb,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI;IAKpC,KAAK,IAAI,IAAI;IAMb,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAIlC,OAAO,CAAC,IAAI;IAOZ,OAAO,CAAC,aAAa;IAUrB,OAAO,CAAC,UAAU;CAKnB"}