@cloudflare/ai-search-snippet 0.0.32 → 0.0.33
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,4 +1,4 @@
|
|
|
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","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,
|
|
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","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}));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(`
|
|
2
2
|
|
|
3
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">
|
|
4
4
|
<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"/>
|
|
@@ -807,7 +807,7 @@
|
|
|
807
807
|
</div>
|
|
808
808
|
</div>
|
|
809
809
|
</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
|
|
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
811
|
${B}
|
|
812
812
|
${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
813
|
.chat-bubble-widget {
|
|
@@ -988,7 +988,7 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
|
|
|
988
988
|
<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
989
|
<strong>Error:</strong> The <code>api-url</code> attribute is required. Please provide a valid API URL.
|
|
990
990
|
</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,
|
|
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
992
|
${B}
|
|
993
993
|
${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
994
|
:host {
|
|
@@ -1309,7 +1309,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1309
1309
|
<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
1310
|
<strong>Error:</strong> The <code>api-url</code> attribute is required. Please provide a valid API URL.
|
|
1311
1311
|
</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(
|
|
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`
|
|
1313
1313
|
<div class="chat-list-item ${t?"active":""}" data-session-id="${e.id}">
|
|
1314
1314
|
<div class="chat-list-item-content">
|
|
1315
1315
|
<div class="chat-list-item-title">${this.escapeHTML(e.title)}</div>
|
|
@@ -1321,7 +1321,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1321
1321
|
</svg>
|
|
1322
1322
|
</button>
|
|
1323
1323
|
</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(
|
|
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=`
|
|
1325
1325
|
/* Search view states */
|
|
1326
1326
|
.search-view {
|
|
1327
1327
|
transition: var(--search-snippet-transition-slow);
|
|
@@ -2334,5 +2334,5 @@ ${ee}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,o=d
|
|
|
2334
2334
|
<div class="error">
|
|
2335
2335
|
<strong>Error:</strong> ${d(e)}
|
|
2336
2336
|
</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},this.savedHtmlOverflow=document.documentElement.style.overflow,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,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=
|
|
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},this.savedHtmlOverflow=document.documentElement.style.overflow,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,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"}})}));
|
|
2338
2338
|
//# sourceMappingURL=search-snippet.umd.js.map
|