@chatcops/widget 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chatcops.esm.js +11 -3
- package/dist/chatcops.min.js +1 -1
- package/dist/markdown.d.ts.map +1 -1
- package/package.json +4 -4
package/dist/chatcops.esm.js
CHANGED
|
@@ -89,9 +89,17 @@ function renderMarkdown(input) {
|
|
|
89
89
|
/\[([^\]]+)\]\(((?:[^()]*|\([^()]*\))*)\)/g,
|
|
90
90
|
(_match, text, href) => isSafeHref(href) ? `<a href="${href}" target="_blank" rel="noopener noreferrer">${text}</a>` : text
|
|
91
91
|
);
|
|
92
|
-
html = html.replace(/^- (.+)$/gm,
|
|
93
|
-
html = html.replace(
|
|
94
|
-
html = html.replace(
|
|
92
|
+
html = html.replace(/^- (.+)$/gm, '<li data-md="ul">$1</li>');
|
|
93
|
+
html = html.replace(/^\d+\. (.+)$/gm, '<li data-md="ol">$1</li>');
|
|
94
|
+
html = html.replace(
|
|
95
|
+
/(?:<li data-md="ul">.*?<\/li>\n?)+|(?:<li data-md="ol">.*?<\/li>\n?)+/g,
|
|
96
|
+
(run) => {
|
|
97
|
+
const ordered = run.includes('data-md="ol"');
|
|
98
|
+
const tag = ordered ? "ol" : "ul";
|
|
99
|
+
const items = run.replace(/ data-md="(?:ul|ol)"/g, "").replace(/\n/g, "");
|
|
100
|
+
return `<${tag}>${items}</${tag}>`;
|
|
101
|
+
}
|
|
102
|
+
);
|
|
95
103
|
html = html.replace(/\n\n/g, "<br><br>");
|
|
96
104
|
html = html.replace(/\n/g, "<br>");
|
|
97
105
|
return html;
|
package/dist/chatcops.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ChatCops=function(e){"use strict";var t=Object.defineProperty,s=(e,s,a)=>((e,s,a)=>s in e?t(e,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[s]=a)(e,"symbol"!=typeof s?s+"":s,a);function a(e){const t=document.createElement("div");t.id="chatcops-root",e?e.appendChild(t):document.body.appendChild(t);const s=t.attachShadow({mode:"open"}),a=document.createElement("style");return a.textContent=":host{--cc-accent: #6366f1;--cc-accent-hover: #4f46e5;--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 ease,box-shadow .2s ease;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-text);transition:transform .3s ease}.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 ease,transform .2s ease}.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;opacity:1;transform:none;pointer-events:auto;transition:none}.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-text)}.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 ease}.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);color:var(--cc-text);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-text)}.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-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 ease,color .15s ease,opacity .15s ease}.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-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 ease}.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 ease,opacity .15s ease}.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-text)}.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 ease,transform .3s ease;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-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 ease}.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);color:var(--cc-text);border:none;border-radius:8px;padding:10px 16px;font-family:var(--cc-font);font-size:14px;font-weight:500;cursor:pointer;transition:background .15s ease;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-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}}",s.appendChild(a),s}const i='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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 n{constructor(e,t){s(this,"el"),s(this,"badge"),s(this,"isOpen",!1),this.el=document.createElement("button"),this.el.className="cc-fab cc-pulse",this.el.setAttribute("aria-label","Open chat"),"bottom-left"===t.position&&this.el.classList.add("cc-left"),this.el.innerHTML=i,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.isOpen=e,this.el.innerHTML=e?'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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>':i,e||this.el.appendChild(this.badge),this.el.classList.toggle("cc-open",e),this.el.setAttribute("aria-label",e?"Close chat":"Open chat")}showBadge(){this.badge.classList.add("cc-visible")}hideBadge(){this.badge.classList.remove("cc-visible")}destroy(){this.el.remove()}}const r={"&":"&","<":"<",">":">",'"':""","'":"'"};const o=new Set(["http","https","mailto","tel"]);function c(e){let t=e.replace(/[&<>"']/g,e=>r[e]??e);return t=t.replace(/```(?:\w*)\n?([\s\S]*?)```/g,(e,t)=>`<pre><code>${t.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/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||o.has(s[1].toLowerCase())}(s)?`<a href="${s}" target="_blank" rel="noopener noreferrer">${t}</a>`:t),t=t.replace(/^- (.+)$/gm,"<li>$1</li>"),t=t.replace(/(<li>.*<\/li>\n?)+/g,e=>`<ul>${e}</ul>`),t=t.replace(/^\d+\. (.+)$/gm,"<li>$1</li>"),t=t.replace(/\n\n/g,"<br><br>"),t=t.replace(/\n/g,"<br>"),t}class l{constructor(e,t){s(this,"container"),s(this,"typingEl",null),s(this,"actions"),this.actions=t,this.container=document.createElement("div"),this.container.className="cc-messages",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.container.querySelector(`[data-id="${e.id}"]`);t&&(this.renderMessageElement(t,e),this.scrollToBottom())}showTyping(){this.typingEl||(this.typingEl=document.createElement("div"),this.typingEl.className="cc-typing",this.typingEl.innerHTML='<div class="cc-typing-dot"></div><div class="cc-typing-dot"></div><div class="cc-typing-dot"></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.container.querySelector(`[data-id="${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.container.querySelector(`[data-id="${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)}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,t.status?e.dataset.status=t.status:delete e.dataset.status,t.errorType?e.dataset.errorType=t.errorType:delete e.dataset.errorType,e.innerHTML="";const s=document.createElement("div");s.className="cc-message-content",s.innerHTML="assistant"===t.role?c(t.content):this.escapeHtml(t.content),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 d{constructor(e,t){s(this,"area"),s(this,"textarea"),s(this,"sendBtn"),s(this,"onSend"),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.rows=1,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","Send message"),this.sendBtn.innerHTML='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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){"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"}}class h{constructor(e,t){s(this,"el"),s(this,"inline"),s(this,"messages"),s(this,"input"),s(this,"messagesContainer"),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");const a=document.createElement("div");if(a.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,a.appendChild(e)}else{const e=document.createElement("div");e.className="cc-header-avatar-placeholder",e.innerHTML='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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>',a.appendChild(e)}const i=document.createElement("div");if(i.className="cc-header-info",i.innerHTML=`<div class="cc-header-name">${this.escapeHtml(t.branding.name)}</div><div class="cc-header-subtitle">${this.escapeHtml(t.branding.subtitle)}</div>`,a.appendChild(i),!t.inline){const e=document.createElement("button");e.className="cc-header-close",e.setAttribute("aria-label","Close chat"),e.innerHTML='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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),a.appendChild(e)}this.el.appendChild(a),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 l(this.messagesContainer,t.messageActions),this.input=new d(this.el,{placeholder:t.placeholder,onSend:t.onSend});const n=document.createElement("div");n.className="cc-footer",n.innerHTML=t.footerText,this.el.appendChild(n),e.appendChild(this.el)}show(){this.el.classList.add("cc-visible"),this.inline||this.input.focus()}hide(){this.el.classList.remove("cc-visible")}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()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const p="chatcops_bubble_shown";class u{constructor(e,t){s(this,"el"),s(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;const a=document.createElement("button");if(a.className="cc-bubble-close",a.innerHTML="×",a.addEventListener("click",e=>{e.stopPropagation(),this.hide()}),this.el.appendChild(a),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")},t.delay??3e3)}hide(){this.el.classList.remove("cc-visible"),this.timerId&&(clearTimeout(this.timerId),this.timerId=null)}destroy(){this.hide(),this.el.remove()}}class g{constructor(e){s(this,"apiUrl"),s(this,"timeout"),this.apiUrl=e.apiUrl,this.timeout=e.timeout??3e4}async*sendMessage(e){var t;const s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout);try{const a=await fetch(this.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:s.signal});if(!a.ok)return 429===a.status?void(yield{error:"rate_limit"}):void(yield{error:`HTTP ${a.status}`});const i=null==(t=a.body)?void 0:t.getReader();if(!i)return void(yield{error:"No response body"});const n=new TextDecoder;let r="";for(;;){const{done:e,value:t}=await i.read();if(e)break;r+=n.decode(t,{stream:!0});const s=r.split("\n");r=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 void(yield{done:!0});try{yield JSON.parse(t)}catch{}}}yield{done:!0}}catch(i){i instanceof DOMException&&"AbortError"===i.name?yield{error:"timeout"}:yield{error:"network"}}finally{clearTimeout(a)}}}const m="chatcops_conversation";class b{constructor(e){s(this,"key"),this.key=e?`${m}_${e}`:m}load(){try{const e=localStorage.getItem(this.key);return e?JSON.parse(e):null}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(){const e="chatcops_session_id";try{let t=sessionStorage.getItem(e);return t||(t=crypto.randomUUID(),sessionStorage.setItem(e,t)),t}catch{return crypto.randomUUID()}}isPreChatCompleted(e){try{return"true"===sessionStorage.getItem(`chatcops-prechat-${e}`)}catch{return!1}}setPreChatCompleted(e){try{sessionStorage.setItem(`chatcops-prechat-${e}`,"true")}catch{}}}function f(e,t){const s=e.host;t.accent&&(s.style.setProperty("--cc-accent",t.accent),s.style.setProperty("--cc-accent-hover",function(e,t){const[s,a,i]=v(e),n=1-t/100;return x(Math.round(s*n),Math.round(a*n),Math.round(i*n))}(t.accent,10))),t.textColor&&s.style.setProperty("--cc-text",t.textColor),t.bgColor&&(s.style.setProperty("--cc-bg",t.bgColor),s.style.setProperty("--cc-bg-surface",y(t.bgColor,8)),s.style.setProperty("--cc-bg-input",y(t.bgColor,14))),t.fontFamily&&s.style.setProperty("--cc-font",t.fontFamily),t.borderRadius&&s.style.setProperty("--cc-radius",t.borderRadius)}function v(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 x(e,t,s){return"#"+[e,t,s].map(e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")).join("")}function y(e,t){const[s,a,i]=v(e),n=t/100;return x(Math.round(s+(255-s)*n),Math.round(a+(255-a)*n),Math.round(i+(255-i)*n))}const w={welcomeMessage:"Hi! How can I help you today?",inputPlaceholder:"Type a message...",sendButton:"Send",closeButton:"Close",errorGeneric:"Something went wrong. Please try again.",errorNetwork:"Connection error. Please check your network.",errorRateLimit:"Too many messages. Please wait a moment.",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"},C={en:w};class E{constructor(e,t){if(s(this,"container"),s(this,"fieldElements",new Map),s(this,"errorElements",new Map),s(this,"submitBtn"),s(this,"options"),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 a=document.createElement("form");a.className="cc-prechat-fields",a.addEventListener("submit",e=>{e.preventDefault(),this.handleSubmit()});for(const s of t.fields)a.appendChild(this.createField(s));this.submitBtn=document.createElement("button"),this.submitBtn.type="submit",this.submitBtn.className="cc-prechat-submit",this.submitBtn.textContent=t.submitLabel,a.appendChild(this.submitBtn),this.container.appendChild(a),e.appendChild(this.container),this.updateSubmitState();const i=this.fieldElements.values().next().value;i&&setTimeout(()=>i.focus(),100)}createField(e){const t=document.createElement("div");t.className="cc-prechat-field";const s=document.createElement("label");if(s.className="cc-prechat-label",s.textContent=e.label,e.required){const e=document.createElement("span");e.className="cc-required",e.textContent="*",s.appendChild(e)}let a;if(t.appendChild(s),"select"===e.type){const t=document.createElement("select");t.className="cc-prechat-select";const s=document.createElement("option");s.value="",s.textContent=e.placeholder??`Select ${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)}a=t}else if("textarea"===e.type){const t=document.createElement("textarea");t.className="cc-prechat-textarea",t.placeholder=e.placeholder??"",t.rows=3,a=t}else{const t=document.createElement("input");t.type=e.type,t.className="cc-prechat-input",t.placeholder=e.placeholder??"",a=t}a.name=e.name,a.addEventListener("input",()=>{this.clearError(e.name),this.updateSubmitState()}),a instanceof HTMLSelectElement&&a.addEventListener("change",()=>{this.clearError(e.name),this.updateSubmitState()}),t.appendChild(a),this.fieldElements.set(e.name,a);const i=document.createElement("div");return i.className="cc-prechat-error",t.appendChild(i),this.errorElements.set(e.name,i),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)}clearError(e){const t=this.errorElements.get(e);t&&(t.textContent="")}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}destroy(){this.container.remove(),this.fieldElements.clear(),this.errorElements.clear()}}class M{constructor(e){s(this,"config"),s(this,"shadow"),s(this,"fab"),s(this,"panel"),s(this,"bubble"),s(this,"preChatFormEl"),s(this,"client"),s(this,"storage"),s(this,"locale"),s(this,"conversationId"),s(this,"messages",[]),s(this,"userData"),s(this,"userDataSent",!1),s(this,"isStreaming",!1),s(this,"retryRequests",new Map),s(this,"eventHandlers",new Map),s(this,"containerEl"),this.config=e,this.client=new g({apiUrl:e.apiUrl}),this.storage=new b,this.locale=function(e,t){const s=C[e]??w;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,s,i,r,o;this.isInline?(this.containerEl=this.resolveContainer(),this.shadow=a(this.containerEl)):this.shadow=a(),this.config.theme&&f(this.shadow,this.config.theme);const c=(null==(e=this.config.theme)?void 0:e.position)??"bottom-right";if(this.isInline||(this.fab=new n(this.shadow,{position:c,onClick:()=>this.toggle()})),this.panel=new h(this.shadow,{position:c,inline:this.isInline,preChatEnabled:(null==(t=this.config.preChatForm)?void 0:t.enabled)??!1,branding:{name:(null==(s=this.config.branding)?void 0:s.name)??"AI Assistant",avatar:null==(i=this.config.branding)?void 0:i.avatar,subtitle:(null==(r=this.config.branding)?void 0:r.subtitle)??"Online"},placeholder:this.config.placeholder??this.locale.inputPlaceholder,footerText:this.locale.poweredBy,messageActions:{onRetry:e=>{this.handleRetry(e)},onRegenerate:e=>{this.handleRegenerate(e)},retryLabel:this.locale.retryButton,regenerateLabel:this.locale.regenerateButton},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==(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,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;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;this.panel.hide(),this.isInline||null==(e=this.fab)||e.setOpen(!1),null==(s=(t=this.config).onClose)||s.call(t),this.emit("close")}toggle(){this.panel.isVisible?this.close():this.open()}destroy(){var e,t,s;null==(e=this.preChatFormEl)||e.destroy(),null==(t=this.bubble)||t.destroy(),this.panel.destroy(),null==(s=this.fab)||s.destroy(),function(e){const t=(e??document.body).querySelector("#chatcops-root")??document.getElementById("chatcops-root");t&&t.remove()}(this.containerEl),this.eventHandlers.clear(),this.messages=[]}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t)}off(e,t){var s;null==(s=this.eventHandlers.get(e))||s.delete(t)}emit(e,...t){var s;null==(s=this.eventHandlers.get(e))||s.forEach(e=>e(...t))}isPreChatCompleted(){return this.storage.isPreChatCompleted(this.conversationId)}setPreChatCompleted(){this.storage.setPreChatCompleted(this.conversationId)}showPreChatForm(){const e=this.config.preChatForm;this.panel.hideMessages(),this.panel.input.setVisible(!1),this.preChatFormEl=new E(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;this.userData=e,this.setPreChatCompleted(),null==(t=this.preChatFormEl)||t.destroy(),this.preChatFormEl=void 0,this.panel.showMessages(),this.panel.input.setVisible(!0),this.showChatView(),null==(a=(s=this.config).onPreChatSubmit)||a.call(s,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={id:"welcome",role:"assistant",content:t?`Hi ${t}! ${this.config.welcomeMessage??this.locale.welcomeMessage}`:this.config.welcomeMessage??this.locale.welcomeMessage};this.messages.push(s),this.panel.addMessage(s)}}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:!0,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"},p=!(!this.userData||this.userDataSent);let u=!0,g=!1,m=!1;try{for await(const r of this.client.sendMessage(this.createRequest(e,t,p))){if(r.error){const e=this.resolveErrorType(r.error);h.content=this.getErrorMessage(e),h.status="error",h.errorType=e,m=!0,this.retryRequests.set(h.id,{regenerate:t.regenerate,userMessageId:t.userMessageId}),this.panel.messages.removeTyping(),u?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){g=!0;break}r.leadCaptured&&(null==(n=(i=this.config).onLeadCaptured)||n.call(i,r.leadData),this.emit("leadCaptured",r.leadData)),r.content&&(u&&(this.panel.messages.removeTyping(),this.panel.addMessage(h),u=!1),h.content+=r.content,this.panel.messages.updateMessage(h))}m||g||(g=!0),!m&&u&&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){h.content=this.locale.errorGeneric,h.status="error",h.errorType="network",this.retryRequests.set(h.id,{regenerate:t.regenerate,userMessageId:t.userMessageId}),this.panel.messages.removeTyping(),this.panel.addMessage(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{p&&g&&(this.userDataSent=!0),this.isStreaming=!1,this.panel.input.setDisabled(!1),this.panel.input.focus(),this.saveHistory()}}createRequest(e,t,s){const a=!1!==this.config.pageContext?{url:window.location.href,title:document.title}:void 0;return{conversationId:this.conversationId,message:e,messageId:t.userMessageId,regenerate:t.regenerate,pageContext:a,locale:this.config.locale,...s?{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){switch(e){case"rate_limit":case"network":case"provider_error":case"timeout":return e;default:return"provider_error"}}getErrorMessage(e){switch(e){case"rate_limit":return this.locale.errorRateLimit;case"network":case"timeout":return this.locale.errorNetwork;default:return this.locale.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 S=null;const k={init:e=>(S&&S.destroy(),S=new M(e),S.init(),S),open(){null==S||S.open()},close(){null==S||S.close()},destroy(){null==S||S.destroy(),S=null},on(e,t){null==S||S.on(e,t)},off(e,t){null==S||S.off(e,t)}};function L(){const e=document.currentScript;if(!e)return;const t=e.dataset.apiUrl;if(!t)return;const s=e.dataset.mode,a=e.dataset.container;k.init({apiUrl:t,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:void 0!==e.dataset.autoOpen?""===e.dataset.autoOpen||"true"===e.dataset.autoOpen||(parseInt(e.dataset.autoOpen,10)||!0):void 0,placeholder:e.dataset.placeholder,locale:e.dataset.locale})}const B=document.currentScript;return B&&B.dataset.apiUrl&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",L):L()),"undefined"!=typeof window&&(window.ChatCops=k),e.Widget=M,e.default=k,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
|
|
1
|
+
var ChatCops=function(e){"use strict";var t=Object.defineProperty,s=(e,s,a)=>((e,s,a)=>s in e?t(e,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[s]=a)(e,"symbol"!=typeof s?s+"":s,a);function a(e){const t=document.createElement("div");t.id="chatcops-root",e?e.appendChild(t):document.body.appendChild(t);const s=t.attachShadow({mode:"open"}),a=document.createElement("style");return a.textContent=":host{--cc-accent: #6366f1;--cc-accent-hover: #4f46e5;--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 ease,box-shadow .2s ease;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-text);transition:transform .3s ease}.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 ease,transform .2s ease}.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;opacity:1;transform:none;pointer-events:auto;transition:none}.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-text)}.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 ease}.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);color:var(--cc-text);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-text)}.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-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 ease,color .15s ease,opacity .15s ease}.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-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 ease}.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 ease,opacity .15s ease}.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-text)}.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 ease,transform .3s ease;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-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 ease}.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);color:var(--cc-text);border:none;border-radius:8px;padding:10px 16px;font-family:var(--cc-font);font-size:14px;font-weight:500;cursor:pointer;transition:background .15s ease;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-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}}",s.appendChild(a),s}const i='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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 n{constructor(e,t){s(this,"el"),s(this,"badge"),s(this,"isOpen",!1),this.el=document.createElement("button"),this.el.className="cc-fab cc-pulse",this.el.setAttribute("aria-label","Open chat"),"bottom-left"===t.position&&this.el.classList.add("cc-left"),this.el.innerHTML=i,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.isOpen=e,this.el.innerHTML=e?'<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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>':i,e||this.el.appendChild(this.badge),this.el.classList.toggle("cc-open",e),this.el.setAttribute("aria-label",e?"Close chat":"Open chat")}showBadge(){this.badge.classList.add("cc-visible")}hideBadge(){this.badge.classList.remove("cc-visible")}destroy(){this.el.remove()}}const r={"&":"&","<":"<",">":">",'"':""","'":"'"};const o=new Set(["http","https","mailto","tel"]);function c(e){let t=e.replace(/[&<>"']/g,e=>r[e]??e);return t=t.replace(/```(?:\w*)\n?([\s\S]*?)```/g,(e,t)=>`<pre><code>${t.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/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||o.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(/\n\n/g,"<br><br>"),t=t.replace(/\n/g,"<br>"),t}class l{constructor(e,t){s(this,"container"),s(this,"typingEl",null),s(this,"actions"),this.actions=t,this.container=document.createElement("div"),this.container.className="cc-messages",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.container.querySelector(`[data-id="${e.id}"]`);t&&(this.renderMessageElement(t,e),this.scrollToBottom())}showTyping(){this.typingEl||(this.typingEl=document.createElement("div"),this.typingEl.className="cc-typing",this.typingEl.innerHTML='<div class="cc-typing-dot"></div><div class="cc-typing-dot"></div><div class="cc-typing-dot"></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.container.querySelector(`[data-id="${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.container.querySelector(`[data-id="${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)}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,t.status?e.dataset.status=t.status:delete e.dataset.status,t.errorType?e.dataset.errorType=t.errorType:delete e.dataset.errorType,e.innerHTML="";const s=document.createElement("div");s.className="cc-message-content",s.innerHTML="assistant"===t.role?c(t.content):this.escapeHtml(t.content),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 d{constructor(e,t){s(this,"area"),s(this,"textarea"),s(this,"sendBtn"),s(this,"onSend"),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.rows=1,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","Send message"),this.sendBtn.innerHTML='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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){"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"}}class h{constructor(e,t){s(this,"el"),s(this,"inline"),s(this,"messages"),s(this,"input"),s(this,"messagesContainer"),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");const a=document.createElement("div");if(a.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,a.appendChild(e)}else{const e=document.createElement("div");e.className="cc-header-avatar-placeholder",e.innerHTML='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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>',a.appendChild(e)}const i=document.createElement("div");if(i.className="cc-header-info",i.innerHTML=`<div class="cc-header-name">${this.escapeHtml(t.branding.name)}</div><div class="cc-header-subtitle">${this.escapeHtml(t.branding.subtitle)}</div>`,a.appendChild(i),!t.inline){const e=document.createElement("button");e.className="cc-header-close",e.setAttribute("aria-label","Close chat"),e.innerHTML='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><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),a.appendChild(e)}this.el.appendChild(a),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 l(this.messagesContainer,t.messageActions),this.input=new d(this.el,{placeholder:t.placeholder,onSend:t.onSend});const n=document.createElement("div");n.className="cc-footer",n.innerHTML=t.footerText,this.el.appendChild(n),e.appendChild(this.el)}show(){this.el.classList.add("cc-visible"),this.inline||this.input.focus()}hide(){this.el.classList.remove("cc-visible")}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()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const p="chatcops_bubble_shown";class u{constructor(e,t){s(this,"el"),s(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;const a=document.createElement("button");if(a.className="cc-bubble-close",a.innerHTML="×",a.addEventListener("click",e=>{e.stopPropagation(),this.hide()}),this.el.appendChild(a),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")},t.delay??3e3)}hide(){this.el.classList.remove("cc-visible"),this.timerId&&(clearTimeout(this.timerId),this.timerId=null)}destroy(){this.hide(),this.el.remove()}}class m{constructor(e){s(this,"apiUrl"),s(this,"timeout"),this.apiUrl=e.apiUrl,this.timeout=e.timeout??3e4}async*sendMessage(e){var t;const s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout);try{const a=await fetch(this.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:s.signal});if(!a.ok)return 429===a.status?void(yield{error:"rate_limit"}):void(yield{error:`HTTP ${a.status}`});const i=null==(t=a.body)?void 0:t.getReader();if(!i)return void(yield{error:"No response body"});const n=new TextDecoder;let r="";for(;;){const{done:e,value:t}=await i.read();if(e)break;r+=n.decode(t,{stream:!0});const s=r.split("\n");r=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 void(yield{done:!0});try{yield JSON.parse(t)}catch{}}}yield{done:!0}}catch(i){i instanceof DOMException&&"AbortError"===i.name?yield{error:"timeout"}:yield{error:"network"}}finally{clearTimeout(a)}}}const g="chatcops_conversation";class b{constructor(e){s(this,"key"),this.key=e?`${g}_${e}`:g}load(){try{const e=localStorage.getItem(this.key);return e?JSON.parse(e):null}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(){const e="chatcops_session_id";try{let t=sessionStorage.getItem(e);return t||(t=crypto.randomUUID(),sessionStorage.setItem(e,t)),t}catch{return crypto.randomUUID()}}isPreChatCompleted(e){try{return"true"===sessionStorage.getItem(`chatcops-prechat-${e}`)}catch{return!1}}setPreChatCompleted(e){try{sessionStorage.setItem(`chatcops-prechat-${e}`,"true")}catch{}}}function f(e,t){const s=e.host;t.accent&&(s.style.setProperty("--cc-accent",t.accent),s.style.setProperty("--cc-accent-hover",function(e,t){const[s,a,i]=v(e),n=1-t/100;return x(Math.round(s*n),Math.round(a*n),Math.round(i*n))}(t.accent,10))),t.textColor&&s.style.setProperty("--cc-text",t.textColor),t.bgColor&&(s.style.setProperty("--cc-bg",t.bgColor),s.style.setProperty("--cc-bg-surface",y(t.bgColor,8)),s.style.setProperty("--cc-bg-input",y(t.bgColor,14))),t.fontFamily&&s.style.setProperty("--cc-font",t.fontFamily),t.borderRadius&&s.style.setProperty("--cc-radius",t.borderRadius)}function v(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 x(e,t,s){return"#"+[e,t,s].map(e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")).join("")}function y(e,t){const[s,a,i]=v(e),n=t/100;return x(Math.round(s+(255-s)*n),Math.round(a+(255-a)*n),Math.round(i+(255-i)*n))}const w={welcomeMessage:"Hi! How can I help you today?",inputPlaceholder:"Type a message...",sendButton:"Send",closeButton:"Close",errorGeneric:"Something went wrong. Please try again.",errorNetwork:"Connection error. Please check your network.",errorRateLimit:"Too many messages. Please wait a moment.",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"},C={en:w};class E{constructor(e,t){if(s(this,"container"),s(this,"fieldElements",new Map),s(this,"errorElements",new Map),s(this,"submitBtn"),s(this,"options"),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 a=document.createElement("form");a.className="cc-prechat-fields",a.addEventListener("submit",e=>{e.preventDefault(),this.handleSubmit()});for(const s of t.fields)a.appendChild(this.createField(s));this.submitBtn=document.createElement("button"),this.submitBtn.type="submit",this.submitBtn.className="cc-prechat-submit",this.submitBtn.textContent=t.submitLabel,a.appendChild(this.submitBtn),this.container.appendChild(a),e.appendChild(this.container),this.updateSubmitState();const i=this.fieldElements.values().next().value;i&&setTimeout(()=>i.focus(),100)}createField(e){const t=document.createElement("div");t.className="cc-prechat-field";const s=document.createElement("label");if(s.className="cc-prechat-label",s.textContent=e.label,e.required){const e=document.createElement("span");e.className="cc-required",e.textContent="*",s.appendChild(e)}let a;if(t.appendChild(s),"select"===e.type){const t=document.createElement("select");t.className="cc-prechat-select";const s=document.createElement("option");s.value="",s.textContent=e.placeholder??`Select ${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)}a=t}else if("textarea"===e.type){const t=document.createElement("textarea");t.className="cc-prechat-textarea",t.placeholder=e.placeholder??"",t.rows=3,a=t}else{const t=document.createElement("input");t.type=e.type,t.className="cc-prechat-input",t.placeholder=e.placeholder??"",a=t}a.name=e.name,a.addEventListener("input",()=>{this.clearError(e.name),this.updateSubmitState()}),a instanceof HTMLSelectElement&&a.addEventListener("change",()=>{this.clearError(e.name),this.updateSubmitState()}),t.appendChild(a),this.fieldElements.set(e.name,a);const i=document.createElement("div");return i.className="cc-prechat-error",t.appendChild(i),this.errorElements.set(e.name,i),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)}clearError(e){const t=this.errorElements.get(e);t&&(t.textContent="")}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}destroy(){this.container.remove(),this.fieldElements.clear(),this.errorElements.clear()}}class M{constructor(e){s(this,"config"),s(this,"shadow"),s(this,"fab"),s(this,"panel"),s(this,"bubble"),s(this,"preChatFormEl"),s(this,"client"),s(this,"storage"),s(this,"locale"),s(this,"conversationId"),s(this,"messages",[]),s(this,"userData"),s(this,"userDataSent",!1),s(this,"isStreaming",!1),s(this,"retryRequests",new Map),s(this,"eventHandlers",new Map),s(this,"containerEl"),this.config=e,this.client=new m({apiUrl:e.apiUrl}),this.storage=new b,this.locale=function(e,t){const s=C[e]??w;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,s,i,r,o;this.isInline?(this.containerEl=this.resolveContainer(),this.shadow=a(this.containerEl)):this.shadow=a(),this.config.theme&&f(this.shadow,this.config.theme);const c=(null==(e=this.config.theme)?void 0:e.position)??"bottom-right";if(this.isInline||(this.fab=new n(this.shadow,{position:c,onClick:()=>this.toggle()})),this.panel=new h(this.shadow,{position:c,inline:this.isInline,preChatEnabled:(null==(t=this.config.preChatForm)?void 0:t.enabled)??!1,branding:{name:(null==(s=this.config.branding)?void 0:s.name)??"AI Assistant",avatar:null==(i=this.config.branding)?void 0:i.avatar,subtitle:(null==(r=this.config.branding)?void 0:r.subtitle)??"Online"},placeholder:this.config.placeholder??this.locale.inputPlaceholder,footerText:this.locale.poweredBy,messageActions:{onRetry:e=>{this.handleRetry(e)},onRegenerate:e=>{this.handleRegenerate(e)},retryLabel:this.locale.retryButton,regenerateLabel:this.locale.regenerateButton},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==(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,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;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;this.panel.hide(),this.isInline||null==(e=this.fab)||e.setOpen(!1),null==(s=(t=this.config).onClose)||s.call(t),this.emit("close")}toggle(){this.panel.isVisible?this.close():this.open()}destroy(){var e,t,s;null==(e=this.preChatFormEl)||e.destroy(),null==(t=this.bubble)||t.destroy(),this.panel.destroy(),null==(s=this.fab)||s.destroy(),function(e){const t=(e??document.body).querySelector("#chatcops-root")??document.getElementById("chatcops-root");t&&t.remove()}(this.containerEl),this.eventHandlers.clear(),this.messages=[]}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t)}off(e,t){var s;null==(s=this.eventHandlers.get(e))||s.delete(t)}emit(e,...t){var s;null==(s=this.eventHandlers.get(e))||s.forEach(e=>e(...t))}isPreChatCompleted(){return this.storage.isPreChatCompleted(this.conversationId)}setPreChatCompleted(){this.storage.setPreChatCompleted(this.conversationId)}showPreChatForm(){const e=this.config.preChatForm;this.panel.hideMessages(),this.panel.input.setVisible(!1),this.preChatFormEl=new E(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;this.userData=e,this.setPreChatCompleted(),null==(t=this.preChatFormEl)||t.destroy(),this.preChatFormEl=void 0,this.panel.showMessages(),this.panel.input.setVisible(!0),this.showChatView(),null==(a=(s=this.config).onPreChatSubmit)||a.call(s,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={id:"welcome",role:"assistant",content:t?`Hi ${t}! ${this.config.welcomeMessage??this.locale.welcomeMessage}`:this.config.welcomeMessage??this.locale.welcomeMessage};this.messages.push(s),this.panel.addMessage(s)}}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:!0,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"},p=!(!this.userData||this.userDataSent);let u=!0,m=!1,g=!1;try{for await(const r of this.client.sendMessage(this.createRequest(e,t,p))){if(r.error){const e=this.resolveErrorType(r.error);h.content=this.getErrorMessage(e),h.status="error",h.errorType=e,g=!0,this.retryRequests.set(h.id,{regenerate:t.regenerate,userMessageId:t.userMessageId}),this.panel.messages.removeTyping(),u?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){m=!0;break}r.leadCaptured&&(null==(n=(i=this.config).onLeadCaptured)||n.call(i,r.leadData),this.emit("leadCaptured",r.leadData)),r.content&&(u&&(this.panel.messages.removeTyping(),this.panel.addMessage(h),u=!1),h.content+=r.content,this.panel.messages.updateMessage(h))}g||m||(m=!0),!g&&u&&this.panel.messages.removeTyping(),!g&&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){h.content=this.locale.errorGeneric,h.status="error",h.errorType="network",this.retryRequests.set(h.id,{regenerate:t.regenerate,userMessageId:t.userMessageId}),this.panel.messages.removeTyping(),this.panel.addMessage(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{p&&m&&(this.userDataSent=!0),this.isStreaming=!1,this.panel.input.setDisabled(!1),this.panel.input.focus(),this.saveHistory()}}createRequest(e,t,s){const a=!1!==this.config.pageContext?{url:window.location.href,title:document.title}:void 0;return{conversationId:this.conversationId,message:e,messageId:t.userMessageId,regenerate:t.regenerate,pageContext:a,locale:this.config.locale,...s?{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){switch(e){case"rate_limit":case"network":case"provider_error":case"timeout":return e;default:return"provider_error"}}getErrorMessage(e){switch(e){case"rate_limit":return this.locale.errorRateLimit;case"network":case"timeout":return this.locale.errorNetwork;default:return this.locale.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 S=null;const k={init:e=>(S&&S.destroy(),S=new M(e),S.init(),S),open(){null==S||S.open()},close(){null==S||S.close()},destroy(){null==S||S.destroy(),S=null},on(e,t){null==S||S.on(e,t)},off(e,t){null==S||S.off(e,t)}};function L(){const e=document.currentScript;if(!e)return;const t=e.dataset.apiUrl;if(!t)return;const s=e.dataset.mode,a=e.dataset.container;k.init({apiUrl:t,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:void 0!==e.dataset.autoOpen?""===e.dataset.autoOpen||"true"===e.dataset.autoOpen||(parseInt(e.dataset.autoOpen,10)||!0):void 0,placeholder:e.dataset.placeholder,locale:e.dataset.locale})}const B=document.currentScript;return B&&B.dataset.apiUrl&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",L):L()),"undefined"!=typeof window&&(window.ChatCops=k),e.Widget=M,e.default=k,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),e}({});
|
package/dist/markdown.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"markdown.d.ts","sourceRoot":"","sources":["../src/markdown.ts"],"names":[],"mappings":"AAuBA,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"markdown.d.ts","sourceRoot":"","sources":["../src/markdown.ts"],"names":[],"mappings":"AAuBA,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CA8CpD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatcops/widget",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Embeddable AI chatbot widget - zero dependencies, Shadow DOM isolated",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/chatcops.min.js",
|
|
@@ -18,10 +18,10 @@
|
|
|
18
18
|
],
|
|
19
19
|
"devDependencies": {
|
|
20
20
|
"typescript": "^5.7.0",
|
|
21
|
-
"vite": "^6.
|
|
21
|
+
"vite": "^6.4.3",
|
|
22
22
|
"terser": "^5.37.0",
|
|
23
|
-
"vitest": "^
|
|
24
|
-
"happy-dom": "^
|
|
23
|
+
"vitest": "^4.1.11",
|
|
24
|
+
"happy-dom": "^20.14.5"
|
|
25
25
|
},
|
|
26
26
|
"repository": {
|
|
27
27
|
"type": "git",
|