akvo-rag-js 1.3.1 → 1.5.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.
package/README.md CHANGED
@@ -4,6 +4,10 @@ An embeddable chatbot widget for Akvo RAG.
4
4
 
5
5
  - **Premium Markdown Rendering**: Supports GitHub Flavored Markdown (GFM), tables, code blocks, and lists with isolated, premium styling.
6
6
  - **Optimized Streaming UX**: Intelligent text cleaning to prevent mid-word spacing issues during real-time streaming.
7
+ - **Cross-Page Chat History Persistence**: Dialogue history automatically rehydrates across route changes and browser refreshes with sliding-window capacity.
8
+ - **Strict Multi-User Isolation**: Built-in composite keying (`userId`/`visitorId` + `kb_id`) ensures zero history leakage across different users or shared devices.
9
+ - **Configurable Citation Control**: Toggle source citation popovers and badges on or off (`showCitations`) with clean token suppression.
10
+ - **Draggable Positioning & Persistence**: Smooth draggable launcher and header with quadrant anchoring and coordinate persistence (ADR-006).
7
11
  - **Embeddable & Flexible**: Embed directly into HTML with `<script>` or use as an NPM module.
8
12
  - **Knowledge Base Selection**: Supports multiple KB selections with a clear "Start Chat" workflow.
9
13
  - **Isolated Styling**: Scoped CSS (`#akvo-rag`) using SCSS to prevent style collisions with host sites.
@@ -102,33 +106,76 @@ initChat({
102
106
 
103
107
  The `initChat` function accepts a configuration object to customize the chat widget behavior, appearance, and dimensions:
104
108
 
105
- | Parameter | Type | Required | Default | Description |
106
- | ---------------- | ----------------------------------------- | -------- | ------------------ | ------------------------------------------------------------------ |
107
- | `title` | `string` | ✅ Yes | `"Chatbot"` | The title displayed in the chat header. |
108
- | `wsURL` | `string` | ✅ Yes | — | WebSocket endpoint URL for real-time chat communication. |
109
- | `kb_id` | `number` | ❌ No | `null` | Initial Knowledge Base ID to query directly. |
110
- | `kb_options` | `Array<{ kb_id: number, label: string }>` | ❌ No | `[]` | Knowledge Base choices for the user before starting chat. |
111
- | `primaryColor` | `string` | ❌ No | `"#007A78"` | Primary brand color (`#hex`, `rgb`, `hsl`) cascading via CSS var. |
112
- | `showLauncher` | `boolean` | ❌ No | `true` | `true`: Floating 56×56px launcher button; `false`: embedded box. |
113
- | `startMinimized` | `boolean` | ❌ No | `true` | Whether the widget initializes minimized or expanded. |
114
- | `width` | `number \| string` | ❌ No | `"360px"` | Widget width (`400`, `"420px"`, `"25rem"`). Clamped on mobile. |
115
- | `height` | `number \| string` | ❌ No | `"500px"` | Widget height (`560`, `"600px"`, `"80vh"`). Clamped on mobile. |
116
- | `position` | `"bottom-right" \| "bottom-left"` | ❌ No | `"bottom-right"` | Viewport corner anchor for both launcher and chat window. |
117
- | `borderRadius` | `number \| string` | ❌ No | `"8px"` | Corner radius (`8`, `"12px"`, `"16px"`). |
118
- | `launcherSize` | `number \| string` | ❌ No | `"56px"` | Floating launcher button size (`48`, `"56px"`, `"64px"`). |
119
- | `zIndex` | `number` | ❌ No | `99999` | Stacking index (launcher automatically takes `zIndex - 1`). |
120
- | `launcherIcon` | `string` | ❌ No | Default comments | Custom SVG markup, image URL, or FontAwesome class string. |
121
- | `headerIcon` | `string` | ❌ No | `null` | Avatar or icon rendered adjacent to the header title. |
122
- | `autoReconnect` | `boolean` | ❌ No | `true` | Reconnection with exponential backoff on drop (ADR-005). |
109
+ | Parameter | Type | Required | Default | Description |
110
+ | -------------------- | ----------------------------------------- | -------- | -------------------- | ------------------------------------------------------------------ |
111
+ | `title` | `string` | ✅ Yes | `"Chatbot"` | The title displayed in the chat header. |
112
+ | `wsURL` | `string` | ✅ Yes | — | WebSocket endpoint URL for real-time chat communication. |
113
+ | `kb_id` | `number` | ❌ No | `null` | Initial Knowledge Base ID to query directly. |
114
+ | `kb_options` | `Array<{ kb_id: number, label: string }>` | ❌ No | `[]` | Knowledge Base choices for the user before starting chat. |
115
+ | `persistHistory` | `boolean` | ❌ No | `true` | Preserve conversation transcript across page refreshes / routes. |
116
+ | `userId` | `string` | ❌ No | `null` | Unique user ID for multi-user isolation on shared devices. |
117
+ | `historyStorageType` | `"session" \| "local"` | ❌ No | `"session"` | Storage backend (`sessionStorage` clears on tab close). |
118
+ | `historyStorageKey` | `string` | ❌ No | `"akvo_rag_history"` | Base storage key for chat history persistence. |
119
+ | `maxHistoryMessages` | `number` | ❌ No | `20` | Maximum conversation turns retained in sliding window history. |
120
+ | `showCitations` | `boolean` | ❌ No | `true` | `true`: Render superscript citation popovers; `false`: strip tags. |
121
+ | `draggable` | `boolean` | ❌ No | `true` | Enable draggable positioning for launcher and chat window header. |
122
+ | `persistPosition` | `boolean` | ❌ No | `true` | Persist widget coordinates across reloads in `localStorage`. |
123
+ | `dragThreshold` | `number` | ❌ No | `6` | Pixel distance threshold before a click becomes a drag. |
124
+ | `primaryColor` | `string` | ❌ No | `"#007A78"` | Primary brand color (`#hex`, `rgb`, `hsl`) cascading via CSS var. |
125
+ | `showLauncher` | `boolean` | ❌ No | `true` | `true`: Floating 56×56px launcher button; `false`: embedded box. |
126
+ | `startMinimized` | `boolean` | ❌ No | `true` | Whether the widget initializes minimized or expanded. |
127
+ | `width` | `number \| string` | ❌ No | `"360px"` | Widget width (`400`, `"420px"`, `"25rem"`). Clamped on mobile. |
128
+ | `height` | `number \| string` | ❌ No | `"500px"` | Widget height (`560`, `"600px"`, `"80vh"`). Clamped on mobile. |
129
+ | `position` | `"bottom-right" \| "bottom-left"` | ❌ No | `"bottom-right"` | Viewport corner anchor for both launcher and chat window. |
130
+ | `borderRadius` | `number \| string` | ❌ No | `"8px"` | Corner radius (`8`, `"12px"`, `"16px"`). |
131
+ | `launcherSize` | `number \| string` | ❌ No | `"56px"` | Floating launcher button size (`48`, `"56px"`, `"64px"`). |
132
+ | `zIndex` | `number` | ❌ No | `99999` | Stacking index (launcher automatically takes `zIndex - 1`). |
133
+ | `launcherIcon` | `string` | ❌ No | Default comments | Custom SVG markup, image URL, or FontAwesome class string. |
134
+ | `headerIcon` | `string` | ❌ No | `null` | Avatar or icon rendered adjacent to the header title. |
135
+ | `autoReconnect` | `boolean` | ❌ No | `true` | Reconnection with exponential backoff on drop (ADR-005). |
136
+
137
+ ---
138
+
139
+ ### 💬 Session History & Multi-User Isolation
140
+
141
+ The widget automatically persists dialogue turns across route changes, SPA navigations, and browser refreshes:
142
+
143
+ ```javascript
144
+ const chat = initChat({
145
+ wsURL: "wss://akvo-rag.akvotest.org/ws/chat",
146
+ kb_id: 750,
147
+ persistHistory: true, // On/off toggle (defaults to true)
148
+ userId: currentUser?.id, // Scopes storage to this user (prevents cross-user leaks)
149
+ showCitations: false, // Suppress [citation:X] badges for clean conversational look
150
+ });
151
+ ```
152
+
153
+ #### How User ID Scoping Works:
154
+ 1. **Anonymous Visitors (Default)**: If `userId` is omitted, the widget automatically generates a private UUID saved in `localStorage["akvo-visitor-id"]`. Each device maintains its own isolated transcript.
155
+ 2. **Logged-In Users**: When your application passes `userId: "alice"`, history is stored under `akvo_rag_history_alice_750`. If Bob logs in on the same browser with `userId: "bob"`, he will **never see Alice's history**.
156
+ 3. **Programmatic Controls**:
157
+ - `chat.clearHistory()`: Purges saved messages from storage for the active user/KB and resets the chat UI.
158
+ - `chat.getHistory()`: Returns a deep copy of the current in-memory message history.
159
+
160
+ ---
123
161
 
124
162
  ### 🔧 Component Lifecycle (`AkvoRagChatbox`)
125
163
 
126
- The `initChat` function returns an instance of `AkvoRagChatbox`. You can use it to manage the widget's lifecycle:
164
+ The `initChat` function returns an instance of `AkvoRagChatbox`. You can use it to manage the widget's lifecycle and programmatic actions:
127
165
 
128
166
  ```javascript
129
167
  const chat = initChat({ ... });
130
168
 
131
- // To remove the widget and close connections:
169
+ // Programmatic UI control:
170
+ chat.open(); // Expand chat window
171
+ chat.minimize(); // Collapse to launcher
172
+ chat.close(); // Minimize chat window
173
+
174
+ // History management:
175
+ const messages = chat.getHistory();
176
+ chat.clearHistory();
177
+
178
+ // Clean up connections and DOM elements:
132
179
  chat.destroy();
133
180
  ```
134
181
 
package/dist/akvo-rag.css CHANGED
@@ -2336,4 +2336,4 @@
2336
2336
  clip: auto;
2337
2337
  }
2338
2338
 
2339
- #akvo-rag *,#akvo-rag *::before,#akvo-rag *::after{box-sizing:border-box;margin:0;padding:0}#akvo-rag p{margin-block-start:10px;margin-block-end:10px}.citation{color:var(--akvo-primary, #007A78)}.citation-popover{max-width:320px;width:max-content;background:#fff;color:#1f2937;border:1px solid #e5e7eb;padding:12px 14px;border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.1);font-size:.875rem;line-height:1.4;z-index:99999 !important;font-family:"Inter","Segoe UI",Tahoma,sans-serif;position:absolute;transition:opacity .2s ease,transform .2s ease;opacity:0;transform:translateY(4px);animation:popIn .15s ease-out forwards;word-wrap:break-word;overflow-wrap:break-word;white-space:normal}.citation-popover strong,.citation-popover small,.citation-popover p{word-wrap:break-word;overflow-wrap:break-word;white-space:normal;max-width:100%}.citation-popover strong,.citation-popover small{word-break:break-all}@keyframes popIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.citation-popover .arrow{position:absolute;width:0;height:0}.citation-popover.above .arrow{bottom:-8px;border-left:8px solid rgba(0,0,0,0);border-right:8px solid rgba(0,0,0,0);border-top:8px solid #fff;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.05))}.citation-popover.below .arrow{top:-8px;border-left:8px solid rgba(0,0,0,0);border-right:8px solid rgba(0,0,0,0);border-bottom:8px solid #fff;filter:drop-shadow(0 -1px 2px rgba(0, 0, 0, 0.05))}.citation-popover strong{display:block;font-weight:600;margin-bottom:4px;color:#111827}.citation-popover small{display:block;font-size:.75rem;color:#6b7280;margin-bottom:6px}.citation-popover p{margin:0;font-size:.85rem;color:#374151}#akvo-rag{--akvo-primary: #007A78;--akvo-width: 360px;--akvo-height: 500px;--akvo-border-radius: 8px;--akvo-offset-bottom: 20px;--akvo-offset-side: 20px;--akvo-z-index: 99999;position:fixed;bottom:var(--akvo-offset-bottom, 20px);right:var(--akvo-offset-side, 20px);width:var(--akvo-width, 360px);height:var(--akvo-height, 500px);max-width:calc(100vw - 32px);max-height:calc(100vh - 48px);background-color:#fff;box-shadow:0 4px 12px rgba(0,0,0,.1);border-radius:var(--akvo-border-radius, 8px);z-index:var(--akvo-z-index, 99999);display:flex;flex-direction:column;font-family:"Segoe UI",Tahoma,Geneva,Verdana,sans-serif;overflow:hidden;transition:all .3s ease}#akvo-rag.akvo-position-left{right:auto;left:var(--akvo-offset-side, 20px)}#akvo-rag-header{background-color:var(--akvo-primary, #007A78);color:#fff;padding:12px 16px;font-size:16px;font-weight:bold;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;cursor:pointer}#akvo-rag-header .akvo-header-title{display:flex;align-items:center;gap:8px}#akvo-rag-header .akvo-header-icon{display:inline-flex;align-items:center;justify-content:center}#akvo-rag-header .akvo-header-icon svg{width:20px;height:20px;fill:currentColor}#akvo-rag-header .akvo-header-icon img.akvo-icon-img{width:22px;height:22px;border-radius:50%;object-fit:contain}#akvo-rag-header .akvo-header-icon i.fa{margin-right:0;font-size:18px}#akvo-rag-header i.fa{margin-right:8px;font-size:18px}#akvo-rag-body{flex:1;padding:16px;overflow-y:auto;background-color:#f9f9f9;color:#333;display:block;font-size:14px}#akvo-rag-body .akvo-msg-user{text-align:right;background-color:var(--akvo-primary, #007A78);color:#fff;padding:8px 12px;border-radius:12px;margin:10px 0;max-width:80%;margin-left:auto;word-break:break-word}#akvo-rag-body .akvo-msg-user p{margin:0;color:#fff;line-height:1.4}#akvo-rag-body .akvo-msg-user a{color:#fff;text-decoration:underline}#akvo-rag-body .akvo-msg-assistant{text-align:left;background-color:#e6e6e6;color:#000;padding:8px 12px;border-radius:12px;margin:10px 0;max-width:80%;margin-right:auto}#akvo-rag-body .akvo-msg-system{text-align:center;color:gray;font-style:italic;margin:10px 0}#akvo-rag-input-container{display:flex;padding:8px;border-top:1px solid #ddd;background-color:#fff;flex-shrink:0}#akvo-rag-input-container input{flex:1;padding:8px 12px;border:1px solid #ccc;border-radius:20px;font-size:14px}#akvo-rag-input-container button{margin-left:8px;padding:8px 16px;background-color:var(--akvo-primary, #007A78);color:#fff;border:none;border-radius:20px;cursor:pointer;transition:background-color .2s ease,filter .2s ease}#akvo-rag-input-container button:hover{filter:brightness(0.9)}#akvo-rag-close-btn{background:none;border:none;color:#fff;font-size:18px;cursor:pointer;padding:0 4px}#akvo-rag.minimized{width:calc(var(--akvo-width, 360px) - 40px) !important;height:40px !important;min-height:40px !important;max-height:40px !important;border-radius:4px !important}#akvo-rag.minimized #akvo-rag-body,#akvo-rag.minimized #akvo-rag-input-container{display:none !important}#akvo-rag.minimized #akvo-rag-header{font-size:14px;padding:8px 12px;height:40px}#akvo-rag .answer-container{background:#f5f5f5;padding:10px 15px;border-radius:8px;margin-bottom:8px;max-width:80%;font-family:Arial,sans-serif}#akvo-rag .answer-content{color:#333;white-space:pre-wrap}#akvo-rag .answer-citations{margin-top:10px;font-size:.9em;color:#666;border-top:1px solid #ccc;padding-top:8px}#akvo-rag .answer-citation{margin-bottom:6px}#akvo-rag .typing-indicator{display:inline-flex;align-items:center;gap:4px;height:1em}#akvo-rag .typing-indicator span{display:inline-block;width:6px;height:6px;background-color:#ccc;border-radius:50%;animation:typing-bounce 1.2s infinite ease-in-out}#akvo-rag .typing-indicator span:nth-child(2){animation-delay:.2s}#akvo-rag .typing-indicator span:nth-child(3){animation-delay:.4s}@keyframes typing-bounce{0%,80%,100%{transform:scale(0.6);opacity:.5}40%{transform:scale(1);opacity:1}}#akvo-rag .akvo-send-spinner{display:inline-block;width:14px;height:14px;border:2px solid #fff;border-top:2px solid #888;border-radius:50%;animation:spin .8s linear infinite;vertical-align:middle;margin-right:5px}@keyframes spin{to{transform:rotate(360deg)}}#akvo-rag #akvo-rag-send-btn{position:relative;display:flex;justify-content:center;align-items:center}#akvo-rag #akvo-rag-send-btn:disabled{background-color:#ccc;color:#333;cursor:not-allowed;opacity:.6}#akvo-rag #akvo-kb-options,#akvo-rag .akvo-kb-options{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:0 16px 12px;margin-bottom:16px}#akvo-rag #akvo-kb-options p,#akvo-rag .akvo-kb-options p{font-weight:500;color:#111827;margin-bottom:12px;font-size:.95rem}#akvo-rag #akvo-kb-options .kb-option,#akvo-rag .akvo-kb-options .kb-option{display:flex;align-items:center;margin-bottom:8px;cursor:pointer;transition:background-color .2s ease}#akvo-rag #akvo-kb-options .kb-option input[type=radio],#akvo-rag .akvo-kb-options .kb-option input[type=radio]{margin-right:10px;accent-color:var(--akvo-primary, #007A78);transform:scale(1.1);cursor:pointer}#akvo-rag #akvo-kb-options .kb-option label,#akvo-rag .akvo-kb-options .kb-option label{color:#374151;font-size:.9rem;cursor:pointer}#akvo-rag #akvo-kb-options .kb-option:hover,#akvo-rag .akvo-kb-options .kb-option:hover{background-color:#f3f4f6;border-radius:6px;padding:4px 0}#akvo-rag .akvo-kb-options-hint{font-size:.85rem;color:#6b7280;font-style:italic;margin-top:8px}#akvo-rag .akvo-start-chat-btn{width:100%;padding:8px 16px;background-color:var(--akvo-primary, #007A78);color:#fff;border:none;border-radius:20px;cursor:pointer;font-size:.9rem;font-weight:500;transition:background-color .2s ease,filter .2s ease}#akvo-rag .akvo-start-chat-btn:hover:not(:disabled){filter:brightness(0.9)}#akvo-rag .akvo-start-chat-btn:disabled{background-color:#ccc;color:#333;cursor:not-allowed;opacity:.6}#akvo-rag-launcher{--akvo-primary: #007A78;--akvo-offset-bottom: 24px;--akvo-offset-side: 24px;--akvo-z-index: 99998;--akvo-launcher-size: 56px;--akvo-launcher-width: var(--akvo-launcher-size, 56px);--akvo-launcher-height: var(--akvo-launcher-size, 56px);position:fixed;bottom:var(--akvo-offset-bottom, 24px);right:var(--akvo-offset-side, 24px);width:var(--akvo-launcher-width, 56px);height:var(--akvo-launcher-height, 56px);border-radius:50%;background-color:var(--akvo-primary, #007A78);color:#fff;box-shadow:0 4px 12px rgba(0,0,0,.15);display:flex;align-items:center;justify-content:center;border:none;cursor:pointer;outline:none;z-index:var(--akvo-z-index, 99998);transition:transform .2s ease,box-shadow .2s ease,filter .2s ease}#akvo-rag-launcher.akvo-position-left{right:auto;left:var(--akvo-offset-side, 24px)}#akvo-rag-launcher:hover{transform:scale(1.05);box-shadow:0 6px 16px rgba(0,0,0,.2);filter:brightness(1.05)}#akvo-rag-launcher:active{transform:scale(0.95)}#akvo-rag-launcher svg{width:50%;height:50%;max-width:32px;max-height:32px;fill:currentColor}#akvo-rag-launcher img.akvo-icon-img{width:60%;height:60%;object-fit:contain;border-radius:50%}#akvo-rag-launcher i.fa{font-size:calc(var(--akvo-launcher-height, 56px)*.45);color:#fff}#akvo-rag .akvo-msg-assistant h1,#akvo-rag .akvo-msg-assistant h2,#akvo-rag .akvo-msg-assistant h3,#akvo-rag .akvo-msg-assistant h4,#akvo-rag .akvo-msg-assistant h5,#akvo-rag .akvo-msg-assistant h6{margin-top:1.5em;margin-bottom:.5em;color:var(--akvo-primary, #007A78)}#akvo-rag .akvo-msg-assistant p{margin-bottom:1em;line-height:1.5}#akvo-rag .akvo-msg-assistant ul,#akvo-rag .akvo-msg-assistant ol{margin:10px 0;padding-left:1rem}#akvo-rag .akvo-msg-assistant ul li,#akvo-rag .akvo-msg-assistant ol li{margin-bottom:6px;line-height:1.4}#akvo-rag .akvo-msg-assistant ul li ul,#akvo-rag .akvo-msg-assistant ul li ol,#akvo-rag .akvo-msg-assistant ol li ul,#akvo-rag .akvo-msg-assistant ol li ol{margin:5px 0;padding-left:1rem}#akvo-rag .akvo-msg-assistant ul{list-style-type:disc}#akvo-rag .akvo-msg-assistant ol{list-style-type:decimal}#akvo-rag .akvo-msg-assistant table{width:100%;border-collapse:collapse;margin-bottom:1em;border:1px solid #ddd;font-size:.9em}#akvo-rag .akvo-msg-assistant table th,#akvo-rag .akvo-msg-assistant table td{border:1px solid #ddd;padding:8px 12px;text-align:left}#akvo-rag .akvo-msg-assistant table th{background-color:#f2f2f2;font-weight:bold}#akvo-rag .akvo-msg-assistant table tr:nth-child(even){background-color:#f9f9f9}#akvo-rag .akvo-msg-assistant code{font-family:Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;background-color:#f0f0f0;padding:2px 4px;border-radius:4px;font-size:.9em}#akvo-rag .akvo-msg-assistant pre{background-color:#f0f0f0;padding:12px;border-radius:8px;overflow-x:auto;margin-bottom:1em}#akvo-rag .akvo-msg-assistant pre code{padding:0;background:none}#akvo-rag .akvo-msg-assistant blockquote{border-left:4px solid var(--akvo-primary, #007A78);margin:10px 0;padding:8px 16px;background-color:#fff;font-style:italic;color:#555}#akvo-rag .akvo-msg-assistant hr{border:0;border-top:1px solid #eee;margin:20px 0}#akvo-rag .akvo-msg-assistant a{color:var(--akvo-primary, #007A78);text-decoration:underline}#akvo-rag .akvo-msg-assistant a:hover{text-decoration:none}
2339
+ #akvo-rag *,#akvo-rag *::before,#akvo-rag *::after{box-sizing:border-box;margin:0;padding:0}#akvo-rag p{margin-block-start:10px;margin-block-end:10px}.citation{color:var(--akvo-primary, #007A78)}.citation-popover{max-width:320px;width:max-content;background:#fff;color:#1f2937;border:1px solid #e5e7eb;padding:12px 14px;border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.1);font-size:.875rem;line-height:1.4;z-index:99999 !important;font-family:"Inter","Segoe UI",Tahoma,sans-serif;position:absolute;transition:opacity .2s ease,transform .2s ease;opacity:0;transform:translateY(4px);animation:popIn .15s ease-out forwards;word-wrap:break-word;overflow-wrap:break-word;white-space:normal}.citation-popover strong,.citation-popover small,.citation-popover p{word-wrap:break-word;overflow-wrap:break-word;white-space:normal;max-width:100%}.citation-popover strong,.citation-popover small{word-break:break-all}@keyframes popIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.citation-popover .arrow{position:absolute;width:0;height:0}.citation-popover.above .arrow{bottom:-8px;border-left:8px solid rgba(0,0,0,0);border-right:8px solid rgba(0,0,0,0);border-top:8px solid #fff;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.05))}.citation-popover.below .arrow{top:-8px;border-left:8px solid rgba(0,0,0,0);border-right:8px solid rgba(0,0,0,0);border-bottom:8px solid #fff;filter:drop-shadow(0 -1px 2px rgba(0, 0, 0, 0.05))}.citation-popover strong{display:block;font-weight:600;margin-bottom:4px;color:#111827}.citation-popover small{display:block;font-size:.75rem;color:#6b7280;margin-bottom:6px}.citation-popover p{margin:0;font-size:.85rem;color:#374151}#akvo-rag{--akvo-primary: #007A78;--akvo-width: 360px;--akvo-height: 500px;--akvo-border-radius: 8px;--akvo-offset-bottom: 20px;--akvo-offset-side: 20px;--akvo-z-index: 99999;position:fixed;bottom:var(--akvo-offset-bottom, 20px);right:var(--akvo-offset-side, 20px);width:var(--akvo-width, 360px);height:var(--akvo-height, 500px);max-width:calc(100vw - 32px);max-height:calc(100vh - 48px);background-color:#fff;box-shadow:0 4px 12px rgba(0,0,0,.1);border-radius:var(--akvo-border-radius, 8px);z-index:var(--akvo-z-index, 99999);display:flex;flex-direction:column;font-family:"Segoe UI",Tahoma,Geneva,Verdana,sans-serif;overflow:hidden;transition:all .3s ease}#akvo-rag.akvo-position-left{right:auto;left:var(--akvo-offset-side, 20px)}#akvo-rag.akvo-is-dragging{transition:none !important;user-select:none}#akvo-rag-header{background-color:var(--akvo-primary, #007A78);color:#fff;padding:12px 16px;font-size:16px;font-weight:bold;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;cursor:grab;user-select:none}#akvo-rag-header:active{cursor:grabbing}#akvo-rag-header .akvo-header-title{display:flex;align-items:center;gap:8px}#akvo-rag-header .akvo-header-icon{display:inline-flex;align-items:center;justify-content:center}#akvo-rag-header .akvo-header-icon svg{width:20px;height:20px;fill:currentColor}#akvo-rag-header .akvo-header-icon img.akvo-icon-img{width:22px;height:22px;border-radius:50%;object-fit:contain}#akvo-rag-header .akvo-header-icon i.fa{margin-right:0;font-size:18px}#akvo-rag-header i.fa{margin-right:8px;font-size:18px}#akvo-rag-body{flex:1;padding:16px;overflow-y:auto;background-color:#f9f9f9;color:#333;display:block;font-size:14px}#akvo-rag-body .akvo-msg-user{text-align:right;background-color:var(--akvo-primary, #007A78);color:#fff;padding:8px 12px;border-radius:12px;margin:10px 0;max-width:80%;margin-left:auto;word-break:break-word}#akvo-rag-body .akvo-msg-user p{margin:0;color:#fff;line-height:1.4}#akvo-rag-body .akvo-msg-user a{color:#fff;text-decoration:underline}#akvo-rag-body .akvo-msg-assistant{text-align:left;background-color:#e6e6e6;color:#000;padding:8px 12px;border-radius:12px;margin:10px 0;max-width:80%;margin-right:auto}#akvo-rag-body .akvo-msg-system{text-align:center;color:gray;font-style:italic;margin:10px 0}#akvo-rag-input-container{display:flex;align-items:flex-end;padding:8px;border-top:1px solid #ddd;background-color:#fff;flex-shrink:0}#akvo-rag-input-container textarea{flex:1;padding:8px 12px;border:1px solid #ccc;border-radius:18px;font-size:14px;font-family:inherit;resize:none;min-height:38px;max-height:120px;line-height:1.4;overflow-y:auto;box-sizing:border-box;outline:none;transition:border-color .2s ease}#akvo-rag-input-container textarea:focus{border-color:var(--akvo-primary, #007A78)}#akvo-rag-input-container input{flex:1;padding:8px 12px;border:1px solid #ccc;border-radius:20px;font-size:14px;box-sizing:border-box;outline:none}#akvo-rag-input-container input:focus{border-color:var(--akvo-primary, #007A78)}#akvo-rag-input-container button{margin-left:8px;margin-bottom:2px;padding:8px 16px;background-color:var(--akvo-primary, #007A78);color:#fff;border:none;border-radius:20px;cursor:pointer;transition:background-color .2s ease,filter .2s ease}#akvo-rag-input-container button:hover{filter:brightness(0.9)}#akvo-rag-close-btn{background:none;border:none;color:#fff;font-size:18px;cursor:pointer;padding:0 4px}#akvo-rag.minimized{width:calc(var(--akvo-width, 360px) - 40px) !important;height:40px !important;min-height:40px !important;max-height:40px !important;border-radius:4px !important}#akvo-rag.minimized #akvo-rag-body,#akvo-rag.minimized #akvo-rag-input-container{display:none !important}#akvo-rag.minimized #akvo-rag-header{font-size:14px;padding:8px 12px;height:40px}#akvo-rag .answer-container{background:#f5f5f5;padding:10px 15px;border-radius:8px;margin-bottom:8px;max-width:80%;font-family:Arial,sans-serif}#akvo-rag .answer-content{color:#333;white-space:pre-wrap}#akvo-rag .answer-citations{margin-top:10px;font-size:.9em;color:#666;border-top:1px solid #ccc;padding-top:8px}#akvo-rag .answer-citation{margin-bottom:6px}#akvo-rag .typing-indicator{display:inline-flex;align-items:center;gap:4px;height:1em}#akvo-rag .typing-indicator span{display:inline-block;width:6px;height:6px;background-color:#ccc;border-radius:50%;animation:typing-bounce 1.2s infinite ease-in-out}#akvo-rag .typing-indicator span:nth-child(2){animation-delay:.2s}#akvo-rag .typing-indicator span:nth-child(3){animation-delay:.4s}@keyframes typing-bounce{0%,80%,100%{transform:scale(0.6);opacity:.5}40%{transform:scale(1);opacity:1}}#akvo-rag .akvo-send-spinner{display:inline-block;width:14px;height:14px;border:2px solid #fff;border-top:2px solid #888;border-radius:50%;animation:spin .8s linear infinite;vertical-align:middle;margin-right:5px}@keyframes spin{to{transform:rotate(360deg)}}#akvo-rag #akvo-rag-send-btn{position:relative;display:flex;justify-content:center;align-items:center}#akvo-rag #akvo-rag-send-btn:disabled{background-color:#ccc;color:#333;cursor:not-allowed;opacity:.6}#akvo-rag #akvo-kb-options,#akvo-rag .akvo-kb-options{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:0 16px 12px;margin-bottom:16px}#akvo-rag #akvo-kb-options p,#akvo-rag .akvo-kb-options p{font-weight:500;color:#111827;margin-bottom:12px;font-size:.95rem}#akvo-rag #akvo-kb-options .kb-option,#akvo-rag .akvo-kb-options .kb-option{display:flex;align-items:center;margin-bottom:8px;cursor:pointer;transition:background-color .2s ease}#akvo-rag #akvo-kb-options .kb-option input[type=radio],#akvo-rag .akvo-kb-options .kb-option input[type=radio]{margin-right:10px;accent-color:var(--akvo-primary, #007A78);transform:scale(1.1);cursor:pointer}#akvo-rag #akvo-kb-options .kb-option label,#akvo-rag .akvo-kb-options .kb-option label{color:#374151;font-size:.9rem;cursor:pointer}#akvo-rag #akvo-kb-options .kb-option:hover,#akvo-rag .akvo-kb-options .kb-option:hover{background-color:#f3f4f6;border-radius:6px;padding:4px 0}#akvo-rag .akvo-kb-options-hint{font-size:.85rem;color:#6b7280;font-style:italic;margin-top:8px}#akvo-rag .akvo-start-chat-btn{width:100%;padding:8px 16px;background-color:var(--akvo-primary, #007A78);color:#fff;border:none;border-radius:20px;cursor:pointer;font-size:.9rem;font-weight:500;transition:background-color .2s ease,filter .2s ease}#akvo-rag .akvo-start-chat-btn:hover:not(:disabled){filter:brightness(0.9)}#akvo-rag .akvo-start-chat-btn:disabled{background-color:#ccc;color:#333;cursor:not-allowed;opacity:.6}#akvo-rag-launcher{--akvo-primary: #007A78;--akvo-offset-bottom: 24px;--akvo-offset-side: 24px;--akvo-z-index: 99998;--akvo-launcher-size: 56px;--akvo-launcher-width: var(--akvo-launcher-size, 56px);--akvo-launcher-height: var(--akvo-launcher-size, 56px);position:fixed;bottom:var(--akvo-offset-bottom, 24px);right:var(--akvo-offset-side, 24px);width:var(--akvo-launcher-width, 56px);height:var(--akvo-launcher-height, 56px);border-radius:50%;background-color:var(--akvo-primary, #007A78);color:#fff;box-shadow:0 4px 12px rgba(0,0,0,.15);display:flex;align-items:center;justify-content:center;border:none;cursor:grab;user-select:none;outline:none;z-index:var(--akvo-z-index, 99998);transition:transform .2s ease,box-shadow .2s ease,filter .2s ease}#akvo-rag-launcher.akvo-is-dragging{cursor:grabbing;transition:none !important}#akvo-rag-launcher.akvo-position-left{right:auto;left:var(--akvo-offset-side, 24px)}#akvo-rag-launcher:hover{transform:scale(1.05);box-shadow:0 6px 16px rgba(0,0,0,.2);filter:brightness(1.05)}#akvo-rag-launcher:active{cursor:grabbing;transform:scale(0.95)}#akvo-rag-launcher svg{width:50%;height:50%;max-width:32px;max-height:32px;fill:currentColor}#akvo-rag-launcher img.akvo-icon-img{width:60%;height:60%;object-fit:contain;border-radius:50%}#akvo-rag-launcher i.fa{font-size:calc(var(--akvo-launcher-height, 56px)*.45);color:#fff}#akvo-rag .akvo-msg-assistant h1,#akvo-rag .akvo-msg-assistant h2,#akvo-rag .akvo-msg-assistant h3,#akvo-rag .akvo-msg-assistant h4,#akvo-rag .akvo-msg-assistant h5,#akvo-rag .akvo-msg-assistant h6{margin-top:1.5em;margin-bottom:.5em;color:var(--akvo-primary, #007A78)}#akvo-rag .akvo-msg-assistant p{margin-bottom:1em;line-height:1.5}#akvo-rag .akvo-msg-assistant ul,#akvo-rag .akvo-msg-assistant ol{margin:10px 0;padding-left:1rem}#akvo-rag .akvo-msg-assistant ul li,#akvo-rag .akvo-msg-assistant ol li{margin-bottom:6px;line-height:1.4}#akvo-rag .akvo-msg-assistant ul li ul,#akvo-rag .akvo-msg-assistant ul li ol,#akvo-rag .akvo-msg-assistant ol li ul,#akvo-rag .akvo-msg-assistant ol li ol{margin:5px 0;padding-left:1rem}#akvo-rag .akvo-msg-assistant ul{list-style-type:disc}#akvo-rag .akvo-msg-assistant ol{list-style-type:decimal}#akvo-rag .akvo-msg-assistant table{width:100%;border-collapse:collapse;margin-bottom:1em;border:1px solid #ddd;font-size:.9em}#akvo-rag .akvo-msg-assistant table th,#akvo-rag .akvo-msg-assistant table td{border:1px solid #ddd;padding:8px 12px;text-align:left}#akvo-rag .akvo-msg-assistant table th{background-color:#f2f2f2;font-weight:bold}#akvo-rag .akvo-msg-assistant table tr:nth-child(even){background-color:#f9f9f9}#akvo-rag .akvo-msg-assistant code{font-family:Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;background-color:#f0f0f0;padding:2px 4px;border-radius:4px;font-size:.9em}#akvo-rag .akvo-msg-assistant pre{background-color:#f0f0f0;padding:12px;border-radius:8px;overflow-x:auto;margin-bottom:1em}#akvo-rag .akvo-msg-assistant pre code{padding:0;background:none}#akvo-rag .akvo-msg-assistant blockquote{border-left:4px solid var(--akvo-primary, #007A78);margin:10px 0;padding:8px 16px;background-color:#fff;font-style:italic;color:#555}#akvo-rag .akvo-msg-assistant hr{border:0;border-top:1px solid #eee;margin:20px 0}#akvo-rag .akvo-msg-assistant a{color:var(--akvo-primary, #007A78);text-decoration:underline}#akvo-rag .akvo-msg-assistant a:hover{text-decoration:none}
package/dist/akvo-rag.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see akvo-rag.js.LICENSE.txt */
2
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AkvoRAG=t():e.AkvoRAG=t()}(this,(()=>(()=>{"use strict";var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{initChat:()=>Lt});const{entries:n,setPrototypeOf:r,isFrozen:i,getPrototypeOf:o,getOwnPropertyDescriptor:s}=Object;let{freeze:a,seal:l,create:c}=Object,{apply:u,construct:p}="undefined"!=typeof Reflect&&Reflect;a||(a=function(e){return e}),l||(l=function(e){return e}),u||(u=function(e,t,n){return e.apply(t,n)}),p||(p=function(e,t){return new e(...t)});const h=A(Array.prototype.forEach),d=A(Array.prototype.lastIndexOf),f=A(Array.prototype.pop),g=A(Array.prototype.push),m=A(Array.prototype.splice),k=A(String.prototype.toLowerCase),b=A(String.prototype.toString),y=A(String.prototype.match),x=A(String.prototype.replace),v=A(String.prototype.indexOf),w=A(String.prototype.trim),S=A(Object.prototype.hasOwnProperty),_=A(RegExp.prototype.test),T=(E=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return p(E,t)});var E;function A(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return u(e,t,r)}}function R(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:k;r&&r(e,null);let o=t.length;for(;o--;){let r=t[o];if("string"==typeof r){const e=n(r);e!==r&&(i(t)||(t[o]=e),r=e)}e[r]=!0}return e}function L(e){for(let t=0;t<e.length;t++)S(e,t)||(e[t]=null);return e}function C(e){const t=c(null);for(const[r,i]of n(e))S(e,r)&&(Array.isArray(i)?t[r]=L(i):i&&"object"==typeof i&&i.constructor===Object?t[r]=C(i):t[r]=i);return t}function O(e,t){for(;null!==e;){const n=s(e,t);if(n){if(n.get)return A(n.get);if("function"==typeof n.value)return A(n.value)}e=o(e)}return function(){return null}}const z=a(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),N=a(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),I=a(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),M=a(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),P=a(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),$=a(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),D=a(["#text"]),H=a(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),U=a(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),B=a(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),j=a(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),q=l(/\{\{[\w\W]*|[\w\W]*\}\}/gm),F=l(/<%[\w\W]*|[\w\W]*%>/gm),W=l(/\$\{[\w\W]*/gm),G=l(/^data-[\-\w.\u00B7-\uFFFF]+$/),Z=l(/^aria-[\-\w]+$/),Y=l(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),X=l(/^(?:\w+script|data):/i),Q=l(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),J=l(/^html$/i),V=l(/^[a-z][.\w]*(-[.\w]+)+$/i);var K=Object.freeze({__proto__:null,ARIA_ATTR:Z,ATTR_WHITESPACE:Q,CUSTOM_ELEMENT:V,DATA_ATTR:G,DOCTYPE_NAME:J,ERB_EXPR:F,IS_ALLOWED_URI:Y,IS_SCRIPT_OR_DATA:X,MUSTACHE_EXPR:q,TMPLIT_EXPR:W});const ee=function(){return"undefined"==typeof window?null:window};var te=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ee();const r=t=>e(t);if(r.version="3.2.5",r.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return r.isSupported=!1,r;let{document:i}=t;const o=i,s=o.currentScript,{DocumentFragment:l,HTMLTemplateElement:u,Node:p,Element:E,NodeFilter:A,NamedNodeMap:L=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:q,DOMParser:F,trustedTypes:W}=t,G=E.prototype,Z=O(G,"cloneNode"),X=O(G,"remove"),Q=O(G,"nextSibling"),V=O(G,"childNodes"),te=O(G,"parentNode");if("function"==typeof u){const e=i.createElement("template");e.content&&e.content.ownerDocument&&(i=e.content.ownerDocument)}let ne,re="";const{implementation:ie,createNodeIterator:oe,createDocumentFragment:se,getElementsByTagName:ae}=i,{importNode:le}=o;let ce={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};r.isSupported="function"==typeof n&&"function"==typeof te&&ie&&void 0!==ie.createHTMLDocument;const{MUSTACHE_EXPR:ue,ERB_EXPR:pe,TMPLIT_EXPR:he,DATA_ATTR:de,ARIA_ATTR:fe,IS_SCRIPT_OR_DATA:ge,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:ke}=K;let{IS_ALLOWED_URI:be}=K,ye=null;const xe=R({},[...z,...N,...I,...P,...D]);let ve=null;const we=R({},[...H,...U,...B,...j]);let Se=Object.seal(c(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),_e=null,Te=null,Ee=!0,Ae=!0,Re=!1,Le=!0,Ce=!1,Oe=!0,ze=!1,Ne=!1,Ie=!1,Me=!1,Pe=!1,$e=!1,De=!0,He=!1,Ue=!0,Be=!1,je={},qe=null;const Fe=R({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let We=null;const Ge=R({},["audio","video","img","source","image","track"]);let Ze=null;const Ye=R({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Xe="http://www.w3.org/1998/Math/MathML",Qe="http://www.w3.org/2000/svg",Je="http://www.w3.org/1999/xhtml";let Ve=Je,Ke=!1,et=null;const tt=R({},[Xe,Qe,Je],b);let nt=R({},["mi","mo","mn","ms","mtext"]),rt=R({},["annotation-xml"]);const it=R({},["title","style","font","a","script"]);let ot=null;const st=["application/xhtml+xml","text/html"];let at=null,lt=null;const ct=i.createElement("form"),ut=function(e){return e instanceof RegExp||e instanceof Function},pt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!lt||lt!==e){if(e&&"object"==typeof e||(e={}),e=C(e),ot=-1===st.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,at="application/xhtml+xml"===ot?b:k,ye=S(e,"ALLOWED_TAGS")?R({},e.ALLOWED_TAGS,at):xe,ve=S(e,"ALLOWED_ATTR")?R({},e.ALLOWED_ATTR,at):we,et=S(e,"ALLOWED_NAMESPACES")?R({},e.ALLOWED_NAMESPACES,b):tt,Ze=S(e,"ADD_URI_SAFE_ATTR")?R(C(Ye),e.ADD_URI_SAFE_ATTR,at):Ye,We=S(e,"ADD_DATA_URI_TAGS")?R(C(Ge),e.ADD_DATA_URI_TAGS,at):Ge,qe=S(e,"FORBID_CONTENTS")?R({},e.FORBID_CONTENTS,at):Fe,_e=S(e,"FORBID_TAGS")?R({},e.FORBID_TAGS,at):{},Te=S(e,"FORBID_ATTR")?R({},e.FORBID_ATTR,at):{},je=!!S(e,"USE_PROFILES")&&e.USE_PROFILES,Ee=!1!==e.ALLOW_ARIA_ATTR,Ae=!1!==e.ALLOW_DATA_ATTR,Re=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Le=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Ce=e.SAFE_FOR_TEMPLATES||!1,Oe=!1!==e.SAFE_FOR_XML,ze=e.WHOLE_DOCUMENT||!1,Me=e.RETURN_DOM||!1,Pe=e.RETURN_DOM_FRAGMENT||!1,$e=e.RETURN_TRUSTED_TYPE||!1,Ie=e.FORCE_BODY||!1,De=!1!==e.SANITIZE_DOM,He=e.SANITIZE_NAMED_PROPS||!1,Ue=!1!==e.KEEP_CONTENT,Be=e.IN_PLACE||!1,be=e.ALLOWED_URI_REGEXP||Y,Ve=e.NAMESPACE||Je,nt=e.MATHML_TEXT_INTEGRATION_POINTS||nt,rt=e.HTML_INTEGRATION_POINTS||rt,Se=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Se.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Se.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Se.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ce&&(Ae=!1),Pe&&(Me=!0),je&&(ye=R({},D),ve=[],!0===je.html&&(R(ye,z),R(ve,H)),!0===je.svg&&(R(ye,N),R(ve,U),R(ve,j)),!0===je.svgFilters&&(R(ye,I),R(ve,U),R(ve,j)),!0===je.mathMl&&(R(ye,P),R(ve,B),R(ve,j))),e.ADD_TAGS&&(ye===xe&&(ye=C(ye)),R(ye,e.ADD_TAGS,at)),e.ADD_ATTR&&(ve===we&&(ve=C(ve)),R(ve,e.ADD_ATTR,at)),e.ADD_URI_SAFE_ATTR&&R(Ze,e.ADD_URI_SAFE_ATTR,at),e.FORBID_CONTENTS&&(qe===Fe&&(qe=C(qe)),R(qe,e.FORBID_CONTENTS,at)),Ue&&(ye["#text"]=!0),ze&&R(ye,["html","head","body"]),ye.table&&(R(ye,["tbody"]),delete _e.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw T('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw T('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ne=e.TRUSTED_TYPES_POLICY,re=ne.createHTML("")}else void 0===ne&&(ne=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(W,s)),null!==ne&&"string"==typeof re&&(re=ne.createHTML(""));a&&a(e),lt=e}},ht=R({},[...N,...I,...M]),dt=R({},[...P,...$]),ft=function(e){g(r.removed,{element:e});try{te(e).removeChild(e)}catch(t){X(e)}},gt=function(e,t){try{g(r.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){g(r.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(Me||Pe)try{ft(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},mt=function(e){let t=null,n=null;if(Ie)e="<remove></remove>"+e;else{const t=y(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===ot&&Ve===Je&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const r=ne?ne.createHTML(e):e;if(Ve===Je)try{t=(new F).parseFromString(r,ot)}catch(e){}if(!t||!t.documentElement){t=ie.createDocument(Ve,"template",null);try{t.documentElement.innerHTML=Ke?re:r}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(i.createTextNode(n),o.childNodes[0]||null),Ve===Je?ae.call(t,ze?"html":"body")[0]:ze?t.documentElement:o},kt=function(e){return oe.call(e.ownerDocument||e,e,A.SHOW_ELEMENT|A.SHOW_COMMENT|A.SHOW_TEXT|A.SHOW_PROCESSING_INSTRUCTION|A.SHOW_CDATA_SECTION,null)},bt=function(e){return e instanceof q&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof L)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},yt=function(e){return"function"==typeof p&&e instanceof p};function xt(e,t,n){h(e,(e=>{e.call(r,t,n,lt)}))}const vt=function(e){let t=null;if(xt(ce.beforeSanitizeElements,e,null),bt(e))return ft(e),!0;const n=at(e.nodeName);if(xt(ce.uponSanitizeElement,e,{tagName:n,allowedTags:ye}),e.hasChildNodes()&&!yt(e.firstElementChild)&&_(/<[/\w!]/g,e.innerHTML)&&_(/<[/\w!]/g,e.textContent))return ft(e),!0;if(7===e.nodeType)return ft(e),!0;if(Oe&&8===e.nodeType&&_(/<[/\w]/g,e.data))return ft(e),!0;if(!ye[n]||_e[n]){if(!_e[n]&&St(n)){if(Se.tagNameCheck instanceof RegExp&&_(Se.tagNameCheck,n))return!1;if(Se.tagNameCheck instanceof Function&&Se.tagNameCheck(n))return!1}if(Ue&&!qe[n]){const t=te(e)||e.parentNode,n=V(e)||e.childNodes;if(n&&t)for(let r=n.length-1;r>=0;--r){const i=Z(n[r],!0);i.__removalCount=(e.__removalCount||0)+1,t.insertBefore(i,Q(e))}}return ft(e),!0}return e instanceof E&&!function(e){let t=te(e);t&&t.tagName||(t={namespaceURI:Ve,tagName:"template"});const n=k(e.tagName),r=k(t.tagName);return!!et[e.namespaceURI]&&(e.namespaceURI===Qe?t.namespaceURI===Je?"svg"===n:t.namespaceURI===Xe?"svg"===n&&("annotation-xml"===r||nt[r]):Boolean(ht[n]):e.namespaceURI===Xe?t.namespaceURI===Je?"math"===n:t.namespaceURI===Qe?"math"===n&&rt[r]:Boolean(dt[n]):e.namespaceURI===Je?!(t.namespaceURI===Qe&&!rt[r])&&!(t.namespaceURI===Xe&&!nt[r])&&!dt[n]&&(it[n]||!ht[n]):!("application/xhtml+xml"!==ot||!et[e.namespaceURI]))}(e)?(ft(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!_(/<\/no(script|embed|frames)/i,e.innerHTML)?(Ce&&3===e.nodeType&&(t=e.textContent,h([ue,pe,he],(e=>{t=x(t,e," ")})),e.textContent!==t&&(g(r.removed,{element:e.cloneNode()}),e.textContent=t)),xt(ce.afterSanitizeElements,e,null),!1):(ft(e),!0)},wt=function(e,t,n){if(De&&("id"===t||"name"===t)&&(n in i||n in ct))return!1;if(Ae&&!Te[t]&&_(de,t));else if(Ee&&_(fe,t));else if(!ve[t]||Te[t]){if(!(St(e)&&(Se.tagNameCheck instanceof RegExp&&_(Se.tagNameCheck,e)||Se.tagNameCheck instanceof Function&&Se.tagNameCheck(e))&&(Se.attributeNameCheck instanceof RegExp&&_(Se.attributeNameCheck,t)||Se.attributeNameCheck instanceof Function&&Se.attributeNameCheck(t))||"is"===t&&Se.allowCustomizedBuiltInElements&&(Se.tagNameCheck instanceof RegExp&&_(Se.tagNameCheck,n)||Se.tagNameCheck instanceof Function&&Se.tagNameCheck(n))))return!1}else if(Ze[t]);else if(_(be,x(n,me,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==v(n,"data:")||!We[e])if(Re&&!_(ge,x(n,me,"")));else if(n)return!1;return!0},St=function(e){return"annotation-xml"!==e&&y(e,ke)},_t=function(e){xt(ce.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||bt(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ve,forceKeepAttr:void 0};let i=t.length;for(;i--;){const o=t[i],{name:s,namespaceURI:a,value:l}=o,c=at(s);let u="value"===s?l:w(l);if(n.attrName=c,n.attrValue=u,n.keepAttr=!0,n.forceKeepAttr=void 0,xt(ce.uponSanitizeAttribute,e,n),u=n.attrValue,!He||"id"!==c&&"name"!==c||(gt(s,e),u="user-content-"+u),Oe&&_(/((--!?|])>)|<\/(style|title)/i,u)){gt(s,e);continue}if(n.forceKeepAttr)continue;if(gt(s,e),!n.keepAttr)continue;if(!Le&&_(/\/>/i,u)){gt(s,e);continue}Ce&&h([ue,pe,he],(e=>{u=x(u,e," ")}));const p=at(e.nodeName);if(wt(p,c,u)){if(ne&&"object"==typeof W&&"function"==typeof W.getAttributeType)if(a);else switch(W.getAttributeType(p,c)){case"TrustedHTML":u=ne.createHTML(u);break;case"TrustedScriptURL":u=ne.createScriptURL(u)}try{a?e.setAttributeNS(a,s,u):e.setAttribute(s,u),bt(e)?ft(e):f(r.removed)}catch(e){}}}xt(ce.afterSanitizeAttributes,e,null)},Tt=function e(t){let n=null;const r=kt(t);for(xt(ce.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)xt(ce.uponSanitizeShadowNode,n,null),vt(n),_t(n),n.content instanceof l&&e(n.content);xt(ce.afterSanitizeShadowDOM,t,null)};return r.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,i=null,s=null,a=null;if(Ke=!e,Ke&&(e="\x3c!--\x3e"),"string"!=typeof e&&!yt(e)){if("function"!=typeof e.toString)throw T("toString is not a function");if("string"!=typeof(e=e.toString()))throw T("dirty is not a string, aborting")}if(!r.isSupported)return e;if(Ne||pt(t),r.removed=[],"string"==typeof e&&(Be=!1),Be){if(e.nodeName){const t=at(e.nodeName);if(!ye[t]||_e[t])throw T("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof p)n=mt("\x3c!----\x3e"),i=n.ownerDocument.importNode(e,!0),1===i.nodeType&&"BODY"===i.nodeName||"HTML"===i.nodeName?n=i:n.appendChild(i);else{if(!Me&&!Ce&&!ze&&-1===e.indexOf("<"))return ne&&$e?ne.createHTML(e):e;if(n=mt(e),!n)return Me?null:$e?re:""}n&&Ie&&ft(n.firstChild);const c=kt(Be?e:n);for(;s=c.nextNode();)vt(s),_t(s),s.content instanceof l&&Tt(s.content);if(Be)return e;if(Me){if(Pe)for(a=se.call(n.ownerDocument);n.firstChild;)a.appendChild(n.firstChild);else a=n;return(ve.shadowroot||ve.shadowrootmode)&&(a=le.call(o,a,!0)),a}let u=ze?n.outerHTML:n.innerHTML;return ze&&ye["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&_(J,n.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+u),Ce&&h([ue,pe,he],(e=>{u=x(u,e," ")})),ne&&$e?ne.createHTML(u):u},r.setConfig=function(){pt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Ne=!0},r.clearConfig=function(){lt=null,Ne=!1},r.isValidAttribute=function(e,t,n){lt||pt({});const r=at(e),i=at(t);return wt(r,i,n)},r.addHook=function(e,t){"function"==typeof t&&g(ce[e],t)},r.removeHook=function(e,t){if(void 0!==t){const n=d(ce[e],t);return-1===n?void 0:m(ce[e],n,1)[0]}return f(ce[e])},r.removeHooks=function(e){ce[e]=[]},r.removeAllHooks=function(){ce={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},r}();function ne(e){return ne="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ne(e)}function re(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function ie(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?re(Object(n),!0).forEach((function(t){oe(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):re(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function oe(e,t,n){return(t=function(e){var t=function(e){if("object"!=ne(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ne(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ne(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function se(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}let ae={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function le(e){ae=e}const ce={exec:()=>null};function ue(e,t=""){let n="string"==typeof e?e:e.source;const r={replace:(e,t)=>{let i="string"==typeof t?t:t.source;return i=i.replace(pe.caret,"$1"),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}const pe={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[\t ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},he=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,de=/(?:[*+-]|\d{1,9}[.)])/,fe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ge=ue(fe).replace(/bull/g,de).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),me=ue(fe).replace(/bull/g,de).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ke=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,be=/(?!\s*\])(?:\\.|[^\[\]\\])+/,ye=ue(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",be).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),xe=ue(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,de).getRegex(),ve="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",we=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Se=ue("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",we).replace("tag",ve).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),_e=ue(ke).replace("hr",he).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ve).getRegex(),Te={blockquote:ue(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",_e).getRegex(),code:/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,def:ye,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:he,html:Se,lheading:ge,list:xe,newline:/^(?:[ \t]*(?:\n|$))+/,paragraph:_e,table:ce,text:/^[^\n]+/},Ee=ue("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",he).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ve).getRegex(),Ae={...Te,lheading:me,table:Ee,paragraph:ue(ke).replace("hr",he).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ee).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ve).getRegex()},Re={...Te,html:ue("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",we).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ce,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ue(ke).replace("hr",he).replace("heading"," *#{1,6} *[^\n]").replace("lheading",ge).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Le=/^( {2,}|\\)\n(?!\s*$)/,Ce=/[\p{P}\p{S}]/u,Oe=/[\s\p{P}\p{S}]/u,ze=/[^\s\p{P}\p{S}]/u,Ne=ue(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Oe).getRegex(),Ie=/(?!~)[\p{P}\p{S}]/u,Me=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Pe=ue(Me,"u").replace(/punct/g,Ce).getRegex(),$e=ue(Me,"u").replace(/punct/g,Ie).getRegex(),De="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",He=ue(De,"gu").replace(/notPunctSpace/g,ze).replace(/punctSpace/g,Oe).replace(/punct/g,Ce).getRegex(),Ue=ue(De,"gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|~)/u).replace(/punctSpace/g,/(?!~)[\s\p{P}\p{S}]/u).replace(/punct/g,Ie).getRegex(),Be=ue("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ze).replace(/punctSpace/g,Oe).replace(/punct/g,Ce).getRegex(),je=ue(/\\(punct)/,"gu").replace(/punct/g,Ce).getRegex(),qe=ue(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Fe=ue(we).replace("(?:--\x3e|$)","--\x3e").getRegex(),We=ue("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Fe).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ge=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ze=ue(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Ge).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ye=ue(/^!?\[(label)\]\[(ref)\]/).replace("label",Ge).replace("ref",be).getRegex(),Xe=ue(/^!?\[(ref)\](?:\[\])?/).replace("ref",be).getRegex(),Qe={_backpedal:ce,anyPunctuation:je,autolink:qe,blockSkip:/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,br:Le,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:ce,emStrongLDelim:Pe,emStrongRDelimAst:He,emStrongRDelimUnd:Be,escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,link:Ze,nolink:Xe,punctuation:Ne,reflink:Ye,reflinkSearch:ue("reflink|nolink(?!\\()","g").replace("reflink",Ye).replace("nolink",Xe).getRegex(),tag:We,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:ce},Je={...Qe,link:ue(/^!?\[(label)\]\((.*?)\)/).replace("label",Ge).getRegex(),reflink:ue(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ge).getRegex()},Ve={...Qe,emStrongRDelimAst:Ue,emStrongLDelim:$e,url:ue(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Ke={...Ve,br:ue(Le).replace("{2,}","*").getRegex(),text:ue(Ve.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},et={normal:Te,gfm:Ae,pedantic:Re},tt={normal:Qe,gfm:Ve,breaks:Ke,pedantic:Je},nt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},rt=e=>nt[e];function it(e,t){if(t){if(pe.escapeTest.test(e))return e.replace(pe.escapeReplace,rt)}else if(pe.escapeTestNoEncode.test(e))return e.replace(pe.escapeReplaceNoEncode,rt);return e}function ot(e){try{e=encodeURI(e).replace(pe.percentDecode,"%")}catch{return null}return e}function st(e,t){const n=e.replace(pe.findPipe,((e,t,n)=>{let r=!1,i=t;for(;--i>=0&&"\\"===n[i];)r=!r;return r?"|":" |"})).split(pe.splitPipe);let r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(pe.slashPipe,"|");return n}function at(e,t,n){const r=e.length;if(0===r)return"";let i=0;for(;i<r&&e.charAt(r-i-1)===t;)i++;return e.slice(0,r-i)}function lt(e,t,n,r,i){const o=t.href,s=t.title||null,a=e[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;const l={type:"!"===e[0].charAt(0)?"image":"link",raw:n,href:o,title:s,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}class ct{options;rules;lexer;constructor(e){this.options=e||ae}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:at(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t,n){const r=e.match(n.other.indentCodeCompensation);if(null===r)return t;const i=r[1];return t.split("\n").map((e=>{const t=e.match(n.other.beginningSpace);if(null===t)return e;const[r]=t;return r.length>=i.length?e.slice(i.length):e})).join("\n")}(e,t[3]||"",this.rules);return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){const t=at(e,"#");this.options.pedantic?e=t.trim():t&&!this.rules.other.endingSpaceChar.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:at(t[0],"\n")}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){let e=at(t[0],"\n").split("\n"),n="",r="";const i=[];for(;e.length>0;){let t=!1;const o=[];let s;for(s=0;s<e.length;s++)if(this.rules.other.blockquoteStart.test(e[s]))o.push(e[s]),t=!0;else{if(t)break;o.push(e[s])}e=e.slice(s);const a=o.join("\n"),l=a.replace(this.rules.other.blockquoteSetextReplace,"\n $1").replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}\n${a}`:a,r=r?`${r}\n${l}`:l;const c=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(l,i,!0),this.lexer.state.top=c,0===e.length)break;const u=i.at(-1);if("code"===u?.type)break;if("blockquote"===u?.type){const t=u,o=t.raw+"\n"+e.join("\n"),s=this.blockquote(o);i[i.length-1]=s,n=n.substring(0,n.length-t.raw.length)+s.raw,r=r.substring(0,r.length-t.text.length)+s.text;break}if("list"!==u?.type);else{const t=u,o=t.raw+"\n"+e.join("\n"),s=this.list(o);i[i.length-1]=s,n=n.substring(0,n.length-u.raw.length)+s.raw,r=r.substring(0,r.length-t.raw.length)+s.raw,e=o.substring(i.at(-1).raw.length).split("\n")}}return{type:"blockquote",raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");const o=this.rules.other.listItemRegex(n);let s=!1;for(;e;){let n=!1,r="",a="";if(!(t=o.exec(e)))break;if(this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let l=t[2].split("\n",1)[0].replace(this.rules.other.listReplaceTabs,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],u=!l.trim(),p=0;if(this.options.pedantic?(p=2,a=l.trimStart()):u?p=t[1].length+1:(p=t[2].search(this.rules.other.nonSpaceChar),p=p>4?1:p,a=l.slice(p),p+=t[1].length),u&&this.rules.other.blankLine.test(c)&&(r+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=this.rules.other.nextBulletRegex(p),n=this.rules.other.hrRegex(p),i=this.rules.other.fencesBeginRegex(p),o=this.rules.other.headingBeginRegex(p),s=this.rules.other.htmlBeginRegex(p);for(;e;){const h=e.split("\n",1)[0];let d;if(c=h,this.options.pedantic?(c=c.replace(this.rules.other.listReplaceNesting," "),d=c):d=c.replace(this.rules.other.tabCharGlobal," "),i.test(c))break;if(o.test(c))break;if(s.test(c))break;if(t.test(c))break;if(n.test(c))break;if(d.search(this.rules.other.nonSpaceChar)>=p||!c.trim())a+="\n"+d.slice(p);else{if(u)break;if(l.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4)break;if(i.test(l))break;if(o.test(l))break;if(n.test(l))break;a+="\n"+c}u||c.trim()||(u=!0),r+=h+"\n",e=e.substring(h.length+1),l=d.slice(p)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(s=!0));let h,d=null;this.options.gfm&&(d=this.rules.other.listIsTask.exec(a),d&&(h="[ ] "!==d[0],a=a.replace(this.rules.other.listReplaceTask,""))),i.items.push({type:"list_item",raw:r,task:!!d,checked:h,loose:!1,text:a,tokens:[]}),i.raw+=r}const a=i.items.at(-1);if(!a)return;a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd(),i.raw=i.raw.trimEnd();for(let e=0;e<i.items.length;e++)if(this.lexer.state.top=!1,i.items[e].tokens=this.lexer.blockTokens(i.items[e].text,[]),!i.loose){const t=i.items[e].tokens.filter((e=>"space"===e.type)),n=t.length>0&&t.some((e=>this.rules.other.anyLine.test(e.raw)));i.loose=n}if(i.loose)for(let e=0;e<i.items.length;e++)i.items[e].loose=!0;return i}}html(e){const t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:r}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!this.rules.other.tableDelimiter.test(t[2]))return;const n=st(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split("\n"):[],o={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(const e of r)this.rules.other.tableAlignRight.test(e)?o.align.push("right"):this.rules.other.tableAlignCenter.test(e)?o.align.push("center"):this.rules.other.tableAlignLeft.test(e)?o.align.push("left"):o.align.push(null);for(let e=0;e<n.length;e++)o.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:o.align[e]});for(const e of i)o.rows.push(st(e,o.header.length).map(((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:o.align[t]}))));return o}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;const t=at(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let r=0;r<e.length;r++)if("\\"===e[r])r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}(t[2],"()");if(-2===e)return;if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],r="";if(this.options.pedantic){const e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),lt(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:r?r.replace(this.rules.inline.anyPunctuation,"$1"):r},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return lt(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(r&&(!r[3]||!n.match(this.rules.other.unicodeAlphaNumeric))&&(!r[1]&&!r[2]||!n||this.rules.inline.punctuation.exec(n))){const n=[...r[0]].length-1;let i,o,s=n,a=0;const l="*"===r[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(l.lastIndex=0,t=t.slice(-1*e.length+n);null!=(r=l.exec(t));){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(o=[...i].length,r[3]||r[4]){s+=o;continue}if((r[5]||r[6])&&n%3&&!((n+o)%3)){a+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s+a);const t=[...r[0]][0].length,l=e.slice(0,n+r.index+t+o);if(Math.min(n,o)%2){const e=l.slice(1,-1);return{type:"em",raw:l,text:e,tokens:this.lexer.inlineTokens(e)}}const c=l.slice(2,-2);return{type:"strong",raw:l,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal," ");const n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=t[1],n="mailto:"+e):(e=t[1],n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=t[0],n="mailto:"+e;else{let r;do{r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(r!==t[0]);e=t[0],n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){const e=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:e}}}}class ut{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ae,this.options.tokenizer=this.options.tokenizer||new ct,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const t={other:pe,block:et.normal,inline:tt.normal};this.options.pedantic?(t.block=et.pedantic,t.inline=tt.pedantic):this.options.gfm&&(t.block=et.gfm,this.options.breaks?t.inline=tt.breaks:t.inline=tt.gfm),this.tokenizer.rules=t}static get rules(){return{block:et,inline:tt}}static lex(e,t){return new ut(t).lex(e)}static lexInline(e,t){return new ut(t).inlineTokens(e)}lex(e){e=e.replace(pe.carriageReturn,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(pe.tabCharGlobal," ").replace(pe.spaceLine,""));e;){let r;if(this.options.extensions?.block?.some((n=>!!(r=n.call({lexer:this},e,t))&&(e=e.substring(r.raw.length),t.push(r),!0))))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);const n=t.at(-1);1===r.raw.length&&void 0!==n?n.raw+="\n":t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);const n=t.at(-1);"paragraph"===n?.type||"text"===n?.type?(n.raw+="\n"+r.raw,n.text+="\n"+r.text,this.inlineQueue.at(-1).src=n.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);const n=t.at(-1);"paragraph"===n?.type||"text"===n?.type?(n.raw+="\n"+r.raw,n.text+="\n"+r.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title});continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let t=1/0;const n=e.slice(1);let r;this.options.extensions.startBlock.forEach((e=>{r=e.call({lexer:this},n),"number"==typeof r&&r>=0&&(t=Math.min(t,r))})),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){const o=t.at(-1);n&&"paragraph"===o?.type?(o.raw+="\n"+r.raw,o.text+="\n"+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length)}else if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);const n=t.at(-1);"text"===n?.type?(n.raw+="\n"+r.raw,n.text+="\n"+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(r)}else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(r=this.tokenizer.rules.inline.reflinkSearch.exec(n));)e.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(r=this.tokenizer.rules.inline.anyPunctuation.exec(n));)n=n.slice(0,r.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;null!=(r=this.tokenizer.rules.inline.blockSkip.exec(n));)n=n.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let i=!1,o="";for(;e;){let r;if(i||(o=""),i=!1,this.options.extensions?.inline?.some((n=>!!(r=n.call({lexer:this},e,t))&&(e=e.substring(r.raw.length),t.push(r),!0))))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);const n=t.at(-1);"text"===r.type&&"text"===n?.type?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let s=e;if(this.options.extensions?.startInline){let t=1/0;const n=e.slice(1);let r;this.options.extensions.startInline.forEach((e=>{r=e.call({lexer:this},n),"number"==typeof r&&r>=0&&(t=Math.min(t,r))})),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(s)){e=e.substring(r.raw.length),"_"!==r.raw.slice(-1)&&(o=r.raw.slice(-1)),i=!0;const n=t.at(-1);"text"===n?.type?(n.raw+=r.raw,n.text+=r.text):t.push(r)}else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return t}}class pt{options;parser;constructor(e){this.options=e||ae}space(e){return""}code({text:e,lang:t,escaped:n}){const r=(t||"").match(pe.notSpaceStart)?.[0],i=e.replace(pe.endingNewline,"")+"\n";return r?'<pre><code class="language-'+it(r)+'">'+(n?i:it(i,!0))+"</code></pre>\n":"<pre><code>"+(n?i:it(i,!0))+"</code></pre>\n"}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return"<hr>\n"}list(e){const t=e.ordered,n=e.start;let r="";for(let t=0;t<e.items.length;t++){const n=e.items[t];r+=this.listitem(n)}const i=t?"ol":"ul";return"<"+i+(t&&1!==n?' start="'+n+'"':"")+">\n"+r+"</"+i+">\n"}listitem(e){let t="";if(e.task){const n=this.checkbox({checked:!!e.checked});e.loose?"paragraph"===e.tokens[0]?.type?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&"text"===e.tokens[0].tokens[0].type&&(e.tokens[0].tokens[0].text=n+" "+it(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`<li>${t}</li>\n`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t="",n="";for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let r="";for(let t=0;t<e.rows.length;t++){const i=e.rows[t];n="";for(let e=0;e<i.length;e++)n+=this.tablecell(i[e]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),"<table>\n<thead>\n"+t+"</thead>\n"+r+"</table>\n"}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){const t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${it(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){const r=this.parser.parseInline(n),i=ot(e);if(null===i)return r;let o='<a href="'+(e=i)+'"';return t&&(o+=' title="'+it(t)+'"'),o+=">"+r+"</a>",o}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));const i=ot(e);if(null===i)return it(n);let o=`<img src="${e=i}" alt="${n}"`;return t&&(o+=` title="${it(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:it(e.text)}}class ht{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}}class dt{options;renderer;textRenderer;constructor(e){this.options=e||ae,this.options.renderer=this.options.renderer||new pt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ht}static parse(e,t){return new dt(t).parse(e)}static parseInline(e,t){return new dt(t).parseInline(e)}parse(e,t=!0){let n="";for(let r=0;r<e.length;r++){const i=e[r];if(this.options.extensions?.renderers?.[i.type]){const e=i,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){n+=t||"";continue}}const o=i;switch(o.type){case"space":n+=this.renderer.space(o);continue;case"hr":n+=this.renderer.hr(o);continue;case"heading":n+=this.renderer.heading(o);continue;case"code":n+=this.renderer.code(o);continue;case"table":n+=this.renderer.table(o);continue;case"blockquote":n+=this.renderer.blockquote(o);continue;case"list":n+=this.renderer.list(o);continue;case"html":n+=this.renderer.html(o);continue;case"paragraph":n+=this.renderer.paragraph(o);continue;case"text":{let i=o,s=this.renderer.text(i);for(;r+1<e.length&&"text"===e[r+1].type;)i=e[++r],s+="\n"+this.renderer.text(i);n+=t?this.renderer.paragraph({type:"paragraph",raw:s,text:s,tokens:[{type:"text",raw:s,text:s,escaped:!0}]}):s;continue}default:{const e='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}parseInline(e,t=this.renderer){let n="";for(let r=0;r<e.length;r++){const i=e[r];if(this.options.extensions?.renderers?.[i.type]){const e=this.options.extensions.renderers[i.type].call({parser:this},i);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){n+=e||"";continue}}const o=i;switch(o.type){case"escape":case"text":n+=t.text(o);break;case"html":n+=t.html(o);break;case"link":n+=t.link(o);break;case"image":n+=t.image(o);break;case"strong":n+=t.strong(o);break;case"em":n+=t.em(o);break;case"codespan":n+=t.codespan(o);break;case"br":n+=t.br(o);break;case"del":n+=t.del(o);break;default:{const e='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}}class ft{options;block;constructor(e){this.options=e||ae}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?ut.lex:ut.lexInline}provideParser(){return this.block?dt.parse:dt.parseInline}}const gt=new class{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=dt;Renderer=pt;TextRenderer=ht;Lexer=ut;Tokenizer=ct;Hooks=ft;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{const e=r;for(const r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(const r of e.rows)for(const e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{const e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach((r=>{const i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let r=e.renderer.apply(this,t);return!1===r&&(r=n.apply(this,t)),r}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new pt(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;const r=n,i=e.renderer[r],o=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return!1===n&&(n=o.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new ct(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const r=n,i=e.tokenizer[r],o=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return!1===n&&(n=o.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new ft;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;const r=n,i=e.hooks[r],o=t[r];ft.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async)return Promise.resolve(i.call(t,e)).then((e=>o.call(t,e)));const n=i.call(t,e);return o.call(t,n)}:t[r]=(...e)=>{let n=i.apply(t,e);return!1===n&&(n=o.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ut.lex(e,t??this.defaults)}parser(e,t){return dt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{const r={...n},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(!0===this.defaults.async&&!1===r.async)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(null==t)return o(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof t)return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));i.hooks&&(i.hooks.options=i,i.hooks.block=e);const s=i.hooks?i.hooks.provideLexer():e?ut.lex:ut.lexInline,a=i.hooks?i.hooks.provideParser():e?dt.parse:dt.parseInline;if(i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(t):t).then((e=>s(e,i))).then((e=>i.hooks?i.hooks.processAllTokens(e):e)).then((e=>i.walkTokens?Promise.all(this.walkTokens(e,i.walkTokens)).then((()=>e)):e)).then((e=>a(e,i))).then((e=>i.hooks?i.hooks.postprocess(e):e)).catch(o);try{i.hooks&&(t=i.hooks.preprocess(t));let e=s(t,i);i.hooks&&(e=i.hooks.processAllTokens(e)),i.walkTokens&&this.walkTokens(e,i.walkTokens);let n=a(e,i);return i.hooks&&(n=i.hooks.postprocess(n)),n}catch(e){return o(e)}}}onError(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="<p>An error occurred:</p><pre>"+it(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function mt(e,t){return gt.parse(e,t)}function kt(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=document.querySelector("#akvo-rag-body");if(i){var o=document.createElement("div"),s="akvo-msg-".concat(e,"-").concat(r);if(o.id=s,o.className="akvo-msg-".concat(e),n)o.innerHTML='\n <div class="typing-indicator">\n <span></span><span></span><span></span>\n </div>\n ';else{var a=mt.parse(t||""),l=te.sanitize(a);o.innerHTML=l}return i.appendChild(o),i.scrollTop=i.scrollHeight,o}}function bt(){"undefined"!=typeof document&&"function"==typeof document.querySelectorAll&&document.querySelectorAll(".citation-popover").forEach((function(e){return e.remove()}))}function yt(e){bt();var t=e.target,n=document.createElement("div");n.className="citation-popover";var r='\n <div class="arrow"></div>\n <div><strong>'.concat(t.dataset.title||"","</strong></div>\n <div><small>Source: ").concat(t.dataset.source||"",", Page: ").concat(t.dataset.page||"","</small></div>\n <p>").concat(t.dataset.text||"","</p>\n ");n.innerHTML=te.sanitize(r),document.body.appendChild(n);var i=n.offsetWidth,o=n.offsetHeight,s=t.getBoundingClientRect(),a=s.left+window.scrollX-i/2+s.width/2,l=window.scrollX+window.innerWidth-i-10,c=window.scrollX+10;a=Math.max(Math.min(a,l),c),s.top;var u=window.innerHeight-s.bottom<o+8+10,p=u?s.top+window.scrollY-o-8-2:s.bottom+window.scrollY+8+2;n.style.left="".concat(a,"px"),n.style.top="".concat(p,"px"),n.dataset.target=t.dataset.id,n.classList.toggle("above",u),n.classList.toggle("below",!u);var h=n.querySelector(".arrow"),d=s.left+s.width/2+window.scrollX-a-8;d=Math.max(8,Math.min(d,i-16)),h.style.left="".concat(d,"px")}function xt(e){var t=e.target;document.querySelectorAll(".citation-popover").forEach((function(e){e.dataset.target===t.dataset.id&&e.remove()}))}function vt(e){return vt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},vt(e)}function wt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function St(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?wt(Object(n),!0).forEach((function(t){_t(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):wt(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _t(e,t,n){return(t=Et(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tt(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Et(r.key),r)}}function Et(e){var t=function(e){if("object"!=vt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=vt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==vt(t)?t:t+""}mt.options=mt.setOptions=function(e){return gt.setOptions(e),mt.defaults=gt.defaults,le(mt.defaults),mt},mt.getDefaults=function(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}},mt.defaults=ae,mt.use=function(...e){return gt.use(...e),mt.defaults=gt.defaults,le(mt.defaults),mt},mt.walkTokens=function(e,t){return gt.walkTokens(e,t)},mt.parseInline=gt.parseInline,mt.Parser=dt,mt.parser=dt.parse,mt.Renderer=pt,mt.TextRenderer=ht,mt.Lexer=ut,mt.lexer=ut.lex,mt.Tokenizer=ct,mt.Hooks=ft,mt.parse=mt,mt.options,mt.setOptions,mt.use,mt.walkTokens,mt.parseInline,dt.parse,ut.lex,mt.setOptions({gfm:!0,breaks:!0});var At="Hello! How can I help you today?",Rt=function(){return e=function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.options=n,this.showLauncher=void 0===this.options.showLauncher||Boolean(this.options.showLauncher),this.isMinimized=void 0!==this.options.startMinimized?Boolean(this.options.startMinimized):this.showLauncher,this.wsConnection=null,this.currentAssistantMsgEl=null,this.isLoading=!1,this.citations=[],this.messageCounter=0,this.chatHistory=[],this.visitorId=((t=localStorage.getItem("akvo-visitor-id"))||(t=crypto.randomUUID(),localStorage.setItem("akvo-visitor-id",t)),t),this.container=null,this.launcher=null,this._onMessage=this._onMessage.bind(this),this._handleSend=this._handleSend.bind(this),this._handleStartChat=this._handleStartChat.bind(this),this.init()},t=[{key:"init",value:function(){if(this.container=document.getElementById("akvo-rag"),this.launcher=document.getElementById("akvo-rag-launcher"),this.container)return this._applyCustomStyles(this.container,!1),this.launcher&&this._applyCustomStyles(this.launcher,!0),void(this.isMinimized?this.close():this.open());this.showLauncher?this._createLauncher():this.launcher=null,this._createUI(),this._bindEvents(),this.isMinimized?this.close():this.open(),this.options.kb_id&&this._connect()}},{key:"destroy",value:function(){this.wsConnection&&this.wsConnection.close(),this.container&&(this.container.remove(),this.container=null),this.launcher&&(this.launcher.remove(),this.launcher=null),bt()}},{key:"open",value:function(){var e;this.isMinimized=!1,this.container&&(this.container.style&&(this.container.style.display="flex"),null===(e=this.container.classList)||void 0===e||e.remove("minimized")),this.launcher&&this.launcher.style&&(this.launcher.style.display="none")}},{key:"close",value:function(){var e;this.isMinimized=!0,this.container&&(this.showLauncher?this.container.style&&(this.container.style.display="none"):null===(e=this.container.classList)||void 0===e||e.add("minimized")),this.launcher&&this.launcher.style&&(this.launcher.style.display="flex")}},{key:"minimize",value:function(){this.close()}},{key:"_isValidCssColor",value:function(e){if(!e||"string"!=typeof e)return!1;var t=e.trim();return!!/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(t)||!!/^(?:rgb|hsl)a?\(\s*[\d.%\s,/-]+\s*\)$/i.test(t)||/^(?:teal|blue|green|red|purple|indigo|slate|gray|black|white|transparent)$/i.test(t)}},{key:"_toCssDimension",value:function(e){if("number"==typeof e&&Number.isFinite(e)&&e>0)return"".concat(e,"px");if("string"==typeof e){var t=e.trim();if(/^\d+(\.\d+)?$/.test(t))return"".concat(t,"px");if(/^\d+(\.\d+)?(px|rem|em|vh|vw|%)$/i.test(t))return t}return null}},{key:"_toSafeZIndex",value:function(e){if("number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=2147483647)return e;if("string"==typeof e){var t=e.trim();if(/^\d+$/.test(t)){var n=parseInt(t,10);if(!isNaN(n)&&n>=0&&n<=2147483647)return n}}return null}},{key:"_applyCustomStyles",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e&&e.style){var n;this._isValidCssColor(this.options.primaryColor)&&"function"==typeof e.style.setProperty&&e.style.setProperty("--akvo-primary",this.options.primaryColor.trim()),"bottom-left"===String(this.options.position||"").trim().toLowerCase()&&(null===(n=e.classList)||void 0===n||n.add("akvo-position-left"));var r=this._toSafeZIndex(this.options.zIndex);if(null!==r&&"function"==typeof e.style.setProperty){var i=t?Math.max(0,r-1):r;e.style.setProperty("--akvo-z-index",String(i)),e.style.zIndex=String(i)}if(t&&"function"==typeof e.style.setProperty){var o=this._toCssDimension(this.options.launcherSize),s=this._toCssDimension(this.options.launcherWidth)||o,a=this._toCssDimension(this.options.launcherHeight)||o;s&&e.style.setProperty("--akvo-launcher-width",s),a&&e.style.setProperty("--akvo-launcher-height",a)}else if(!t&&"function"==typeof e.style.setProperty){var l=this._toCssDimension(this.options.width);l&&e.style.setProperty("--akvo-width",l);var c=this._toCssDimension(this.options.height);c&&e.style.setProperty("--akvo-height",c);var u=this._toCssDimension(this.options.borderRadius);u&&e.style.setProperty("--akvo-border-radius",u)}}}},{key:"_sanitizeHtml",value:function(e,t){if("function"==typeof(null==te?void 0:te.sanitize))return te.sanitize(e,t);if("function"==typeof te)try{var n=te(globalThis.window||globalThis);if("function"==typeof(null==n?void 0:n.sanitize))return n.sanitize(e,t)}catch(e){}return String(e).replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+="[^"]*"/gi,"").replace(/on\w+='[^']*'/gi,"")}},{key:"_renderIcon",value:function(e){if(!e)return arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";var t=String(e).trim();if(t.startsWith("<svg")||t.includes("<svg"))return this._sanitizeHtml(t,{USE_PROFILES:{svg:!0,svgFilters:!0}});if(/^(https?:\/\/|data:image\/|\/|\.\/)/i.test(t)||/\.(svg|png|jpe?g|webp|gif)(\?.*)?$/i.test(t)){var n=this._sanitizeHtml(t);return'<img src="'.concat(n,'" alt="icon" class="akvo-icon-img" />')}var r=this._sanitizeHtml(t);return'<i class="'.concat(r,'" aria-hidden="true"></i>')}},{key:"_createLauncher",value:function(){this.launcher=document.createElement("button"),this.launcher.id="akvo-rag-launcher",this.launcher.className="akvo-rag-launcher","function"==typeof this.launcher.setAttribute&&(this.launcher.setAttribute("type","button"),this.launcher.setAttribute("aria-label","Open chat")),this.launcher.innerHTML=this._renderIcon(this.options.launcherIcon,'<i class="fa fa-comments" aria-hidden="true"></i>'),this._applyCustomStyles(this.launcher,!0),this.launcher.style&&(this.launcher.style.display=this.isMinimized?"flex":"none"),document.body&&"function"==typeof document.body.appendChild&&document.body.appendChild(this.launcher)}},{key:"_renderInputArea",value:function(){return'\n <input\n type="text"\n id="akvo-rag-input"\n placeholder="Type a message..."\n autocomplete="off"\n autocorrect="off"\n autocapitalize="off"\n spellcheck="false"\n />\n <button id="akvo-rag-send-btn">Send</button>\n '}},{key:"_createUI",value:function(){var e;this.container=document.createElement("div"),this.container.id="akvo-rag",this._applyCustomStyles(this.container,!1),this.container.style&&(this.container.style.display=this.showLauncher&&this.isMinimized?"none":"flex");var t=this.options.headerIcon?'<span class="akvo-header-icon">'.concat(this._renderIcon(this.options.headerIcon,""),"</span>"):"";this.container.innerHTML='\n <div id="akvo-rag-header">\n <div class="akvo-header-title">\n '.concat(t,"\n <span>").concat(this.options.title||"Chatbot",'</span>\n </div>\n <button id="akvo-rag-close-btn" class="akvo-rag-close-btn" aria-label="Minimize chat">\n <i class="fa fa-window-minimize" aria-hidden="true"></i>\n </button>\n </div>\n <div id="akvo-rag-body" class="akvo-rag-body">\n ').concat(!this.options.kb_id&&null!==(e=this.options.kb_options)&&void 0!==e&&e.length?'\n <div id="akvo-kb-options" class="akvo-kb-options">\n <p>Please select a knowledge base to continue:</p>\n '.concat(this.options.kb_options.map((function(e){return'\n <div class="kb-option">\n <input type="radio" id="kb-'.concat(e.kb_id,'" name="akvo-kb" value="').concat(e.kb_id,'">\n <label for="kb-').concat(e.kb_id,'">').concat(e.label,"</label>\n </div>\n ")})).join(""),'\n <div class="akvo-kb-options-hint">\n After selecting, click "Start Chat" to begin.\n </div>\n </div>\n '):'<p class="akvo-msg-system">'.concat(At,"</p>"),'\n </div>\n <div id="akvo-rag-input-container" class="akvo-rag-input-container">\n ').concat(this.options.kb_id?this._renderInputArea():'\n <button id="akvo-start-chat-btn" class="akvo-start-chat-btn" style="flex: 1;" disabled>\n Start Chat\n </button>\n ',"\n </div>\n "),document.body.appendChild(this.container)}},{key:"_bindEvents",value:function(){var e,t,n,r=this,i=null===(e=this.container)||void 0===e?void 0:e.querySelector("#akvo-rag-header"),o=null===(t=this.container)||void 0===t?void 0:t.querySelector("#akvo-rag-close-btn");if(this.launcher&&"function"==typeof this.launcher.addEventListener&&this.launcher.addEventListener("click",(function(){r.open()})),o&&o.addEventListener("click",(function(e){var t;e.stopPropagation(),r.showLauncher?r.close():null!==(t=r.container)&&void 0!==t&&null!==(t=t.classList)&&void 0!==t&&t.contains("minimized")?r.open():r.close()})),i&&i.addEventListener("click",(function(){var e;r.showLauncher?r.isMinimized&&r.open():null!==(e=r.container)&&void 0!==e&&null!==(e=e.classList)&&void 0!==e&&e.contains("minimized")&&r.open()})),!this.options.kb_id&&null!==(n=this.options.kb_options)&&void 0!==n&&n.length){var s=this.container.querySelector("#akvo-start-chat-btn");this.container.querySelectorAll("input[name='akvo-kb']").forEach((function(e){e.addEventListener("change",(function(){s.disabled=!1}))})),s.addEventListener("click",this._handleStartChat)}else this._bindInputEvents()}},{key:"_bindInputEvents",value:function(){var e=this,t=this.container.querySelector("#akvo-rag-input"),n=this.container.querySelector("#akvo-rag-send-btn");t&&n&&(t.addEventListener("keypress",(function(t){"Enter"===t.key&&e._handleSend()})),n.addEventListener("click",this._handleSend))}},{key:"_connect",value:function(){var e=this,t={onReconnect:function(t){console.log("Reconnecting attempt #".concat(t,", resetting isLoading")),e.isLoading=!1,e._updateSendButtonState()},onMaxReconnect:function(){e.isLoading=!1,e._updateSendButtonState(),kt("system","Connection to the chat server lost. Please check your network and refresh the page.")}};this.wsConnection=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=null,i=0,o=e.wsURL||e.wsUrl;return function s(){o?(console.log("[WebSocket] Connecting to: ".concat(o)),(r=new WebSocket(o)).onopen=function(){console.log("[WebSocket] Connected"),i=0,r.send(JSON.stringify({type:"auth",visitor_id:e.visitorId,kb_id:e.kb_id})),e.onOpen&&e.onOpen()},r.onmessage=function(e){var n=null;try{n=JSON.parse(e.data)}catch(t){return void console.warn("[WebSocket] Received non-JSON data",e.data)}if(t){if("ping"===n.type)return r.send(JSON.stringify({type:"pong"})),void console.log("Pong sent to server");if("response_chunk"===n.type&&n.content.includes("__LLM_RESPONSE__"))try{var i,o=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,o,s,a=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return se(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?se(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(n.content.split("__LLM_RESPONSE__"),2),s=o[0],a=o[1],l=function(e){if(!e)return"";var t=e.split(":")[1].trim().replace(/^"|"$/g,"").match(/[A-Za-z0-9+/=]+/);return t?t[0]:""}(s),c=null;if(l)try{var u=atob(l);c=JSON.parse(u)}catch(e){console.warn("Failed to decode or parse base64 contextData",e)}var p=(null===(i=c)||void 0===i||null===(i=i.context)||void 0===i?void 0:i.map((function(e,t){return{id:t+1,text:e.page_content,metadata:e.metadata}})))||[];t(ie(ie({},n),{},{content:a.trim(),citations:p}))}catch(e){console.error("Failed to parse __LLM_RESPONSE__",e),t(n)}else t(n)}},r.onclose=function(t){if(console.warn("[WebSocket] Closed (URL: ".concat(o,"): code=").concat(t.code," reason=").concat(t.reason||"no reason provided")),e.autoReconnect&&1e3!==t.code)if(i<10){i++;var r=Math.min(1e3*Math.pow(2,i-1),3e4),a=1e3*Math.random()-500,l=Math.max(1e3,r+a);console.log("[WebSocket] Reconnect attempt ".concat(i," in ").concat(Math.round(l),"ms")),null!=n&&n.onReconnect&&n.onReconnect(i),setTimeout((function(){s()}),l)}else console.error("[WebSocket] Max reconnect attempts reached."),e.onMaxReconnect&&e.onMaxReconnect()},r.onerror=function(t){console.error("[WebSocket] Error (URL: ".concat(o,"):"),t),e.onError&&e.onError(t)}):console.warn("[WebSocket] No wsURL provided in options.")}(),{get socket(){return r},close:function(){e.autoReconnect=!1,r&&r.close(1e3,"Client closed connection")}}}(St(St({},this.options),{},{autoReconnect:!0,visitorId:this.visitorId,onMaxReconnect:t.onMaxReconnect}),this._onMessage,t)}},{key:"_handleStartChat",value:function(){var e=this.container.querySelector("input[name='akvo-kb']:checked");if(e){this.options.kb_id=parseInt(e.value,10);var t=this.container.querySelector("#akvo-kb-options");t&&t.remove(),this.container.querySelector("#akvo-rag-input-container").innerHTML=this._renderInputArea(),this._connect();var n=this.container.querySelector("#akvo-rag-body"),r=document.createElement("p");r.className="akvo-msg-system",r.textContent=At,n.appendChild(r),this._bindInputEvents()}}},{key:"_handleSend",value:function(){var e;if(!this.isLoading){var t=this.container.querySelector("#akvo-rag-input"),n=t.value.trim();if(n&&(null===(e=this.wsConnection)||void 0===e||null===(e=e.socket)||void 0===e?void 0:e.readyState)===WebSocket.OPEN){this.chatHistory.push({role:"user",content:n});var r=this.chatHistory.slice(-10);this.wsConnection.socket.send(JSON.stringify({type:"chat",kb_id:this.options.kb_id,messages:r})),kt("user",n),t.value="",this.currentAssistantMsgEl=null,this.isLoading=!0,this._updateSendButtonState()}}}},{key:"_updateSendButtonState",value:function(){var e=this.container.querySelector("#akvo-rag-send-btn");e&&(this.isLoading?(e.disabled=!0,e.innerHTML='<span class="akvo-send-spinner"></span>'):(e.disabled=!1,e.innerHTML="Send"))}},{key:"_onMessage",value:function(e){var t=this;if("info"===e.type)kt("system",e.message);else if("start"===e.type)this.citations=[],this.messageCounter++,this.currentAssistantMsgEl=kt("assistant","",!0,this.messageCounter);else if("response_chunk"===e.type){var n;null!=e&&null!==(n=e.citations)&&void 0!==n&&n.length&&e.citations.forEach((function(e){var n=t.citations.findIndex((function(t){return t.id===e.id}));if(n>-1){var r=t.citations[n],i=e.text&&e.metadata,o=r.text&&r.metadata;!i&&o||(t.citations[n]=e)}else t.citations.push(e)})),function(e,t){var n=document.querySelector("#akvo-rag-body");if(n&&e&&t){t.rawText||(t.rawText="");var r=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(/^\s*d:\{/.test(e))return t;var n=e;(n=n.replace(/^\d+:\s*/,"")).startsWith('"')&&(n=n.substring(1)),n.endsWith('"')?n=n.substring(0,n.length-1):n.trimEnd().endsWith('"')&&(n=(n=n.trimEnd()).substring(0,n.length-1));try{var r=n.replace(/\\"/g,'"').replace(/"/g,'\\"');n=JSON.parse('"'+r+'"')}catch(e){}return((t||"")+n).replace(/^"\s*/,"")}(e,t.rawText);t.rawText=r;var i=function(e){var t=e;t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/\b[A-Za-z0-9](?: [A-Za-z0-9])+\b/g,(function(e){return e.replace(/ /g,"")}))).replace(/\s+([,.:;!?])/g,"$1")).replace(/(\*\*|__)\s*(.*?)\s*(\*\*|__)/g,"$1$2$3")).replace(/` +([^`]+?) +`/g,"`$1`")).replace(/``` *bash/g,"```bash")).replace(/\\\n\s*/g,"")).replace(/\n{3,}/g,"\n\n")).replace(/[ \t]{2,}/g," ")).split("\n").map((function(e){return e.trim()})).join("\n");var n=[],r="";return t.split("\n").forEach((function(e){""===e?r&&(n.push(r.trim()),r=""):r?/[.!?]$/.test(r)?(n.push(r.trim()),r=e):r+=" "+e:r=e})),r&&n.push(r.trim()),n.join("\n\n")}(t.rawText);if(t.lastRenderedText!==i){var o=mt.parse(i),s=te.sanitize(o);t.innerHTML=s,t.lastRenderedText=i,n.scrollTop=n.scrollHeight}}}(e.content,this.currentAssistantMsgEl)}else if("end"===e.type){var r=this.currentAssistantMsgEl||document.querySelector("#akvo-msg-assistant-".concat(this.messageCounter));r&&(function(e,t){e&&null!=t&&t.length&&requestAnimationFrame((function(){var n=e.innerHTML;t.forEach((function(e){var t=null==e?void 0:e.id;if(null!=t){var r=new RegExp("(\\[|&?#?[a-zA-Z0-9]+;)\\s*citation:\\s*".concat(t,"\\s*(\\]|&?#?[a-zA-Z0-9]+;)"),"gi"),i=((null==e?void 0:e.text)||"").replace(/\s+/g," ").trim().slice(0,200)+"...",o=(null==e?void 0:e.metadata)||{},s=o.source||"Unknown Source",a=o.page_label||o.page||"n/a",l=o.title||o.source||"Untitled Document",c=i.replace(/"/g,"&quot;"),u=s.replace(/"/g,"&quot;"),p=l.replace(/"/g,"&quot;"),h='\n <sup\n class="citation"\n data-id="'.concat(t,'"\n data-text="').concat(c,'"\n data-source="').concat(u,'"\n data-page="').concat(a,'"\n data-title="').concat(p,'"\n >[').concat(t,"]</sup>");n=n.replace(r,h)}})),n=n.replace(/(?:\[|&#91;|&lbrack;)\s*citation:\s*\d+\s*(?:\]|&#93;|&rbrack;)/gi,""),e.innerHTML=n,e.querySelectorAll(".citation").forEach((function(e){e.style.cursor="pointer",e.addEventListener("mouseenter",yt),e.addEventListener("mouseleave",xt)}))}))}(r,this.citations),null!=r&&r.rawText&&this.chatHistory.push({role:"assistant",content:r.rawText})),this.isLoading=!1,this._updateSendButtonState()}}}],t&&Tt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Lt(){return new Rt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}return"undefined"!=typeof window&&(window.AkvoRAG={initChat:Lt}),t})()));
2
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AkvoRAG=t():e.AkvoRAG=t()}(this,(()=>(()=>{"use strict";var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{initChat:()=>Pt});const{entries:n,setPrototypeOf:i,isFrozen:r,getPrototypeOf:o,getOwnPropertyDescriptor:s}=Object;let{freeze:a,seal:l,create:c}=Object,{apply:u,construct:h}="undefined"!=typeof Reflect&&Reflect;a||(a=function(e){return e}),l||(l=function(e){return e}),u||(u=function(e,t,n){return e.apply(t,n)}),h||(h=function(e,t){return new e(...t)});const p=A(Array.prototype.forEach),d=A(Array.prototype.lastIndexOf),f=A(Array.prototype.pop),g=A(Array.prototype.push),m=A(Array.prototype.splice),y=A(String.prototype.toLowerCase),k=A(String.prototype.toString),b=A(String.prototype.match),v=A(String.prototype.replace),x=A(String.prototype.indexOf),w=A(String.prototype.trim),S=A(Object.prototype.hasOwnProperty),_=A(RegExp.prototype.test),T=(E=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return h(E,t)});var E;function A(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return u(e,t,i)}}function R(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:y;i&&i(e,null);let o=t.length;for(;o--;){let i=t[o];if("string"==typeof i){const e=n(i);e!==i&&(r(t)||(t[o]=e),i=e)}e[i]=!0}return e}function L(e){for(let t=0;t<e.length;t++)S(e,t)||(e[t]=null);return e}function C(e){const t=c(null);for(const[i,r]of n(e))S(e,i)&&(Array.isArray(r)?t[i]=L(r):r&&"object"==typeof r&&r.constructor===Object?t[i]=C(r):t[i]=r);return t}function N(e,t){for(;null!==e;){const n=s(e,t);if(n){if(n.get)return A(n.get);if("function"==typeof n.value)return A(n.value)}e=o(e)}return function(){return null}}const I=a(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),P=a(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),M=a(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),O=a(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),z=a(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),D=a(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),$=a(["#text"]),H=a(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),B=a(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),j=a(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),U=a(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),F=l(/\{\{[\w\W]*|[\w\W]*\}\}/gm),q=l(/<%[\w\W]*|[\w\W]*%>/gm),W=l(/\$\{[\w\W]*/gm),G=l(/^data-[\-\w.\u00B7-\uFFFF]+$/),Z=l(/^aria-[\-\w]+$/),Y=l(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),K=l(/^(?:\w+script|data):/i),X=l(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),J=l(/^html$/i),Q=l(/^[a-z][.\w]*(-[.\w]+)+$/i);var V=Object.freeze({__proto__:null,ARIA_ATTR:Z,ATTR_WHITESPACE:X,CUSTOM_ELEMENT:Q,DATA_ATTR:G,DOCTYPE_NAME:J,ERB_EXPR:q,IS_ALLOWED_URI:Y,IS_SCRIPT_OR_DATA:K,MUSTACHE_EXPR:F,TMPLIT_EXPR:W});const ee=function(){return"undefined"==typeof window?null:window};var te=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ee();const i=t=>e(t);if(i.version="3.2.5",i.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return i.isSupported=!1,i;let{document:r}=t;const o=r,s=o.currentScript,{DocumentFragment:l,HTMLTemplateElement:u,Node:h,Element:E,NodeFilter:A,NamedNodeMap:L=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:F,DOMParser:q,trustedTypes:W}=t,G=E.prototype,Z=N(G,"cloneNode"),K=N(G,"remove"),X=N(G,"nextSibling"),Q=N(G,"childNodes"),te=N(G,"parentNode");if("function"==typeof u){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let ne,ie="";const{implementation:re,createNodeIterator:oe,createDocumentFragment:se,getElementsByTagName:ae}=r,{importNode:le}=o;let ce={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};i.isSupported="function"==typeof n&&"function"==typeof te&&re&&void 0!==re.createHTMLDocument;const{MUSTACHE_EXPR:ue,ERB_EXPR:he,TMPLIT_EXPR:pe,DATA_ATTR:de,ARIA_ATTR:fe,IS_SCRIPT_OR_DATA:ge,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:ye}=V;let{IS_ALLOWED_URI:ke}=V,be=null;const ve=R({},[...I,...P,...M,...z,...$]);let xe=null;const we=R({},[...H,...B,...j,...U]);let Se=Object.seal(c(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),_e=null,Te=null,Ee=!0,Ae=!0,Re=!1,Le=!0,Ce=!1,Ne=!0,Ie=!1,Pe=!1,Me=!1,Oe=!1,ze=!1,De=!1,$e=!0,He=!1,Be=!0,je=!1,Ue={},Fe=null;const qe=R({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let We=null;const Ge=R({},["audio","video","img","source","image","track"]);let Ze=null;const Ye=R({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ke="http://www.w3.org/1998/Math/MathML",Xe="http://www.w3.org/2000/svg",Je="http://www.w3.org/1999/xhtml";let Qe=Je,Ve=!1,et=null;const tt=R({},[Ke,Xe,Je],k);let nt=R({},["mi","mo","mn","ms","mtext"]),it=R({},["annotation-xml"]);const rt=R({},["title","style","font","a","script"]);let ot=null;const st=["application/xhtml+xml","text/html"];let at=null,lt=null;const ct=r.createElement("form"),ut=function(e){return e instanceof RegExp||e instanceof Function},ht=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!lt||lt!==e){if(e&&"object"==typeof e||(e={}),e=C(e),ot=-1===st.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,at="application/xhtml+xml"===ot?k:y,be=S(e,"ALLOWED_TAGS")?R({},e.ALLOWED_TAGS,at):ve,xe=S(e,"ALLOWED_ATTR")?R({},e.ALLOWED_ATTR,at):we,et=S(e,"ALLOWED_NAMESPACES")?R({},e.ALLOWED_NAMESPACES,k):tt,Ze=S(e,"ADD_URI_SAFE_ATTR")?R(C(Ye),e.ADD_URI_SAFE_ATTR,at):Ye,We=S(e,"ADD_DATA_URI_TAGS")?R(C(Ge),e.ADD_DATA_URI_TAGS,at):Ge,Fe=S(e,"FORBID_CONTENTS")?R({},e.FORBID_CONTENTS,at):qe,_e=S(e,"FORBID_TAGS")?R({},e.FORBID_TAGS,at):{},Te=S(e,"FORBID_ATTR")?R({},e.FORBID_ATTR,at):{},Ue=!!S(e,"USE_PROFILES")&&e.USE_PROFILES,Ee=!1!==e.ALLOW_ARIA_ATTR,Ae=!1!==e.ALLOW_DATA_ATTR,Re=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Le=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Ce=e.SAFE_FOR_TEMPLATES||!1,Ne=!1!==e.SAFE_FOR_XML,Ie=e.WHOLE_DOCUMENT||!1,Oe=e.RETURN_DOM||!1,ze=e.RETURN_DOM_FRAGMENT||!1,De=e.RETURN_TRUSTED_TYPE||!1,Me=e.FORCE_BODY||!1,$e=!1!==e.SANITIZE_DOM,He=e.SANITIZE_NAMED_PROPS||!1,Be=!1!==e.KEEP_CONTENT,je=e.IN_PLACE||!1,ke=e.ALLOWED_URI_REGEXP||Y,Qe=e.NAMESPACE||Je,nt=e.MATHML_TEXT_INTEGRATION_POINTS||nt,it=e.HTML_INTEGRATION_POINTS||it,Se=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Se.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ut(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Se.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Se.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ce&&(Ae=!1),ze&&(Oe=!0),Ue&&(be=R({},$),xe=[],!0===Ue.html&&(R(be,I),R(xe,H)),!0===Ue.svg&&(R(be,P),R(xe,B),R(xe,U)),!0===Ue.svgFilters&&(R(be,M),R(xe,B),R(xe,U)),!0===Ue.mathMl&&(R(be,z),R(xe,j),R(xe,U))),e.ADD_TAGS&&(be===ve&&(be=C(be)),R(be,e.ADD_TAGS,at)),e.ADD_ATTR&&(xe===we&&(xe=C(xe)),R(xe,e.ADD_ATTR,at)),e.ADD_URI_SAFE_ATTR&&R(Ze,e.ADD_URI_SAFE_ATTR,at),e.FORBID_CONTENTS&&(Fe===qe&&(Fe=C(Fe)),R(Fe,e.FORBID_CONTENTS,at)),Be&&(be["#text"]=!0),Ie&&R(be,["html","head","body"]),be.table&&(R(be,["tbody"]),delete _e.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw T('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw T('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ne=e.TRUSTED_TYPES_POLICY,ie=ne.createHTML("")}else void 0===ne&&(ne=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}}(W,s)),null!==ne&&"string"==typeof ie&&(ie=ne.createHTML(""));a&&a(e),lt=e}},pt=R({},[...P,...M,...O]),dt=R({},[...z,...D]),ft=function(e){g(i.removed,{element:e});try{te(e).removeChild(e)}catch(t){K(e)}},gt=function(e,t){try{g(i.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){g(i.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(Oe||ze)try{ft(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},mt=function(e){let t=null,n=null;if(Me)e="<remove></remove>"+e;else{const t=b(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===ot&&Qe===Je&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const i=ne?ne.createHTML(e):e;if(Qe===Je)try{t=(new q).parseFromString(i,ot)}catch(e){}if(!t||!t.documentElement){t=re.createDocument(Qe,"template",null);try{t.documentElement.innerHTML=Ve?ie:i}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),Qe===Je?ae.call(t,Ie?"html":"body")[0]:Ie?t.documentElement:o},yt=function(e){return oe.call(e.ownerDocument||e,e,A.SHOW_ELEMENT|A.SHOW_COMMENT|A.SHOW_TEXT|A.SHOW_PROCESSING_INSTRUCTION|A.SHOW_CDATA_SECTION,null)},kt=function(e){return e instanceof F&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof L)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},bt=function(e){return"function"==typeof h&&e instanceof h};function vt(e,t,n){p(e,(e=>{e.call(i,t,n,lt)}))}const xt=function(e){let t=null;if(vt(ce.beforeSanitizeElements,e,null),kt(e))return ft(e),!0;const n=at(e.nodeName);if(vt(ce.uponSanitizeElement,e,{tagName:n,allowedTags:be}),e.hasChildNodes()&&!bt(e.firstElementChild)&&_(/<[/\w!]/g,e.innerHTML)&&_(/<[/\w!]/g,e.textContent))return ft(e),!0;if(7===e.nodeType)return ft(e),!0;if(Ne&&8===e.nodeType&&_(/<[/\w]/g,e.data))return ft(e),!0;if(!be[n]||_e[n]){if(!_e[n]&&St(n)){if(Se.tagNameCheck instanceof RegExp&&_(Se.tagNameCheck,n))return!1;if(Se.tagNameCheck instanceof Function&&Se.tagNameCheck(n))return!1}if(Be&&!Fe[n]){const t=te(e)||e.parentNode,n=Q(e)||e.childNodes;if(n&&t)for(let i=n.length-1;i>=0;--i){const r=Z(n[i],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,X(e))}}return ft(e),!0}return e instanceof E&&!function(e){let t=te(e);t&&t.tagName||(t={namespaceURI:Qe,tagName:"template"});const n=y(e.tagName),i=y(t.tagName);return!!et[e.namespaceURI]&&(e.namespaceURI===Xe?t.namespaceURI===Je?"svg"===n:t.namespaceURI===Ke?"svg"===n&&("annotation-xml"===i||nt[i]):Boolean(pt[n]):e.namespaceURI===Ke?t.namespaceURI===Je?"math"===n:t.namespaceURI===Xe?"math"===n&&it[i]:Boolean(dt[n]):e.namespaceURI===Je?!(t.namespaceURI===Xe&&!it[i])&&!(t.namespaceURI===Ke&&!nt[i])&&!dt[n]&&(rt[n]||!pt[n]):!("application/xhtml+xml"!==ot||!et[e.namespaceURI]))}(e)?(ft(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!_(/<\/no(script|embed|frames)/i,e.innerHTML)?(Ce&&3===e.nodeType&&(t=e.textContent,p([ue,he,pe],(e=>{t=v(t,e," ")})),e.textContent!==t&&(g(i.removed,{element:e.cloneNode()}),e.textContent=t)),vt(ce.afterSanitizeElements,e,null),!1):(ft(e),!0)},wt=function(e,t,n){if($e&&("id"===t||"name"===t)&&(n in r||n in ct))return!1;if(Ae&&!Te[t]&&_(de,t));else if(Ee&&_(fe,t));else if(!xe[t]||Te[t]){if(!(St(e)&&(Se.tagNameCheck instanceof RegExp&&_(Se.tagNameCheck,e)||Se.tagNameCheck instanceof Function&&Se.tagNameCheck(e))&&(Se.attributeNameCheck instanceof RegExp&&_(Se.attributeNameCheck,t)||Se.attributeNameCheck instanceof Function&&Se.attributeNameCheck(t))||"is"===t&&Se.allowCustomizedBuiltInElements&&(Se.tagNameCheck instanceof RegExp&&_(Se.tagNameCheck,n)||Se.tagNameCheck instanceof Function&&Se.tagNameCheck(n))))return!1}else if(Ze[t]);else if(_(ke,v(n,me,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==x(n,"data:")||!We[e])if(Re&&!_(ge,v(n,me,"")));else if(n)return!1;return!0},St=function(e){return"annotation-xml"!==e&&b(e,ye)},_t=function(e){vt(ce.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||kt(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:xe,forceKeepAttr:void 0};let r=t.length;for(;r--;){const o=t[r],{name:s,namespaceURI:a,value:l}=o,c=at(s);let u="value"===s?l:w(l);if(n.attrName=c,n.attrValue=u,n.keepAttr=!0,n.forceKeepAttr=void 0,vt(ce.uponSanitizeAttribute,e,n),u=n.attrValue,!He||"id"!==c&&"name"!==c||(gt(s,e),u="user-content-"+u),Ne&&_(/((--!?|])>)|<\/(style|title)/i,u)){gt(s,e);continue}if(n.forceKeepAttr)continue;if(gt(s,e),!n.keepAttr)continue;if(!Le&&_(/\/>/i,u)){gt(s,e);continue}Ce&&p([ue,he,pe],(e=>{u=v(u,e," ")}));const h=at(e.nodeName);if(wt(h,c,u)){if(ne&&"object"==typeof W&&"function"==typeof W.getAttributeType)if(a);else switch(W.getAttributeType(h,c)){case"TrustedHTML":u=ne.createHTML(u);break;case"TrustedScriptURL":u=ne.createScriptURL(u)}try{a?e.setAttributeNS(a,s,u):e.setAttribute(s,u),kt(e)?ft(e):f(i.removed)}catch(e){}}}vt(ce.afterSanitizeAttributes,e,null)},Tt=function e(t){let n=null;const i=yt(t);for(vt(ce.beforeSanitizeShadowDOM,t,null);n=i.nextNode();)vt(ce.uponSanitizeShadowNode,n,null),xt(n),_t(n),n.content instanceof l&&e(n.content);vt(ce.afterSanitizeShadowDOM,t,null)};return i.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,r=null,s=null,a=null;if(Ve=!e,Ve&&(e="\x3c!--\x3e"),"string"!=typeof e&&!bt(e)){if("function"!=typeof e.toString)throw T("toString is not a function");if("string"!=typeof(e=e.toString()))throw T("dirty is not a string, aborting")}if(!i.isSupported)return e;if(Pe||ht(t),i.removed=[],"string"==typeof e&&(je=!1),je){if(e.nodeName){const t=at(e.nodeName);if(!be[t]||_e[t])throw T("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof h)n=mt("\x3c!----\x3e"),r=n.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?n=r:n.appendChild(r);else{if(!Oe&&!Ce&&!Ie&&-1===e.indexOf("<"))return ne&&De?ne.createHTML(e):e;if(n=mt(e),!n)return Oe?null:De?ie:""}n&&Me&&ft(n.firstChild);const c=yt(je?e:n);for(;s=c.nextNode();)xt(s),_t(s),s.content instanceof l&&Tt(s.content);if(je)return e;if(Oe){if(ze)for(a=se.call(n.ownerDocument);n.firstChild;)a.appendChild(n.firstChild);else a=n;return(xe.shadowroot||xe.shadowrootmode)&&(a=le.call(o,a,!0)),a}let u=Ie?n.outerHTML:n.innerHTML;return Ie&&be["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&_(J,n.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+u),Ce&&p([ue,he,pe],(e=>{u=v(u,e," ")})),ne&&De?ne.createHTML(u):u},i.setConfig=function(){ht(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Pe=!0},i.clearConfig=function(){lt=null,Pe=!1},i.isValidAttribute=function(e,t,n){lt||ht({});const i=at(e),r=at(t);return wt(i,r,n)},i.addHook=function(e,t){"function"==typeof t&&g(ce[e],t)},i.removeHook=function(e,t){if(void 0!==t){const n=d(ce[e],t);return-1===n?void 0:m(ce[e],n,1)[0]}return f(ce[e])},i.removeHooks=function(e){ce[e]=[]},i.removeAllHooks=function(){ce={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},i}();function ne(e){return ne="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ne(e)}function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function re(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ie(Object(n),!0).forEach((function(t){oe(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ie(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function oe(e,t,n){return(t=function(e){var t=function(e){if("object"!=ne(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ne(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ne(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function se(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}let ae={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function le(e){ae=e}const ce={exec:()=>null};function ue(e,t=""){let n="string"==typeof e?e:e.source;const i={replace:(e,t)=>{let r="string"==typeof t?t:t.source;return r=r.replace(he.caret,"$1"),n=n.replace(e,r),i},getRegex:()=>new RegExp(n,t)};return i}const he={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[\t ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},pe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,de=/(?:[*+-]|\d{1,9}[.)])/,fe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ge=ue(fe).replace(/bull/g,de).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),me=ue(fe).replace(/bull/g,de).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ye=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ke=/(?!\s*\])(?:\\.|[^\[\]\\])+/,be=ue(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ke).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ve=ue(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,de).getRegex(),xe="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",we=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Se=ue("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",we).replace("tag",xe).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),_e=ue(ye).replace("hr",pe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",xe).getRegex(),Te={blockquote:ue(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",_e).getRegex(),code:/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,def:be,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:pe,html:Se,lheading:ge,list:ve,newline:/^(?:[ \t]*(?:\n|$))+/,paragraph:_e,table:ce,text:/^[^\n]+/},Ee=ue("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",pe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",xe).getRegex(),Ae={...Te,lheading:me,table:Ee,paragraph:ue(ye).replace("hr",pe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ee).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",xe).getRegex()},Re={...Te,html:ue("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",we).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ce,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ue(ye).replace("hr",pe).replace("heading"," *#{1,6} *[^\n]").replace("lheading",ge).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Le=/^( {2,}|\\)\n(?!\s*$)/,Ce=/[\p{P}\p{S}]/u,Ne=/[\s\p{P}\p{S}]/u,Ie=/[^\s\p{P}\p{S}]/u,Pe=ue(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ne).getRegex(),Me=/(?!~)[\p{P}\p{S}]/u,Oe=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,ze=ue(Oe,"u").replace(/punct/g,Ce).getRegex(),De=ue(Oe,"u").replace(/punct/g,Me).getRegex(),$e="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",He=ue($e,"gu").replace(/notPunctSpace/g,Ie).replace(/punctSpace/g,Ne).replace(/punct/g,Ce).getRegex(),Be=ue($e,"gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|~)/u).replace(/punctSpace/g,/(?!~)[\s\p{P}\p{S}]/u).replace(/punct/g,Me).getRegex(),je=ue("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ie).replace(/punctSpace/g,Ne).replace(/punct/g,Ce).getRegex(),Ue=ue(/\\(punct)/,"gu").replace(/punct/g,Ce).getRegex(),Fe=ue(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),qe=ue(we).replace("(?:--\x3e|$)","--\x3e").getRegex(),We=ue("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",qe).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ge=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ze=ue(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Ge).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ye=ue(/^!?\[(label)\]\[(ref)\]/).replace("label",Ge).replace("ref",ke).getRegex(),Ke=ue(/^!?\[(ref)\](?:\[\])?/).replace("ref",ke).getRegex(),Xe={_backpedal:ce,anyPunctuation:Ue,autolink:Fe,blockSkip:/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,br:Le,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:ce,emStrongLDelim:ze,emStrongRDelimAst:He,emStrongRDelimUnd:je,escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,link:Ze,nolink:Ke,punctuation:Pe,reflink:Ye,reflinkSearch:ue("reflink|nolink(?!\\()","g").replace("reflink",Ye).replace("nolink",Ke).getRegex(),tag:We,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:ce},Je={...Xe,link:ue(/^!?\[(label)\]\((.*?)\)/).replace("label",Ge).getRegex(),reflink:ue(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ge).getRegex()},Qe={...Xe,emStrongRDelimAst:Be,emStrongLDelim:De,url:ue(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Ve={...Qe,br:ue(Le).replace("{2,}","*").getRegex(),text:ue(Qe.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},et={normal:Te,gfm:Ae,pedantic:Re},tt={normal:Xe,gfm:Qe,breaks:Ve,pedantic:Je},nt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},it=e=>nt[e];function rt(e,t){if(t){if(he.escapeTest.test(e))return e.replace(he.escapeReplace,it)}else if(he.escapeTestNoEncode.test(e))return e.replace(he.escapeReplaceNoEncode,it);return e}function ot(e){try{e=encodeURI(e).replace(he.percentDecode,"%")}catch{return null}return e}function st(e,t){const n=e.replace(he.findPipe,((e,t,n)=>{let i=!1,r=t;for(;--r>=0&&"\\"===n[r];)i=!i;return i?"|":" |"})).split(he.splitPipe);let i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(he.slashPipe,"|");return n}function at(e,t,n){const i=e.length;if(0===i)return"";let r=0;for(;r<i&&e.charAt(i-r-1)===t;)r++;return e.slice(0,i-r)}function lt(e,t,n,i,r){const o=t.href,s=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");i.state.inLink=!0;const l={type:"!"===e[0].charAt(0)?"image":"link",raw:n,href:o,title:s,text:a,tokens:i.inlineTokens(a)};return i.state.inLink=!1,l}class ct{options;rules;lexer;constructor(e){this.options=e||ae}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:at(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t,n){const i=e.match(n.other.indentCodeCompensation);if(null===i)return t;const r=i[1];return t.split("\n").map((e=>{const t=e.match(n.other.beginningSpace);if(null===t)return e;const[i]=t;return i.length>=r.length?e.slice(r.length):e})).join("\n")}(e,t[3]||"",this.rules);return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){const t=at(e,"#");this.options.pedantic?e=t.trim():t&&!this.rules.other.endingSpaceChar.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:at(t[0],"\n")}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){let e=at(t[0],"\n").split("\n"),n="",i="";const r=[];for(;e.length>0;){let t=!1;const o=[];let s;for(s=0;s<e.length;s++)if(this.rules.other.blockquoteStart.test(e[s]))o.push(e[s]),t=!0;else{if(t)break;o.push(e[s])}e=e.slice(s);const a=o.join("\n"),l=a.replace(this.rules.other.blockquoteSetextReplace,"\n $1").replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}\n${a}`:a,i=i?`${i}\n${l}`:l;const c=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(l,r,!0),this.lexer.state.top=c,0===e.length)break;const u=r.at(-1);if("code"===u?.type)break;if("blockquote"===u?.type){const t=u,o=t.raw+"\n"+e.join("\n"),s=this.blockquote(o);r[r.length-1]=s,n=n.substring(0,n.length-t.raw.length)+s.raw,i=i.substring(0,i.length-t.text.length)+s.text;break}if("list"!==u?.type);else{const t=u,o=t.raw+"\n"+e.join("\n"),s=this.list(o);r[r.length-1]=s,n=n.substring(0,n.length-u.raw.length)+s.raw,i=i.substring(0,i.length-t.raw.length)+s.raw,e=o.substring(r.at(-1).raw.length).split("\n")}}return{type:"blockquote",raw:n,tokens:r,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const i=n.length>1,r={type:"list",raw:"",ordered:i,start:i?+n.slice(0,-1):"",loose:!1,items:[]};n=i?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=i?n:"[*+-]");const o=this.rules.other.listItemRegex(n);let s=!1;for(;e;){let n=!1,i="",a="";if(!(t=o.exec(e)))break;if(this.rules.block.hr.test(e))break;i=t[0],e=e.substring(i.length);let l=t[2].split("\n",1)[0].replace(this.rules.other.listReplaceTabs,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],u=!l.trim(),h=0;if(this.options.pedantic?(h=2,a=l.trimStart()):u?h=t[1].length+1:(h=t[2].search(this.rules.other.nonSpaceChar),h=h>4?1:h,a=l.slice(h),h+=t[1].length),u&&this.rules.other.blankLine.test(c)&&(i+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=this.rules.other.nextBulletRegex(h),n=this.rules.other.hrRegex(h),r=this.rules.other.fencesBeginRegex(h),o=this.rules.other.headingBeginRegex(h),s=this.rules.other.htmlBeginRegex(h);for(;e;){const p=e.split("\n",1)[0];let d;if(c=p,this.options.pedantic?(c=c.replace(this.rules.other.listReplaceNesting," "),d=c):d=c.replace(this.rules.other.tabCharGlobal," "),r.test(c))break;if(o.test(c))break;if(s.test(c))break;if(t.test(c))break;if(n.test(c))break;if(d.search(this.rules.other.nonSpaceChar)>=h||!c.trim())a+="\n"+d.slice(h);else{if(u)break;if(l.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4)break;if(r.test(l))break;if(o.test(l))break;if(n.test(l))break;a+="\n"+c}u||c.trim()||(u=!0),i+=p+"\n",e=e.substring(p.length+1),l=d.slice(h)}}r.loose||(s?r.loose=!0:this.rules.other.doubleBlankLine.test(i)&&(s=!0));let p,d=null;this.options.gfm&&(d=this.rules.other.listIsTask.exec(a),d&&(p="[ ] "!==d[0],a=a.replace(this.rules.other.listReplaceTask,""))),r.items.push({type:"list_item",raw:i,task:!!d,checked:p,loose:!1,text:a,tokens:[]}),r.raw+=i}const a=r.items.at(-1);if(!a)return;a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd(),r.raw=r.raw.trimEnd();for(let e=0;e<r.items.length;e++)if(this.lexer.state.top=!1,r.items[e].tokens=this.lexer.blockTokens(r.items[e].text,[]),!r.loose){const t=r.items[e].tokens.filter((e=>"space"===e.type)),n=t.length>0&&t.some((e=>this.rules.other.anyLine.test(e.raw)));r.loose=n}if(r.loose)for(let e=0;e<r.items.length;e++)r.items[e].loose=!0;return r}}html(e){const t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:i}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!this.rules.other.tableDelimiter.test(t[2]))return;const n=st(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split("\n"):[],o={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===i.length){for(const e of i)this.rules.other.tableAlignRight.test(e)?o.align.push("right"):this.rules.other.tableAlignCenter.test(e)?o.align.push("center"):this.rules.other.tableAlignLeft.test(e)?o.align.push("left"):o.align.push(null);for(let e=0;e<n.length;e++)o.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:o.align[e]});for(const e of r)o.rows.push(st(e,o.header.length).map(((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:o.align[t]}))));return o}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;const t=at(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let i=0;i<e.length;i++)if("\\"===e[i])i++;else if(e[i]===t[0])n++;else if(e[i]===t[1]&&(n--,n<0))return i;return n>0?-2:-1}(t[2],"()");if(-2===e)return;if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){const e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],i=e[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),lt(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:i?i.replace(this.rules.inline.anyPunctuation,"$1"):i},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return lt(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(i&&(!i[3]||!n.match(this.rules.other.unicodeAlphaNumeric))&&(!i[1]&&!i[2]||!n||this.rules.inline.punctuation.exec(n))){const n=[...i[0]].length-1;let r,o,s=n,a=0;const l="*"===i[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(l.lastIndex=0,t=t.slice(-1*e.length+n);null!=(i=l.exec(t));){if(r=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!r)continue;if(o=[...r].length,i[3]||i[4]){s+=o;continue}if((i[5]||i[6])&&n%3&&!((n+o)%3)){a+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s+a);const t=[...i[0]][0].length,l=e.slice(0,n+i.index+t+o);if(Math.min(n,o)%2){const e=l.slice(1,-1);return{type:"em",raw:l,text:e,tokens:this.lexer.inlineTokens(e)}}const c=l.slice(2,-2);return{type:"strong",raw:l,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal," ");const n=this.rules.other.nonSpaceChar.test(e),i=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&i&&(e=e.substring(1,e.length-1)),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=t[1],n="mailto:"+e):(e=t[1],n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=t[0],n="mailto:"+e;else{let i;do{i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(i!==t[0]);e=t[0],n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){const e=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:e}}}}class ut{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ae,this.options.tokenizer=this.options.tokenizer||new ct,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const t={other:he,block:et.normal,inline:tt.normal};this.options.pedantic?(t.block=et.pedantic,t.inline=tt.pedantic):this.options.gfm&&(t.block=et.gfm,this.options.breaks?t.inline=tt.breaks:t.inline=tt.gfm),this.tokenizer.rules=t}static get rules(){return{block:et,inline:tt}}static lex(e,t){return new ut(t).lex(e)}static lexInline(e,t){return new ut(t).inlineTokens(e)}lex(e){e=e.replace(he.carriageReturn,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(he.tabCharGlobal," ").replace(he.spaceLine,""));e;){let i;if(this.options.extensions?.block?.some((n=>!!(i=n.call({lexer:this},e,t))&&(e=e.substring(i.raw.length),t.push(i),!0))))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);const n=t.at(-1);1===i.raw.length&&void 0!==n?n.raw+="\n":t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);const n=t.at(-1);"paragraph"===n?.type||"text"===n?.type?(n.raw+="\n"+i.raw,n.text+="\n"+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);const n=t.at(-1);"paragraph"===n?.type||"text"===n?.type?(n.raw+="\n"+i.raw,n.text+="\n"+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title});continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let r=e;if(this.options.extensions?.startBlock){let t=1/0;const n=e.slice(1);let i;this.options.extensions.startBlock.forEach((e=>{i=e.call({lexer:this},n),"number"==typeof i&&i>=0&&(t=Math.min(t,i))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(r))){const o=t.at(-1);n&&"paragraph"===o?.type?(o.raw+="\n"+i.raw,o.text+="\n"+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(i),n=r.length!==e.length,e=e.substring(i.raw.length)}else if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);const n=t.at(-1);"text"===n?.type?(n.raw+="\n"+i.raw,n.text+="\n"+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i)}else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,i=null;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(n));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(n));)n=n.slice(0,i.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(n));)n=n.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let r=!1,o="";for(;e;){let i;if(r||(o=""),r=!1,this.options.extensions?.inline?.some((n=>!!(i=n.call({lexer:this},e,t))&&(e=e.substring(i.raw.length),t.push(i),!0))))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);const n=t.at(-1);"text"===i.type&&"text"===n?.type?(n.raw+=i.raw,n.text+=i.text):t.push(i);continue}if(i=this.tokenizer.emStrong(e,n,o)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.del(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.autolink(e)){e=e.substring(i.raw.length),t.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),t.push(i);continue}let s=e;if(this.options.extensions?.startInline){let t=1/0;const n=e.slice(1);let i;this.options.extensions.startInline.forEach((e=>{i=e.call({lexer:this},n),"number"==typeof i&&i>=0&&(t=Math.min(t,i))})),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(i=this.tokenizer.inlineText(s)){e=e.substring(i.raw.length),"_"!==i.raw.slice(-1)&&(o=i.raw.slice(-1)),r=!0;const n=t.at(-1);"text"===n?.type?(n.raw+=i.raw,n.text+=i.text):t.push(i)}else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return t}}class ht{options;parser;constructor(e){this.options=e||ae}space(e){return""}code({text:e,lang:t,escaped:n}){const i=(t||"").match(he.notSpaceStart)?.[0],r=e.replace(he.endingNewline,"")+"\n";return i?'<pre><code class="language-'+rt(i)+'">'+(n?r:rt(r,!0))+"</code></pre>\n":"<pre><code>"+(n?r:rt(r,!0))+"</code></pre>\n"}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return"<hr>\n"}list(e){const t=e.ordered,n=e.start;let i="";for(let t=0;t<e.items.length;t++){const n=e.items[t];i+=this.listitem(n)}const r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+i+"</"+r+">\n"}listitem(e){let t="";if(e.task){const n=this.checkbox({checked:!!e.checked});e.loose?"paragraph"===e.tokens[0]?.type?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&"text"===e.tokens[0].tokens[0].type&&(e.tokens[0].tokens[0].text=n+" "+rt(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`<li>${t}</li>\n`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t="",n="";for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let i="";for(let t=0;t<e.rows.length;t++){const r=e.rows[t];n="";for(let e=0;e<r.length;e++)n+=this.tablecell(r[e]);i+=this.tablerow({text:n})}return i&&(i=`<tbody>${i}</tbody>`),"<table>\n<thead>\n"+t+"</thead>\n"+i+"</table>\n"}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){const t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${rt(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){const i=this.parser.parseInline(n),r=ot(e);if(null===r)return i;let o='<a href="'+(e=r)+'"';return t&&(o+=' title="'+rt(t)+'"'),o+=">"+i+"</a>",o}image({href:e,title:t,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));const r=ot(e);if(null===r)return rt(n);let o=`<img src="${e=r}" alt="${n}"`;return t&&(o+=` title="${rt(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:rt(e.text)}}class pt{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}}class dt{options;renderer;textRenderer;constructor(e){this.options=e||ae,this.options.renderer=this.options.renderer||new ht,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new pt}static parse(e,t){return new dt(t).parse(e)}static parseInline(e,t){return new dt(t).parseInline(e)}parse(e,t=!0){let n="";for(let i=0;i<e.length;i++){const r=e[i];if(this.options.extensions?.renderers?.[r.type]){const e=r,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){n+=t||"";continue}}const o=r;switch(o.type){case"space":n+=this.renderer.space(o);continue;case"hr":n+=this.renderer.hr(o);continue;case"heading":n+=this.renderer.heading(o);continue;case"code":n+=this.renderer.code(o);continue;case"table":n+=this.renderer.table(o);continue;case"blockquote":n+=this.renderer.blockquote(o);continue;case"list":n+=this.renderer.list(o);continue;case"html":n+=this.renderer.html(o);continue;case"paragraph":n+=this.renderer.paragraph(o);continue;case"text":{let r=o,s=this.renderer.text(r);for(;i+1<e.length&&"text"===e[i+1].type;)r=e[++i],s+="\n"+this.renderer.text(r);n+=t?this.renderer.paragraph({type:"paragraph",raw:s,text:s,tokens:[{type:"text",raw:s,text:s,escaped:!0}]}):s;continue}default:{const e='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}parseInline(e,t=this.renderer){let n="";for(let i=0;i<e.length;i++){const r=e[i];if(this.options.extensions?.renderers?.[r.type]){const e=this.options.extensions.renderers[r.type].call({parser:this},r);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){n+=e||"";continue}}const o=r;switch(o.type){case"escape":case"text":n+=t.text(o);break;case"html":n+=t.html(o);break;case"link":n+=t.link(o);break;case"image":n+=t.image(o);break;case"strong":n+=t.strong(o);break;case"em":n+=t.em(o);break;case"codespan":n+=t.codespan(o);break;case"br":n+=t.br(o);break;case"del":n+=t.del(o);break;default:{const e='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}}class ft{options;block;constructor(e){this.options=e||ae}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?ut.lex:ut.lexInline}provideParser(){return this.block?dt.parse:dt.parseInline}}const gt=new class{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=dt;Renderer=ht;TextRenderer=pt;Lexer=ut;Tokenizer=ct;Hooks=ft;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(const i of e)switch(n=n.concat(t.call(this,i)),i.type){case"table":{const e=i;for(const i of e.header)n=n.concat(this.walkTokens(i.tokens,t));for(const i of e.rows)for(const e of i)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=i;n=n.concat(this.walkTokens(e.items,t));break}default:{const e=i;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach((i=>{const r=e[i].flat(1/0);n=n.concat(this.walkTokens(r,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let i=e.renderer.apply(this,t);return!1===i&&(i=n.apply(this,t)),i}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new ht(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;const i=n,r=e.renderer[i],o=t[i];t[i]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=o.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new ct(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const i=n,r=e.tokenizer[i],o=t[i];t[i]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=o.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new ft;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;const i=n,r=e.hooks[i],o=t[i];ft.passThroughHooks.has(n)?t[i]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>o.call(t,e)));const n=r.call(t,e);return o.call(t,n)}:t[i]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=o.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,i=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(i.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ut.lex(e,t??this.defaults)}parser(e,t){return dt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{const i={...n},r={...this.defaults,...i},o=this.onError(!!r.silent,!!r.async);if(!0===this.defaults.async&&!1===i.async)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(null==t)return o(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof t)return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));r.hooks&&(r.hooks.options=r,r.hooks.block=e);const s=r.hooks?r.hooks.provideLexer():e?ut.lex:ut.lexInline,a=r.hooks?r.hooks.provideParser():e?dt.parse:dt.parseInline;if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(t):t).then((e=>s(e,r))).then((e=>r.hooks?r.hooks.processAllTokens(e):e)).then((e=>r.walkTokens?Promise.all(this.walkTokens(e,r.walkTokens)).then((()=>e)):e)).then((e=>a(e,r))).then((e=>r.hooks?r.hooks.postprocess(e):e)).catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let e=s(t,r);r.hooks&&(e=r.hooks.processAllTokens(e)),r.walkTokens&&this.walkTokens(e,r.walkTokens);let n=a(e,r);return r.hooks&&(n=r.hooks.postprocess(n)),n}catch(e){return o(e)}}}onError(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="<p>An error occurred:</p><pre>"+rt(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function mt(e,t){return gt.parse(e,t)}function yt(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,r=document.querySelector("#akvo-rag-body");if(r){var o=document.createElement("div"),s="akvo-msg-".concat(e,"-").concat(i);if(o.id=s,o.className="akvo-msg-".concat(e),n)o.innerHTML='\n <div class="typing-indicator">\n <span></span><span></span><span></span>\n </div>\n ';else{var a=function(e){if("function"==typeof(null==te?void 0:te.sanitize))return te.sanitize(e);if("function"==typeof te)try{var t=te(globalThis.window||globalThis);if("function"==typeof(null==t?void 0:t.sanitize))return t.sanitize(e)}catch(e){}return e}(mt.parse(t||""));o.innerHTML=a}return r.appendChild(o),r.scrollTop=r.scrollHeight,o}}function kt(){"undefined"!=typeof document&&"function"==typeof document.querySelectorAll&&document.querySelectorAll(".citation-popover").forEach((function(e){return e.remove()}))}function bt(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];e&&requestAnimationFrame((function(){if(!1!==n){if(null!=t&&t.length){var i=e.innerHTML;t.forEach((function(e){var t=null==e?void 0:e.id;if(null!=t){var n=new RegExp("(\\[|&?#?[a-zA-Z0-9]+;)\\s*citation:\\s*".concat(t,"\\s*(\\]|&?#?[a-zA-Z0-9]+;)"),"gi"),r=((null==e?void 0:e.text)||"").replace(/\s+/g," ").trim().slice(0,200)+"...",o=(null==e?void 0:e.metadata)||{},s=o.source||"Unknown Source",a=o.page_label||o.page||"n/a",l=o.title||o.source||"Untitled Document",c=r.replace(/"/g,"&quot;"),u=s.replace(/"/g,"&quot;"),h=l.replace(/"/g,"&quot;"),p='\n <sup\n class="citation"\n data-id="'.concat(t,'"\n data-text="').concat(c,'"\n data-source="').concat(u,'"\n data-page="').concat(a,'"\n data-title="').concat(h,'"\n >[').concat(t,"]</sup>");i=i.replace(n,p)}})),i=i.replace(/(?:\[|&#91;|&lbrack;)\s*citation:\s*\d+\s*(?:\]|&#93;|&rbrack;)/gi,""),e.innerHTML=i,e.querySelectorAll(".citation").forEach((function(e){e.style.cursor="pointer",e.addEventListener("mouseenter",vt),e.addEventListener("mouseleave",xt)}))}}else e.innerHTML=e.innerHTML.replace(/(?:\[|&#91;|&lbrack;)\s*citation:\s*\d+\s*(?:\]|&#93;|&rbrack;)/gi,"")}))}function vt(e){kt();var t=e.target,n=document.createElement("div");n.className="citation-popover";var i='\n <div class="arrow"></div>\n <div><strong>'.concat(t.dataset.title||"","</strong></div>\n <div><small>Source: ").concat(t.dataset.source||"",", Page: ").concat(t.dataset.page||"","</small></div>\n <p>").concat(t.dataset.text||"","</p>\n ");n.innerHTML=te.sanitize(i),document.body.appendChild(n);var r=n.offsetWidth,o=n.offsetHeight,s=t.getBoundingClientRect(),a=s.left+window.scrollX-r/2+s.width/2,l=window.scrollX+window.innerWidth-r-10,c=window.scrollX+10;a=Math.max(Math.min(a,l),c),s.top;var u=window.innerHeight-s.bottom<o+8+10,h=u?s.top+window.scrollY-o-8-2:s.bottom+window.scrollY+8+2;n.style.left="".concat(a,"px"),n.style.top="".concat(h,"px"),n.dataset.target=t.dataset.id,n.classList.toggle("above",u),n.classList.toggle("below",!u);var p=n.querySelector(".arrow"),d=s.left+s.width/2+window.scrollX-a-8;d=Math.max(8,Math.min(d,r-16)),p.style.left="".concat(d,"px")}function xt(e){var t=e.target;document.querySelectorAll(".citation-popover").forEach((function(e){e.dataset.target===t.dataset.id&&e.remove()}))}function wt(e){return wt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wt(e)}function St(e){return function(e){if(Array.isArray(e))return Tt(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||_t(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _t(e,t){if(e){if("string"==typeof e)return Tt(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Tt(e,t):void 0}}function Tt(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function Et(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function At(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Et(Object(n),!0).forEach((function(t){Rt(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Et(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Rt(e,t,n){return(t=Ct(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Lt(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,Ct(i.key),i)}}function Ct(e){var t=function(e){if("object"!=wt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=wt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==wt(t)?t:t+""}mt.options=mt.setOptions=function(e){return gt.setOptions(e),mt.defaults=gt.defaults,le(mt.defaults),mt},mt.getDefaults=function(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}},mt.defaults=ae,mt.use=function(...e){return gt.use(...e),mt.defaults=gt.defaults,le(mt.defaults),mt},mt.walkTokens=function(e,t){return gt.walkTokens(e,t)},mt.parseInline=gt.parseInline,mt.Parser=dt,mt.parser=dt.parse,mt.Renderer=ht,mt.TextRenderer=pt,mt.Lexer=ut,mt.lexer=ut.lex,mt.Tokenizer=ct,mt.Hooks=ft,mt.parse=mt,mt.options,mt.setOptions,mt.use,mt.walkTokens,mt.parseInline,dt.parse,ut.lex,mt.setOptions({gfm:!0,breaks:!0});var Nt="Hello! How can I help you today?",It=function(){return e=function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.options=At({draggable:!0,persistPosition:!0,storageKey:"akvo_rag_pos",dragThreshold:6,persistHistory:!0,historyStorageType:"session",historyStorageKey:"akvo_rag_history",maxHistoryMessages:20,showCitations:!0},n),void 0!==n.draggable&&(this.options.draggable=Boolean(n.draggable)),void 0!==n.persistPosition&&(this.options.persistPosition=Boolean(n.persistPosition)),void 0!==n.dragThreshold){var i=Number(n.dragThreshold);this.options.dragThreshold=Number.isFinite(i)&&i>=0?i:6}if("string"==typeof n.storageKey&&n.storageKey.trim()&&(this.options.storageKey=n.storageKey.trim()),void 0!==n.persistHistory&&(this.options.persistHistory=Boolean(n.persistHistory)),"local"===n.historyStorageType||"session"===n.historyStorageType?this.options.historyStorageType=n.historyStorageType:this.options.historyStorageType="session","string"==typeof n.historyStorageKey&&n.historyStorageKey.trim()&&(this.options.historyStorageKey=n.historyStorageKey.trim()),void 0!==n.maxHistoryMessages){var r=Number(n.maxHistoryMessages);this.options.maxHistoryMessages=Number.isFinite(r)&&r>0?Math.floor(r):20}void 0!==n.showCitations&&(this.options.showCitations=Boolean(n.showCitations)),void 0!==n.userId&&null!==n.userId&&(this.options.userId=String(n.userId).trim()),this.showLauncher=void 0===this.options.showLauncher||Boolean(this.options.showLauncher),this.isMinimized=void 0!==this.options.startMinimized?Boolean(this.options.startMinimized):this.showLauncher,this.wsConnection=null,this.currentAssistantMsgEl=null,this.isLoading=!1,this.citations=[],this.messageCounter=0,this.chatHistory=[],this.visitorId=((t=localStorage.getItem("akvo-visitor-id"))||(t=crypto.randomUUID(),localStorage.setItem("akvo-visitor-id",t)),t),this.container=null,this.launcher=null,this.currentPosition=null,this._activeDragCleanup=[],this._suppressNextClick=!1,this._onMessage=this._onMessage.bind(this),this._handleSend=this._handleSend.bind(this),this._handleStartChat=this._handleStartChat.bind(this),this.init()},t=[{key:"init",value:function(){var e=this._loadSavedPosition();if(e&&(this.currentPosition=e),this.container=document.getElementById("akvo-rag"),this.launcher=document.getElementById("akvo-rag-launcher"),this.container)return this._applyCustomStyles(this.container,!1),this.launcher&&(this._applyCustomStyles(this.launcher,!0),this.currentPosition&&this._applyPosition(this.launcher,this.currentPosition)),void(this.isMinimized?this.close():this.open());this.showLauncher?this._createLauncher():this.launcher=null,this._createUI(),this._bindEvents(),this._rehydrateHistory(),this.isMinimized?this.close():this.open(),this.options.kb_id&&this._connect()}},{key:"_getStorageBackend",value:function(){try{var e,t;return"local"===this.options.historyStorageType?"function"==typeof(null===(t=globalThis.localStorage)||void 0===t?void 0:t.getItem)?globalThis.localStorage:null:"function"==typeof(null===(e=globalThis.sessionStorage)||void 0===e?void 0:e.getItem)?globalThis.sessionStorage:null}catch(e){return null}}},{key:"_getHistoryStorageKey",value:function(){var e=String(this.options.userId||this.visitorId||"anon").trim(),t=String(this.options.kb_id||"default").trim(),n=String(this.options.historyStorageKey||"akvo_rag_history").trim();return"".concat(n,"_").concat(e,"_").concat(t)}},{key:"_saveHistoryToStorage",value:function(){if(this.options.persistHistory){var e=this._getStorageBackend();if(e)try{var t=this._getHistoryStorageKey(),n=this.options.maxHistoryMessages||20,i=this.chatHistory.slice(-n);e.setItem(t,JSON.stringify(i))}catch(e){}}}},{key:"_loadHistoryFromStorage",value:function(){if(!this.options.persistHistory)return[];var e=this._getStorageBackend();if(!e)return[];try{var t=this._getHistoryStorageKey(),n=e.getItem(t);if(n){var i=JSON.parse(n);if(Array.isArray(i)){var r=this.options.maxHistoryMessages||20;return i.slice(-r)}}}catch(e){}return[]}},{key:"_rehydrateHistory",value:function(){var e,t=this;if(this.options.persistHistory){var n=this._loadHistoryFromStorage();if(n.length){this.chatHistory=St(n);var i=null===(e=this.container)||void 0===e?void 0:e.querySelector("#akvo-rag-body");if(i){var r=i.querySelector(".akvo-msg-system");r&&r.remove(),n.forEach((function(e){if(e&&e.role&&e.content){t.messageCounter++;var n=yt(e.role,e.content,!1,t.messageCounter);"assistant"===e.role&&n&&(e.citations&&e.citations.length?bt(n,e.citations,t.options.showCitations):bt(n,[],t.options.showCitations))}}))}}}}},{key:"clearHistory",value:function(){var e;this.chatHistory=[];var t=this._getStorageBackend();if(t)try{t.removeItem(this._getHistoryStorageKey())}catch(e){}var n,i=null===(e=this.container)||void 0===e?void 0:e.querySelector("#akvo-rag-body");i&&(i.innerHTML=!this.options.kb_id&&null!==(n=this.options.kb_options)&&void 0!==n&&n.length?'\n <div id="akvo-kb-options" class="akvo-kb-options">\n <p>Please select a knowledge base to continue:</p>\n '.concat(this.options.kb_options.map((function(e){return'\n <div class="kb-option">\n <input type="radio" id="kb-'.concat(e.kb_id,'" name="akvo-kb" value="').concat(e.kb_id,'">\n <label for="kb-').concat(e.kb_id,'">').concat(e.label,"</label>\n </div>\n ")})).join(""),'\n <div class="akvo-kb-options-hint">\n After selecting, click "Start Chat" to begin.\n </div>\n </div>\n '):'<p class="akvo-msg-system">'.concat(Nt,"</p>"))}},{key:"getHistory",value:function(){return JSON.parse(JSON.stringify(this.chatHistory))}},{key:"_loadSavedPosition",value:function(){if(!this.options.persistPosition)return null;try{var e;if("function"==typeof(null===(e=globalThis.localStorage)||void 0===e?void 0:e.getItem)){var t=globalThis.localStorage.getItem(this.options.storageKey);if(t){var n=JSON.parse(t);if(n&&"number"==typeof n.left&&Number.isFinite(n.left)&&"number"==typeof n.top&&Number.isFinite(n.top))return{left:n.left,top:n.top}}}}catch(e){}return null}},{key:"_savePosition",value:function(e){if(e&&"number"==typeof e.left&&"number"==typeof e.top&&(this.currentPosition={left:e.left,top:e.top},this.options.persistPosition))try{var t;"function"==typeof(null===(t=globalThis.localStorage)||void 0===t?void 0:t.setItem)&&globalThis.localStorage.setItem(this.options.storageKey,JSON.stringify(this.currentPosition))}catch(e){}}},{key:"_applyPosition",value:function(e,t){e&&e.style&&t&&(e.style.left="".concat(t.left,"px"),e.style.top="".concat(t.top,"px"),e.style.bottom="auto",e.style.right="auto")}},{key:"_anchorWindowToLauncher",value:function(){var e,t,n;if(this.container&&this.currentPosition){var i=this.currentPosition.left,r=this.currentPosition.top,o="function"==typeof(null===(e=this.launcher)||void 0===e?void 0:e.getBoundingClientRect)?this.launcher.getBoundingClientRect():{width:56,height:56},s=o.width||56,a=o.height||56,l="function"==typeof this.container.getBoundingClientRect?this.container.getBoundingClientRect():{width:360,height:500},c=l.width||parseFloat(this.options.width)||360,u=l.height||parseFloat(this.options.height)||500,h=(null===(t=globalThis.window)||void 0===t?void 0:t.innerWidth)||1024,p=(null===(n=globalThis.window)||void 0===n?void 0:n.innerHeight)||768,d=0;d=i>h/2?i+s-c:i;var f=0;f=r>p/2?r+a-u:r;var g=Math.max(0,h-c),m=Math.max(0,p-u);d=Math.max(0,Math.min(d,g)),f=Math.max(0,Math.min(f,m)),this._applyPosition(this.container,{left:d,top:f})}}},{key:"_makeDraggable",value:function(e,t,n){var i,r,o=this;if(e&&t&&this.options.draggable){var s=0,a=0,l=0,c=0,u=!1,h=function(e){var i,r,h,p,d,f;if(e.target&&"function"==typeof e.target.closest){if(e.target.closest("#akvo-rag-close-btn")||e.target.closest(".akvo-rag-close-btn"))return}else if(e.target&&"akvo-rag-close-btn"===e.target.id)return;if("mousedown"!==e.type||void 0===e.button||0===e.button){var g=e.touches?e.touches[0]:e;s=g.clientX,a=g.clientY;var m="function"==typeof t.getBoundingClientRect?t.getBoundingClientRect():{left:0,top:0,width:56,height:56},y=parseFloat(null===(i=t.style)||void 0===i?void 0:i.left),k=parseFloat(null===(r=t.style)||void 0===r?void 0:r.top);l=isNaN(y)?m.left||0:y,c=isNaN(k)?m.top||0:k,u=!1;var b=function(e){var n,i=e.touches?e.touches[0]:e,r=i.clientX-s,h=i.clientY-a,p=Math.hypot(r,h);if(!u&&p>=o.options.dragThreshold&&(u=!0,o.isDragging=!0,null===(n=t.classList)||void 0===n||n.add("akvo-is-dragging")),u){var d,f,g,y;"function"==typeof e.preventDefault&&e.preventDefault();var k=(null===(d=globalThis.window)||void 0===d?void 0:d.innerWidth)||1024,b=(null===(f=globalThis.window)||void 0===f?void 0:f.innerHeight)||768,v=m.width||parseFloat(null===(g=t.style)||void 0===g?void 0:g.width)||56,x=m.height||parseFloat(null===(y=t.style)||void 0===y?void 0:y.height)||56,w=Math.max(0,k-v),S=Math.max(0,b-x),_=Math.max(0,Math.min(l+r,w)),T=Math.max(0,Math.min(c+h,S));o._applyPosition(t,{left:_,top:T})}},v=function(e){var i,r,l,c,h=e.changedTouches?e.changedTouches[0]:e,p=(void 0!==(null==h?void 0:h.clientX)?h.clientX:s)-s,d=(void 0!==(null==h?void 0:h.clientY)?h.clientY:a)-a,f=Math.hypot(p,d),g=globalThis.window||globalThis;if(null===(i=g.removeEventListener)||void 0===i||i.call(g,"mousemove",b),null===(r=g.removeEventListener)||void 0===r||r.call(g,"mouseup",v),null===(l=g.removeEventListener)||void 0===l||l.call(g,"touchmove",b),null===(c=g.removeEventListener)||void 0===c||c.call(g,"touchend",v),u||f>=o.options.dragThreshold){var m,y,k;u=!1,o.isDragging=!1,o._suppressNextClick=!0,null===(m=t.classList)||void 0===m||m.remove("akvo-is-dragging");var x={left:parseFloat(null===(y=t.style)||void 0===y?void 0:y.left)||0,top:parseFloat(null===(k=t.style)||void 0===k?void 0:k.top)||0};o._savePosition(x),"function"==typeof n&&n(x)}},x=globalThis.window||globalThis;null===(h=x.addEventListener)||void 0===h||h.call(x,"mousemove",b,{passive:!1}),null===(p=x.addEventListener)||void 0===p||p.call(x,"mouseup",v),null===(d=x.addEventListener)||void 0===d||d.call(x,"touchmove",b,{passive:!1}),null===(f=x.addEventListener)||void 0===f||f.call(x,"touchend",v),o._activeDragCleanup.push((function(){var e,t,n,i;null===(e=x.removeEventListener)||void 0===e||e.call(x,"mousemove",b),null===(t=x.removeEventListener)||void 0===t||t.call(x,"mouseup",v),null===(n=x.removeEventListener)||void 0===n||n.call(x,"touchmove",b),null===(i=x.removeEventListener)||void 0===i||i.call(x,"touchend",v)}))}};null===(i=e.addEventListener)||void 0===i||i.call(e,"mousedown",h),null===(r=e.addEventListener)||void 0===r||r.call(e,"touchstart",h,{passive:!0}),this._activeDragCleanup.push((function(){var t,n;null===(t=e.removeEventListener)||void 0===t||t.call(e,"mousedown",h),null===(n=e.removeEventListener)||void 0===n||n.call(e,"touchstart",h)}))}}},{key:"destroy",value:function(){this.wsConnection&&this.wsConnection.close();var e,t=function(e){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!t){if(Array.isArray(e)||(t=_t(e))){t&&(e=t);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,s=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return o=e.done,e},e:function(e){s=!0,r=e},f:function(){try{o||null==t.return||t.return()}finally{if(s)throw r}}}}(this._activeDragCleanup);try{for(t.s();!(e=t.n()).done;){var n=e.value;try{n()}catch(e){}}}catch(e){t.e(e)}finally{t.f()}this._activeDragCleanup=[],this.container&&(this.container.remove(),this.container=null),this.launcher&&(this.launcher.remove(),this.launcher=null),kt()}},{key:"open",value:function(){var e;this.isMinimized=!1,this.currentPosition&&this._anchorWindowToLauncher(),this.container&&(this.container.style&&(this.container.style.display="flex"),null===(e=this.container.classList)||void 0===e||e.remove("minimized")),this.launcher&&this.launcher.style&&(this.launcher.style.display="none")}},{key:"close",value:function(){var e;this.isMinimized=!0,this.currentPosition&&this.launcher&&this._applyPosition(this.launcher,this.currentPosition),this.container&&(this.showLauncher?this.container.style&&(this.container.style.display="none"):null===(e=this.container.classList)||void 0===e||e.add("minimized")),this.launcher&&this.launcher.style&&(this.launcher.style.display="flex")}},{key:"minimize",value:function(){this.close()}},{key:"_isValidCssColor",value:function(e){if(!e||"string"!=typeof e)return!1;var t=e.trim();return!!/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(t)||!!/^(?:rgb|hsl)a?\(\s*[\d.%\s,/-]+\s*\)$/i.test(t)||/^(?:teal|blue|green|red|purple|indigo|slate|gray|black|white|transparent)$/i.test(t)}},{key:"_toCssDimension",value:function(e){if("number"==typeof e&&Number.isFinite(e)&&e>0)return"".concat(e,"px");if("string"==typeof e){var t=e.trim();if(/^\d+(\.\d+)?$/.test(t))return"".concat(t,"px");if(/^\d+(\.\d+)?(px|rem|em|vh|vw|%)$/i.test(t))return t}return null}},{key:"_toSafeZIndex",value:function(e){if("number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=2147483647)return e;if("string"==typeof e){var t=e.trim();if(/^\d+$/.test(t)){var n=parseInt(t,10);if(!isNaN(n)&&n>=0&&n<=2147483647)return n}}return null}},{key:"_applyCustomStyles",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e&&e.style){var n;this._isValidCssColor(this.options.primaryColor)&&"function"==typeof e.style.setProperty&&e.style.setProperty("--akvo-primary",this.options.primaryColor.trim()),"bottom-left"===String(this.options.position||"").trim().toLowerCase()&&(null===(n=e.classList)||void 0===n||n.add("akvo-position-left"));var i=this._toSafeZIndex(this.options.zIndex);if(null!==i&&"function"==typeof e.style.setProperty){var r=t?Math.max(0,i-1):i;e.style.setProperty("--akvo-z-index",String(r)),e.style.zIndex=String(r)}if(t&&"function"==typeof e.style.setProperty){var o=this._toCssDimension(this.options.launcherSize),s=this._toCssDimension(this.options.launcherWidth)||o,a=this._toCssDimension(this.options.launcherHeight)||o;s&&e.style.setProperty("--akvo-launcher-width",s),a&&e.style.setProperty("--akvo-launcher-height",a)}else if(!t&&"function"==typeof e.style.setProperty){var l=this._toCssDimension(this.options.width);l&&e.style.setProperty("--akvo-width",l);var c=this._toCssDimension(this.options.height);c&&e.style.setProperty("--akvo-height",c);var u=this._toCssDimension(this.options.borderRadius);u&&e.style.setProperty("--akvo-border-radius",u)}}}},{key:"_sanitizeHtml",value:function(e,t){if("function"==typeof(null==te?void 0:te.sanitize))return te.sanitize(e,t);if("function"==typeof te)try{var n=te(globalThis.window||globalThis);if("function"==typeof(null==n?void 0:n.sanitize))return n.sanitize(e,t)}catch(e){}return String(e).replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+="[^"]*"/gi,"").replace(/on\w+='[^']*'/gi,"")}},{key:"_renderIcon",value:function(e){if(!e)return arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";var t=String(e).trim();if(t.startsWith("<svg")||t.includes("<svg"))return this._sanitizeHtml(t,{USE_PROFILES:{svg:!0,svgFilters:!0}});if(/^(https?:\/\/|data:image\/|\/|\.\/)/i.test(t)||/\.(svg|png|jpe?g|webp|gif)(\?.*)?$/i.test(t)){var n=this._sanitizeHtml(t);return'<img src="'.concat(n,'" alt="icon" class="akvo-icon-img" />')}var i=this._sanitizeHtml(t);return'<i class="'.concat(i,'" aria-hidden="true"></i>')}},{key:"_createLauncher",value:function(){var e=this;this.launcher=document.createElement("button"),this.launcher.id="akvo-rag-launcher",this.launcher.className="akvo-rag-launcher","function"==typeof this.launcher.setAttribute&&(this.launcher.setAttribute("type","button"),this.launcher.setAttribute("aria-label","Open chat")),this.launcher.innerHTML=this._renderIcon(this.options.launcherIcon,'<i class="fa fa-comments" aria-hidden="true"></i>'),this._applyCustomStyles(this.launcher,!0),this.currentPosition&&this._applyPosition(this.launcher,this.currentPosition),this.launcher.style&&(this.launcher.style.display=this.isMinimized?"flex":"none"),document.body&&"function"==typeof document.body.appendChild&&document.body.appendChild(this.launcher),this._makeDraggable(this.launcher,this.launcher,(function(t){e.currentPosition=t}))}},{key:"_renderInputArea",value:function(){return'\n <textarea\n id="akvo-rag-input"\n rows="1"\n placeholder="Type a message..."\n autocomplete="off"\n autocorrect="off"\n autocapitalize="off"\n spellcheck="false"\n ></textarea>\n <button id="akvo-rag-send-btn">Send</button>\n '}},{key:"_createUI",value:function(){var e,t=this;this.container=document.createElement("div"),this.container.id="akvo-rag",this._applyCustomStyles(this.container,!1),this.container.style&&(this.container.style.display=this.showLauncher&&this.isMinimized?"none":"flex"),this.currentPosition&&!this.isMinimized&&this._anchorWindowToLauncher();var n=this.options.headerIcon?'<span class="akvo-header-icon">'.concat(this._renderIcon(this.options.headerIcon,""),"</span>"):"";this.container.innerHTML='\n <div id="akvo-rag-header">\n <div class="akvo-header-title">\n '.concat(n,"\n <span>").concat(this.options.title||"Chatbot",'</span>\n </div>\n <button id="akvo-rag-close-btn" class="akvo-rag-close-btn" aria-label="Minimize chat">\n <i class="fa fa-window-minimize" aria-hidden="true"></i>\n </button>\n </div>\n <div id="akvo-rag-body" class="akvo-rag-body">\n ').concat(!this.options.kb_id&&null!==(e=this.options.kb_options)&&void 0!==e&&e.length?'\n <div id="akvo-kb-options" class="akvo-kb-options">\n <p>Please select a knowledge base to continue:</p>\n '.concat(this.options.kb_options.map((function(e){return'\n <div class="kb-option">\n <input type="radio" id="kb-'.concat(e.kb_id,'" name="akvo-kb" value="').concat(e.kb_id,'">\n <label for="kb-').concat(e.kb_id,'">').concat(e.label,"</label>\n </div>\n ")})).join(""),'\n <div class="akvo-kb-options-hint">\n After selecting, click "Start Chat" to begin.\n </div>\n </div>\n '):'<p class="akvo-msg-system">'.concat(Nt,"</p>"),'\n </div>\n <div id="akvo-rag-input-container" class="akvo-rag-input-container">\n ').concat(this.options.kb_id?this._renderInputArea():'\n <button id="akvo-start-chat-btn" class="akvo-start-chat-btn" style="flex: 1;" disabled>\n Start Chat\n </button>\n ',"\n </div>\n "),document.body.appendChild(this.container);var i=this.container.querySelector("#akvo-rag-header");i&&this._makeDraggable(i,this.container,(function(e){t.currentPosition=e,t.launcher&&t._applyPosition(t.launcher,e)}))}},{key:"_bindEvents",value:function(){var e,t,n,i=this,r=null===(e=this.container)||void 0===e?void 0:e.querySelector("#akvo-rag-header"),o=null===(t=this.container)||void 0===t?void 0:t.querySelector("#akvo-rag-close-btn");if(this.launcher&&"function"==typeof this.launcher.addEventListener&&this.launcher.addEventListener("click",(function(){i._suppressNextClick?i._suppressNextClick=!1:i.open()})),o&&o.addEventListener("click",(function(e){var t;e.stopPropagation(),i.showLauncher?i.close():null!==(t=i.container)&&void 0!==t&&null!==(t=t.classList)&&void 0!==t&&t.contains("minimized")?i.open():i.close()})),r&&r.addEventListener("click",(function(){var e;i._suppressNextClick?i._suppressNextClick=!1:i.showLauncher?i.isMinimized&&i.open():null!==(e=i.container)&&void 0!==e&&null!==(e=e.classList)&&void 0!==e&&e.contains("minimized")&&i.open()})),!this.options.kb_id&&null!==(n=this.options.kb_options)&&void 0!==n&&n.length){var s=this.container.querySelector("#akvo-start-chat-btn");this.container.querySelectorAll("input[name='akvo-kb']").forEach((function(e){e.addEventListener("change",(function(){s.disabled=!1}))})),s.addEventListener("click",this._handleStartChat)}else this._bindInputEvents()}},{key:"_autoResizeInput",value:function(e){if(e&&e.style){e.style.height="auto";var t="number"==typeof e.scrollHeight?e.scrollHeight:38,n=Math.min(120,Math.max(38,t));e.style.height="".concat(n,"px")}}},{key:"_bindInputEvents",value:function(){var e=this,t=this.container.querySelector("#akvo-rag-input"),n=this.container.querySelector("#akvo-rag-send-btn");t&&n&&(t.addEventListener("input",(function(){e._autoResizeInput(t)})),t.addEventListener("keydown",(function(t){"Enter"!==t.key||t.shiftKey||("function"==typeof t.preventDefault&&t.preventDefault(),e._handleSend())})),n.addEventListener("click",this._handleSend))}},{key:"_connect",value:function(){var e=this,t={onReconnect:function(t){console.log("Reconnecting attempt #".concat(t,", resetting isLoading")),e.isLoading=!1,e._updateSendButtonState()},onMaxReconnect:function(){e.isLoading=!1,e._updateSendButtonState(),yt("system","Connection to the chat server lost. Please check your network and refresh the page.")}};this.wsConnection=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=null,r=0,o=e.wsURL||e.wsUrl;return function s(){o?(console.log("[WebSocket] Connecting to: ".concat(o)),(i=new WebSocket(o)).onopen=function(){console.log("[WebSocket] Connected"),r=0,i.send(JSON.stringify({type:"auth",visitor_id:e.visitorId,kb_id:e.kb_id})),e.onOpen&&e.onOpen()},i.onmessage=function(e){var n=null;try{n=JSON.parse(e.data)}catch(t){return void console.warn("[WebSocket] Received non-JSON data",e.data)}if(t){if("ping"===n.type)return i.send(JSON.stringify({type:"pong"})),void console.log("Pong sent to server");if("response_chunk"===n.type&&n.content.includes("__LLM_RESPONSE__"))try{var r,o=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],l=!0,c=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;l=!1}else for(;!(l=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);l=!0);}catch(e){c=!0,r=e}finally{try{if(!l&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return se(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?se(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(n.content.split("__LLM_RESPONSE__"),2),s=o[0],a=o[1],l=function(e){if(!e)return"";var t=e.split(":")[1].trim().replace(/^"|"$/g,"").match(/[A-Za-z0-9+/=]+/);return t?t[0]:""}(s),c=null;if(l)try{var u=atob(l);c=JSON.parse(u)}catch(e){console.warn("Failed to decode or parse base64 contextData",e)}var h=(null===(r=c)||void 0===r||null===(r=r.context)||void 0===r?void 0:r.map((function(e,t){return{id:t+1,text:e.page_content,metadata:e.metadata}})))||[];t(re(re({},n),{},{content:a.trim(),citations:h}))}catch(e){console.error("Failed to parse __LLM_RESPONSE__",e),t(n)}else t(n)}},i.onclose=function(t){if(console.warn("[WebSocket] Closed (URL: ".concat(o,"): code=").concat(t.code," reason=").concat(t.reason||"no reason provided")),e.autoReconnect&&1e3!==t.code)if(r<10){r++;var i=Math.min(1e3*Math.pow(2,r-1),3e4),a=1e3*Math.random()-500,l=Math.max(1e3,i+a);console.log("[WebSocket] Reconnect attempt ".concat(r," in ").concat(Math.round(l),"ms")),null!=n&&n.onReconnect&&n.onReconnect(r),setTimeout((function(){s()}),l)}else console.error("[WebSocket] Max reconnect attempts reached."),e.onMaxReconnect&&e.onMaxReconnect()},i.onerror=function(t){console.error("[WebSocket] Error (URL: ".concat(o,"):"),t),e.onError&&e.onError(t)}):console.warn("[WebSocket] No wsURL provided in options.")}(),{get socket(){return i},close:function(){e.autoReconnect=!1,i&&i.close(1e3,"Client closed connection")}}}(At(At({},this.options),{},{autoReconnect:!0,visitorId:this.visitorId,onMaxReconnect:t.onMaxReconnect}),this._onMessage,t)}},{key:"_handleStartChat",value:function(){var e=this.container.querySelector("input[name='akvo-kb']:checked");if(e){this.options.kb_id=parseInt(e.value,10);var t=this.container.querySelector("#akvo-kb-options");t&&t.remove(),this.container.querySelector("#akvo-rag-input-container").innerHTML=this._renderInputArea(),this._connect();var n=this.container.querySelector("#akvo-rag-body");if(!this._loadHistoryFromStorage().length){var i=document.createElement("p");i.className="akvo-msg-system",i.textContent=Nt,n.appendChild(i)}this._bindInputEvents(),this._rehydrateHistory()}}},{key:"_handleSend",value:function(){var e;if(!this.isLoading){var t=this.container.querySelector("#akvo-rag-input"),n=t.value.trim();if(n&&(null===(e=this.wsConnection)||void 0===e||null===(e=e.socket)||void 0===e?void 0:e.readyState)===WebSocket.OPEN){this.chatHistory.push({role:"user",content:n}),this._saveHistoryToStorage();var i=this.chatHistory.slice(-10);this.wsConnection.socket.send(JSON.stringify({type:"chat",kb_id:this.options.kb_id,messages:i})),yt("user",n),t.value="",t.style&&(t.style.height="auto"),this.currentAssistantMsgEl=null,this.isLoading=!0,this._updateSendButtonState()}}}},{key:"_updateSendButtonState",value:function(){var e=this.container.querySelector("#akvo-rag-send-btn");e&&(this.isLoading?(e.disabled=!0,e.innerHTML='<span class="akvo-send-spinner"></span>'):(e.disabled=!1,e.innerHTML="Send"))}},{key:"_onMessage",value:function(e){var t=this;if("info"===e.type)yt("system",e.message);else if("start"===e.type)this.citations=[],this.messageCounter++,this.currentAssistantMsgEl=yt("assistant","",!0,this.messageCounter);else if("response_chunk"===e.type){var n;null!=e&&null!==(n=e.citations)&&void 0!==n&&n.length&&e.citations.forEach((function(e){var n=t.citations.findIndex((function(t){return t.id===e.id}));if(n>-1){var i=t.citations[n],r=e.text&&e.metadata,o=i.text&&i.metadata;!r&&o||(t.citations[n]=e)}else t.citations.push(e)})),function(e,t){var n=document.querySelector("#akvo-rag-body");if(n&&e&&t){t.rawText||(t.rawText="");var i=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(/^\s*d:\{/.test(e))return t;var n=e;(n=n.replace(/^\d+:\s*/,"")).startsWith('"')&&(n=n.substring(1)),n.endsWith('"')?n=n.substring(0,n.length-1):n.trimEnd().endsWith('"')&&(n=(n=n.trimEnd()).substring(0,n.length-1));try{var i=n.replace(/\\"/g,'"').replace(/"/g,'\\"');n=JSON.parse('"'+i+'"')}catch(e){}return((t||"")+n).replace(/^"\s*/,"")}(e,t.rawText);t.rawText=i;var r=function(e){var t=e;t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/\b[A-Za-z0-9](?: [A-Za-z0-9])+\b/g,(function(e){return e.replace(/ /g,"")}))).replace(/\s+([,.:;!?])/g,"$1")).replace(/(\*\*|__)\s*(.*?)\s*(\*\*|__)/g,"$1$2$3")).replace(/` +([^`]+?) +`/g,"`$1`")).replace(/``` *bash/g,"```bash")).replace(/\\\n\s*/g,"")).replace(/\n{3,}/g,"\n\n")).replace(/[ \t]{2,}/g," ")).split("\n").map((function(e){return e.trim()})).join("\n");var n=[],i="";return t.split("\n").forEach((function(e){""===e?i&&(n.push(i.trim()),i=""):i?/[.!?]$/.test(i)?(n.push(i.trim()),i=e):i+=" "+e:i=e})),i&&n.push(i.trim()),n.join("\n\n")}(t.rawText);if(t.lastRenderedText!==r){var o=mt.parse(r),s=te.sanitize(o);t.innerHTML=s,t.lastRenderedText=r,n.scrollTop=n.scrollHeight}}}(e.content,this.currentAssistantMsgEl)}else if("end"===e.type){var i=this.currentAssistantMsgEl||document.querySelector("#akvo-msg-assistant-".concat(this.messageCounter));i&&(bt(i,this.citations,this.options.showCitations),null!=i&&i.rawText&&(this.chatHistory.push({role:"assistant",content:i.rawText,citations:this.citations&&this.citations.length?St(this.citations):void 0}),this._saveHistoryToStorage())),this.isLoading=!1,this._updateSendButtonState()}}}],t&&Lt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Pt(){return new It(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}return"undefined"!=typeof window&&(window.AkvoRAG={initChat:Pt}),t})()));
package/dist/index.html CHANGED
@@ -52,7 +52,7 @@
52
52
  .tok-bool { color: #F59E0B; } /* amber-500 booleans */
53
53
  .tok-num { color: #A78BFA; } /* violet-400 numbers */
54
54
  .tok-com { color: #64748B; font-style: italic; } /* slate-500 comments */
55
- .tok-punc { color: #94A3B8; } /* slate-400 punctuation */</style><script defer="defer" src="akvo-rag.js"></script><link href="akvo-rag.css" rel="stylesheet"></head><body class="min-h-screen bg-[#F8F9FA] text-[#09090B] font-sans antialiased selection:bg-[#007A78]/15 selection:text-[#005D5B]"><header class="sticky top-0 z-40 bg-white/95 backdrop-blur border-b border-border" data-purpose="top-navigation-bar"><div class="max-w-[1536px] mx-auto px-4 sm:px-6 lg:px-8 h-14 flex items-center justify-between gap-4"><div class="flex items-center gap-3"><div class="w-8 h-8 rounded-lg bg-neutral-900 text-white flex items-center justify-center font-mono font-bold text-xs tracking-wider border border-neutral-700 shadow-sm">AR</div><nav aria-label="Breadcrumb" class="flex items-center space-x-2 text-sm"><a class="font-semibold text-neutral-900 hover:text-black tracking-tight font-mono" href="#">akvo-rag-js</a> <span class="text-neutral-400">/</span> <span class="font-medium text-neutral-600">Workbench</span></nav><div class="hidden sm:flex items-center gap-1.5 ml-2"><span class="inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-mono font-medium bg-emerald-50 text-emerald-700 border border-emerald-200/60">v1.2.4 </span><span class="inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-mono text-neutral-500 bg-neutral-100 border border-neutral-200">UMD + ESM </span><span class="inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-mono text-neutral-500 bg-neutral-100 border border-neutral-200">Node 18+</span></div></div><div class="flex items-center gap-2"><a class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 rounded-md transition-colors" href="https://github.com/akvo/akvo-rag-js#readme" target="_blank" rel="noopener noreferrer"><svg class="w-4 h-4 text-neutral-400" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1-2.5-2.5Z"></path><path d="M6 6h10"></path><path d="M6 10h10"></path></svg> Docs </a><a class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 rounded-md transition-colors" href="https://github.com/akvo/akvo-rag-js" target="_blank" rel="noopener noreferrer"><svg class="w-4 h-4 text-neutral-400" fill="currentColor" viewbox="0 0 24 24"><path clip-rule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.53 1.032 1.53 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" fill-rule="evenodd"></path></svg> Repository</a><div class="h-4 w-[1px] bg-neutral-200 mx-1"></div><button id="btnResetConfig" class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-neutral-700 bg-neutral-100 hover:bg-neutral-200 border border-neutral-300 rounded-md transition-all shadow-xs" type="button"><svg class="w-3.5 h-3.5 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path><path d="M3 3v5h5"></path></svg> Reset</button></div></div></header><main class="max-w-[1536px] mx-auto px-4 sm:px-6 lg:px-8 py-7" data-purpose="workbench-workspace"><div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-3"><div><h1 class="text-xl font-bold tracking-tight text-neutral-900 flex items-center gap-2">RAG Integration Harness <span class="inline-flex items-center gap-1.5 text-xs font-medium px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200"><span class="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span> Mounted &amp; Active</span></h1><p class="text-xs text-neutral-500 mt-1 max-w-2xl leading-relaxed">Interactive client-side harness for testing launcher positioning, runtime CSS custom properties, reactive DOM lifecycle hooks, and tokenized chatbox embedding.</p></div><div class="flex items-center gap-2 self-start md:self-auto"><span class="text-xs font-mono text-neutral-400">Target: DOM-Window</span> <button class="text-xs font-medium px-2.5 py-1.5 bg-white border border-neutral-200 rounded-md text-neutral-700 hover:bg-neutral-50 shadow-xs flex items-center gap-1.5" id="togglePreviewViewBtn" type="button"><svg class="w-3.5 h-3.5 text-neutral-400" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><rect height="18" rx="2" width="18" x="3" y="3"></rect><path d="M9 3v18"></path></svg> Layout View</button></div></div><div id="workspaceGrid" class="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start"><section class="lg:col-span-5 bg-white border border-border rounded-xl shadow-card flex flex-col overflow-hidden" data-purpose="configuration-inspector"><div class="px-5 py-3.5 border-b border-border bg-neutral-50/50 flex items-center justify-between"><div class="flex items-center gap-2"><svg class="w-4 h-4 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"></path><circle cx="12" cy="12" r="3"></circle></svg><h2 class="text-xs font-semibold tracking-wider uppercase text-neutral-800 font-mono">Configuration Inspector</h2></div><span class="text-[11px] font-mono text-neutral-400">client_options</span></div><div class="p-5 space-y-6 divide-y divide-neutral-100 max-h-[calc(100vh-210px)] overflow-y-auto"><div class="space-y-3 pt-1"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Display Mode</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.showLauncher</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1" role="radiogroup"><button aria-checked="true" class="px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 font-sans flex items-center justify-center gap-1.5" id="btnDisplayFab" type="button"><svg class="w-3.5 h-3.5 text-emerald-600" fill="none" stroke="currentColor" stroke-width="2.5" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg> Circular FAB <span class="text-[10px] text-neutral-400">(Modern)</span></button> <button aria-checked="false" class="px-3 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all font-sans flex items-center justify-center gap-1.5" id="btnDisplayEmbedded" type="button">Embedded Box <span class="text-[10px] text-neutral-400">(Legacy)</span></button></div><p class="text-[11px] text-neutral-500 leading-normal">Circular FAB renders a persistent 56×56px floating trigger at the viewport edge. Embedded mounts a direct 360×500px container inside host markup.</p></div><div id="startStateContainer" class="space-y-3 pt-5"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Initial Mount State</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.startMinimized</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1"><button class="px-3 py-1.5 text-xs font-mono font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5" id="btnMountMinTrue" type="button">startMinimized: true</button> <button class="px-3 py-1.5 text-xs font-mono font-medium rounded-md text-neutral-500 hover:text-neutral-900 transition-all" id="btnMountMinFalse" type="button">startMinimized: false</button></div><p class="text-[11px] text-neutral-500 leading-normal">When true, the chat engine mounts with the discreet launcher bubble; clicking expands the chat. When false, the full chatbox renders open immediately.</p></div><div class="space-y-3 pt-5" data-purpose="theme-token-selector"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Theme Token</label> <code class="text-[11px] font-mono text-teal-700 bg-teal-50 border border-teal-200/50 px-1.5 py-0.5 rounded">--akvo-primary</code></div><div class="flex items-center gap-2 flex-wrap"><button class="theme-swatch group relative w-8 h-8 rounded-lg bg-[#007A78] flex items-center justify-center ring-2 ring-neutral-900 ring-offset-2 transition-transform active:scale-95" data-color="#007A78" title="Default Teal (#007A78)" type="button"><svg class="w-4 h-4 text-white check-icon" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#0284C7] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#0284C7" title="Cyan 600 (#0284C7)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#059669] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#059669" title="Emerald 600 (#059669)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#D97706] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#D97706" title="Amber 600 (#D97706)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#475569] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#475569" title="Slate 600 (#475569)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#09090B] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#09090B" title="Zinc 950 (#09090B)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button><div class="ml-auto flex items-center border border-neutral-300 rounded-lg overflow-hidden focus-within:border-neutral-800 transition-colors bg-white"><input class="w-7 h-7 p-0 border-0 cursor-pointer ml-1" id="nativeColorInput" type="color" value="#007A78"/> <span class="text-xs font-mono text-neutral-400 pl-1">#</span> <input class="w-20 border-0 text-xs font-mono py-1 px-1 text-neutral-800 uppercase focus:ring-0" id="hexTextInput" maxlength="6" value="007A78"/></div></div><p class="text-[11px] text-neutral-500 leading-normal">Dynamically cascades into FAB backdrop, active citations, inline copy-action highlights, and send button state.</p></div><div id="launcherIconContainer" class="space-y-3 pt-5"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700" for="selectLauncherIcon">Launcher Icon & Size</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.launcherIcon</code></div><div class="relative"><select class="w-full text-xs font-medium rounded-lg border-neutral-300 py-2 pl-3 pr-8 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900 focus:ring-1 focus:ring-neutral-900" id="selectLauncherIcon"><option selected="" value="bubble">Default Comment Bubble (FontAwesome)</option><option value="sparkle">Sparkle AI Intelligence (Inline SVG)</option><option value="robot">Assistant Bot Silhouette (Inline SVG)</option><option value="custom_url">External Asset URL (CDN image)</option></select></div><div><div class="flex items-center justify-between mb-1"><label class="text-[11px] font-medium text-neutral-600" for="selectLauncherSize">Button Size (FAB)</label> <code class="text-[10px] font-mono text-neutral-400">options.launcherSize</code></div><select class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-2 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectLauncherSize"><option value="48px">48×48px (Compact)</option><option selected="selected" value="56px">56×56px (Standard FAB)</option><option value="64px">64×64px (Large)</option></select></div><p class="text-[11px] text-neutral-400">Supports DOMPurified SVG markup, image URLs (.svg/.png), and custom button dimensions.</p></div><div class="space-y-4 pt-5"><div><div class="flex items-center justify-between mb-1.5"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700" for="inputHeaderTitle">Chat Header Title</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.title</code></div><input class="w-full text-xs font-mono rounded-lg border-neutral-300 py-2 px-3 text-neutral-900 focus:border-neutral-900 focus:ring-1 focus:ring-neutral-900" id="inputHeaderTitle" value="Akvo Assistant"/></div><div><div class="flex items-center justify-between mb-1.5"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700" for="selectHeaderAvatar">Header Avatar Icon</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.headerIcon</code></div><select class="w-full text-xs font-medium rounded-lg border-neutral-300 py-2 pl-3 pr-8 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectHeaderAvatar"><option selected="" value="none">None (Title Only)</option><option value="bot">Default Verified Bot Badge (SVG)</option><option value="custom_url">Custom Team Avatar (Image URL)</option></select></div></div><div class="space-y-4 pt-5"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Position & Dimensions</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">position / size</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1"><button class="px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1" id="btnPosRight" type="button">Bottom Right</button> <button class="px-3 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all flex items-center justify-center gap-1" id="btnPosLeft" type="button">Bottom Left</button></div><div class="grid grid-cols-2 gap-3"><div><label class="block text-[11px] font-medium text-neutral-600 mb-1" for="selectWidth">Width</label> <select class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-2 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectWidth"><option value="320px">320px (Compact)</option><option selected="selected" value="360px">360px (Standard)</option><option value="400px">400px (Medium)</option><option value="460px">460px (Wide)</option></select></div><div><label class="block text-[11px] font-medium text-neutral-600 mb-1" for="selectHeight">Height</label> <select class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-2 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectHeight"><option value="460px">460px (Short)</option><option selected="selected" value="500px">500px (Standard)</option><option value="580px">580px (Tall)</option><option value="660px">660px (Expanded)</option></select></div></div><div><div class="flex items-center justify-between mb-1"><label class="text-[11px] font-medium text-neutral-600" for="selectRadius">Corner Radius</label> <code class="text-[10px] font-mono text-neutral-400">options.borderRadius</code></div><select class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-2 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectRadius"><option value="4px">4px (Subtle)</option><option selected="selected" value="8px">8px (Default)</option><option value="12px">12px (Rounded)</option><option value="16px">16px (Pill / Soft)</option></select></div></div><div class="space-y-4 pt-5" data-purpose="kb-configuration-group"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">RAG Backend Connection</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.wsURL</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1"><button class="px-2.5 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1.5 font-sans" id="btnWsOnline" type="button"><span class="w-2 h-2 rounded-full bg-emerald-500"></span> Online RAG</button> <button class="px-2.5 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all flex items-center justify-center gap-1.5 font-sans" id="btnWsLocal" type="button"><span class="w-2 h-2 rounded-full bg-neutral-400"></span> Localhost:81</button></div><input class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-3 text-neutral-900 focus:border-neutral-900" id="inputWsUrl" value="wss://akvo-rag.akvotest.org/ws/chat"/><div class="flex items-center justify-between pt-2"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Knowledge Base Setup</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">kb_id / kb_options</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1" role="radiogroup"><button class="px-3 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all flex items-center justify-center gap-1.5 font-sans" id="btnKbModeSingle" type="button">Single KB <span class="text-[10px] text-neutral-400">(Direct)</span></button> <button class="px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1.5 font-sans" id="btnKbModeMulti" type="button">Multi-KB <span class="text-[10px] text-neutral-400">(Picker)</span></button></div><div id="singleKbContainer" class="hidden space-y-2 p-3 bg-neutral-50/80 rounded-lg border border-neutral-200/80"><div class="flex items-center justify-between"><label class="text-[11px] font-semibold text-neutral-700" for="inputSingleKbId">Single KB ID (Direct Session)</label> <code class="text-[10px] font-mono text-neutral-500 bg-neutral-200/60 px-1 rounded">options.kb_id</code></div><input class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-3 text-neutral-900 focus:border-neutral-900" id="inputSingleKbId" type="number" value="750"/><p class="text-[11px] text-neutral-500 leading-normal">Direct connection. Bypasses the knowledge base selection screen and connects immediately with the welcome message and input field ready.</p></div><div id="multiKbContainer" class="space-y-2 p-3 bg-neutral-50/80 rounded-lg border border-neutral-200/80"><div class="flex items-center justify-between"><label class="text-[11px] font-semibold text-neutral-700">Multi-KB Options List</label> <code class="text-[10px] font-mono text-neutral-500 bg-neutral-200/60 px-1 rounded">options.kb_options</code></div><div class="space-y-1.5 text-xs font-mono"><div class="flex items-center justify-between bg-white px-2.5 py-1.5 rounded border border-neutral-200 shadow-2xs"><span class="font-medium text-neutral-800">Critical Thinking</span> <span class="text-[11px] text-neutral-500 bg-neutral-100 px-1.5 py-0.5 rounded font-mono">ID: 750</span></div></div><p class="text-[11px] text-neutral-500 leading-normal">Presents the user with interactive radio buttons to choose their knowledge base first, then enables "Start Chat".</p></div></div></div><div class="p-4 bg-neutral-50/80 border-t border-border mt-auto flex flex-col gap-2.5"><button class="w-full py-2.5 px-4 rounded-lg bg-[#007A78] hover:bg-[#005D5B] text-white text-xs font-semibold tracking-wide transition-all shadow-subtle flex items-center justify-center gap-2 active:scale-[0.99]" id="btnApplyConfig" type="button"><svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2.5" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg> Apply Configuration to Session</button><div class="grid grid-cols-2 gap-2"><button class="py-2 px-3 text-xs font-medium text-neutral-700 bg-white hover:bg-neutral-100 border border-neutral-300 rounded-lg transition-colors flex items-center justify-center gap-1.5" id="btnTriggerOpen" type="button"><svg class="w-3.5 h-3.5 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M15 3h6v6"></path><path d="M10 14 21 3"></path><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path></svg> Trigger Open</button> <button class="py-2 px-3 text-xs font-medium text-neutral-700 bg-white hover:bg-neutral-100 border border-neutral-300 rounded-lg transition-colors flex items-center justify-center gap-1.5" id="btnTriggerMinimize" type="button"><svg class="w-3.5 h-3.5 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M4 14h6v6"></path><path d="M20 10h-6V4"></path><path d="M14 10l7-7"></path><path d="M3 21l7-7"></path></svg> Trigger Minimize</button></div></div></section><section class="lg:col-span-7 space-y-6 flex flex-col" data-purpose="output-telemetry-panel"><div class="bg-surface-dark rounded-xl border border-neutral-800 shadow-card overflow-hidden"><div class="px-4 py-3 bg-[#18181B] border-b border-neutral-800/80 flex items-center justify-between"><div class="flex items-center gap-2"><div class="flex items-center gap-1.5 mr-2"><span class="w-2.5 h-2.5 rounded-full bg-neutral-700"></span> <span class="w-2.5 h-2.5 rounded-full bg-neutral-700"></span> <span class="w-2.5 h-2.5 rounded-full bg-neutral-700"></span></div><div class="flex items-center space-x-1" role="tablist"><button id="tabMultiKb" class="px-2.5 py-1 text-xs font-mono rounded bg-neutral-800 text-white font-medium transition-colors" type="button">Multi-KB (kb_options)</button> <button id="tabSingleKb" class="px-2.5 py-1 text-xs font-mono rounded text-neutral-400 hover:text-neutral-200 hover:bg-neutral-800/50 transition-colors" type="button">Single KB (kb_id)</button> <button id="tabHtmlScript" class="px-2.5 py-1 text-xs font-mono rounded text-neutral-400 hover:text-neutral-200 hover:bg-neutral-800/50 transition-colors" type="button">HTML Script Tag</button></div></div><div class="flex items-center gap-3"><span class="hidden sm:inline-flex items-center gap-1 text-[11px] font-mono text-emerald-400"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400"></span> Ready to deploy </span><button class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono text-neutral-300 hover:text-white bg-neutral-800 hover:bg-neutral-700 rounded border border-neutral-700 transition-colors" id="copyCodeBtn" type="button"><svg class="w-3.5 h-3.5 text-neutral-400" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><rect height="14" rx="2" ry="2" width="14" x="8" y="8"></rect><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"></path></svg> <span id="copyBtnLabel">Copy</span></button></div></div><div class="p-4 sm:p-5 overflow-x-auto text-[13px] font-mono leading-relaxed select-all"><pre class="text-neutral-300"><code id="codeSnippetPre"></code></pre></div><div class="px-4 py-2 bg-[#0E0E10] border-t border-neutral-800 text-[11px] font-mono text-neutral-500 flex justify-between"><span>Bundle cost: ~12.4 kB gzipped</span> <span>UTF-8 | LF</span></div></div><div class="bg-white rounded-xl border border-border shadow-card overflow-hidden" data-purpose="diagnostic-metrics"><div class="px-5 py-3 border-b border-border bg-neutral-50/50 flex items-center justify-between"><div class="flex items-center gap-2"><svg class="w-4 h-4 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M22 12h-4l-3 9L9 3l-3 9H2"></path></svg><h3 class="text-xs font-semibold tracking-wider uppercase text-neutral-800 font-mono">DOM State &amp; Diagnostic Metrics</h3></div><span class="text-[11px] font-mono text-neutral-400">MutationObserver active</span></div><div class="p-5 grid grid-cols-1 sm:grid-cols-3 gap-4"><div class="p-3.5 rounded-lg border border-neutral-200/90 bg-neutral-50/40"><div class="text-[11px] font-mono uppercase text-neutral-500 font-medium">Launcher Element</div><div class="text-sm font-semibold font-mono text-neutral-900 mt-1 flex items-center gap-1.5" id="metricLauncher"><span class="w-2 h-2 rounded-full bg-emerald-500"></span> Visible (56px FAB)</div><span class="text-[10px] text-neutral-400 block mt-0.5">Fixed z-index: 99998</span></div><div class="p-3.5 rounded-lg border border-neutral-200/90 bg-neutral-50/40"><div class="text-[11px] font-mono uppercase text-neutral-500 font-medium">Chatbox Display</div><div class="text-sm font-semibold font-mono text-neutral-900 mt-1" id="metricChatbox">none (Collapsed)</div><span class="text-[10px] text-neutral-400 block mt-0.5">Hydrated &amp; Collapsed</span></div><div class="p-3.5 rounded-lg border border-neutral-200/90 bg-neutral-50/40"><div class="text-[11px] font-mono uppercase text-neutral-500 font-medium">Token Inheritance</div><div class="text-sm font-semibold font-mono text-neutral-900 mt-1 flex items-center gap-1.5" id="metricToken"><span class="w-3 h-3 rounded bg-[#007A78]" id="metricColorDot"></span> <span id="metricTokenHex">#007A78</span></div><span class="text-[10px] text-neutral-400 block mt-0.5">Applied via --akvo-primary</span></div></div><div class="px-5 py-3 border-t border-neutral-100 bg-neutral-50/20 text-xs text-neutral-500 flex items-center justify-between"><span class="font-mono text-[11px] flex items-center gap-1.5"><span class="text-neutral-400">Recent Event:</span> <span id="recentEventText" class="text-neutral-700 bg-neutral-100 px-1.5 py-0.5 rounded font-mono">chat:ready (t+0ms)</span> </span><span class="text-[11px] font-mono text-teal-700">Live Client Connected</span></div></div></section></div></main><script data-purpose="workbench-interactivity">document.addEventListener('DOMContentLoaded', () => {
55
+ .tok-punc { color: #94A3B8; } /* slate-400 punctuation */</style><script defer="defer" src="akvo-rag.js"></script><link href="akvo-rag.css" rel="stylesheet"></head><body class="min-h-screen bg-[#F8F9FA] text-[#09090B] font-sans antialiased selection:bg-[#007A78]/15 selection:text-[#005D5B]"><header class="sticky top-0 z-40 bg-white/95 backdrop-blur border-b border-border" data-purpose="top-navigation-bar"><div class="max-w-[1536px] mx-auto px-4 sm:px-6 lg:px-8 h-14 flex items-center justify-between gap-4"><div class="flex items-center gap-3"><div class="w-8 h-8 rounded-lg bg-neutral-900 text-white flex items-center justify-center font-mono font-bold text-xs tracking-wider border border-neutral-700 shadow-sm">AR</div><nav aria-label="Breadcrumb" class="flex items-center space-x-2 text-sm"><a class="font-semibold text-neutral-900 hover:text-black tracking-tight font-mono" href="#">akvo-rag-js</a> <span class="text-neutral-400">/</span> <span class="font-medium text-neutral-600">Workbench</span></nav><div class="hidden sm:flex items-center gap-1.5 ml-2"><span class="inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-mono font-medium bg-emerald-50 text-emerald-700 border border-emerald-200/60">v1.2.4 </span><span class="inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-mono text-neutral-500 bg-neutral-100 border border-neutral-200">UMD + ESM </span><span class="inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-mono text-neutral-500 bg-neutral-100 border border-neutral-200">Node 18+</span></div></div><div class="flex items-center gap-2"><a class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 rounded-md transition-colors" href="https://github.com/akvo/akvo-rag-js#readme" target="_blank" rel="noopener noreferrer"><svg class="w-4 h-4 text-neutral-400" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1-2.5-2.5Z"></path><path d="M6 6h10"></path><path d="M6 10h10"></path></svg> Docs </a><a class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 rounded-md transition-colors" href="https://github.com/akvo/akvo-rag-js" target="_blank" rel="noopener noreferrer"><svg class="w-4 h-4 text-neutral-400" fill="currentColor" viewbox="0 0 24 24"><path clip-rule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.53 1.032 1.53 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" fill-rule="evenodd"></path></svg> Repository</a><div class="h-4 w-[1px] bg-neutral-200 mx-1"></div><button id="btnResetConfig" class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-neutral-700 bg-neutral-100 hover:bg-neutral-200 border border-neutral-300 rounded-md transition-all shadow-xs" type="button"><svg class="w-3.5 h-3.5 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path><path d="M3 3v5h5"></path></svg> Reset</button></div></div></header><main class="max-w-[1536px] mx-auto px-4 sm:px-6 lg:px-8 py-7" data-purpose="workbench-workspace"><div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-3"><div><h1 class="text-xl font-bold tracking-tight text-neutral-900 flex items-center gap-2">RAG Integration Harness <span class="inline-flex items-center gap-1.5 text-xs font-medium px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200"><span class="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span> Mounted &amp; Active</span></h1><p class="text-xs text-neutral-500 mt-1 max-w-2xl leading-relaxed">Interactive client-side harness for testing launcher positioning, runtime CSS custom properties, reactive DOM lifecycle hooks, and tokenized chatbox embedding.</p></div><div class="flex items-center gap-2 self-start md:self-auto"><span class="text-xs font-mono text-neutral-400">Target: DOM-Window</span> <button class="text-xs font-medium px-2.5 py-1.5 bg-white border border-neutral-200 rounded-md text-neutral-700 hover:bg-neutral-50 shadow-xs flex items-center gap-1.5" id="togglePreviewViewBtn" type="button"><svg class="w-3.5 h-3.5 text-neutral-400" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><rect height="18" rx="2" width="18" x="3" y="3"></rect><path d="M9 3v18"></path></svg> Layout View</button></div></div><div id="workspaceGrid" class="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start"><section class="lg:col-span-5 bg-white border border-border rounded-xl shadow-card flex flex-col overflow-hidden" data-purpose="configuration-inspector"><div class="px-5 py-3.5 border-b border-border bg-neutral-50/50 flex items-center justify-between"><div class="flex items-center gap-2"><svg class="w-4 h-4 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"></path><circle cx="12" cy="12" r="3"></circle></svg><h2 class="text-xs font-semibold tracking-wider uppercase text-neutral-800 font-mono">Configuration Inspector</h2></div><span class="text-[11px] font-mono text-neutral-400">client_options</span></div><div class="p-5 space-y-6 divide-y divide-neutral-100 max-h-[calc(100vh-210px)] overflow-y-auto"><div class="space-y-3 pt-1"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Display Mode</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.showLauncher</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1" role="radiogroup"><button aria-checked="true" class="px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 font-sans flex items-center justify-center gap-1.5" id="btnDisplayFab" type="button"><svg class="w-3.5 h-3.5 text-emerald-600" fill="none" stroke="currentColor" stroke-width="2.5" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg> Circular FAB <span class="text-[10px] text-neutral-400">(Modern)</span></button> <button aria-checked="false" class="px-3 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all font-sans flex items-center justify-center gap-1.5" id="btnDisplayEmbedded" type="button">Embedded Box <span class="text-[10px] text-neutral-400">(Legacy)</span></button></div><p class="text-[11px] text-neutral-500 leading-normal">Circular FAB renders a persistent 56×56px floating trigger at the viewport edge. Embedded mounts a direct 360×500px container inside host markup.</p></div><div id="startStateContainer" class="space-y-3 pt-5"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Initial Mount State</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.startMinimized</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1"><button class="px-3 py-1.5 text-xs font-mono font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5" id="btnMountMinTrue" type="button">startMinimized: true</button> <button class="px-3 py-1.5 text-xs font-mono font-medium rounded-md text-neutral-500 hover:text-neutral-900 transition-all" id="btnMountMinFalse" type="button">startMinimized: false</button></div><p class="text-[11px] text-neutral-500 leading-normal">When true, the chat engine mounts with the discreet launcher bubble; clicking expands the chat. When false, the full chatbox renders open immediately.</p></div><div class="space-y-3 pt-5" data-purpose="theme-token-selector"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Theme Token</label> <code class="text-[11px] font-mono text-teal-700 bg-teal-50 border border-teal-200/50 px-1.5 py-0.5 rounded">--akvo-primary</code></div><div class="flex items-center gap-2 flex-wrap"><button class="theme-swatch group relative w-8 h-8 rounded-lg bg-[#007A78] flex items-center justify-center ring-2 ring-neutral-900 ring-offset-2 transition-transform active:scale-95" data-color="#007A78" title="Default Teal (#007A78)" type="button"><svg class="w-4 h-4 text-white check-icon" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#0284C7] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#0284C7" title="Cyan 600 (#0284C7)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#059669] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#059669" title="Emerald 600 (#059669)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#D97706] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#D97706" title="Amber 600 (#D97706)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#475569] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#475569" title="Slate 600 (#475569)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button> <button class="theme-swatch w-8 h-8 rounded-lg bg-[#09090B] flex items-center justify-center ring-1 ring-black/10 hover:ring-2 hover:ring-neutral-400 ring-offset-1 transition-transform active:scale-95" data-color="#09090B" title="Zinc 950 (#09090B)" type="button"><svg class="w-4 h-4 text-white check-icon hidden" fill="none" stroke="currentColor" stroke-width="3" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg></button><div class="ml-auto flex items-center border border-neutral-300 rounded-lg overflow-hidden focus-within:border-neutral-800 transition-colors bg-white"><input class="w-7 h-7 p-0 border-0 cursor-pointer ml-1" id="nativeColorInput" type="color" value="#007A78"/> <span class="text-xs font-mono text-neutral-400 pl-1">#</span> <input class="w-20 border-0 text-xs font-mono py-1 px-1 text-neutral-800 uppercase focus:ring-0" id="hexTextInput" maxlength="6" value="007A78"/></div></div><p class="text-[11px] text-neutral-500 leading-normal">Dynamically cascades into FAB backdrop, active citations, inline copy-action highlights, and send button state.</p></div><div id="launcherIconContainer" class="space-y-3 pt-5"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700" for="selectLauncherIcon">Launcher Icon & Size</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.launcherIcon</code></div><div class="relative"><select class="w-full text-xs font-medium rounded-lg border-neutral-300 py-2 pl-3 pr-8 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900 focus:ring-1 focus:ring-neutral-900" id="selectLauncherIcon"><option selected="" value="bubble">Default Comment Bubble (FontAwesome)</option><option value="sparkle">Sparkle AI Intelligence (Inline SVG)</option><option value="robot">Assistant Bot Silhouette (Inline SVG)</option><option value="custom_url">External Asset URL (CDN image)</option></select></div><div><div class="flex items-center justify-between mb-1"><label class="text-[11px] font-medium text-neutral-600" for="selectLauncherSize">Button Size (FAB)</label> <code class="text-[10px] font-mono text-neutral-400">options.launcherSize</code></div><select class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-2 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectLauncherSize"><option value="48px">48×48px (Compact)</option><option selected="selected" value="56px">56×56px (Standard FAB)</option><option value="64px">64×64px (Large)</option></select></div><p class="text-[11px] text-neutral-400">Supports DOMPurified SVG markup, image URLs (.svg/.png), and custom button dimensions.</p></div><div class="space-y-4 pt-5"><div><div class="flex items-center justify-between mb-1.5"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700" for="inputHeaderTitle">Chat Header Title</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.title</code></div><input class="w-full text-xs font-mono rounded-lg border-neutral-300 py-2 px-3 text-neutral-900 focus:border-neutral-900 focus:ring-1 focus:ring-neutral-900" id="inputHeaderTitle" value="Akvo Assistant"/></div><div><div class="flex items-center justify-between mb-1.5"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700" for="selectHeaderAvatar">Header Avatar Icon</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.headerIcon</code></div><select class="w-full text-xs font-medium rounded-lg border-neutral-300 py-2 pl-3 pr-8 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectHeaderAvatar"><option selected="" value="none">None (Title Only)</option><option value="bot">Default Verified Bot Badge (SVG)</option><option value="custom_url">Custom Team Avatar (Image URL)</option></select></div></div><div class="space-y-4 pt-5"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Position & Dimensions</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">position / size</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1"><button class="px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1" id="btnPosRight" type="button">Bottom Right</button> <button class="px-3 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all flex items-center justify-center gap-1" id="btnPosLeft" type="button">Bottom Left</button></div><div class="grid grid-cols-2 gap-3"><div><label class="block text-[11px] font-medium text-neutral-600 mb-1" for="selectWidth">Width</label> <select class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-2 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectWidth"><option value="320px">320px (Compact)</option><option selected="selected" value="360px">360px (Standard)</option><option value="400px">400px (Medium)</option><option value="460px">460px (Wide)</option></select></div><div><label class="block text-[11px] font-medium text-neutral-600 mb-1" for="selectHeight">Height</label> <select class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-2 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectHeight"><option value="460px">460px (Short)</option><option selected="selected" value="500px">500px (Standard)</option><option value="580px">580px (Tall)</option><option value="660px">660px (Expanded)</option></select></div></div><div><div class="flex items-center justify-between mb-1"><label class="text-[11px] font-medium text-neutral-600" for="selectRadius">Corner Radius</label> <code class="text-[10px] font-mono text-neutral-400">options.borderRadius</code></div><select class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-2 text-neutral-800 bg-white hover:border-neutral-400 focus:border-neutral-900" id="selectRadius"><option value="4px">4px (Subtle)</option><option selected="selected" value="8px">8px (Default)</option><option value="12px">12px (Rounded)</option><option value="16px">16px (Pill / Soft)</option></select></div><div class="pt-2 border-t border-neutral-100 space-y-2"><div class="flex items-center justify-between"><span class="text-[11px] font-medium text-neutral-700">Draggable Launcher & Header</span> <label class="relative inline-flex items-center cursor-pointer"><input type="checkbox" id="checkDraggable" checked="checked" class="sr-only peer"><div class="w-8 h-4 bg-neutral-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-neutral-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-[#007A78]"></div></label></div><div class="flex items-center justify-between"><span class="text-[11px] font-medium text-neutral-700">Persist Position (localStorage)</span> <label class="relative inline-flex items-center cursor-pointer"><input type="checkbox" id="checkPersist" checked="checked" class="sr-only peer"><div class="w-8 h-4 bg-neutral-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-neutral-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-[#007A78]"></div></label></div></div></div><div class="space-y-3 pt-5" data-purpose="history-citations-group"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">History & Citations</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">history / citations</code></div><div class="flex items-center justify-between"><div><span class="text-[11px] font-medium text-neutral-700 block">Persist History</span> <span class="text-[10px] text-neutral-400">Preserve chat transcript across page reloads</span></div><label class="relative inline-flex items-center cursor-pointer"><input type="checkbox" id="checkPersistHistory" checked="checked" class="sr-only peer"><div class="w-8 h-4 bg-neutral-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-neutral-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-[#007A78]"></div></label></div><div><div class="flex items-center justify-between mb-1"><label class="text-[11px] font-medium text-neutral-600" for="inputUserId">User ID (Isolation Scope)</label> <code class="text-[10px] font-mono text-neutral-400">options.userId</code></div><input class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-3 text-neutral-900 focus:border-neutral-900" id="inputUserId" placeholder="e.g. user_alpha (leave empty for visitorId)" value=""/><p class="text-[10px] text-neutral-400 mt-1">Different user IDs maintain completely segregated chat transcripts.</p></div><div class="flex items-center justify-between pt-1"><div><span class="text-[11px] font-medium text-neutral-700 block">Show Citations</span> <span class="text-[10px] text-neutral-400">Render superscript source popovers</span></div><label class="relative inline-flex items-center cursor-pointer"><input type="checkbox" id="checkShowCitations" checked="checked" class="sr-only peer"><div class="w-8 h-4 bg-neutral-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-neutral-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-[#007A78]"></div></label></div><div class="pt-2"><button class="w-full py-1.5 px-3 text-xs font-medium text-red-600 bg-red-50 hover:bg-red-100 border border-red-200 rounded-lg transition-colors flex items-center justify-center gap-1.5" id="btnClearHistory" type="button"><svg class="w-3.5 h-3.5 text-red-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M10 11v6M14 11v6"></path></svg> Clear Current Session History</button></div></div><div class="space-y-4 pt-5" data-purpose="kb-configuration-group"><div class="flex items-center justify-between"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">RAG Backend Connection</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">options.wsURL</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1"><button class="px-2.5 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1.5 font-sans" id="btnWsOnline" type="button"><span class="w-2 h-2 rounded-full bg-emerald-500"></span> Online RAG</button> <button class="px-2.5 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all flex items-center justify-center gap-1.5 font-sans" id="btnWsLocal" type="button"><span class="w-2 h-2 rounded-full bg-neutral-400"></span> Localhost:81</button></div><input class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-3 text-neutral-900 focus:border-neutral-900" id="inputWsUrl" value="wss://akvo-rag.akvotest.org/ws/chat"/><div class="flex items-center justify-between pt-2"><label class="text-xs font-semibold uppercase tracking-wider text-neutral-700">Knowledge Base Setup</label> <code class="text-[11px] font-mono text-neutral-400 bg-neutral-100 px-1.5 py-0.5 rounded">kb_id / kb_options</code></div><div class="grid grid-cols-2 p-1 bg-neutral-100/90 border border-neutral-200/80 rounded-lg gap-1" role="radiogroup"><button class="px-3 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all flex items-center justify-center gap-1.5 font-sans" id="btnKbModeSingle" type="button">Single KB <span class="text-[10px] text-neutral-400">(Direct)</span></button> <button class="px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1.5 font-sans" id="btnKbModeMulti" type="button">Multi-KB <span class="text-[10px] text-neutral-400">(Picker)</span></button></div><div id="singleKbContainer" class="hidden space-y-2 p-3 bg-neutral-50/80 rounded-lg border border-neutral-200/80"><div class="flex items-center justify-between"><label class="text-[11px] font-semibold text-neutral-700" for="inputSingleKbId">Single KB ID (Direct Session)</label> <code class="text-[10px] font-mono text-neutral-500 bg-neutral-200/60 px-1 rounded">options.kb_id</code></div><input class="w-full text-xs font-mono rounded-lg border-neutral-300 py-1.5 px-3 text-neutral-900 focus:border-neutral-900" id="inputSingleKbId" type="number" value="750"/><p class="text-[11px] text-neutral-500 leading-normal">Direct connection. Bypasses the knowledge base selection screen and connects immediately with the welcome message and input field ready.</p></div><div id="multiKbContainer" class="space-y-2 p-3 bg-neutral-50/80 rounded-lg border border-neutral-200/80"><div class="flex items-center justify-between"><label class="text-[11px] font-semibold text-neutral-700">Multi-KB Options List</label> <code class="text-[10px] font-mono text-neutral-500 bg-neutral-200/60 px-1 rounded">options.kb_options</code></div><div class="space-y-1.5 text-xs font-mono"><div class="flex items-center justify-between bg-white px-2.5 py-1.5 rounded border border-neutral-200 shadow-2xs"><span class="font-medium text-neutral-800">Critical Thinking</span> <span class="text-[11px] text-neutral-500 bg-neutral-100 px-1.5 py-0.5 rounded font-mono">ID: 750</span></div></div><p class="text-[11px] text-neutral-500 leading-normal">Presents the user with interactive radio buttons to choose their knowledge base first, then enables "Start Chat".</p></div></div></div><div class="p-4 bg-neutral-50/80 border-t border-border mt-auto flex flex-col gap-2.5"><button class="w-full py-2.5 px-4 rounded-lg bg-[#007A78] hover:bg-[#005D5B] text-white text-xs font-semibold tracking-wide transition-all shadow-subtle flex items-center justify-center gap-2 active:scale-[0.99]" id="btnApplyConfig" type="button"><svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2.5" viewbox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg> Apply Configuration to Session</button><div class="grid grid-cols-2 gap-2"><button class="py-2 px-3 text-xs font-medium text-neutral-700 bg-white hover:bg-neutral-100 border border-neutral-300 rounded-lg transition-colors flex items-center justify-center gap-1.5" id="btnTriggerOpen" type="button"><svg class="w-3.5 h-3.5 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M15 3h6v6"></path><path d="M10 14 21 3"></path><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path></svg> Trigger Open</button> <button class="py-2 px-3 text-xs font-medium text-neutral-700 bg-white hover:bg-neutral-100 border border-neutral-300 rounded-lg transition-colors flex items-center justify-center gap-1.5" id="btnTriggerMinimize" type="button"><svg class="w-3.5 h-3.5 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M4 14h6v6"></path><path d="M20 10h-6V4"></path><path d="M14 10l7-7"></path><path d="M3 21l7-7"></path></svg> Trigger Minimize</button></div></div></section><section class="lg:col-span-7 space-y-6 flex flex-col" data-purpose="output-telemetry-panel"><div class="bg-surface-dark rounded-xl border border-neutral-800 shadow-card overflow-hidden"><div class="px-4 py-3 bg-[#18181B] border-b border-neutral-800/80 flex items-center justify-between"><div class="flex items-center gap-2"><div class="flex items-center gap-1.5 mr-2"><span class="w-2.5 h-2.5 rounded-full bg-neutral-700"></span> <span class="w-2.5 h-2.5 rounded-full bg-neutral-700"></span> <span class="w-2.5 h-2.5 rounded-full bg-neutral-700"></span></div><div class="flex items-center space-x-1" role="tablist"><button id="tabMultiKb" class="px-2.5 py-1 text-xs font-mono rounded bg-neutral-800 text-white font-medium transition-colors" type="button">Multi-KB (kb_options)</button> <button id="tabSingleKb" class="px-2.5 py-1 text-xs font-mono rounded text-neutral-400 hover:text-neutral-200 hover:bg-neutral-800/50 transition-colors" type="button">Single KB (kb_id)</button> <button id="tabHtmlScript" class="px-2.5 py-1 text-xs font-mono rounded text-neutral-400 hover:text-neutral-200 hover:bg-neutral-800/50 transition-colors" type="button">HTML Script Tag</button></div></div><div class="flex items-center gap-3"><span class="hidden sm:inline-flex items-center gap-1 text-[11px] font-mono text-emerald-400"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400"></span> Ready to deploy </span><button class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono text-neutral-300 hover:text-white bg-neutral-800 hover:bg-neutral-700 rounded border border-neutral-700 transition-colors" id="copyCodeBtn" type="button"><svg class="w-3.5 h-3.5 text-neutral-400" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><rect height="14" rx="2" ry="2" width="14" x="8" y="8"></rect><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"></path></svg> <span id="copyBtnLabel">Copy</span></button></div></div><div class="p-4 sm:p-5 overflow-x-auto text-[13px] font-mono leading-relaxed select-all"><pre class="text-neutral-300"><code id="codeSnippetPre"></code></pre></div><div class="px-4 py-2 bg-[#0E0E10] border-t border-neutral-800 text-[11px] font-mono text-neutral-500 flex justify-between"><span>Bundle cost: ~12.4 kB gzipped</span> <span>UTF-8 | LF</span></div></div><div class="bg-white rounded-xl border border-border shadow-card overflow-hidden" data-purpose="diagnostic-metrics"><div class="px-5 py-3 border-b border-border bg-neutral-50/50 flex items-center justify-between"><div class="flex items-center gap-2"><svg class="w-4 h-4 text-neutral-500" fill="none" stroke="currentColor" stroke-width="2" viewbox="0 0 24 24"><path d="M22 12h-4l-3 9L9 3l-3 9H2"></path></svg><h3 class="text-xs font-semibold tracking-wider uppercase text-neutral-800 font-mono">DOM State &amp; Diagnostic Metrics</h3></div><span class="text-[11px] font-mono text-neutral-400">MutationObserver active</span></div><div class="p-5 grid grid-cols-1 sm:grid-cols-3 gap-4"><div class="p-3.5 rounded-lg border border-neutral-200/90 bg-neutral-50/40"><div class="text-[11px] font-mono uppercase text-neutral-500 font-medium">Launcher Element</div><div class="text-sm font-semibold font-mono text-neutral-900 mt-1 flex items-center gap-1.5" id="metricLauncher"><span class="w-2 h-2 rounded-full bg-emerald-500"></span> Visible (56px FAB)</div><span class="text-[10px] text-neutral-400 block mt-0.5">Fixed z-index: 99998</span></div><div class="p-3.5 rounded-lg border border-neutral-200/90 bg-neutral-50/40"><div class="text-[11px] font-mono uppercase text-neutral-500 font-medium">Chatbox Display</div><div class="text-sm font-semibold font-mono text-neutral-900 mt-1" id="metricChatbox">none (Collapsed)</div><span class="text-[10px] text-neutral-400 block mt-0.5">Hydrated &amp; Collapsed</span></div><div class="p-3.5 rounded-lg border border-neutral-200/90 bg-neutral-50/40"><div class="text-[11px] font-mono uppercase text-neutral-500 font-medium">Token Inheritance</div><div class="text-sm font-semibold font-mono text-neutral-900 mt-1 flex items-center gap-1.5" id="metricToken"><span class="w-3 h-3 rounded bg-[#007A78]" id="metricColorDot"></span> <span id="metricTokenHex">#007A78</span></div><span class="text-[10px] text-neutral-400 block mt-0.5">Applied via --akvo-primary</span></div></div><div class="px-5 py-3 border-t border-neutral-100 bg-neutral-50/20 text-xs text-neutral-500 flex items-center justify-between"><span class="font-mono text-[11px] flex items-center gap-1.5"><span class="text-neutral-400">Recent Event:</span> <span id="recentEventText" class="text-neutral-700 bg-neutral-100 px-1.5 py-0.5 rounded font-mono">chat:ready (t+0ms)</span> </span><span class="text-[11px] font-mono text-teal-700">Live Client Connected</span></div></div></section></div></main><script data-purpose="workbench-interactivity">document.addEventListener('DOMContentLoaded', () => {
56
56
  // Configuration State
57
57
  const config = {
58
58
  wsURL: "wss://akvo-rag.akvotest.org/ws/chat",
@@ -65,6 +65,11 @@
65
65
  position: "bottom-right",
66
66
  borderRadius: "8px",
67
67
  launcherSize: "56px",
68
+ draggable: true,
69
+ persistPosition: true,
70
+ persistHistory: true,
71
+ showCitations: true,
72
+ userId: "",
68
73
  launcherIconType: "bubble",
69
74
  headerIconType: "none",
70
75
  kbMode: "multi", // "multi" or "single"
@@ -118,6 +123,12 @@
118
123
  const selectWidth = document.getElementById('selectWidth');
119
124
  const selectHeight = document.getElementById('selectHeight');
120
125
  const selectRadius = document.getElementById('selectRadius');
126
+ const checkDraggable = document.getElementById('checkDraggable');
127
+ const checkPersist = document.getElementById('checkPersist');
128
+ const checkPersistHistory = document.getElementById('checkPersistHistory');
129
+ const inputUserId = document.getElementById('inputUserId');
130
+ const checkShowCitations = document.getElementById('checkShowCitations');
131
+ const btnClearHistory = document.getElementById('btnClearHistory');
121
132
 
122
133
  const btnKbModeSingle = document.getElementById('btnKbModeSingle');
123
134
  const btnKbModeMulti = document.getElementById('btnKbModeMulti');
@@ -158,10 +169,18 @@
158
169
  position: config.position,
159
170
  borderRadius: config.borderRadius,
160
171
  launcherSize: config.launcherSize,
172
+ draggable: config.draggable,
173
+ persistPosition: config.persistPosition,
174
+ persistHistory: config.persistHistory,
175
+ showCitations: config.showCitations,
161
176
  launcherIcon: ICONS.launcher[config.launcherIconType] || null,
162
177
  headerIcon: ICONS.header[config.headerIconType] || null
163
178
  };
164
179
 
180
+ if (config.userId) {
181
+ opts.userId = config.userId;
182
+ }
183
+
165
184
  if (config.kbMode === "single") {
166
185
  opts.kb_id = config.kb_id;
167
186
  } else {
@@ -199,6 +218,10 @@
199
218
  <span class="tok-prop">position</span>: <span class="tok-str">"${opts.position}"</span>,
200
219
  <span class="tok-prop">borderRadius</span>: <span class="tok-str">"${opts.borderRadius}"</span>,
201
220
  <span class="tok-prop">launcherSize</span>: <span class="tok-str">"${opts.launcherSize}"</span>,
221
+ <span class="tok-prop">draggable</span>: <span class="tok-bool">${opts.draggable}</span>,
222
+ <span class="tok-prop">persistPosition</span>: <span class="tok-bool">${opts.persistPosition}</span>,
223
+ <span class="tok-prop">persistHistory</span>: <span class="tok-bool">${opts.persistHistory}</span>,
224
+ <span class="tok-prop">showCitations</span>: <span class="tok-bool">${opts.showCitations}</span>,${opts.userId ? `\n <span class="tok-prop">userId</span>: <span class="tok-str">"${opts.userId}"</span>,` : ''}
202
225
  <span class="tok-prop">launcherIcon</span>: <span class="tok-bool">${iconStr}</span>,
203
226
  <span class="tok-prop">headerIcon</span>: <span class="tok-bool">${headerIconStr}</span>
204
227
  });`;
@@ -218,6 +241,10 @@
218
241
  <span class="tok-prop">position</span>: <span class="tok-str">"${opts.position}"</span>,
219
242
  <span class="tok-prop">borderRadius</span>: <span class="tok-str">"${opts.borderRadius}"</span>,
220
243
  <span class="tok-prop">launcherSize</span>: <span class="tok-str">"${opts.launcherSize}"</span>,
244
+ <span class="tok-prop">draggable</span>: <span class="tok-bool">${opts.draggable}</span>,
245
+ <span class="tok-prop">persistPosition</span>: <span class="tok-bool">${opts.persistPosition}</span>,
246
+ <span class="tok-prop">persistHistory</span>: <span class="tok-bool">${opts.persistHistory}</span>,
247
+ <span class="tok-prop">showCitations</span>: <span class="tok-bool">${opts.showCitations}</span>,${opts.userId ? `\n <span class="tok-prop">userId</span>: <span class="tok-str">"${opts.userId}"</span>,` : ''}
221
248
  <span class="tok-prop">launcherIcon</span>: <span class="tok-bool">${iconStr}</span>,
222
249
  <span class="tok-prop">headerIcon</span>: <span class="tok-bool">${headerIconStr}</span>,
223
250
  <span class="tok-prop">kb_options</span>: [
@@ -242,7 +269,9 @@
242
269
  <span class="tok-prop">title</span>: <span class="tok-str">"${opts.title}"</span>,
243
270
  <span class="tok-prop">primaryColor</span>: <span class="tok-str">"${opts.primaryColor}"</span>,
244
271
  <span class="tok-prop">showLauncher</span>: <span class="tok-bool">${opts.showLauncher}</span>,
245
- <span class="tok-prop">startMinimized</span>: <span class="tok-bool">${opts.startMinimized}</span>
272
+ <span class="tok-prop">startMinimized</span>: <span class="tok-bool">${opts.startMinimized}</span>,
273
+ <span class="tok-prop">persistHistory</span>: <span class="tok-bool">${opts.persistHistory}</span>,
274
+ <span class="tok-prop">showCitations</span>: <span class="tok-bool">${opts.showCitations}</span>${opts.userId ? `,\n <span class="tok-prop">userId</span>: <span class="tok-str">"${opts.userId}"</span>` : ''}
246
275
  });
247
276
  });
248
277
  <span class="tok-tag">&lt;/script&gt;</span>`;
@@ -527,6 +556,55 @@
527
556
  });
528
557
  }
529
558
 
559
+ if (checkDraggable) {
560
+ checkDraggable.addEventListener('change', (e) => {
561
+ config.draggable = e.target.checked;
562
+ mount();
563
+ logEvent(`draggable:${config.draggable}`);
564
+ });
565
+ }
566
+
567
+ if (checkPersist) {
568
+ checkPersist.addEventListener('change', (e) => {
569
+ config.persistPosition = e.target.checked;
570
+ mount();
571
+ logEvent(`persist:${config.persistPosition}`);
572
+ });
573
+ }
574
+
575
+ if (checkPersistHistory) {
576
+ checkPersistHistory.addEventListener('change', (e) => {
577
+ config.persistHistory = e.target.checked;
578
+ mount();
579
+ logEvent(`persistHistory:${config.persistHistory}`);
580
+ });
581
+ }
582
+
583
+ if (inputUserId) {
584
+ inputUserId.addEventListener('change', (e) => {
585
+ config.userId = e.target.value.trim();
586
+ mount();
587
+ logEvent(`userId:${config.userId || "anon"}`);
588
+ });
589
+ }
590
+
591
+ if (checkShowCitations) {
592
+ checkShowCitations.addEventListener('change', (e) => {
593
+ config.showCitations = e.target.checked;
594
+ mount();
595
+ logEvent(`showCitations:${config.showCitations}`);
596
+ });
597
+ }
598
+
599
+ if (btnClearHistory) {
600
+ btnClearHistory.addEventListener('click', () => {
601
+ if (window.chatInstance && typeof window.chatInstance.clearHistory === 'function') {
602
+ window.chatInstance.clearHistory();
603
+ logEvent("history:cleared");
604
+ }
605
+ });
606
+ }
607
+
530
608
  // Knowledge Base Mode Listeners
531
609
  if (btnKbModeSingle && btnKbModeMulti) {
532
610
  btnKbModeSingle.addEventListener('click', () => {
@@ -688,6 +766,9 @@
688
766
  { "kb_id": 750, "label": "Critical Thinking" }
689
767
  ];
690
768
  config.activeTab = "multi";
769
+ config.persistHistory = true;
770
+ config.showCitations = true;
771
+ config.userId = "";
691
772
 
692
773
  if (inputWsUrl) inputWsUrl.value = config.wsURL;
693
774
  if (btnWsOnline) btnWsOnline.className = "px-2.5 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1.5 font-sans";
@@ -701,6 +782,9 @@
701
782
  if (selectWidth) selectWidth.value = "360px";
702
783
  if (selectHeight) selectHeight.value = "500px";
703
784
  if (selectRadius) selectRadius.value = "8px";
785
+ if (checkPersistHistory) checkPersistHistory.checked = true;
786
+ if (checkShowCitations) checkShowCitations.checked = true;
787
+ if (inputUserId) inputUserId.value = "";
704
788
  if (btnPosRight) btnPosRight.className = 'px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1';
705
789
  if (btnPosLeft) btnPosLeft.className = 'px-3 py-1.5 text-xs font-medium rounded-md text-neutral-600 hover:text-neutral-900 transition-all flex items-center justify-center gap-1';
706
790
  btnDisplayFab.className = 'px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-xs bg-white text-neutral-900 border border-black/5 flex items-center justify-center gap-1.5';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akvo-rag-js",
3
- "version": "1.3.1",
3
+ "version": "1.5.0",
4
4
  "description": "An embeddable chatbot widget for Akvo RAG.",
5
5
  "main": "dist/akvo-rag.js",
6
6
  "files": [