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