@cloudflare/ai-search-snippet 0.0.37 → 0.0.39

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.
@@ -1,9 +1,29 @@
1
- (function(p,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p.SearchSnippet={}))})(this,(function(p){"use strict";var re=Object.defineProperty;var ae=(p,h,w)=>h in p?re(p,h,{enumerable:!0,configurable:!0,writable:!0,value:w}):p[h]=w;var a=(p,h,w)=>ae(p,typeof h!="symbol"?h+"":h,w);const h=["Searching...","Digging through results...","Scanning the knowledge base...","Finding the best matches...","Sifting through the data...","Almost there...","Looking far and wide...","Connecting the dots...","Rummaging through pages...","Hunting down answers..."];function I(n,i){let e;function t(...s){clearTimeout(e),e=setTimeout(()=>{n(...s)},i)}return t.cancel=()=>clearTimeout(e),t}function d(n){const i=document.createElement("div");return i.textContent=n,i.innerHTML}function z(n){try{return decodeURI(n)}catch{return n}}function A(n){return new DOMParser().parseFromString(n,"text/html").documentElement.textContent||""}function K(n){const i=new Date(n),t=new Date().getTime()-i.getTime();if(t<6e4)return"Just now";if(t<36e5){const s=Math.floor(t/6e4);return`${s} ${s===1?"minute":"minutes"} ago`}if(t<864e5){const s=Math.floor(t/36e5);return`${s} ${s===1?"hour":"hours"} ago`}return i.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function T(n){return new Date(n).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function $(n="id"){return`${n}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function u(n,i){return n!==null?n:i}function v(n,i){return n===null?i:n==="true"||n===""}function k(n,i){if(n===null)return i;const e=Number.parseInt(n,10);return Number.isNaN(e)?i:e}function b(n,i){return new CustomEvent(n,{detail:i,bubbles:!0,composed:!0,cancelable:!0})}function C(n){if(!n)throw new Error("API URL is required");return new R(n)}function y(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function q(...n){const i={};for(const e of n)if(e)for(const[t,s]of Object.entries(e)){const r=i[t];y(r)&&y(s)?i[t]=q(r,s):i[t]=s}return i}function G(n,i){if(!y(i))return n;const e=new URLSearchParams;for(const[l,g]of Object.entries(i))g!=null&&e.append(l,String(g));const t=e.toString();if(!t)return n;const s=n.indexOf("#"),r=s===-1?n:n.slice(0,s),o=s===-1?"":n.slice(s),c=r.includes("?")?"&":"?";return`${r}${c}${t}${o}`}function F(n){if(!y(n))return{};const i={};for(const[e,t]of Object.entries(n))t!=null&&(i[e]=String(t));return i}function Y(n){return y(n)?n:void 0}class R{constructor(i){a(this,"activeRequests",new Map);a(this,"baseUrl");this.baseUrl=i.replace(/\/$/,"")}request(i,e,t,s){const r=e==="search"?"snippet-search":"snippet-chat-completions",o=G(`${this.baseUrl}/${e}`,s?.queryParams);return fetch(o,{method:"POST",body:JSON.stringify(q(Y(s?.body),i)),headers:{...F(s?.headers),"Content-Type":"application/json",Accept:i.stream?"text/event-stream":"application/json","cf-ai-search-source":r},signal:t})}async search(i,e={}){const t=this.generateRequestId(),s=new AbortController,r=e.signal||s.signal;this.registerRequest(t,s);try{const o=await this.request({messages:[{role:"user",content:i}],stream:!1,ai_search_options:{retrieval:{metadata_only:!0,max_num_results:e.maxResults??30}}},"search",r,e.request);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);if(!o.body)throw new Error("Response body is empty");const c=await o.json();if(c.success&&c.result)return c.result.chunks.map(l=>({type:"result",id:l.id,title:A(l.item.metadata?.title),description:l.item.metadata?.description?A(l.item.metadata?.description):"",timestamp:l.item.timestamp??void 0,url:l.item.key,image:l.item.metadata?.image||void 0,metadata:{...l.item.metadata,instance_id:l.instance_id}}));throw c.success===!1?new Error(c.error):new Error("Unknown error")}finally{this.unregisterRequest(t)}}async*searchStream(i,e={}){const t=this.generateRequestId(),s=new AbortController,r=e.signal||s.signal;this.registerRequest(t,s);const o=await this.request({messages:[{role:"user",content:i}],stream:!0,...e.maxResults!==void 0&&{max_num_results:e.maxResults}},"ai-search",r,e.request);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);if(!o.body)throw new Error("Response body is empty");let c="";const l=o.body.getReader(),g=new TextDecoder;for(;;){const{done:m,value:L}=await l.read();if(m)break;const ie=g.decode(L,{stream:!0});c+=ie}yield{type:"result",id:"",title:"",description:c.replaceAll("data: ","").trim().split(`
1
+ (function(g,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(g=typeof globalThis<"u"?globalThis:g||self,v(g.SearchSnippet={}))})(this,(function(g){"use strict";var be=Object.defineProperty;var ye=(g,v,u)=>v in g?be(g,v,{enumerable:!0,configurable:!0,writable:!0,value:u}):g[v]=u;var a=(g,v,u)=>ye(g,typeof v!="symbol"?v+"":v,u);const v={loadingAriaLabel:"Loading",errorPrefix:"Error:",missingApiUrlError:"The api-url attribute is required. Please provide a valid API URL.",poweredBy:"Powered by",poweredByLinkLabel:"Cloudflare AI Search",placeholder:"Search...",searchButtonLabel:"Search",searchInputAriaLabel:"Search input",searchResultsAriaLabel:"Search results",emptyStateTitle:"Start Searching",emptyStateDescription:"Enter a query to search for results",modalEmptyStateDescription:"Start typing to search",noResultsTitle:"No Results Found",noResultsDescription:'No results found for "{query}"',modalNoResultsTitle:"No results found",modalNoResultsDescription:'No results for "{query}"',resultsCount:"Found {n} result",resultsCountPlural:"Found {n} results",resultsCountOverflow:"Showing {n} of {total} results",modalResultsCount:"{n} result",modalResultsCountPlural:"{n} results",modalResultsCountZero:"0 results",modalResultsCountError:"Error",seeMoreResults:"See more results",navigateHint:"Navigate",selectHint:"Select",closeHint:"Close",chatTitle:"Chat",chatPlaceholder:"Type a message...",chatInputAriaLabel:"Chat message input",sendButtonLabel:"Send",sendButtonAriaLabel:"Send message",chatEmptyTitle:"Start a Conversation",chatEmptyDescription:"Send a message to begin chatting",userAvatar:"U",assistantAvatar:"AI",unknownError:"Unknown error",openChatAriaLabel:"Open chat",clearHistoryAriaLabel:"Clear history",minimizeAriaLabel:"Minimize",closeAriaLabel:"Close",historyTitle:"History",newChatButton:"New Chat",clearChatButton:"Clear Chat",toggleSidebarTitle:"Toggle sidebar",deleteChatTitle:"Delete chat",noChatsYet:"No chats yet",yesterday:"Yesterday",justNow:"Just now",minuteAgo:"{n} minute ago",minutesAgo:"{n} minutes ago",hourAgo:"{n} hour ago",hoursAgo:"{n} hours ago",loadingMessages:["Searching...","Digging through results...","Scanning the knowledge base...","Finding the best matches...","Sifting through the data...","Almost there...","Looking far and wide...","Connecting the dots...","Rummaging through pages...","Hunting down answers..."]};function u(l){if(!l||typeof l!="object")return v;const i={...v};for(const e of Object.keys(l)){const t=l[e];if(t!=null){if(e==="loadingMessages"){Array.isArray(t)&&t.length>0&&(i.loadingMessages=t.filter(s=>typeof s=="string"),i.loadingMessages.length===0&&(i.loadingMessages=v.loadingMessages));continue}typeof t=="string"&&(i[e]=t)}}return i}function x(l,i={}){return l.replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(i,t)?String(i[t]):e)}function E(l,i){if(!l)return null;try{const e=JSON.parse(l);if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("translations must be a JSON object");return e}catch(e){return console.error(`${i}: invalid translations attribute`,e),null}}const A=2500;function $(l,i){let e;function t(...s){clearTimeout(e),e=setTimeout(()=>{l(...s)},i)}return t.cancel=()=>clearTimeout(e),t}function c(l){const i=document.createElement("div");return i.textContent=l,i.innerHTML}function q(l){try{return decodeURI(l)}catch{return l}}function B(l){return new DOMParser().parseFromString(l,"text/html").documentElement.textContent||""}function se(l,i){const e=u(i),t=new Date(l),r=new Date().getTime()-t.getTime();if(r<6e4)return e.justNow;if(r<36e5){const n=Math.floor(r/6e4),o=n===1?e.minuteAgo:e.minutesAgo;return x(o,{n})}if(r<864e5){const n=Math.floor(r/36e5),o=n===1?e.hourAgo:e.hoursAgo;return x(o,{n})}return t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function O(l){return new Date(l).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function H(l="id"){return`${l}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function f(l,i){return l!==null?l:i}function b(l,i){return l===null?i:l==="true"||l===""}function C(l,i){if(l===null)return i;const e=Number.parseInt(l,10);return Number.isNaN(e)?i:e}function N(l,i){if(!(l===null||l===""))try{const e=JSON.parse(l);if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("chat-query-rewrite must be a JSON object");const t=e,s={};return typeof t.enabled=="boolean"&&(s.enabled=t.enabled),typeof t.model=="string"&&(s.model=t.model),typeof t.rewritePrompt=="string"&&(s.rewritePrompt=t.rewritePrompt),s}catch(e){console.error(`${i}: invalid chat-query-rewrite attribute`,e);return}}function w(l,i){return new CustomEvent(l,{detail:i,bubbles:!0,composed:!0,cancelable:!0})}function M(l){if(!l)throw new Error("API URL is required");return new P(l)}const ie="@cf/meta/llama-3.3-70b-instruct-fp8-fast",re=`You rewrite a multi-turn chat into a single standalone search query for a retrieval system.
2
2
 
3
- `).map(m=>JSON.parse(m)).map(m=>m.response).join(""),url:"",metadata:{}}}async*chat(i,e){const t=new AbortController,s=e?.signal||t.signal,r=await this.request({messages:[{role:"user",content:i}],stream:!1},"chat/completions",s);if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);if(!r.body)throw new Error("Response body is empty");yield{type:"text",message:(await r.json()).choices.map(c=>c.message.content).join("")}}cancelRequest(i){const e=this.activeRequests.get(i);e&&(e.controller.abort(),this.unregisterRequest(i))}cancelAllRequests(){for(const[i]of this.activeRequests)this.cancelRequest(i)}registerRequest(i,e){this.activeRequests.set(i,{id:i,controller:e,timestamp:Date.now()})}unregisterRequest(i){this.activeRequests.delete(i)}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}const S=`Powered by <a href="https://workers.cloudflare.com/product/ai-search" target="_blank" rel="noopener noreferrer">Cloudflare AI Search <svg width="32" height="10" viewBox="0 0 412 186" xmlns="http://www.w3.org/2000/svg" aria-label="Cloudflare" role="img">
3
+ Inputs: the full conversation in \`messages\`. The final user message is the one to answer; earlier messages are context only.
4
+
5
+ Rules:
6
+ - Output ONLY the rewritten query as plain text. No preamble, no quotes, no markdown, no explanation.
7
+ - Resolve pronouns and references (it, that, they, the second one, the previous one, etc.) using prior turns.
8
+ - Inline any entities, names, versions, products, or constraints from earlier turns that the final message depends on.
9
+ - Preserve the user's original language and terminology. Do not translate.
10
+ - Do not invent facts, sources, dates, or details not present in the conversation.
11
+ - If the final user message is already fully self-contained, return it unchanged (modulo trivial cleanup).
12
+ - Drop greetings, thanks, and meta questions about the assistant itself; keep only the information need.
13
+ - Keep it concise — a search query, not a sentence. Aim for under 200 characters when possible.
14
+
15
+ Return only the rewritten query.`;function ae(l){let i="message";const e=[];for(const t of l.split(`
16
+ `)){const s=t.endsWith("\r")?t.slice(0,-1):t;if(s===""||s.startsWith(":"))continue;const r=s.indexOf(":"),n=r===-1?s:s.slice(0,r);let o=r===-1?"":s.slice(r+1);o.startsWith(" ")&&(o=o.slice(1)),n==="event"?i=o:n==="data"&&e.push(o)}return e.length===0?null:{event:i,data:e.join(`
17
+ `)}}function k(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)}function D(...l){const i={};for(const e of l)if(e)for(const[t,s]of Object.entries(e)){const r=i[t];k(r)&&k(s)?i[t]=D(r,s):i[t]=s}return i}function ne(l,i){if(!k(i))return l;const e=new URLSearchParams;for(const[h,d]of Object.entries(i))d!=null&&e.append(h,String(d));const t=e.toString();if(!t)return l;const s=l.indexOf("#"),r=s===-1?l:l.slice(0,s),n=s===-1?"":l.slice(s),o=r.includes("?")?"&":"?";return`${r}${o}${t}${n}`}function oe(l){if(!k(l))return{};const i={};for(const[e,t]of Object.entries(l))t!=null&&(i[e]=String(t));return i}function le(l){return k(l)?l:void 0}class P{constructor(i){a(this,"activeRequests",new Map);a(this,"baseUrl");this.baseUrl=i.replace(/\/$/,"")}request(i,e,t,s){const r=e==="search"?"snippet-search":"snippet-chat-completions",n=ne(`${this.baseUrl}/${e}`,s?.queryParams);return fetch(n,{method:"POST",body:JSON.stringify(D(le(s?.body),i)),headers:{...oe(s?.headers),"Content-Type":"application/json",Accept:i.stream?"text/event-stream":"application/json","cf-ai-search-source":r},signal:t})}async search(i,e={}){const t=this.generateRequestId(),s=new AbortController,r=e.signal||s.signal;this.registerRequest(t,s);try{const n=await this.request({messages:[{role:"user",content:i}],stream:!1,ai_search_options:{retrieval:{metadata_only:!0,max_num_results:e.maxResults??30}}},"search",r,e.request);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");const o=await n.json();if(o.success&&o.result)return o.result.chunks.map(h=>({type:"result",id:h.id,title:B(h.item.metadata?.title),description:h.item.metadata?.description?B(h.item.metadata?.description):"",timestamp:h.item.timestamp??void 0,url:h.item.key,image:h.item.metadata?.image||void 0,metadata:{...h.item.metadata,instance_id:h.instance_id}}));throw o.success===!1?new Error(o.error):new Error("Unknown error")}finally{this.unregisterRequest(t)}}async*searchStream(i,e={}){const t=this.generateRequestId(),s=new AbortController,r=e.signal||s.signal;this.registerRequest(t,s);const n=await this.request({messages:[{role:"user",content:i}],stream:!0,...e.maxResults!==void 0&&{max_num_results:e.maxResults}},"ai-search",r,e.request);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");let o="";const h=n.body.getReader(),d=new TextDecoder;for(;;){const{done:m,value:y}=await h.read();if(m)break;const z=d.decode(y,{stream:!0});o+=z}yield{type:"result",id:"",title:"",description:o.replaceAll("data: ","").trim().split(`
18
+
19
+ `).map(m=>JSON.parse(m)).map(m=>m.response).join(""),url:"",metadata:{}}}async*chat(i,e){const t=new AbortController,s=e?.signal||t.signal,r=e?.stream??!0,o={messages:[...e?.history??[],{role:"user",content:i}],stream:r};if(e?.queryRewrite){const d=typeof e.queryRewrite=="object"?e.queryRewrite:{};o.ai_search_options={query_rewrite:{enabled:!0,model:d.model??ie,rewrite_prompt:d.rewritePrompt??re}}}const h=await this.request(o,"chat/completions",s);if(!h.ok)throw new Error(`HTTP error! status: ${h.status}`);if(!h.body)throw new Error("Response body is empty");if(!r){yield{type:"text",message:(await h.json()).choices.map(p=>p.message.content).join("")};return}yield*this.parseChatStream(h.body)}async*parseChatStream(i){const e=i.getReader(),t=new TextDecoder;let s="";const r=n=>{const o=ae(n);if(!o||o.event==="chunks")return null;if(o.data==="[DONE]")return"done";try{const d=JSON.parse(o.data).choices?.[0]?.delta?.content;if(typeof d=="string"&&d.length>0)return{type:"text",message:d}}catch(h){console.error("AISearchClient: failed to parse SSE chat chunk",h)}return null};try{for(;;){const{done:n,value:o}=await e.read();if(n)break;s+=t.decode(o,{stream:!0});let h=s.indexOf(`
20
+
21
+ `);for(;h!==-1;){const d=s.slice(0,h);s=s.slice(h+2);const p=r(d);if(p==="done")return;p&&(yield p),h=s.indexOf(`
22
+
23
+ `)}}if(s+=t.decode(),s.trim().length>0){const n=r(s);n&&n!=="done"&&(yield n)}}catch(n){if(n.name==="AbortError")return;throw n}finally{e.releaseLock()}}cancelRequest(i){const e=this.activeRequests.get(i);e&&(e.controller.abort(),this.unregisterRequest(i))}cancelAllRequests(){for(const[i]of this.activeRequests)this.cancelRequest(i)}registerRequest(i,e){this.activeRequests.set(i,{id:i,controller:e,timestamp:Date.now()})}unregisterRequest(i){this.activeRequests.delete(i)}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}const ce="0.0.39",L=`Powered by <a href="https://workers.cloudflare.com/product/ai-search" target="_blank" rel="noopener noreferrer">Cloudflare AI Search <svg width="32" height="10" viewBox="0 0 412 186" xmlns="http://www.w3.org/2000/svg" aria-label="Cloudflare" role="img">
4
24
  <path fill="#f38020" d="m280.8395,183.31456c11,-26 -4,-38 -19,-38l-148,-2c-4,0 -4,-6 1,-7l150,-2c17,-1 37,-15 43,-33c0,0 10,-21 9,-24a97,97 0 0 0 -187,-11c-38,-25 -78,9 -69,46c-48,3 -65,46 -60,72c0,1 1,2 3,2l274,0c1,0 3,-1 3,-3z"/>
5
25
  <path fill="#faae40" d="m330.8395,81.31456c-4,0 -6,-1 -7,1l-5,21c-5,16 3,30 20,31l32,2c4,0 4,6 -1,7l-33,1c-36,4 -46,39 -46,39c0,2 0,3 2,3l113,0l3,-2a81,81 0 0 0 -78,-103"/>
6
- </svg></a>`,B=`
26
+ </svg></a>`,he=2e4,de=20,pe="/stats";function U(){return typeof document<"u"&&typeof window<"u"}class I{constructor(i,e={}){a(this,"baseUrl");a(this,"endpoint");a(this,"snippetVersion");a(this,"flushIntervalMs");a(this,"maxBufferSize");a(this,"buffer",[]);a(this,"flushTimer",null);a(this,"destroyed",!1);a(this,"boundUnloadHandler");a(this,"boundVisibilityHandler");this.baseUrl=i.replace(/\/$/,""),this.endpoint=e.endpoint??pe,this.snippetVersion=e.snippetVersion??ce,this.flushIntervalMs=e.flushIntervalMs??he,this.maxBufferSize=Math.max(1,e.maxBufferSize??de),this.boundUnloadHandler=()=>this.flushBeacon(),this.boundVisibilityHandler=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&this.flushBeacon()},U()&&(window.addEventListener("pagehide",this.boundUnloadHandler),document.addEventListener("visibilitychange",this.boundVisibilityHandler))}trackSearch(i,e){this.track({inputQuery:i,snippetVersion:this.snippetVersion,totalResult:e})}trackClick(i,e,t,s){this.track({inputQuery:i,snippetVersion:this.snippetVersion,totalResult:e,clickedResultId:t,clickPosition:s,clickViewMore:!1})}trackViewMore(i,e){this.track({inputQuery:i,snippetVersion:this.snippetVersion,totalResult:e,clickViewMore:!0})}track(i){if(!this.destroyed){if(this.buffer.push(i),this.buffer.length>=this.maxBufferSize){this.flush();return}this.scheduleFlush()}}flush(){const i=this.drainBuffer();if(i.length===0)return;const e=JSON.stringify({events:i});fetch(this.buildUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}).catch(t=>{console.log(t)})}flushBeacon(){const i=this.drainBuffer();if(i.length===0)return;const e=JSON.stringify({events:i}),t=this.buildUrl();if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{const s=new Blob([e],{type:"application/json"});if(navigator.sendBeacon(t,s))return}catch{}typeof fetch<"u"&&fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}).catch(()=>{})}destroy(){this.destroyed||(this.destroyed=!0,this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),U()&&(window.removeEventListener("pagehide",this.boundUnloadHandler),document.removeEventListener("visibilitychange",this.boundVisibilityHandler)),this.flushBeacon())}scheduleFlush(){this.flushTimer!==null||this.destroyed||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},this.flushIntervalMs))}drainBuffer(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.buffer.length===0)return[];const i=this.buffer;return this.buffer=[],i}buildUrl(){const i=this.endpoint.startsWith("/")?this.endpoint:`/${this.endpoint}`;return`${this.baseUrl}${i}`}}const _=`
7
27
  /* Chat container */
8
28
  .chat-container {
9
29
  display: flex;
@@ -46,6 +66,7 @@
46
66
  gap: var(--search-snippet-spacing-sm);
47
67
  max-width: 85%;
48
68
  animation: slideIn var(--search-snippet-animation-duration) ease-out;
69
+ animation-fill-mode: both;
49
70
  }
50
71
 
51
72
  @keyframes slideIn {
@@ -116,6 +137,9 @@
116
137
  border-radius: var(--search-snippet-border-radius);
117
138
  word-wrap: break-word;
118
139
  overflow-wrap: break-word;
140
+ /* Isolate layout cost of bubble height changes during streaming so
141
+ siblings don't reflow. */
142
+ contain: layout style;
119
143
  }
120
144
 
121
145
  .chat-message-user .chat-message-bubble {
@@ -320,7 +344,7 @@
320
344
  .chat-message-bubble a:hover {
321
345
  text-decoration: none;
322
346
  }
323
- `,E=`
347
+ `,T=`
324
348
  :host {
325
349
  /* Colors - Light Mode */
326
350
  --search-snippet-primary-color: #2563eb;
@@ -754,61 +778,53 @@
754
778
  padding: var(--search-snippet-spacing-xs) 0;
755
779
  text-align: center;
756
780
  }
757
- `;function J(n){let i=n;i=W(i),i=i.replace(/```([\s\S]*?)```/g,(o,c)=>`<pre><code>${c.trim()}</code></pre>`);const e=i.split(`
758
- `),t=[];let s=!1,r="";for(let o=0;o<e.length;o++){const c=e[o],l=c.match(/^(#{1,6})\s+(.+)$/);if(l){const m=l[1].length,L=l[2];t.push(`<h${m}>${x(L)}</h${m}>`);continue}if(c.match(/^---+$/)){t.push("<hr />");continue}if(c.match(/^>\s+/)){const m=c.replace(/^>\s+/,"");t.push(`<blockquote>${x(m)}</blockquote>`);continue}const g=c.match(/^[-*]\s+(.+)$/);if(g){(!s||r!=="ul")&&(s&&t.push(`</${r}>`),t.push("<ul>"),s=!0,r="ul"),t.push(`<li>${x(g[1])}</li>`);continue}const f=c.match(/^\d+\.\s+(.+)$/);if(f){(!s||r!=="ol")&&(s&&t.push(`</${r}>`),t.push("<ol>"),s=!0,r="ol"),t.push(`<li>${x(f[1])}</li>`);continue}if(s&&(t.push(`</${r}>`),s=!1,r=""),c.trim()===""){t.push("<br />");continue}t.push(`<p>${x(c)}</p>`)}return s&&t.push(`</${r}>`),t.join(`
759
- `)}function x(n){let i=n;return i=i.replace(/`([^`]+)`/g,"<code>$1</code>"),i=i.replace(/\*\*\*(.+?)\*\*\*/g,"<strong><em>$1</em></strong>"),i=i.replace(/___(.+?)___/g,"<strong><em>$1</em></strong>"),i=i.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),i=i.replace(/__(.+?)__/g,"<strong>$1</strong>"),i=i.replace(/\*(.+?)\*/g,"<em>$1</em>"),i=i.replace(/_(.+?)_/g,"<em>$1</em>"),i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),i}function W(n){const i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return n.replace(/[&<>"']/g,e=>i[e]||e)}class H{constructor(i,e,t){a(this,"container");a(this,"client");a(this,"props");a(this,"inputElement",null);a(this,"messagesContainer",null);a(this,"sendButton",null);a(this,"messages",[]);a(this,"isStreaming",!1);a(this,"currentStreamingMessageId",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleInputResize",null);a(this,"handleInputKeydown",null);a(this,"handleSendClick",null);this.container=i,this.client=e,this.props=t,this.render(),this.attachEventListeners()}render(){this.container.innerHTML=`
781
+ `;function ue(l){let i=l;i=ge(i),i=i.replace(/```([\s\S]*?)```/g,(n,o)=>`<pre><code>${o.trim()}</code></pre>`);const e=i.split(`
782
+ `),t=[];let s=!1,r="";for(let n=0;n<e.length;n++){const o=e[n],h=o.match(/^(#{1,6})\s+(.+)$/);if(h){const m=h[1].length,y=h[2];t.push(`<h${m}>${S(y)}</h${m}>`);continue}if(o.match(/^---+$/)){t.push("<hr />");continue}if(o.match(/^>\s+/)){const m=o.replace(/^>\s+/,"");t.push(`<blockquote>${S(m)}</blockquote>`);continue}const d=o.match(/^[-*]\s+(.+)$/);if(d){(!s||r!=="ul")&&(s&&t.push(`</${r}>`),t.push("<ul>"),s=!0,r="ul"),t.push(`<li>${S(d[1])}</li>`);continue}const p=o.match(/^\d+\.\s+(.+)$/);if(p){(!s||r!=="ol")&&(s&&t.push(`</${r}>`),t.push("<ol>"),s=!0,r="ol"),t.push(`<li>${S(p[1])}</li>`);continue}if(s&&(t.push(`</${r}>`),s=!1,r=""),o.trim()===""){t.push("<br />");continue}t.push(`<p>${S(o)}</p>`)}return s&&t.push(`</${r}>`),t.join(`
783
+ `)}function S(l){let i=l;return i=i.replace(/`([^`]+)`/g,"<code>$1</code>"),i=i.replace(/\*\*\*(.+?)\*\*\*/g,"<strong><em>$1</em></strong>"),i=i.replace(/___(.+?)___/g,"<strong><em>$1</em></strong>"),i=i.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),i=i.replace(/__(.+?)__/g,"<strong>$1</strong>"),i=i.replace(/\*(.+?)\*/g,"<em>$1</em>"),i=i.replace(/_(.+?)_/g,"<em>$1</em>"),i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),i}function ge(l){const i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return l.replace(/[&<>"']/g,e=>i[e]||e)}const me=64;class V{constructor(i,e,t){a(this,"container");a(this,"client");a(this,"props");a(this,"translations");a(this,"inputElement",null);a(this,"messagesContainer",null);a(this,"sendButton",null);a(this,"messages",[]);a(this,"isStreaming",!1);a(this,"currentStreamingMessageId",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"pendingScrollFrame",null);a(this,"handleInputResize",null);a(this,"handleInputKeydown",null);a(this,"handleSendClick",null);this.container=i,this.client=e,this.props=t,this.translations=u(t.translations),this.render(),this.attachEventListeners()}render(){const i=this.translations;this.container.innerHTML=`
760
784
  <div class="chat-container">
761
785
  <div class="chat-messages">
762
- <div class="chat-empty">
763
- <svg class="chat-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
764
- <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
765
- </svg>
766
- <div class="chat-empty-title">Start a Conversation</div>
767
- <div class="chat-empty-description">
768
- Send a message to begin chatting
769
- </div>
770
- </div>
786
+ ${this.renderEmptyStateHTML()}
771
787
  </div>
772
788
  <div class="chat-input-area">
773
789
  <div class="chat-input-wrapper">
774
790
  <textarea
775
791
  class="chat-input"
776
- placeholder="${d(this.props.placeholder||"Type a message...")}"
777
- aria-label="Chat message input"
792
+ placeholder="${c(this.props.placeholder||i.chatPlaceholder)}"
793
+ aria-label="${c(i.chatInputAriaLabel)}"
778
794
  style="height: 40px;"
779
795
  rows="1"
780
796
  ></textarea>
781
- <button class="button chat-send-button" aria-label="Send message">
782
- <span>Send</span>
797
+ <button class="button chat-send-button" aria-label="${c(i.sendButtonAriaLabel)}">
798
+ <span>${c(i.sendButtonLabel)}</span>
783
799
  </button>
784
800
  </div>
785
801
  </div>
786
802
  </div>
787
- `,this.messagesContainer=this.container.querySelector(".chat-messages"),this.inputElement=this.container.querySelector(".chat-input"),this.sendButton=this.container.querySelector(".chat-send-button")}attachEventListeners(){!this.inputElement||!this.sendButton||(this.handleInputResize=i=>{const e=i.target;e.style.height="auto",e.style.height=`${e.scrollHeight}px`},this.inputElement.addEventListener("input",this.handleInputResize),this.handleInputKeydown=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.handleSendMessage())},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleSendClick=()=>{this.handleSendMessage()},this.sendButton.addEventListener("click",this.handleSendClick))}async handleSendMessage(){if(!this.inputElement||this.isStreaming)return;const i=this.inputElement.value.trim();i.length!==0&&(this.inputElement.value="",this.inputElement.style.height="auto",await this.sendMessage(i))}async sendMessage(i){const e={id:$("msg"),role:"user",content:i,timestamp:Date.now()};this.addMessage(e),this.renderMessages(!0),this.setStreamingState(!0);const t=$("msg"),s={id:t,role:"assistant",content:"",timestamp:Date.now()};this.addMessage(s),this.currentStreamingMessageId=t,this.renderMessages(!0);try{const r=this.client.chat(i);let o="";for await(const l of r)if(l.type==="text"&&l.message)o+=l.message,this.updateStreamingMessage(t,o);else if(l.type==="error"){this.showErrorInMessage(t,l.message||"Unknown error");break}const c=this.messages.findIndex(l=>l.id===t);c!==-1&&(this.messages[c].content=o),this.container.dispatchEvent(b("message",{message:s}))}catch(r){this.showErrorInMessage(t,r.message),this.container.dispatchEvent(b("error",{error:{message:r.message,code:"CHAT_ERROR"}}))}finally{this.setStreamingState(!1),this.renderMessages(),this.currentStreamingMessageId=null}}addMessage(i){this.messages.push(i),this.renderMessages()}updateStreamingMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=e,this.renderMessages(!0))}showErrorInMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=`Error: ${e}`,this.renderMessages())}renderMessages(i=!1){if(!this.messagesContainer)return;if(this.messages.length===0){this.messagesContainer.innerHTML=`
788
- <div class="chat-empty">
789
- <svg class="chat-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
790
- <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
791
- </svg>
792
- <div class="chat-empty-title">Start a Conversation</div>
793
- <div class="chat-empty-description">
794
- Send a message to begin chatting
795
- </div>
803
+ `,this.messagesContainer=this.container.querySelector(".chat-messages"),this.inputElement=this.container.querySelector(".chat-input"),this.sendButton=this.container.querySelector(".chat-send-button")}renderEmptyStateHTML(){const i=this.translations;return`
804
+ <div class="chat-empty">
805
+ <svg class="chat-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
806
+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
807
+ </svg>
808
+ <div class="chat-empty-title">${c(i.chatEmptyTitle)}</div>
809
+ <div class="chat-empty-description">
810
+ ${c(i.chatEmptyDescription)}
796
811
  </div>
797
- `;return}const e=this.messages.map(t=>this.renderMessage(t,i&&t.id===this.currentStreamingMessageId)).join("");this.messagesContainer.innerHTML=e,this.scrollToBottom()}renderMessage(i,e=!1){const t=`chat-message-${i.role}`,s=i.role==="user"?"U":"AI";return`
798
- <div class="chat-message ${t}">
799
- <div class="chat-message-avatar">${s}</div>
812
+ </div>
813
+ `}attachEventListeners(){!this.inputElement||!this.sendButton||(this.handleInputResize=i=>{const e=i.target;e.style.height="auto",e.style.height=`${e.scrollHeight}px`},this.inputElement.addEventListener("input",this.handleInputResize),this.handleInputKeydown=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.handleSendMessage())},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleSendClick=()=>{this.handleSendMessage()},this.sendButton.addEventListener("click",this.handleSendClick))}async handleSendMessage(){if(!this.inputElement||this.isStreaming)return;const i=this.inputElement.value.trim();i.length!==0&&(this.inputElement.value="",this.inputElement.style.height="auto",await this.sendMessage(i))}async sendMessage(i){const e=this.messages.map(o=>({role:o.role,content:o.content})),t=this.resolveQueryRewriteOption(e),s={id:H("msg"),role:"user",content:i,timestamp:Date.now()};this.addMessage(s),this.renderMessages(!0),this.setStreamingState(!0);const r=H("msg"),n={id:r,role:"assistant",content:"",timestamp:Date.now()};this.addMessage(n),this.currentStreamingMessageId=r,this.renderMessages(!0);try{const o=this.client.chat(i,{history:e,queryRewrite:t});let h="";for await(const p of o)if(p.type==="text"&&p.message)h+=p.message,this.updateStreamingMessage(r,h);else if(p.type==="error"){this.showErrorInMessage(r,p.message||this.translations.unknownError);break}const d=this.messages.findIndex(p=>p.id===r);d!==-1&&(this.messages[d].content=h),this.container.dispatchEvent(w("message",{message:n}))}catch(o){this.showErrorInMessage(r,o.message),this.container.dispatchEvent(w("error",{error:{message:o.message,code:"CHAT_ERROR"}}))}finally{this.setStreamingState(!1),this.renderMessages(),this.currentStreamingMessageId=null}}resolveQueryRewriteOption(i){const e=this.props.chatQueryRewrite;return e?.enabled===!1||i.length===0?!1:e&&(e.model!==void 0||e.rewritePrompt!==void 0)?{model:e.model,rewritePrompt:e.rewritePrompt}:!0}addMessage(i){this.messages.push(i),this.renderMessages()}updateStreamingMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=e,this.updateStreamingMessageDOM(i,e)||this.renderMessages(!0))}updateStreamingMessageDOM(i,e){if(!this.messagesContainer)return!1;const t=this.messagesContainer.querySelector(`[data-message-id="${CSS.escape(i)}"]`);if(!t)return!1;const s=t.querySelector(".chat-message-bubble");if(!s)return!1;const r=this.isNearBottom();let n=s.querySelector(".chat-message-text");if(!n){const o=document.createElement("div");o.className="chat-message-text";const h=s.querySelector(".chat-streaming");h?s.insertBefore(o,h):s.appendChild(o),n=o}return n.textContent=e,r&&this.scheduleScrollToBottom(),!0}showErrorInMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=`${this.translations.errorPrefix} ${e}`,this.renderMessages())}renderMessages(i=!1){if(!this.messagesContainer)return;if(this.messages.length===0){this.messagesContainer.innerHTML=this.renderEmptyStateHTML();return}const e=this.messages.map(t=>this.renderMessage(t,i&&t.id===this.currentStreamingMessageId)).join("");this.messagesContainer.innerHTML=e,this.scheduleScrollToBottom()}renderMessage(i,e=!1){const t=this.translations,s=`chat-message-${i.role}`,r=i.role==="user"?t.userAvatar:t.assistantAvatar,n=t.loadingMessages[this.loadingMessageIndex]??"",o=i.content?e?c(i.content):ue(i.content):"";return`
814
+ <div class="chat-message ${s}" data-message-id="${c(i.id)}">
815
+ <div class="chat-message-avatar">${c(r)}</div>
800
816
  <div class="chat-message-content">
801
817
  <div class="chat-message-bubble">
802
- ${i.content?`<div class="chat-message-text">${J(i.content)}</div>`:""}
803
- ${e?`<div class="chat-streaming"><span class="chat-streaming-dot"></span><span class="chat-streaming-dot"></span><span class="chat-streaming-dot"></span><span class="loading-text">${h[this.loadingMessageIndex]}</span></div>`:""}
818
+ ${o?`<div class="chat-message-text">${o}</div>`:""}
819
+ ${e?`<div class="chat-streaming"><span class="chat-streaming-dot"></span><span class="chat-streaming-dot"></span><span class="chat-streaming-dot"></span><span class="loading-text">${c(n)}</span></div>`:""}
804
820
  </div>
805
821
  <div class="chat-message-metadata">
806
- <span class="chat-message-time">${K(i.timestamp)}</span>
822
+ <span class="chat-message-time">${c(se(i.timestamp,this.translations))}</span>
807
823
  </div>
808
824
  </div>
809
825
  </div>
810
- `}scrollToBottom(){this.messagesContainer&&requestAnimationFrame(()=>{this.messagesContainer&&(this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight)})}setStreamingState(i){this.isStreaming=i,this.inputElement&&(this.inputElement.disabled=i),this.sendButton&&(this.sendButton.disabled=i,this.sendButton.innerHTML=i?'<div class="loading"></div>':"<span>Send</span>"),i?this.startLoadingMessages():this.clearLoadingMessages()}startLoadingMessages(){this.loadingMessageIndex=Math.floor(Math.random()*h.length),this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%h.length,this.isStreaming&&this.renderMessages(!0)},2500)}clearLoadingMessages(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}getMessages(){return[...this.messages]}clearMessages(){this.messages=[],this.renderMessages()}setMessages(i){this.messages=[...i],this.renderMessages()}destroy(){this.clearLoadingMessages(),this.isStreaming&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputResize&&this.inputElement.removeEventListener("input",this.handleInputResize),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.sendButton&&this.handleSendClick&&this.sendButton.removeEventListener("click",this.handleSendClick),this.handleInputResize=null,this.handleInputKeydown=null,this.handleSendClick=null}}const N="chat-bubble-snippet";class _ extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"isExpanded",!1);a(this,"isMinimized",!1);a(this,"handleBubbleClick",null);a(this,"handleCloseClick",null);a(this,"handleMinimizeClick",null);a(this,"handleClearClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.dispatchEvent(b("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Type a message..."),theme:u(this.getAttribute("theme"),"auto"),hideBranding:v(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatBubbleSnippet: api-url attribute is required"),this.client=null;return}try{this.client=C(e.apiUrl)}catch(t){console.error("ChatBubbleSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${E}
811
- ${B}
826
+ `}isNearBottom(){const i=this.messagesContainer;return i?i.scrollHeight-i.scrollTop-i.clientHeight<me:!0}scheduleScrollToBottom(){this.messagesContainer&&this.pendingScrollFrame===null&&(this.pendingScrollFrame=requestAnimationFrame(()=>{this.pendingScrollFrame=null;const i=this.messagesContainer;i&&(i.scrollTop=i.scrollHeight)}))}setStreamingState(i){this.isStreaming=i,this.inputElement&&(this.inputElement.disabled=i),this.sendButton&&(this.sendButton.disabled=i,this.sendButton.innerHTML=i?'<div class="loading"></div>':`<span>${c(this.translations.sendButtonLabel)}</span>`),i?this.startLoadingMessages():this.clearLoadingMessages()}startLoadingMessages(){this.clearLoadingMessages();const i=this.translations.loadingMessages;this.loadingMessageIndex=Math.floor(Math.random()*i.length),this.loadingMessageInterval=setInterval(()=>{const e=this.translations.loadingMessages;if(this.loadingMessageIndex=(this.loadingMessageIndex+1)%e.length,!this.isStreaming)return;this.updateLoadingTextDOM(e[this.loadingMessageIndex]??"")||this.renderMessages(!0)},A)}updateLoadingTextDOM(i){if(!this.messagesContainer||!this.currentStreamingMessageId)return!1;const e=this.messagesContainer.querySelector(`[data-message-id="${CSS.escape(this.currentStreamingMessageId)}"]`);if(!e)return!1;const t=e.querySelector(".chat-streaming .loading-text");return t?(t.textContent=i,!0):!1}clearLoadingMessages(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}getMessages(){return[...this.messages]}clearMessages(){this.messages=[],this.renderMessages()}setMessages(i){this.messages=[...i],this.renderMessages()}setProps(i){this.props=i,this.translations=u(i.translations),this.detachEventListeners(),this.render(),this.attachEventListeners(),this.renderMessages(this.isStreaming),this.isStreaming&&this.setStreamingState(!0)}detachEventListeners(){this.inputElement&&(this.handleInputResize&&this.inputElement.removeEventListener("input",this.handleInputResize),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.sendButton&&this.handleSendClick&&this.sendButton.removeEventListener("click",this.handleSendClick),this.handleInputResize=null,this.handleInputKeydown=null,this.handleSendClick=null}destroy(){this.clearLoadingMessages(),this.pendingScrollFrame!==null&&(cancelAnimationFrame(this.pendingScrollFrame),this.pendingScrollFrame=null),this.isStreaming&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputResize&&this.inputElement.removeEventListener("input",this.handleInputResize),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.sendButton&&this.handleSendClick&&this.sendButton.removeEventListener("click",this.handleSendClick),this.handleInputResize=null,this.handleInputKeydown=null,this.handleSendClick=null}}const j="chat-bubble-snippet";class F extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"isExpanded",!1);a(this,"isMinimized",!1);a(this,"translationsOverride",null);a(this,"resolvedTranslations",u(null));a(this,"chatQueryRewriteOverride",null);a(this,"handleBubbleClick",null);a(this,"handleCloseClick",null);a(this,"handleMinimizeClick",null);a(this,"handleClearClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding","translations","chat-query-rewrite"]}connectedCallback(){this.syncTranslationsFromAttribute(),this.render(),this.initializeClient(),this.dispatchEvent(w("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"?this.updateTheme(s):e==="translations"&&(this.syncTranslationsFromAttribute(),this.isConnected&&this.rerenderAfterTranslationsChange()))}get translations(){return this.translationsOverride}get chatQueryRewrite(){return this.chatQueryRewriteOverride}set chatQueryRewrite(e){this.chatQueryRewriteOverride=e??null,this.chatView&&this.chatView.setProps(this.getProps())}set translations(e){this.translationsOverride=e??null,this.resolvedTranslations=u(this.translationsOverride),this.isConnected&&this.rerenderAfterTranslationsChange()}syncTranslationsFromAttribute(){if(this.translationsOverride){this.resolvedTranslations=u(this.translationsOverride);return}const e=E(this.getAttribute("translations"),"ChatBubbleSnippet");this.resolvedTranslations=u(e)}rerenderAfterTranslationsChange(){const e=this.isExpanded,t=this.isMinimized;this.removeEventListeners();const s=this.chatView?this.shadow.querySelector(".chat-content"):null;s?.parentNode&&s.parentNode.removeChild(s),this.render(),e&&(this.shadow.querySelector(".bubble-button")?.classList.add("hidden"),this.shadow.querySelector(".chat-window")?.classList.add("expanded"),t&&this.shadow.querySelector(".chat-window")?.classList.add("minimized"));const r=this.shadow.querySelector(".chat-window");if(this.chatView&&s&&r){const n=r.querySelector(".chat-content");n?r.replaceChild(s,n):r.appendChild(s),this.chatView.setProps(this.getProps())}else e&&this.initializeChatView()}getProps(){const e=this.resolvedTranslations;return{apiUrl:f(this.getAttribute("api-url"),""),placeholder:f(this.getAttribute("placeholder"),e.chatPlaceholder),theme:f(this.getAttribute("theme"),"auto"),hideBranding:b(this.getAttribute("hide-branding"),!1),translations:this.translationsOverride??void 0,chatQueryRewrite:this.resolveChatQueryRewrite()}}resolveChatQueryRewrite(){return this.chatQueryRewriteOverride!==null?this.chatQueryRewriteOverride:N(this.getAttribute("chat-query-rewrite"),"ChatBubbleSnippet")}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatBubbleSnippet: api-url attribute is required"),this.client=null;return}try{this.client=M(e.apiUrl)}catch(t){console.error("ChatBubbleSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${T}
827
+ ${_}
812
828
  ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.container.className="chat-bubble-widget",this.container.innerHTML=this.getBaseHTML(),this.shadow.innerHTML="",this.shadow.appendChild(e),this.shadow.appendChild(this.container),this.attachEventListeners()}getBubbleStyles(){return`
813
829
  .chat-bubble-widget {
814
830
  position: var(--chat-bubble-position);
@@ -947,8 +963,8 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
947
963
  max-width: 400px;
948
964
  }
949
965
  }
950
- `}getBaseHTML(){return`
951
- <button class="bubble-button" aria-label="Open chat">
966
+ `}getBaseHTML(){const e=this.getProps(),t=this.resolvedTranslations,s=e.hideBranding?"":`<div class="powered-by">${L}</div>`;return`
967
+ <button class="bubble-button" aria-label="${c(t.openChatAriaLabel)}">
952
968
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
953
969
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
954
970
  </svg>
@@ -959,21 +975,21 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
959
975
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
960
976
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
961
977
  </svg>
962
- <span>Chat</span>
978
+ <span>${c(t.chatTitle)}</span>
963
979
  </div>
964
980
  <div class="chat-header-actions">
965
- <button class="icon-button clear-button" aria-label="Clear history">
981
+ <button class="icon-button clear-button" aria-label="${c(t.clearHistoryAriaLabel)}">
966
982
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
967
983
  <polyline points="3 6 5 6 21 6"></polyline>
968
984
  <path d="M19 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 2v2"></path>
969
985
  </svg>
970
986
  </button>
971
- <button class="icon-button minimize-button" aria-label="Minimize">
987
+ <button class="icon-button minimize-button" aria-label="${c(t.minimizeAriaLabel)}">
972
988
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
973
989
  <line x1="5" y1="12" x2="19" y2="12"></line>
974
990
  </svg>
975
991
  </button>
976
- <button class="icon-button close-button" aria-label="Close">
992
+ <button class="icon-button close-button" aria-label="${c(t.closeAriaLabel)}">
977
993
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
978
994
  <line x1="18" y1="6" x2="6" y2="18"></line>
979
995
  <line x1="6" y1="6" x2="18" y2="18"></line>
@@ -982,14 +998,14 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
982
998
  </div>
983
999
  </div>
984
1000
  <div class="chat-content"></div>
985
- ${this.getProps().hideBranding?"":`<div class="powered-by">${S}</div>`}
1001
+ ${s}
986
1002
  </div>
987
- `}attachEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick=()=>this.toggleChat(),this.handleCloseClick=()=>this.closeChat(),this.handleMinimizeClick=()=>this.toggleMinimize(),this.handleClearClick=()=>this.clearChat(),e?.addEventListener("click",this.handleBubbleClick),t?.addEventListener("click",this.handleCloseClick),s?.addEventListener("click",this.handleMinimizeClick),r?.addEventListener("click",this.handleClearClick)}removeEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick&&e?.removeEventListener("click",this.handleBubbleClick),this.handleCloseClick&&t?.removeEventListener("click",this.handleCloseClick),this.handleMinimizeClick&&s?.removeEventListener("click",this.handleMinimizeClick),this.handleClearClick&&r?.removeEventListener("click",this.handleClearClick),this.handleBubbleClick=null,this.handleCloseClick=null,this.handleMinimizeClick=null,this.handleClearClick=null}toggleChat(){this.isExpanded=!this.isExpanded;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");this.isExpanded?(e?.classList.add("hidden"),t?.classList.add("expanded"),this.initializeChatView()):(e?.classList.remove("hidden"),t?.classList.remove("expanded"))}closeChat(){this.isExpanded=!1,this.isMinimized=!1;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");e?.classList.remove("hidden"),t?.classList.remove("expanded","minimized")}toggleMinimize(){this.isMinimized=!this.isMinimized;const e=this.shadow.querySelector(".chat-window");this.isMinimized?e?.classList.add("minimized"):e?.classList.remove("minimized")}initializeChatView(){if(this.chatView)return;const e=this.shadow.querySelector(".chat-content");if(!e)return;if(!this.client){e.innerHTML=`
1003
+ `}attachEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick=()=>this.toggleChat(),this.handleCloseClick=()=>this.closeChat(),this.handleMinimizeClick=()=>this.toggleMinimize(),this.handleClearClick=()=>this.clearChat(),e?.addEventListener("click",this.handleBubbleClick),t?.addEventListener("click",this.handleCloseClick),s?.addEventListener("click",this.handleMinimizeClick),r?.addEventListener("click",this.handleClearClick)}removeEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick&&e?.removeEventListener("click",this.handleBubbleClick),this.handleCloseClick&&t?.removeEventListener("click",this.handleCloseClick),this.handleMinimizeClick&&s?.removeEventListener("click",this.handleMinimizeClick),this.handleClearClick&&r?.removeEventListener("click",this.handleClearClick),this.handleBubbleClick=null,this.handleCloseClick=null,this.handleMinimizeClick=null,this.handleClearClick=null}toggleChat(){this.isExpanded=!this.isExpanded;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");this.isExpanded?(e?.classList.add("hidden"),t?.classList.add("expanded"),this.initializeChatView()):(e?.classList.remove("hidden"),t?.classList.remove("expanded"))}closeChat(){this.isExpanded=!1,this.isMinimized=!1;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");e?.classList.remove("hidden"),t?.classList.remove("expanded","minimized")}toggleMinimize(){this.isMinimized=!this.isMinimized;const e=this.shadow.querySelector(".chat-window");this.isMinimized?e?.classList.add("minimized"):e?.classList.remove("minimized")}initializeChatView(){if(this.chatView)return;const e=this.shadow.querySelector(".chat-content");if(!e)return;if(!this.client){const s=this.resolvedTranslations;e.innerHTML=`
988
1004
  <div style="padding: 16px; color: var(--search-snippet-error-color, #ef4444); font-family: var(--search-snippet-font-family, sans-serif); font-size: var(--search-snippet-font-size-base, 14px);">
989
- <strong>Error:</strong> The <code>api-url</code> attribute is required. Please provide a valid API URL.
1005
+ <strong>${c(s.errorPrefix)}</strong> ${c(s.missingApiUrlError)}
990
1006
  </div>
991
- `;return}const t=this.getProps();this.chatView=new H(e,this.client,t)}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.chatView?.clearMessages()}async sendMessage(e){this.chatView&&await this.chatView.sendMessage(e)}getMessages(){return this.chatView?.getMessages()||[]}}customElements.get(N)||customElements.define(N,_);const O="chat-page-snippet",U="chat-page-sessions";class P extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"sessions",[]);a(this,"currentSessionId",null);a(this,"sidebarCollapsed",!1);a(this,"handleClearClick",null);a(this,"handleNewChatClick",null);a(this,"handleToggleSidebarClick",null);a(this,"handleChatListClick",null);a(this,"handleMessageEvent",null);this.shadow=this.attachShadow({mode:"open"}),this.loadSessions()}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.setupView(),this.dispatchEvent(b("ready",void 0))}disconnectedCallback(){this.saveCurrentSession(),this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?(this.initializeClient(),this.setupView()):e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Type a message..."),theme:u(this.getAttribute("theme"),"auto"),hideBranding:v(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatPageSnippet: api-url attribute is required"),this.client=null;return}try{this.client=C(e.apiUrl)}catch(t){console.error("ChatPageSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${E}
992
- ${B}
1007
+ `;return}const t=this.getProps();this.chatView=new V(e,this.client,t)}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.chatView?.clearMessages()}async sendMessage(e){this.chatView&&await this.chatView.sendMessage(e)}getMessages(){return this.chatView?.getMessages()||[]}}customElements.get(j)||customElements.define(j,F);const K="chat-page-snippet",Q="chat-page-sessions";class G extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"sessions",[]);a(this,"currentSessionId",null);a(this,"sidebarCollapsed",!1);a(this,"translationsOverride",null);a(this,"resolvedTranslations",u(null));a(this,"chatQueryRewriteOverride",null);a(this,"handleClearClick",null);a(this,"handleNewChatClick",null);a(this,"handleToggleSidebarClick",null);a(this,"handleChatListClick",null);a(this,"handleMessageEvent",null);this.shadow=this.attachShadow({mode:"open"}),this.loadSessions()}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding","translations","chat-query-rewrite"]}connectedCallback(){this.syncTranslationsFromAttribute(),this.render(),this.initializeClient(),this.setupView(),this.dispatchEvent(w("ready",void 0))}disconnectedCallback(){this.saveCurrentSession(),this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?(this.initializeClient(),this.setupView()):e==="theme"?this.updateTheme(s):e==="translations"&&(this.syncTranslationsFromAttribute(),this.isConnected&&this.rerenderAfterTranslationsChange()))}get translations(){return this.translationsOverride}get chatQueryRewrite(){return this.chatQueryRewriteOverride}set chatQueryRewrite(e){this.chatQueryRewriteOverride=e??null,this.chatView&&this.chatView.setProps(this.getProps())}set translations(e){this.translationsOverride=e??null,this.resolvedTranslations=u(this.translationsOverride),this.refreshDefaultSessionTitles(),this.isConnected&&this.rerenderAfterTranslationsChange()}syncTranslationsFromAttribute(){if(this.translationsOverride){this.resolvedTranslations=u(this.translationsOverride),this.refreshDefaultSessionTitles();return}const e=E(this.getAttribute("translations"),"ChatPageSnippet");this.resolvedTranslations=u(e),this.refreshDefaultSessionTitles()}refreshDefaultSessionTitles(){if(this.sessions.length===0)return;const e=this.resolvedTranslations.newChatButton;let t=!1;for(const s of this.sessions)s.titleIsDefault&&s.title!==e&&(s.title=e,t=!0);t&&this.saveSessions()}rerenderAfterTranslationsChange(){this.removeEventListeners();const e=this.chatView?this.shadow.querySelector(".container"):null;e?.parentNode&&e.parentNode.removeChild(e),this.render(),this.attachEventListeners(),this.renderChatList();const t=this.shadow.querySelector(".chat-page-content");if(this.chatView&&e&&t){const s=t.querySelector(".container");s?t.replaceChild(e,s):t.appendChild(e),this.chatView.setProps(this.getProps()),this.handleMessageEvent=()=>{this.saveCurrentSession(),this.updateSessionTitle(),this.renderChatList()},e.addEventListener("message",this.handleMessageEvent)}}getProps(){const e=this.resolvedTranslations;return{apiUrl:f(this.getAttribute("api-url"),""),placeholder:f(this.getAttribute("placeholder"),e.chatPlaceholder),theme:f(this.getAttribute("theme"),"auto"),hideBranding:b(this.getAttribute("hide-branding"),!1),translations:this.translationsOverride??void 0,chatQueryRewrite:this.resolveChatQueryRewrite()}}resolveChatQueryRewrite(){return this.chatQueryRewriteOverride!==null?this.chatQueryRewriteOverride:N(this.getAttribute("chat-query-rewrite"),"ChatPageSnippet")}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatPageSnippet: api-url attribute is required"),this.client=null;return}try{this.client=M(e.apiUrl)}catch(t){console.error("ChatPageSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${T}
1008
+ ${_}
993
1009
  ${this.getPageStyles()}`,this.container=document.createElement("div"),this.container.className="chat-page-container",this.container.innerHTML=this.getBaseHTML(),this.shadow.innerHTML="",this.shadow.appendChild(e),this.shadow.appendChild(this.container),this.attachEventListeners()}getPageStyles(){return`
994
1010
  :host {
995
1011
  display: block;
@@ -1263,24 +1279,24 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
1263
1279
  background: var(--search-snippet-background);
1264
1280
  border-radius: 0;
1265
1281
  }
1266
- `}getBaseHTML(){return`
1282
+ `}getBaseHTML(){const e=this.getProps(),t=this.resolvedTranslations,s=e.hideBranding?"":`<div class="powered-by">${L}</div>`;return`
1267
1283
  <div class="chat-sidebar">
1268
1284
  <div class="sidebar-header">
1269
- <span class="sidebar-title">History</span>
1285
+ <span class="sidebar-title">${c(t.historyTitle)}</span>
1270
1286
  </div>
1271
1287
  <button class="new-chat-button">
1272
1288
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1273
1289
  <path d="M12 5v14M5 12h14"></path>
1274
1290
  </svg>
1275
- New Chat
1291
+ ${c(t.newChatButton)}
1276
1292
  </button>
1277
1293
  <div class="chat-list"></div>
1278
- ${this.getProps().hideBranding?"":`<div class="powered-by">${S}</div>`}
1294
+ ${s}
1279
1295
  </div>
1280
1296
  <div class="chat-main">
1281
1297
  <div class="chat-page-header">
1282
1298
  <div class="chat-page-header-left">
1283
- <button class="toggle-sidebar-button" title="Toggle sidebar">
1299
+ <button class="toggle-sidebar-button" title="${c(t.toggleSidebarTitle)}">
1284
1300
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1285
1301
  <path d="M3 12h18M3 6h18M3 18h18"></path>
1286
1302
  </svg>
@@ -1289,7 +1305,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
1289
1305
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1290
1306
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
1291
1307
  </svg>
1292
- <span>Chat</span>
1308
+ <span>${c(t.chatTitle)}</span>
1293
1309
  </div>
1294
1310
  </div>
1295
1311
  <div class="chat-page-header-actions">
@@ -1297,7 +1313,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
1297
1313
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1298
1314
  <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 2v2"></path>
1299
1315
  </svg>
1300
- Clear Chat
1316
+ ${c(t.clearChatButton)}
1301
1317
  </button>
1302
1318
  </div>
1303
1319
  </div>
@@ -1305,23 +1321,23 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
1305
1321
  <div class="container"></div>
1306
1322
  </div>
1307
1323
  </div>
1308
- `}attachEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),r=this.shadow.querySelector(".chat-list");this.handleClearClick=()=>this.clearCurrentChat(),this.handleNewChatClick=()=>this.createNewChat(),this.handleToggleSidebarClick=()=>this.toggleSidebar(),this.handleChatListClick=o=>this.onChatListClick(o),e?.addEventListener("click",this.handleClearClick),t?.addEventListener("click",this.handleNewChatClick),s?.addEventListener("click",this.handleToggleSidebarClick),r?.addEventListener("click",this.handleChatListClick)}removeEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),r=this.shadow.querySelector(".chat-list"),o=this.shadow.querySelector(".container");this.handleClearClick&&e?.removeEventListener("click",this.handleClearClick),this.handleNewChatClick&&t?.removeEventListener("click",this.handleNewChatClick),this.handleToggleSidebarClick&&s?.removeEventListener("click",this.handleToggleSidebarClick),this.handleChatListClick&&r?.removeEventListener("click",this.handleChatListClick),this.handleMessageEvent&&o&&o.removeEventListener("message",this.handleMessageEvent),this.handleClearClick=null,this.handleNewChatClick=null,this.handleToggleSidebarClick=null,this.handleChatListClick=null,this.handleMessageEvent=null}setupView(){const e=this.shadow.querySelector(".container");if(!this.client){e&&(e.innerHTML=`
1324
+ `}attachEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),r=this.shadow.querySelector(".chat-list");this.handleClearClick=()=>this.clearCurrentChat(),this.handleNewChatClick=()=>this.createNewChat(),this.handleToggleSidebarClick=()=>this.toggleSidebar(),this.handleChatListClick=n=>this.onChatListClick(n),e?.addEventListener("click",this.handleClearClick),t?.addEventListener("click",this.handleNewChatClick),s?.addEventListener("click",this.handleToggleSidebarClick),r?.addEventListener("click",this.handleChatListClick)}removeEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),r=this.shadow.querySelector(".chat-list"),n=this.shadow.querySelector(".container");this.handleClearClick&&e?.removeEventListener("click",this.handleClearClick),this.handleNewChatClick&&t?.removeEventListener("click",this.handleNewChatClick),this.handleToggleSidebarClick&&s?.removeEventListener("click",this.handleToggleSidebarClick),this.handleChatListClick&&r?.removeEventListener("click",this.handleChatListClick),this.handleMessageEvent&&n&&n.removeEventListener("message",this.handleMessageEvent),this.handleClearClick=null,this.handleNewChatClick=null,this.handleToggleSidebarClick=null,this.handleChatListClick=null,this.handleMessageEvent=null}setupView(){const e=this.shadow.querySelector(".container");if(!this.client){if(e){const s=this.resolvedTranslations;e.innerHTML=`
1309
1325
  <div style="padding: 16px; color: var(--search-snippet-error-color, #ef4444); font-family: var(--search-snippet-font-family, sans-serif); font-size: var(--search-snippet-font-size-base, 14px);">
1310
- <strong>Error:</strong> The <code>api-url</code> attribute is required. Please provide a valid API URL.
1326
+ <strong>${c(s.errorPrefix)}</strong> ${c(s.missingApiUrlError)}
1311
1327
  </div>
1312
- `);return}if(!e)return;const t=this.getProps();if(this.chatView=new H(e,this.client,t),this.sessions.length===0)this.createNewChat();else{const s=this.sessions[0];this.switchToSession(s.id)}this.handleMessageEvent=()=>{this.saveCurrentSession(),this.updateSessionTitle(),this.renderChatList()},e.addEventListener("message",this.handleMessageEvent),this.renderChatList()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}loadSessions(){try{const e=localStorage.getItem(U);e&&(this.sessions=JSON.parse(e),this.sessions.sort((t,s)=>s.updatedAt-t.updatedAt))}catch(e){console.error("Failed to load chat sessions:",e)}}saveSessions(){try{localStorage.setItem(U,JSON.stringify(this.sessions))}catch(e){console.error("Failed to save chat sessions:",e)}}saveCurrentSession(){if(!this.currentSessionId||!this.chatView)return;const e=this.sessions.findIndex(t=>t.id===this.currentSessionId);e!==-1&&(this.sessions[e].messages=this.chatView.getMessages(),this.sessions[e].updatedAt=Date.now(),this.saveSessions())}updateSessionTitle(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);if(e&&e.messages.length>0&&e.title==="New Chat"){const t=e.messages.find(s=>s.role==="user");t&&(e.title=t.content.slice(0,50)+(t.content.length>50?"...":""),this.saveSessions())}}createNewChat(){this.saveCurrentSession();const e={id:this.generateSessionId(),title:"New Chat",messages:[],createdAt:Date.now(),updatedAt:Date.now()};this.sessions.unshift(e),this.currentSessionId=e.id,this.saveSessions(),this.chatView?.clearMessages(),this.renderChatList()}switchToSession(e){if(e===this.currentSessionId)return;this.saveCurrentSession();const t=this.sessions.find(s=>s.id===e);t&&this.chatView&&(this.currentSessionId=e,this.chatView.setMessages(t.messages),this.renderChatList())}deleteSession(e){const t=this.sessions.findIndex(s=>s.id===e);t!==-1&&(this.sessions.splice(t,1),this.saveSessions(),e===this.currentSessionId&&(this.sessions.length>0?this.switchToSession(this.sessions[0].id):this.createNewChat()),this.renderChatList())}clearCurrentChat(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);e&&(e.messages=[],e.title="New Chat",e.updatedAt=Date.now(),this.saveSessions()),this.chatView?.clearMessages(),this.renderChatList()}toggleSidebar(){this.sidebarCollapsed=!this.sidebarCollapsed,this.shadow.querySelector(".chat-sidebar")?.classList.toggle("collapsed",this.sidebarCollapsed)}onChatListClick(e){const t=e.target,s=t.closest(".chat-list-item-delete");if(s){e.stopPropagation();const o=s.getAttribute("data-session-id");o&&this.deleteSession(o);return}const r=t.closest(".chat-list-item");if(r){const o=r.getAttribute("data-session-id");o&&this.switchToSession(o)}}renderChatList(){const e=this.shadow.querySelector(".chat-list");if(e){if(this.sessions.length===0){e.innerHTML='<div class="chat-list-empty">No chats yet</div>';return}e.innerHTML=this.sessions.map(t=>this.renderChatListItem(t)).join("")}}renderChatListItem(e){const t=e.id===this.currentSessionId,s=this.formatDate(e.updatedAt);return`
1328
+ `}return}if(!e)return;const t=this.getProps();if(this.chatView=new V(e,this.client,t),this.sessions.length===0)this.createNewChat();else{const s=this.sessions[0];this.switchToSession(s.id)}this.handleMessageEvent=()=>{this.saveCurrentSession(),this.updateSessionTitle(),this.renderChatList()},e.addEventListener("message",this.handleMessageEvent),this.renderChatList()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}loadSessions(){try{const e=localStorage.getItem(Q);e&&(this.sessions=JSON.parse(e),this.sessions.sort((t,s)=>s.updatedAt-t.updatedAt))}catch(e){console.error("Failed to load chat sessions:",e)}}saveSessions(){try{localStorage.setItem(Q,JSON.stringify(this.sessions))}catch(e){console.error("Failed to save chat sessions:",e)}}saveCurrentSession(){if(!this.currentSessionId||!this.chatView)return;const e=this.sessions.findIndex(t=>t.id===this.currentSessionId);e!==-1&&(this.sessions[e].messages=this.chatView.getMessages(),this.sessions[e].updatedAt=Date.now(),this.saveSessions())}updateSessionTitle(){if(!this.currentSessionId)return;const e=this.sessions.find(r=>r.id===this.currentSessionId);if(!e||e.messages.length===0||!(e.titleIsDefault??e.title===this.resolvedTranslations.newChatButton))return;const s=e.messages.find(r=>r.role==="user");s&&(e.title=s.content.slice(0,50)+(s.content.length>50?"...":""),e.titleIsDefault=!1,this.saveSessions())}createNewChat(){this.saveCurrentSession();const e={id:this.generateSessionId(),title:this.resolvedTranslations.newChatButton,messages:[],createdAt:Date.now(),updatedAt:Date.now(),titleIsDefault:!0};this.sessions.unshift(e),this.currentSessionId=e.id,this.saveSessions(),this.chatView?.clearMessages(),this.renderChatList()}switchToSession(e){if(e===this.currentSessionId)return;this.saveCurrentSession();const t=this.sessions.find(s=>s.id===e);t&&this.chatView&&(this.currentSessionId=e,this.chatView.setMessages(t.messages),this.renderChatList())}deleteSession(e){const t=this.sessions.findIndex(s=>s.id===e);t!==-1&&(this.sessions.splice(t,1),this.saveSessions(),e===this.currentSessionId&&(this.sessions.length>0?this.switchToSession(this.sessions[0].id):this.createNewChat()),this.renderChatList())}clearCurrentChat(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);e&&(e.messages=[],e.title=this.resolvedTranslations.newChatButton,e.titleIsDefault=!0,e.updatedAt=Date.now(),this.saveSessions()),this.chatView?.clearMessages(),this.renderChatList()}toggleSidebar(){this.sidebarCollapsed=!this.sidebarCollapsed,this.shadow.querySelector(".chat-sidebar")?.classList.toggle("collapsed",this.sidebarCollapsed)}onChatListClick(e){const t=e.target,s=t.closest(".chat-list-item-delete");if(s){e.stopPropagation();const n=s.getAttribute("data-session-id");n&&this.deleteSession(n);return}const r=t.closest(".chat-list-item");if(r){const n=r.getAttribute("data-session-id");n&&this.switchToSession(n)}}renderChatList(){const e=this.shadow.querySelector(".chat-list");if(!e)return;const t=this.resolvedTranslations;if(this.sessions.length===0){e.innerHTML=`<div class="chat-list-empty">${this.escapeHTML(t.noChatsYet)}</div>`;return}e.innerHTML=this.sessions.map(s=>this.renderChatListItem(s)).join("")}renderChatListItem(e){const t=e.id===this.currentSessionId,s=this.formatDate(e.updatedAt),r=this.resolvedTranslations.deleteChatTitle;return`
1313
1329
  <div class="chat-list-item ${t?"active":""}" data-session-id="${e.id}">
1314
1330
  <div class="chat-list-item-content">
1315
1331
  <div class="chat-list-item-title">${this.escapeHTML(e.title)}</div>
1316
1332
  <div class="chat-list-item-date">${s}</div>
1317
1333
  </div>
1318
- <button class="chat-list-item-delete" data-session-id="${e.id}" title="Delete chat">
1334
+ <button class="chat-list-item-delete" data-session-id="${e.id}" title="${this.escapeHTML(r)}">
1319
1335
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1320
1336
  <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 2v2"></path>
1321
1337
  </svg>
1322
1338
  </button>
1323
1339
  </div>
1324
- `}formatDate(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),o=Math.floor(r/(1e3*60*60*24));return o===0?t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):o===1?"Yesterday":o<7?t.toLocaleDateString(void 0,{weekday:"long"}):t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.clearCurrentChat()}async sendMessage(e){this.chatView&&(await this.chatView.sendMessage(e),this.saveCurrentSession())}getMessages(){return this.chatView?.getMessages()||[]}getSessions(){return[...this.sessions]}getCurrentSession(){return this.sessions.find(e=>e.id===this.currentSessionId)||null}}customElements.get(O)||customElements.define(O,P);const X=`
1340
+ `}formatDate(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),n=Math.floor(r/(1e3*60*60*24));return n===0?t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):n===1?this.resolvedTranslations.yesterday:n<7?t.toLocaleDateString(void 0,{weekday:"long"}):t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.clearCurrentChat()}async sendMessage(e){this.chatView&&(await this.chatView.sendMessage(e),this.saveCurrentSession())}getMessages(){return this.chatView?.getMessages()||[]}getSessions(){return[...this.sessions]}getCurrentSession(){return this.sessions.find(e=>e.id===this.currentSessionId)||null}}customElements.get(K)||customElements.define(K,G);const ve=`
1325
1341
  /* Search view states */
1326
1342
  .search-view {
1327
1343
  transition: var(--search-snippet-transition-slow);
@@ -1691,8 +1707,8 @@ a.search-result-item:focus-visible {
1691
1707
  border-radius: 2px;
1692
1708
  font-weight: var(--search-snippet-font-weight-medium);
1693
1709
  }
1694
- `,D="search-bar-snippet",Z=10,Q=50;class M extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"container",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"searchButton",null);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleInputChange",null);a(this,"handleInputKeydownEnter",null);a(this,"handleInputKeydownEscape",null);a(this,"handleSearchButtonClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","debounce-ms","theme","hide-branding","show-url","show-date","hide-thumbnails","see-more","request-options"]}connectedCallback(){this.initializeClient(),this.render(),this.dispatchEvent(b("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Search..."),maxResults:k(this.getAttribute("max-results"),10),debounceMs:k(this.getAttribute("debounce-ms"),300),theme:u(this.getAttribute("theme"),"auto"),hideBranding:v(this.getAttribute("hide-branding"),!1),showUrl:v(this.getAttribute("show-url"),!1),showDate:v(this.getAttribute("show-date"),!1),hideThumbnails:v(this.getAttribute("hide-thumbnails"),!1),seeMore:u(this.getAttribute("see-more"),"")}}getRequestOptions(){const e=this.getAttribute("request-options");if(e)try{const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("request-options must be a JSON object");return t}catch(t){console.error("SearchBarSnippet: invalid request-options attribute",t);return}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchBarSnippet: api-url attribute is required"),this.client=null,this.showMissingApiUrlError();return}try{this.client=C(e.apiUrl)}catch(t){console.error("SearchBarSnippet:",t)}}render(){const e=this.getProps(),t=r=>this.performSearch(r);this.debouncedSearch=I(t,e.debounceMs||400);const s=document.createElement("style");s.textContent=`${E}
1695
- ${X}`,this.container=document.createElement("div"),this.container.className="container",this.container.innerHTML=`
1710
+ `,Y="search-bar-snippet",W=10,J=50;class R extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"stats",null);a(this,"container",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"searchButton",null);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"translationsOverride",null);a(this,"resolvedTranslations",u(null));a(this,"lastSearchQuery","");a(this,"lastSearchTotal",0);a(this,"handleInputChange",null);a(this,"handleInputKeydownEnter",null);a(this,"handleInputKeydownEscape",null);a(this,"handleSearchButtonClick",null);a(this,"handleResultClick",null);a(this,"handleSeeMoreClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","max-render-results","debounce-ms","theme","hide-branding","show-url","show-date","hide-thumbnails","see-more","disable-analytics","request-options","translations"]}connectedCallback(){this.syncTranslationsFromAttribute(),this.initializeClient(),this.render(),this.dispatchEvent(w("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"||e==="disable-analytics"?this.initializeClient():e==="theme"?this.updateTheme(s):e==="translations"&&(this.syncTranslationsFromAttribute(),this.isConnected&&this.rerender()))}get translations(){return this.translationsOverride}set translations(e){this.translationsOverride=e??null,this.resolvedTranslations=u(this.translationsOverride),this.isConnected&&this.rerender()}rerender(){const e=this.inputElement?.value??"";this.render(),e&&this.inputElement&&(this.inputElement.value=e,e.trim().length>0&&this.performSearch(e.trim()))}syncTranslationsFromAttribute(){if(this.translationsOverride){this.resolvedTranslations=u(this.translationsOverride);return}const e=E(this.getAttribute("translations"),"SearchBarSnippet");this.resolvedTranslations=u(e)}getProps(){const e=this.resolvedTranslations;return{apiUrl:f(this.getAttribute("api-url"),""),placeholder:f(this.getAttribute("placeholder"),e.placeholder),maxResults:C(this.getAttribute("max-results"),J),maxRenderResults:C(this.getAttribute("max-render-results"),W),debounceMs:C(this.getAttribute("debounce-ms"),300),theme:f(this.getAttribute("theme"),"auto"),hideBranding:b(this.getAttribute("hide-branding"),!1),showUrl:b(this.getAttribute("show-url"),!1),showDate:b(this.getAttribute("show-date"),!1),hideThumbnails:b(this.getAttribute("hide-thumbnails"),!1),seeMore:f(this.getAttribute("see-more"),""),disableAnalytics:b(this.getAttribute("disable-analytics"),!1),translations:this.translationsOverride??void 0}}getRequestOptions(){const e=this.getAttribute("request-options");if(e)try{const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("request-options must be a JSON object");return t}catch(t){console.error("SearchBarSnippet: invalid request-options attribute",t);return}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchBarSnippet: api-url attribute is required"),this.client=null,this.destroyStatsClient(),this.showMissingApiUrlError();return}try{this.client=M(e.apiUrl),this.destroyStatsClient(),e.disableAnalytics||(this.stats=new I(e.apiUrl))}catch(t){console.error("SearchBarSnippet:",t)}}destroyStatsClient(){this.stats&&(this.stats.destroy(),this.stats=null)}render(){const e=this.getProps(),t=this.resolvedTranslations,s=n=>this.performSearch(n);this.debouncedSearch=$(s,e.debounceMs||400);const r=document.createElement("style");r.textContent=`${T}
1711
+ ${ve}`,this.container=document.createElement("div"),this.container.className="container",this.container.innerHTML=`
1696
1712
  <div class="search-view">
1697
1713
  <div class="search-input-wrapper">
1698
1714
  <svg xmlns="http://www.w3.org/2000/svg" class="search-icon" height="24px" viewBox="0 -960 960 960" width="24px" fill="currentColor"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400Z"/></svg>
@@ -1700,12 +1716,12 @@ ${X}`,this.container=document.createElement("div"),this.container.className="con
1700
1716
  type="text"
1701
1717
  name="search-input"
1702
1718
  class="search-input"
1703
- placeholder="${d(e.placeholder||"Search...")}"
1704
- aria-label="Search input"
1719
+ placeholder="${c(e.placeholder||t.placeholder)}"
1720
+ aria-label="${c(t.searchInputAriaLabel)}"
1705
1721
  autocomplete="off"
1706
1722
  />
1707
- <button class="button search-submit-button" aria-label="Search">
1708
- <span>Search</span>
1723
+ <button class="button search-submit-button" aria-label="${c(t.searchButtonLabel)}">
1724
+ <span>${c(t.searchButtonLabel)}</span>
1709
1725
  </button>
1710
1726
  </div>
1711
1727
  <div class="search-content">
@@ -1714,32 +1730,32 @@ ${X}`,this.container=document.createElement("div"),this.container.className="con
1714
1730
  </div>
1715
1731
  </div>
1716
1732
  </div>
1717
- `,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(this.container),this.inputElement=this.container.querySelector(".search-input"),this.resultsContainer=this.container.querySelector(".search-results-wrapper"),this.searchButton=this.container.querySelector(".search-submit-button"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachEventListeners(){this.inputElement&&(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):this.showEmptyState()},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydownEnter=e=>{if(e.key==="Enter"){const t=e.target.value.trim();t.length>0&&this.performSearch(t)}},this.inputElement.addEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape=e=>{e.key==="Escape"&&this.inputElement&&(this.inputElement.value="")},window.addEventListener("keydown",this.handleInputKeydownEscape),this.searchButton&&(this.handleSearchButtonClick=()=>{const e=this.inputElement?.value.trim()||"";e.length>0&&this.performSearch(e)},this.searchButton.addEventListener("click",this.handleSearchButtonClick)))}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:Q,request:this.getRequestOptions()}),s=this.getProps(),r=t.slice(0,s.maxResults||Z);this.displayResults(r,e,t.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),o=r.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,c=s>e.length,l=c?`Showing ${e.length} of ${s} results`:`Found ${s} result${s===1?"":"s"}`,g=r.seeMore&&c?`<div class="search-footer">
1718
- <a href="${d(r.seeMore+encodeURIComponent(t))}" class="search-see-more">
1719
- <span>See more results</span>
1733
+ `,this.shadow.innerHTML="",this.shadow.appendChild(r),this.shadow.appendChild(this.container),this.inputElement=this.container.querySelector(".search-input"),this.resultsContainer=this.container.querySelector(".search-results-wrapper"),this.searchButton=this.container.querySelector(".search-submit-button"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachEventListeners(){this.inputElement&&(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):this.showEmptyState()},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydownEnter=e=>{if(e.key==="Enter"){const t=e.target.value.trim();t.length>0&&this.performSearch(t)}},this.inputElement.addEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape=e=>{e.key==="Escape"&&this.inputElement&&(this.inputElement.value="")},window.addEventListener("keydown",this.handleInputKeydownEscape),this.searchButton&&(this.handleSearchButtonClick=()=>{const e=this.inputElement?.value.trim()||"";e.length>0&&this.performSearch(e)},this.searchButton.addEventListener("click",this.handleSearchButtonClick)))}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=this.getProps(),s=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:t.maxResults||J,request:this.getRequestOptions()}),r=s.slice(0,t.maxRenderResults||W);this.lastSearchQuery=e,this.lastSearchTotal=s.length,this.stats?.trackSearch(e,s.length),this.displayResults(r,e,s.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=this.resolvedTranslations,o=r.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,h=s>e.length,d=h?x(n.resultsCountOverflow,{n:e.length,total:s}):x(s===1?n.resultsCount:n.resultsCountPlural,{n:s}),p=r.seeMore&&h?`<div class="search-footer">
1734
+ <a href="${c(r.seeMore+encodeURIComponent(t))}" class="search-see-more">
1735
+ <span>${c(n.seeMoreResults)}</span>
1720
1736
  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
1721
1737
  </a>
1722
- </div>`:"",f=`
1738
+ </div>`:"",m=`
1723
1739
  <div class="search-header">
1724
1740
  <div class="search-count">
1725
- ${l}
1741
+ ${c(d)}
1726
1742
  </div>
1727
1743
  ${o}
1728
1744
  </div>
1729
1745
  <div class="search-results">
1730
- ${e.map(m=>this.renderResult(m)).join("")}
1746
+ ${e.map((y,z)=>this.renderResult(y,z)).join("")}
1731
1747
  </div>
1732
- ${g}
1733
- `;this.resultsContainer.innerHTML=f,this.attachResultHandlers()}renderResult(e){const t=this.getProps(),s=t.hideThumbnails?"":this.renderResultImage(e.image,e.title),r=e.url?d(e.url):"#",o=e.url?d(z(e.url)):"",c=t.showDate&&e.timestamp!==void 0?`<div class="search-result-date">${d(T(e.timestamp))}</div>`:"",l=t.showUrl&&e.url||c?`<div class="search-result-metadata">
1734
- ${t.showUrl&&e.url?`<span class="search-result-url">${o}</span>`:'<span class="search-result-url search-result-url-empty"></span>'}
1735
- ${c}
1748
+ ${p}
1749
+ `;this.resultsContainer.innerHTML=m,this.attachResultHandlers()}renderResult(e,t){const s=this.getProps(),r=s.hideThumbnails?"":this.renderResultImage(e.image,e.title),n=e.url?c(e.url):"#",o=e.url?c(q(e.url)):"",h=s.showDate&&e.timestamp!==void 0?`<div class="search-result-date">${c(O(e.timestamp))}</div>`:"",d=s.showUrl&&e.url||h?`<div class="search-result-metadata">
1750
+ ${s.showUrl&&e.url?`<span class="search-result-url">${o}</span>`:'<span class="search-result-url search-result-url-empty"></span>'}
1751
+ ${h}
1736
1752
  </div>`:"";return`
1737
- <a href="${r}" class="search-result-item" data-result-id="${d(e.url||"")}">
1738
- ${s}
1753
+ <a href="${n}" class="search-result-item" data-index="${t}" data-result-id="${c(e.id||"")}">
1754
+ ${r}
1739
1755
  <div class="search-result-content">
1740
- <div class="search-result-title">${d(e.title||"")}</div>
1741
- <div class="search-result-snippet">${d(e.description||"")}</div>
1742
- ${l}
1756
+ <div class="search-result-title">${c(e.title||"")}</div>
1757
+ <div class="search-result-snippet">${c(e.description||"")}</div>
1758
+ ${d}
1743
1759
  </div>
1744
1760
  </a>
1745
1761
  `}renderResultImage(e,t){const s='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>';return e?`
@@ -1748,8 +1764,8 @@ ${X}`,this.container=document.createElement("div"),this.container.className="con
1748
1764
  <div class="search-result-image-placeholder" style="display: none;">${s}</div>
1749
1765
  <img
1750
1766
  class="search-result-image"
1751
- src="${d(e)}"
1752
- alt="${d(t)}"
1767
+ src="${c(e)}"
1768
+ alt="${c(t)}"
1753
1769
  loading="lazy"
1754
1770
  />
1755
1771
  </div>
@@ -1757,38 +1773,38 @@ ${X}`,this.container=document.createElement("div"),this.container.className="con
1757
1773
  <div class="search-result-image-container">
1758
1774
  <div class="search-result-image-placeholder">${s}</div>
1759
1775
  </div>
1760
- `}attachResultHandlers(){const e=this.container?.querySelectorAll(".search-result-item");if(!e)return;for(const s of e)s.getAttribute("href")==="#"&&s.addEventListener("click",o=>{o.preventDefault()});this.container?.querySelectorAll(".search-result-image")?.forEach(s=>{s.addEventListener("load",()=>{s.classList.add("loaded"),s.closest(".search-result-image-container")?.querySelector(".search-result-image-loading")?.remove()}),s.addEventListener("error",()=>{const r=s.closest(".search-result-image-container");r?.querySelector(".search-result-image-loading")?.remove();const o=r?.querySelector(".search-result-image-placeholder");o&&(o.style.display="flex"),s.style.display="none"})})}showLoadingState(){this.resultsContainer&&(this.clearLoadingInterval(),this.loadingMessageIndex=Math.floor(Math.random()*h.length),this.resultsContainer.innerHTML=`
1776
+ `}attachResultHandlers(){this.detachResultTrackingHandlers();const e=this.resultsContainer;if(!e)return;this.handleResultClick=r=>{const o=r.target?.closest(".search-result-item");if(!o)return;o.getAttribute("href")==="#"&&r.preventDefault();const d=o.getAttribute("data-index"),p=o.getAttribute("data-result-id")??"",m=d!==null?Number.parseInt(d,10):Number.NaN;!Number.isNaN(m)&&p&&this.stats?.trackClick(this.lastSearchQuery,this.lastSearchTotal,p,m)},e.addEventListener("click",this.handleResultClick);const t=e.querySelector(".search-see-more");t&&(this.handleSeeMoreClick=()=>{this.stats?.trackViewMore(this.lastSearchQuery,this.lastSearchTotal)},t.addEventListener("click",this.handleSeeMoreClick)),this.container?.querySelectorAll(".search-result-image")?.forEach(r=>{r.addEventListener("load",()=>{r.classList.add("loaded"),r.closest(".search-result-image-container")?.querySelector(".search-result-image-loading")?.remove()}),r.addEventListener("error",()=>{const n=r.closest(".search-result-image-container");n?.querySelector(".search-result-image-loading")?.remove();const o=n?.querySelector(".search-result-image-placeholder");o&&(o.style.display="flex"),r.style.display="none"})})}detachResultTrackingHandlers(){const e=this.resultsContainer;e&&this.handleResultClick&&e.removeEventListener("click",this.handleResultClick),this.handleResultClick=null,this.handleSeeMoreClick=null}showLoadingState(){if(!this.resultsContainer)return;this.clearLoadingInterval();const e=this.resolvedTranslations.loadingMessages;this.loadingMessageIndex=Math.floor(Math.random()*e.length);const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
1761
1777
  <div class="search-loading">
1762
- <div class="loading" aria-label="Loading"></div>
1763
- <div class="loading-text loading-text-animate">${h[this.loadingMessageIndex]}</div>
1778
+ <div class="loading" aria-label="${c(t.loadingAriaLabel)}"></div>
1779
+ <div class="loading-text loading-text-animate">${c(e[this.loadingMessageIndex])}</div>
1764
1780
  </div>
1765
- `,this.startLoadingInterval())}startLoadingInterval(){this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%h.length;const e=this.resultsContainer?.querySelector(".loading-text");e&&(e.classList.remove("loading-text-animate"),e.offsetWidth,e.textContent=h[this.loadingMessageIndex],e.classList.add("loading-text-animate"))},2500)}clearLoadingInterval(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}showEmptyState(){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
1781
+ `,this.startLoadingInterval()}startLoadingInterval(){this.loadingMessageInterval=setInterval(()=>{const e=this.resolvedTranslations.loadingMessages;this.loadingMessageIndex=(this.loadingMessageIndex+1)%e.length;const t=this.resultsContainer?.querySelector(".loading-text");t&&(t.classList.remove("loading-text-animate"),t.offsetWidth,t.textContent=e[this.loadingMessageIndex],t.classList.add("loading-text-animate"))},A)}clearLoadingInterval(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}showEmptyState(){if(this.clearLoadingInterval(),!this.resultsContainer)return;const e=this.resolvedTranslations;this.resultsContainer.innerHTML=`
1766
1782
  <div class="search-empty">
1767
1783
  <svg class="search-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1768
1784
  <circle cx="11" cy="11" r="8"></circle>
1769
1785
  <path d="m21 21-4.35-4.35"></path>
1770
1786
  </svg>
1771
- <div class="search-empty-title">Start Searching</div>
1787
+ <div class="search-empty-title">${c(e.emptyStateTitle)}</div>
1772
1788
  <div class="search-empty-description">
1773
- Enter a query to search for results
1789
+ ${c(e.emptyStateDescription)}
1774
1790
  </div>
1775
1791
  </div>
1776
- `)}showNoResultsState(e){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
1792
+ `}showNoResultsState(e){if(this.clearLoadingInterval(),!this.resultsContainer)return;const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
1777
1793
  <div class="search-empty">
1778
1794
  <svg class="search-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1779
1795
  <circle cx="11" cy="11" r="8"></circle>
1780
1796
  <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
1781
1797
  </svg>
1782
- <div class="search-empty-title">No Results Found</div>
1798
+ <div class="search-empty-title">${c(t.noResultsTitle)}</div>
1783
1799
  <div class="search-empty-description">
1784
- No results found for "${d(e)}"
1800
+ ${c(x(t.noResultsDescription,{query:e}))}
1785
1801
  </div>
1786
1802
  </div>
1787
- `)}showErrorState(e){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
1803
+ `}showErrorState(e){if(this.clearLoadingInterval(),!this.resultsContainer)return;const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
1788
1804
  <div class="error">
1789
- <strong>Error:</strong> ${d(e)}
1805
+ <strong>${c(t.errorPrefix)}</strong> ${c(e)}
1790
1806
  </div>
1791
- `)}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState("The api-url attribute is required. Please provide a valid API URL.")}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.client&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydownEnter&&this.inputElement.removeEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape&&window.removeEventListener("keydown",this.handleInputKeydownEscape)),this.searchButton&&this.handleSearchButtonClick&&this.searchButton.removeEventListener("click",this.handleSearchButtonClick),this.handleInputChange=null,this.handleInputKeydownEnter=null,this.handleInputKeydownEscape=null,this.handleSearchButtonClick=null}async search(e){await this.performSearch(e)}}customElements.get(D)||customElements.define(D,M);const ee=`
1807
+ `}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState(this.resolvedTranslations.missingApiUrlError)}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.client&&this.client.cancelAllRequests(),this.destroyStatsClient(),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydownEnter&&this.inputElement.removeEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape&&window.removeEventListener("keydown",this.handleInputKeydownEscape)),this.searchButton&&this.handleSearchButtonClick&&this.searchButton.removeEventListener("click",this.handleSearchButtonClick),this.detachResultTrackingHandlers(),this.handleInputChange=null,this.handleInputKeydownEnter=null,this.handleInputKeydownEscape=null,this.handleSearchButtonClick=null}async search(e){await this.performSearch(e)}}customElements.get(Y)||customElements.define(Y,R);const fe=`
1792
1808
  /* Modal backdrop */
1793
1809
  .modal-backdrop {
1794
1810
  position: fixed;
@@ -2225,8 +2241,8 @@ a.modal-result-item:focus-visible {
2225
2241
  .modal-container.open {
2226
2242
  animation: modal-slide-in var(--search-snippet-transition) ease-out;
2227
2243
  }
2228
- `,j="search-modal-snippet",te=10,se=50;class V extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"backdrop",null);a(this,"modal",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"footerCount",null);a(this,"isOpen",!1);a(this,"results",[]);a(this,"activeIndex",-1);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleGlobalKeydown",null);a(this,"handleInputChange",null);a(this,"handleInputKeydown",null);a(this,"handleBackdropClick",null);a(this,"savedBodyStyles",null);a(this,"savedHtmlOverflow",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","theme","shortcut","use-meta-key","debounce-ms","hide-branding","show-url","show-date","hide-thumbnails","see-more","request-options"]}connectedCallback(){this.initializeClient(),this.render(),this.attachGlobalKeyboardShortcut(),this.dispatchEvent(b("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Search..."),maxResults:k(this.getAttribute("max-results"),10),debounceMs:k(this.getAttribute("debounce-ms"),300),theme:u(this.getAttribute("theme"),"auto"),shortcut:u(this.getAttribute("shortcut"),"k"),useMetaKey:this.getAttribute("use-meta-key")!=="false",hideBranding:v(this.getAttribute("hide-branding"),!1),showUrl:v(this.getAttribute("show-url"),!1),showDate:v(this.getAttribute("show-date"),!1),hideThumbnails:v(this.getAttribute("hide-thumbnails"),!1),seeMore:u(this.getAttribute("see-more"),"")}}getRequestOptions(){const e=this.getAttribute("request-options");if(e)try{const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("request-options must be a JSON object");return t}catch(t){console.error("SearchModalSnippet: invalid request-options attribute",t);return}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchModalSnippet: api-url attribute is required"),this.client=null,this.showMissingApiUrlError();return}try{this.client=C(e.apiUrl)}catch(t){console.error("SearchModalSnippet:",t)}}render(){const e=this.getProps(),t=c=>this.performSearch(c);this.debouncedSearch=I(t,e.debounceMs||300);const s=document.createElement("style");s.textContent=`${E}
2229
- ${ee}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,o=document.createElement("div");o.innerHTML=`
2244
+ `,X="search-modal-snippet",Z=10,ee=50;class te extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"stats",null);a(this,"backdrop",null);a(this,"modal",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"footerCount",null);a(this,"isOpen",!1);a(this,"results",[]);a(this,"activeIndex",-1);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"translationsOverride",null);a(this,"resolvedTranslations",u(null));a(this,"lastSearchQuery","");a(this,"lastSearchTotal",0);a(this,"handleGlobalKeydown",null);a(this,"handleInputChange",null);a(this,"handleInputKeydown",null);a(this,"handleBackdropClick",null);a(this,"handleResultsContainerClick",null);a(this,"savedBodyStyles",null);a(this,"savedHtmlOverflow",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","max-render-results","theme","shortcut","use-meta-key","debounce-ms","hide-branding","show-url","show-date","hide-thumbnails","see-more","disable-analytics","request-options","translations"]}connectedCallback(){this.syncTranslationsFromAttribute(),this.initializeClient(),this.render(),this.attachGlobalKeyboardShortcut(),this.dispatchEvent(w("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"||e==="disable-analytics"?this.initializeClient():e==="theme"?this.updateTheme(s):e==="translations"&&(this.syncTranslationsFromAttribute(),this.isConnected&&this.rerender()))}get translations(){return this.translationsOverride}set translations(e){this.translationsOverride=e??null,this.resolvedTranslations=u(this.translationsOverride),this.isConnected&&this.rerender()}rerender(){const e=this.isOpen,t=this.inputElement?.value??"";this.isOpen=!1,this.render(),e&&(this.isOpen=!0,this.backdrop?.classList.add("open"),this.modal?.classList.add("open"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.inputElement?.focus()})})),t&&this.inputElement&&(this.inputElement.value=t,t.trim().length>0&&this.performSearch(t.trim()))}syncTranslationsFromAttribute(){if(this.translationsOverride){this.resolvedTranslations=u(this.translationsOverride);return}const e=E(this.getAttribute("translations"),"SearchModalSnippet");this.resolvedTranslations=u(e)}getProps(){const e=this.resolvedTranslations;return{apiUrl:f(this.getAttribute("api-url"),""),placeholder:f(this.getAttribute("placeholder"),e.placeholder),maxResults:C(this.getAttribute("max-results"),ee),maxRenderResults:C(this.getAttribute("max-render-results"),Z),debounceMs:C(this.getAttribute("debounce-ms"),300),theme:f(this.getAttribute("theme"),"auto"),shortcut:f(this.getAttribute("shortcut"),"k"),useMetaKey:this.getAttribute("use-meta-key")!=="false",hideBranding:b(this.getAttribute("hide-branding"),!1),showUrl:b(this.getAttribute("show-url"),!1),showDate:b(this.getAttribute("show-date"),!1),hideThumbnails:b(this.getAttribute("hide-thumbnails"),!1),seeMore:f(this.getAttribute("see-more"),""),disableAnalytics:b(this.getAttribute("disable-analytics"),!1),translations:this.translationsOverride??void 0}}getRequestOptions(){const e=this.getAttribute("request-options");if(e)try{const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("request-options must be a JSON object");return t}catch(t){console.error("SearchModalSnippet: invalid request-options attribute",t);return}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchModalSnippet: api-url attribute is required"),this.client=null,this.destroyStatsClient(),this.showMissingApiUrlError();return}try{this.client=M(e.apiUrl),this.destroyStatsClient(),e.disableAnalytics||(this.stats=new I(e.apiUrl))}catch(t){console.error("SearchModalSnippet:",t)}}destroyStatsClient(){this.stats&&(this.stats.destroy(),this.stats=null)}render(){const e=this.getProps(),t=this.resolvedTranslations,s=h=>this.performSearch(h);this.debouncedSearch=$(s,e.debounceMs||300);const r=document.createElement("style");r.textContent=`${T}
2245
+ ${fe}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,o=document.createElement("div");o.innerHTML=`
2230
2246
  <div class="modal-backdrop" role="presentation"></div>
2231
2247
  <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
2232
2248
  <div class="modal-header">
@@ -2236,8 +2252,8 @@ ${ee}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,o=d
2236
2252
  <input
2237
2253
  type="text"
2238
2254
  class="modal-search-input"
2239
- placeholder="${d(e.placeholder||"Search...")}"
2240
- aria-label="Search"
2255
+ placeholder="${c(e.placeholder||t.placeholder)}"
2256
+ aria-label="${c(t.searchButtonLabel)}"
2241
2257
  aria-autocomplete="list"
2242
2258
  aria-controls="modal-results-list"
2243
2259
  aria-expanded="false"
@@ -2246,7 +2262,7 @@ ${ee}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,o=d
2246
2262
  />
2247
2263
  </div>
2248
2264
  <div class="modal-content">
2249
- <div class="modal-results" id="modal-results-list" role="listbox" aria-label="Search results">
2265
+ <div class="modal-results" id="modal-results-list" role="listbox" aria-label="${c(t.searchResultsAriaLabel)}">
2250
2266
  ${this.renderEmptyState()}
2251
2267
  </div>
2252
2268
  </div>
@@ -2255,42 +2271,43 @@ ${ee}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,o=d
2255
2271
  <div class="modal-footer-hint">
2256
2272
  <kbd class="modal-kbd">↑</kbd>
2257
2273
  <kbd class="modal-kbd">↓</kbd>
2258
- <span>Navigate</span>
2274
+ <span>${c(t.navigateHint)}</span>
2259
2275
  </div>
2260
2276
  <div class="modal-footer-hint">
2261
2277
  <kbd class="modal-kbd">↵</kbd>
2262
- <span>Select</span>
2278
+ <span>${c(t.selectHint)}</span>
2263
2279
  </div>
2264
2280
  <div class="modal-footer-hint">
2265
2281
  <kbd class="modal-kbd">Esc</kbd>
2266
- <span>Close</span>
2282
+ <span>${c(t.closeHint)}</span>
2267
2283
  </div>
2268
2284
  </div>
2269
- ${r}
2285
+ ${n}
2270
2286
  </div>
2271
2287
  </div>
2272
- `,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(o),this.backdrop=this.shadow.querySelector(".modal-backdrop"),this.modal=this.shadow.querySelector(".modal-container"),this.inputElement=this.shadow.querySelector(".modal-search-input"),this.resultsContainer=this.shadow.querySelector(".modal-results"),this.footerCount=this.shadow.querySelector(".modal-results-count"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachGlobalKeyboardShortcut(){const e=this.getProps(),t=e.shortcut?.toLowerCase()||"k";this.handleGlobalKeydown=s=>{(e.useMetaKey&&s.metaKey||s.ctrlKey)&&s.key.toLowerCase()===t&&!this.isOpen&&(s.preventDefault(),this.open())},document.addEventListener("keydown",this.handleGlobalKeydown)}attachEventListeners(){!this.inputElement||!this.backdrop||(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):(this.debouncedSearch?.cancel(),this.currentSearchController?.abort(),this.results=[],this.activeIndex=-1,this.showEmptyState())},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydown=e=>{switch(e.key){case"ArrowDown":e.preventDefault(),this.navigateResults(1);break;case"ArrowUp":e.preventDefault(),this.navigateResults(-1);break;case"Enter":e.preventDefault(),this.selectActiveResult();break;case"Escape":e.preventDefault(),this.close();break}},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleBackdropClick=e=>{e.target===this.backdrop&&this.close()},this.backdrop.addEventListener("click",this.handleBackdropClick))}navigateResults(e){if(this.results.length===0)return;const t=this.activeIndex+e;t<0?this.activeIndex=this.results.length-1:t>=this.results.length?this.activeIndex=0:this.activeIndex=t,this.updateActiveResult()}updateActiveResult(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");e&&(e.forEach((t,s)=>{s===this.activeIndex?(t.classList.add("active"),t.setAttribute("aria-selected","true"),t.scrollIntoView({block:"nearest"})):(t.classList.remove("active"),t.setAttribute("aria-selected","false"))}),this.inputElement&&this.activeIndex>=0?this.inputElement.setAttribute("aria-activedescendant",`result-${this.activeIndex}`):this.inputElement&&this.inputElement.removeAttribute("aria-activedescendant"))}selectActiveResult(){if(this.activeIndex<0||this.activeIndex>=this.results.length){const s=this.inputElement?.value.trim();s&&s.length>0&&this.performSearch(s);return}const e=this.results[this.activeIndex];this.dispatchEvent(b("result-select",{result:e,index:this.activeIndex}));const t=this.resultsContainer?.querySelector(`.modal-result-item[data-index="${this.activeIndex}"]`);t&&e.url&&t.click(),this.close()}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:se,request:this.getRequestOptions()}),s=this.getProps();this.results=t.slice(0,s.maxResults||te),this.activeIndex=this.results.length>0?0:-1,this.displayResults(this.results,e,t.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),o=e.map((f,m)=>this.renderResult(f,m)).join(""),c=s>e.length,l=c?`Showing ${e.length} of ${s} results`:`${s} result${s===1?"":"s"}`,g=r.seeMore&&c?`<a href="${d(r.seeMore+encodeURIComponent(t))}" class="modal-see-more">
2273
- <span>See more results</span>
2288
+ `,this.shadow.innerHTML="",this.shadow.appendChild(r),this.shadow.appendChild(o),this.backdrop=this.shadow.querySelector(".modal-backdrop"),this.modal=this.shadow.querySelector(".modal-container"),this.inputElement=this.shadow.querySelector(".modal-search-input"),this.resultsContainer=this.shadow.querySelector(".modal-results"),this.footerCount=this.shadow.querySelector(".modal-results-count"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachGlobalKeyboardShortcut(){const e=this.getProps(),t=e.shortcut?.toLowerCase()||"k";this.handleGlobalKeydown=s=>{(e.useMetaKey&&s.metaKey||s.ctrlKey)&&s.key.toLowerCase()===t&&!this.isOpen&&(s.preventDefault(),this.open())},document.addEventListener("keydown",this.handleGlobalKeydown)}attachEventListeners(){!this.inputElement||!this.backdrop||(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):(this.debouncedSearch?.cancel(),this.currentSearchController?.abort(),this.results=[],this.activeIndex=-1,this.showEmptyState())},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydown=e=>{switch(e.key){case"ArrowDown":e.preventDefault(),this.navigateResults(1);break;case"ArrowUp":e.preventDefault(),this.navigateResults(-1);break;case"Enter":e.preventDefault(),this.selectActiveResult();break;case"Escape":e.preventDefault(),this.close();break}},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleBackdropClick=e=>{e.target===this.backdrop&&this.close()},this.backdrop.addEventListener("click",this.handleBackdropClick))}navigateResults(e){if(this.results.length===0)return;const t=this.activeIndex+e;t<0?this.activeIndex=this.results.length-1:t>=this.results.length?this.activeIndex=0:this.activeIndex=t,this.updateActiveResult()}updateActiveResult(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");e&&(e.forEach((t,s)=>{s===this.activeIndex?(t.classList.add("active"),t.setAttribute("aria-selected","true"),t.scrollIntoView({block:"nearest"})):(t.classList.remove("active"),t.setAttribute("aria-selected","false"))}),this.inputElement&&this.activeIndex>=0?this.inputElement.setAttribute("aria-activedescendant",`result-${this.activeIndex}`):this.inputElement&&this.inputElement.removeAttribute("aria-activedescendant"))}selectActiveResult(){if(this.activeIndex<0||this.activeIndex>=this.results.length){const s=this.inputElement?.value.trim();s&&s.length>0&&this.performSearch(s);return}const e=this.results[this.activeIndex];this.dispatchEvent(w("result-select",{result:e,index:this.activeIndex}));const t=this.resultsContainer?.querySelector(`.modal-result-item[data-index="${this.activeIndex}"]`);t&&e.url&&t.click(),this.close()}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=this.getProps(),s=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:t.maxResults||ee,request:this.getRequestOptions()});this.results=s.slice(0,t.maxRenderResults||Z),this.activeIndex=this.results.length>0?0:-1,this.lastSearchQuery=e,this.lastSearchTotal=s.length,this.stats?.trackSearch(e,s.length),this.displayResults(this.results,e,s.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=this.resolvedTranslations,o=e.map((m,y)=>this.renderResult(m,y)).join(""),h=s>e.length,d=h?x(n.resultsCountOverflow,{n:e.length,total:s}):x(s===1?n.modalResultsCount:n.modalResultsCountPlural,{n:s}),p=r.seeMore&&h?`<a href="${c(r.seeMore+encodeURIComponent(t))}" class="modal-see-more">
2289
+ <span>${c(n.seeMoreResults)}</span>
2274
2290
  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
2275
- </a>`:"";this.resultsContainer.innerHTML=o+g,this.footerCount&&(this.footerCount.textContent=l),this.inputElement&&this.inputElement.setAttribute("aria-expanded","true"),this.attachResultHandlers(),this.updateActiveResult()}renderResult(e,t){const s=this.getProps(),r=s.hideThumbnails?"":this.renderResultImage(e.image,e.title),o=e.url?d(e.url):"#",c=e.url?d(z(e.url)):"",l=s.showDate&&e.timestamp!==void 0?`<div class="modal-result-date">${d(T(e.timestamp))}</div>`:"",g=s.showUrl&&e.url||l?`<div class="modal-result-metadata">
2276
- ${s.showUrl&&e.url?`<span class="modal-result-url">${c}</span>`:'<span class="modal-result-url modal-result-url-empty"></span>'}
2277
- ${l}
2291
+ </a>`:"";this.resultsContainer.innerHTML=o+p,this.footerCount&&(this.footerCount.textContent=d),this.inputElement&&this.inputElement.setAttribute("aria-expanded","true"),this.attachResultHandlers(),this.updateActiveResult()}renderResult(e,t){const s=this.getProps(),r=s.hideThumbnails?"":this.renderResultImage(e.image,e.title),n=e.url?c(e.url):"#",o=e.url?c(q(e.url)):"",h=s.showDate&&e.timestamp!==void 0?`<div class="modal-result-date">${c(O(e.timestamp))}</div>`:"",d=s.showUrl&&e.url||h?`<div class="modal-result-metadata">
2292
+ ${s.showUrl&&e.url?`<span class="modal-result-url">${o}</span>`:'<span class="modal-result-url modal-result-url-empty"></span>'}
2293
+ ${h}
2278
2294
  </div>`:"";return`
2279
2295
  <a
2280
- href="${o}"
2296
+ href="${n}"
2281
2297
  class="modal-result-item${t===this.activeIndex?" active":""}"
2282
2298
  role="option"
2283
2299
  id="result-${t}"
2284
2300
  aria-selected="${t===this.activeIndex}"
2285
2301
  tabindex="-1"
2286
2302
  data-index="${t}"
2287
- data-url="${d(e.url||"")}"
2303
+ data-result-id="${c(e.id||"")}"
2304
+ data-url="${c(e.url||"")}"
2288
2305
  >
2289
2306
  ${r}
2290
2307
  <div class="modal-result-content">
2291
- <div class="modal-result-title">${d(e.title||"")}</div>
2292
- ${e.description?`<div class="modal-result-description">${d(e.description)}</div>`:""}
2293
- ${g}
2308
+ <div class="modal-result-title">${c(e.title||"")}</div>
2309
+ ${e.description?`<div class="modal-result-description">${c(e.description)}</div>`:""}
2310
+ ${d}
2294
2311
  </div>
2295
2312
  </a>
2296
2313
  `}renderResultImage(e,t){const s='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>';return e?`
@@ -2299,8 +2316,8 @@ ${ee}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,o=d
2299
2316
  <div class="modal-result-image-placeholder" style="display: none;">${s}</div>
2300
2317
  <img
2301
2318
  class="modal-result-image"
2302
- src="${d(e)}"
2303
- alt="${d(t)}"
2319
+ src="${c(e)}"
2320
+ alt="${c(t)}"
2304
2321
  loading="lazy"
2305
2322
  />
2306
2323
  </div>
@@ -2308,31 +2325,31 @@ ${ee}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,o=d
2308
2325
  <div class="modal-result-image-container">
2309
2326
  <div class="modal-result-image-placeholder">${s}</div>
2310
2327
  </div>
2311
- `}attachResultHandlers(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");if(!e)return;e.forEach((s,r)=>{s.getAttribute("href")==="#"&&s.addEventListener("click",c=>{c.preventDefault()}),s.addEventListener("mouseenter",()=>{this.activeIndex=r,this.updateActiveResult()})}),this.resultsContainer?.querySelectorAll(".modal-result-image")?.forEach(s=>{s.addEventListener("load",()=>{s.classList.add("loaded"),s.closest(".modal-result-image-container")?.querySelector(".modal-result-image-loading")?.remove()}),s.addEventListener("error",()=>{const r=s.closest(".modal-result-image-container");r?.querySelector(".modal-result-image-loading")?.remove();const o=r?.querySelector(".modal-result-image-placeholder");o&&(o.style.display="flex"),s.style.display="none"})})}renderEmptyState(){return`
2328
+ `}attachResultHandlers(){this.detachResultsContainerClick();const e=this.resultsContainer;if(!e)return;this.handleResultsContainerClick=r=>{const n=r.target;if(!n)return;const o=n.closest(".modal-result-item");if(o){o.getAttribute("href")==="#"&&r.preventDefault();const p=o.getAttribute("data-index"),m=o.getAttribute("data-result-id")??"",y=p!==null?Number.parseInt(p,10):Number.NaN;!Number.isNaN(y)&&m&&this.stats?.trackClick(this.lastSearchQuery,this.lastSearchTotal,m,y);return}n.closest(".modal-see-more")&&this.stats?.trackViewMore(this.lastSearchQuery,this.lastSearchTotal)},e.addEventListener("click",this.handleResultsContainerClick),e.querySelectorAll(".modal-result-item").forEach((r,n)=>{r.addEventListener("mouseenter",()=>{this.activeIndex=n,this.updateActiveResult()})}),e.querySelectorAll(".modal-result-image").forEach(r=>{r.addEventListener("load",()=>{r.classList.add("loaded"),r.closest(".modal-result-image-container")?.querySelector(".modal-result-image-loading")?.remove()}),r.addEventListener("error",()=>{const n=r.closest(".modal-result-image-container");n?.querySelector(".modal-result-image-loading")?.remove();const o=n?.querySelector(".modal-result-image-placeholder");o&&(o.style.display="flex"),r.style.display="none"})})}detachResultsContainerClick(){this.resultsContainer&&this.handleResultsContainerClick&&this.resultsContainer.removeEventListener("click",this.handleResultsContainerClick),this.handleResultsContainerClick=null}renderEmptyState(){const e=this.resolvedTranslations;return`
2312
2329
  <div class="modal-empty">
2313
2330
  <svg class="modal-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
2314
2331
  <circle cx="11" cy="11" r="8"></circle>
2315
2332
  <path d="m21 21-4.35-4.35"></path>
2316
2333
  </svg>
2317
- <div class="modal-empty-description">Start typing to search</div>
2334
+ <div class="modal-empty-description">${c(e.modalEmptyStateDescription)}</div>
2318
2335
  </div>
2319
- `}showEmptyState(){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=this.renderEmptyState(),this.footerCount&&(this.footerCount.textContent=""),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false"))}showLoadingState(){this.resultsContainer&&(this.clearLoadingInterval(),this.loadingMessageIndex=Math.floor(Math.random()*h.length),this.resultsContainer.innerHTML=`
2336
+ `}showEmptyState(){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=this.renderEmptyState(),this.footerCount&&(this.footerCount.textContent=""),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false"))}showLoadingState(){if(!this.resultsContainer)return;this.clearLoadingInterval();const e=this.resolvedTranslations.loadingMessages,t=this.resolvedTranslations;this.loadingMessageIndex=Math.floor(Math.random()*e.length),this.resultsContainer.innerHTML=`
2320
2337
  <div class="modal-loading">
2321
- <div class="loading" aria-label="Loading"></div>
2322
- <div class="loading-text loading-text-animate">${h[this.loadingMessageIndex]}</div>
2338
+ <div class="loading" aria-label="${c(t.loadingAriaLabel)}"></div>
2339
+ <div class="loading-text loading-text-animate">${c(e[this.loadingMessageIndex])}</div>
2323
2340
  </div>
2324
- `,this.footerCount&&(this.footerCount.textContent=h[this.loadingMessageIndex]),this.startLoadingInterval())}startLoadingInterval(){this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%h.length;const e=this.resultsContainer?.querySelector(".loading-text");e&&(e.classList.remove("loading-text-animate"),e.offsetWidth,e.textContent=h[this.loadingMessageIndex],e.classList.add("loading-text-animate")),this.footerCount&&(this.footerCount.textContent=h[this.loadingMessageIndex])},2500)}clearLoadingInterval(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}showNoResultsState(e){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
2341
+ `,this.footerCount&&(this.footerCount.textContent=e[this.loadingMessageIndex]),this.startLoadingInterval()}startLoadingInterval(){this.loadingMessageInterval=setInterval(()=>{const e=this.resolvedTranslations.loadingMessages;this.loadingMessageIndex=(this.loadingMessageIndex+1)%e.length;const t=this.resultsContainer?.querySelector(".loading-text");t&&(t.classList.remove("loading-text-animate"),t.offsetWidth,t.textContent=e[this.loadingMessageIndex],t.classList.add("loading-text-animate")),this.footerCount&&(this.footerCount.textContent=e[this.loadingMessageIndex])},A)}clearLoadingInterval(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}showNoResultsState(e){if(this.clearLoadingInterval(),!this.resultsContainer)return;const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
2325
2342
  <div class="modal-empty">
2326
2343
  <svg class="modal-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
2327
2344
  <circle cx="11" cy="11" r="8"></circle>
2328
2345
  <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
2329
2346
  </svg>
2330
- <div class="modal-empty-title">No results found</div>
2331
- <div class="modal-empty-description">No results for "${d(e)}"</div>
2347
+ <div class="modal-empty-title">${c(t.modalNoResultsTitle)}</div>
2348
+ <div class="modal-empty-description">${c(x(t.modalNoResultsDescription,{query:e}))}</div>
2332
2349
  </div>
2333
- `,this.footerCount&&(this.footerCount.textContent="0 results"),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false"))}showErrorState(e){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
2350
+ `,this.footerCount&&(this.footerCount.textContent=t.modalResultsCountZero),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false")}showErrorState(e){if(this.clearLoadingInterval(),!this.resultsContainer)return;const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
2334
2351
  <div class="error">
2335
- <strong>Error:</strong> ${d(e)}
2352
+ <strong>${c(t.errorPrefix)}</strong> ${c(e)}
2336
2353
  </div>
2337
- `,this.footerCount&&(this.footerCount.textContent="Error"))}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState("The api-url attribute is required. Please provide a valid API URL.")}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}lockBodyScroll(){const e=window.scrollY;this.savedBodyStyles={overflow:document.body.style.overflow,position:document.body.style.position,top:document.body.style.top,width:document.body.style.width,scrollbarGutter:document.body.style.scrollbarGutter},this.savedHtmlOverflow=document.documentElement.style.overflow,document.body.style.scrollbarGutter="stable",document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%"}unlockBodyScroll(){if(!this.savedBodyStyles)return;const e=Math.abs(Number.parseInt(document.body.style.top||"0",10));document.documentElement.style.overflow=this.savedHtmlOverflow||"",document.body.style.overflow=this.savedBodyStyles.overflow,document.body.style.position=this.savedBodyStyles.position,document.body.style.top=this.savedBodyStyles.top,document.body.style.width=this.savedBodyStyles.width,document.body.style.scrollbarGutter=this.savedBodyStyles.scrollbarGutter||"",window.scrollTo(0,e),this.savedBodyStyles=null,this.savedHtmlOverflow=null}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.handleGlobalKeydown&&(document.removeEventListener("keydown",this.handleGlobalKeydown),this.handleGlobalKeydown=null),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.backdrop&&this.handleBackdropClick&&this.backdrop.removeEventListener("click",this.handleBackdropClick),this.handleInputChange=null,this.handleInputKeydown=null,this.handleBackdropClick=null,this.client&&this.client.cancelAllRequests()}open(){this.isOpen||(this.isOpen=!0,this.backdrop?.classList.add("open"),this.modal?.classList.add("open"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.inputElement?.focus()})}),this.lockBodyScroll(),this.dispatchEvent(b("open",void 0)))}close(){this.isOpen&&(this.isOpen=!1,this.backdrop?.classList.remove("open"),this.modal?.classList.remove("open"),this.inputElement&&(this.inputElement.value=""),this.results=[],this.activeIndex=-1,this.showEmptyState(),this.unlockBodyScroll(),this.dispatchEvent(b("close",void 0)))}toggle(){this.isOpen?this.close():this.open()}async search(e){this.isOpen||this.open(),this.inputElement&&(this.inputElement.value=e),await this.performSearch(e)}getResults(){return[...this.results]}isModalOpen(){return this.isOpen}}customElements.get(j)||customElements.define(j,V),p.AISearchClient=R,p.ChatBubbleSnippet=_,p.ChatPageSnippet=P,p.SearchBarSnippet=M,p.SearchModalSnippet=V,p.default=M,Object.defineProperties(p,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
2354
+ `,this.footerCount&&(this.footerCount.textContent=t.modalResultsCountError)}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState(this.resolvedTranslations.missingApiUrlError)}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}lockBodyScroll(){const e=window.scrollY;this.savedBodyStyles={overflow:document.body.style.overflow,position:document.body.style.position,top:document.body.style.top,width:document.body.style.width,scrollbarGutter:document.body.style.scrollbarGutter},this.savedHtmlOverflow=document.documentElement.style.overflow,document.body.style.scrollbarGutter="stable",document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%"}unlockBodyScroll(){if(!this.savedBodyStyles)return;const e=Math.abs(Number.parseInt(document.body.style.top||"0",10));document.documentElement.style.overflow=this.savedHtmlOverflow||"",document.body.style.overflow=this.savedBodyStyles.overflow,document.body.style.position=this.savedBodyStyles.position,document.body.style.top=this.savedBodyStyles.top,document.body.style.width=this.savedBodyStyles.width,document.body.style.scrollbarGutter=this.savedBodyStyles.scrollbarGutter||"",window.scrollTo(0,e),this.savedBodyStyles=null,this.savedHtmlOverflow=null}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.handleGlobalKeydown&&(document.removeEventListener("keydown",this.handleGlobalKeydown),this.handleGlobalKeydown=null),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.backdrop&&this.handleBackdropClick&&this.backdrop.removeEventListener("click",this.handleBackdropClick),this.detachResultsContainerClick(),this.handleInputChange=null,this.handleInputKeydown=null,this.handleBackdropClick=null,this.destroyStatsClient(),this.client&&this.client.cancelAllRequests()}open(){this.isOpen||(this.isOpen=!0,this.backdrop?.classList.add("open"),this.modal?.classList.add("open"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.inputElement?.focus()})}),this.lockBodyScroll(),this.dispatchEvent(w("open",void 0)))}close(){this.isOpen&&(this.isOpen=!1,this.backdrop?.classList.remove("open"),this.modal?.classList.remove("open"),this.inputElement&&(this.inputElement.value=""),this.results=[],this.activeIndex=-1,this.showEmptyState(),this.unlockBodyScroll(),this.dispatchEvent(w("close",void 0)))}toggle(){this.isOpen?this.close():this.open()}async search(e){this.isOpen||this.open(),this.inputElement&&(this.inputElement.value=e),await this.performSearch(e)}getResults(){return[...this.results]}isModalOpen(){return this.isOpen}}customElements.get(X)||customElements.define(X,te),g.AISearchClient=P,g.ChatBubbleSnippet=F,g.ChatPageSnippet=G,g.DEFAULT_TRANSLATIONS=v,g.SearchBarSnippet=R,g.SearchModalSnippet=te,g.StatsClient=I,g.default=R,g.mergeTranslations=u,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
2338
2355
  //# sourceMappingURL=search-snippet.umd.js.map