Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@oramacloud/client

Package Overview
Dependencies
Maintainers
0
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@oramacloud/client - npm Package Compare versions

Comparing version 1.3.3 to 1.3.4

17

dist/index.d.ts

@@ -1,2 +0,2 @@

import { SearchParams, AnyOrama, AnyDocument, Results, Nullable } from '@orama/orama';
import { AnyDocument, Results, SearchParams, AnyOrama, Nullable } from '@orama/orama';
import { OpenAI } from 'openai';

@@ -29,6 +29,7 @@

type InferenceType = 'documentation';
type AnswerParams$1 = {
type AnswerParams$1<UserContext = unknown> = {
initialMessages: Message[];
inferenceType: InferenceType;
oramaClient: OramaClient;
userContext?: UserContext;
events?: {

@@ -39,5 +40,8 @@ onMessageChange?: (messages: Message[]) => void;

onSourceChange?: <T = AnyDocument>(sources: Results<T>) => void;
onQueryTranslated?: (query: string) => void;
onQueryTranslated?: (query: SearchParams<AnyOrama>) => void;
};
};
type AskParams = SearchParams<AnyOrama> & {
userData?: unknown;
};
declare class AnswerSession {

@@ -50,7 +54,8 @@ private messages;

private events;
private userContext?;
private conversationID;
private userID;
constructor(params: AnswerParams$1);
askStream(params: SearchParams<AnyOrama>): Promise<AsyncGenerator<string>>;
ask(params: SearchParams<AnyOrama>): Promise<string>;
askStream(params: AskParams): Promise<AsyncGenerator<string>>;
ask(params: AskParams): Promise<string>;
getMessages(): Message[];

@@ -86,2 +91,3 @@ clearSession(): void;

initialMessages?: Message[];
userContext?: unknown;
events?: {

@@ -92,2 +98,3 @@ onMessageChange?: (messages: Message[]) => void;

onSourceChange?: <T = AnyDocument>(sources: Results<T>) => void;
onQueryTranslated?: (query: SearchParams<AnyOrama>) => void;
};

@@ -94,0 +101,0 @@ };

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

"use strict";var OramaClient=(()=>{var ft=Object.create;var k=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var wt=(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})},se=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mt(e))!bt.call(t,o)&&o!==n&&k(t,o,{get:()=>e[o],enumerable:!(r=yt(e,o))||r.enumerable});return t};var V=(t,e,n)=>(n=t!=null?ft(gt(t)):{},se(e||!t||!t.__esModule?k(n,"default",{value:t,enumerable:!0}):n,t)),xt=t=>se(k({},"__esModule",{value:!0}),t);var fe=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 Y(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=Y;function ue(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=ue;function de(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=de;function he(t,e){Y(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}h.output=he;var Et={number:M,bool:pe,bytes:Y,hash:ue,exists:de,output:he};h.default=Et});var ge=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),K=BigInt(32);function q(t,e=!1){return e?{h:Number(t&R),l:Number(t>>K&R)}:{h:Number(t>>K&R)|0,l:Number(t&R)|0}}f.fromBig=q;function ye(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}=q(t[o],e);[n[o],r[o]]=[i,s]}return[n,r]}f.split=ye;var Ot=(t,e)=>BigInt(t>>>0)<<K|BigInt(e>>>0);f.toBig=Ot;var _t=(t,e,n)=>t>>>n,It=(t,e,n)=>t<<32-n|e>>>n,Tt=(t,e,n)=>t>>>n|e<<32-n,At=(t,e,n)=>t<<32-n|e>>>n,Ct=(t,e,n)=>t<<64-n|e>>>n-32,Pt=(t,e,n)=>t>>>n-32|e<<64-n,vt=(t,e)=>e,Nt=(t,e)=>t,Dt=(t,e,n)=>t<<n|e>>>32-n,kt=(t,e,n)=>e<<n|t>>>32-n,Mt=(t,e,n)=>e<<n-32|t>>>64-n,Rt=(t,e,n)=>t<<n-32|e>>>64-n;function me(t,e,n,r){let o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}f.add=me;var Lt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Bt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Ut=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),jt=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,$t=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Ht=(t,e,n,r,o,i)=>e+n+r+o+i+(t/2**32|0)|0,Ft={fromBig:q,split:ye,toBig:f.toBig,shrSH:_t,shrSL:It,rotrSH:Tt,rotrSL:At,rotrBH:Ct,rotrBL:Pt,rotr32H:vt,rotr32L:Nt,rotlSH:Dt,rotlSL:kt,rotlBH:Mt,rotlBL:Rt,add:me,add3L:Lt,add3H:Bt,add4L:Ut,add4H:jt,add5H:Ht,add5L:$t};f.default=Ft});var be=S(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.crypto=void 0;var L=wt("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=be(),J=t=>t instanceof Uint8Array,Gt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Gt;var Vt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Vt;var Wt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Wt;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 qt(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=qt;function Xt(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=Xt;var zt=async()=>{};c.nextTick=zt;async function Jt(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=Jt;function we(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}c.utf8ToBytes=we;function U(t){if(typeof t=="string"&&(t=we(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 Qt=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function en(t,e){if(e!==void 0&&(typeof e!="object"||!Qt(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}c.checkOpts=en;function tn(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=tn;function nn(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=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.wrapXOFConstructorWithOpts=rn;function on(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=on});var Ce=S(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.shake256=p.shake128=p.keccak_512=p.keccak_384=p.keccak_256=p.keccak_224=p.sha3_512=p.sha3_384=p.sha3_256=p.sha3_224=p.Keccak=p.keccakP=void 0;var E=fe(),T=ge(),I=Se(),[Oe,_e,Ie]=[[],[],[]],sn=BigInt(0),_=BigInt(1),an=BigInt(2),cn=BigInt(7),ln=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],Oe.push(2*(5*r+n)),_e.push((t+1)*(t+2)/2%64);let o=sn;for(let i=0;i<7;i++)e=(e<<_^(e>>cn)*pn)%ln,e&an&&(o^=_<<(_<<BigInt(i))-_);Ie.push(o)}var[un,dn]=T.default.split(Ie,!0),xe=(t,e,n)=>n>32?T.default.rotlBH(t,e,n):T.default.rotlSH(t,e,n),Ee=(t,e,n)=>n>32?T.default.rotlBL(t,e,n):T.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,u=n[l],d=n[l+1],y=xe(u,d,1)^n[a],m=Ee(u,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=_e[s],l=xe(o,i,a),u=Ee(o,i,a),d=Oe[s];o=t[d],i=t[d+1],t[d]=l,t[d+1]=u}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]^=un[r],t[1]^=dn[r]}n.fill(0)}p.keccakP=Te;var A=class t extends I.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,I.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,I.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}};p.Keccak=A;var b=(t,e,n)=>(0,I.wrapConstructor)(()=>new A(e,t,n));p.sha3_224=b(6,144,224/8);p.sha3_256=b(6,136,256/8);p.sha3_384=b(6,104,384/8);p.sha3_512=b(6,72,512/8);p.keccak_224=b(1,144,224/8);p.keccak_256=b(1,136,256/8);p.keccak_384=b(1,104,384/8);p.keccak_512=b(1,72,512/8);var Ae=(t,e,n)=>(0,I.wrapXOFConstructorWithOpts)((r={})=>new A(e,t,r.dkLen===void 0?n:r.dkLen,!0));p.shake128=Ae(31,168,128/8);p.shake256=Ae(31,136,256/8)});var Le=S((Fn,w)=>{"use strict";var{sha3_512:hn}=Ce(),ve=24,C=32,Z=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Ne(t){let e=8n,n=0n;for(let r of t.values()){let o=BigInt(r);n=(n<<e)+o}return n}var De=(t="")=>Ne(hn(t)).toString(36).slice(1),Pe=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),fn=t=>Pe[Math.floor(t()*Pe.length)],ke=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+Z(C,e):Z(C,e);return De(r).substring(0,C)},Me=t=>()=>t++,yn=476782367,Re=({random:t=Math.random,counter:e=Me(Math.floor(t()*yn)),length:n=ve,fingerprint:r=ke({random:t})}={})=>function(){let i=fn(t),s=Date.now().toString(36),a=e().toString(36),l=Z(n,t),u=`${s+l+a+r}`;return`${i+De(u).substring(1,n)}`},mn=Re(),gn=(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};w.exports.getConstants=()=>({defaultLength:ve,bigLength:C});w.exports.init=Re;w.exports.createId=mn;w.exports.bufToBigInt=Ne;w.exports.createCounter=Me;w.exports.createFingerprint=ke;w.exports.isCuid=gn});var j=S((Gn,P)=>{"use strict";var{createId:bn,init:wn,getConstants:Sn,isCuid:xn}=Le();P.exports.createId=bn;P.exports.init=wn;P.exports.getConstants=Sn;P.exports.isCuid=xn});var vn={};St(vn,{AnswerSession:()=>D,CloudManager:()=>oe,OramaClient:()=>te,OramaProxy:()=>ne});var Dn=Date.now().toString().slice(5);var ie=BigInt(1e3),ae=BigInt(1e6),ce=BigInt(1e9);async function le(t){return typeof t=="number"&&(t=BigInt(t)),t<ie?`${t}ns`:t<ae?`${t/ie}\u03BCs`:t<ce?`${t/ae}ms`:`${t/ce}s`}async function W(t){return{raw:Number(t),formatted:await le(t)}}var Xe=V(j(),1);var qe=V(j(),1);var Ye=V(j(),1);var Be="https://answer.api.orama.com",v="https://secure-proxy.orama.run",Ue="/init",je="/chat",$e="/summary",He="/query",Q="orama_user_id",Fe="server-side-session";var Ve="1.3.3";var We={name:"@oramacloud/client",version:Ve,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:We.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 Fe;let e=localStorage.getItem(Q);if(e)return e;let n=(0,Ye.createId)();return localStorage.setItem(Q,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 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 x=(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=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 Y(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=Y;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){Y(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:Y,hash:de,exists:he,output:fe};h.default=Ot});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),K=BigInt(32);function q(t,e=!1){return e?{h:Number(t&R),l:Number(t>>K&R)}:{h:Number(t>>K&R)|0,l:Number(t&R)|0}}f.fromBig=q;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}=q(t[o],e);[n[o],r[o]]=[i,s]}return[n,r]}f.split=me;var _t=(t,e)=>BigInt(t>>>0)<<K|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:q,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=xt("node:crypto");B.crypto=L&&typeof L=="object"&&"webcrypto"in L?L.webcrypto:void 0});var Se=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 Yt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Yt;var Kt=(t,e)=>t<<32-e|t>>>e;c.rotr=Kt;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!c.isLE)throw new Error("Non little-endian hardware is not supported");var qt=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+=qt[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=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 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 b=(t,e,n)=>(0,A.wrapConstructor)(()=>new T(e,t,n));u.sha3_224=b(6,144,224/8);u.sha3_256=b(6,136,256/8);u.sha3_384=b(6,104,384/8);u.sha3_512=b(6,72,512/8);u.keccak_224=b(1,144,224/8);u.keccak_256=b(1,136,256/8);u.keccak_384=b(1,104,384/8);u.keccak_512=b(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,w)=>{"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};w.exports.getConstants=()=>({defaultLength:Ne,bigLength:C});w.exports.init=Le;w.exports.createId=gn;w.exports.bufToBigInt=De;w.exports.createCounter=Re;w.exports.createFingerprint=Me;w.exports.isCuid=bn});var j=x((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 Ke=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.4";var Ye={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:Ye.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,Ke.createId)();return localStorage.setItem(Z,n),n}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function qe(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}var D=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){let n=e.oramaClient.answersApiBaseURL||Be;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,qe.createId)(),this.userID=O.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let o of n)r=o;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let n=new URLSearchParams;n.append("type",this.inferenceType),n.append("messages",JSON.stringify(this.messages)),n.append("query",e.term??""),n.append("conversationId",this.conversationID),n.append("userId",this.userID),n.append("endpoint",this.oramaClient.endpoint),n.append("searchParams",JSON.stringify(e));let r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),signal:this.abortController.signal});if(!r.ok||!r.body)throw new Error(r.statusText);let o=r.body.getReader(),i=new TextDecoder,s=[],a="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let l=this.messages.at(-1);try{for(;;){let{value:u,done:d}=await o.read();if(d)break;a+=i.decode(u,{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=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;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));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),x=JSON.parse(g.data);if(x.type==="sources")this.events?.onSourceChange&&this.events.onSourceChange(x.message);else if(x.type==="query-translated")this.events?.onQueryTranslated&&this.events.onQueryTranslated(x.message);else if(x.type==="text")for(s.push(x.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(u){if(u.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw u}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 te=class{id=(0,Xe.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),u=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 u(),d(i)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),y(m))}},n?.debounce||300)}):u();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 u=Date.now();i.elapsed=await W(BigInt(u*1e6-l*1e6)),o=u-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})}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=Ve,a.id=this.id,i.body=Object.entries(a).map(([l,u])=>`${l}=${encodeURIComponent(JSON.stringify(u))}`).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 ze="text-embedding-ada-002",Je="text-embedding-3-small",Ze="text-embedding-3-large",Qe="gte-small",et="gte-medium",tt="gte-large",nt="gpt-4-0125-preview",rt="gpt-4-1106-preview",ot="gpt-4-turbo-preview ",st="gpt-4",it="gpt-3.5-turbo",at="gpt-3.5-turbo-16k",ct="gpt-3.5-turbo-0125 ",On={[`openai/${ze}`]:`openai/${ze}`,[`openai/${Je}`]:`openai/${Je}`,[`openai/${Ze}`]:`openai/${Ze}`,[`orama/${tt}`]:`orama/${tt}`,[`orama/${et}`]:`orama/${et}`,[`orama/${Qe}`]:`orama/${Qe}`},lt={[`openai/${it}`]:it,[`openai/${st}`]:st,[`openai/${at}`]:at,[`openai/${rt}`]:rt,[`openai/${nt}`]:nt,[`openai/${ot}`]:ot,[`openai/${ct}`]:ct},ne=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}${He}?apiKey=${encodeURIComponent(this.api_key)}`,s=await(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:On[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}${$e}?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:lt[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}${je}?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 An(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:lt[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:u}=await s.read();if(u)break;yield a.decode(l,{stream:!0})}}async init(){let e=`${v}${Ue}?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 _n(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 _n(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 An(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 re="snapshot",F="notify",ut="deploy",dt="has-data";var Cn="https://api.askorama.ai",ht=`${Cn}/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(re,[])).success}async snapshot(e){return(await this.callIndexWebhook(re,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(ut)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(dt)).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 oe=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(`${ht}/webhooks/${this.indexId}/${e}`,r)).json()}};return xt(vn);})();
`))!==-1;){let m=a.slice(0,y);a=a.slice(y+2);try{let g=qe(m),S=JSON.parse(g.data);if(S.type==="sources")this.events?.onSourceChange&&this.events.onSourceChange(S.message);else if(S.type==="query-translated")this.events?.onQueryTranslated&&this.events.onQueryTranslated(S.message);else if(S.type==="text")for(s.push(S.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);})();
/*! Bundled license information:

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

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

var be=Date.now().toString().slice(5);var P=BigInt(1e3),x=BigInt(1e6),w=BigInt(1e9);async function v(o){return typeof o=="number"&&(o=BigInt(o)),o<P?`${o}ns`:o<x?`${o/P}\u03BCs`:o<w?`${o/x}ms`:`${o/w}s`}async function I(o){return{raw:Number(o),formatted:await v(o)}}import{createId as de}from"@paralleldrive/cuid2";import{createId as le}from"@paralleldrive/cuid2";import{createId as pe}from"@paralleldrive/cuid2";var D="https://answer.api.orama.com",f="https://secure-proxy.orama.run",N="/init",R="/chat",M="/summary",k="/query",O="orama_user_id",L="server-side-session";var $="1.3.3";var U={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(o,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(o,e);return}fetch(o,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var m=class o{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new o(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:U.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 L;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 j(o){let[e,...t]=o.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 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 le}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.4";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=le();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}}var g=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){let t=e.oramaClient.answersApiBaseURL||D;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=le(),this.userID=m.getUserID()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),n="";for await(let r of t)n=r;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),n}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let t=new URLSearchParams;t.append("type",this.inferenceType),t.append("messages",JSON.stringify(this.messages)),t.append("query",e.term??""),t.append("conversationId",this.conversationID),t.append("userId",this.userID),t.append("endpoint",this.oramaClient.endpoint),t.append("searchParams",JSON.stringify(e));let n=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!n.ok||!n.body)throw new Error(n.statusText);let r=n.body.getReader(),s=new TextDecoder,a=[],i="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let c=this.messages.at(-1);try{for(;;){let{value:p,done:l}=await r.read();if(l)break;i+=s.decode(p,{stream:!0});let d;for(;(d=i.indexOf(`
`).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;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));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:p,done:l}=await o.read();if(l)break;i+=s.decode(p,{stream:!0});let d;for(;(d=i.indexOf(`
`))!==-1;){let u=i.slice(0,d);i=i.slice(d+2);try{let A=j(u),h=JSON.parse(A.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==="text")for(a.push(h.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:",u)}}}}catch(p){if(p.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw p}finally{r.releaseLock()}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var S=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var b=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){y(this.params.endpoint)?.catch(e=>console.log(e))}};var H=class{id=de();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,r=`search-${JSON.stringify(e)}`,s=null,a,i=!1,c=t?.fresh!==!0&&this.cache?.has(r),p=async()=>{try{let l=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let d=Date.now();s.elapsed=await I(BigInt(d*1e6-l*1e6)),a=d-l,this.cache?.set(r,s)}catch(l){if(l.name!=="AbortError")throw console.error("Search request failed",l),l}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:a,query:e,cached:i,searchedAt:new Date}),s};if(c&&this.cache)a=0,s=this.cache.get(r),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((l,d)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),l(s)}catch(u){u.name!=="AbortError"&&(console.error("Search request failed",u),d(u))}},t?.debounce||300)}):p();return n===this.searchRequestCounter?s:null}async vectorSearch(e,t){await this.initPromise;let n=`vectorSearch-${JSON.stringify(e)}`,r,s,a=!1;if((t?.fresh!==!0&&this.cache?.has(n))===!0&&this.cache!=null)r=0,s=this.cache.get(n),a=!0;else{let c=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let p=Date.now();s.elapsed=await I(BigInt(p*1e6-c*1e6)),r=p-c,this.cache?.set(n,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits?.length??0,roundTripTime:r,query:e,cached:a,searchedAt:new Date}),s}createAnswerSession(e){return new g({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new b({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,n,r){if(r?.signal.aborted===!0)throw new Error("Request aborted");let s={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:r?.signal};if(t==="POST"&&n!==void 0){let i=n;i.version=$,i.id=this.id,s.body=Object.entries(i).map(([c,p])=>`${c}=${encodeURIComponent(JSON.stringify(p))}`).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 G="text-embedding-ada-002",Y="text-embedding-3-small",K="text-embedding-3-large",F="gte-small",V="gte-medium",W="gte-large",q="gpt-4-0125-preview",z="gpt-4-1106-preview",X="gpt-4-turbo-preview ",J="gpt-4",Z="gpt-3.5-turbo",Q="gpt-3.5-turbo-16k",ee="gpt-3.5-turbo-0125 ",ue={[`openai/${G}`]:`openai/${G}`,[`openai/${Y}`]:`openai/${Y}`,[`openai/${K}`]:`openai/${K}`,[`orama/${W}`]:`orama/${W}`,[`orama/${V}`]:`orama/${V}`,[`orama/${F}`]:`orama/${F}`},te={[`openai/${Z}`]:Z,[`openai/${J}`]:J,[`openai/${Q}`]:Q,[`openai/${z}`]:z,[`openai/${q}`]:q,[`openai/${X}`]:X,[`openai/${ee}`]:ee},ne=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(t=>(console.log(t),!1))}async generateEmbeddings(e,t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let r=`${f}${k}?apiKey=${encodeURIComponent(this.api_key)}`,a=await(await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:ue[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}${M}?apiKey=${encodeURIComponent(this.api_key)}`;try{let r=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:te[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!r.ok||r.body==null)throw r.statusText;let s=r.body.getReader(),a=new TextDecoder;for(;;){let{value:i,done:c}=await s.read();if(c)break;yield a.decode(i,{stream:!0})}}catch(r){if(r.name!=="AbortError")throw r}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n="";for await(let r of this.summaryStream(e))n+=r;return n}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n="";for await(let r of this.chatStream(e))n+=r;return n}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n=`${f}${R}?apiKey=${encodeURIComponent(this.api_key)}`,r=e.messages;this.publicKey&&(r=await Promise.all(r.map(async c=>!c.content||typeof c.content!="string"?c:{...c,content:await ye(this.publicKey,c.content)})));let s=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:te[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:p}=await a.read();if(p)break;yield i.decode(c,{stream:!0})}}async init(){let e=`${f}${N}?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 he(fe(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 he(o){return await crypto.subtle.importKey("spki",o,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function me(o,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},o,e);return new Uint8Array(t)}function fe(o){return Uint8Array.from(o)}var re=50;async function ye(o,e){let t=new TextEncoder().encode(e),n=[];for(let r=0;r<t.length;r+=re){let s=t.subarray(r,r+re),a=await me(o,s);n.push(Array.from(a))}return n}var C="snapshot",E="notify",oe="deploy",se="has-data";var ge="https://api.askorama.ai",ae=`${ge}/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(C,[])).success}async snapshot(e){return(await this.callIndexWebhook(C,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(oe)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(se)).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 ie=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(`${ae}/webhooks/${this.indexId}/${e}`,n)).json()}};export{g as AnswerSession,ie as CloudManager,H as OramaClient,ne as OramaProxy};
`))!==-1;){let u=i.slice(0,d);i=i.slice(d+2);try{let A=H(u),h=JSON.parse(A.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==="text")for(a.push(h.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:",u)}}}}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 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),p=async()=>{try{let l=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let d=Date.now();s.elapsed=await C(BigInt(d*1e6-l*1e6)),a=d-l,this.cache?.set(o,s)}catch(l){if(l.name!=="AbortError")throw console.error("Search request failed",l),l}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:a,query:e,cached: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((l,d)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),l(s)}catch(u){u.name!=="AbortError"&&(console.error("Search request failed",u),d(u))}},t?.debounce||300)}):p();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 p=Date.now();s.elapsed=await C(BigInt(p*1e6-c*1e6)),o=p-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,p])=>`${c}=${encodeURIComponent(JSON.stringify(p))}`).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:p}=await a.read();if(p)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

@@ -1,2 +0,2 @@

import { SearchParams, AnyOrama, AnyDocument, Results, Nullable } from '@orama/orama';
import { AnyDocument, Results, SearchParams, AnyOrama, Nullable } from '@orama/orama';
import React from 'react';

@@ -26,6 +26,7 @@

type InferenceType = 'documentation';
type AnswerParams = {
type AnswerParams<UserContext = unknown> = {
initialMessages: Message[];
inferenceType: InferenceType;
oramaClient: OramaClient;
userContext?: UserContext;
events?: {

@@ -36,5 +37,8 @@ onMessageChange?: (messages: Message[]) => void;

onSourceChange?: <T = AnyDocument>(sources: Results<T>) => void;
onQueryTranslated?: (query: string) => void;
onQueryTranslated?: (query: SearchParams<AnyOrama>) => void;
};
};
type AskParams = SearchParams<AnyOrama> & {
userData?: unknown;
};
declare class AnswerSession {

@@ -47,7 +51,8 @@ private messages;

private events;
private userContext?;
private conversationID;
private userID;
constructor(params: AnswerParams);
askStream(params: SearchParams<AnyOrama>): Promise<AsyncGenerator<string>>;
ask(params: SearchParams<AnyOrama>): Promise<string>;
askStream(params: AskParams): Promise<AsyncGenerator<string>>;
ask(params: AskParams): Promise<string>;
getMessages(): Message[];

@@ -74,2 +79,3 @@ clearSession(): void;

initialMessages?: Message[];
userContext?: unknown;
events?: {

@@ -80,2 +86,3 @@ onMessageChange?: (messages: Message[]) => void;

onSourceChange?: <T = AnyDocument>(sources: Results<T>) => void;
onQueryTranslated?: (query: SearchParams<AnyOrama>) => void;
};

@@ -82,0 +89,0 @@ };

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

var X=Date.now().toString().slice(5);var R=BigInt(1e3),P=BigInt(1e6),D=BigInt(1e9);async function _(n){return typeof n=="number"&&(n=BigInt(n)),n<R?`${n}ns`:n<P?`${n/R}\u03BCs`:n<D?`${n/P}ms`:`${n/D}s`}async function T(n){return{raw:Number(n),formatted:await _(n)}}import{createId as F}from"@paralleldrive/cuid2";import{createId as H}from"@paralleldrive/cuid2";import{createId as V}from"@paralleldrive/cuid2";var M="https://answer.api.orama.com";var E="orama_user_id",N="server-side-session";var B="1.3.3";var L={name:"@oramacloud/client",version:B,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:L.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};b(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(s=>console.log(s))}static getUserID(){if(typeof localStorage>"u")return N;let e=localStorage.getItem(E);if(e)return e;let t=V();return localStorage.setItem(E,t),t}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};function j(n){let[e,...t]=n.split(`
var W=Date.now().toString().slice(5);var R=BigInt(1e3),D=BigInt(1e6),_=BigInt(1e9);async function M(n){return typeof n=="number"&&(n=BigInt(n)),n<R?`${n}ns`:n<D?`${n/R}\u03BCs`:n<_?`${n/D}ms`:`${n/_}s`}async function T(n){return{raw:Number(n),formatted:await M(n)}}import{createId as F}from"@paralleldrive/cuid2";import{createId as q}from"@paralleldrive/cuid2";import{createId as H}from"@paralleldrive/cuid2";var N="https://answer.api.orama.com";var E="orama_user_id",k="server-side-session";var L="1.3.4";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=H();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}}var g=class{messages;inferenceType;oramaClient;endpoint;abortController;events;conversationID;userID;constructor(e){let t=e.oramaClient.answersApiBaseURL||M;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()}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),s="";for await(let i of t)s=i;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),s}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}async*fetchAnswer(e){this.abortController=new AbortController;let t=new URLSearchParams;t.append("type",this.inferenceType),t.append("messages",JSON.stringify(this.messages)),t.append("query",e.term??""),t.append("conversationId",this.conversationID),t.append("userId",this.userID),t.append("endpoint",this.oramaClient.endpoint),t.append("searchParams",JSON.stringify(e));let s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!s.ok||!s.body)throw new Error(s.statusText);let i=s.body.getReader(),r=new TextDecoder,a=[],o="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let u=this.messages.at(-1);try{for(;;){let{value:c,done:p}=await i.read();if(p)break;o+=r.decode(c,{stream:!0});let l;for(;(l=o.indexOf(`
`).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=q(),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;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));let s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString(),signal:this.abortController.signal});if(!s.ok||!s.body)throw new Error(s.statusText);let i=s.body.getReader(),r=new TextDecoder,a=[],o="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let u=this.messages.at(-1);try{for(;;){let{value:c,done:p}=await i.read();if(p)break;o+=r.decode(c,{stream:!0});let l;for(;(l=o.indexOf(`
`))!==-1;){let h=o.slice(0,l);o=o.slice(l+2);try{let S=j(h),f=JSON.parse(S.data);if(f.type==="sources")this.events?.onSourceChange&&this.events.onSourceChange(f.message);else if(f.type==="query-translated")this.events?.onQueryTranslated&&this.events.onQueryTranslated(f.message);else if(f.type==="text")for(a.push(f.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 C=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var A=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 C(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})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new A({...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=B,o.id=this.id,r.body=Object.entries(o).map(([u,c])=>`${u}=${encodeURIComponent(JSON.stringify(c))}`).join("&")}let a=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!a.ok){let o=new Error;throw o.httpResponse=a,o}return await a.json()}};import G,{useState as w,useEffect as U,createContext as z,useContext as J}from"react";import{useState as v,useRef as Y,useEffect as q,useCallback as O}from"react";function K(n){let[e,t]=v(n.initialMessages||[]),[s,i]=v(!1),[r,a]=v(null),[o,u]=v(!1),[c,p]=v(null),l=Y(null);q(()=>{let x="oramaClient"in n?n.oramaClient:new y({api_key:n.apiKey,endpoint:n.endpoint});return l.current=new g({...n,initialMessages:n.initialMessages||[],inferenceType:n.inferenceType||"documentation",oramaClient:x,events:{onMessageChange:d=>{t(d)},onMessageLoading:d=>{i(d)},onAnswerAborted:d=>{u(d)},onSourceChange:d=>{p(d)}}}),()=>{l.current?.abortAnswer()}},[n]);let h=O(async x=>{if(!l.current)try{u(!1),await l.current.ask(x)}catch(d){a(d)}},[]),S=O(()=>{l?.current?.abortAnswer()},[]),f=O(()=>{l?.current?.clearSession()},[]);return{messages:e,loading:s,aborted:o,abortAnswer:S,error:r,sources:c,ask:h,clearSession:f}}var $=z({endpoint:"",apiKey:""}),ke=({children:n,endpoint:e,apiKey:t})=>G.createElement($.Provider,{value:{endpoint:e,apiKey:t}},n);function Be(n){let{apiKey:e,endpoint:t}=J($),[s,i]=w(!1),[r,a]=w(null),[o,u]=w(null),[c,p]=w(null);return U(()=>{a(new y({api_key:e,endpoint:t})),i(!0)},[]),U(()=>{r!==null&&r.search(n).then(u).catch(p)},[r,n]),{ready:s,results:o,error:c}}export{ke as OramaCloud,K as useAnswerSession,Be as useSearch};
`))!==-1;){let f=o.slice(0,l);o=o.slice(l+2);try{let S=U(f),h=JSON.parse(S.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==="text")for(a.push(h.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:",f)}}}}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 A=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(f){f.name!=="AbortError"&&(console.error("Search request failed",f),l(f))}},t?.debounce||300)}):c();return s===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let s=`vectorSearch-${JSON.stringify(e)}`,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 A({...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 w,useEffect as $,createContext as J,useContext as X}from"react";import{useState as C,useRef as Y,useEffect as K,useCallback as P}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:d=>{t(d)},onMessageLoading:d=>{i(d)},onAnswerAborted:d=>{u(d)},onSourceChange:d=>{p(d)}}}),()=>{l.current?.abortAnswer()}},[n]);let f=P(async x=>{if(!l.current)try{u(!1),await l.current.ask(x)}catch(d){a(d)}},[]),S=P(()=>{l?.current?.abortAnswer()},[]),h=P(()=>{l?.current?.clearSession()},[]);return{messages:e,loading:s,aborted:o,abortAnswer:S,error:r,sources:c,ask:f,clearSession:h}}var V=J({endpoint:"",apiKey:""}),Be=({children:n,endpoint:e,apiKey:t})=>z.createElement(V.Provider,{value:{endpoint:e,apiKey:t}},n);function Le(n){let{apiKey:e,endpoint:t}=X(V),[s,i]=w(!1),[r,a]=w(null),[o,u]=w(null),[c,p]=w(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};
//# sourceMappingURL=index.js.map

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

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

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc