@oramacloud/client
Advanced tools
Comparing version 1.0.10 to 1.0.11
@@ -1,2 +0,2 @@ | ||
"use strict";var OramaClient=(()=>{var Xt=Object.create;var k=Object.defineProperty;var Yt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var Zt=(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),Qt=(e,t)=>{for(var n in t)k(e,n,{get:t[n],enumerable:!0})},z=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Wt(t))!Jt.call(e,o)&&o!==n&&k(e,o,{get:()=>t[o],enumerable:!(r=Yt(t,o))||r.enumerable});return e};var te=(e,t,n)=>(n=e!=null?Xt(zt(e)):{},z(t||!e||!e.__esModule?k(n,"default",{value:e,enumerable:!0}):n,e)),ee=e=>z(k({},"__esModule",{value:!0}),e);var it=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 P(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}f.number=P;function et(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}f.bool=et;function $(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=$;function nt(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");P(e.outputLen),P(e.blockLen)}f.hash=nt;function rt(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=rt;function ot(e,t){$(e);let n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=ot;var ne={number:P,bool:et,bytes:$,hash:nt,exists:rt,output:ot};f.default=ne});var ct=g(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.add=h.toBig=h.split=h.fromBig=void 0;var R=BigInt(2**32-1),U=BigInt(32);function F(e,t=!1){return t?{h:Number(e&R),l:Number(e>>U&R)}:{h:Number(e>>U&R)|0,l:Number(e&R)|0}}h.fromBig=F;function st(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}=F(e[o],t);[n[o],r[o]]=[s,i]}return[n,r]}h.split=st;var re=(e,t)=>BigInt(e>>>0)<<U|BigInt(t>>>0);h.toBig=re;var oe=(e,t,n)=>e>>>n,ie=(e,t,n)=>e<<32-n|t>>>n,se=(e,t,n)=>e>>>n|t<<32-n,ae=(e,t,n)=>e<<32-n|t>>>n,ce=(e,t,n)=>e<<64-n|t>>>n-32,ue=(e,t,n)=>e>>>n-32|t<<64-n,le=(e,t)=>t,pe=(e,t)=>e,de=(e,t,n)=>e<<n|t>>>32-n,fe=(e,t,n)=>t<<n|e>>>32-n,he=(e,t,n)=>t<<n-32|e>>>64-n,ye=(e,t,n)=>e<<n-32|t>>>64-n;function at(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}h.add=at;var me=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ge=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,be=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),we=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,_e=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),xe=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0,Oe={fromBig:F,split:st,toBig:h.toBig,shrSH:oe,shrSL:ie,rotrSH:se,rotrSL:ae,rotrBH:ce,rotrBL:ue,rotr32H:le,rotr32L:pe,rotlSH:de,rotlSL:fe,rotlBH:he,rotlBL:ye,add:at,add3L:me,add3H:ge,add4L:be,add4H:we,add5H:xe,add5L:_e};h.default=Oe});var ut=g(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.crypto=void 0;var v=Zt("node:crypto");D.crypto=v&&typeof v=="object"&&"webcrypto"in v?v.webcrypto:void 0});var pt=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 V=ut(),K=e=>e instanceof Uint8Array,Ee=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);a.u8=Ee;var Ae=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));a.u32=Ae;var Se=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);a.createView=Se;var Te=(e,t)=>e<<32-t|e>>>t;a.rotr=Te;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Ce=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ie(e){if(!K(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Ce[e[n]];return t}a.bytesToHex=Ie;function ke(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=ke;var Pe=async()=>{};a.nextTick=Pe;async function Re(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=Re;function lt(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}a.utf8ToBytes=lt;function N(e){if(typeof e=="string"&&(e=lt(e)),!K(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}a.toBytes=N;function ve(...e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;return e.forEach(r=>{if(!K(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}a.concatBytes=ve;var G=class{clone(){return this._cloneInto()}};a.Hash=G;var De=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function Ne(e,t){if(t!==void 0&&(typeof t!="object"||!De(t)))throw new Error("Options should be object or undefined");return Object.assign(e,t)}a.checkOpts=Ne;function Le(e){let t=r=>e().update(N(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}a.wrapConstructor=Le;function Be(e){let t=(r,o)=>e(o).update(N(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapConstructorWithOpts=Be;function Me(e){let t=(r,o)=>e(o).update(N(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapXOFConstructorWithOpts=Me;function je(e=32){if(V.crypto&&typeof V.crypto.getRandomValues=="function")return V.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=je});var wt=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 w=it(),E=ct(),O=pt(),[ht,yt,mt]=[[],[],[]],He=BigInt(0),x=BigInt(1),$e=BigInt(2),Ue=BigInt(7),Fe=BigInt(256),Ve=BigInt(113);for(let e=0,t=x,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ht.push(2*(5*r+n)),yt.push((e+1)*(e+2)/2%64);let o=He;for(let s=0;s<7;s++)t=(t<<x^(t>>Ue)*Ve)%Fe,t&$e&&(o^=x<<(x<<BigInt(s))-x);mt.push(o)}var[Ge,Ke]=E.default.split(mt,!0),dt=(e,t,n)=>n>32?E.default.rotlBH(e,t,n):E.default.rotlSH(e,t,n),ft=(e,t,n)=>n>32?E.default.rotlBL(e,t,n):E.default.rotlSL(e,t,n);function gt(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,d=n[l],p=n[l+1],b=dt(d,p,1)^n[c],_=ft(d,p,1)^n[c+1];for(let I=0;I<50;I+=10)e[i+I]^=b,e[i+I+1]^=_}let o=e[2],s=e[3];for(let i=0;i<24;i++){let c=yt[i],l=dt(o,s,c),d=ft(o,s,c),p=ht[i];o=e[p],s=e[p+1],e[p]=l,e[p+1]=d}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]^=Ge[r],e[1]^=Ke[r]}n.fill(0)}u.keccakP=gt;var A=class e extends O.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,w.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,O.u32)(this.state)}keccak(){gt(this.state32,this.rounds),this.posOut=0,this.pos=0}update(t){w.default.exists(this);let{blockLen:n,state:r}=this;t=(0,O.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){w.default.exists(this,!1),w.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 w.default.number(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(w.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=A;var y=(e,t,n)=>(0,O.wrapConstructor)(()=>new A(t,e,n));u.sha3_224=y(6,144,224/8);u.sha3_256=y(6,136,256/8);u.sha3_384=y(6,104,384/8);u.sha3_512=y(6,72,512/8);u.keccak_224=y(1,144,224/8);u.keccak_256=y(1,136,256/8);u.keccak_384=y(1,104,384/8);u.keccak_512=y(1,72,512/8);var bt=(e,t,n)=>(0,O.wrapXOFConstructorWithOpts)((r={})=>new A(t,e,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=bt(31,168,128/8);u.shake256=bt(31,136,256/8)});var Ct=g((xn,m)=>{"use strict";var{sha3_512:qe}=wt(),xt=24,S=32,q=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n=n+Math.floor(t()*36).toString(36);return n};function Ot(e){let t=8n,n=0n;for(let r of e.values()){let o=BigInt(r);n=(n<<t)+o}return n}var Et=(e="")=>Ot(qe(e)).toString(36).slice(1),_t=Array.from({length:26},(e,t)=>String.fromCharCode(t+97)),Xe=e=>_t[Math.floor(e()*_t.length)],At=({globalObj:e=typeof global<"u"?global:typeof window<"u"?window:{},random:t=Math.random}={})=>{let n=Object.keys(e).toString(),r=n.length?n+q(S,t):q(S,t);return Et(r).substring(0,S)},St=e=>()=>e++,Ye=476782367,Tt=({random:e=Math.random,counter:t=St(Math.floor(e()*Ye)),length:n=xt,fingerprint:r=At({random:e})}={})=>function(){let s=Xe(e),i=Date.now().toString(36),c=t().toString(36),l=q(n,e),d=`${i+l+c+r}`;return`${s+Et(d).substring(1,n)}`},We=Tt(),ze=(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};m.exports.getConstants=()=>({defaultLength:xt,bigLength:S});m.exports.init=Tt;m.exports.createId=We;m.exports.bufToBigInt=Ot;m.exports.createCounter=St;m.exports.createFingerprint=At;m.exports.isCuid=ze});var It=g((On,T)=>{"use strict";var{createId:Je,init:Ze,getConstants:Qe,isCuid:tn}=Ct();T.exports.createId=Je;T.exports.init=Ze;T.exports.getConstants=Qe;T.exports.isCuid=tn});var un={};Qt(un,{OramaClient:()=>Y,OramaProxy:()=>W});var pn=Date.now().toString().slice(5);var J=BigInt(1e3),Z=BigInt(1e6),Q=BigInt(1e9);async function tt(e){return typeof e=="number"&&(e=BigInt(e)),e<J?`${e}ns`:e<Z?`${e/J}\u03BCs`:e<Q?`${e/Z}ms`:`${e/Q}s`}async function H(e){return{raw:Number(e),formatted:await tt(e)}}var Lt=te(It(),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 B="https://secure-proxy.orama.run",kt="/init",Pt="/chat",Rt="/query";var Dt="1.0.10";var Nt={name:"@oramacloud/client",version:Dt,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:"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.1","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21","lodash.debounce":"^4.0.8","lodash.throttle":"^4.1.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/lodash.debounce":"^4.0.9","@types/lodash.throttle":"^4.1.9","@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 C(e,t){if(typeof navigator<"u"){typeof navigator.sendBeacon<"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:Nt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:t};C(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 j=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(){C(this.params.endpoint)?.catch(t=>console.log(t))}};var Y=class{id=(0,Lt.createId)();api_key;endpoint;collector;cache;abortController;searchDebounceTimer;searchRequestCounter=0;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 L(n)}this.init()}async search(t,n){await this.initPromise;let r=++this.searchRequestCounter,o=`search-${JSON.stringify(t)}`,s,i,c=!1,l=n?.fresh!==!0&&this.cache?.has(o),d=async()=>{try{let p=Date.now();s=await this.fetch("search","POST",{q:t},this.abortController);let b=Date.now();s.elapsed=await H(BigInt(b*1e6-p*1e6)),i=b-p,this.cache?.set(o,s)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&this.collector.add({rawSearchString:t.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:t,cached:c,searchedAt:new Date}),s};if(l&&this.cache)i=0,s=this.cache.get(o),c=!0,this.collector&&this.collector.add({rawSearchString:t.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:t,cached:c,searchedAt:new Date});else return n?.debounce?new Promise((p,b)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await d(),p(s)}catch(_){_.name!=="AbortError"&&(console.error("Search request failed",_),b(_))}},n?.debounce||300)}):d();return r===this.searchRequestCounter?s:null}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 d=Date.now();s.elapsed=await H(BigInt(d*1e6-l*1e6)),o=d-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:s.hits?.length??0,roundTripTime:o,query:t,cached:i,searchedAt:new Date}),s}startHeartBeat(t){this.heartbeat?.stop(),this.heartbeat=new j({...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=Dt,c.id=this.id,s.body=Object.entries(c).map(([l,d])=>`${l}=${encodeURIComponent(JSON.stringify(d))}`).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 Bt="text-embedding-ada-002",Mt="text-embedding-3-small",jt="text-embedding-3-large",Ht="gte-small",$t="gte-medium",Ut="gte-large",Ft="gpt-4-1106-preview",Vt="gpt-4",Gt="gpt-3.5-turbo",Kt="gpt-3.5-turbo-16k",nn={[`openai/${Bt}`]:`openai/${Bt}`,[`openai/${Mt}`]:`openai/${Mt}`,[`openai/${jt}`]:`openai/${jt}`,[`orama/${Ut}`]:`orama/${Ut}`,[`orama/${$t}`]:`orama/${$t}`,[`orama/${Ht}`]:`orama/${Ht}`},rn={[`openai/${Gt}`]:Gt,[`openai/${Vt}`]:Vt,[`openai/${Kt}`]:Kt,[`openai/${Ft}`]:Ft},W=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=`${B}${Rt}?apiKey=${this.api_key}`,i=await(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:t,csrf:this.CSRFToken,model:nn[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}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){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${B}${Pt}?apiKey=${this.api_key}`,o=t.messages;this.publicKey&&(o=await Promise.all(o.map(async l=>!l.content||typeof l.content!="string"?l:{...l,content:await cn(this.publicKey,l.content)})));let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(o),csrf:this.CSRFToken,model:rn[t.model]}).toString()});if(!s.ok||s.body==null)throw s.statusText;let i=s.body.getReader(),c=new TextDecoder;for(;;){let{value:l,done:d}=await i.read();if(d)break;yield c.decode(l,{stream:!0})}}async init(){let t=`${B}${kt}?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 on(an(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 on(e){return await crypto.subtle.importKey("spki",e,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function sn(e,t){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},e,t);return new Uint8Array(n)}function an(e){return Uint8Array.from(e)}var qt=50;async function cn(e,t){let n=new TextEncoder().encode(t),r=[];for(let o=0;o<n.length;o+=qt){let s=n.subarray(o,o+qt),i=await sn(e,s);r.push(Array.from(i))}return r}return ee(un);})(); | ||
"use strict";var OramaClient=(()=>{var Xt=Object.create;var k=Object.defineProperty;var Yt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var Zt=(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),Qt=(e,t)=>{for(var n in t)k(e,n,{get:t[n],enumerable:!0})},z=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Wt(t))!Jt.call(e,o)&&o!==n&&k(e,o,{get:()=>t[o],enumerable:!(r=Yt(t,o))||r.enumerable});return e};var te=(e,t,n)=>(n=e!=null?Xt(zt(e)):{},z(t||!e||!e.__esModule?k(n,"default",{value:e,enumerable:!0}):n,e)),ee=e=>z(k({},"__esModule",{value:!0}),e);var it=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 R(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}f.number=R;function et(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}f.bool=et;function H(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=H;function nt(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");R(e.outputLen),R(e.blockLen)}f.hash=nt;function rt(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=rt;function ot(e,t){H(e);let n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=ot;var ne={number:R,bool:et,bytes:H,hash:nt,exists:rt,output:ot};f.default=ne});var ct=g(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.add=h.toBig=h.split=h.fromBig=void 0;var P=BigInt(2**32-1),$=BigInt(32);function F(e,t=!1){return t?{h:Number(e&P),l:Number(e>>$&P)}:{h:Number(e>>$&P)|0,l:Number(e&P)|0}}h.fromBig=F;function st(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}=F(e[o],t);[n[o],r[o]]=[s,i]}return[n,r]}h.split=st;var re=(e,t)=>BigInt(e>>>0)<<$|BigInt(t>>>0);h.toBig=re;var oe=(e,t,n)=>e>>>n,ie=(e,t,n)=>e<<32-n|t>>>n,se=(e,t,n)=>e>>>n|t<<32-n,ae=(e,t,n)=>e<<32-n|t>>>n,ce=(e,t,n)=>e<<64-n|t>>>n-32,ue=(e,t,n)=>e>>>n-32|t<<64-n,le=(e,t)=>t,pe=(e,t)=>e,de=(e,t,n)=>e<<n|t>>>32-n,fe=(e,t,n)=>t<<n|e>>>32-n,he=(e,t,n)=>t<<n-32|e>>>64-n,ye=(e,t,n)=>e<<n-32|t>>>64-n;function at(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}h.add=at;var me=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ge=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,be=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),we=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,_e=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),xe=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0,Oe={fromBig:F,split:st,toBig:h.toBig,shrSH:oe,shrSL:ie,rotrSH:se,rotrSL:ae,rotrBH:ce,rotrBL:ue,rotr32H:le,rotr32L:pe,rotlSH:de,rotlSL:fe,rotlBH:he,rotlBL:ye,add:at,add3L:me,add3H:ge,add4L:be,add4H:we,add5H:xe,add5L:_e};h.default=Oe});var ut=g(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.crypto=void 0;var v=Zt("node:crypto");D.crypto=v&&typeof v=="object"&&"webcrypto"in v?v.webcrypto:void 0});var pt=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 V=ut(),K=e=>e instanceof Uint8Array,Ee=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);a.u8=Ee;var Ae=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));a.u32=Ae;var Se=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);a.createView=Se;var Te=(e,t)=>e<<32-t|e>>>t;a.rotr=Te;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Ce=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ie(e){if(!K(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Ce[e[n]];return t}a.bytesToHex=Ie;function ke(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=ke;var Re=async()=>{};a.nextTick=Re;async function Pe(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=Pe;function lt(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}a.utf8ToBytes=lt;function N(e){if(typeof e=="string"&&(e=lt(e)),!K(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}a.toBytes=N;function ve(...e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;return e.forEach(r=>{if(!K(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}a.concatBytes=ve;var G=class{clone(){return this._cloneInto()}};a.Hash=G;var De=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function Ne(e,t){if(t!==void 0&&(typeof t!="object"||!De(t)))throw new Error("Options should be object or undefined");return Object.assign(e,t)}a.checkOpts=Ne;function Le(e){let t=r=>e().update(N(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}a.wrapConstructor=Le;function Be(e){let t=(r,o)=>e(o).update(N(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapConstructorWithOpts=Be;function Me(e){let t=(r,o)=>e(o).update(N(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapXOFConstructorWithOpts=Me;function je(e=32){if(V.crypto&&typeof V.crypto.getRandomValues=="function")return V.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=je});var wt=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 w=it(),E=ct(),O=pt(),[ht,yt,mt]=[[],[],[]],Ue=BigInt(0),x=BigInt(1),He=BigInt(2),$e=BigInt(7),Fe=BigInt(256),Ve=BigInt(113);for(let e=0,t=x,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ht.push(2*(5*r+n)),yt.push((e+1)*(e+2)/2%64);let o=Ue;for(let s=0;s<7;s++)t=(t<<x^(t>>$e)*Ve)%Fe,t&He&&(o^=x<<(x<<BigInt(s))-x);mt.push(o)}var[Ge,Ke]=E.default.split(mt,!0),dt=(e,t,n)=>n>32?E.default.rotlBH(e,t,n):E.default.rotlSH(e,t,n),ft=(e,t,n)=>n>32?E.default.rotlBL(e,t,n):E.default.rotlSL(e,t,n);function gt(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,d=n[l],p=n[l+1],b=dt(d,p,1)^n[c],_=ft(d,p,1)^n[c+1];for(let I=0;I<50;I+=10)e[i+I]^=b,e[i+I+1]^=_}let o=e[2],s=e[3];for(let i=0;i<24;i++){let c=yt[i],l=dt(o,s,c),d=ft(o,s,c),p=ht[i];o=e[p],s=e[p+1],e[p]=l,e[p+1]=d}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]^=Ge[r],e[1]^=Ke[r]}n.fill(0)}u.keccakP=gt;var A=class e extends O.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,w.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,O.u32)(this.state)}keccak(){gt(this.state32,this.rounds),this.posOut=0,this.pos=0}update(t){w.default.exists(this);let{blockLen:n,state:r}=this;t=(0,O.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){w.default.exists(this,!1),w.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 w.default.number(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(w.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=A;var y=(e,t,n)=>(0,O.wrapConstructor)(()=>new A(t,e,n));u.sha3_224=y(6,144,224/8);u.sha3_256=y(6,136,256/8);u.sha3_384=y(6,104,384/8);u.sha3_512=y(6,72,512/8);u.keccak_224=y(1,144,224/8);u.keccak_256=y(1,136,256/8);u.keccak_384=y(1,104,384/8);u.keccak_512=y(1,72,512/8);var bt=(e,t,n)=>(0,O.wrapXOFConstructorWithOpts)((r={})=>new A(t,e,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=bt(31,168,128/8);u.shake256=bt(31,136,256/8)});var Ct=g((xn,m)=>{"use strict";var{sha3_512:qe}=wt(),xt=24,S=32,q=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n=n+Math.floor(t()*36).toString(36);return n};function Ot(e){let t=8n,n=0n;for(let r of e.values()){let o=BigInt(r);n=(n<<t)+o}return n}var Et=(e="")=>Ot(qe(e)).toString(36).slice(1),_t=Array.from({length:26},(e,t)=>String.fromCharCode(t+97)),Xe=e=>_t[Math.floor(e()*_t.length)],At=({globalObj:e=typeof global<"u"?global:typeof window<"u"?window:{},random:t=Math.random}={})=>{let n=Object.keys(e).toString(),r=n.length?n+q(S,t):q(S,t);return Et(r).substring(0,S)},St=e=>()=>e++,Ye=476782367,Tt=({random:e=Math.random,counter:t=St(Math.floor(e()*Ye)),length:n=xt,fingerprint:r=At({random:e})}={})=>function(){let s=Xe(e),i=Date.now().toString(36),c=t().toString(36),l=q(n,e),d=`${i+l+c+r}`;return`${s+Et(d).substring(1,n)}`},We=Tt(),ze=(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};m.exports.getConstants=()=>({defaultLength:xt,bigLength:S});m.exports.init=Tt;m.exports.createId=We;m.exports.bufToBigInt=Ot;m.exports.createCounter=St;m.exports.createFingerprint=At;m.exports.isCuid=ze});var It=g((On,T)=>{"use strict";var{createId:Je,init:Ze,getConstants:Qe,isCuid:tn}=Ct();T.exports.createId=Je;T.exports.init=Ze;T.exports.getConstants=Qe;T.exports.isCuid=tn});var un={};Qt(un,{OramaClient:()=>Y,OramaProxy:()=>W});var pn=Date.now().toString().slice(5);var J=BigInt(1e3),Z=BigInt(1e6),Q=BigInt(1e9);async function tt(e){return typeof e=="number"&&(e=BigInt(e)),e<J?`${e}ns`:e<Z?`${e/J}\u03BCs`:e<Q?`${e/Z}ms`:`${e/Q}s`}async function U(e){return{raw:Number(e),formatted:await tt(e)}}var Lt=te(It(),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 B="https://secure-proxy.orama.run",kt="/init",Rt="/chat",Pt="/query";var Dt="1.0.10";var Nt={name:"@oramacloud/client",version:Dt,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:"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.1","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21","lodash.debounce":"^4.0.8","lodash.throttle":"^4.1.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/lodash.debounce":"^4.0.9","@types/lodash.throttle":"^4.1.9","@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 C(e,t){if(typeof navigator<"u"){typeof navigator.sendBeacon<"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:Nt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:t};C(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 j=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(){C(this.params.endpoint)?.catch(t=>console.log(t))}};var Y=class{id=(0,Lt.createId)();api_key;endpoint;collector;cache;abortController;searchDebounceTimer;searchRequestCounter=0;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 L(n)}this.init()}async search(t,n){await this.initPromise;let r=++this.searchRequestCounter,o=`search-${JSON.stringify(t)}`,s,i,c=!1,l=n?.fresh!==!0&&this.cache?.has(o),d=async()=>{try{let p=Date.now();s=await this.fetch("search","POST",{q:t},this.abortController);let b=Date.now();s.elapsed=await U(BigInt(b*1e6-p*1e6)),i=b-p,this.cache?.set(o,s)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&this.collector.add({rawSearchString:t.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:t,cached:c,searchedAt:new Date}),s};if(l&&this.cache)i=0,s=this.cache.get(o),c=!0,this.collector&&this.collector.add({rawSearchString:t.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:t,cached:c,searchedAt:new Date});else return n?.debounce?new Promise((p,b)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await d(),p(s)}catch(_){_.name!=="AbortError"&&(console.error("Search request failed",_),b(_))}},n?.debounce||300)}):d();return r===this.searchRequestCounter?s:null}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 d=Date.now();s.elapsed=await U(BigInt(d*1e6-l*1e6)),o=d-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:s.hits?.length??0,roundTripTime:o,query:t,cached:i,searchedAt:new Date}),s}startHeartBeat(t){this.heartbeat?.stop(),this.heartbeat=new j({...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=Dt,c.id=this.id,s.body=Object.entries(c).map(([l,d])=>`${l}=${encodeURIComponent(JSON.stringify(d))}`).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 Bt="text-embedding-ada-002",Mt="text-embedding-3-small",jt="text-embedding-3-large",Ut="gte-small",Ht="gte-medium",$t="gte-large",Ft="gpt-4-1106-preview",Vt="gpt-4",Gt="gpt-3.5-turbo",Kt="gpt-3.5-turbo-16k",nn={[`openai/${Bt}`]:`openai/${Bt}`,[`openai/${Mt}`]:`openai/${Mt}`,[`openai/${jt}`]:`openai/${jt}`,[`orama/${$t}`]:`orama/${$t}`,[`orama/${Ht}`]:`orama/${Ht}`,[`orama/${Ut}`]:`orama/${Ut}`},rn={[`openai/${Gt}`]:Gt,[`openai/${Vt}`]:Vt,[`openai/${Kt}`]:Kt,[`openai/${Ft}`]:Ft},W=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=`${B}${Pt}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:t,csrf:this.CSRFToken,model:nn[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}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){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${B}${Rt}?apiKey=${encodeURIComponent(this.api_key)}`,o=t.messages;this.publicKey&&(o=await Promise.all(o.map(async l=>!l.content||typeof l.content!="string"?l:{...l,content:await cn(this.publicKey,l.content)})));let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(o),csrf:this.CSRFToken,model:rn[t.model]}).toString()});if(!s.ok||s.body==null)throw s.statusText;let i=s.body.getReader(),c=new TextDecoder;for(;;){let{value:l,done:d}=await i.read();if(d)break;yield c.decode(l,{stream:!0})}}async init(){let t=`${B}${kt}?apiKey=${encodeURIComponent(this.api_key)}`,r=await(await fetch(t,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await on(an(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 on(e){return await crypto.subtle.importKey("spki",e,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function sn(e,t){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},e,t);return new Uint8Array(n)}function an(e){return Uint8Array.from(e)}var qt=50;async function cn(e,t){let n=new TextEncoder().encode(t),r=[];for(let o=0;o<n.length;o+=qt){let s=n.subarray(o,o+qt),i=await sn(e,s);r.push(Array.from(i))}return r}return ee(un);})(); | ||
/*! Bundled license information: | ||
@@ -3,0 +3,0 @@ |
@@ -1,2 +0,2 @@ | ||
import{formatElapsedTime as T}from"@orama/orama/components";import{createId as H}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 m="https://secure-proxy.orama.run",C="/init",E="/chat",S="/query";var A="1.0.10";var b={name:"@oramacloud/client",version:A,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:"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.1","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21","lodash.debounce":"^4.0.8","lodash.throttle":"^4.1.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/lodash.debounce":"^4.0.9","@types/lodash.throttle":"^4.1.9","@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(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 y=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};p(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(a=>console.log(a))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var f=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 R=class{id=H();api_key;endpoint;collector;cache;abortController;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=y.create(t)}if(e.cache!==!1){let t={};this.cache=new u(t)}this.init()}async search(e,t){await this.initPromise;let a=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,r,o,c=!1,s=t?.fresh!==!0&&this.cache?.has(i),l=async()=>{try{let d=Date.now();r=await this.fetch("search","POST",{q:e},this.abortController);let h=Date.now();r.elapsed=await T(BigInt(h*1e6-d*1e6)),o=h-d,this.cache?.set(i,r)}catch(d){if(d.name!=="AbortError")throw console.error("Search request failed",d),d}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:c,searchedAt:new Date}),r};if(s&&this.cache)o=0,r=this.cache.get(i),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:c,searchedAt:new Date});else return t?.debounce?new Promise((d,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),d(r)}catch(g){g.name!=="AbortError"&&(console.error("Search request failed",g),h(g))}},t?.debounce||300)}):l();return a===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let a=`vectorSearch-${JSON.stringify(e)}`,i,r,o=!1;if((t?.fresh!==!0&&this.cache?.has(a))===!0&&this.cache!=null)i=0,r=this.cache.get(a),o=!0;else{let s=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await T(BigInt(l*1e6-s*1e6)),i=l-s,this.cache?.set(a,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits?.length??0,roundTripTime:i,query:e,cached:o,searchedAt:new Date}),r}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new f({...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,a,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"&&a!==void 0){let c=a;c.version=A,c.id=this.id,r.body=Object.entries(c).map(([s,l])=>`${s}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!o.ok){let c=new Error;throw c.httpResponse=o,c}return await o.json()}};var v="text-embedding-ada-002",D="text-embedding-3-small",P="text-embedding-3-large",I="gte-small",w="gte-medium",x="gte-large",N="gpt-4-1106-preview",M="gpt-4",k="gpt-3.5-turbo",L="gpt-3.5-turbo-16k",U={[`openai/${v}`]:`openai/${v}`,[`openai/${D}`]:`openai/${D}`,[`openai/${P}`]:`openai/${P}`,[`orama/${x}`]:`orama/${x}`,[`orama/${w}`]:`orama/${w}`,[`orama/${I}`]:`orama/${I}`},G={[`openai/${k}`]:k,[`openai/${M}`]:M,[`openai/${L}`]:L,[`openai/${N}`]:N},B=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=`${m}${S}?apiKey=${this.api_key}`,o=await(await fetch(i,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:U[t]}).toString()})).json();return o.length===1&&(o=o[0]),o}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let a="";for await(let i of this.chatStream(e))a+=i;return a}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let a=`${m}${E}?apiKey=${this.api_key}`,i=e.messages;this.publicKey&&(i=await Promise.all(i.map(async s=>!s.content||typeof s.content!="string"?s:{...s,content:await q(this.publicKey,s.content)})));let r=await fetch(a,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(i),csrf:this.CSRFToken,model:G[e.model]}).toString()});if(!r.ok||r.body==null)throw r.statusText;let o=r.body.getReader(),c=new TextDecoder;for(;;){let{value:s,done:l}=await o.read();if(l)break;yield c.decode(s,{stream:!0})}}async init(){let e=`${m}${C}?apiKey=${this.api_key}`,a=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=a.csrfToken,a.encryption?.enabled===!0&&(this.publicKey=await K(Y(a.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 K(n){return await crypto.subtle.importKey("spki",n,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function F(n,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},n,e);return new Uint8Array(t)}function Y(n){return Uint8Array.from(n)}var $=50;async function q(n,e){let t=new TextEncoder().encode(e),a=[];for(let i=0;i<t.length;i+=$){let r=t.subarray(i,i+$),o=await F(n,r);a.push(Array.from(o))}return a}export{R as OramaClient,B as OramaProxy}; | ||
import{formatElapsedTime as T}from"@orama/orama/components";import{createId as U}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 m="https://secure-proxy.orama.run",_="/init",E="/chat",S="/query";var A="1.0.10";var b={name:"@oramacloud/client",version:A,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:"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.1","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21","lodash.debounce":"^4.0.8","lodash.throttle":"^4.1.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/lodash.debounce":"^4.0.9","@types/lodash.throttle":"^4.1.9","@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(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 y=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};p(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(a=>console.log(a))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var f=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 R=class{id=U();api_key;endpoint;collector;cache;abortController;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=y.create(t)}if(e.cache!==!1){let t={};this.cache=new u(t)}this.init()}async search(e,t){await this.initPromise;let a=++this.searchRequestCounter,o=`search-${JSON.stringify(e)}`,r,i,c=!1,s=t?.fresh!==!0&&this.cache?.has(o),l=async()=>{try{let d=Date.now();r=await this.fetch("search","POST",{q:e},this.abortController);let h=Date.now();r.elapsed=await T(BigInt(h*1e6-d*1e6)),i=h-d,this.cache?.set(o,r)}catch(d){if(d.name!=="AbortError")throw console.error("Search request failed",d),d}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date}),r};if(s&&this.cache)i=0,r=this.cache.get(o),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date});else return t?.debounce?new Promise((d,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),d(r)}catch(g){g.name!=="AbortError"&&(console.error("Search request failed",g),h(g))}},t?.debounce||300)}):l();return a===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let a=`vectorSearch-${JSON.stringify(e)}`,o,r,i=!1;if((t?.fresh!==!0&&this.cache?.has(a))===!0&&this.cache!=null)o=0,r=this.cache.get(a),i=!0;else{let s=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await T(BigInt(l*1e6-s*1e6)),o=l-s,this.cache?.set(a,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits?.length??0,roundTripTime:o,query:e,cached:i,searchedAt:new Date}),r}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new f({...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,a,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"&&a!==void 0){let c=a;c.version=A,c.id=this.id,r.body=Object.entries(c).map(([s,l])=>`${s}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let i=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!i.ok){let c=new Error;throw c.httpResponse=i,c}return await i.json()}};var v="text-embedding-ada-002",D="text-embedding-3-small",P="text-embedding-3-large",I="gte-small",w="gte-medium",x="gte-large",N="gpt-4-1106-preview",M="gpt-4",k="gpt-3.5-turbo",L="gpt-3.5-turbo-16k",H={[`openai/${v}`]:`openai/${v}`,[`openai/${D}`]:`openai/${D}`,[`openai/${P}`]:`openai/${P}`,[`orama/${x}`]:`orama/${x}`,[`orama/${w}`]:`orama/${w}`,[`orama/${I}`]:`orama/${I}`},G={[`openai/${k}`]:k,[`openai/${M}`]:M,[`openai/${L}`]:L,[`openai/${N}`]:N},B=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 o=`${m}${S}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:H[t]}).toString()})).json();return i.length===1&&(i=i[0]),i}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let a="";for await(let o of this.chatStream(e))a+=o;return a}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let a=`${m}${E}?apiKey=${encodeURIComponent(this.api_key)}`,o=e.messages;this.publicKey&&(o=await Promise.all(o.map(async s=>!s.content||typeof s.content!="string"?s:{...s,content:await q(this.publicKey,s.content)})));let r=await fetch(a,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(o),csrf:this.CSRFToken,model:G[e.model]}).toString()});if(!r.ok||r.body==null)throw r.statusText;let i=r.body.getReader(),c=new TextDecoder;for(;;){let{value:s,done:l}=await i.read();if(l)break;yield c.decode(s,{stream:!0})}}async init(){let e=`${m}${_}?apiKey=${encodeURIComponent(this.api_key)}`,a=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=a.csrfToken,a.encryption?.enabled===!0&&(this.publicKey=await K(Y(a.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 K(n){return await crypto.subtle.importKey("spki",n,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function F(n,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},n,e);return new Uint8Array(t)}function Y(n){return Uint8Array.from(n)}var $=50;async function q(n,e){let t=new TextEncoder().encode(e),a=[];for(let o=0;o<t.length;o+=$){let r=t.subarray(o,o+$),i=await F(n,r);a.push(Array.from(i))}return a}export{R as OramaClient,B as OramaProxy}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@oramacloud/client", | ||
"version": "1.0.10", | ||
"version": "1.0.11", | ||
"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
276201