@cloudflare/ai-search-snippet 0.0.33 → 0.0.35

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,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(`
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,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(`
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"/>
@@ -1691,7 +1691,7 @@ a.search-result-item:focus-visible {
1691
1691
  border-radius: 2px;
1692
1692
  font-weight: var(--search-snippet-font-weight-medium);
1693
1693
  }
1694
- `,D="search-bar-snippet",Z=10,Q=100;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}
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
1695
  ${X}`,this.container=document.createElement("div"),this.container.className="container",this.container.innerHTML=`
1696
1696
  <div class="search-view">
1697
1697
  <div class="search-input-wrapper">
@@ -2225,7 +2225,7 @@ a.modal-result-item:focus-visible {
2225
2225
  .modal-container.open {
2226
2226
  animation: modal-slide-in var(--search-snippet-transition) ease-out;
2227
2227
  }
2228
- `,j="search-modal-snippet",te=10,se=100;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}
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
2229
  ${ee}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,o=document.createElement("div");o.innerHTML=`
2230
2230
  <div class="modal-backdrop" role="presentation"></div>
2231
2231
  <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">