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