@onedeskpro/chatbot-core 0.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,129 @@
1
+ import { ApiError } from '@onedeskpro/chatbot-types';
2
+ import { ApiResponse } from '@onedeskpro/chatbot-types';
3
+ import { ChatbotBlockReason } from '@onedeskpro/chatbot-types';
4
+ import { ChatbotEventMap } from '@onedeskpro/chatbot-types';
5
+ import { ChatbotInitOptions } from '@onedeskpro/chatbot-types';
6
+ import { ChatbotState } from '@onedeskpro/chatbot-types';
7
+ import { ChatMessage } from '@onedeskpro/chatbot-types';
8
+ import { ChatRequest } from '@onedeskpro/chatbot-types';
9
+ import { ChatResponseData } from '@onedeskpro/chatbot-types';
10
+ import { SdkConfigResponse } from '@onedeskpro/chatbot-types';
11
+
12
+ export declare class ApiClient {
13
+ private baseUrl;
14
+ private apiKey;
15
+ private timeoutMs;
16
+ constructor(options: ApiClientOptions);
17
+ private fail;
18
+ private request;
19
+ sendMessage(payload: ChatRequest): Promise<ChatResponseData>;
20
+ fetchHistory(sessionId: string): Promise<ChatMessage[]>;
21
+ fetchConfig(): Promise<SdkConfigResponse>;
22
+ }
23
+
24
+ declare interface ApiClientOptions {
25
+ baseUrl: string;
26
+ apiKey: string;
27
+ /** Abort a request that has not responded within this many milliseconds. */
28
+ timeoutMs?: number;
29
+ }
30
+
31
+ export { ApiError }
32
+
33
+ export { ApiResponse }
34
+
35
+ export { ChatbotBlockReason }
36
+
37
+ export declare class ChatbotCore {
38
+ private apiClient;
39
+ private emitter;
40
+ private session;
41
+ private widget;
42
+ private options;
43
+ private callerSetName;
44
+ /**
45
+ * Bumped by every init() and by destroy(). An async init compares the token it
46
+ * started with against this before touching anything, so a superseded run — a
47
+ * React StrictMode remount, or a caller re-initialising — quietly stands down
48
+ * instead of racing the live one.
49
+ */
50
+ private initToken;
51
+ private _state;
52
+ /**
53
+ * The single place state is written. Replaces `_state` rather than mutating it
54
+ * and announces the change, so subscribers (React especially) stay in sync with
55
+ * everything — not just the transitions that have a dedicated event.
56
+ */
57
+ private setState;
58
+ init(options: ChatbotInitOptions): Promise<void>;
59
+ /** Returns null on failure — a network blip must not block the user from trying. */
60
+ private fetchConfig;
61
+ sendMessage(text: string): Promise<void>;
62
+ private loadHistory;
63
+ on<K extends keyof ChatbotEventMap>(event: K, listener: Listener<K>): () => void;
64
+ resetSession(): void;
65
+ open(): void;
66
+ close(): void;
67
+ toggle(): void;
68
+ getState(): Readonly<ChatbotState>;
69
+ /**
70
+ * Unmounts the widget and cancels any in-flight init. Subscriptions are left
71
+ * alone on purpose: they belong to whoever registered them, and tearing them
72
+ * down here would silently kill listeners this instance does not own — every
73
+ * useChatbot() in the tree, for one. They are released with the instance.
74
+ */
75
+ destroy(): void;
76
+ }
77
+
78
+ export { ChatbotEventMap }
79
+
80
+ export { ChatbotInitOptions }
81
+
82
+ /** An Error carrying the API's structured error body and the HTTP status. */
83
+ export declare interface ChatbotRequestError extends Error {
84
+ apiError: ApiError;
85
+ status: number;
86
+ }
87
+
88
+ export { ChatbotState }
89
+
90
+ export { ChatMessage }
91
+
92
+ export { ChatRequest }
93
+
94
+ export { ChatResponseData }
95
+
96
+ /** Default OneDesk Pro API origin when `apiBaseUrl` is omitted from init options. */
97
+ export declare const DEFAULT_API_BASE_URL: "https://api.onedeskpro.com";
98
+
99
+ export declare const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
100
+
101
+ export declare class EventEmitter {
102
+ private readonly _listeners;
103
+ on<K extends keyof ChatbotEventMap>(event: K, listener: Listener_2<ChatbotEventMap[K]>): () => void;
104
+ off<K extends keyof ChatbotEventMap>(event: K, listener: Listener_2<ChatbotEventMap[K]>): void;
105
+ emit<K extends keyof ChatbotEventMap>(event: K, ...args: ChatbotEventMap[K] extends void ? [] : [ChatbotEventMap[K]]): void;
106
+ removeAllListeners(): void;
107
+ }
108
+
109
+ declare type Listener<K extends keyof ChatbotEventMap> = ChatbotEventMap[K] extends void ? () => void : (payload: ChatbotEventMap[K]) => void;
110
+
111
+ declare type Listener_2<T> = T extends void ? () => void : (payload: T) => void;
112
+
113
+ export declare const OnedeskProChatbot: {
114
+ init(options: ChatbotInitOptions): Promise<ChatbotCore>;
115
+ getInstance(): ChatbotCore | null;
116
+ };
117
+
118
+ export { SdkConfigResponse }
119
+
120
+ export declare class SessionManager {
121
+ private sessionId;
122
+ init(providedSessionId?: string): string;
123
+ get(): string | null;
124
+ reset(): string;
125
+ private persist;
126
+ private generateId;
127
+ }
128
+
129
+ export { }
@@ -0,0 +1,265 @@
1
+ var OnedeskProChatbot=function(h){"use strict";function S(i){return typeof i=="object"&&i!==null&&typeof i.message=="string"}class f{constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,""),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??3e4}fail(t,e,n,s){const a={statusCode:e,message:t,code:n,timestamp:new Date().toISOString(),path:s};throw Object.assign(new Error(t),{apiError:a,status:e})}async request(t,e,n,s){const a=new URL(`${this.baseUrl}${e}`);if(s)for(const[u,P]of Object.entries(s))a.searchParams.set(u,P);const l={"Content-Type":"application/json","X-API-Key":this.apiKey},r=new AbortController,o=setTimeout(()=>r.abort(),this.timeoutMs);let c;try{c=await fetch(a.toString(),{method:t,headers:l,signal:r.signal,...n!==void 0?{body:JSON.stringify(n)}:{}})}catch(u){r.signal.aborted&&this.fail(`Request timed out after ${this.timeoutMs}ms.`,0,"TIMEOUT",e),this.fail(u instanceof Error?u.message:"Network request failed.",0,"NETWORK_ERROR",e)}finally{clearTimeout(o)}const d=await c.text();let p=null;if(d)try{p=JSON.parse(d)}catch{p=null}if(!c.ok){if(S(p))throw Object.assign(new Error(p.message),{apiError:p,status:c.status});this.fail(`Request failed with status ${c.status} ${c.statusText}`.trim(),c.status,"HTTP_ERROR",e)}return p===null&&this.fail("The server returned an empty or malformed response.",c.status,"BAD_RESPONSE",e),p.data}async sendMessage(t){return this.request("POST","/sdk/chat",t)}async fetchHistory(t){return this.request("GET","/sdk/chat-history",void 0,{sessionId:t})}async fetchConfig(){return this.request("GET","/sdk/config")}}const x="https://api.onedeskpro.com";class w{constructor(){this._listeners={}}on(t,e){return this._listeners[t]||(this._listeners[t]=[]),this._listeners[t].push(e),()=>this.off(t,e)}off(t,e){const n=this._listeners[t];n&&(this._listeners[t]=n.filter(s=>s!==e))}emit(t,...e){const n=this._listeners[t];if(n)for(const s of n)s(...e)}removeAllListeners(){for(const t of Object.keys(this._listeners))delete this._listeners[t]}}const y="onedeskpro_chatbot_session_id";function M(i){try{return typeof window<"u"?window.localStorage.getItem(i):null}catch{return null}}function I(i,t){try{typeof window<"u"&&window.localStorage.setItem(i,t)}catch{}}class v{constructor(){this.sessionId=null}init(t){if(t)return this.sessionId=t,this.persist(),this.sessionId;const e=M(y);return e?this.sessionId=e:(this.sessionId=this.generateId(),this.persist()),this.sessionId}get(){return this.sessionId}reset(){return this.sessionId=this.generateId(),this.persist(),this.sessionId}persist(){this.sessionId&&I(y,this.sessionId)}generateId(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2)+Date.now().toString(36)}}function _(i,t){const e=`
2
+ --ttcb-bg: #ffffff;
3
+ --ttcb-bg-secondary: #f3f4f6;
4
+ --ttcb-text: #111827;
5
+ --ttcb-text-muted: #6b7280;
6
+ --ttcb-border: #e5e7eb;
7
+ --ttcb-user-bubble: ${i};
8
+ --ttcb-user-text: #ffffff;
9
+ --ttcb-ai-bubble: #f3f4f6;
10
+ --ttcb-ai-text: #111827;
11
+ --ttcb-input-bg: #ffffff;
12
+ --ttcb-shadow: 0 20px 60px rgba(0,0,0,0.15);
13
+ `,n=`
14
+ --ttcb-bg: #1f2937;
15
+ --ttcb-bg-secondary: #111827;
16
+ --ttcb-text: #f9fafb;
17
+ --ttcb-text-muted: #9ca3af;
18
+ --ttcb-border: #374151;
19
+ --ttcb-user-bubble: ${i};
20
+ --ttcb-user-text: #ffffff;
21
+ --ttcb-ai-bubble: #374151;
22
+ --ttcb-ai-text: #f9fafb;
23
+ --ttcb-input-bg: #111827;
24
+ --ttcb-shadow: 0 20px 60px rgba(0,0,0,0.4);
25
+ `;let s;return t==="dark"?s=`:host { ${n} }`:t==="light"?s=`:host { ${e} }`:s=`
26
+ :host { ${e} }
27
+ @media (prefers-color-scheme: dark) { :host { ${n} } }
28
+ `,`
29
+ ${s}
30
+
31
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
32
+
33
+ .ttcb-fab {
34
+ position: fixed;
35
+ width: 56px; height: 56px;
36
+ border-radius: 50%;
37
+ background: ${i};
38
+ border: none; cursor: pointer;
39
+ display: flex; align-items: center; justify-content: center;
40
+ box-shadow: 0 4px 20px rgba(0,0,0,0.2);
41
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
42
+ z-index: 9999;
43
+ }
44
+ .ttcb-fab:hover { transform: scale(1.08); box-shadow: 0 6px 24px rgba(0,0,0,0.25); }
45
+ .ttcb-fab svg { width: 24px; height: 24px; fill: #fff; }
46
+ .ttcb-fab.bottom-right { bottom: 24px; right: 24px; }
47
+ .ttcb-fab.bottom-left { bottom: 24px; left: 24px; }
48
+
49
+ .ttcb-panel {
50
+ position: fixed;
51
+ width: 380px; height: 560px;
52
+ background: var(--ttcb-bg);
53
+ border: 1px solid var(--ttcb-border);
54
+ border-radius: 16px;
55
+ display: flex; flex-direction: column;
56
+ box-shadow: var(--ttcb-shadow);
57
+ overflow: hidden;
58
+ z-index: 9998;
59
+ transition: opacity 0.2s ease, transform 0.25s ease;
60
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
61
+ }
62
+ .ttcb-panel.bottom-right { bottom: 92px; right: 24px; }
63
+ .ttcb-panel.bottom-left { bottom: 92px; left: 24px; }
64
+ .ttcb-panel.hidden {
65
+ opacity: 0; pointer-events: none;
66
+ transform: translateY(12px) scale(0.97);
67
+ }
68
+
69
+ .ttcb-header {
70
+ padding: 14px 16px;
71
+ border-bottom: 1px solid var(--ttcb-border);
72
+ display: flex; align-items: center; gap: 10px;
73
+ background: var(--ttcb-bg);
74
+ flex-shrink: 0;
75
+ }
76
+ .ttcb-avatar {
77
+ width: 32px; height: 32px; border-radius: 50%;
78
+ background: ${i}22;
79
+ display: flex; align-items: center; justify-content: center;
80
+ flex-shrink: 0;
81
+ }
82
+ .ttcb-avatar svg { width: 16px; height: 16px; fill: ${i}; }
83
+ .ttcb-header-title { font-weight: 600; font-size: 14px; color: var(--ttcb-text); flex: 1; }
84
+ .ttcb-close-btn, .ttcb-new-session-btn {
85
+ background: none; border: none; cursor: pointer;
86
+ color: var(--ttcb-text-muted); padding: 4px; border-radius: 6px;
87
+ display: flex; align-items: center; justify-content: center;
88
+ }
89
+ .ttcb-close-btn:hover, .ttcb-new-session-btn:hover { background: var(--ttcb-bg-secondary); }
90
+ .ttcb-close-btn svg { width: 18px; height: 18px; fill: currentColor; }
91
+ .ttcb-new-session-btn svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; }
92
+
93
+ .ttcb-messages {
94
+ flex: 1; overflow-y: auto; padding: 16px;
95
+ display: flex; flex-direction: column; gap: 12px;
96
+ scroll-behavior: smooth;
97
+ font-size: 14px;
98
+ }
99
+
100
+ .ttcb-empty {
101
+ display: flex; flex-direction: column; align-items: center;
102
+ justify-content: center; text-align: center;
103
+ padding: 32px 16px; flex: 1;
104
+ color: var(--ttcb-text-muted); font-size: 13px;
105
+ }
106
+ .ttcb-empty-icon {
107
+ width: 48px; height: 48px; border-radius: 50%;
108
+ background: var(--ttcb-bg-secondary);
109
+ display: flex; align-items: center; justify-content: center;
110
+ margin-bottom: 12px;
111
+ }
112
+ .ttcb-empty-icon svg { width: 22px; height: 22px; fill: var(--ttcb-text-muted); }
113
+ .ttcb-empty strong { color: var(--ttcb-text); }
114
+
115
+ .ttcb-initial-loading {
116
+ display: flex; flex-direction: column; align-items: center;
117
+ justify-content: center; flex: 1; padding: 32px 16px;
118
+ color: var(--ttcb-text-muted); font-size: 13px;
119
+ }
120
+ .ttcb-spinner {
121
+ width: 24px; height: 24px;
122
+ border: 2px solid var(--ttcb-border);
123
+ border-top-color: var(--ttcb-text-muted);
124
+ border-radius: 50%;
125
+ animation: ttcb-spin 0.7s linear infinite;
126
+ margin-bottom: 10px;
127
+ }
128
+ @keyframes ttcb-spin { to { transform: rotate(360deg); } }
129
+
130
+ .ttcb-blocked {
131
+ display: flex; flex-direction: column; align-items: center;
132
+ justify-content: center; text-align: center;
133
+ padding: 32px 20px; flex: 1;
134
+ }
135
+ .ttcb-blocked-icon {
136
+ width: 44px; height: 44px; border-radius: 50%;
137
+ background: var(--ttcb-bg-secondary);
138
+ display: flex; align-items: center; justify-content: center;
139
+ margin-bottom: 14px;
140
+ }
141
+ .ttcb-blocked-icon svg { width: 20px; height: 20px; fill: var(--ttcb-text-muted); }
142
+ .ttcb-blocked-title { font-size: 14px; font-weight: 600; color: var(--ttcb-text); margin-bottom: 8px; }
143
+ .ttcb-blocked-desc { font-size: 12px; color: var(--ttcb-text-muted); line-height: 1.5; max-width: 220px; }
144
+
145
+ .ttcb-msg { display: flex; gap: 8px; max-width: 100%; }
146
+ .ttcb-msg.human { flex-direction: row-reverse; }
147
+ .ttcb-msg-avatar {
148
+ width: 28px; height: 28px; border-radius: 50%;
149
+ background: var(--ttcb-bg-secondary);
150
+ display: flex; align-items: center; justify-content: center;
151
+ flex-shrink: 0; margin-top: 2px;
152
+ }
153
+ .ttcb-msg-avatar svg { width: 13px; height: 13px; fill: var(--ttcb-text-muted); }
154
+ .ttcb-bubble {
155
+ max-width: 78%; padding: 9px 13px;
156
+ border-radius: 16px 16px 16px 4px;
157
+ line-height: 1.5;
158
+ color: var(--ttcb-ai-text);
159
+ background: var(--ttcb-ai-bubble);
160
+ white-space: pre-wrap; word-break: break-word;
161
+ font-size: 14px;
162
+ }
163
+ .ttcb-msg.human .ttcb-bubble {
164
+ background: var(--ttcb-user-bubble);
165
+ color: var(--ttcb-user-text);
166
+ border-radius: 16px 16px 4px 16px;
167
+ }
168
+
169
+ /* Markdown styles inside AI bubble */
170
+ .ttcb-bubble p { margin: 0 0 6px 0; }
171
+ .ttcb-bubble p:last-child { margin-bottom: 0; }
172
+ .ttcb-bubble strong { font-weight: 600; }
173
+ .ttcb-bubble em { font-style: italic; }
174
+ .ttcb-bubble code {
175
+ background: rgba(0,0,0,0.08);
176
+ padding: 1px 5px; border-radius: 3px;
177
+ font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;
178
+ font-size: 12px;
179
+ }
180
+ .ttcb-bubble pre {
181
+ background: rgba(0,0,0,0.08);
182
+ padding: 10px 12px; border-radius: 6px;
183
+ overflow-x: auto; margin: 6px 0;
184
+ }
185
+ .ttcb-bubble pre code { background: none; padding: 0; font-size: 12px; }
186
+ .ttcb-bubble h1, .ttcb-bubble h2, .ttcb-bubble h3 {
187
+ font-weight: 600; margin: 8px 0 4px; line-height: 1.3;
188
+ }
189
+ .ttcb-bubble h1 { font-size: 15px; }
190
+ .ttcb-bubble h2 { font-size: 14px; }
191
+ .ttcb-bubble h3 { font-size: 13px; }
192
+ .ttcb-bubble ul, .ttcb-bubble ol { padding-left: 18px; margin: 4px 0; }
193
+ .ttcb-bubble li { margin: 2px 0; }
194
+ .ttcb-bubble a { color: inherit; text-decoration: underline; }
195
+
196
+ .ttcb-typing { display: flex; gap: 4px; padding: 8px 2px; align-items: center; }
197
+ .ttcb-typing span {
198
+ width: 6px; height: 6px; border-radius: 50%;
199
+ background: var(--ttcb-text-muted);
200
+ animation: ttcb-bounce 1.2s infinite;
201
+ }
202
+ .ttcb-typing span:nth-child(2) { animation-delay: 0.15s; }
203
+ .ttcb-typing span:nth-child(3) { animation-delay: 0.3s; }
204
+ @keyframes ttcb-bounce {
205
+ 0%, 80%, 100% { transform: translateY(0); opacity: 0.4; }
206
+ 40% { transform: translateY(-5px); opacity: 1; }
207
+ }
208
+
209
+ .ttcb-footer {
210
+ border-top: 1px solid var(--ttcb-border);
211
+ padding: 12px;
212
+ background: var(--ttcb-bg);
213
+ flex-shrink: 0;
214
+ }
215
+ .ttcb-form { display: flex; gap: 8px; }
216
+ .ttcb-input {
217
+ flex: 1; padding: 9px 12px;
218
+ border: 1px solid var(--ttcb-border);
219
+ border-radius: 8px;
220
+ font-size: 14px; outline: none;
221
+ background: var(--ttcb-input-bg);
222
+ color: var(--ttcb-text);
223
+ transition: border-color 0.15s;
224
+ font-family: inherit;
225
+ }
226
+ .ttcb-input:focus { border-color: ${i}; }
227
+ .ttcb-input::placeholder { color: var(--ttcb-text-muted); }
228
+ .ttcb-input:disabled { opacity: 0.6; cursor: not-allowed; }
229
+ .ttcb-send-btn {
230
+ padding: 0 14px; height: 38px;
231
+ background: ${i}; color: #fff;
232
+ border: none; border-radius: 8px; cursor: pointer;
233
+ display: flex; align-items: center; justify-content: center;
234
+ transition: opacity 0.15s; flex-shrink: 0;
235
+ }
236
+ .ttcb-send-btn:hover { opacity: 0.9; }
237
+ .ttcb-send-btn:disabled { opacity: 0.5; cursor: not-allowed; }
238
+ .ttcb-send-btn svg { width: 16px; height: 16px; fill: #fff; }
239
+
240
+ @media (max-width: 440px) {
241
+ .ttcb-panel { width: calc(100vw - 16px); right: 8px !important; left: 8px !important; bottom: 84px !important; }
242
+ .ttcb-fab.bottom-right { right: 16px; }
243
+ .ttcb-fab.bottom-left { left: 16px; }
244
+ }
245
+ `}function g(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function L(i){const t=[];let e=i.replace(/```[\w]*\n?([\s\S]*?)```/g,(r,o)=>{const c=t.length;return t.push(`<pre><code>${g(o.trim())}</code></pre>`),`${c}`});e=e.replace(/`([^`\n]+)`/g,(r,o)=>{const c=t.length;return t.push(`<code>${g(o)}</code>`),`${c}`}),e=g(e);const n=e.split(`
246
+ `),s=[];let a="";const l=()=>{a&&(s.push(`</${a}>`),a="")};for(const r of n){let o;(o=r.match(/^### (.+)/))?(l(),s.push(`<h3>${o[1]}</h3>`)):(o=r.match(/^## (.+)/))?(l(),s.push(`<h2>${o[1]}</h2>`)):(o=r.match(/^# (.+)/))?(l(),s.push(`<h1>${o[1]}</h1>`)):(o=r.match(/^[*-] (.+)/))?(a!=="ul"&&(l(),s.push("<ul>"),a="ul"),s.push(`<li>${o[1]}</li>`)):(o=r.match(/^\d+\. (.+)/))?(a!=="ol"&&(l(),s.push("<ol>"),a="ol"),s.push(`<li>${o[1]}</li>`)):(l(),s.push(r))}return l(),e=s.join(`
247
+ `),e=e.replace(/\*\*(.+?)\*\*/gs,"<strong>$1</strong>").replace(/__(.+?)__/gs,"<strong>$1</strong>").replace(/\*(.+?)\*/gs,"<em>$1</em>").replace(/_(.+?)_/gs,"<em>$1</em>").replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.split(/\n{2,}/).map(r=>{const o=r.trim();return o?/^<(h[1-3]|ul|ol|pre|li)/.test(o)?o:o.split(/(\x04\d+\x05)/g).map(c=>{if(/^\x04\d+\x05$/.test(c))return c;const d=c.trim();return d?`<p>${d.replace(/\n/g,"<br>")}</p>`:""}).join(""):""}).filter(Boolean).join(""),e=e.replace(/\x04(\d+)\x05/g,(r,o)=>t[+o]??"").replace(/\x02(\d+)\x03/g,(r,o)=>t[+o]??""),e}function N(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
248
+ <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"/>
249
+ </svg>`}function E(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
250
+ <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/>
251
+ </svg>`}function A(){return`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">
252
+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
253
+ <line x1="12" y1="8" x2="12" y2="14"/>
254
+ <line x1="9" y1="11" x2="15" y2="11"/>
255
+ </svg>`}function O(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
256
+ <path d="M20 2H4C2.9 2 2 2.9 2 4v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
257
+ </svg>`}function B(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
258
+ <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 12z"/>
259
+ </svg>`}function $(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
260
+ <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
261
+ </svg>`}function b(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
262
+ <path d="M20 9V7c0-1.1-.9-2-2-2h-3c0-1.66-1.34-3-3-3S9 3.34 9 5H6c-1.1 0-2 .9-2 2v2c-1.66 0-3 1.34-3 3s1.34 3 3 3v4c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-4c1.66 0 3-1.34 3-3s-1.34-3-3-3zm-2 10H6V7h12v12zm-9-6c-.83 0-1.5-.67-1.5-1.5S8.17 10 9 10s1.5.67 1.5 1.5S9.83 13 9 13zm6 0c-.83 0-1.5-.67-1.5-1.5S14.17 10 15 10s1.5.67 1.5 1.5S15.83 13 15 13z"/>
263
+ </svg>`}function H(){return`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
264
+ <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
265
+ </svg>`}function C(i,t){const e=document.createElement("div");e.className=`ttcb-msg ${t}`;const n=document.createElement("div");n.className="ttcb-msg-avatar",n.innerHTML=t==="human"?H():b();const s=document.createElement("div");return s.className="ttcb-bubble",t==="human"?s.textContent=i:s.innerHTML=L(i),e.appendChild(n),e.appendChild(s),e}function z(){const i=document.createElement("div");i.className="ttcb-msg ai",i.id="ttcb-typing";const t=document.createElement("div");t.className="ttcb-msg-avatar",t.innerHTML=b();const e=document.createElement("div");return e.className="ttcb-typing",e.innerHTML="<span></span><span></span><span></span>",i.appendChild(t),i.appendChild(e),i}class U{constructor(t,e){this.isOpen=!1,this.destroyed=!1,this.position=t.position??"bottom-right",this.callbacks=e,this.mount(t)}mount(t){this.host=document.createElement("div"),this.host.id="onedeskpro-chatbot-host",this.shadow=this.host.attachShadow({mode:"closed"});const e=document.createElement("style");e.textContent=_(t.primaryColor??"#2563EB",t.theme??"auto"),this.shadow.appendChild(e);const n=document.createElement("button");n.className=`ttcb-fab ${this.position}`,n.setAttribute("aria-label","Open chat"),n.innerHTML=O(),n.addEventListener("click",()=>this.toggle()),this.shadow.appendChild(n),this.panel=document.createElement("div"),this.panel.className=`ttcb-panel ${this.position} hidden`,this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-modal","true"),this.panel.setAttribute("aria-label",t.chatbotName??"AI Assistant");const s=document.createElement("div");s.className="ttcb-header";const a=document.createElement("div");a.className="ttcb-avatar",a.innerHTML=b();const l=document.createElement("span");l.className="ttcb-header-title",l.textContent=t.chatbotName??"AI Assistant";const r=document.createElement("button");r.className="ttcb-new-session-btn",r.setAttribute("aria-label","New conversation"),r.title="New conversation",r.innerHTML=A(),r.addEventListener("click",()=>this.callbacks.onReset());const o=document.createElement("button");o.className="ttcb-close-btn",o.setAttribute("aria-label","Close chat"),o.innerHTML=B(),o.addEventListener("click",()=>this.close()),s.appendChild(a),s.appendChild(l),s.appendChild(r),s.appendChild(o),this.panel.appendChild(s),this.messagesContainer=document.createElement("div"),this.messagesContainer.className="ttcb-messages",this.messagesContainer.setAttribute("aria-live","polite"),this.messagesContainer.setAttribute("aria-label","Chat messages"),this.panel.appendChild(this.messagesContainer);const c=document.createElement("div");c.className="ttcb-footer";const d=document.createElement("form");d.className="ttcb-form",d.addEventListener("submit",p=>{p.preventDefault(),this.handleSend()}),this.input=document.createElement("input"),this.input.type="text",this.input.className="ttcb-input",this.input.placeholder=t.placeholder??"Type your message…",this.input.setAttribute("aria-label","Message input"),this.input.setAttribute("autocomplete","off"),this.sendBtn=document.createElement("button"),this.sendBtn.type="submit",this.sendBtn.className="ttcb-send-btn",this.sendBtn.innerHTML=$(),this.sendBtn.setAttribute("aria-label","Send message"),d.appendChild(this.input),d.appendChild(this.sendBtn),c.appendChild(d),this.panel.appendChild(c),this.shadow.appendChild(this.panel),this.attachToDocument(),this.showInitialLoading(),t.autoOpen&&this.open()}attachToDocument(){const t=()=>{this.destroyed||(document.body??document.documentElement).appendChild(this.host)};document.body?t():document.addEventListener("DOMContentLoaded",t,{once:!0})}showInitialLoading(){this.messagesContainer.innerHTML="",this.input.disabled=!0,this.sendBtn.disabled=!0;const t=document.createElement("div");t.className="ttcb-initial-loading",t.id="ttcb-initial-loading";const e=document.createElement("div");e.className="ttcb-spinner";const n=document.createElement("p");n.textContent="Loading…",t.appendChild(e),t.appendChild(n),this.messagesContainer.appendChild(t)}showEmptyState(t){const e=document.createElement("div");e.className="ttcb-empty",e.id="ttcb-empty";const n=document.createElement("div");n.className="ttcb-empty-icon",n.innerHTML=b();const s=document.createElement("p"),a=document.createElement("strong");a.textContent=t,s.appendChild(document.createTextNode("Welcome to ")),s.appendChild(a);const l=document.createElement("p");l.textContent="Ask me anything — I'm here to help!",l.style.marginTop="6px",l.style.fontSize="12px",e.appendChild(n),e.appendChild(s),e.appendChild(l),this.messagesContainer.appendChild(e)}removeEmptyState(){const t=this.shadow.getElementById("ttcb-empty");t&&t.remove()}handleSend(){const t=this.input.value.trim();t&&(this.input.value="",this.callbacks.onSend(t))}appendMessage(t){this.removeEmptyState();const e="message"in t?t.message:t,n=C(e.content,e.type);this.messagesContainer.appendChild(n),this.scrollToBottom()}setMessages(t){if(this.messagesContainer.innerHTML="",t.length!==0){for(const e of t){const n=C(e.message.content,e.message.type);this.messagesContainer.appendChild(n)}this.scrollToBottom()}}setLoading(t){if(this.sendBtn.disabled=t,this.input.disabled=t,t)this.shadow.getElementById("ttcb-typing")||(this.messagesContainer.appendChild(z()),this.scrollToBottom());else{const e=this.shadow.getElementById("ttcb-typing");e&&e.remove()}}open(){this.isOpen=!0,this.panel.classList.remove("hidden"),this.input.focus(),this.callbacks.onOpen()}close(){this.isOpen=!1,this.panel.classList.add("hidden"),this.callbacks.onClose()}toggle(){this.isOpen?this.close():this.open()}readyToChat(t){this.messagesContainer.innerHTML="",this.input.disabled=!1,this.sendBtn.disabled=!1;const e=this.shadow.querySelector(".ttcb-header-title");e&&t.chatbotName&&(e.textContent=t.chatbotName),t.welcomeMessage?this.appendMessage({type:"ai",content:t.welcomeMessage}):this.showEmptyState(t.chatbotName??"AI Assistant")}showBlocked(t){this.messagesContainer.innerHTML="";const e=document.createElement("div");e.className="ttcb-blocked";const n=document.createElement("div");n.className="ttcb-blocked-icon";const s=document.createElement("p");s.className="ttcb-blocked-title";const a=document.createElement("p");a.className="ttcb-blocked-desc",t==="no-prompt"?(n.innerHTML=E(),s.textContent="Business Context Required",a.textContent="Add a system prompt for this agent in the admin panel."):t==="no-directories"?(n.innerHTML=E(),s.textContent="Knowledge Base Required",a.textContent="Assign at least one knowledge-base directory to this agent in the admin panel."):(n.innerHTML=N(),s.textContent="Chatbot Settings Required",a.textContent="The chatbot has not been configured yet. Please set it up in the admin panel."),e.appendChild(n),e.appendChild(s),e.appendChild(a),this.messagesContainer.appendChild(e)}clearMessages(t){this.messagesContainer.innerHTML="",this.showEmptyState(t)}destroy(){this.destroyed=!0,this.host.remove()}scrollToBottom(){this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight}}const R={apiBaseUrl:x,chatbotName:"AI Assistant",primaryColor:"#2563EB",theme:"auto",position:"bottom-right",welcomeMessage:"",placeholder:"Type your message…",autoOpen:!1,sessionId:"",requestTimeoutMs:3e4};function j(i){return Object.fromEntries(Object.entries(i).filter(([,t])=>t!==void 0))}let D=0;const k=()=>Date.now()*1e3+D++%1e3;class T{constructor(){this.emitter=new w,this.session=new v,this.widget=null,this.callerSetName=!1,this.initToken=0,this._state={isOpen:!1,isLoading:!1,isReady:!1,blockReason:null,messages:[],sessionId:null,error:null}}setState(t){this._state={...this._state,...t},this.emitter.emit("state-change",this._state)}async init(t){var l,r,o;if(!t.apiKey)throw new Error("[onedeskpro-chatbot] `apiKey` is required to initialise the chatbot.");const e=++this.initToken;(l=this.widget)==null||l.destroy(),this.widget=null,this.callerSetName=t.chatbotName!==void 0,this.options={...R,...j(t)},this.apiClient=new f({baseUrl:this.options.apiBaseUrl,apiKey:this.options.apiKey,timeoutMs:this.options.requestTimeoutMs});const n=this.session.init(this.options.sessionId||void 0);this.setState({sessionId:n}),typeof window<"u"&&typeof document<"u"&&(this.widget=new U(this.options,{onSend:c=>void this.sendMessage(c),onOpen:()=>{this.setState({isOpen:!0}),this.emitter.emit("open")},onClose:()=>{this.setState({isOpen:!1}),this.emitter.emit("close")},onReset:()=>this.resetSession()}));const s=await this.fetchConfig();if(e!==this.initToken)return;s&&!this.callerSetName&&s.agentName.trim()&&(this.options.chatbotName=s.agentName);const a=(s==null?void 0:s.blockReason)??null;if(this.setState({blockReason:a,isReady:a===null}),a)(r=this.widget)==null||r.showBlocked(a);else if((o=this.widget)==null||o.readyToChat(this.options),await this.loadHistory(e),e!==this.initToken)return;this.emitter.emit("ready")}async fetchConfig(){try{return await this.apiClient.fetchConfig()}catch{return null}}async sendMessage(t){var a,l,r,o;const e=this.session.get();if(!this.apiClient||!e)throw new Error("[onedeskpro-chatbot] Call init() before sendMessage().");const n=t.trim();if(!n||this._state.isLoading)return;const s={id:k(),sessionId:e,message:{type:"human",content:n}};this.setState({messages:[...this._state.messages,s],isLoading:!0,error:null}),(a=this.widget)==null||a.appendMessage(s),(l=this.widget)==null||l.setLoading(!0),this.emitter.emit("message",s);try{const c=await this.apiClient.sendMessage({chatInput:n,sessionId:e}),d={id:k(),sessionId:e,message:{type:"ai",content:c.text}};this.setState({messages:[...this._state.messages,d],isLoading:!1}),(r=this.widget)==null||r.appendMessage(d),this.emitter.emit("message",d)}catch(c){const d=c instanceof Error?c:new Error(String(c));this.setState({error:d.message,isLoading:!1}),this.emitter.emit("error",d)}finally{(o=this.widget)==null||o.setLoading(!1)}}async loadHistory(t){var n;const e=this.session.get();if(e)try{const s=await this.apiClient.fetchHistory(e);if(t!==this.initToken)return;this.setState({messages:s}),s.length>0&&((n=this.widget)==null||n.setMessages(s))}catch{}}on(t,e){return this.emitter.on(t,e)}resetSession(){var e;if(!this._state.isReady)return;const t=this.session.reset();this.setState({sessionId:t,messages:[],error:null}),(e=this.widget)==null||e.clearMessages(this.options.chatbotName),this.emitter.emit("session-reset")}open(){var t;(t=this.widget)==null||t.open()}close(){var t;(t=this.widget)==null||t.close()}toggle(){var t;(t=this.widget)==null||t.toggle()}getState(){return{...this._state}}destroy(){var t;this.initToken++,(t=this.widget)==null||t.destroy(),this.widget=null,this.setState({isOpen:!1,isLoading:!1,isReady:!1})}}let m=null;const q={async init(i){return m=new T,await m.init(i),m},getInstance(){return m}};return h.ApiClient=f,h.ChatbotCore=T,h.DEFAULT_API_BASE_URL=x,h.DEFAULT_REQUEST_TIMEOUT_MS=3e4,h.EventEmitter=w,h.OnedeskProChatbot=q,h.SessionManager=v,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"}),h}({});