@cognitiondesk/widget 1.1.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,531 @@
1
+ const u = "https://mounaji-backendv3.onrender.com", b = `
2
+ :host {
3
+ all: initial;
4
+ font-family: system-ui, sans-serif;
5
+ --cd-offset: clamp(12px, 4vw, 24px);
6
+ --cd-launcher-size: clamp(56px, 14vw, 64px);
7
+ --cd-launcher-gap: 12px;
8
+ --cd-viewport-height: 100vh;
9
+ --cd-safe-top: env(safe-area-inset-top, 0px);
10
+ --cd-safe-right: env(safe-area-inset-right, 0px);
11
+ --cd-safe-bottom: env(safe-area-inset-bottom, 0px);
12
+ --cd-safe-left: env(safe-area-inset-left, 0px);
13
+ }
14
+
15
+ .cd-root {
16
+ position: fixed;
17
+ inset: 0;
18
+ pointer-events: none;
19
+ z-index: 2147483000;
20
+ }
21
+
22
+ .cd-root > * {
23
+ pointer-events: auto;
24
+ }
25
+
26
+ .cd-widget-btn {
27
+ position: fixed;
28
+ bottom: calc(var(--cd-offset) + var(--cd-safe-bottom));
29
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
30
+ z-index: 2147483647;
31
+ width: var(--cd-launcher-size);
32
+ height: var(--cd-launcher-size);
33
+ border-radius: 50%;
34
+ background: var(--cd-primary, #2563eb);
35
+ color: #fff;
36
+ border: none;
37
+ cursor: pointer;
38
+ display: flex;
39
+ align-items: center;
40
+ justify-content: center;
41
+ box-shadow: 0 4px 20px rgba(37,99,235,.45);
42
+ transition: transform .2s, box-shadow .2s;
43
+ touch-action: manipulation;
44
+ }
45
+ .cd-widget-btn:hover { transform: scale(1.08); box-shadow: 0 6px 24px rgba(37,99,235,.55); }
46
+ .cd-widget-btn svg { width: 26px; height: 26px; }
47
+
48
+ .cd-panel {
49
+ position: fixed;
50
+ bottom: calc(var(--cd-offset) + var(--cd-safe-bottom) + var(--cd-launcher-size) + var(--cd-launcher-gap));
51
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
52
+ z-index: 2147483646;
53
+ width: min(380px, calc(100vw - (var(--cd-offset) * 2) - var(--cd-safe-left) - var(--cd-safe-right)));
54
+ height: min(560px, calc(var(--cd-viewport-height) - (var(--cd-offset) * 2) - var(--cd-safe-top) - var(--cd-safe-bottom) - var(--cd-launcher-size) - var(--cd-launcher-gap)));
55
+ max-height: calc(var(--cd-viewport-height) - (var(--cd-offset) * 2) - var(--cd-safe-top) - var(--cd-safe-bottom));
56
+ background: #fff;
57
+ border-radius: 16px;
58
+ box-shadow: 0 12px 40px rgba(0,0,0,.18);
59
+ display: flex;
60
+ flex-direction: column;
61
+ overflow: hidden;
62
+ transform: scale(.96) translateY(8px);
63
+ opacity: 0;
64
+ pointer-events: none;
65
+ transition: opacity .2s, transform .2s;
66
+ overscroll-behavior: contain;
67
+ }
68
+ .cd-panel.open {
69
+ transform: scale(1) translateY(0);
70
+ opacity: 1;
71
+ pointer-events: all;
72
+ }
73
+
74
+ .cd-header {
75
+ background: var(--cd-primary, #2563eb);
76
+ color: #fff;
77
+ padding: 14px 16px;
78
+ display: flex;
79
+ align-items: center;
80
+ gap: 10px;
81
+ flex-shrink: 0;
82
+ }
83
+ .cd-header-avatar {
84
+ width: 36px; height: 36px; border-radius: 50%;
85
+ background: rgba(255,255,255,.25);
86
+ display: flex; align-items: center; justify-content: center;
87
+ font-size: 18px;
88
+ }
89
+ .cd-header-info { flex: 1; min-width: 0; }
90
+ .cd-header-name { font-size: 14px; font-weight: 600; }
91
+ .cd-header-status { font-size: 11px; opacity: .85; display: flex; align-items: center; gap: 4px; }
92
+ .cd-status-dot { width: 7px; height: 7px; border-radius: 50%; background: #4ade80; }
93
+ .cd-close-btn {
94
+ background: none; border: none; color: rgba(255,255,255,.75);
95
+ cursor: pointer; padding: 4px; border-radius: 6px;
96
+ display: flex; align-items: center; justify-content: center;
97
+ }
98
+ .cd-close-btn:hover { color: #fff; background: rgba(255,255,255,.15); }
99
+ .cd-close-btn svg { width: 18px; height: 18px; }
100
+
101
+ .cd-messages {
102
+ flex: 1;
103
+ overflow-y: auto;
104
+ padding: 16px;
105
+ display: flex;
106
+ flex-direction: column;
107
+ gap: 12px;
108
+ background: #f8fafc;
109
+ }
110
+ .cd-msg {
111
+ max-width: 78%;
112
+ padding: 10px 13px;
113
+ border-radius: 14px;
114
+ font-size: 13.5px;
115
+ line-height: 1.5;
116
+ word-break: break-word;
117
+ }
118
+ .cd-msg.user {
119
+ align-self: flex-end;
120
+ background: var(--cd-primary, #2563eb);
121
+ color: #fff;
122
+ border-bottom-right-radius: 4px;
123
+ }
124
+ .cd-msg.assistant {
125
+ align-self: flex-start;
126
+ background: #fff;
127
+ color: #1e293b;
128
+ border-bottom-left-radius: 4px;
129
+ box-shadow: 0 1px 4px rgba(0,0,0,.08);
130
+ }
131
+ .cd-msg.error {
132
+ align-self: flex-start;
133
+ background: #fef2f2;
134
+ color: #b91c1c;
135
+ border-bottom-left-radius: 4px;
136
+ }
137
+ .cd-typing { display: flex; gap: 4px; align-items: center; padding: 4px 0; }
138
+ .cd-typing span {
139
+ width: 7px; height: 7px; background: #94a3b8; border-radius: 50%;
140
+ animation: cd-bounce .9s infinite;
141
+ }
142
+ .cd-typing span:nth-child(2) { animation-delay: .15s; }
143
+ .cd-typing span:nth-child(3) { animation-delay: .3s; }
144
+ @keyframes cd-bounce {
145
+ 0%,60%,100% { transform: translateY(0); }
146
+ 30% { transform: translateY(-5px); }
147
+ }
148
+
149
+ .cd-input-area {
150
+ border-top: 1px solid #e2e8f0;
151
+ padding: 12px;
152
+ padding-bottom: calc(12px + (var(--cd-safe-bottom) * 0.35));
153
+ display: flex;
154
+ gap: 8px;
155
+ align-items: flex-end;
156
+ background: #fff;
157
+ flex-shrink: 0;
158
+ }
159
+ .cd-textarea {
160
+ flex: 1;
161
+ border: 1px solid #e2e8f0;
162
+ border-radius: 10px;
163
+ padding: 9px 12px;
164
+ font-size: 13.5px;
165
+ font-family: inherit;
166
+ resize: none;
167
+ outline: none;
168
+ max-height: 120px;
169
+ line-height: 1.5;
170
+ background: #f8fafc;
171
+ color: #1e293b;
172
+ transition: border-color .15s;
173
+ }
174
+ .cd-textarea:focus { border-color: var(--cd-primary, #2563eb); background: #fff; }
175
+ .cd-send-btn {
176
+ width: 36px; height: 36px;
177
+ background: var(--cd-primary, #2563eb);
178
+ color: #fff;
179
+ border: none;
180
+ border-radius: 10px;
181
+ cursor: pointer;
182
+ display: flex; align-items: center; justify-content: center;
183
+ flex-shrink: 0;
184
+ transition: opacity .15s;
185
+ }
186
+ .cd-send-btn:disabled { opacity: .45; cursor: not-allowed; }
187
+ .cd-send-btn svg { width: 16px; height: 16px; }
188
+
189
+ .cd-powered {
190
+ text-align: center;
191
+ font-size: 10px;
192
+ color: #94a3b8;
193
+ padding: 6px 0;
194
+ background: #fff;
195
+ flex-shrink: 0;
196
+ }
197
+ .cd-powered a { color: #94a3b8; text-decoration: none; }
198
+ .cd-powered a:hover { color: #64748b; }
199
+
200
+ /* Dark theme */
201
+ .cd-dark .cd-panel { background: #1e293b; }
202
+ .cd-dark .cd-messages { background: #0f172a; }
203
+ .cd-dark .cd-msg.assistant { background: #1e293b; color: #f1f5f9; box-shadow: 0 1px 4px rgba(0,0,0,.3); }
204
+ .cd-dark .cd-input-area { background: #1e293b; border-color: #334155; }
205
+ .cd-dark .cd-textarea { background: #0f172a; border-color: #334155; color: #f1f5f9; }
206
+ .cd-dark .cd-textarea:focus { border-color: var(--cd-primary, #3b82f6); }
207
+ .cd-dark .cd-powered { background: #1e293b; }
208
+
209
+ @media (max-width: 640px) {
210
+ .cd-panel {
211
+ left: calc(var(--cd-offset) + var(--cd-safe-left));
212
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
213
+ width: auto;
214
+ height: min(540px, calc(var(--cd-viewport-height) - (var(--cd-offset) * 2) - var(--cd-safe-top) - var(--cd-safe-bottom) - 12px));
215
+ }
216
+ }
217
+
218
+ @media (max-width: 480px) {
219
+ .cd-panel {
220
+ top: var(--cd-safe-top);
221
+ right: 0;
222
+ bottom: 0;
223
+ left: 0;
224
+ width: auto;
225
+ height: calc(var(--cd-viewport-height) - var(--cd-safe-top));
226
+ max-height: calc(var(--cd-viewport-height) - var(--cd-safe-top));
227
+ border-radius: 18px 18px 0 0;
228
+ }
229
+
230
+ .cd-header {
231
+ padding: 16px;
232
+ }
233
+
234
+ .cd-messages {
235
+ padding: 14px;
236
+ }
237
+
238
+ .cd-input-area {
239
+ padding: 10px;
240
+ padding-bottom: calc(10px + var(--cd-safe-bottom));
241
+ }
242
+
243
+ .cd-textarea {
244
+ font-size: 16px;
245
+ }
246
+ }
247
+ `, h = {
248
+ chat: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',
249
+ close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',
250
+ send: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>'
251
+ };
252
+ function _() {
253
+ return "cd_" + Math.random().toString(36).slice(2) + Date.now().toString(36);
254
+ }
255
+ class m {
256
+ constructor(e = {}) {
257
+ if (!e.apiKey) throw new Error("[CognitionDesk] apiKey is required");
258
+ this._cfg = {
259
+ apiKey: e.apiKey,
260
+ widgetId: e.widgetId || null,
261
+ assistantId: e.assistantId || null,
262
+ backendUrl: e.backendUrl || u,
263
+ primaryColor: e.primaryColor || "#2563eb",
264
+ theme: e.theme || "light",
265
+ // 'light' | 'dark' | 'auto'
266
+ botName: e.botName || "AI Assistant",
267
+ botEmoji: e.botEmoji || "🤖",
268
+ welcomeMessage: e.welcomeMessage || "Hello! How can I help you today?",
269
+ placeholder: e.placeholder || "Type a message…",
270
+ position: e.position || "bottom-right",
271
+ streaming: e.streaming !== !1
272
+ // default: true
273
+ }, this._sessionId = _(), this._messages = [], this._open = !1, this._loading = !1, this._container = null, this._shadow = null, this._panel = null, this._messagesEl = null, this._textarea = null, this._sendBtn = null, this._viewportHandler = null;
274
+ }
275
+ // ── Public API ──────────────────────────────────────────────────────────────
276
+ /**
277
+ * Mount the widget.
278
+ * If `widgetId` was provided, fetches the server-side config first (async).
279
+ * Returns a Promise so callers can await full initialisation.
280
+ */
281
+ mount(e) {
282
+ const t = () => {
283
+ const s = e || document.body;
284
+ this._container = document.createElement("div"), this._container.setAttribute("data-cognitiondesk", ""), s.appendChild(this._container), this._shadow = this._container.attachShadow({ mode: "open" });
285
+ const a = document.createElement("style");
286
+ a.textContent = b, this._shadow.appendChild(a), this._buildDOM(), this._applyTheme(), this._syncViewportMetrics(), this._bindViewportMetrics(), this._bindEvents(), this._cfg.welcomeMessage && this._appendMessage("assistant", this._cfg.welcomeMessage, !1);
287
+ };
288
+ return this._cfg.widgetId ? this._fetchWidgetConfig().then(() => t()).catch(() => t()) : (t(), Promise.resolve(this));
289
+ }
290
+ /**
291
+ * Fetch public widget config from the platform and merge into this._cfg.
292
+ * Only fields not already overridden by the constructor are applied.
293
+ */
294
+ async _fetchWidgetConfig() {
295
+ var t;
296
+ const e = `${this._cfg.backendUrl}/platforms/web-widget/public/${this._cfg.widgetId}`;
297
+ try {
298
+ const s = await fetch(e);
299
+ if (!s.ok) return;
300
+ const { config: a } = await s.json();
301
+ if (!a) return;
302
+ a.botName && !this._userSet("botName") && (this._cfg.botName = a.botName), a.welcomeMessage && !this._userSet("welcomeMessage") && (this._cfg.welcomeMessage = a.welcomeMessage), a.primaryColor && !this._userSet("primaryColor") && (this._cfg.primaryColor = a.primaryColor), a.placeholder && !this._userSet("placeholder") && (this._cfg.placeholder = a.placeholder), a.assistantId && !this._cfg.assistantId && (this._cfg.assistantId = a.assistantId), (t = a.avatar) != null && t.value && !this._userSet("botEmoji") && (this._cfg.botEmoji = a.avatar.value);
303
+ } catch {
304
+ }
305
+ }
306
+ // eslint-disable-next-line no-unused-vars
307
+ _userSet(e) {
308
+ return !1;
309
+ }
310
+ unmount() {
311
+ this._unbindViewportMetrics(), this._container && (this._container.remove(), this._container = null);
312
+ }
313
+ open() {
314
+ var e, t;
315
+ this._open = !0, this._syncViewportMetrics(), (e = this._panel) == null || e.classList.add("open"), (t = this._textarea) == null || t.focus();
316
+ }
317
+ close() {
318
+ var e;
319
+ this._open = !1, (e = this._panel) == null || e.classList.remove("open");
320
+ }
321
+ toggle() {
322
+ this._open ? this.close() : this.open();
323
+ }
324
+ clearHistory() {
325
+ this._messages = [], this._messagesEl && (this._messagesEl.innerHTML = ""), this._cfg.welcomeMessage && this._appendMessage("assistant", this._cfg.welcomeMessage);
326
+ }
327
+ // ── DOM ─────────────────────────────────────────────────────────────────────
328
+ _buildDOM() {
329
+ const e = document.createElement("div");
330
+ e.className = "cd-root";
331
+ const t = document.createElement("button");
332
+ t.className = "cd-widget-btn", t.innerHTML = h.chat, t.setAttribute("aria-label", "Open chat"), t.style.setProperty("--cd-primary", this._cfg.primaryColor), this._toggleBtn = t;
333
+ const s = document.createElement("div");
334
+ s.className = "cd-panel", this._panel = s;
335
+ const a = document.createElement("div");
336
+ a.className = "cd-header", a.innerHTML = `
337
+ <div class="cd-header-avatar">${this._cfg.botEmoji}</div>
338
+ <div class="cd-header-info">
339
+ <div class="cd-header-name">${this._escHtml(this._cfg.botName)}</div>
340
+ <div class="cd-header-status">
341
+ <span class="cd-status-dot"></span> Online
342
+ </div>
343
+ </div>
344
+ `;
345
+ const r = document.createElement("button");
346
+ r.className = "cd-close-btn", r.innerHTML = h.close, r.setAttribute("aria-label", "Close chat"), a.appendChild(r), this._closeBtn = r;
347
+ const i = document.createElement("div");
348
+ i.className = "cd-messages", i.setAttribute("role", "log"), i.setAttribute("aria-live", "polite"), this._messagesEl = i;
349
+ const n = document.createElement("div");
350
+ n.className = "cd-input-area";
351
+ const o = document.createElement("textarea");
352
+ o.className = "cd-textarea", o.rows = 1, o.placeholder = this._cfg.placeholder, this._textarea = o;
353
+ const d = document.createElement("button");
354
+ d.className = "cd-send-btn", d.innerHTML = h.send, d.setAttribute("aria-label", "Send"), this._sendBtn = d, n.appendChild(o), n.appendChild(d);
355
+ const l = document.createElement("div");
356
+ l.className = "cd-powered", l.innerHTML = 'Powered by <a href="https://cognitiondesk.com" target="_blank" rel="noopener">CognitionDesk</a>', s.appendChild(a), s.appendChild(i), s.appendChild(n), s.appendChild(l), e.appendChild(t), e.appendChild(s), this._shadow.appendChild(e), this._root = e;
357
+ }
358
+ _applyTheme() {
359
+ var t, s, a;
360
+ (this._cfg.theme === "auto" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : this._cfg.theme) === "dark" && ((t = this._root) == null || t.classList.add("cd-dark")), (s = this._root) == null || s.style.setProperty("--cd-primary", this._cfg.primaryColor), (a = this._panel) == null || a.style.setProperty("--cd-primary", this._cfg.primaryColor);
361
+ }
362
+ // ── Events ──────────────────────────────────────────────────────────────────
363
+ _bindEvents() {
364
+ this._toggleBtn.addEventListener("click", () => this.toggle()), this._closeBtn.addEventListener("click", () => this.close()), this._sendBtn.addEventListener("click", () => this._sendMessage()), this._textarea.addEventListener("keydown", (e) => {
365
+ e.key === "Enter" && !e.shiftKey && (e.preventDefault(), this._sendMessage());
366
+ }), this._textarea.addEventListener("input", () => {
367
+ this._textarea.style.height = "auto", this._textarea.style.height = Math.min(this._textarea.scrollHeight, 120) + "px";
368
+ }), this._textarea.addEventListener("focus", () => {
369
+ this._syncViewportMetrics();
370
+ });
371
+ }
372
+ _bindViewportMetrics() {
373
+ this._viewportHandler || (this._viewportHandler = () => this._syncViewportMetrics(), window.addEventListener("resize", this._viewportHandler, { passive: !0 }), window.addEventListener("orientationchange", this._viewportHandler), window.visualViewport && (window.visualViewport.addEventListener("resize", this._viewportHandler), window.visualViewport.addEventListener("scroll", this._viewportHandler)));
374
+ }
375
+ _unbindViewportMetrics() {
376
+ this._viewportHandler && (window.removeEventListener("resize", this._viewportHandler), window.removeEventListener("orientationchange", this._viewportHandler), window.visualViewport && (window.visualViewport.removeEventListener("resize", this._viewportHandler), window.visualViewport.removeEventListener("scroll", this._viewportHandler)), this._viewportHandler = null);
377
+ }
378
+ _syncViewportMetrics() {
379
+ const e = this._root || this._container;
380
+ if (!e) return;
381
+ const t = window.visualViewport, s = t ? t.height : window.innerHeight;
382
+ e.style.setProperty("--cd-viewport-height", `${Math.round(s)}px`);
383
+ }
384
+ // ── Chat ────────────────────────────────────────────────────────────────────
385
+ async _sendMessage() {
386
+ const e = this._textarea.value.trim();
387
+ if (!(!e || this._loading)) {
388
+ this._textarea.value = "", this._textarea.style.height = "auto", this._loading = !0, this._sendBtn.disabled = !0, this._messages.push({ role: "user", content: e }), this._appendMessage("user", e, !1);
389
+ try {
390
+ if (this._cfg.streaming)
391
+ await this._callApiStream();
392
+ else {
393
+ const t = this._showTyping(), s = await this._callApi();
394
+ this._removeTyping(t), this._messages.push({ role: "assistant", content: s }), this._appendMessage("assistant", s, !0);
395
+ }
396
+ } catch (t) {
397
+ this._appendMessage("error", "Sorry, something went wrong. Please try again.", !1), console.error("[CognitionDesk]", t);
398
+ } finally {
399
+ this._loading = !1, this._sendBtn.disabled = !1, this._textarea.focus();
400
+ }
401
+ }
402
+ }
403
+ _buildRequestBody() {
404
+ return {
405
+ messages: this._messages,
406
+ assistantId: this._cfg.assistantId || void 0,
407
+ userContext: {
408
+ sessionId: this._sessionId,
409
+ assistantId: this._cfg.assistantId || void 0,
410
+ widgetId: this._cfg.widgetId || void 0,
411
+ platform: "cognitiondesk-widget"
412
+ }
413
+ };
414
+ }
415
+ /** Streaming path — uses SSE endpoint */
416
+ async _callApiStream() {
417
+ const e = `${this._cfg.backendUrl}/chat-apiKeyAuth/stream`, t = await fetch(e, {
418
+ method: "POST",
419
+ headers: { "Content-Type": "application/json", "x-api-key": this._cfg.apiKey },
420
+ body: JSON.stringify({ ...this._buildRequestBody(), stream: !0 })
421
+ });
422
+ if (!t.ok) {
423
+ const o = await t.json().catch(() => ({}));
424
+ throw new Error(o.message || `HTTP ${t.status}`);
425
+ }
426
+ const s = document.createElement("div");
427
+ s.className = "cd-msg assistant", s.innerHTML = '<div class="cd-typing"><span></span><span></span><span></span></div>', this._messagesEl.appendChild(s), this._scrollToBottom();
428
+ const a = t.body.getReader(), r = new TextDecoder();
429
+ let i = "", n = !1;
430
+ try {
431
+ for (; ; ) {
432
+ const { done: o, value: d } = await a.read();
433
+ if (o) break;
434
+ const l = r.decode(d, { stream: !0 });
435
+ for (const g of l.split(`
436
+ `)) {
437
+ if (!g.startsWith("data: ")) continue;
438
+ const f = g.slice(6).trim();
439
+ if (f === "[DONE]") break;
440
+ let p;
441
+ try {
442
+ p = JSON.parse(f);
443
+ } catch {
444
+ continue;
445
+ }
446
+ p.type === "content" && p.data && (n || (s.innerHTML = "", n = !0), i += p.data, s.innerHTML = this._renderMarkdown(i), this._scrollToBottom());
447
+ }
448
+ }
449
+ } finally {
450
+ a.releaseLock();
451
+ }
452
+ n || (s.innerHTML = this._renderMarkdown("No response")), i && this._messages.push({ role: "assistant", content: i });
453
+ }
454
+ /** Non-streaming fallback path */
455
+ async _callApi() {
456
+ var a, r, i;
457
+ const e = `${this._cfg.backendUrl}/chat-apiKeyAuth/chat`, t = await fetch(e, {
458
+ method: "POST",
459
+ headers: { "Content-Type": "application/json", "x-api-key": this._cfg.apiKey },
460
+ body: JSON.stringify(this._buildRequestBody())
461
+ });
462
+ if (!t.ok) {
463
+ const n = await t.json().catch(() => ({}));
464
+ throw new Error(n.message || `HTTP ${t.status}`);
465
+ }
466
+ const s = await t.json();
467
+ return s.response || s.message || s.content || ((i = (r = (a = s.choices) == null ? void 0 : a[0]) == null ? void 0 : r.message) == null ? void 0 : i.content) || "No response";
468
+ }
469
+ // ── DOM helpers ─────────────────────────────────────────────────────────────
470
+ _appendMessage(e, t, s = !0) {
471
+ const a = document.createElement("div");
472
+ a.className = `cd-msg ${e}`, s && e !== "user" ? a.innerHTML = this._renderMarkdown(t) : a.textContent = t, this._messagesEl.appendChild(a), this._scrollToBottom();
473
+ }
474
+ /** Minimal, safe markdown → HTML renderer (no dependencies). */
475
+ _renderMarkdown(e) {
476
+ if (!e) return "";
477
+ let t = this._escHtml(e);
478
+ return t = t.replace(
479
+ /```[\w]*\n?([\s\S]*?)```/g,
480
+ (s, a) => `<pre style="background:#0f172a;color:#e2e8f0;padding:10px;border-radius:6px;font-size:12px;overflow-x:auto;margin:6px 0;white-space:pre-wrap">${a.trim()}</pre>`
481
+ ), t = t.replace(/`([^`]+)`/g, '<code style="background:rgba(0,0,0,.08);padding:1px 5px;border-radius:4px;font-size:.9em">$1</code>'), t = t.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>"), t = t.replace(/__([^_]+)__/g, "<strong>$1</strong>"), t = t.replace(/\*([^*]+)\*/g, "<em>$1</em>"), t = t.replace(/_([^_]+)_/g, "<em>$1</em>"), t = t.replace(
482
+ /\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,
483
+ '<a href="$2" target="_blank" rel="noopener" style="color:var(--cd-primary,#2563eb)">$1</a>'
484
+ ), t = t.replace(/\n/g, "<br>"), t;
485
+ }
486
+ _showTyping() {
487
+ const e = document.createElement("div");
488
+ return e.className = "cd-msg assistant", e.innerHTML = '<div class="cd-typing"><span></span><span></span><span></span></div>', this._messagesEl.appendChild(e), this._scrollToBottom(), e;
489
+ }
490
+ _removeTyping(e) {
491
+ e == null || e.remove();
492
+ }
493
+ _scrollToBottom() {
494
+ this._messagesEl && (this._messagesEl.scrollTop = this._messagesEl.scrollHeight);
495
+ }
496
+ _escHtml(e) {
497
+ return String(e).replace(/[&<>"']/g, (t) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[t]);
498
+ }
499
+ }
500
+ function w(c) {
501
+ const e = new m(c);
502
+ return e.mount(), e;
503
+ }
504
+ if (typeof document < "u") {
505
+ const c = () => {
506
+ document.querySelectorAll("script[data-api-key]").forEach((e) => {
507
+ const t = e.getAttribute("data-api-key");
508
+ if (!t) return;
509
+ const s = e.getAttribute("data-widget-id") || void 0, a = e.getAttribute("data-streaming"), r = new m({
510
+ apiKey: t,
511
+ widgetId: s,
512
+ assistantId: e.getAttribute("data-assistant-id") || void 0,
513
+ theme: e.getAttribute("data-theme") || "light",
514
+ primaryColor: e.getAttribute("data-primary-color") || "#2563eb",
515
+ botName: e.getAttribute("data-bot-name") || "AI Assistant",
516
+ botEmoji: e.getAttribute("data-bot-emoji") || void 0,
517
+ welcomeMessage: e.getAttribute("data-welcome-message") || void 0,
518
+ placeholder: e.getAttribute("data-placeholder") || void 0,
519
+ backendUrl: e.getAttribute("data-backend-url") || void 0,
520
+ streaming: a === null ? !0 : a !== "false"
521
+ });
522
+ Promise.resolve(r.mount());
523
+ });
524
+ };
525
+ document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", c) : c();
526
+ }
527
+ export {
528
+ m as CognitionDeskWidget,
529
+ m as default,
530
+ w as init
531
+ };