@cloudflare/ai-search-snippet 0.0.29 → 0.0.30
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 Z=Object.defineProperty;var Q=(p,h,w)=>h in p?Z(p,h,{enumerable:!0,configurable:!0,writable:!0,value:w}):p[h]=w;var a=(p,h,w)=>Q(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 L(c,i){let e;
|
|
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 Z=Object.defineProperty;var Q=(p,h,w)=>h in p?Z(p,h,{enumerable:!0,configurable:!0,writable:!0,value:w}):p[h]=w;var a=(p,h,w)=>Q(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 L(c,i){let e;function t(...s){clearTimeout(e),e=setTimeout(()=>{c(...s)},i)}return t.cancel=()=>clearTimeout(e),t}function d(c){const i=document.createElement("div");return i.textContent=c,i.innerHTML}function I(c){return new DOMParser().parseFromString(c,"text/html").documentElement.textContent||""}function O(c){const i=new Date(c),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 z(c){return new Date(c).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function T(c="id"){return`${c}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function u(c,i){return c!==null?c:i}function m(c,i){return c===null?i:c==="true"||c===""}function x(c,i){if(c===null)return i;const e=Number.parseInt(c,10);return Number.isNaN(e)?i:e}function v(c,i){return new CustomEvent(c,{detail:i,bubbles:!0,composed:!0,cancelable:!0})}function k(c){if(!c)throw new Error("API URL is required");return new A(c)}class A{constructor(i){a(this,"activeRequests",new Map);a(this,"baseUrl");this.baseUrl=i.replace(/\/$/,"")}request(i={},e,t){const s=e==="search"?"snippet-search":"snippet-chat-completions";return fetch(`${this.baseUrl}/${e}`,{method:"POST",body:JSON.stringify({messages:[{role:"user",content:i.query}],stream:i.streaming,max_results:i.maxResults,...e==="search"&&{ai_search_options:{retrieval:{metadata_only:!0}}}}),headers:{"Content-Type":"application/json","cf-ai-search-source":s},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({query:i,streaming:!1,maxResults:e.maxResults||30},"search",r);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(l=>({type:"result",id:l.id,title:I(l.item.metadata?.title),description:l.item.metadata?.description?I(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 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({query:i,streaming:!0},"ai-search",r);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");let o="";const l=n.body.getReader(),b=new TextDecoder;for(;;){const{done:g,value:M}=await l.read();if(g)break;const J=b.decode(M,{stream:!0});o+=J}yield{type:"result",id:"",title:"",description:o.replaceAll("data: ","").trim().split(`
|
|
2
2
|
|
|
3
3
|
`).map(g=>JSON.parse(g)).map(g=>g.response).join(""),url:"",metadata:{}}}async*chat(i,e){const t=new AbortController,s=e?.signal||t.signal,r=await this.request({query:i,streaming:!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(o=>o.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 C=`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"/>
|
|
@@ -2269,7 +2269,7 @@ ${Y}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,n=do
|
|
|
2269
2269
|
${r}
|
|
2270
2270
|
</div>
|
|
2271
2271
|
</div>
|
|
2272
|
-
`,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(n),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.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(v("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,{streaming:!1,signal:this.currentSearchController.signal,maxResults:X}),s=this.getProps();this.results=t.slice(0,s.maxResults||W),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(console.log({results:e,query:t,totalResults:s}),this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=e.map((f,g)=>this.renderResult(f,g)).join(""),o=s>e.length,l=o?`Showing ${e.length} of ${s} results`:`${s} result${s===1?"":"s"}`,b=r.seeMore&&o?`<a href="${d(r.seeMore+encodeURIComponent(t))}" class="modal-see-more">
|
|
2272
|
+
`,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(n),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(v("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,{streaming:!1,signal:this.currentSearchController.signal,maxResults:X}),s=this.getProps();this.results=t.slice(0,s.maxResults||W),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(console.log({results:e,query:t,totalResults:s}),this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=e.map((f,g)=>this.renderResult(f,g)).join(""),o=s>e.length,l=o?`Showing ${e.length} of ${s} results`:`${s} result${s===1?"":"s"}`,b=r.seeMore&&o?`<a href="${d(r.seeMore+encodeURIComponent(t))}" class="modal-see-more">
|
|
2273
2273
|
<span>See more results</span>
|
|
2274
2274
|
<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
2275
|
</a>`:"";this.resultsContainer.innerHTML=n+b,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),n=e.url?d(e.url):"#",o=s.showDate&&e.timestamp!==void 0?`<div class="modal-result-date">${d(z(e.timestamp))}</div>`:"",l=s.showUrl&&e.url||o?`<div class="modal-result-metadata">
|