@chatcops/widget 0.2.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.
@@ -0,0 +1,752 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ const widgetStyles = ":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-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}.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-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)}@media(max-width:768px){.cc-panel{width:100%;height:100%;max-height:100%;bottom:0;right:0;left:0;border-radius:0;border:none}.cc-panel.cc-left{left:0}.cc-bubble{bottom:84px;right:16px;left:16px;max-width:none}}";
5
+ function createShadowRoot() {
6
+ const host = document.createElement("div");
7
+ host.id = "chatcops-root";
8
+ document.body.appendChild(host);
9
+ const shadow = host.attachShadow({ mode: "open" });
10
+ const style = document.createElement("style");
11
+ style.textContent = widgetStyles;
12
+ shadow.appendChild(style);
13
+ return shadow;
14
+ }
15
+ function destroyShadowRoot() {
16
+ const host = document.getElementById("chatcops-root");
17
+ if (host) host.remove();
18
+ }
19
+ const CHAT_ICON = `<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>`;
20
+ const CLOSE_ICON$1 = `<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>`;
21
+ class FAB {
22
+ constructor(root, options) {
23
+ __publicField(this, "el");
24
+ __publicField(this, "badge");
25
+ __publicField(this, "isOpen", false);
26
+ this.el = document.createElement("button");
27
+ this.el.className = "cc-fab cc-pulse";
28
+ this.el.setAttribute("aria-label", "Open chat");
29
+ if (options.position === "bottom-left") {
30
+ this.el.classList.add("cc-left");
31
+ }
32
+ this.el.innerHTML = CHAT_ICON;
33
+ this.badge = document.createElement("div");
34
+ this.badge.className = "cc-fab-badge";
35
+ this.el.appendChild(this.badge);
36
+ this.el.addEventListener("click", () => {
37
+ this.el.classList.remove("cc-pulse");
38
+ options.onClick();
39
+ });
40
+ root.appendChild(this.el);
41
+ }
42
+ setOpen(open) {
43
+ this.isOpen = open;
44
+ this.el.innerHTML = open ? CLOSE_ICON$1 : CHAT_ICON;
45
+ if (!open) this.el.appendChild(this.badge);
46
+ this.el.classList.toggle("cc-open", open);
47
+ this.el.setAttribute("aria-label", open ? "Close chat" : "Open chat");
48
+ }
49
+ showBadge() {
50
+ this.badge.classList.add("cc-visible");
51
+ }
52
+ hideBadge() {
53
+ this.badge.classList.remove("cc-visible");
54
+ }
55
+ destroy() {
56
+ this.el.remove();
57
+ }
58
+ }
59
+ const ESCAPE_MAP = {
60
+ "&": "&amp;",
61
+ "<": "&lt;",
62
+ ">": "&gt;",
63
+ '"': "&quot;",
64
+ "'": "&#39;"
65
+ };
66
+ function escapeHtml(text) {
67
+ return text.replace(/[&<>"']/g, (ch) => ESCAPE_MAP[ch] ?? ch);
68
+ }
69
+ function renderMarkdown(input) {
70
+ let html = escapeHtml(input);
71
+ html = html.replace(/```(?:\w*)\n?([\s\S]*?)```/g, (_match, code) => {
72
+ return `<pre><code>${code.trim()}</code></pre>`;
73
+ });
74
+ html = html.replace(/`([^`]+)`/g, "<code>$1</code>");
75
+ html = html.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
76
+ html = html.replace(/\*(.+?)\*/g, "<em>$1</em>");
77
+ html = html.replace(
78
+ /\[([^\]]+)\]\(((?:[^()]*|\([^()]*\))*)\)/g,
79
+ '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'
80
+ );
81
+ html = html.replace(/^- (.+)$/gm, "<li>$1</li>");
82
+ html = html.replace(/(<li>.*<\/li>\n?)+/g, (match) => `<ul>${match}</ul>`);
83
+ html = html.replace(/^\d+\. (.+)$/gm, "<li>$1</li>");
84
+ html = html.replace(/\n\n/g, "<br><br>");
85
+ html = html.replace(/\n/g, "<br>");
86
+ return html;
87
+ }
88
+ class Messages {
89
+ constructor(parent) {
90
+ __publicField(this, "container");
91
+ __publicField(this, "typingEl", null);
92
+ this.container = document.createElement("div");
93
+ this.container.className = "cc-messages";
94
+ parent.appendChild(this.container);
95
+ }
96
+ addMessage(msg) {
97
+ this.removeTyping();
98
+ const el = document.createElement("div");
99
+ el.className = `cc-message cc-message-${msg.role}`;
100
+ el.dataset.id = msg.id;
101
+ el.innerHTML = msg.role === "assistant" ? renderMarkdown(msg.content) : this.escapeHtml(msg.content);
102
+ this.container.appendChild(el);
103
+ this.scrollToBottom();
104
+ return el;
105
+ }
106
+ updateMessage(id, content, isAssistant) {
107
+ const el = this.container.querySelector(`[data-id="${id}"]`);
108
+ if (el) {
109
+ el.innerHTML = isAssistant ? renderMarkdown(content) : this.escapeHtml(content);
110
+ this.scrollToBottom();
111
+ }
112
+ }
113
+ showTyping() {
114
+ if (this.typingEl) return;
115
+ this.typingEl = document.createElement("div");
116
+ this.typingEl.className = "cc-typing";
117
+ this.typingEl.innerHTML = '<div class="cc-typing-dot"></div><div class="cc-typing-dot"></div><div class="cc-typing-dot"></div>';
118
+ this.container.appendChild(this.typingEl);
119
+ this.scrollToBottom();
120
+ }
121
+ removeTyping() {
122
+ if (this.typingEl) {
123
+ this.typingEl.remove();
124
+ this.typingEl = null;
125
+ }
126
+ }
127
+ clear() {
128
+ this.container.innerHTML = "";
129
+ this.typingEl = null;
130
+ }
131
+ scrollToBottom() {
132
+ this.container.scrollTop = this.container.scrollHeight;
133
+ }
134
+ escapeHtml(text) {
135
+ const div = document.createElement("div");
136
+ div.textContent = text;
137
+ return div.innerHTML;
138
+ }
139
+ }
140
+ class Input {
141
+ constructor(parent, options) {
142
+ __publicField(this, "area");
143
+ __publicField(this, "textarea");
144
+ __publicField(this, "sendBtn");
145
+ __publicField(this, "onSend");
146
+ this.onSend = options.onSend;
147
+ this.area = document.createElement("div");
148
+ this.area.className = "cc-input-area";
149
+ this.textarea = document.createElement("textarea");
150
+ this.textarea.className = "cc-input";
151
+ this.textarea.placeholder = options.placeholder;
152
+ this.textarea.rows = 1;
153
+ this.textarea.addEventListener("input", () => this.autoResize());
154
+ this.textarea.addEventListener("keydown", (e) => this.handleKeydown(e));
155
+ this.sendBtn = document.createElement("button");
156
+ this.sendBtn.className = "cc-send-btn";
157
+ this.sendBtn.disabled = true;
158
+ this.sendBtn.setAttribute("aria-label", "Send message");
159
+ 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>';
160
+ this.sendBtn.addEventListener("click", () => this.send());
161
+ this.textarea.addEventListener("input", () => {
162
+ this.sendBtn.disabled = this.textarea.value.trim().length === 0;
163
+ });
164
+ this.area.appendChild(this.textarea);
165
+ this.area.appendChild(this.sendBtn);
166
+ parent.appendChild(this.area);
167
+ }
168
+ focus() {
169
+ this.textarea.focus();
170
+ }
171
+ setDisabled(disabled) {
172
+ this.textarea.disabled = disabled;
173
+ this.sendBtn.disabled = disabled || this.textarea.value.trim().length === 0;
174
+ }
175
+ clear() {
176
+ this.textarea.value = "";
177
+ this.sendBtn.disabled = true;
178
+ this.autoResize();
179
+ }
180
+ send() {
181
+ const text = this.textarea.value.trim();
182
+ if (!text) return;
183
+ this.onSend(text);
184
+ this.clear();
185
+ }
186
+ handleKeydown(e) {
187
+ if (e.key === "Enter" && !e.shiftKey) {
188
+ e.preventDefault();
189
+ this.send();
190
+ }
191
+ }
192
+ autoResize() {
193
+ this.textarea.style.height = "auto";
194
+ const maxHeight = 96;
195
+ this.textarea.style.height = Math.min(this.textarea.scrollHeight, maxHeight) + "px";
196
+ }
197
+ }
198
+ const BOT_ICON = `<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>`;
199
+ const CLOSE_ICON = `<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>`;
200
+ class Panel {
201
+ constructor(root, options) {
202
+ __publicField(this, "el");
203
+ __publicField(this, "messages");
204
+ __publicField(this, "input");
205
+ this.el = document.createElement("div");
206
+ this.el.className = "cc-panel";
207
+ if (options.position === "bottom-left") {
208
+ this.el.classList.add("cc-left");
209
+ }
210
+ const header = document.createElement("div");
211
+ header.className = "cc-header";
212
+ if (options.branding.avatar) {
213
+ const img = document.createElement("img");
214
+ img.className = "cc-header-avatar";
215
+ img.src = options.branding.avatar;
216
+ img.alt = options.branding.name;
217
+ header.appendChild(img);
218
+ } else {
219
+ const placeholder = document.createElement("div");
220
+ placeholder.className = "cc-header-avatar-placeholder";
221
+ placeholder.innerHTML = BOT_ICON;
222
+ header.appendChild(placeholder);
223
+ }
224
+ const info = document.createElement("div");
225
+ info.className = "cc-header-info";
226
+ info.innerHTML = `<div class="cc-header-name">${this.escapeHtml(options.branding.name)}</div><div class="cc-header-subtitle">${this.escapeHtml(options.branding.subtitle)}</div>`;
227
+ header.appendChild(info);
228
+ const closeBtn = document.createElement("button");
229
+ closeBtn.className = "cc-header-close";
230
+ closeBtn.setAttribute("aria-label", "Close chat");
231
+ closeBtn.innerHTML = CLOSE_ICON;
232
+ closeBtn.addEventListener("click", options.onClose);
233
+ header.appendChild(closeBtn);
234
+ this.el.appendChild(header);
235
+ this.messages = new Messages(this.el);
236
+ this.input = new Input(this.el, {
237
+ placeholder: options.placeholder,
238
+ onSend: options.onSend
239
+ });
240
+ const footer = document.createElement("div");
241
+ footer.className = "cc-footer";
242
+ footer.innerHTML = options.footerText;
243
+ this.el.appendChild(footer);
244
+ root.appendChild(this.el);
245
+ }
246
+ show() {
247
+ this.el.classList.add("cc-visible");
248
+ this.input.focus();
249
+ }
250
+ hide() {
251
+ this.el.classList.remove("cc-visible");
252
+ }
253
+ get isVisible() {
254
+ return this.el.classList.contains("cc-visible");
255
+ }
256
+ addMessage(msg) {
257
+ return this.messages.addMessage(msg);
258
+ }
259
+ destroy() {
260
+ this.el.remove();
261
+ }
262
+ escapeHtml(text) {
263
+ const div = document.createElement("div");
264
+ div.textContent = text;
265
+ return div.innerHTML;
266
+ }
267
+ }
268
+ const BUBBLE_SHOWN_KEY = "chatcops_bubble_shown";
269
+ class WelcomeBubble {
270
+ constructor(root, options) {
271
+ __publicField(this, "el");
272
+ __publicField(this, "timerId", null);
273
+ this.el = document.createElement("div");
274
+ this.el.className = "cc-bubble";
275
+ if (options.position === "bottom-left") {
276
+ this.el.classList.add("cc-left");
277
+ }
278
+ this.el.textContent = options.text;
279
+ const closeBtn = document.createElement("button");
280
+ closeBtn.className = "cc-bubble-close";
281
+ closeBtn.innerHTML = "&times;";
282
+ closeBtn.addEventListener("click", (e) => {
283
+ e.stopPropagation();
284
+ this.hide();
285
+ });
286
+ this.el.appendChild(closeBtn);
287
+ this.el.addEventListener("click", () => {
288
+ this.hide();
289
+ options.onClick();
290
+ });
291
+ root.appendChild(this.el);
292
+ if (options.showOnce) {
293
+ try {
294
+ if (sessionStorage.getItem(BUBBLE_SHOWN_KEY)) return;
295
+ sessionStorage.setItem(BUBBLE_SHOWN_KEY, "1");
296
+ } catch {
297
+ }
298
+ }
299
+ this.timerId = setTimeout(() => {
300
+ this.el.classList.add("cc-visible");
301
+ }, options.delay ?? 3e3);
302
+ }
303
+ hide() {
304
+ this.el.classList.remove("cc-visible");
305
+ if (this.timerId) {
306
+ clearTimeout(this.timerId);
307
+ this.timerId = null;
308
+ }
309
+ }
310
+ destroy() {
311
+ this.hide();
312
+ this.el.remove();
313
+ }
314
+ }
315
+ class ChatClient {
316
+ constructor(options) {
317
+ __publicField(this, "apiUrl");
318
+ __publicField(this, "timeout");
319
+ this.apiUrl = options.apiUrl;
320
+ this.timeout = options.timeout ?? 3e4;
321
+ }
322
+ async *sendMessage(request) {
323
+ var _a;
324
+ const controller = new AbortController();
325
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
326
+ try {
327
+ const response = await fetch(this.apiUrl, {
328
+ method: "POST",
329
+ headers: { "Content-Type": "application/json" },
330
+ body: JSON.stringify(request),
331
+ signal: controller.signal
332
+ });
333
+ if (!response.ok) {
334
+ if (response.status === 429) {
335
+ yield { error: "rate_limit" };
336
+ return;
337
+ }
338
+ yield { error: `HTTP ${response.status}` };
339
+ return;
340
+ }
341
+ const reader = (_a = response.body) == null ? void 0 : _a.getReader();
342
+ if (!reader) {
343
+ yield { error: "No response body" };
344
+ return;
345
+ }
346
+ const decoder = new TextDecoder();
347
+ let buffer = "";
348
+ while (true) {
349
+ const { done, value } = await reader.read();
350
+ if (done) break;
351
+ buffer += decoder.decode(value, { stream: true });
352
+ const lines = buffer.split("\n");
353
+ buffer = lines.pop() ?? "";
354
+ for (const line of lines) {
355
+ const trimmed = line.trim();
356
+ if (!trimmed || !trimmed.startsWith("data: ")) continue;
357
+ const data = trimmed.slice(6);
358
+ if (data === "[DONE]") {
359
+ yield { done: true };
360
+ return;
361
+ }
362
+ try {
363
+ yield JSON.parse(data);
364
+ } catch {
365
+ }
366
+ }
367
+ }
368
+ yield { done: true };
369
+ } catch (err) {
370
+ if (err instanceof DOMException && err.name === "AbortError") {
371
+ yield { error: "timeout" };
372
+ } else {
373
+ yield { error: "network" };
374
+ }
375
+ } finally {
376
+ clearTimeout(timeoutId);
377
+ }
378
+ }
379
+ }
380
+ const KEY_PREFIX = "chatcops_conversation";
381
+ class ConversationStorage {
382
+ constructor(siteId) {
383
+ __publicField(this, "key");
384
+ this.key = siteId ? `${KEY_PREFIX}_${siteId}` : KEY_PREFIX;
385
+ }
386
+ load() {
387
+ try {
388
+ const raw = localStorage.getItem(this.key);
389
+ if (!raw) return null;
390
+ return JSON.parse(raw);
391
+ } catch {
392
+ return null;
393
+ }
394
+ }
395
+ save(conversation) {
396
+ try {
397
+ localStorage.setItem(this.key, JSON.stringify(conversation));
398
+ } catch {
399
+ }
400
+ }
401
+ clear() {
402
+ try {
403
+ localStorage.removeItem(this.key);
404
+ } catch {
405
+ }
406
+ }
407
+ getSessionId() {
408
+ const SESSION_KEY = "chatcops_session_id";
409
+ try {
410
+ let id = sessionStorage.getItem(SESSION_KEY);
411
+ if (!id) {
412
+ id = crypto.randomUUID();
413
+ sessionStorage.setItem(SESSION_KEY, id);
414
+ }
415
+ return id;
416
+ } catch {
417
+ return crypto.randomUUID();
418
+ }
419
+ }
420
+ }
421
+ function applyTheme(root, theme) {
422
+ const host = root.host;
423
+ if (theme.accent) {
424
+ host.style.setProperty("--cc-accent", theme.accent);
425
+ host.style.setProperty("--cc-accent-hover", darken(theme.accent, 10));
426
+ }
427
+ if (theme.textColor) {
428
+ host.style.setProperty("--cc-text", theme.textColor);
429
+ }
430
+ if (theme.bgColor) {
431
+ host.style.setProperty("--cc-bg", theme.bgColor);
432
+ host.style.setProperty("--cc-bg-surface", lighten(theme.bgColor, 8));
433
+ host.style.setProperty("--cc-bg-input", lighten(theme.bgColor, 14));
434
+ }
435
+ if (theme.fontFamily) {
436
+ host.style.setProperty("--cc-font", theme.fontFamily);
437
+ }
438
+ if (theme.borderRadius) {
439
+ host.style.setProperty("--cc-radius", theme.borderRadius);
440
+ }
441
+ }
442
+ function parseHex(hex) {
443
+ if (!/^#?[\da-f]{3}(?:[\da-f]{3})?$/i.test(hex)) return [0, 0, 0];
444
+ const h = hex.replace("#", "");
445
+ const n = parseInt(h.length === 3 ? h.split("").map((c) => c + c).join("") : h, 16);
446
+ return [n >> 16 & 255, n >> 8 & 255, n & 255];
447
+ }
448
+ function toHex(r, g, b) {
449
+ return "#" + [r, g, b].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("");
450
+ }
451
+ function darken(hex, percent) {
452
+ const [r, g, b] = parseHex(hex);
453
+ const f = 1 - percent / 100;
454
+ return toHex(Math.round(r * f), Math.round(g * f), Math.round(b * f));
455
+ }
456
+ function lighten(hex, percent) {
457
+ const [r, g, b] = parseHex(hex);
458
+ const f = percent / 100;
459
+ return toHex(Math.round(r + (255 - r) * f), Math.round(g + (255 - g) * f), Math.round(b + (255 - b) * f));
460
+ }
461
+ const en = {
462
+ welcomeMessage: "Hi! How can I help you today?",
463
+ inputPlaceholder: "Type a message...",
464
+ sendButton: "Send",
465
+ closeButton: "Close",
466
+ errorGeneric: "Something went wrong. Please try again.",
467
+ errorNetwork: "Connection error. Please check your network.",
468
+ errorRateLimit: "Too many messages. Please wait a moment.",
469
+ typingIndicator: "Typing...",
470
+ poweredBy: "Powered by ChatCops",
471
+ newConversation: "New conversation",
472
+ welcomeBubbleDefault: "Need help? Chat with us!"
473
+ };
474
+ const locales = { en };
475
+ function getWidgetLocale(code, overrides) {
476
+ const base = locales[code] ?? en;
477
+ return overrides ? { ...base, ...overrides } : base;
478
+ }
479
+ class Widget {
480
+ constructor(config) {
481
+ __publicField(this, "config");
482
+ __publicField(this, "shadow");
483
+ __publicField(this, "fab");
484
+ __publicField(this, "panel");
485
+ __publicField(this, "bubble");
486
+ __publicField(this, "client");
487
+ __publicField(this, "storage");
488
+ __publicField(this, "locale");
489
+ __publicField(this, "conversationId");
490
+ __publicField(this, "messages", []);
491
+ __publicField(this, "isStreaming", false);
492
+ __publicField(this, "eventHandlers", /* @__PURE__ */ new Map());
493
+ this.config = config;
494
+ this.client = new ChatClient({ apiUrl: config.apiUrl });
495
+ this.storage = new ConversationStorage();
496
+ this.locale = getWidgetLocale(config.locale ?? "en", config.strings);
497
+ this.conversationId = this.storage.getSessionId();
498
+ }
499
+ init() {
500
+ var _a, _b, _c, _d;
501
+ this.shadow = createShadowRoot();
502
+ if (this.config.theme) {
503
+ applyTheme(this.shadow, this.config.theme);
504
+ }
505
+ const position = ((_a = this.config.theme) == null ? void 0 : _a.position) ?? "bottom-right";
506
+ this.fab = new FAB(this.shadow, {
507
+ position,
508
+ onClick: () => this.toggle()
509
+ });
510
+ this.panel = new Panel(this.shadow, {
511
+ position,
512
+ branding: {
513
+ name: ((_b = this.config.branding) == null ? void 0 : _b.name) ?? "AI Assistant",
514
+ avatar: (_c = this.config.branding) == null ? void 0 : _c.avatar,
515
+ subtitle: ((_d = this.config.branding) == null ? void 0 : _d.subtitle) ?? "Online"
516
+ },
517
+ placeholder: this.config.placeholder ?? this.locale.inputPlaceholder,
518
+ footerText: this.locale.poweredBy,
519
+ onSend: (text) => this.handleSend(text),
520
+ onClose: () => this.close()
521
+ });
522
+ if (this.config.persistHistory !== false) {
523
+ const saved = this.storage.load();
524
+ if (saved) {
525
+ this.conversationId = saved.id;
526
+ for (const msg of saved.messages) {
527
+ this.messages.push(msg);
528
+ this.panel.addMessage(msg);
529
+ }
530
+ }
531
+ }
532
+ if (this.messages.length === 0) {
533
+ const welcomeText = this.config.welcomeMessage ?? this.locale.welcomeMessage;
534
+ const welcomeMsg = {
535
+ id: "welcome",
536
+ role: "assistant",
537
+ content: welcomeText
538
+ };
539
+ this.messages.push(welcomeMsg);
540
+ this.panel.addMessage(welcomeMsg);
541
+ }
542
+ if (this.config.welcomeBubble) {
543
+ this.bubble = new WelcomeBubble(this.shadow, {
544
+ text: this.config.welcomeBubble.text,
545
+ delay: this.config.welcomeBubble.delay,
546
+ showOnce: this.config.welcomeBubble.showOnce ?? true,
547
+ position,
548
+ onClick: () => this.open()
549
+ });
550
+ }
551
+ }
552
+ open() {
553
+ var _a, _b, _c;
554
+ this.panel.show();
555
+ this.fab.setOpen(true);
556
+ this.fab.hideBadge();
557
+ (_a = this.bubble) == null ? void 0 : _a.hide();
558
+ (_c = (_b = this.config).onOpen) == null ? void 0 : _c.call(_b);
559
+ this.emit("open");
560
+ }
561
+ close() {
562
+ var _a, _b;
563
+ this.panel.hide();
564
+ this.fab.setOpen(false);
565
+ (_b = (_a = this.config).onClose) == null ? void 0 : _b.call(_a);
566
+ this.emit("close");
567
+ }
568
+ toggle() {
569
+ if (this.panel.isVisible) {
570
+ this.close();
571
+ } else {
572
+ this.open();
573
+ }
574
+ }
575
+ destroy() {
576
+ var _a;
577
+ (_a = this.bubble) == null ? void 0 : _a.destroy();
578
+ this.panel.destroy();
579
+ this.fab.destroy();
580
+ destroyShadowRoot();
581
+ this.eventHandlers.clear();
582
+ this.messages = [];
583
+ }
584
+ on(event, handler) {
585
+ if (!this.eventHandlers.has(event)) {
586
+ this.eventHandlers.set(event, /* @__PURE__ */ new Set());
587
+ }
588
+ this.eventHandlers.get(event).add(handler);
589
+ }
590
+ off(event, handler) {
591
+ var _a;
592
+ (_a = this.eventHandlers.get(event)) == null ? void 0 : _a.delete(handler);
593
+ }
594
+ emit(event, ...args) {
595
+ var _a;
596
+ (_a = this.eventHandlers.get(event)) == null ? void 0 : _a.forEach((h) => h(...args));
597
+ }
598
+ async handleSend(text) {
599
+ var _a, _b, _c, _d, _e, _f, _g, _h;
600
+ if (this.isStreaming) return;
601
+ const userMsg = {
602
+ id: crypto.randomUUID(),
603
+ role: "user",
604
+ content: text
605
+ };
606
+ this.messages.push(userMsg);
607
+ this.panel.addMessage(userMsg);
608
+ (_b = (_a = this.config).onMessage) == null ? void 0 : _b.call(_a, userMsg);
609
+ this.emit("message", userMsg);
610
+ this.isStreaming = true;
611
+ this.panel.input.setDisabled(true);
612
+ this.panel.messages.showTyping();
613
+ const assistantMsg = {
614
+ id: crypto.randomUUID(),
615
+ role: "assistant",
616
+ content: ""
617
+ };
618
+ const pageContext = this.config.pageContext !== false ? { url: window.location.href, title: document.title } : void 0;
619
+ try {
620
+ let firstChunk = true;
621
+ for await (const chunk of this.client.sendMessage({
622
+ conversationId: this.conversationId,
623
+ message: text,
624
+ pageContext,
625
+ locale: this.config.locale
626
+ })) {
627
+ if (chunk.error) {
628
+ const errorKey = chunk.error === "rate_limit" ? "errorRateLimit" : chunk.error === "network" ? "errorNetwork" : "errorGeneric";
629
+ assistantMsg.content = this.locale[errorKey];
630
+ this.panel.messages.removeTyping();
631
+ this.panel.addMessage(assistantMsg);
632
+ (_d = (_c = this.config).onError) == null ? void 0 : _d.call(_c, new Error(chunk.error));
633
+ this.emit("error", new Error(chunk.error));
634
+ break;
635
+ }
636
+ if (chunk.done) break;
637
+ if (chunk.content) {
638
+ if (firstChunk) {
639
+ this.panel.messages.removeTyping();
640
+ this.panel.addMessage(assistantMsg);
641
+ firstChunk = false;
642
+ }
643
+ assistantMsg.content += chunk.content;
644
+ this.panel.messages.updateMessage(assistantMsg.id, assistantMsg.content, true);
645
+ }
646
+ }
647
+ if (assistantMsg.content) {
648
+ this.messages.push(assistantMsg);
649
+ (_f = (_e = this.config).onMessage) == null ? void 0 : _f.call(_e, assistantMsg);
650
+ this.emit("message", assistantMsg);
651
+ if (!this.panel.isVisible) {
652
+ this.fab.showBadge();
653
+ }
654
+ }
655
+ } catch (err) {
656
+ this.panel.messages.removeTyping();
657
+ assistantMsg.content = this.locale.errorGeneric;
658
+ this.panel.addMessage(assistantMsg);
659
+ (_h = (_g = this.config).onError) == null ? void 0 : _h.call(_g, err instanceof Error ? err : new Error(String(err)));
660
+ } finally {
661
+ this.isStreaming = false;
662
+ this.panel.input.setDisabled(false);
663
+ this.panel.input.focus();
664
+ this.saveHistory();
665
+ }
666
+ }
667
+ saveHistory() {
668
+ if (this.config.persistHistory === false) return;
669
+ const maxMessages = this.config.maxMessages ?? 50;
670
+ const toSave = this.messages.filter((m) => m.id !== "welcome").slice(-maxMessages);
671
+ this.storage.save({
672
+ id: this.conversationId,
673
+ messages: toSave.map((m) => ({
674
+ id: m.id,
675
+ role: m.role,
676
+ content: m.content,
677
+ timestamp: Date.now()
678
+ })),
679
+ updatedAt: Date.now()
680
+ });
681
+ }
682
+ }
683
+ let instance = null;
684
+ const ChatCops = {
685
+ init(config) {
686
+ if (instance) {
687
+ instance.destroy();
688
+ }
689
+ instance = new Widget(config);
690
+ instance.init();
691
+ return instance;
692
+ },
693
+ open() {
694
+ instance == null ? void 0 : instance.open();
695
+ },
696
+ close() {
697
+ instance == null ? void 0 : instance.close();
698
+ },
699
+ destroy() {
700
+ instance == null ? void 0 : instance.destroy();
701
+ instance = null;
702
+ },
703
+ on(event, handler) {
704
+ instance == null ? void 0 : instance.on(event, handler);
705
+ },
706
+ off(event, handler) {
707
+ instance == null ? void 0 : instance.off(event, handler);
708
+ }
709
+ };
710
+ function autoInit() {
711
+ const script = document.currentScript;
712
+ if (!script) return;
713
+ const apiUrl = script.dataset.apiUrl;
714
+ if (!apiUrl) return;
715
+ ChatCops.init({
716
+ apiUrl,
717
+ theme: {
718
+ accent: script.dataset.accent,
719
+ textColor: script.dataset.textColor,
720
+ bgColor: script.dataset.bgColor,
721
+ fontFamily: script.dataset.fontFamily,
722
+ borderRadius: script.dataset.borderRadius,
723
+ position: script.dataset.position || void 0
724
+ },
725
+ branding: {
726
+ name: script.dataset.brandName,
727
+ avatar: script.dataset.brandAvatar,
728
+ subtitle: script.dataset.brandSubtitle
729
+ },
730
+ welcomeMessage: script.dataset.welcomeMessage,
731
+ welcomeBubble: script.dataset.welcomeBubble ? {
732
+ text: script.dataset.welcomeBubble,
733
+ delay: script.dataset.welcomeBubbleDelay ? parseInt(script.dataset.welcomeBubbleDelay, 10) : void 0
734
+ } : void 0,
735
+ placeholder: script.dataset.placeholder,
736
+ locale: script.dataset.locale
737
+ });
738
+ }
739
+ const currentScript = document.currentScript;
740
+ if (currentScript && currentScript.dataset.apiUrl) {
741
+ if (document.readyState === "loading") {
742
+ document.addEventListener("DOMContentLoaded", autoInit);
743
+ } else {
744
+ autoInit();
745
+ }
746
+ }
747
+ if (typeof window !== "undefined") {
748
+ window.ChatCops = ChatCops;
749
+ }
750
+ export {
751
+ ChatCops as default
752
+ };
@@ -0,0 +1 @@
1
+ var ChatCops=function(){"use strict";var e=Object.defineProperty,t=(t,s,a)=>((t,s,a)=>s in t?e(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a)(t,"symbol"!=typeof s?s+"":s,a);const s='<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 a{constructor(e,a){t(this,"el"),t(this,"badge"),t(this,"isOpen",!1),this.el=document.createElement("button"),this.el.className="cc-fab cc-pulse",this.el.setAttribute("aria-label","Open chat"),"bottom-left"===a.position&&this.el.classList.add("cc-left"),this.el.innerHTML=s,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"),a.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>':s,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 i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function n(e){let t=e.replace(/[&<>"']/g,e=>i[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,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),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 o{constructor(e){t(this,"container"),t(this,"typingEl",null),this.container=document.createElement("div"),this.container.className="cc-messages",e.appendChild(this.container)}addMessage(e){this.removeTyping();const t=document.createElement("div");return t.className=`cc-message cc-message-${e.role}`,t.dataset.id=e.id,t.innerHTML="assistant"===e.role?n(e.content):this.escapeHtml(e.content),this.container.appendChild(t),this.scrollToBottom(),t}updateMessage(e,t,s){const a=this.container.querySelector(`[data-id="${e}"]`);a&&(a.innerHTML=s?n(t):this.escapeHtml(t),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}scrollToBottom(){this.container.scrollTop=this.container.scrollHeight}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}class c{constructor(e,s){t(this,"area"),t(this,"textarea"),t(this,"sendBtn"),t(this,"onSend"),this.onSend=s.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=s.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()}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 r{constructor(e,s){t(this,"el"),t(this,"messages"),t(this,"input"),this.el=document.createElement("div"),this.el.className="cc-panel","bottom-left"===s.position&&this.el.classList.add("cc-left");const a=document.createElement("div");if(a.className="cc-header",s.branding.avatar){const e=document.createElement("img");e.className="cc-header-avatar",e.src=s.branding.avatar,e.alt=s.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");i.className="cc-header-info",i.innerHTML=`<div class="cc-header-name">${this.escapeHtml(s.branding.name)}</div><div class="cc-header-subtitle">${this.escapeHtml(s.branding.subtitle)}</div>`,a.appendChild(i);const n=document.createElement("button");n.className="cc-header-close",n.setAttribute("aria-label","Close chat"),n.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>',n.addEventListener("click",s.onClose),a.appendChild(n),this.el.appendChild(a),this.messages=new o(this.el),this.input=new c(this.el,{placeholder:s.placeholder,onSend:s.onSend});const r=document.createElement("div");r.className="cc-footer",r.innerHTML=s.footerText,this.el.appendChild(r),e.appendChild(this.el)}show(){this.el.classList.add("cc-visible"),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)}destroy(){this.el.remove()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const l="chatcops_bubble_shown";class d{constructor(e,s){t(this,"el"),t(this,"timerId",null),this.el=document.createElement("div"),this.el.className="cc-bubble","bottom-left"===s.position&&this.el.classList.add("cc-left"),this.el.textContent=s.text;const a=document.createElement("button");if(a.className="cc-bubble-close",a.innerHTML="&times;",a.addEventListener("click",e=>{e.stopPropagation(),this.hide()}),this.el.appendChild(a),this.el.addEventListener("click",()=>{this.hide(),s.onClick()}),e.appendChild(this.el),s.showOnce)try{if(sessionStorage.getItem(l))return;sessionStorage.setItem(l,"1")}catch{}this.timerId=setTimeout(()=>{this.el.classList.add("cc-visible")},s.delay??3e3)}hide(){this.el.classList.remove("cc-visible"),this.timerId&&(clearTimeout(this.timerId),this.timerId=null)}destroy(){this.hide(),this.el.remove()}}class h{constructor(e){t(this,"apiUrl"),t(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 o="";for(;;){const{done:e,value:t}=await i.read();if(e)break;o+=n.decode(t,{stream:!0});const s=o.split("\n");o=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 p="chatcops_conversation";class g{constructor(e){t(this,"key"),this.key=e?`${p}_${e}`:p}load(){try{const e=localStorage.getItem(this.key);return e?JSON.parse(e):null}catch{return null}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}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()}}}function u(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]=m(e),n=1-t/100;return b(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",f(t.bgColor,8)),s.style.setProperty("--cc-bg-input",f(t.bgColor,14))),t.fontFamily&&s.style.setProperty("--cc-font",t.fontFamily),t.borderRadius&&s.style.setProperty("--cc-radius",t.borderRadius)}function m(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 b(e,t,s){return"#"+[e,t,s].map(e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0")).join("")}function f(e,t){const[s,a,i]=m(e),n=t/100;return b(Math.round(s+(255-s)*n),Math.round(a+(255-a)*n),Math.round(i+(255-i)*n))}const x={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!"},v={en:x};class y{constructor(e){t(this,"config"),t(this,"shadow"),t(this,"fab"),t(this,"panel"),t(this,"bubble"),t(this,"client"),t(this,"storage"),t(this,"locale"),t(this,"conversationId"),t(this,"messages",[]),t(this,"isStreaming",!1),t(this,"eventHandlers",new Map),this.config=e,this.client=new h({apiUrl:e.apiUrl}),this.storage=new g,this.locale=function(e,t){const s=v[e]??x;return t?{...s,...t}:s}(e.locale??"en",e.strings),this.conversationId=this.storage.getSessionId()}init(){var e,t,s,i;this.shadow=function(){const e=document.createElement("div");e.id="chatcops-root",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),s=document.createElement("style");return s.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-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}.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-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)}@media(max-width:768px){.cc-panel{width:100%;height:100%;max-height:100%;bottom:0;right:0;left:0;border-radius:0;border:none}.cc-panel.cc-left{left:0}.cc-bubble{bottom:84px;right:16px;left:16px;max-width:none}}",t.appendChild(s),t}(),this.config.theme&&u(this.shadow,this.config.theme);const n=(null==(e=this.config.theme)?void 0:e.position)??"bottom-right";if(this.fab=new a(this.shadow,{position:n,onClick:()=>this.toggle()}),this.panel=new r(this.shadow,{position:n,branding:{name:(null==(t=this.config.branding)?void 0:t.name)??"AI Assistant",avatar:null==(s=this.config.branding)?void 0:s.avatar,subtitle:(null==(i=this.config.branding)?void 0:i.subtitle)??"Online"},placeholder:this.config.placeholder??this.locale.inputPlaceholder,footerText:this.locale.poweredBy,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(0===this.messages.length){const e={id:"welcome",role:"assistant",content:this.config.welcomeMessage??this.locale.welcomeMessage};this.messages.push(e),this.panel.addMessage(e)}this.config.welcomeBubble&&(this.bubble=new d(this.shadow,{text:this.config.welcomeBubble.text,delay:this.config.welcomeBubble.delay,showOnce:this.config.welcomeBubble.showOnce??!0,position:n,onClick:()=>this.open()}))}open(){var e,t,s;this.panel.show(),this.fab.setOpen(!0),this.fab.hideBadge(),null==(e=this.bubble)||e.hide(),null==(s=(t=this.config).onOpen)||s.call(t),this.emit("open")}close(){var e,t;this.panel.hide(),this.fab.setOpen(!1),null==(t=(e=this.config).onClose)||t.call(e),this.emit("close")}toggle(){this.panel.isVisible?this.close():this.open()}destroy(){var e;null==(e=this.bubble)||e.destroy(),this.panel.destroy(),this.fab.destroy(),function(){const e=document.getElementById("chatcops-root");e&&e.remove()}(),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))}async handleSend(e){var t,s,a,i,n,o,c,r;if(this.isStreaming)return;const l={id:crypto.randomUUID(),role:"user",content:e};this.messages.push(l),this.panel.addMessage(l),null==(s=(t=this.config).onMessage)||s.call(t,l),this.emit("message",l),this.isStreaming=!0,this.panel.input.setDisabled(!0),this.panel.messages.showTyping();const d={id:crypto.randomUUID(),role:"assistant",content:""},h=!1!==this.config.pageContext?{url:window.location.href,title:document.title}:void 0;try{let t=!0;for await(const s of this.client.sendMessage({conversationId:this.conversationId,message:e,pageContext:h,locale:this.config.locale})){if(s.error){const e="rate_limit"===s.error?"errorRateLimit":"network"===s.error?"errorNetwork":"errorGeneric";d.content=this.locale[e],this.panel.messages.removeTyping(),this.panel.addMessage(d),null==(i=(a=this.config).onError)||i.call(a,new Error(s.error)),this.emit("error",new Error(s.error));break}if(s.done)break;s.content&&(t&&(this.panel.messages.removeTyping(),this.panel.addMessage(d),t=!1),d.content+=s.content,this.panel.messages.updateMessage(d.id,d.content,!0))}d.content&&(this.messages.push(d),null==(o=(n=this.config).onMessage)||o.call(n,d),this.emit("message",d),this.panel.isVisible||this.fab.showBadge())}catch(p){this.panel.messages.removeTyping(),d.content=this.locale.errorGeneric,this.panel.addMessage(d),null==(r=(c=this.config).onError)||r.call(c,p instanceof Error?p:new Error(String(p)))}finally{this.isStreaming=!1,this.panel.input.setDisabled(!1),this.panel.input.focus(),this.saveHistory()}}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,timestamp:Date.now()})),updatedAt:Date.now()})}}let w=null;const k={init:e=>(w&&w.destroy(),w=new y(e),w.init(),w),open(){null==w||w.open()},close(){null==w||w.close()},destroy(){null==w||w.destroy(),w=null},on(e,t){null==w||w.on(e,t)},off(e,t){null==w||w.off(e,t)}};function C(){const e=document.currentScript;if(!e)return;const t=e.dataset.apiUrl;t&&k.init({apiUrl:t,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,placeholder:e.dataset.placeholder,locale:e.dataset.locale})}const M=document.currentScript;return M&&M.dataset.apiUrl&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",C):C()),"undefined"!=typeof window&&(window.ChatCops=k),k}();
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@chatcops/widget",
3
+ "version": "0.2.0",
4
+ "description": "Embeddable AI chatbot widget - zero dependencies, Shadow DOM isolated",
5
+ "type": "module",
6
+ "main": "dist/chatcops.min.js",
7
+ "module": "dist/chatcops.esm.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/chatcops.esm.js",
13
+ "require": "./dist/chatcops.min.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "dev": "vite build --watch",
21
+ "build": "vite build && tsc --emitDeclarationOnly",
22
+ "typecheck": "tsc --noEmit",
23
+ "test": "vitest run",
24
+ "test:watch": "vitest",
25
+ "clean": "rm -rf dist *.tsbuildinfo"
26
+ },
27
+ "devDependencies": {
28
+ "typescript": "^5.7.0",
29
+ "vite": "^6.0.0",
30
+ "terser": "^5.37.0",
31
+ "vitest": "^3.0.0",
32
+ "happy-dom": "^16.0.0"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "license": "MIT"
38
+ }