New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@oramacloud/client

Package Overview
Dependencies
Maintainers
6
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@oramacloud/client - npm Package Compare versions

Comparing version 1.2.0 to 1.2.1

7

dist/index.global.js

@@ -1,5 +0,6 @@

"use strict";var OramaClient=(()=>{var at=Object.create;var k=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var dt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ht=(t,e)=>{for(var n in e)k(t,n,{get:e[n],enumerable:!0})},te=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ut(e))!pt.call(t,o)&&o!==n&&k(t,o,{get:()=>e[o],enumerable:!(r=ct(e,o))||r.enumerable});return t};var F=(t,e,n)=>(n=t!=null?at(lt(t)):{},te(e||!t||!t.__esModule?k(n,"default",{value:t,enumerable:!0}):n,t)),ft=t=>te(k({},"__esModule",{value:!0}),t);var le=S(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.output=h.exists=h.hash=h.bytes=h.bool=h.number=void 0;function M(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}h.number=M;function ie(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}h.bool=ie;function V(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}h.bytes=V;function ae(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");M(t.outputLen),M(t.blockLen)}h.hash=ae;function ce(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}h.exists=ce;function ue(t,e){V(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}h.output=ue;var mt={number:M,bool:ie,bytes:V,hash:ae,exists:ce,output:ue};h.default=mt});var he=S(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.add=f.toBig=f.split=f.fromBig=void 0;var D=BigInt(2**32-1),K=BigInt(32);function Y(t,e=!1){return e?{h:Number(t&D),l:Number(t>>K&D)}:{h:Number(t>>K&D)|0,l:Number(t&D)|0}}f.fromBig=Y;function pe(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let o=0;o<t.length;o++){let{h:i,l:s}=Y(t[o],e);[n[o],r[o]]=[i,s]}return[n,r]}f.split=pe;var yt=(t,e)=>BigInt(t>>>0)<<K|BigInt(e>>>0);f.toBig=yt;var gt=(t,e,n)=>t>>>n,bt=(t,e,n)=>t<<32-n|e>>>n,wt=(t,e,n)=>t>>>n|e<<32-n,St=(t,e,n)=>t<<32-n|e>>>n,_t=(t,e,n)=>t<<64-n|e>>>n-32,Ot=(t,e,n)=>t>>>n-32|e<<64-n,At=(t,e)=>e,xt=(t,e)=>t,Et=(t,e,n)=>t<<n|e>>>32-n,Tt=(t,e,n)=>e<<n|t>>>32-n,It=(t,e,n)=>e<<n-32|t>>>64-n,Ct=(t,e,n)=>t<<n-32|e>>>64-n;function de(t,e,n,r){let o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}f.add=de;var vt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Pt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Rt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),kt=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Mt=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Dt=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0,Nt={fromBig:Y,split:pe,toBig:f.toBig,shrSH:gt,shrSL:bt,rotrSH:wt,rotrSL:St,rotrBH:_t,rotrBL:Ot,rotr32H:At,rotr32L:xt,rotlSH:Et,rotlSL:Tt,rotlBH:It,rotlBL:Ct,add:de,add3L:vt,add3H:Pt,add4L:Rt,add4H:kt,add5H:Dt,add5L:Mt};f.default=Nt});var fe=S(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.crypto=void 0;var N=dt("node:crypto");L.crypto=N&&typeof N=="object"&&"webcrypto"in N?N.webcrypto:void 0});var ye=S(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.randomBytes=c.wrapXOFConstructorWithOpts=c.wrapConstructorWithOpts=c.wrapConstructor=c.checkOpts=c.Hash=c.concatBytes=c.toBytes=c.utf8ToBytes=c.asyncLoop=c.nextTick=c.hexToBytes=c.bytesToHex=c.isLE=c.rotr=c.createView=c.u32=c.u8=void 0;var q=fe(),W=t=>t instanceof Uint8Array,Lt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Lt;var Bt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Bt;var jt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=jt;var Ut=(t,e)=>t<<32-e|t>>>e;c.rotr=Ut;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!c.isLE)throw new Error("Non little-endian hardware is not supported");var $t=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ht(t){if(!W(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=$t[t[n]];return e}c.bytesToHex=Ht;function Ft(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){let o=r*2,i=t.slice(o,o+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");n[r]=s}return n}c.hexToBytes=Ft;var Gt=async()=>{};c.nextTick=Gt;async function Vt(t,e,n){let r=Date.now();for(let o=0;o<t;o++){n(o);let i=Date.now()-r;i>=0&&i<e||(await(0,c.nextTick)(),r+=i)}}c.asyncLoop=Vt;function me(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}c.utf8ToBytes=me;function B(t){if(typeof t=="string"&&(t=me(t)),!W(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}c.toBytes=B;function Kt(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;return t.forEach(r=>{if(!W(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}c.concatBytes=Kt;var X=class{clone(){return this._cloneInto()}};c.Hash=X;var Yt=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function qt(t,e){if(e!==void 0&&(typeof e!="object"||!Yt(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}c.checkOpts=qt;function Xt(t){let e=r=>t().update(B(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}c.wrapConstructor=Xt;function Wt(t){let e=(r,o)=>t(o).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}c.wrapConstructorWithOpts=Wt;function zt(t){let e=(r,o)=>t(o).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}c.wrapXOFConstructorWithOpts=zt;function Jt(t=32){if(q.crypto&&typeof q.crypto.getRandomValues=="function")return q.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}c.randomBytes=Jt});var xe=S(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.shake256=l.shake128=l.keccak_512=l.keccak_384=l.keccak_256=l.keccak_224=l.sha3_512=l.sha3_384=l.sha3_256=l.sha3_224=l.Keccak=l.keccakP=void 0;var _=le(),E=he(),x=ye(),[we,Se,_e]=[[],[],[]],Zt=BigInt(0),A=BigInt(1),Qt=BigInt(2),en=BigInt(7),tn=BigInt(256),nn=BigInt(113);for(let t=0,e=A,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],we.push(2*(5*r+n)),Se.push((t+1)*(t+2)/2%64);let o=Zt;for(let i=0;i<7;i++)e=(e<<A^(e>>en)*nn)%tn,e&Qt&&(o^=A<<(A<<BigInt(i))-A);_e.push(o)}var[rn,on]=E.default.split(_e,!0),ge=(t,e,n)=>n>32?E.default.rotlBH(t,e,n):E.default.rotlSH(t,e,n),be=(t,e,n)=>n>32?E.default.rotlBL(t,e,n):E.default.rotlSL(t,e,n);function Oe(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let s=0;s<10;s++)n[s]=t[s]^t[s+10]^t[s+20]^t[s+30]^t[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,u=(s+2)%10,p=n[u],d=n[u+1],m=ge(p,d,1)^n[a],y=be(p,d,1)^n[a+1];for(let g=0;g<50;g+=10)t[s+g]^=m,t[s+g+1]^=y}let o=t[2],i=t[3];for(let s=0;s<24;s++){let a=Se[s],u=ge(o,i,a),p=be(o,i,a),d=we[s];o=t[d],i=t[d+1],t[d]=u,t[d+1]=p}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)n[a]=t[s+a];for(let a=0;a<10;a++)t[s+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=rn[r],t[1]^=on[r]}n.fill(0)}l.keccakP=Oe;var T=class t extends x.Hash{constructor(e,n,r,o=!1,i=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,_.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,x.u32)(this.state)}keccak(){Oe(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){_.default.exists(this);let{blockLen:n,state:r}=this;e=(0,x.toBytes)(e);let o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);for(let a=0;a<s;a++)r[this.pos++]^=e[i++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:o}=this;e[r]^=n,n&128&&r===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){_.default.exists(this,!1),_.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,i=e.length;o<i;){this.posOut>=r&&this.keccak();let s=Math.min(r-this.posOut,i-o);e.set(n.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return _.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(_.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:o,rounds:i,enableXOF:s}=this;return e||(e=new t(n,r,o,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=o,e.enableXOF=s,e.destroyed=this.destroyed,e}};l.Keccak=T;var b=(t,e,n)=>(0,x.wrapConstructor)(()=>new T(e,t,n));l.sha3_224=b(6,144,224/8);l.sha3_256=b(6,136,256/8);l.sha3_384=b(6,104,384/8);l.sha3_512=b(6,72,512/8);l.keccak_224=b(1,144,224/8);l.keccak_256=b(1,136,256/8);l.keccak_384=b(1,104,384/8);l.keccak_512=b(1,72,512/8);var Ae=(t,e,n)=>(0,x.wrapXOFConstructorWithOpts)((r={})=>new T(e,t,r.dkLen===void 0?n:r.dkLen,!0));l.shake128=Ae(31,168,128/8);l.shake256=Ae(31,136,256/8)});var ke=S((Mn,w)=>{"use strict";var{sha3_512:sn}=xe(),Te=24,I=32,z=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Ie(t){let e=8n,n=0n;for(let r of t.values()){let o=BigInt(r);n=(n<<e)+o}return n}var Ce=(t="")=>Ie(sn(t)).toString(36).slice(1),Ee=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),an=t=>Ee[Math.floor(t()*Ee.length)],ve=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+z(I,e):z(I,e);return Ce(r).substring(0,I)},Pe=t=>()=>t++,cn=476782367,Re=({random:t=Math.random,counter:e=Pe(Math.floor(t()*cn)),length:n=Te,fingerprint:r=ve({random:t})}={})=>function(){let i=an(t),s=Date.now().toString(36),a=e().toString(36),u=z(n,t),p=`${s+u+a+r}`;return`${i+Ce(p).substring(1,n)}`},un=Re(),ln=(t,{minLength:e=2,maxLength:n=I}={})=>{let r=t.length,o=/^[0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&o.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:Te,bigLength:I});w.exports.init=Re;w.exports.createId=un;w.exports.bufToBigInt=Ie;w.exports.createCounter=Pe;w.exports.createFingerprint=ve;w.exports.isCuid=ln});var j=S((Dn,C)=>{"use strict";var{createId:pn,init:dn,getConstants:hn,isCuid:fn}=ke();C.exports.createId=pn;C.exports.init=dn;C.exports.getConstants=hn;C.exports.isCuid=fn});var _n={};ht(_n,{OramaClient:()=>Q,OramaProxy:()=>ee});var An=Date.now().toString().slice(5);var ne=BigInt(1e3),re=BigInt(1e6),oe=BigInt(1e9);async function se(t){return typeof t=="number"&&(t=BigInt(t)),t<ne?`${t}ns`:t<re?`${t/ne}\u03BCs`:t<oe?`${t/re}ms`:`${t/oe}s`}async function G(t){return{raw:Number(t),formatted:await se(t)}}var Ke=F(j(),1);var Ve=F(j(),1);var Fe=F(j(),1);var Me="https://answer.api.orama.com",v="https://secure-proxy.orama.run",De="/init",Ne="/chat",Le="/summary",Be="/query",J="orama_user_id",je="server-side-session";var $e="1.2.0";var He={name:"@oramacloud/client",version:$e,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function P(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var O=class t{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let n=new t(e);return n.start(),n}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:He.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};P(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}static getUserID(){if(typeof localStorage>"u")return je;let e=localStorage.getItem(J);if(e)return e;let n=(0,Fe.createId)();return localStorage.setItem(J,n),n}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function Ge(t){let e=t.split(`
`),n={};for(let r of e){let[o,i]=r.split(": ");o&&(n[o]=i)}return n}var U=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${Me}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,Ve.createId)(),this.userID=O.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let o of n)r=o;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let n=new URLSearchParams;n.append("type",this.inferenceType),n.append("messages",JSON.stringify(this.messages)),n.append("query",e.term??""),n.append("conversationId",this.conversationID),n.append("userId",this.userID),n.append("endpoint",this.oramaClient.endpoint),n.append("searchParams",JSON.stringify(e));let r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),signal:this.abortController.signal});if(!r.ok||!r.body)throw new Error(r.statusText);let o=r.body.getReader(),i=new TextDecoder,s=[],a="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let u=this.messages.at(-1);try{for(;;){let{value:p,done:d}=await o.read();if(d)break;a+=i.decode(p,{stream:!0});let m;for(;(m=a.indexOf(`
"use strict";var OramaClient=(()=>{var at=Object.create;var M=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var dt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ht=(t,e)=>{for(var n in e)M(t,n,{get:e[n],enumerable:!0})},te=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ut(e))!pt.call(t,o)&&o!==n&&M(t,o,{get:()=>e[o],enumerable:!(r=ct(e,o))||r.enumerable});return t};var F=(t,e,n)=>(n=t!=null?at(lt(t)):{},te(e||!t||!t.__esModule?M(n,"default",{value:t,enumerable:!0}):n,t)),ft=t=>te(M({},"__esModule",{value:!0}),t);var le=S(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.output=h.exists=h.hash=h.bytes=h.bool=h.number=void 0;function R(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}h.number=R;function ie(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}h.bool=ie;function V(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}h.bytes=V;function ae(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");R(t.outputLen),R(t.blockLen)}h.hash=ae;function ce(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}h.exists=ce;function ue(t,e){V(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}h.output=ue;var mt={number:R,bool:ie,bytes:V,hash:ae,exists:ce,output:ue};h.default=mt});var he=S(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.add=f.toBig=f.split=f.fromBig=void 0;var k=BigInt(2**32-1),K=BigInt(32);function Y(t,e=!1){return e?{h:Number(t&k),l:Number(t>>K&k)}:{h:Number(t>>K&k)|0,l:Number(t&k)|0}}f.fromBig=Y;function pe(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let o=0;o<t.length;o++){let{h:i,l:s}=Y(t[o],e);[n[o],r[o]]=[i,s]}return[n,r]}f.split=pe;var yt=(t,e)=>BigInt(t>>>0)<<K|BigInt(e>>>0);f.toBig=yt;var gt=(t,e,n)=>t>>>n,bt=(t,e,n)=>t<<32-n|e>>>n,wt=(t,e,n)=>t>>>n|e<<32-n,St=(t,e,n)=>t<<32-n|e>>>n,_t=(t,e,n)=>t<<64-n|e>>>n-32,At=(t,e,n)=>t>>>n-32|e<<64-n,Ot=(t,e)=>e,xt=(t,e)=>t,Et=(t,e,n)=>t<<n|e>>>32-n,Tt=(t,e,n)=>e<<n|t>>>32-n,It=(t,e,n)=>e<<n-32|t>>>64-n,Ct=(t,e,n)=>t<<n-32|e>>>64-n;function de(t,e,n,r){let o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}f.add=de;var vt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Pt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Mt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Rt=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,kt=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Dt=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0,Nt={fromBig:Y,split:pe,toBig:f.toBig,shrSH:gt,shrSL:bt,rotrSH:wt,rotrSL:St,rotrBH:_t,rotrBL:At,rotr32H:Ot,rotr32L:xt,rotlSH:Et,rotlSL:Tt,rotlBH:It,rotlBL:Ct,add:de,add3L:vt,add3H:Pt,add4L:Mt,add4H:Rt,add5H:Dt,add5L:kt};f.default=Nt});var fe=S(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.crypto=void 0;var D=dt("node:crypto");N.crypto=D&&typeof D=="object"&&"webcrypto"in D?D.webcrypto:void 0});var ye=S(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.randomBytes=c.wrapXOFConstructorWithOpts=c.wrapConstructorWithOpts=c.wrapConstructor=c.checkOpts=c.Hash=c.concatBytes=c.toBytes=c.utf8ToBytes=c.asyncLoop=c.nextTick=c.hexToBytes=c.bytesToHex=c.isLE=c.rotr=c.createView=c.u32=c.u8=void 0;var q=fe(),W=t=>t instanceof Uint8Array,Lt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Lt;var Bt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Bt;var jt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=jt;var Ut=(t,e)=>t<<32-e|t>>>e;c.rotr=Ut;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!c.isLE)throw new Error("Non little-endian hardware is not supported");var $t=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ht(t){if(!W(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=$t[t[n]];return e}c.bytesToHex=Ht;function Ft(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){let o=r*2,i=t.slice(o,o+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");n[r]=s}return n}c.hexToBytes=Ft;var Gt=async()=>{};c.nextTick=Gt;async function Vt(t,e,n){let r=Date.now();for(let o=0;o<t;o++){n(o);let i=Date.now()-r;i>=0&&i<e||(await(0,c.nextTick)(),r+=i)}}c.asyncLoop=Vt;function me(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}c.utf8ToBytes=me;function L(t){if(typeof t=="string"&&(t=me(t)),!W(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}c.toBytes=L;function Kt(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;return t.forEach(r=>{if(!W(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}c.concatBytes=Kt;var X=class{clone(){return this._cloneInto()}};c.Hash=X;var Yt=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function qt(t,e){if(e!==void 0&&(typeof e!="object"||!Yt(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}c.checkOpts=qt;function Xt(t){let e=r=>t().update(L(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}c.wrapConstructor=Xt;function Wt(t){let e=(r,o)=>t(o).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}c.wrapConstructorWithOpts=Wt;function zt(t){let e=(r,o)=>t(o).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}c.wrapXOFConstructorWithOpts=zt;function Jt(t=32){if(q.crypto&&typeof q.crypto.getRandomValues=="function")return q.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}c.randomBytes=Jt});var xe=S(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.shake256=l.shake128=l.keccak_512=l.keccak_384=l.keccak_256=l.keccak_224=l.sha3_512=l.sha3_384=l.sha3_256=l.sha3_224=l.Keccak=l.keccakP=void 0;var _=le(),E=he(),x=ye(),[we,Se,_e]=[[],[],[]],Zt=BigInt(0),O=BigInt(1),Qt=BigInt(2),en=BigInt(7),tn=BigInt(256),nn=BigInt(113);for(let t=0,e=O,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],we.push(2*(5*r+n)),Se.push((t+1)*(t+2)/2%64);let o=Zt;for(let i=0;i<7;i++)e=(e<<O^(e>>en)*nn)%tn,e&Qt&&(o^=O<<(O<<BigInt(i))-O);_e.push(o)}var[rn,on]=E.default.split(_e,!0),ge=(t,e,n)=>n>32?E.default.rotlBH(t,e,n):E.default.rotlSH(t,e,n),be=(t,e,n)=>n>32?E.default.rotlBL(t,e,n):E.default.rotlSL(t,e,n);function Ae(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let s=0;s<10;s++)n[s]=t[s]^t[s+10]^t[s+20]^t[s+30]^t[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,u=(s+2)%10,p=n[u],d=n[u+1],m=ge(p,d,1)^n[a],y=be(p,d,1)^n[a+1];for(let g=0;g<50;g+=10)t[s+g]^=m,t[s+g+1]^=y}let o=t[2],i=t[3];for(let s=0;s<24;s++){let a=Se[s],u=ge(o,i,a),p=be(o,i,a),d=we[s];o=t[d],i=t[d+1],t[d]=u,t[d+1]=p}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)n[a]=t[s+a];for(let a=0;a<10;a++)t[s+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=rn[r],t[1]^=on[r]}n.fill(0)}l.keccakP=Ae;var T=class t extends x.Hash{constructor(e,n,r,o=!1,i=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,_.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,x.u32)(this.state)}keccak(){Ae(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){_.default.exists(this);let{blockLen:n,state:r}=this;e=(0,x.toBytes)(e);let o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);for(let a=0;a<s;a++)r[this.pos++]^=e[i++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:o}=this;e[r]^=n,n&128&&r===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){_.default.exists(this,!1),_.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,i=e.length;o<i;){this.posOut>=r&&this.keccak();let s=Math.min(r-this.posOut,i-o);e.set(n.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return _.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(_.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:o,rounds:i,enableXOF:s}=this;return e||(e=new t(n,r,o,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=o,e.enableXOF=s,e.destroyed=this.destroyed,e}};l.Keccak=T;var b=(t,e,n)=>(0,x.wrapConstructor)(()=>new T(e,t,n));l.sha3_224=b(6,144,224/8);l.sha3_256=b(6,136,256/8);l.sha3_384=b(6,104,384/8);l.sha3_512=b(6,72,512/8);l.keccak_224=b(1,144,224/8);l.keccak_256=b(1,136,256/8);l.keccak_384=b(1,104,384/8);l.keccak_512=b(1,72,512/8);var Oe=(t,e,n)=>(0,x.wrapXOFConstructorWithOpts)((r={})=>new T(e,t,r.dkLen===void 0?n:r.dkLen,!0));l.shake128=Oe(31,168,128/8);l.shake256=Oe(31,136,256/8)});var Re=S((kn,w)=>{"use strict";var{sha3_512:sn}=xe(),Te=24,I=32,z=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Ie(t){let e=8n,n=0n;for(let r of t.values()){let o=BigInt(r);n=(n<<e)+o}return n}var Ce=(t="")=>Ie(sn(t)).toString(36).slice(1),Ee=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),an=t=>Ee[Math.floor(t()*Ee.length)],ve=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+z(I,e):z(I,e);return Ce(r).substring(0,I)},Pe=t=>()=>t++,cn=476782367,Me=({random:t=Math.random,counter:e=Pe(Math.floor(t()*cn)),length:n=Te,fingerprint:r=ve({random:t})}={})=>function(){let i=an(t),s=Date.now().toString(36),a=e().toString(36),u=z(n,t),p=`${s+u+a+r}`;return`${i+Ce(p).substring(1,n)}`},un=Me(),ln=(t,{minLength:e=2,maxLength:n=I}={})=>{let r=t.length,o=/^[0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&o.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:Te,bigLength:I});w.exports.init=Me;w.exports.createId=un;w.exports.bufToBigInt=Ie;w.exports.createCounter=Pe;w.exports.createFingerprint=ve;w.exports.isCuid=ln});var B=S((Dn,C)=>{"use strict";var{createId:pn,init:dn,getConstants:hn,isCuid:fn}=Re();C.exports.createId=pn;C.exports.init=dn;C.exports.getConstants=hn;C.exports.isCuid=fn});var _n={};ht(_n,{OramaClient:()=>Q,OramaProxy:()=>ee});var On=Date.now().toString().slice(5);var ne=BigInt(1e3),re=BigInt(1e6),oe=BigInt(1e9);async function se(t){return typeof t=="number"&&(t=BigInt(t)),t<ne?`${t}ns`:t<re?`${t/ne}\u03BCs`:t<oe?`${t/re}ms`:`${t/oe}s`}async function G(t){return{raw:Number(t),formatted:await se(t)}}var Ke=F(B(),1);var Ve=F(B(),1);var Fe=F(B(),1);var ke="https://answer.api.orama.com",v="https://secure-proxy.orama.run",De="/init",Ne="/chat",Le="/summary",Be="/query",J="orama_user_id",je="server-side-session";var $e="1.2.1";var He={name:"@oramacloud/client",version:$e,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function P(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var A=class t{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let n=new t(e);return n.start(),n}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:He.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};P(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}static getUserID(){if(typeof localStorage>"u")return je;let e=localStorage.getItem(J);if(e)return e;let n=(0,Fe.createId)();return localStorage.setItem(J,n),n}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function Ge(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}var j=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${ke}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,Ve.createId)(),this.userID=A.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let o of n)r=o;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let n=new URLSearchParams;n.append("type",this.inferenceType),n.append("messages",JSON.stringify(this.messages)),n.append("query",e.term??""),n.append("conversationId",this.conversationID),n.append("userId",this.userID),n.append("endpoint",this.oramaClient.endpoint),n.append("searchParams",JSON.stringify(e));let r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),signal:this.abortController.signal});if(!r.ok||!r.body)throw new Error(r.statusText);let o=r.body.getReader(),i=new TextDecoder,s=[],a="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let u=this.messages.at(-1);try{for(;;){let{value:p,done:d}=await o.read();if(d)break;a+=i.decode(p,{stream:!0});let m;for(;(m=a.indexOf(`
`))!==-1;){let y=a.slice(0,m);a=a.slice(m+2);try{let g=Ge(y),R=JSON.parse(g.data);if(R.type==="sources"){this.events?.onSourceChange&&this.events.onSourceChange(R.message);continue}if(s.push(R.message),R.endOfBlock)for(;s.length>0;)u.content+=s.shift(),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield u.content}catch(g){console.error("Error parsing SSE event:",g),console.error("Raw message:",y)}}}}catch(p){if(p.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw p}finally{o.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var $=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var H=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){P(this.params.endpoint)?.catch(e=>console.log(e))}};var Q=class{id=(0,Ke.createId)();api_key;endpoint;collector;cache;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=O.create(n)}if(e.cache!==!1){let n={};this.cache=new $(n)}this.init()}async search(e,n){await this.initPromise;let r=++this.searchRequestCounter,o=`search-${JSON.stringify(e)}`,i=null,s,a=!1,u=n?.fresh!==!0&&this.cache?.has(o),p=async()=>{try{let d=Date.now();i=await this.fetch("search","POST",{q:e},n?.abortController);let m=Date.now();i.elapsed=await G(BigInt(m*1e6-d*1e6)),s=m-d,this.cache?.set(o,i)}catch(d){if(d.name!=="AbortError")throw console.error("Search request failed",d),d}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:i?.hits?.length??0,roundTripTime:s,query:e,cached:a,searchedAt:new Date}),i};if(u&&this.cache)s=0,i=this.cache.get(o),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:i?.hits?.length??0,roundTripTime:s,query:e,cached:a,searchedAt:new Date});else return n?.debounce?new Promise((d,m)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),d(i)}catch(y){y.name!=="AbortError"&&(console.error("Search request failed",y),m(y))}},n?.debounce||300)}):p();return r===this.searchRequestCounter?i:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,o,i,s=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,i=this.cache.get(r),s=!0;else{let u=Date.now();i=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let p=Date.now();i.elapsed=await G(BigInt(p*1e6-u*1e6)),o=p-u,this.cache?.set(r,i)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:i.hits?.length??0,roundTripTime:o,query:e,cached:s,searchedAt:new Date}),i}createAnswerSession(e){return new U({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new H({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,n,r,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let i={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(n==="POST"&&r!==void 0){let a=r;a.version=$e,a.id=this.id,i.body=Object.entries(a).map(([u,p])=>`${u}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let s=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,i);if(!s.ok){let a=new Error;throw a.httpResponse=s,a}return await s.json()}};var Ye="text-embedding-ada-002",qe="text-embedding-3-small",Xe="text-embedding-3-large",We="gte-small",ze="gte-medium",Je="gte-large",Ze="gpt-4-0125-preview",Qe="gpt-4-1106-preview",et="gpt-4-turbo-preview ",tt="gpt-4",nt="gpt-3.5-turbo",rt="gpt-3.5-turbo-16k",ot="gpt-3.5-turbo-0125 ",yn={[`openai/${Ye}`]:`openai/${Ye}`,[`openai/${qe}`]:`openai/${qe}`,[`openai/${Xe}`]:`openai/${Xe}`,[`orama/${Je}`]:`orama/${Je}`,[`orama/${ze}`]:`orama/${ze}`,[`orama/${We}`]:`orama/${We}`},st={[`openai/${nt}`]:nt,[`openai/${tt}`]:tt,[`openai/${rt}`]:rt,[`openai/${Qe}`]:Qe,[`openai/${Ze}`]:Ze,[`openai/${et}`]:et,[`openai/${ot}`]:ot},ee=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(e,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let o=`${v}${Be}?apiKey=${encodeURIComponent(this.api_key)}`,s=await(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:yn[n]}).toString()})).json();return s.length===1&&(s=s[0]),s}async*summaryStream(e){if(!await this.ready){console.log("OramaProxy had an error during the initialization");return}this.summaryAbortController&&this.summaryAbortController.abort(),this.summaryAbortController=new AbortController;let r=`${v}${Le}?apiKey=${encodeURIComponent(this.api_key)}`;try{let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:st[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),s=new TextDecoder;for(;;){let{value:a,done:u}=await i.read();if(u)break;yield s.decode(a,{stream:!0})}}catch(o){if(o.name!=="AbortError")throw o}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.summaryStream(e))r+=o;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.chatStream(e))r+=o;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${Ne}?apiKey=${encodeURIComponent(this.api_key)}`,o=e.messages;this.publicKey&&(o=await Promise.all(o.map(async u=>!u.content||typeof u.content!="string"?u:{...u,content:await Sn(this.publicKey,u.content)})));let i=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(o),csrf:this.CSRFToken,model:st[e.model]}).toString()});if(!i.ok||i.body==null)throw i.statusText;let s=i.body.getReader(),a=new TextDecoder;for(;;){let{value:u,done:p}=await s.read();if(p)break;yield a.decode(u,{stream:!0})}}async init(){let e=`${v}${De}?apiKey=${encodeURIComponent(this.api_key)}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await gn(wn(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function gn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function bn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function wn(t){return Uint8Array.from(t)}var it=50;async function Sn(t,e){let n=new TextEncoder().encode(e),r=[];for(let o=0;o<n.length;o+=it){let i=n.subarray(o,o+it),s=await bn(t,i);r.push(Array.from(s))}return r}return ft(_n);})();
`))!==-1;){let y=a.slice(0,m);a=a.slice(m+2);try{let g=Ge(y),H=JSON.parse(g.data);if(H.type==="sources"){this.events?.onSourceChange&&this.events.onSourceChange(H.message);continue}for(s.push(H.message);s.length>0;)u.content+=s.shift(),this.events?.onMessageChange&&(console.log("onMessageChange is defined"),this.events.onMessageChange(this.messages)),yield u.content}catch(g){console.error("Error parsing SSE event:",g),console.error("Raw message:",y)}}}}catch(p){if(p.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw p}finally{o.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var U=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){P(this.params.endpoint)?.catch(e=>console.log(e))}};var Q=class{id=(0,Ke.createId)();api_key;endpoint;collector;cache;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=A.create(n)}if(e.cache!==!1){let n={};this.cache=new U(n)}this.init()}async search(e,n){await this.initPromise;let r=++this.searchRequestCounter,o=`search-${JSON.stringify(e)}`,i=null,s,a=!1,u=n?.fresh!==!0&&this.cache?.has(o),p=async()=>{try{let d=Date.now();i=await this.fetch("search","POST",{q:e},n?.abortController);let m=Date.now();i.elapsed=await G(BigInt(m*1e6-d*1e6)),s=m-d,this.cache?.set(o,i)}catch(d){if(d.name!=="AbortError")throw console.error("Search request failed",d),d}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:i?.hits?.length??0,roundTripTime:s,query:e,cached:a,searchedAt:new Date}),i};if(u&&this.cache)s=0,i=this.cache.get(o),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:i?.hits?.length??0,roundTripTime:s,query:e,cached:a,searchedAt:new Date});else return n?.debounce?new Promise((d,m)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),d(i)}catch(y){y.name!=="AbortError"&&(console.error("Search request failed",y),m(y))}},n?.debounce||300)}):p();return r===this.searchRequestCounter?i:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,o,i,s=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,i=this.cache.get(r),s=!0;else{let u=Date.now();i=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let p=Date.now();i.elapsed=await G(BigInt(p*1e6-u*1e6)),o=p-u,this.cache?.set(r,i)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:i.hits?.length??0,roundTripTime:o,query:e,cached:s,searchedAt:new Date}),i}createAnswerSession(e){return new j({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,n,r,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let i={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(n==="POST"&&r!==void 0){let a=r;a.version=$e,a.id=this.id,i.body=Object.entries(a).map(([u,p])=>`${u}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let s=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,i);if(!s.ok){let a=new Error;throw a.httpResponse=s,a}return await s.json()}};var Ye="text-embedding-ada-002",qe="text-embedding-3-small",Xe="text-embedding-3-large",We="gte-small",ze="gte-medium",Je="gte-large",Ze="gpt-4-0125-preview",Qe="gpt-4-1106-preview",et="gpt-4-turbo-preview ",tt="gpt-4",nt="gpt-3.5-turbo",rt="gpt-3.5-turbo-16k",ot="gpt-3.5-turbo-0125 ",yn={[`openai/${Ye}`]:`openai/${Ye}`,[`openai/${qe}`]:`openai/${qe}`,[`openai/${Xe}`]:`openai/${Xe}`,[`orama/${Je}`]:`orama/${Je}`,[`orama/${ze}`]:`orama/${ze}`,[`orama/${We}`]:`orama/${We}`},st={[`openai/${nt}`]:nt,[`openai/${tt}`]:tt,[`openai/${rt}`]:rt,[`openai/${Qe}`]:Qe,[`openai/${Ze}`]:Ze,[`openai/${et}`]:et,[`openai/${ot}`]:ot},ee=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(e,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let o=`${v}${Be}?apiKey=${encodeURIComponent(this.api_key)}`,s=await(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:yn[n]}).toString()})).json();return s.length===1&&(s=s[0]),s}async*summaryStream(e){if(!await this.ready){console.log("OramaProxy had an error during the initialization");return}this.summaryAbortController&&this.summaryAbortController.abort(),this.summaryAbortController=new AbortController;let r=`${v}${Le}?apiKey=${encodeURIComponent(this.api_key)}`;try{let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:st[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),s=new TextDecoder;for(;;){let{value:a,done:u}=await i.read();if(u)break;yield s.decode(a,{stream:!0})}}catch(o){if(o.name!=="AbortError")throw o}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.summaryStream(e))r+=o;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.chatStream(e))r+=o;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${Ne}?apiKey=${encodeURIComponent(this.api_key)}`,o=e.messages;this.publicKey&&(o=await Promise.all(o.map(async u=>!u.content||typeof u.content!="string"?u:{...u,content:await Sn(this.publicKey,u.content)})));let i=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(o),csrf:this.CSRFToken,model:st[e.model]}).toString()});if(!i.ok||i.body==null)throw i.statusText;let s=i.body.getReader(),a=new TextDecoder;for(;;){let{value:u,done:p}=await s.read();if(p)break;yield a.decode(u,{stream:!0})}}async init(){let e=`${v}${De}?apiKey=${encodeURIComponent(this.api_key)}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await gn(wn(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function gn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function bn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function wn(t){return Uint8Array.from(t)}var it=50;async function Sn(t,e){let n=new TextEncoder().encode(e),r=[];for(let o=0;o<n.length;o+=it){let i=n.subarray(o,o+it),s=await bn(t,i);r.push(Array.from(s))}return r}return ft(_n);})();
/*! Bundled license information:

@@ -6,0 +7,0 @@

@@ -1,5 +0,6 @@

var pe=Date.now().toString().slice(5);var T=BigInt(1e3),C=BigInt(1e6),w=BigInt(1e9);async function I(o){return typeof o=="number"&&(o=BigInt(o)),o<T?`${o}ns`:o<C?`${o/T}\u03BCs`:o<w?`${o/C}ms`:`${o/w}s`}async function _(o){return{raw:Number(o),formatted:await I(o)}}import{createId as oe}from"@paralleldrive/cuid2";import{createId as ne}from"@paralleldrive/cuid2";import{createId as re}from"@paralleldrive/cuid2";var v="https://answer.api.orama.com",m="https://secure-proxy.orama.run",P="/init",x="/chat",R="/summary",D="/query",O="orama_user_id",M="server-side-session";var k="1.2.0";var L={name:"@oramacloud/client",version:k,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function f(o,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(o,e);return}fetch(o,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var h=class o{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new o(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:L.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};f(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(n=>console.log(n))}static getUserID(){if(typeof localStorage>"u")return M;let e=localStorage.getItem(O);if(e)return e;let t=re();return localStorage.setItem(O,t),t}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function B(o){let e=o.split(`
`),t={};for(let n of e){let[r,s]=n.split(": ");r&&(t[r]=s)}return t}var g=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${v}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=ne(),this.userID=h.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),n="";for await(let r of t)n=r;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),n}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let t=new URLSearchParams;t.append("type",this.inferenceType),t.append("messages",JSON.stringify(this.messages)),t.append("query",e.term??""),t.append("conversationId",this.conversationID),t.append("userId",this.userID),t.append("endpoint",this.oramaClient.endpoint),t.append("searchParams",JSON.stringify(e));let n=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!n.ok||!n.body)throw new Error(n.statusText);let r=n.body.getReader(),s=new TextDecoder,i=[],a="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let c=this.messages.at(-1);try{for(;;){let{value:l,done:p}=await r.read();if(p)break;a+=s.decode(l,{stream:!0});let u;for(;(u=a.indexOf(`
var pe=Date.now().toString().slice(5);var C=BigInt(1e3),E=BigInt(1e6),w=BigInt(1e9);async function v(o){return typeof o=="number"&&(o=BigInt(o)),o<C?`${o}ns`:o<E?`${o/C}\u03BCs`:o<w?`${o/E}ms`:`${o/w}s`}async function _(o){return{raw:Number(o),formatted:await v(o)}}import{createId as oe}from"@paralleldrive/cuid2";import{createId as ne}from"@paralleldrive/cuid2";import{createId as re}from"@paralleldrive/cuid2";var I="https://answer.api.orama.com",m="https://secure-proxy.orama.run",P="/init",x="/chat",R="/summary",D="/query",O="orama_user_id",M="server-side-session";var k="1.2.1";var L={name:"@oramacloud/client",version:k,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function f(o,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(o,e);return}fetch(o,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var h=class o{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new o(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:L.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};f(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(r=>console.log(r))}static getUserID(){if(typeof localStorage>"u")return M;let e=localStorage.getItem(O);if(e)return e;let t=re();return localStorage.setItem(O,t),t}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function B(o){let[e,...t]=o.split(`
`),r=t.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}var y=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${I}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=ne(),this.userID=h.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),r="";for await(let n of t)r=n;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let t=new URLSearchParams;t.append("type",this.inferenceType),t.append("messages",JSON.stringify(this.messages)),t.append("query",e.term??""),t.append("conversationId",this.conversationID),t.append("userId",this.userID),t.append("endpoint",this.oramaClient.endpoint),t.append("searchParams",JSON.stringify(e));let r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!r.ok||!r.body)throw new Error(r.statusText);let n=r.body.getReader(),s=new TextDecoder,i=[],a="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let c=this.messages.at(-1);try{for(;;){let{value:l,done:p}=await n.read();if(p)break;a+=s.decode(l,{stream:!0});let u;for(;(u=a.indexOf(`
`))!==-1;){let d=a.slice(0,u);a=a.slice(u+2);try{let A=B(d),y=JSON.parse(A.data);if(y.type==="sources"){this.events?.onSourceChange&&this.events.onSourceChange(y.message);continue}if(i.push(y.message),y.endOfBlock)for(;i.length>0;)c.content+=i.shift(),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield c.content}catch(A){console.error("Error parsing SSE event:",A),console.error("Raw message:",d)}}}}catch(l){if(l.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw l}finally{r.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var S=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var b=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){f(this.params.endpoint)?.catch(e=>console.log(e))}};var $=class{id=oe();api_key;endpoint;collector;cache;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=h.create(t)}if(e.cache!==!1){let t={};this.cache=new S(t)}this.init()}async search(e,t){await this.initPromise;let n=++this.searchRequestCounter,r=`search-${JSON.stringify(e)}`,s=null,i,a=!1,c=t?.fresh!==!0&&this.cache?.has(r),l=async()=>{try{let p=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let u=Date.now();s.elapsed=await _(BigInt(u*1e6-p*1e6)),i=u-p,this.cache?.set(r,s)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:e,cached:a,searchedAt:new Date}),s};if(c&&this.cache)i=0,s=this.cache.get(r),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:e,cached:a,searchedAt:new Date});else return t?.debounce?new Promise((p,u)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),p(s)}catch(d){d.name!=="AbortError"&&(console.error("Search request failed",d),u(d))}},t?.debounce||300)}):l();return n===this.searchRequestCounter?s:null}async vectorSearch(e,t){await this.initPromise;let n=`vectorSearch-${JSON.stringify(e)}`,r,s,i=!1;if((t?.fresh!==!0&&this.cache?.has(n))===!0&&this.cache!=null)r=0,s=this.cache.get(n),i=!0;else{let c=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await _(BigInt(l*1e6-c*1e6)),r=l-c,this.cache?.set(n,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits?.length??0,roundTripTime:r,query:e,cached:i,searchedAt:new Date}),s}createAnswerSession(e){return new g({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new b({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,n,r){if(r?.signal.aborted===!0)throw new Error("Request aborted");let s={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:r?.signal};if(t==="POST"&&n!==void 0){let a=n;a.version=k,a.id=this.id,s.body=Object.entries(a).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let i=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!i.ok){let a=new Error;throw a.httpResponse=i,a}return await i.json()}};var j="text-embedding-ada-002",U="text-embedding-3-small",G="text-embedding-3-large",H="gte-small",K="gte-medium",Y="gte-large",V="gpt-4-0125-preview",F="gpt-4-1106-preview",q="gpt-4-turbo-preview ",X="gpt-4",z="gpt-3.5-turbo",J="gpt-3.5-turbo-16k",W="gpt-3.5-turbo-0125 ",se={[`openai/${j}`]:`openai/${j}`,[`openai/${U}`]:`openai/${U}`,[`openai/${G}`]:`openai/${G}`,[`orama/${Y}`]:`orama/${Y}`,[`orama/${K}`]:`orama/${K}`,[`orama/${H}`]:`orama/${H}`},Z={[`openai/${z}`]:z,[`openai/${X}`]:X,[`openai/${J}`]:J,[`openai/${F}`]:F,[`openai/${V}`]:V,[`openai/${q}`]:q,[`openai/${W}`]:W},Q=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(t=>(console.log(t),!1))}async generateEmbeddings(e,t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let r=`${m}${D}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:se[t]}).toString()})).json();return i.length===1&&(i=i[0]),i}async*summaryStream(e){if(!await this.ready){console.log("OramaProxy had an error during the initialization");return}this.summaryAbortController&&this.summaryAbortController.abort(),this.summaryAbortController=new AbortController;let n=`${m}${R}?apiKey=${encodeURIComponent(this.api_key)}`;try{let r=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:Z[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!r.ok||r.body==null)throw r.statusText;let s=r.body.getReader(),i=new TextDecoder;for(;;){let{value:a,done:c}=await s.read();if(c)break;yield i.decode(a,{stream:!0})}}catch(r){if(r.name!=="AbortError")throw r}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n="";for await(let r of this.summaryStream(e))n+=r;return n}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n="";for await(let r of this.chatStream(e))n+=r;return n}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n=`${m}${x}?apiKey=${encodeURIComponent(this.api_key)}`,r=e.messages;this.publicKey&&(r=await Promise.all(r.map(async c=>!c.content||typeof c.content!="string"?c:{...c,content:await le(this.publicKey,c.content)})));let s=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:Z[e.model]}).toString()});if(!s.ok||s.body==null)throw s.statusText;let i=s.body.getReader(),a=new TextDecoder;for(;;){let{value:c,done:l}=await i.read();if(l)break;yield a.decode(c,{stream:!0})}}async init(){let e=`${m}${P}?apiKey=${encodeURIComponent(this.api_key)}`,n=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=n.csrfToken,n.encryption?.enabled===!0&&(this.publicKey=await ie(ce(n.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function ie(o){return await crypto.subtle.importKey("spki",o,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function ae(o,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},o,e);return new Uint8Array(t)}function ce(o){return Uint8Array.from(o)}var ee=50;async function le(o,e){let t=new TextEncoder().encode(e),n=[];for(let r=0;r<t.length;r+=ee){let s=t.subarray(r,r+ee),i=await ae(o,s);n.push(Array.from(i))}return n}export{$ as OramaClient,Q as OramaProxy};
`))!==-1;){let d=a.slice(0,u);a=a.slice(u+2);try{let b=B(d),A=JSON.parse(b.data);if(A.type==="sources"){this.events?.onSourceChange&&this.events.onSourceChange(A.message);continue}for(i.push(A.message);i.length>0;)c.content+=i.shift(),this.events?.onMessageChange&&(console.log("onMessageChange is defined"),this.events.onMessageChange(this.messages)),yield c.content}catch(b){console.error("Error parsing SSE event:",b),console.error("Raw message:",d)}}}}catch(l){if(l.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw l}finally{n.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var g=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var S=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){f(this.params.endpoint)?.catch(e=>console.log(e))}};var $=class{id=oe();api_key;endpoint;collector;cache;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=h.create(t)}if(e.cache!==!1){let t={};this.cache=new g(t)}this.init()}async search(e,t){await this.initPromise;let r=++this.searchRequestCounter,n=`search-${JSON.stringify(e)}`,s=null,i,a=!1,c=t?.fresh!==!0&&this.cache?.has(n),l=async()=>{try{let p=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let u=Date.now();s.elapsed=await _(BigInt(u*1e6-p*1e6)),i=u-p,this.cache?.set(n,s)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:e,cached:a,searchedAt:new Date}),s};if(c&&this.cache)i=0,s=this.cache.get(n),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:e,cached:a,searchedAt:new Date});else return t?.debounce?new Promise((p,u)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),p(s)}catch(d){d.name!=="AbortError"&&(console.error("Search request failed",d),u(d))}},t?.debounce||300)}):l();return r===this.searchRequestCounter?s:null}async vectorSearch(e,t){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,n,s,i=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)n=0,s=this.cache.get(r),i=!0;else{let c=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await _(BigInt(l*1e6-c*1e6)),n=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits?.length??0,roundTripTime:n,query:e,cached:i,searchedAt:new Date}),s}createAnswerSession(e){return new y({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new S({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,r,n){if(n?.signal.aborted===!0)throw new Error("Request aborted");let s={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:n?.signal};if(t==="POST"&&r!==void 0){let a=r;a.version=k,a.id=this.id,s.body=Object.entries(a).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let i=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!i.ok){let a=new Error;throw a.httpResponse=i,a}return await i.json()}};var j="text-embedding-ada-002",U="text-embedding-3-small",G="text-embedding-3-large",H="gte-small",K="gte-medium",Y="gte-large",V="gpt-4-0125-preview",F="gpt-4-1106-preview",q="gpt-4-turbo-preview ",X="gpt-4",z="gpt-3.5-turbo",J="gpt-3.5-turbo-16k",W="gpt-3.5-turbo-0125 ",se={[`openai/${j}`]:`openai/${j}`,[`openai/${U}`]:`openai/${U}`,[`openai/${G}`]:`openai/${G}`,[`orama/${Y}`]:`orama/${Y}`,[`orama/${K}`]:`orama/${K}`,[`orama/${H}`]:`orama/${H}`},Z={[`openai/${z}`]:z,[`openai/${X}`]:X,[`openai/${J}`]:J,[`openai/${F}`]:F,[`openai/${V}`]:V,[`openai/${q}`]:q,[`openai/${W}`]:W},Q=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(t=>(console.log(t),!1))}async generateEmbeddings(e,t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let n=`${m}${D}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:se[t]}).toString()})).json();return i.length===1&&(i=i[0]),i}async*summaryStream(e){if(!await this.ready){console.log("OramaProxy had an error during the initialization");return}this.summaryAbortController&&this.summaryAbortController.abort(),this.summaryAbortController=new AbortController;let r=`${m}${R}?apiKey=${encodeURIComponent(this.api_key)}`;try{let n=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:Z[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!n.ok||n.body==null)throw n.statusText;let s=n.body.getReader(),i=new TextDecoder;for(;;){let{value:a,done:c}=await s.read();if(c)break;yield i.decode(a,{stream:!0})}}catch(n){if(n.name!=="AbortError")throw n}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let n of this.summaryStream(e))r+=n;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let n of this.chatStream(e))r+=n;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${m}${x}?apiKey=${encodeURIComponent(this.api_key)}`,n=e.messages;this.publicKey&&(n=await Promise.all(n.map(async c=>!c.content||typeof c.content!="string"?c:{...c,content:await le(this.publicKey,c.content)})));let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(n),csrf:this.CSRFToken,model:Z[e.model]}).toString()});if(!s.ok||s.body==null)throw s.statusText;let i=s.body.getReader(),a=new TextDecoder;for(;;){let{value:c,done:l}=await i.read();if(l)break;yield a.decode(c,{stream:!0})}}async init(){let e=`${m}${P}?apiKey=${encodeURIComponent(this.api_key)}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await ie(ce(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function ie(o){return await crypto.subtle.importKey("spki",o,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function ae(o,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},o,e);return new Uint8Array(t)}function ce(o){return Uint8Array.from(o)}var ee=50;async function le(o,e){let t=new TextEncoder().encode(e),r=[];for(let n=0;n<t.length;n+=ee){let s=t.subarray(n,n+ee),i=await ae(o,s);r.push(Array.from(i))}return r}export{$ as OramaClient,Q as OramaProxy};
//# sourceMappingURL=index.js.map

@@ -1,5 +0,6 @@

var X=Date.now().toString().slice(5);var P=BigInt(1e3),R=BigInt(1e6),_=BigInt(1e9);async function D(n){return typeof n=="number"&&(n=BigInt(n)),n<P?`${n}ns`:n<R?`${n/P}\u03BCs`:n<_?`${n/R}ms`:`${n/_}s`}async function T(n){return{raw:Number(n),formatted:await D(n)}}import{createId as F}from"@paralleldrive/cuid2";import{createId as H}from"@paralleldrive/cuid2";import{createId as V}from"@paralleldrive/cuid2";var M="https://answer.api.orama.com";var E="orama_user_id",N="server-side-session";var j="1.2.0";var B={name:"@oramacloud/client",version:j,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function b(n,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(n,e);return}fetch(n,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var m=class n{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new n(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:B.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};b(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(s=>console.log(s))}static getUserID(){if(typeof localStorage>"u")return N;let e=localStorage.getItem(E);if(e)return e;let t=V();return localStorage.setItem(E,t),t}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function L(n){let e=n.split(`
`),t={};for(let s of e){let[o,r]=s.split(": ");o&&(t[o]=r)}return t}var g=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${M}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=H(),this.userID=m.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),s="";for await(let o of t)s=o;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),s}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let t=new URLSearchParams;t.append("type",this.inferenceType),t.append("messages",JSON.stringify(this.messages)),t.append("query",e.term??""),t.append("conversationId",this.conversationID),t.append("userId",this.userID),t.append("endpoint",this.oramaClient.endpoint),t.append("searchParams",JSON.stringify(e));let s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!s.ok||!s.body)throw new Error(s.statusText);let o=s.body.getReader(),r=new TextDecoder,a=[],i="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let u=this.messages.at(-1);try{for(;;){let{value:c,done:p}=await o.read();if(p)break;i+=r.decode(c,{stream:!0});let l;for(;(l=i.indexOf(`
var X=Date.now().toString().slice(5);var P=BigInt(1e3),R=BigInt(1e6),D=BigInt(1e9);async function _(n){return typeof n=="number"&&(n=BigInt(n)),n<P?`${n}ns`:n<R?`${n/P}\u03BCs`:n<D?`${n/R}ms`:`${n/D}s`}async function T(n){return{raw:Number(n),formatted:await _(n)}}import{createId as F}from"@paralleldrive/cuid2";import{createId as H}from"@paralleldrive/cuid2";import{createId as V}from"@paralleldrive/cuid2";var M="https://answer.api.orama.com";var E="orama_user_id",N="server-side-session";var j="1.2.1";var B={name:"@oramacloud/client",version:j,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function b(n,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(n,e);return}fetch(n,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var f=class n{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new n(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:B.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};b(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(s=>console.log(s))}static getUserID(){if(typeof localStorage>"u")return N;let e=localStorage.getItem(E);if(e)return e;let t=V();return localStorage.setItem(E,t),t}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function L(n){let[e,...t]=n.split(`
`),s=t.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:s}}var m=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${M}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=H(),this.userID=f.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),s="";for await(let i of t)s=i;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),s}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let t=new URLSearchParams;t.append("type",this.inferenceType),t.append("messages",JSON.stringify(this.messages)),t.append("query",e.term??""),t.append("conversationId",this.conversationID),t.append("userId",this.userID),t.append("endpoint",this.oramaClient.endpoint),t.append("searchParams",JSON.stringify(e));let s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!s.ok||!s.body)throw new Error(s.statusText);let i=s.body.getReader(),r=new TextDecoder,a=[],o="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let u=this.messages.at(-1);try{for(;;){let{value:c,done:p}=await i.read();if(p)break;o+=r.decode(c,{stream:!0});let l;for(;(l=o.indexOf(`
`))!==-1;){let f=i.slice(0,l);i=i.slice(l+2);try{let S=L(f),h=JSON.parse(S.data);if(h.type==="sources"){this.events?.onSourceChange&&this.events.onSourceChange(h.message);continue}if(a.push(h.message),h.endOfBlock)for(;a.length>0;)u.content+=a.shift(),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield u.content}catch(S){console.error("Error parsing SSE event:",S),console.error("Raw message:",f)}}}}catch(c){if(c.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw c}finally{o.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var v=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var w=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){b(this.params.endpoint)?.catch(e=>console.log(e))}};var y=class{id=F();api_key;endpoint;collector;cache;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=m.create(t)}if(e.cache!==!1){let t={};this.cache=new v(t)}this.init()}async search(e,t){await this.initPromise;let s=++this.searchRequestCounter,o=`search-${JSON.stringify(e)}`,r=null,a,i=!1,u=t?.fresh!==!0&&this.cache?.has(o),c=async()=>{try{let p=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await T(BigInt(l*1e6-p*1e6)),a=l-p,this.cache?.set(o,r)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:a,query:e,cached:i,searchedAt:new Date}),r};if(u&&this.cache)a=0,r=this.cache.get(o),i=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:a,query:e,cached:i,searchedAt:new Date});else return t?.debounce?new Promise((p,l)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await c(),p(r)}catch(f){f.name!=="AbortError"&&(console.error("Search request failed",f),l(f))}},t?.debounce||300)}):c();return s===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let s=`vectorSearch-${JSON.stringify(e)}`,o,r,a=!1;if((t?.fresh!==!0&&this.cache?.has(s))===!0&&this.cache!=null)o=0,r=this.cache.get(s),a=!0;else{let u=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let c=Date.now();r.elapsed=await T(BigInt(c*1e6-u*1e6)),o=c-u,this.cache?.set(s,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date}),r}createAnswerSession(e){return new g({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new w({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,s,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(t==="POST"&&s!==void 0){let i=s;i.version=j,i.id=this.id,r.body=Object.entries(i).map(([u,c])=>`${u}=${encodeURIComponent(JSON.stringify(c))}`).join("&")}let a=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!a.ok){let i=new Error;throw i.httpResponse=a,i}return await a.json()}};import G,{useState as A,useEffect as U,createContext as z,useContext as J}from"react";import{useState as C,useRef as Y,useEffect as K,useCallback as O}from"react";function q(n){let[e,t]=C(n.initialMessages||[]),[s,o]=C(!1),[r,a]=C(null),[i,u]=C(!1),[c,p]=C(null),l=Y(null);K(()=>{let x="oramaClient"in n?n.oramaClient:new y({api_key:n.apiKey,endpoint:n.endpoint});return l.current=new g({...n,initialMessages:n.initialMessages||[],inferenceType:n.inferenceType||"documentation",oramaClient:x,events:{onMessageChange:d=>{t(d)},onMessageLoading:d=>{o(d)},onAnswerAborted:d=>{u(d)},onSourceChange:d=>{p(d)}}}),()=>{l.current?.abortAnswer()}},[n]);let f=O(async x=>{if(!l.current)try{u(!1),await l.current.ask(x)}catch(d){a(d)}},[]),S=O(()=>{l?.current?.abortAnswer()},[]),h=O(()=>{l?.current?.clearSession()},[]);return{messages:e,loading:s,aborted:i,abortAnswer:S,error:r,sources:c,ask:f,clearSession:h}}var $=z({endpoint:"",apiKey:""}),ke=({children:n,endpoint:e,apiKey:t})=>G.createElement($.Provider,{value:{endpoint:e,apiKey:t}},n);function je(n){let{apiKey:e,endpoint:t}=J($),[s,o]=A(!1),[r,a]=A(null),[i,u]=A(null),[c,p]=A(null);return U(()=>{a(new y({api_key:e,endpoint:t})),o(!0)},[]),U(()=>{r!==null&&r.search(n).then(u).catch(p)},[r,n]),{ready:s,results:i,error:c}}export{ke as OramaCloud,q as useAnswerSession,je as useSearch};
`))!==-1;){let h=o.slice(0,l);o=o.slice(l+2);try{let y=L(h),S=JSON.parse(y.data);if(S.type==="sources"){this.events?.onSourceChange&&this.events.onSourceChange(S.message);continue}for(a.push(S.message);a.length>0;)u.content+=a.shift(),this.events?.onMessageChange&&(console.log("onMessageChange is defined"),this.events.onMessageChange(this.messages)),yield u.content}catch(y){console.error("Error parsing SSE event:",y),console.error("Raw message:",h)}}}}catch(c){if(c.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw c}finally{i.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var v=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var w=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){b(this.params.endpoint)?.catch(e=>console.log(e))}};var g=class{id=F();api_key;endpoint;collector;cache;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=f.create(t)}if(e.cache!==!1){let t={};this.cache=new v(t)}this.init()}async search(e,t){await this.initPromise;let s=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,r=null,a,o=!1,u=t?.fresh!==!0&&this.cache?.has(i),c=async()=>{try{let p=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await T(BigInt(l*1e6-p*1e6)),a=l-p,this.cache?.set(i,r)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:a,query:e,cached:o,searchedAt:new Date}),r};if(u&&this.cache)a=0,r=this.cache.get(i),o=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:a,query:e,cached:o,searchedAt:new Date});else return t?.debounce?new Promise((p,l)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await c(),p(r)}catch(h){h.name!=="AbortError"&&(console.error("Search request failed",h),l(h))}},t?.debounce||300)}):c();return s===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let s=`vectorSearch-${JSON.stringify(e)}`,i,r,a=!1;if((t?.fresh!==!0&&this.cache?.has(s))===!0&&this.cache!=null)i=0,r=this.cache.get(s),a=!0;else{let u=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let c=Date.now();r.elapsed=await T(BigInt(c*1e6-u*1e6)),i=c-u,this.cache?.set(s,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits?.length??0,roundTripTime:i,query:e,cached:a,searchedAt:new Date}),r}createAnswerSession(e){return new m({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new w({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,s,i){if(i?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i?.signal};if(t==="POST"&&s!==void 0){let o=s;o.version=j,o.id=this.id,r.body=Object.entries(o).map(([u,c])=>`${u}=${encodeURIComponent(JSON.stringify(c))}`).join("&")}let a=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!a.ok){let o=new Error;throw o.httpResponse=a,o}return await a.json()}};import G,{useState as A,useEffect as U,createContext as z,useContext as J}from"react";import{useState as C,useRef as Y,useEffect as K,useCallback as O}from"react";function q(n){let[e,t]=C(n.initialMessages||[]),[s,i]=C(!1),[r,a]=C(null),[o,u]=C(!1),[c,p]=C(null),l=Y(null);K(()=>{let x="oramaClient"in n?n.oramaClient:new g({api_key:n.apiKey,endpoint:n.endpoint});return l.current=new m({...n,initialMessages:n.initialMessages||[],inferenceType:n.inferenceType||"documentation",oramaClient:x,events:{onMessageChange:d=>{t(d)},onMessageLoading:d=>{i(d)},onAnswerAborted:d=>{u(d)},onSourceChange:d=>{p(d)}}}),()=>{l.current?.abortAnswer()}},[n]);let h=O(async x=>{if(!l.current)try{u(!1),await l.current.ask(x)}catch(d){a(d)}},[]),y=O(()=>{l?.current?.abortAnswer()},[]),S=O(()=>{l?.current?.clearSession()},[]);return{messages:e,loading:s,aborted:o,abortAnswer:y,error:r,sources:c,ask:h,clearSession:S}}var $=z({endpoint:"",apiKey:""}),ke=({children:n,endpoint:e,apiKey:t})=>G.createElement($.Provider,{value:{endpoint:e,apiKey:t}},n);function je(n){let{apiKey:e,endpoint:t}=J($),[s,i]=A(!1),[r,a]=A(null),[o,u]=A(null),[c,p]=A(null);return U(()=>{a(new g({api_key:e,endpoint:t})),i(!0)},[]),U(()=>{r!==null&&r.search(n).then(u).catch(p)},[r,n]),{ready:s,results:o,error:c}}export{ke as OramaCloud,q as useAnswerSession,je as useSearch};
//# sourceMappingURL=index.js.map

@@ -1,5 +0,6 @@

var Y=Date.now().toString().slice(5);var A=BigInt(1e3),x=BigInt(1e6),E=BigInt(1e9);async function I(r){return typeof r=="number"&&(r=BigInt(r)),r<A?`${r}ns`:r<x?`${r/A}\u03BCs`:r<E?`${r/x}ms`:`${r/E}s`}async function C(r){return{raw:Number(r),formatted:await I(r)}}import{createId as L}from"@paralleldrive/cuid2";import{createId as B}from"@paralleldrive/cuid2";import{createId as j}from"@paralleldrive/cuid2";var O="https://answer.api.orama.com";var w="orama_user_id",R="server-side-session";var _="1.2.0";var D={name:"@oramacloud/client",version:_,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function h(r,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(r,e);return}fetch(r,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var f=class r{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new r(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:D.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};h(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(s=>console.log(s))}static getUserID(){if(typeof localStorage>"u")return R;let e=localStorage.getItem(w);if(e)return e;let t=j();return localStorage.setItem(w,t),t}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function M(r){let e=r.split(`
`),t={};for(let s of e){let[o,n]=s.split(": ");o&&(t[o]=n)}return t}var g=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${O}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=B(),this.userID=f.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),s="";for await(let o of t)s=o;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),s}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let t=new URLSearchParams;t.append("type",this.inferenceType),t.append("messages",JSON.stringify(this.messages)),t.append("query",e.term??""),t.append("conversationId",this.conversationID),t.append("userId",this.userID),t.append("endpoint",this.oramaClient.endpoint),t.append("searchParams",JSON.stringify(e));let s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!s.ok||!s.body)throw new Error(s.statusText);let o=s.body.getReader(),n=new TextDecoder,i=[],a="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let c=this.messages.at(-1);try{for(;;){let{value:l,done:u}=await o.read();if(u)break;a+=n.decode(l,{stream:!0});let p;for(;(p=a.indexOf(`
var Y=Date.now().toString().slice(5);var A=BigInt(1e3),x=BigInt(1e6),E=BigInt(1e9);async function I(r){return typeof r=="number"&&(r=BigInt(r)),r<A?`${r}ns`:r<x?`${r/A}\u03BCs`:r<E?`${r/x}ms`:`${r/E}s`}async function C(r){return{raw:Number(r),formatted:await I(r)}}import{createId as L}from"@paralleldrive/cuid2";import{createId as B}from"@paralleldrive/cuid2";import{createId as j}from"@paralleldrive/cuid2";var O="https://answer.api.orama.com";var w="orama_user_id",R="server-side-session";var _="1.2.1";var D={name:"@oramacloud/client",version:_,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function h(r,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(r,e);return}fetch(r,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var f=class r{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new r(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:D.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};h(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(n=>console.log(n))}static getUserID(){if(typeof localStorage>"u")return R;let e=localStorage.getItem(w);if(e)return e;let t=j();return localStorage.setItem(w,t),t}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function M(r){let[e,...t]=r.split(`
`),n=t.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:n}}var m=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${O}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=B(),this.userID=f.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),n="";for await(let i of t)n=i;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),n}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let t=new URLSearchParams;t.append("type",this.inferenceType),t.append("messages",JSON.stringify(this.messages)),t.append("query",e.term??""),t.append("conversationId",this.conversationID),t.append("userId",this.userID),t.append("endpoint",this.oramaClient.endpoint),t.append("searchParams",JSON.stringify(e));let n=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!n.ok||!n.body)throw new Error(n.statusText);let i=n.body.getReader(),s=new TextDecoder,o=[],a="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let c=this.messages.at(-1);try{for(;;){let{value:l,done:u}=await i.read();if(u)break;a+=s.decode(l,{stream:!0});let p;for(;(p=a.indexOf(`
`))!==-1;){let d=a.slice(0,p);a=a.slice(p+2);try{let v=M(d),m=JSON.parse(v.data);if(m.type==="sources"){this.events?.onSourceChange&&this.events.onSourceChange(m.message);continue}if(i.push(m.message),m.endOfBlock)for(;i.length>0;)c.content+=i.shift(),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield c.content}catch(v){console.error("Error parsing SSE event:",v),console.error("Raw message:",d)}}}}catch(l){if(l.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw l}finally{o.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var y=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var S=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){h(this.params.endpoint)?.catch(e=>console.log(e))}};var b=class{id=L();api_key;endpoint;collector;cache;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=f.create(t)}if(e.cache!==!1){let t={};this.cache=new y(t)}this.init()}async search(e,t){await this.initPromise;let s=++this.searchRequestCounter,o=`search-${JSON.stringify(e)}`,n=null,i,a=!1,c=t?.fresh!==!0&&this.cache?.has(o),l=async()=>{try{let u=Date.now();n=await this.fetch("search","POST",{q:e},t?.abortController);let p=Date.now();n.elapsed=await C(BigInt(p*1e6-u*1e6)),i=p-u,this.cache?.set(o,n)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:n?.hits?.length??0,roundTripTime:i,query:e,cached:a,searchedAt:new Date}),n};if(c&&this.cache)i=0,n=this.cache.get(o),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:n?.hits?.length??0,roundTripTime:i,query:e,cached:a,searchedAt:new Date});else return t?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(n)}catch(d){d.name!=="AbortError"&&(console.error("Search request failed",d),p(d))}},t?.debounce||300)}):l();return s===this.searchRequestCounter?n:null}async vectorSearch(e,t){await this.initPromise;let s=`vectorSearch-${JSON.stringify(e)}`,o,n,i=!1;if((t?.fresh!==!0&&this.cache?.has(s))===!0&&this.cache!=null)o=0,n=this.cache.get(s),i=!0;else{let c=Date.now();n=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();n.elapsed=await C(BigInt(l*1e6-c*1e6)),o=l-c,this.cache?.set(s,n)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:n.hits?.length??0,roundTripTime:o,query:e,cached:i,searchedAt:new Date}),n}createAnswerSession(e){return new g({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new S({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,s,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let n={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(t==="POST"&&s!==void 0){let a=s;a.version=_,a.id=this.id,n.body=Object.entries(a).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let i=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,n);if(!i.ok){let a=new Error;throw a.httpResponse=i,a}return await i.json()}};import{onMounted as U,ref as N,shallowRef as k,toValue as $,watchEffect as V}from"vue";import{omit as F}from"lodash";function xe(r){let e=N(!1),t=k(null),s=N(null),o=k();return U(()=>{if(!r.cloudConfig)throw new Error("No config was passed");e.value=!0,o.value=new b(r.cloudConfig)}),V(()=>{let n=Object.keys(F(r,"cloudConfig")).reduce((i,a)=>{let c=a;return i[c]=$(r[c]),i},{});o.value&&o.value.search(n).then(i=>t.value=i).catch(i=>s.value=i)}),{ready:e,results:t,error:s}}export{xe as useSearch};
`))!==-1;){let d=a.slice(0,p);a=a.slice(p+2);try{let b=M(d),v=JSON.parse(b.data);if(v.type==="sources"){this.events?.onSourceChange&&this.events.onSourceChange(v.message);continue}for(o.push(v.message);o.length>0;)c.content+=o.shift(),this.events?.onMessageChange&&(console.log("onMessageChange is defined"),this.events.onMessageChange(this.messages)),yield c.content}catch(b){console.error("Error parsing SSE event:",b),console.error("Raw message:",d)}}}}catch(l){if(l.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw l}finally{i.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var g=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var y=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){h(this.params.endpoint)?.catch(e=>console.log(e))}};var S=class{id=L();api_key;endpoint;collector;cache;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=f.create(t)}if(e.cache!==!1){let t={};this.cache=new g(t)}this.init()}async search(e,t){await this.initPromise;let n=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,s=null,o,a=!1,c=t?.fresh!==!0&&this.cache?.has(i),l=async()=>{try{let u=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let p=Date.now();s.elapsed=await C(BigInt(p*1e6-u*1e6)),o=p-u,this.cache?.set(i,s)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date}),s};if(c&&this.cache)o=0,s=this.cache.get(i),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date});else return t?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(s)}catch(d){d.name!=="AbortError"&&(console.error("Search request failed",d),p(d))}},t?.debounce||300)}):l();return n===this.searchRequestCounter?s:null}async vectorSearch(e,t){await this.initPromise;let n=`vectorSearch-${JSON.stringify(e)}`,i,s,o=!1;if((t?.fresh!==!0&&this.cache?.has(n))===!0&&this.cache!=null)i=0,s=this.cache.get(n),o=!0;else{let c=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await C(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(n,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits?.length??0,roundTripTime:i,query:e,cached:o,searchedAt:new Date}),s}createAnswerSession(e){return new m({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new y({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,n,i){if(i?.signal.aborted===!0)throw new Error("Request aborted");let s={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i?.signal};if(t==="POST"&&n!==void 0){let a=n;a.version=_,a.id=this.id,s.body=Object.entries(a).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!o.ok){let a=new Error;throw a.httpResponse=o,a}return await o.json()}};import{onMounted as U,ref as N,shallowRef as k,toValue as $,watchEffect as V}from"vue";import{omit as F}from"lodash";function xe(r){let e=N(!1),t=k(null),n=N(null),i=k();return U(()=>{if(!r.cloudConfig)throw new Error("No config was passed");e.value=!0,i.value=new S(r.cloudConfig)}),V(()=>{let s=Object.keys(F(r,"cloudConfig")).reduce((o,a)=>{let c=a;return o[c]=$(r[c]),o},{});i.value&&i.value.search(s).then(o=>t.value=o).catch(o=>n.value=o)}),{ready:e,results:t,error:n}}export{xe as useSearch};
//# sourceMappingURL=index.js.map
{
"name": "@oramacloud/client",
"version": "1.2.0",
"version": "1.2.1",
"description": "Orama SDK for Node.js, Deno, and Browsers",

@@ -5,0 +5,0 @@ "type": "module",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc