@oramacloud/client
Advanced tools
Comparing version 1.0.3 to 1.0.4
@@ -1,2 +0,2 @@ | ||
"use strict";var OramaClient=(()=>{var Vt=Object.create;var I=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Xt=Object.getOwnPropertyNames;var Gt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var qt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Wt=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},q=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xt(t))!Yt.call(e,o)&&o!==n&&I(e,o,{get:()=>t[o],enumerable:!(r=Kt(t,o))||r.enumerable});return e};var zt=(e,t,n)=>(n=e!=null?Vt(Gt(e)):{},q(t||!e||!e.__esModule?I(n,"default",{value:e,enumerable:!0}):n,e)),Jt=e=>q(I({},"__esModule",{value:!0}),e);var rt=g(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.output=f.exists=f.hash=f.bytes=f.bool=f.number=void 0;function C(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}f.number=C;function Q(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}f.bool=Q;function j(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}f.bytes=j;function tt(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");C(e.outputLen),C(e.blockLen)}f.hash=tt;function et(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}f.exists=et;function nt(e,t){j(e);let n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=nt;var Zt={number:C,bool:Q,bytes:j,hash:tt,exists:et,output:nt};f.default=Zt});var st=g(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.add=d.toBig=d.split=d.fromBig=void 0;var k=BigInt(2**32-1),H=BigInt(32);function U(e,t=!1){return t?{h:Number(e&k),l:Number(e>>H&k)}:{h:Number(e>>H&k)|0,l:Number(e&k)|0}}d.fromBig=U;function ot(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let o=0;o<e.length;o++){let{h:s,l:i}=U(e[o],t);[n[o],r[o]]=[s,i]}return[n,r]}d.split=ot;var Qt=(e,t)=>BigInt(e>>>0)<<H|BigInt(t>>>0);d.toBig=Qt;var te=(e,t,n)=>e>>>n,ee=(e,t,n)=>e<<32-n|t>>>n,ne=(e,t,n)=>e>>>n|t<<32-n,re=(e,t,n)=>e<<32-n|t>>>n,oe=(e,t,n)=>e<<64-n|t>>>n-32,ie=(e,t,n)=>e>>>n-32|t<<64-n,se=(e,t)=>t,ae=(e,t)=>e,ce=(e,t,n)=>e<<n|t>>>32-n,ue=(e,t,n)=>t<<n|e>>>32-n,le=(e,t,n)=>t<<n-32|e>>>64-n,pe=(e,t,n)=>e<<n-32|t>>>64-n;function it(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}d.add=it;var fe=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),de=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,he=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ye=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,me=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),ge=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0,be={fromBig:U,split:ot,toBig:d.toBig,shrSH:te,shrSL:ee,rotrSH:ne,rotrSL:re,rotrBH:oe,rotrBL:ie,rotr32H:se,rotr32L:ae,rotlSH:ce,rotlSL:ue,rotlBH:le,rotlBL:pe,add:it,add3L:fe,add3H:de,add4L:he,add4H:ye,add5H:ge,add5L:me};d.default=be});var at=g(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.crypto=void 0;var L=qt("node:crypto");v.crypto=L&&typeof L=="object"&&"webcrypto"in L?L.webcrypto:void 0});var ut=g(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var $=at(),V=e=>e instanceof Uint8Array,we=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);a.u8=we;var _e=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));a.u32=_e;var xe=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);a.createView=xe;var Oe=(e,t)=>e<<32-t|e>>>t;a.rotr=Oe;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Ae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Se(e){if(!V(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Ae[e[n]];return t}a.bytesToHex=Se;function Ee(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){let o=r*2,s=e.slice(o,o+2),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Ee;var Te=async()=>{};a.nextTick=Te;async function Ie(e,t,n){let r=Date.now();for(let o=0;o<e;o++){n(o);let s=Date.now()-r;s>=0&&s<t||(await(0,a.nextTick)(),r+=s)}}a.asyncLoop=Ie;function ct(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}a.utf8ToBytes=ct;function P(e){if(typeof e=="string"&&(e=ct(e)),!V(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}a.toBytes=P;function Ce(...e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;return e.forEach(r=>{if(!V(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}a.concatBytes=Ce;var F=class{clone(){return this._cloneInto()}};a.Hash=F;var ke=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function Le(e,t){if(t!==void 0&&(typeof t!="object"||!ke(t)))throw new Error("Options should be object or undefined");return Object.assign(e,t)}a.checkOpts=Le;function ve(e){let t=r=>e().update(P(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}a.wrapConstructor=ve;function Pe(e){let t=(r,o)=>e(o).update(P(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapConstructorWithOpts=Pe;function Be(e){let t=(r,o)=>e(o).update(P(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapXOFConstructorWithOpts=Be;function Ne(e=32){if($.crypto&&typeof $.crypto.getRandomValues=="function")return $.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=Ne});var gt=g(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.shake256=u.shake128=u.keccak_512=u.keccak_384=u.keccak_256=u.keccak_224=u.sha3_512=u.sha3_384=u.sha3_256=u.sha3_224=u.Keccak=u.keccakP=void 0;var b=rt(),x=st(),_=ut(),[ft,dt,ht]=[[],[],[]],Me=BigInt(0),w=BigInt(1),Re=BigInt(2),De=BigInt(7),je=BigInt(256),He=BigInt(113);for(let e=0,t=w,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ft.push(2*(5*r+n)),dt.push((e+1)*(e+2)/2%64);let o=Me;for(let s=0;s<7;s++)t=(t<<w^(t>>De)*He)%je,t&Re&&(o^=w<<(w<<BigInt(s))-w);ht.push(o)}var[Ue,$e]=x.default.split(ht,!0),lt=(e,t,n)=>n>32?x.default.rotlBH(e,t,n):x.default.rotlSH(e,t,n),pt=(e,t,n)=>n>32?x.default.rotlBL(e,t,n):x.default.rotlSL(e,t,n);function yt(e,t=24){let n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,l=(i+2)%10,p=n[l],m=n[l+1],$t=lt(p,m,1)^n[c],Ft=pt(p,m,1)^n[c+1];for(let T=0;T<50;T+=10)e[i+T]^=$t,e[i+T+1]^=Ft}let o=e[2],s=e[3];for(let i=0;i<24;i++){let c=dt[i],l=lt(o,s,c),p=pt(o,s,c),m=ft[i];o=e[m],s=e[m+1],e[m]=l,e[m+1]=p}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=e[i+c];for(let c=0;c<10;c++)e[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}e[0]^=Ue[r],e[1]^=$e[r]}n.fill(0)}u.keccakP=yt;var O=class e extends _.Hash{constructor(t,n,r,o=!1,s=24){if(super(),this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,b.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,_.u32)(this.state)}keccak(){yt(this.state32,this.rounds),this.posOut=0,this.pos=0}update(t){b.default.exists(this);let{blockLen:n,state:r}=this;t=(0,_.toBytes)(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);for(let c=0;c<i;c++)r[this.pos++]^=t[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:n,pos:r,blockLen:o}=this;t[r]^=n,n&128&&r===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){b.default.exists(this,!1),b.default.bytes(t),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,s=t.length;o<s;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,s-o);t.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return b.default.number(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(b.default.output(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(n,r,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=r,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}};u.Keccak=O;var h=(e,t,n)=>(0,_.wrapConstructor)(()=>new O(t,e,n));u.sha3_224=h(6,144,224/8);u.sha3_256=h(6,136,256/8);u.sha3_384=h(6,104,384/8);u.sha3_512=h(6,72,512/8);u.keccak_224=h(1,144,224/8);u.keccak_256=h(1,136,256/8);u.keccak_384=h(1,104,384/8);u.keccak_512=h(1,72,512/8);var mt=(e,t,n)=>(0,_.wrapXOFConstructorWithOpts)((r={})=>new O(t,e,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=mt(31,168,128/8);u.shake256=mt(31,136,256/8)});var Et=g((gn,y)=>{"use strict";var{sha3_512:Fe}=gt(),wt=24,A=32,K=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n=n+Math.floor(t()*36).toString(36);return n};function _t(e){let t=8n,n=0n;for(let r of e.values()){let o=BigInt(r);n=(n<<t)+o}return n}var xt=(e="")=>_t(Fe(e)).toString(36).slice(1),bt=Array.from({length:26},(e,t)=>String.fromCharCode(t+97)),Ve=e=>bt[Math.floor(e()*bt.length)],Ot=({globalObj:e=typeof global<"u"?global:typeof window<"u"?window:{},random:t=Math.random}={})=>{let n=Object.keys(e).toString(),r=n.length?n+K(A,t):K(A,t);return xt(r).substring(0,A)},At=e=>()=>e++,Ke=476782367,St=({random:e=Math.random,counter:t=At(Math.floor(e()*Ke)),length:n=wt,fingerprint:r=Ot({random:e})}={})=>function(){let s=Ve(e),i=Date.now().toString(36),c=t().toString(36),l=K(n,e),p=`${i+l+c+r}`;return`${s+xt(p).substring(1,n)}`},Xe=St(),Ge=(e,{minLength:t=2,maxLength:n=A}={})=>{let r=e.length,o=/^[0-9a-z]+$/;try{if(typeof e=="string"&&r>=t&&r<=n&&o.test(e))return!0}finally{}return!1};y.exports.getConstants=()=>({defaultLength:wt,bigLength:A});y.exports.init=St;y.exports.createId=Xe;y.exports.bufToBigInt=_t;y.exports.createCounter=At;y.exports.createFingerprint=Ot;y.exports.isCuid=Ge});var Tt=g((bn,S)=>{"use strict";var{createId:Ye,init:qe,getConstants:We,isCuid:ze}=Et();S.exports.createId=Ye;S.exports.init=qe;S.exports.getConstants=We;S.exports.isCuid=ze});var on={};Wt(on,{OramaClient:()=>G,OramaProxy:()=>Y});var an=Date.now().toString().slice(5);var W=BigInt(1e3),z=BigInt(1e6),J=BigInt(1e9);async function Z(e){return typeof e=="number"&&(e=BigInt(e)),e<W?`${e}ns`:e<z?`${e/W}\u03BCs`:e<J?`${e/z}ms`:`${e/J}s`}async function D(e){return{raw:Number(e),formatted:await Z(e)}}var Bt=zt(Tt(),1);var B=class{cache;config;constructor(t){this.cache=new Map,this.config=t}set(t,n){this.cache.set(t,n)}get(t){return this.cache.get(t)}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear()}size(){return this.cache.size}};var N="https://secure-proxy.orama.run",It="/init",Ct="/chat",kt="/query";var vt="1.0.3";var Pt={name:"@oramacloud/client",version:vt,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","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.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.1","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@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",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function E(e,t){if(typeof navigator<"u"){navigator.sendBeacon(e,t);return}fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var M=class e{data;params;config;constructor(t){this.data=[],this.config=t}setParams(t){this.params=t}static create(t){let n=new e(t);return n.start(),n}add(t){this.data.push({rawSearchString:t.rawSearchString,query:t.query,resultsCount:t.resultsCount,roundTripTime:t.roundTripTime,searchedAt:t.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 t=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:Pt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:t};E(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let t=setInterval(this.flush.bind(this),this.config.flushInterval);t.unref!=null&&t.unref()}};var R=class{constructor(t){this.params=t}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){E(this.params.endpoint)?.catch(t=>console.log(t))}};var G=class{id=(0,Bt.createId)();api_key;endpoint;collector;cache;heartbeat;initPromise;constructor(t){if(this.api_key=t.api_key,this.endpoint=t.endpoint,t.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:t.telemetry?.flushInterval??5e3,flushSize:t.telemetry?.flushSize??25};this.collector=M.create(n)}if(t.cache!==!1){let n={};this.cache=new B(n)}this.init()}async search(t,n){await this.initPromise;let r=`search-${JSON.stringify(t)}`,o,s,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,s=this.cache.get(r),i=!0;else{let l=Date.now();s=await this.fetch("search","POST",{q:t},n?.abortController);let p=Date.now();s.elapsed=await D(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:s.hits.length,roundTripTime:o,query:t,cached:i,searchedAt:new Date}),s}async vectorSearch(t,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(t)}`,o,s,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,s=this.cache.get(r),i=!0;else{let l=Date.now();s=await this.fetch("vector-search2","POST",{q:t},n?.abortController);let p=Date.now();s.elapsed=await D(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:s.hits.length,roundTripTime:o,query:t,cached:i,searchedAt:new Date}),s}startHeartBeat(t){this.heartbeat?.stop(),this.heartbeat=new R({...t,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(t=>(this.collector?.setParams({endpoint:t.collectUrl,deploymentID:t.deploymentID,index:t.index}),t)).catch(t=>(console.log(t),null))}async fetch(t,n,r,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let s={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(n==="POST"&&r!==void 0){let c=r;c.version=vt,c.id=this.id,s.body=Object.entries(c).map(([l,p])=>`${l}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let i=await fetch(`${this.endpoint}/${t}?api-key=${this.api_key}`,s);if(!i.ok){let c=new Error;throw c.httpResponse=i,c}return await i.json()}};var Nt="text-embedding-ada-002",Mt="gte-small";var Rt="gpt-4-1106-preview",Dt="gpt-4",jt="gpt-3.5-turbo",Ht="gpt-3.5-turbo-16k",Ze={[`openai/${Nt}`]:Nt,[`orama/${Mt}`]:Mt},Qe={[`openai/${jt}`]:jt,[`openai/${Dt}`]:Dt,[`openai/${Ht}`]:Ht,[`openai/${Rt}`]:Rt},Y=class{CSRFToken="";ready;api_key;publicKey;constructor(t){this.api_key=t.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(t,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let o=`${N}${kt}?apiKey=${this.api_key}`;return(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:t,csrf:this.CSRFToken,model:Ze[n]}).toString()})).json()}async chat(t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.chatStream(t))r+=o;return r}async*chatStream(t){let n=`${N}${Ct}?apiKey=${this.api_key}`,r=t.messages;this.publicKey&&(r=await Promise.all(r.map(async c=>!c.content||typeof c.content!="string"?c:{...c,content:await rn(this.publicKey,c.content)})));let o=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:Qe[t.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let s=o.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:l}=await s.read();if(l)break;yield i.decode(c,{stream:!0})}}async init(){let t=`${N}${It}?apiKey=${this.api_key}`,r=await(await fetch(t,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await tn(nn(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 tn(e){return await crypto.subtle.importKey("spki",e,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function en(e,t){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},e,t);return new Uint8Array(n)}function nn(e){return Uint8Array.from(e)}var Ut=50;async function rn(e,t){let n=new TextEncoder().encode(t),r=[];for(let o=0;o<n.length;o+=Ut){let s=n.subarray(o,o+Ut),i=await en(e,s);r.push(Array.from(i))}return r}return Jt(on);})(); | ||
"use strict";var OramaClient=(()=>{var Vt=Object.create;var C=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Xt=Object.getOwnPropertyNames;var Yt=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty;var Gt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Wt=(e,t)=>{for(var n in t)C(e,n,{get:t[n],enumerable:!0})},G=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xt(t))!qt.call(e,o)&&o!==n&&C(e,o,{get:()=>t[o],enumerable:!(r=Kt(t,o))||r.enumerable});return e};var zt=(e,t,n)=>(n=e!=null?Vt(Yt(e)):{},G(t||!e||!e.__esModule?C(n,"default",{value:e,enumerable:!0}):n,e)),Jt=e=>G(C({},"__esModule",{value:!0}),e);var rt=g(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.output=f.exists=f.hash=f.bytes=f.bool=f.number=void 0;function I(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}f.number=I;function Q(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}f.bool=Q;function j(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}f.bytes=j;function tt(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");I(e.outputLen),I(e.blockLen)}f.hash=tt;function et(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}f.exists=et;function nt(e,t){j(e);let n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=nt;var Zt={number:I,bool:Q,bytes:j,hash:tt,exists:et,output:nt};f.default=Zt});var it=g(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.add=d.toBig=d.split=d.fromBig=void 0;var k=BigInt(2**32-1),H=BigInt(32);function U(e,t=!1){return t?{h:Number(e&k),l:Number(e>>H&k)}:{h:Number(e>>H&k)|0,l:Number(e&k)|0}}d.fromBig=U;function ot(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let o=0;o<e.length;o++){let{h:i,l:s}=U(e[o],t);[n[o],r[o]]=[i,s]}return[n,r]}d.split=ot;var Qt=(e,t)=>BigInt(e>>>0)<<H|BigInt(t>>>0);d.toBig=Qt;var te=(e,t,n)=>e>>>n,ee=(e,t,n)=>e<<32-n|t>>>n,ne=(e,t,n)=>e>>>n|t<<32-n,re=(e,t,n)=>e<<32-n|t>>>n,oe=(e,t,n)=>e<<64-n|t>>>n-32,se=(e,t,n)=>e>>>n-32|t<<64-n,ie=(e,t)=>t,ae=(e,t)=>e,ce=(e,t,n)=>e<<n|t>>>32-n,ue=(e,t,n)=>t<<n|e>>>32-n,le=(e,t,n)=>t<<n-32|e>>>64-n,pe=(e,t,n)=>e<<n-32|t>>>64-n;function st(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}d.add=st;var fe=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),de=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,he=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ye=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,me=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),ge=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0,be={fromBig:U,split:ot,toBig:d.toBig,shrSH:te,shrSL:ee,rotrSH:ne,rotrSL:re,rotrBH:oe,rotrBL:se,rotr32H:ie,rotr32L:ae,rotlSH:ce,rotlSL:ue,rotlBH:le,rotlBL:pe,add:st,add3L:fe,add3H:de,add4L:he,add4H:ye,add5H:ge,add5L:me};d.default=be});var at=g(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.crypto=void 0;var P=Gt("node:crypto");v.crypto=P&&typeof P=="object"&&"webcrypto"in P?P.webcrypto:void 0});var ut=g(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var $=at(),V=e=>e instanceof Uint8Array,we=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);a.u8=we;var xe=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));a.u32=xe;var _e=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);a.createView=_e;var Oe=(e,t)=>e<<32-t|e>>>t;a.rotr=Oe;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Se=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ae(e){if(!V(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Se[e[n]];return t}a.bytesToHex=Ae;function Te(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){let o=r*2,i=e.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}a.hexToBytes=Te;var Ee=async()=>{};a.nextTick=Ee;async function Ce(e,t,n){let r=Date.now();for(let o=0;o<e;o++){n(o);let i=Date.now()-r;i>=0&&i<t||(await(0,a.nextTick)(),r+=i)}}a.asyncLoop=Ce;function ct(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}a.utf8ToBytes=ct;function B(e){if(typeof e=="string"&&(e=ct(e)),!V(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}a.toBytes=B;function Ie(...e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;return e.forEach(r=>{if(!V(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}a.concatBytes=Ie;var F=class{clone(){return this._cloneInto()}};a.Hash=F;var ke=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function Pe(e,t){if(t!==void 0&&(typeof t!="object"||!ke(t)))throw new Error("Options should be object or undefined");return Object.assign(e,t)}a.checkOpts=Pe;function ve(e){let t=r=>e().update(B(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}a.wrapConstructor=ve;function Be(e){let t=(r,o)=>e(o).update(B(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapConstructorWithOpts=Be;function Le(e){let t=(r,o)=>e(o).update(B(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapXOFConstructorWithOpts=Le;function Re(e=32){if($.crypto&&typeof $.crypto.getRandomValues=="function")return $.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=Re});var gt=g(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.shake256=u.shake128=u.keccak_512=u.keccak_384=u.keccak_256=u.keccak_224=u.sha3_512=u.sha3_384=u.sha3_256=u.sha3_224=u.Keccak=u.keccakP=void 0;var b=rt(),_=it(),x=ut(),[ft,dt,ht]=[[],[],[]],Ne=BigInt(0),w=BigInt(1),De=BigInt(2),Me=BigInt(7),je=BigInt(256),He=BigInt(113);for(let e=0,t=w,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ft.push(2*(5*r+n)),dt.push((e+1)*(e+2)/2%64);let o=Ne;for(let i=0;i<7;i++)t=(t<<w^(t>>Me)*He)%je,t&De&&(o^=w<<(w<<BigInt(i))-w);ht.push(o)}var[Ue,$e]=_.default.split(ht,!0),lt=(e,t,n)=>n>32?_.default.rotlBH(e,t,n):_.default.rotlSH(e,t,n),pt=(e,t,n)=>n>32?_.default.rotlBL(e,t,n):_.default.rotlSL(e,t,n);function yt(e,t=24){let n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let s=0;s<10;s++)n[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let c=(s+8)%10,l=(s+2)%10,p=n[l],m=n[l+1],$t=lt(p,m,1)^n[c],Ft=pt(p,m,1)^n[c+1];for(let E=0;E<50;E+=10)e[s+E]^=$t,e[s+E+1]^=Ft}let o=e[2],i=e[3];for(let s=0;s<24;s++){let c=dt[s],l=lt(o,i,c),p=pt(o,i,c),m=ft[s];o=e[m],i=e[m+1],e[m]=l,e[m+1]=p}for(let s=0;s<50;s+=10){for(let c=0;c<10;c++)n[c]=e[s+c];for(let c=0;c<10;c++)e[s+c]^=~n[(c+2)%10]&n[(c+4)%10]}e[0]^=Ue[r],e[1]^=$e[r]}n.fill(0)}u.keccakP=yt;var O=class e extends x.Hash{constructor(t,n,r,o=!1,i=24){if(super(),this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,b.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(){yt(this.state32,this.rounds),this.posOut=0,this.pos=0}update(t){b.default.exists(this);let{blockLen:n,state:r}=this;t=(0,x.toBytes)(t);let o=t.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);for(let c=0;c<s;c++)r[this.pos++]^=t[i++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:n,pos:r,blockLen:o}=this;t[r]^=n,n&128&&r===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){b.default.exists(this,!1),b.default.bytes(t),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,i=t.length;o<i;){this.posOut>=r&&this.keccak();let s=Math.min(r-this.posOut,i-o);t.set(n.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return b.default.number(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(b.default.output(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:o,rounds:i,enableXOF:s}=this;return t||(t=new e(n,r,o,s,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=r,t.outputLen=o,t.enableXOF=s,t.destroyed=this.destroyed,t}};u.Keccak=O;var h=(e,t,n)=>(0,x.wrapConstructor)(()=>new O(t,e,n));u.sha3_224=h(6,144,224/8);u.sha3_256=h(6,136,256/8);u.sha3_384=h(6,104,384/8);u.sha3_512=h(6,72,512/8);u.keccak_224=h(1,144,224/8);u.keccak_256=h(1,136,256/8);u.keccak_384=h(1,104,384/8);u.keccak_512=h(1,72,512/8);var mt=(e,t,n)=>(0,x.wrapXOFConstructorWithOpts)((r={})=>new O(t,e,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=mt(31,168,128/8);u.shake256=mt(31,136,256/8)});var Tt=g((gn,y)=>{"use strict";var{sha3_512:Fe}=gt(),wt=24,S=32,K=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n=n+Math.floor(t()*36).toString(36);return n};function xt(e){let t=8n,n=0n;for(let r of e.values()){let o=BigInt(r);n=(n<<t)+o}return n}var _t=(e="")=>xt(Fe(e)).toString(36).slice(1),bt=Array.from({length:26},(e,t)=>String.fromCharCode(t+97)),Ve=e=>bt[Math.floor(e()*bt.length)],Ot=({globalObj:e=typeof global<"u"?global:typeof window<"u"?window:{},random:t=Math.random}={})=>{let n=Object.keys(e).toString(),r=n.length?n+K(S,t):K(S,t);return _t(r).substring(0,S)},St=e=>()=>e++,Ke=476782367,At=({random:e=Math.random,counter:t=St(Math.floor(e()*Ke)),length:n=wt,fingerprint:r=Ot({random:e})}={})=>function(){let i=Ve(e),s=Date.now().toString(36),c=t().toString(36),l=K(n,e),p=`${s+l+c+r}`;return`${i+_t(p).substring(1,n)}`},Xe=At(),Ye=(e,{minLength:t=2,maxLength:n=S}={})=>{let r=e.length,o=/^[0-9a-z]+$/;try{if(typeof e=="string"&&r>=t&&r<=n&&o.test(e))return!0}finally{}return!1};y.exports.getConstants=()=>({defaultLength:wt,bigLength:S});y.exports.init=At;y.exports.createId=Xe;y.exports.bufToBigInt=xt;y.exports.createCounter=St;y.exports.createFingerprint=Ot;y.exports.isCuid=Ye});var Et=g((bn,A)=>{"use strict";var{createId:qe,init:Ge,getConstants:We,isCuid:ze}=Tt();A.exports.createId=qe;A.exports.init=Ge;A.exports.getConstants=We;A.exports.isCuid=ze});var on={};Wt(on,{OramaClient:()=>Y,OramaProxy:()=>q});var an=Date.now().toString().slice(5);var W=BigInt(1e3),z=BigInt(1e6),J=BigInt(1e9);async function Z(e){return typeof e=="number"&&(e=BigInt(e)),e<W?`${e}ns`:e<z?`${e/W}\u03BCs`:e<J?`${e/z}ms`:`${e/J}s`}async function M(e){return{raw:Number(e),formatted:await Z(e)}}var Lt=zt(Et(),1);var L=class{cache;config;constructor(t){this.cache=new Map,this.config=t}set(t,n){this.cache.set(t,n)}get(t){return this.cache.get(t)}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear()}size(){return this.cache.size}};var R="https://secure-proxy.orama.run",Ct="/init",It="/chat",kt="/query";var vt="1.0.4";var Bt={name:"@oramacloud/client",version:vt,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","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts && tsx tests/e2e.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.1","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@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",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function T(e,t){if(typeof navigator<"u"){navigator.sendBeacon(e,t);return}fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var N=class e{data;params;config;constructor(t){this.data=[],this.config=t}setParams(t){this.params=t}static create(t){let n=new e(t);return n.start(),n}add(t){this.data.push({rawSearchString:t.rawSearchString,query:t.query,resultsCount:t.resultsCount,roundTripTime:t.roundTripTime,searchedAt:t.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 t=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:Bt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:t};T(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let t=setInterval(this.flush.bind(this),this.config.flushInterval);t.unref!=null&&t.unref()}};var D=class{constructor(t){this.params=t}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){T(this.params.endpoint)?.catch(t=>console.log(t))}};var Y=class{id=(0,Lt.createId)();api_key;endpoint;collector;cache;heartbeat;initPromise;constructor(t){if(this.api_key=t.api_key,this.endpoint=t.endpoint,t.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:t.telemetry?.flushInterval??5e3,flushSize:t.telemetry?.flushSize??25};this.collector=N.create(n)}if(t.cache!==!1){let n={};this.cache=new L(n)}this.init()}async search(t,n){await this.initPromise;let r=`search-${JSON.stringify(t)}`,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 l=Date.now();i=await this.fetch("search","POST",{q:t},n?.abortController);let p=Date.now();i.elapsed=await M(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,i)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:i.hits.length,roundTripTime:o,query:t,cached:s,searchedAt:new Date}),i}async vectorSearch(t,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(t)}`,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 l=Date.now();i=await this.fetch("vector-search2","POST",{q:t},n?.abortController);let p=Date.now();i.elapsed=await M(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,i)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:i.hits.length,roundTripTime:o,query:t,cached:s,searchedAt:new Date}),i}startHeartBeat(t){this.heartbeat?.stop(),this.heartbeat=new D({...t,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(t=>(this.collector?.setParams({endpoint:t.collectUrl,deploymentID:t.deploymentID,index:t.index}),t)).catch(t=>(console.log(t),null))}async fetch(t,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 c=r;c.version=vt,c.id=this.id,i.body=Object.entries(c).map(([l,p])=>`${l}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let s=await fetch(`${this.endpoint}/${t}?api-key=${this.api_key}`,i);if(!s.ok){let c=new Error;throw c.httpResponse=s,c}return await s.json()}};var Rt="text-embedding-ada-002",Nt="gte-small",Dt="gpt-4-1106-preview",Mt="gpt-4",jt="gpt-3.5-turbo",Ht="gpt-3.5-turbo-16k",Ze={[`openai/${Rt}`]:`openai/${Rt}`,[`orama/${Nt}`]:`orama/${Nt}`},Qe={[`openai/${jt}`]:jt,[`openai/${Mt}`]:Mt,[`openai/${Ht}`]:Ht,[`openai/${Dt}`]:Dt},q=class{CSRFToken="";ready;api_key;publicKey;constructor(t){this.api_key=t.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(t,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let o=`${R}${kt}?apiKey=${this.api_key}`,s=await(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:t,csrf:this.CSRFToken,model:Ze[n]}).toString()})).json();return s.length===1&&(s=s[0]),s}async chat(t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.chatStream(t))r+=o;return r}async*chatStream(t){let n=`${R}${It}?apiKey=${this.api_key}`,r=t.messages;this.publicKey&&(r=await Promise.all(r.map(async c=>!c.content||typeof c.content!="string"?c:{...c,content:await rn(this.publicKey,c.content)})));let o=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:Qe[t.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),s=new TextDecoder;for(;;){let{value:c,done:l}=await i.read();if(l)break;yield s.decode(c,{stream:!0})}}async init(){let t=`${R}${Ct}?apiKey=${this.api_key}`,r=await(await fetch(t,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await tn(nn(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 tn(e){return await crypto.subtle.importKey("spki",e,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function en(e,t){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},e,t);return new Uint8Array(n)}function nn(e){return Uint8Array.from(e)}var Ut=50;async function rn(e,t){let n=new TextEncoder().encode(t),r=[];for(let o=0;o<n.length;o+=Ut){let i=n.subarray(o,o+Ut),s=await en(e,i);r.push(Array.from(s))}return r}return Jt(on);})(); | ||
/*! Bundled license information: | ||
@@ -3,0 +3,0 @@ |
@@ -1,2 +0,2 @@ | ||
import{formatElapsedTime as S}from"@orama/orama/components";import{createId as w}from"@paralleldrive/cuid2";var d=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 h="https://secure-proxy.orama.run",f="/init",C="/chat",_="/query";var O="1.0.3";var E={name:"@oramacloud/client",version:O,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","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.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.1","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@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",openai:"^4.24.1","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(a,e){if(typeof navigator<"u"){navigator.sendBeacon(a,e);return}fetch(a,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var u=class a{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new a(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:E.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};p(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var m=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 A=class{id=w();api_key;endpoint;collector;cache;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=u.create(t)}if(e.cache!==!1){let t={};this.cache=new d(t)}this.init()}async search(e,t){await this.initPromise;let r=`search-${JSON.stringify(e)}`,i,s,o=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)i=0,s=this.cache.get(r),o=!0;else{let c=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await S(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits.length,roundTripTime:i,query:e,cached:o,searchedAt:new Date}),s}async vectorSearch(e,t){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,i,s,o=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)i=0,s=this.cache.get(r),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 S(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits.length,roundTripTime:i,query:e,cached:o,searchedAt:new Date}),s}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new m({...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,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"&&r!==void 0){let n=r;n.version=O,n.id=this.id,s.body=Object.entries(n).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 n=new Error;throw n.httpResponse=o,n}return await o.json()}};var T="text-embedding-ada-002",b="gte-small";var v="gpt-4-1106-preview",R="gpt-4",P="gpt-3.5-turbo",D="gpt-3.5-turbo-16k",N={[`openai/${T}`]:T,[`orama/${b}`]:b},k={[`openai/${P}`]:P,[`openai/${R}`]:R,[`openai/${D}`]:D,[`openai/${v}`]:v},I=class{CSRFToken="";ready;api_key;publicKey;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 i=`${h}${_}?apiKey=${this.api_key}`;return(await fetch(i,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:N[t]}).toString()})).json()}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let i of this.chatStream(e))r+=i;return r}async*chatStream(e){let t=`${h}${C}?apiKey=${this.api_key}`,r=e.messages;this.publicKey&&(r=await Promise.all(r.map(async n=>!n.content||typeof n.content!="string"?n:{...n,content:await H(this.publicKey,n.content)})));let i=await fetch(t,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:k[e.model]}).toString()});if(!i.ok||i.body==null)throw i.statusText;let s=i.body.getReader(),o=new TextDecoder;for(;;){let{value:n,done:c}=await s.read();if(c)break;yield o.decode(n,{stream:!0})}}async init(){let e=`${h}${f}?apiKey=${this.api_key}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await L(j(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 L(a){return await crypto.subtle.importKey("spki",a,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function B(a,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},a,e);return new Uint8Array(t)}function j(a){return Uint8Array.from(a)}var x=50;async function H(a,e){let t=new TextEncoder().encode(e),r=[];for(let i=0;i<t.length;i+=x){let s=t.subarray(i,i+x),o=await B(a,s);r.push(Array.from(o))}return r}export{A as OramaClient,I as OramaProxy}; | ||
import{formatElapsedTime as E}from"@orama/orama/components";import{createId as N}from"@paralleldrive/cuid2";var d=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 h="https://secure-proxy.orama.run",f="/init",C="/chat",g="/query";var O="1.0.4";var S={name:"@oramacloud/client",version:O,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","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts && tsx tests/e2e.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.1","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@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",openai:"^4.24.1","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(o,e){if(typeof navigator<"u"){navigator.sendBeacon(o,e);return}fetch(o,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var u=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:S.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};p(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var m=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 T=class{id=N();api_key;endpoint;collector;cache;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=u.create(t)}if(e.cache!==!1){let t={};this.cache=new d(t)}this.init()}async search(e,t){await this.initPromise;let r=`search-${JSON.stringify(e)}`,i,s,a=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)i=0,s=this.cache.get(r),a=!0;else{let c=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await E(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits.length,roundTripTime:i,query:e,cached:a,searchedAt:new Date}),s}async vectorSearch(e,t){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,i,s,a=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)i=0,s=this.cache.get(r),a=!0;else{let c=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await E(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits.length,roundTripTime:i,query:e,cached:a,searchedAt:new Date}),s}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new m({...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,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"&&r!==void 0){let n=r;n.version=O,n.id=this.id,s.body=Object.entries(n).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let a=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!a.ok){let n=new Error;throw n.httpResponse=a,n}return await a.json()}};var A="text-embedding-ada-002",b="gte-small",v="gpt-4-1106-preview",R="gpt-4",P="gpt-3.5-turbo",x="gpt-3.5-turbo-16k",M={[`openai/${A}`]:`openai/${A}`,[`orama/${b}`]:`orama/${b}`},k={[`openai/${P}`]:P,[`openai/${R}`]:R,[`openai/${x}`]:x,[`openai/${v}`]:v},D=class{CSRFToken="";ready;api_key;publicKey;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 i=`${h}${g}?apiKey=${this.api_key}`,a=await(await fetch(i,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:M[t]}).toString()})).json();return a.length===1&&(a=a[0]),a}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let i of this.chatStream(e))r+=i;return r}async*chatStream(e){let t=`${h}${C}?apiKey=${this.api_key}`,r=e.messages;this.publicKey&&(r=await Promise.all(r.map(async n=>!n.content||typeof n.content!="string"?n:{...n,content:await H(this.publicKey,n.content)})));let i=await fetch(t,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:k[e.model]}).toString()});if(!i.ok||i.body==null)throw i.statusText;let s=i.body.getReader(),a=new TextDecoder;for(;;){let{value:n,done:c}=await s.read();if(c)break;yield a.decode(n,{stream:!0})}}async init(){let e=`${h}${f}?apiKey=${this.api_key}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await L(B(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 L(o){return await crypto.subtle.importKey("spki",o,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function j(o,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},o,e);return new Uint8Array(t)}function B(o){return Uint8Array.from(o)}var I=50;async function H(o,e){let t=new TextEncoder().encode(e),r=[];for(let i=0;i<t.length;i+=I){let s=t.subarray(i,i+I),a=await j(o,s);r.push(Array.from(a))}return r}export{T as OramaClient,D as OramaProxy}; | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,2 @@ | ||
import{formatElapsedTime as b}from"@orama/orama/components";import{createId as w}from"@paralleldrive/cuid2";var u=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 g="1.0.3";var v={name:"@oramacloud/client",version:g,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","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.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.1","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@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",openai:"^4.24.1","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(s,e){if(typeof navigator<"u"){navigator.sendBeacon(s,e);return}fetch(s,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var d=class s{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new s(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:v.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(i=>console.log(i))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var p=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 m=class{id=w();api_key;endpoint;collector;cache;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=d.create(t)}if(e.cache!==!1){let t={};this.cache=new u(t)}this.init()}async search(e,t){await this.initPromise;let i=`search-${JSON.stringify(e)}`,a,r,n=!1;if((t?.fresh!==!0&&this.cache?.has(i))===!0&&this.cache!=null)a=0,r=this.cache.get(i),n=!0;else{let c=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await b(BigInt(l*1e6-c*1e6)),a=l-c,this.cache?.set(i,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits.length,roundTripTime:a,query:e,cached:n,searchedAt:new Date}),r}async vectorSearch(e,t){await this.initPromise;let i=`vectorSearch-${JSON.stringify(e)}`,a,r,n=!1;if((t?.fresh!==!0&&this.cache?.has(i))===!0&&this.cache!=null)a=0,r=this.cache.get(i),n=!0;else{let c=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await b(BigInt(l*1e6-c*1e6)),a=l-c,this.cache?.set(i,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits.length,roundTripTime:a,query:e,cached:n,searchedAt:new Date}),r}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new p({...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,i,a){if(a?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:a?.signal};if(t==="POST"&&i!==void 0){let o=i;o.version=g,o.id=this.id,r.body=Object.entries(o).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let n=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!n.ok){let o=new Error;throw o.httpResponse=n,o}return await n.json()}};import R,{useState as f,useEffect as S,createContext as E,useContext as I}from"react";var x=E({endpoint:"",apiKey:""}),Y=({children:s,endpoint:e,apiKey:t})=>R.createElement(x.Provider,{value:{endpoint:e,apiKey:t}},s);function G(s){let{apiKey:e,endpoint:t}=I(x),[i,a]=f(!1),[r,n]=f(null),[o,c]=f(null),[l,O]=f(null);return S(()=>{n(new m({api_key:e,endpoint:t})),a(!0)},[]),S(()=>{r!==null&&r.search(s).then(c).catch(O)},[r,s]),{ready:i,results:o,error:l}}export{Y as OramaCloud,G as useSearch}; | ||
import{formatElapsedTime as b}from"@orama/orama/components";import{createId as w}from"@paralleldrive/cuid2";var u=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 g="1.0.4";var v={name:"@oramacloud/client",version:g,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","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts && tsx tests/e2e.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.1","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@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",openai:"^4.24.1","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(s,e){if(typeof navigator<"u"){navigator.sendBeacon(s,e);return}fetch(s,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var d=class s{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new s(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:v.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(i=>console.log(i))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var p=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 m=class{id=w();api_key;endpoint;collector;cache;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=d.create(t)}if(e.cache!==!1){let t={};this.cache=new u(t)}this.init()}async search(e,t){await this.initPromise;let i=`search-${JSON.stringify(e)}`,a,r,n=!1;if((t?.fresh!==!0&&this.cache?.has(i))===!0&&this.cache!=null)a=0,r=this.cache.get(i),n=!0;else{let c=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await b(BigInt(l*1e6-c*1e6)),a=l-c,this.cache?.set(i,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits.length,roundTripTime:a,query:e,cached:n,searchedAt:new Date}),r}async vectorSearch(e,t){await this.initPromise;let i=`vectorSearch-${JSON.stringify(e)}`,a,r,n=!1;if((t?.fresh!==!0&&this.cache?.has(i))===!0&&this.cache!=null)a=0,r=this.cache.get(i),n=!0;else{let c=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await b(BigInt(l*1e6-c*1e6)),a=l-c,this.cache?.set(i,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits.length,roundTripTime:a,query:e,cached:n,searchedAt:new Date}),r}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new p({...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,i,a){if(a?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:a?.signal};if(t==="POST"&&i!==void 0){let o=i;o.version=g,o.id=this.id,r.body=Object.entries(o).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let n=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!n.ok){let o=new Error;throw o.httpResponse=n,o}return await n.json()}};import R,{useState as f,useEffect as S,createContext as E,useContext as I}from"react";var x=E({endpoint:"",apiKey:""}),Y=({children:s,endpoint:e,apiKey:t})=>R.createElement(x.Provider,{value:{endpoint:e,apiKey:t}},s);function G(s){let{apiKey:e,endpoint:t}=I(x),[i,a]=f(!1),[r,n]=f(null),[o,c]=f(null),[l,O]=f(null);return S(()=>{n(new m({api_key:e,endpoint:t})),a(!0)},[]),S(()=>{r!==null&&r.search(s).then(c).catch(O)},[r,s]),{ready:i,results:o,error:l}}export{Y as OramaCloud,G as useSearch}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@oramacloud/client", | ||
"version": "1.0.3", | ||
"version": "1.0.4", | ||
"description": "Orama SDK for Node.js, Deno, and Browsers", | ||
@@ -77,5 +77,5 @@ "type": "module", | ||
"build:vue": "tsup --config tsup.vue.js", | ||
"test": "tsx tests/index.test.ts", | ||
"test": "tsx tests/index.test.ts && tsx tests/e2e.test.ts", | ||
"serve:example": "esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example" | ||
} | ||
} |
@@ -5,3 +5,3 @@ # Orama Cloud Client | ||
```js | ||
```sh | ||
npm i @oramacloud/client | ||
@@ -8,0 +8,0 @@ ``` |
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
297
252631