@oramacloud/client
Advanced tools
Comparing version 1.3.19 to 1.3.20
@@ -14,7 +14,7 @@ import { AnyDocument, Results, SearchParams, AnyOrama, Nullable } from '@orama/orama'; | ||
} | ||
interface IOramaClientMultiSearch extends Omit<IOramaClient, 'api_key' | 'endpoint'> { | ||
endpoint?: string; | ||
interface IOramaClientMultiSearch<M extends boolean> extends Omit<IOramaClient, 'api_key' | 'endpoint'> { | ||
mergeResults?: M; | ||
indexes: { | ||
api_key: string; | ||
id: string; | ||
endpoint: string; | ||
}[]; | ||
@@ -40,6 +40,6 @@ } | ||
type InferenceType = 'documentation'; | ||
type AnswerParams$1<UserContext = unknown> = { | ||
type AnswerParams$1<M extends boolean, UserContext = unknown> = { | ||
initialMessages: Message[]; | ||
inferenceType: InferenceType; | ||
oramaClient: OramaClient; | ||
oramaClient: OramaClient<M>; | ||
userContext?: UserContext; | ||
@@ -77,3 +77,3 @@ events?: { | ||
}; | ||
declare class AnswerSession { | ||
declare class AnswerSession<M extends boolean> { | ||
private messages; | ||
@@ -90,3 +90,3 @@ private inferenceType; | ||
private systemPrompts?; | ||
constructor(params: AnswerParams$1); | ||
constructor(params: AnswerParams$1<M>); | ||
askStream(params: AskParams): Promise<AsyncGenerator<string>>; | ||
@@ -141,2 +141,3 @@ ask(params: AskParams): Promise<string>; | ||
}> & AdditionalSearchParams; | ||
type OramaClientSearchResult<M> = M extends true ? Results<DocumentType> : Results<DocumentType>[]; | ||
type AnswerSessionParams = { | ||
@@ -159,3 +160,3 @@ inferenceType?: InferenceType; | ||
declare class OramaClient { | ||
declare class OramaClient<M extends boolean = true> { | ||
private readonly id; | ||
@@ -165,2 +166,3 @@ private readonly api_key; | ||
private readonly multiIndexSearch; | ||
private readonly mergeResults; | ||
private readonly multiIndexIndexes?; | ||
@@ -176,3 +178,3 @@ private readonly answersApiBaseURL; | ||
private initPromise?; | ||
constructor(params: IOramaClient | IOramaClientMultiSearch); | ||
constructor(params: IOramaClient | IOramaClientMultiSearch<M>); | ||
private customerUserToken; | ||
@@ -183,5 +185,6 @@ private searchToken; | ||
setOnAuthTokenExpired(onAuthTokenExpired: (token: string) => void): void; | ||
search(query: ClientSearchParams, config?: SearchConfig): Promise<Nullable<Results<AnyDocument>>>; | ||
private addSearchResultsToCollector; | ||
search(query: ClientSearchParams, config?: SearchConfig): Promise<Nullable<OramaClientSearchResult<M>>>; | ||
vectorSearch(query: ClientSearchParams, config?: SearchConfig): Promise<Pick<Results<AnyDocument>, 'hits' | 'elapsed'>>; | ||
createAnswerSession(params?: AnswerSessionParams): AnswerSession; | ||
createAnswerSession(params?: AnswerSessionParams): AnswerSession<M>; | ||
startHeartBeat(config: HeartBeatConfig): void; | ||
@@ -220,6 +223,20 @@ stopHeartBeat(): void; | ||
declare const embeddingsModels: { | ||
[x: string]: string; | ||
"openai/text-embedding-ada-002": string; | ||
"openai/text-embedding-3-small": string; | ||
"openai/text-embedding-3-large": string; | ||
"orama/gte-large": string; | ||
"orama/gte-medium": string; | ||
"orama/gte-small": string; | ||
}; | ||
declare const chatModels: { | ||
[x: string]: string; | ||
"openai/gpt-3.5-turbo": string; | ||
"openai/gpt-4": string; | ||
"openai/gpt-4-1106-preview": string; | ||
"openai/gpt-4-0125-preview": string; | ||
"openai/gpt-4-turbo-preview": string; | ||
"openai/gpt-3.5-turbo-0125": string; | ||
"openai/gpt-4-turbo-2024-04-09": string; | ||
"openai/gpt-4o": string; | ||
"openai/gpt-4o-mini": string; | ||
"openai/gpt-4-turbo": string; | ||
}; | ||
@@ -298,2 +315,2 @@ declare class OramaProxy { | ||
export { type AnswerParams, AnswerSession, type AnswerSessionParams, type ChatMessage, type ChatModel, type ChatParams, type ClientSearchParams, CloudManager, type EmbeddingModel, type Message, OramaClient, OramaProxy, type SearchConfig, type SearchMode, type SortByClauseUnion, type SummaryParams }; | ||
export { type AnswerParams, AnswerSession, type AnswerSessionParams, type ChatMessage, type ChatModel, type ChatParams, type ClientSearchParams, CloudManager, type EmbeddingModel, type Message, OramaClient, type OramaClientSearchResult, OramaProxy, type SearchConfig, type SearchMode, type SortByClauseUnion, type SummaryParams }; |
@@ -1,6 +0,6 @@ | ||
"use strict";var OramaClient=(()=>{var It=Object.create;var N=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var Et=Object.getPrototypeOf,Ot=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ct=(t,e)=>{for(var n in e)N(t,n,{get:e[n],enumerable:!0})},de=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tt(e))!Ot.call(t,s)&&s!==n&&N(t,s,{get:()=>e[s],enumerable:!(r=At(e,s))||r.enumerable});return t};var V=(t,e,n)=>(n=t!=null?It(Et(t)):{},de(e||!t||!t.__esModule?N(n,"default",{value:t,enumerable:!0}):n,t)),_t=t=>de(N({},"__esModule",{value:!0}),t);var we=w(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.output=f.exists=f.hash=f.bytes=f.bool=f.number=void 0;function D(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}f.number=D;function me(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}f.bool=me;function X(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}`)}f.bytes=X;function ge(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");D(t.outputLen),D(t.blockLen)}f.hash=ge;function be(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")}f.exists=be;function Se(t,e){X(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=Se;var Pt={number:D,bool:me,bytes:X,hash:ge,exists:be,output:Se};f.default=Pt});var Ae=w(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.add=y.toBig=y.split=y.fromBig=void 0;var M=BigInt(2**32-1),z=BigInt(32);function Q(t,e=!1){return e?{h:Number(t&M),l:Number(t>>z&M)}:{h:Number(t>>z&M)|0,l:Number(t&M)|0}}y.fromBig=Q;function xe(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=Q(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}y.split=xe;var vt=(t,e)=>BigInt(t>>>0)<<z|BigInt(e>>>0);y.toBig=vt;var kt=(t,e,n)=>t>>>n,Nt=(t,e,n)=>t<<32-n|e>>>n,Dt=(t,e,n)=>t>>>n|e<<32-n,Mt=(t,e,n)=>t<<32-n|e>>>n,Rt=(t,e,n)=>t<<64-n|e>>>n-32,Lt=(t,e,n)=>t>>>n-32|e<<64-n,Bt=(t,e)=>e,Ut=(t,e)=>t,$t=(t,e,n)=>t<<n|e>>>32-n,jt=(t,e,n)=>e<<n|t>>>32-n,Ht=(t,e,n)=>e<<n-32|t>>>64-n,Gt=(t,e,n)=>t<<n-32|e>>>64-n;function Ie(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}y.add=Ie;var Ft=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),qt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Wt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Kt=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Vt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Yt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Xt={fromBig:Q,split:xe,toBig:y.toBig,shrSH:kt,shrSL:Nt,rotrSH:Dt,rotrSL:Mt,rotrBH:Rt,rotrBL:Lt,rotr32H:Bt,rotr32L:Ut,rotlSH:$t,rotlSL:jt,rotlBH:Ht,rotlBL:Gt,add:Ie,add3L:Ft,add3H:qt,add4L:Wt,add4H:Kt,add5H:Yt,add5L:Vt};y.default=Xt});var Te=w(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.crypto=void 0;R.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Oe=w(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var J=Te(),ee=t=>t instanceof Uint8Array,zt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=zt;var Qt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=Qt;var Jt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=Jt;var Zt=(t,e)=>t<<32-e|t>>>e;a.rotr=Zt;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var en=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function tn(t){if(!ee(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=en[t[n]];return e}a.bytesToHex=tn;function nn(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 s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=nn;var rn=async()=>{};a.nextTick=rn;async function sn(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=sn;function Ee(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=Ee;function L(t){if(typeof t=="string"&&(t=Ee(t)),!ee(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=L;function on(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!ee(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=on;var Z=class{clone(){return this._cloneInto()}};a.Hash=Z;var an=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function cn(t,e){if(e!==void 0&&(typeof e!="object"||!an(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=cn;function ln(t){let e=r=>t().update(L(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=ln;function un(t){let e=(r,s)=>t(s).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=un;function dn(t){let e=(r,s)=>t(s).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=dn;function pn(t=32){if(J.crypto&&typeof J.crypto.getRandomValues=="function")return J.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=pn});var Me=w(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=d.keccakP=void 0;var A=we(),O=Ae(),E=Oe(),[Pe,ve,ke]=[[],[],[]],hn=BigInt(0),T=BigInt(1),fn=BigInt(2),yn=BigInt(7),mn=BigInt(256),gn=BigInt(113);for(let t=0,e=T,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Pe.push(2*(5*r+n)),ve.push((t+1)*(t+2)/2%64);let s=hn;for(let o=0;o<7;o++)e=(e<<T^(e>>yn)*gn)%mn,e&fn&&(s^=T<<(T<<BigInt(o))-T);ke.push(s)}var[bn,Sn]=O.default.split(ke,!0),Ce=(t,e,n)=>n>32?O.default.rotlBH(t,e,n):O.default.rotlSH(t,e,n),_e=(t,e,n)=>n>32?O.default.rotlBL(t,e,n):O.default.rotlSL(t,e,n);function Ne(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,u=(i+2)%10,p=n[u],l=n[u+1],h=Ce(p,l,1)^n[c],m=_e(p,l,1)^n[c+1];for(let I=0;I<50;I+=10)t[i+I]^=h,t[i+I+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=ve[i],u=Ce(s,o,c),p=_e(s,o,c),l=Pe[i];s=t[l],o=t[l+1],t[l]=u,t[l+1]=p}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=bn[r],t[1]^=Sn[r]}n.fill(0)}d.keccakP=Ne;var C=class t extends E.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,A.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,E.u32)(this.state)}keccak(){Ne(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){A.default.exists(this);let{blockLen:n,state:r}=this;e=(0,E.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){A.default.exists(this,!1),A.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return A.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(A.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=C;var b=(t,e,n)=>(0,E.wrapConstructor)(()=>new C(e,t,n));d.sha3_224=b(6,144,224/8);d.sha3_256=b(6,136,256/8);d.sha3_384=b(6,104,384/8);d.sha3_512=b(6,72,512/8);d.keccak_224=b(1,144,224/8);d.keccak_256=b(1,136,256/8);d.keccak_384=b(1,104,384/8);d.keccak_512=b(1,72,512/8);var De=(t,e,n)=>(0,E.wrapXOFConstructorWithOpts)((r={})=>new C(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=De(31,168,128/8);d.shake256=De(31,136,256/8)});var Ge=w((zn,S)=>{"use strict";var{sha3_512:wn}=Me(),Le=24,_=32,te=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Be(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Ue=(t="")=>Be(wn(t)).toString(36).slice(1),Re=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),xn=t=>Re[Math.floor(t()*Re.length)],$e=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+te(_,e):te(_,e);return Ue(r).substring(0,_)},je=t=>()=>t++,In=476782367,He=({random:t=Math.random,counter:e=je(Math.floor(t()*In)),length:n=Le,fingerprint:r=$e({random:t})}={})=>function(){let o=xn(t),i=Date.now().toString(36),c=e().toString(36),u=te(n,t),p=`${i+u+c+r}`;return`${o+Ue(p).substring(1,n)}`},An=He(),Tn=(t,{minLength:e=2,maxLength:n=_}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};S.exports.getConstants=()=>({defaultLength:Le,bigLength:_});S.exports.init=He;S.exports.createId=An;S.exports.bufToBigInt=Be;S.exports.createCounter=je;S.exports.createFingerprint=$e;S.exports.isCuid=Tn});var B=w((Qn,P)=>{"use strict";var{createId:En,init:On,getConstants:Cn,isCuid:_n}=Ge();P.exports.createId=En;P.exports.init=On;P.exports.getConstants=Cn;P.exports.isCuid=_n});var Un={};Ct(Un,{AnswerSession:()=>k,CloudManager:()=>le,OramaClient:()=>ie,OramaProxy:()=>ae});var jn=Date.now().toString().slice(5);var pe=BigInt(1e3),he=BigInt(1e6),fe=BigInt(1e9);async function ye(t){return typeof t=="number"&&(t=BigInt(t)),t<pe?`${t}ns`:t<he?`${t/pe}\u03BCs`:t<fe?`${t/he}ms`:`${t/fe}s`}async function Y(t){return{raw:Number(t),formatted:await ye(t)}}var Ze=V(B(),1);var se=V(B(),1);var Fe="https://answer.api.orama.com",v="https://secure-proxy.orama.run",qe="/init",We="/chat",Ke="/summary",Ve="/query",Ye="https://cloud.orama.run/v1/indexes",ne="orama_user_id";function Xe(t){let[e,...n]=t.split(` | ||
"use strict";var OramaClient=(()=>{var qt=Object.create;var D=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Wt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var T=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Xt=(t,e)=>{for(var n in e)D(t,n,{get:e[n],enumerable:!0})},he=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vt(e))!Yt.call(t,s)&&s!==n&&D(t,s,{get:()=>e[s],enumerable:!(r=Kt(e,s))||r.enumerable});return t};var X=(t,e,n)=>(n=t!=null?qt(Wt(t)):{},he(e||!t||!t.__esModule?D(n,"default",{value:t,enumerable:!0}):n,t)),zt=t=>he(D({},"__esModule",{value:!0}),t);var J=T(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.isBytes=Se;g.number=R;g.bool=be;g.bytes=Q;g.hash=xe;g.exists=Ie;g.output=we;function R(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function be(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Se(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Q(t,...e){if(!Se(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function xe(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");R(t.outputLen),R(t.blockLen)}function Ie(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")}function we(t,e){Q(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Qt={number:R,bool:be,bytes:Q,hash:xe,exists:Ie,output:we};g.default=Qt});var qe=T(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=ee;a.split=Te;a.add=Be;var L=BigInt(2**32-1),Z=BigInt(32);function ee(t,e=!1){return e?{h:Number(t&L),l:Number(t>>Z&L)}:{h:Number(t>>Z&L)|0,l:Number(t&L)|0}}function Te(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=ee(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var Ae=(t,e)=>BigInt(t>>>0)<<Z|BigInt(e>>>0);a.toBig=Ae;var _e=(t,e,n)=>t>>>n;a.shrSH=_e;var Ce=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=Ce;var Oe=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=Oe;var Ee=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Ee;var Pe=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Pe;var ve=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=ve;var ke=(t,e)=>e;a.rotr32H=ke;var Me=(t,e)=>t;a.rotr32L=Me;var Ne=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Ne;var De=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=De;var Re=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=Re;var Le=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Le;function Be(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Ue=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Ue;var He=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=He;var je=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=je;var $e=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=$e;var Fe=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=Fe;var Ge=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=Ge;var Jt={fromBig:ee,split:Te,toBig:Ae,shrSH:_e,shrSL:Ce,rotrSH:Oe,rotrSL:Ee,rotrBH:Pe,rotrBL:ve,rotr32H:ke,rotr32L:Me,rotlSH:Ne,rotlSL:De,rotlBH:Re,rotlBL:Le,add:Be,add3L:Ue,add3H:He,add4L:je,add4H:$e,add5H:Ge,add5L:Fe};a.default=Jt});var Ke=T(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.crypto=void 0;B.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Ye=T(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.Hash=l.nextTick=l.byteSwapIfBE=l.byteSwap=l.isLE=l.rotl=l.rotr=l.createView=l.u32=l.u8=void 0;l.isBytes=Zt;l.byteSwap32=an;l.bytesToHex=ln;l.hexToBytes=dn;l.asyncLoop=pn;l.utf8ToBytes=We;l.toBytes=U;l.concatBytes=hn;l.checkOpts=mn;l.wrapConstructor=yn;l.wrapConstructorWithOpts=gn;l.wrapXOFConstructorWithOpts=bn;l.randomBytes=Sn;var _=Ke(),ne=J();function Zt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var en=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);l.u8=en;var tn=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));l.u32=tn;var nn=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);l.createView=nn;var rn=(t,e)=>t<<32-e|t>>>e;l.rotr=rn;var sn=(t,e)=>t<<e|t>>>32-e>>>0;l.rotl=sn;l.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var on=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;l.byteSwap=on;l.byteSwapIfBE=l.isLE?t=>t:t=>(0,l.byteSwap)(t);function an(t){for(let e=0;e<t.length;e++)t[e]=(0,l.byteSwap)(t[e])}var cn=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ln(t){(0,ne.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=cn[t[n]];return e}var b={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Ve(t){if(t>=b._0&&t<=b._9)return t-b._0;if(t>=b._A&&t<=b._F)return t-(b._A-10);if(t>=b._a&&t<=b._f)return t-(b._a-10)}function dn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=Ve(t.charCodeAt(o)),c=Ve(t.charCodeAt(o+1));if(i===void 0||c===void 0){let u=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+u+'" at index '+o)}r[s]=i*16+c}return r}var un=async()=>{};l.nextTick=un;async function pn(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,l.nextTick)(),r+=o)}}function We(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function U(t){return typeof t=="string"&&(t=We(t)),(0,ne.bytes)(t),t}function hn(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,ne.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var te=class{clone(){return this._cloneInto()}};l.Hash=te;var fn={}.toString;function mn(t,e){if(e!==void 0&&fn.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function yn(t){let e=r=>t().update(U(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function gn(t){let e=(r,s)=>t(s).update(U(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function bn(t){let e=(r,s)=>t(s).update(U(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Sn(t=32){if(_.crypto&&typeof _.crypto.getRandomValues=="function")return _.crypto.getRandomValues(new Uint8Array(t));if(_.crypto&&typeof _.crypto.randomBytes=="function")return _.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var nt=T(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=void 0;p.keccakP=et;var C=J(),E=qe(),S=Ye(),Qe=[],Je=[],Ze=[],xn=BigInt(0),O=BigInt(1),In=BigInt(2),wn=BigInt(7),Tn=BigInt(256),An=BigInt(113);for(let t=0,e=O,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Qe.push(2*(5*r+n)),Je.push((t+1)*(t+2)/2%64);let s=xn;for(let o=0;o<7;o++)e=(e<<O^(e>>wn)*An)%Tn,e&In&&(s^=O<<(O<<BigInt(o))-O);Ze.push(s)}var[_n,Cn]=(0,E.split)(Ze,!0),Xe=(t,e,n)=>n>32?(0,E.rotlBH)(t,e,n):(0,E.rotlSH)(t,e,n),ze=(t,e,n)=>n>32?(0,E.rotlBL)(t,e,n):(0,E.rotlSL)(t,e,n);function et(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,u=(i+2)%10,h=n[u],d=n[u+1],f=Xe(h,d,1)^n[c],m=ze(h,d,1)^n[c+1];for(let x=0;x<50;x+=10)t[i+x]^=f,t[i+x+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Je[i],u=Xe(s,o,c),h=ze(s,o,c),d=Qe[i];s=t[d],o=t[d+1],t[d]=u,t[d+1]=h}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=_n[r],t[1]^=Cn[r]}n.fill(0)}var P=class t extends S.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,C.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,S.u32)(this.state)}keccak(){S.isLE||(0,S.byteSwap32)(this.state32),et(this.state32,this.rounds),S.isLE||(0,S.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,C.exists)(this);let{blockLen:n,state:r}=this;e=(0,S.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,C.exists)(this,!1),(0,C.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,C.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,C.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:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};p.Keccak=P;var I=(t,e,n)=>(0,S.wrapConstructor)(()=>new P(e,t,n));p.sha3_224=I(6,144,224/8);p.sha3_256=I(6,136,256/8);p.sha3_384=I(6,104,384/8);p.sha3_512=I(6,72,512/8);p.keccak_224=I(1,144,224/8);p.keccak_256=I(1,136,256/8);p.keccak_384=I(1,104,384/8);p.keccak_512=I(1,72,512/8);var tt=(t,e,n)=>(0,S.wrapXOFConstructorWithOpts)((r={})=>new P(e,t,r.dkLen===void 0?n:r.dkLen,!0));p.shake128=tt(31,168,128/8);p.shake256=tt(31,136,256/8)});var dt=T((rr,w)=>{"use strict";var{sha3_512:On}=nt(),st=24,v=32,re=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function ot(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var it=(t="")=>ot(On(t)).toString(36).slice(1),rt=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),En=t=>rt[Math.floor(t()*rt.length)],at=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+re(v,e):re(v,e);return it(r).substring(0,v)},ct=t=>()=>t++,Pn=476782367,lt=({random:t=Math.random,counter:e=ct(Math.floor(t()*Pn)),length:n=st,fingerprint:r=at({random:t})}={})=>function(){let o=En(t),i=Date.now().toString(36),c=e().toString(36),u=re(n,t),h=`${i+u+c+r}`;return`${o+it(h).substring(1,n)}`},vn=lt(),kn=(t,{minLength:e=2,maxLength:n=v}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:st,bigLength:v});w.exports.init=lt;w.exports.createId=vn;w.exports.bufToBigInt=ot;w.exports.createCounter=ct;w.exports.createFingerprint=at;w.exports.isCuid=kn});var H=T((sr,k)=>{"use strict";var{createId:Mn,init:Nn,getConstants:Dn,isCuid:Rn}=dt();k.exports.createId=Mn;k.exports.init=Nn;k.exports.getConstants=Dn;k.exports.isCuid=Rn});var Kn={};Xt(Kn,{AnswerSession:()=>N,CloudManager:()=>ue,OramaClient:()=>ce,OramaProxy:()=>le});var Wn=Date.now().toString().slice(5);var fe=BigInt(1e3),me=BigInt(1e6),ye=BigInt(1e9);async function ge(t){return typeof t=="number"&&(t=BigInt(t)),t<fe?`${t}ns`:t<me?`${t/fe}\u03BCs`:t<ye?`${t/me}ms`:`${t/ye}s`}async function z(t){return{raw:Number(t),formatted:await ge(t)}}var It=X(H(),1);var ie=X(H(),1);var ut="https://answer.api.orama.com",M="https://secure-proxy.orama.run",pt="/init",ht="/chat",ft="/summary",mt="/query",yt="/v1/indexes",se="orama_user_id";function gt(t){let[e,...n]=t.split(` | ||
`),r=n.join(` | ||
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function re(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var k=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||Fe;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,se.createId)(),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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,se.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",re(this.userContext)),e.userData&&o.append("userData",re(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let u=new TextDecoder,p=[],l="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let h=this.messages.at(-1);for(;;){let{value:m,done:I}=await r.read();if(I)break;l+=u.decode(m,{stream:!0});let W;for(;(W=l.indexOf(` | ||
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function oe(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var N=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||ut;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,ie.createId)(),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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ie.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",oe(this.userContext)),e.userData&&o.append("userData",oe(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let u=new TextDecoder,h=[],d="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:m,done:x}=await r.read();if(x)break;d+=u.decode(m,{stream:!0});let W;for(;(W=d.indexOf(` | ||
`))!==-1;){let ue=l.slice(0,W);l=l.slice(W+2);try{let K=Xe(ue),g=JSON.parse(K.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(p.push(g.message);p.length>0;)h.content+=p.shift(),this.state[s].response=h.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield h.content}catch(K){console.error("Error parsing SSE event:",K),console.error("Raw message:",ue)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var U=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 Qe="1.3.19";var Je={name:"@oramacloud/client",version:Qe,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:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.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/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.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",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function x(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var $=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),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:Je.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};x(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var j=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){x(this.params.endpoint)?.catch(e=>console.log(e))}};var H=V(B(),1);var G=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ne);r?this.userId=r:(this.userId=(0,H.createId)(),localStorage.setItem(ne,this.userId))}else this.userId=(0,H.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await x(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,H.createId)(),this.identity=void 0,this.userAlias=void 0}};function vn(t){return t!==void 0&&t?.signal!==void 0}var ie=class{id=(0,Ze.createId)();api_key;endpoint;multiIndexSearch;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e?(this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes,this.endpoint=e.endpoint||Ye,this.multiIndexSearch=!0):(this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1),this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new G({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=$.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new U(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,u=n?.fresh!==!0&&this.cache?.has(s),p=async()=>{try{let l=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:!0},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let h=Date.now();o.elapsed=await Y(BigInt(h*1e6-l*1e6)),i=h-l,this.cache?.set(s,o)}catch(l){if(l.name!=="AbortError")throw console.error("Search request failed",l),l}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(u&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((l,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),l(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),h(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):p();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let u=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let p=Date.now();o.elapsed=await Y(BigInt(p*1e6-u*1e6)),s=p-u,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new k({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new j({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){let i=vn(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let c={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let l=r;l.version=Qe,l.id=this.id,l.visitorId=this.profile.getUserId(),c.body=Object.entries(l).filter(([h,m])=>!!m).map(([h,m])=>`${h}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let u=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||u.searchParams.append("api-key",this.api_key),o)for(let[l,h]of Object.entries(o))h&&u.searchParams.append(l,h);let p=await fetch(u,c);if(!p.ok){let l=new Error;throw l.httpResponse=p,l}return await p.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var et="text-embedding-ada-002",tt="text-embedding-3-small",nt="text-embedding-3-large",rt="gte-small",st="gte-medium",ot="gte-large",it="gpt-4o",at="gpt-4o-mini",ct="gpt-4-turbo",lt="gpt-4-turbo-2024-04-09",ut="gpt-4-0125-preview",dt="gpt-4-1106-preview",pt="gpt-4-turbo-preview",ht="gpt-4",ft="gpt-3.5-turbo",yt="gpt-3.5-turbo-0125",kn={[`openai/${et}`]:`openai/${et}`,[`openai/${tt}`]:`openai/${tt}`,[`openai/${nt}`]:`openai/${nt}`,[`orama/${ot}`]:`orama/${ot}`,[`orama/${st}`]:`orama/${st}`,[`orama/${rt}`]:`orama/${rt}`},mt={[`openai/${ft}`]:ft,[`openai/${ht}`]:ht,[`openai/${dt}`]:dt,[`openai/${ut}`]:ut,[`openai/${pt}`]:pt,[`openai/${yt}`]:yt,[`openai/${lt}`]:lt,[`openai/${it}`]:it,[`openai/${at}`]:at,[`openai/${ct}`]:ct},ae=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 s=`${v}${Ve}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:kn[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}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}${Ke}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=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:mt[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:u}=await o.read();if(u)break;yield i.decode(c,{stream:!0})}}catch(s){if(s.name!=="AbortError")throw s}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.summaryStream(e))r+=s;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.chatStream(e))r+=s;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${We}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async u=>!u.content||typeof u.content!="string"?u:{...u,content:await Rn(this.publicKey,u.content)})));let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:mt[e.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),c=new TextDecoder;for(;;){let{value:u,done:p}=await i.read();if(p)break;yield c.decode(u,{stream:!0})}}async init(){let e=`${v}${qe}?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 Nn(Mn(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 Nn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function Dn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function Mn(t){return Uint8Array.from(t)}var gt=50;async function Rn(t,e){let n=new TextEncoder().encode(e),r=[];for(let s=0;s<n.length;s+=gt){let o=n.subarray(s,s+gt),i=await Dn(t,o);r.push(Array.from(i))}return r}var ce="snapshot",F="notify",bt="deploy",St="has-data",wt="update-schema";var Ln="https://api.askorama.ai",xt=`${Ln}/api/v1`;var q=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(ce,[])).success}async snapshot(e){return(await this.callIndexWebhook(ce,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 updateSchema(e){try{await this.callIndexWebhook(wt,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(bt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(St)).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 le=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||xt}index(e){return new q({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(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};return _t(Un);})(); | ||
`))!==-1;){let pe=d.slice(0,W);d=d.slice(W+2);try{let Y=gt(pe),y=JSON.parse(Y.data);if(y.type==="sources")this.state[s].sources=y.message,this.events?.onSourceChange&&this.events.onSourceChange(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="query-translated")this.state[s].translatedQuery=y.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="related-queries")this.state[s].relatedQueries=y.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="text")for(h.push(y.message);h.length>0;)f.content+=h.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(Y){console.error("Error parsing SSE event:",Y),console.error("Raw message:",pe)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var j=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 St="1.3.20";var xt={name:"@oramacloud/client",version:St,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 src","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:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.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/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.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",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function A(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var $=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),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:xt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};A(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var F=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){A(this.params.endpoint)?.catch(e=>console.log(e))}};var G=X(H(),1);var q=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(se);r?this.userId=r:(this.userId=(0,G.createId)(),localStorage.setItem(se,this.userId))}else this.userId=(0,G.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await A(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,G.createId)(),this.identity=void 0,this.userAlias=void 0}};function Bn(t){return t!==void 0&&t?.signal!==void 0}var ce=class{id=(0,It.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+yt,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new q({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=$.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new j(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,u=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let d=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();i=f-d;let m=await z(BigInt(f*1e6-d*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let x of o)x.elapsed=m;this.cache?.set(s,o)}catch(d){if(d.name!=="AbortError")throw console.error("Search request failed",d),d}return this.addSearchResultsToCollector(o,i,e,c),o};if(u&&this.cache)i=0,o=this.cache.get(s),c=!0,this.addSearchResultsToCollector(o,i,e,c);else return n?.debounce?new Promise((d,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),d(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),f(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let u=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await z(BigInt(h*1e6-u*1e6)),s=h-u,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new N({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new F({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=Bn(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let c={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let d=r;d.version=St,d.id=this.id,d.visitorId=this.profile.getUserId(),c.body=Object.entries(d).filter(([f,m])=>!!m).map(([f,m])=>`${f}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let u=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||u.searchParams.append("api-key",this.api_key),o)for(let[d,f]of Object.entries(o))f&&u.searchParams.append(d,f);let h=await fetch(u,c);if(!h.ok){let d=new Error;throw d.httpResponse=h,d}return await h.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var wt="text-embedding-ada-002",Tt="text-embedding-3-small",At="text-embedding-3-large",_t="gte-small",Ct="gte-medium",Ot="gte-large",Et="gpt-4o",Pt="gpt-4o-mini",vt="gpt-4-turbo",kt="gpt-4-turbo-2024-04-09",Mt="gpt-4-0125-preview",Nt="gpt-4-1106-preview",Dt="gpt-4-turbo-preview",Rt="gpt-4",Lt="gpt-3.5-turbo",Bt="gpt-3.5-turbo-0125",Un={[`openai/${wt}`]:`openai/${wt}`,[`openai/${Tt}`]:`openai/${Tt}`,[`openai/${At}`]:`openai/${At}`,[`orama/${Ot}`]:`orama/${Ot}`,[`orama/${Ct}`]:`orama/${Ct}`,[`orama/${_t}`]:`orama/${_t}`},Ut={[`openai/${Lt}`]:Lt,[`openai/${Rt}`]:Rt,[`openai/${Nt}`]:Nt,[`openai/${Mt}`]:Mt,[`openai/${Dt}`]:Dt,[`openai/${Bt}`]:Bt,[`openai/${kt}`]:kt,[`openai/${Et}`]:Et,[`openai/${Pt}`]:Pt,[`openai/${vt}`]:vt},le=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 s=`${M}${mt}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:Un[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}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=`${M}${ft}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=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(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:u}=await o.read();if(u)break;yield i.decode(c,{stream:!0})}}catch(s){if(s.name!=="AbortError")throw s}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.summaryStream(e))r+=s;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.chatStream(e))r+=s;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${M}${ht}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async u=>!u.content||typeof u.content!="string"?u:{...u,content:await Fn(this.publicKey,u.content)})));let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:Ut[e.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),c=new TextDecoder;for(;;){let{value:u,done:h}=await i.read();if(h)break;yield c.decode(u,{stream:!0})}}async init(){let e=`${M}${pt}?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 Hn($n(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 Hn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function jn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function $n(t){return Uint8Array.from(t)}var Ht=50;async function Fn(t,e){let n=new TextEncoder().encode(e),r=[];for(let s=0;s<n.length;s+=Ht){let o=n.subarray(s,s+Ht),i=await jn(t,o);r.push(Array.from(i))}return r}var de="snapshot",K="notify",jt="deploy",$t="has-data",Ft="update-schema";var Gn="https://api.askorama.ai",Gt=`${Gn}/api/v1`;var V=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(de,[])).success}async snapshot(e){return(await this.callIndexWebhook(de,e)).success}async insert(e){return(await this.callIndexWebhook(K,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(K,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(K,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(Ft,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(jt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook($t)).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 ue=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||Gt}index(e){return new V({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(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};return zt(Kn);})(); | ||
/*! Bundled license information: | ||
@@ -7,0 +7,0 @@ |
@@ -1,6 +0,6 @@ | ||
var xt=Object.create;var ae=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ot=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of At(e))!Et.call(t,s)&&s!==n&&ae(t,s,{get:()=>e[s],enumerable:!(r=It(e,s))||r.enumerable});return t};var K=(t,e,n)=>(n=t!=null?xt(Tt(t)):{},Ot(e||!t||!t.__esModule?ae(n,"default",{value:t,enumerable:!0}):n,t));var me=w(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.output=f.exists=f.hash=f.bytes=f.bool=f.number=void 0;function k(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}f.number=k;function pe(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}f.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}`)}f.bytes=Y;function he(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");k(t.outputLen),k(t.blockLen)}f.hash=he;function fe(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")}f.exists=fe;function ye(t,e){Y(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=ye;var Ct={number:k,bool:pe,bytes:Y,hash:he,exists:fe,output:ye};f.default=Ct});var Se=w(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.add=y.toBig=y.split=y.fromBig=void 0;var N=BigInt(2**32-1),X=BigInt(32);function z(t,e=!1){return e?{h:Number(t&N),l:Number(t>>X&N)}:{h:Number(t>>X&N)|0,l:Number(t&N)|0}}y.fromBig=z;function ge(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=z(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}y.split=ge;var _t=(t,e)=>BigInt(t>>>0)<<X|BigInt(e>>>0);y.toBig=_t;var Pt=(t,e,n)=>t>>>n,vt=(t,e,n)=>t<<32-n|e>>>n,kt=(t,e,n)=>t>>>n|e<<32-n,Nt=(t,e,n)=>t<<32-n|e>>>n,Dt=(t,e,n)=>t<<64-n|e>>>n-32,Mt=(t,e,n)=>t>>>n-32|e<<64-n,Rt=(t,e)=>e,Lt=(t,e)=>t,Bt=(t,e,n)=>t<<n|e>>>32-n,Ut=(t,e,n)=>e<<n|t>>>32-n,$t=(t,e,n)=>e<<n-32|t>>>64-n,jt=(t,e,n)=>t<<n-32|e>>>64-n;function be(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}y.add=be;var Ht=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Gt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Ft=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),qt=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Wt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Kt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Vt={fromBig:z,split:ge,toBig:y.toBig,shrSH:Pt,shrSL:vt,rotrSH:kt,rotrSL:Nt,rotrBH:Dt,rotrBL:Mt,rotr32H:Rt,rotr32L:Lt,rotlSH:Bt,rotlSL:Ut,rotlBH:$t,rotlBL:jt,add:be,add3L:Ht,add3H:Gt,add4L:Ft,add4H:qt,add5H:Kt,add5L:Wt};y.default=Vt});var we=w(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.crypto=void 0;D.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Ie=w(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var Q=we(),Z=t=>t instanceof Uint8Array,Yt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=Yt;var Xt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=Xt;var zt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=zt;var Qt=(t,e)=>t<<32-e|t>>>e;a.rotr=Qt;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Jt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Zt(t){if(!Z(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Jt[t[n]];return e}a.bytesToHex=Zt;function en(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 s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=en;var tn=async()=>{};a.nextTick=tn;async function nn(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=nn;function xe(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=xe;function M(t){if(typeof t=="string"&&(t=xe(t)),!Z(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=M;function rn(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!Z(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=rn;var J=class{clone(){return this._cloneInto()}};a.Hash=J;var sn=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function on(t,e){if(e!==void 0&&(typeof e!="object"||!sn(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=on;function an(t){let e=r=>t().update(M(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=an;function cn(t){let e=(r,s)=>t(s).update(M(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=cn;function ln(t){let e=(r,s)=>t(s).update(M(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=ln;function un(t=32){if(Q.crypto&&typeof Q.crypto.getRandomValues=="function")return Q.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=un});var ve=w(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=d.keccakP=void 0;var A=me(),O=Se(),E=Ie(),[Ee,Oe,Ce]=[[],[],[]],dn=BigInt(0),T=BigInt(1),pn=BigInt(2),hn=BigInt(7),fn=BigInt(256),yn=BigInt(113);for(let t=0,e=T,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ee.push(2*(5*r+n)),Oe.push((t+1)*(t+2)/2%64);let s=dn;for(let o=0;o<7;o++)e=(e<<T^(e>>hn)*yn)%fn,e&pn&&(s^=T<<(T<<BigInt(o))-T);Ce.push(s)}var[mn,gn]=O.default.split(Ce,!0),Ae=(t,e,n)=>n>32?O.default.rotlBH(t,e,n):O.default.rotlSH(t,e,n),Te=(t,e,n)=>n>32?O.default.rotlBL(t,e,n):O.default.rotlSL(t,e,n);function _e(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,u=(i+2)%10,p=n[u],l=n[u+1],h=Ae(p,l,1)^n[c],m=Te(p,l,1)^n[c+1];for(let I=0;I<50;I+=10)t[i+I]^=h,t[i+I+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Oe[i],u=Ae(s,o,c),p=Te(s,o,c),l=Ee[i];s=t[l],o=t[l+1],t[l]=u,t[l+1]=p}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=mn[r],t[1]^=gn[r]}n.fill(0)}d.keccakP=_e;var C=class t extends E.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,A.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,E.u32)(this.state)}keccak(){_e(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){A.default.exists(this);let{blockLen:n,state:r}=this;e=(0,E.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){A.default.exists(this,!1),A.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return A.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(A.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=C;var b=(t,e,n)=>(0,E.wrapConstructor)(()=>new C(e,t,n));d.sha3_224=b(6,144,224/8);d.sha3_256=b(6,136,256/8);d.sha3_384=b(6,104,384/8);d.sha3_512=b(6,72,512/8);d.keccak_224=b(1,144,224/8);d.keccak_256=b(1,136,256/8);d.keccak_384=b(1,104,384/8);d.keccak_512=b(1,72,512/8);var Pe=(t,e,n)=>(0,E.wrapXOFConstructorWithOpts)((r={})=>new C(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Pe(31,168,128/8);d.shake256=Pe(31,136,256/8)});var Ue=w((Vn,S)=>{"use strict";var{sha3_512:bn}=ve(),Ne=24,_=32,ee=(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=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Me=(t="")=>De(bn(t)).toString(36).slice(1),ke=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),Sn=t=>ke[Math.floor(t()*ke.length)],Re=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+ee(_,e):ee(_,e);return Me(r).substring(0,_)},Le=t=>()=>t++,wn=476782367,Be=({random:t=Math.random,counter:e=Le(Math.floor(t()*wn)),length:n=Ne,fingerprint:r=Re({random:t})}={})=>function(){let o=Sn(t),i=Date.now().toString(36),c=e().toString(36),u=ee(n,t),p=`${i+u+c+r}`;return`${o+Me(p).substring(1,n)}`},xn=Be(),In=(t,{minLength:e=2,maxLength:n=_}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};S.exports.getConstants=()=>({defaultLength:Ne,bigLength:_});S.exports.init=Be;S.exports.createId=xn;S.exports.bufToBigInt=De;S.exports.createCounter=Le;S.exports.createFingerprint=Re;S.exports.isCuid=In});var R=w((Yn,P)=>{"use strict";var{createId:An,init:Tn,getConstants:En,isCuid:On}=Ue();P.exports.createId=An;P.exports.init=Tn;P.exports.getConstants=En;P.exports.isCuid=On});var Bn=Date.now().toString().slice(5);var ce=BigInt(1e3),le=BigInt(1e6),ue=BigInt(1e9);async function de(t){return typeof t=="number"&&(t=BigInt(t)),t<ce?`${t}ns`:t<le?`${t/ce}\u03BCs`:t<ue?`${t/le}ms`:`${t/ue}s`}async function V(t){return{raw:Number(t),formatted:await de(t)}}var ze=K(R(),1);var re=K(R(),1);var $e="https://answer.api.orama.com",v="https://secure-proxy.orama.run",je="/init",He="/chat",Ge="/summary",Fe="/query",qe="https://cloud.orama.run/v1/indexes",te="orama_user_id";function We(t){let[e,...n]=t.split(` | ||
var Gt=Object.create;var le=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Kt=Object.getOwnPropertyNames;var Vt=Object.getPrototypeOf,Wt=Object.prototype.hasOwnProperty;var T=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Yt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Kt(e))!Wt.call(t,s)&&s!==n&&le(t,s,{get:()=>e[s],enumerable:!(r=qt(e,s))||r.enumerable});return t};var Y=(t,e,n)=>(n=t!=null?Gt(Vt(t)):{},Yt(e||!t||!t.__esModule?le(n,"default",{value:t,enumerable:!0}):n,t));var Q=T(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.isBytes=me;g.number=N;g.bool=fe;g.bytes=z;g.hash=ye;g.exists=ge;g.output=be;function N(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function fe(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function me(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function z(t,...e){if(!me(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function ye(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");N(t.outputLen),N(t.blockLen)}function ge(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")}function be(t,e){z(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Xt={number:N,bool:fe,bytes:z,hash:ye,exists:ge,output:be};g.default=Xt});var je=T(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=Z;a.split=Se;a.add=Ne;var D=BigInt(2**32-1),J=BigInt(32);function Z(t,e=!1){return e?{h:Number(t&D),l:Number(t>>J&D)}:{h:Number(t>>J&D)|0,l:Number(t&D)|0}}function Se(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=Z(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var xe=(t,e)=>BigInt(t>>>0)<<J|BigInt(e>>>0);a.toBig=xe;var Ie=(t,e,n)=>t>>>n;a.shrSH=Ie;var we=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=we;var Te=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=Te;var Ae=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Ae;var _e=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=_e;var Ce=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=Ce;var Oe=(t,e)=>e;a.rotr32H=Oe;var Ee=(t,e)=>t;a.rotr32L=Ee;var Pe=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Pe;var ve=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=ve;var ke=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=ke;var Me=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Me;function Ne(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var De=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=De;var Re=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=Re;var Le=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Le;var Be=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=Be;var Ue=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=Ue;var He=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=He;var zt={fromBig:Z,split:Se,toBig:xe,shrSH:Ie,shrSL:we,rotrSH:Te,rotrSL:Ae,rotrBH:_e,rotrBL:Ce,rotr32H:Oe,rotr32L:Ee,rotlSH:Pe,rotlSL:ve,rotlBH:ke,rotlBL:Me,add:Ne,add3L:De,add3H:Re,add4L:Le,add4H:Be,add5H:He,add5L:Ue};a.default=zt});var $e=T(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.crypto=void 0;R.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var qe=T(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.Hash=l.nextTick=l.byteSwapIfBE=l.byteSwap=l.isLE=l.rotl=l.rotr=l.createView=l.u32=l.u8=void 0;l.isBytes=Qt;l.byteSwap32=sn;l.bytesToHex=an;l.hexToBytes=cn;l.asyncLoop=dn;l.utf8ToBytes=Ge;l.toBytes=L;l.concatBytes=un;l.checkOpts=hn;l.wrapConstructor=fn;l.wrapConstructorWithOpts=mn;l.wrapXOFConstructorWithOpts=yn;l.randomBytes=gn;var _=$e(),te=Q();function Qt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Jt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);l.u8=Jt;var Zt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));l.u32=Zt;var en=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);l.createView=en;var tn=(t,e)=>t<<32-e|t>>>e;l.rotr=tn;var nn=(t,e)=>t<<e|t>>>32-e>>>0;l.rotl=nn;l.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var rn=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;l.byteSwap=rn;l.byteSwapIfBE=l.isLE?t=>t:t=>(0,l.byteSwap)(t);function sn(t){for(let e=0;e<t.length;e++)t[e]=(0,l.byteSwap)(t[e])}var on=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function an(t){(0,te.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=on[t[n]];return e}var b={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Fe(t){if(t>=b._0&&t<=b._9)return t-b._0;if(t>=b._A&&t<=b._F)return t-(b._A-10);if(t>=b._a&&t<=b._f)return t-(b._a-10)}function cn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=Fe(t.charCodeAt(o)),c=Fe(t.charCodeAt(o+1));if(i===void 0||c===void 0){let u=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+u+'" at index '+o)}r[s]=i*16+c}return r}var ln=async()=>{};l.nextTick=ln;async function dn(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,l.nextTick)(),r+=o)}}function Ge(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function L(t){return typeof t=="string"&&(t=Ge(t)),(0,te.bytes)(t),t}function un(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,te.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var ee=class{clone(){return this._cloneInto()}};l.Hash=ee;var pn={}.toString;function hn(t,e){if(e!==void 0&&pn.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function fn(t){let e=r=>t().update(L(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function mn(t){let e=(r,s)=>t(s).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function yn(t){let e=(r,s)=>t(s).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function gn(t=32){if(_.crypto&&typeof _.crypto.getRandomValues=="function")return _.crypto.getRandomValues(new Uint8Array(t));if(_.crypto&&typeof _.crypto.randomBytes=="function")return _.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var Je=T(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=void 0;p.keccakP=ze;var C=Q(),E=je(),S=qe(),We=[],Ye=[],Xe=[],bn=BigInt(0),O=BigInt(1),Sn=BigInt(2),xn=BigInt(7),In=BigInt(256),wn=BigInt(113);for(let t=0,e=O,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],We.push(2*(5*r+n)),Ye.push((t+1)*(t+2)/2%64);let s=bn;for(let o=0;o<7;o++)e=(e<<O^(e>>xn)*wn)%In,e&Sn&&(s^=O<<(O<<BigInt(o))-O);Xe.push(s)}var[Tn,An]=(0,E.split)(Xe,!0),Ke=(t,e,n)=>n>32?(0,E.rotlBH)(t,e,n):(0,E.rotlSH)(t,e,n),Ve=(t,e,n)=>n>32?(0,E.rotlBL)(t,e,n):(0,E.rotlSL)(t,e,n);function ze(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,u=(i+2)%10,h=n[u],d=n[u+1],f=Ke(h,d,1)^n[c],m=Ve(h,d,1)^n[c+1];for(let x=0;x<50;x+=10)t[i+x]^=f,t[i+x+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Ye[i],u=Ke(s,o,c),h=Ve(s,o,c),d=We[i];s=t[d],o=t[d+1],t[d]=u,t[d+1]=h}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=Tn[r],t[1]^=An[r]}n.fill(0)}var P=class t extends S.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,C.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,S.u32)(this.state)}keccak(){S.isLE||(0,S.byteSwap32)(this.state32),ze(this.state32,this.rounds),S.isLE||(0,S.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,C.exists)(this);let{blockLen:n,state:r}=this;e=(0,S.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,C.exists)(this,!1),(0,C.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,C.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,C.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:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};p.Keccak=P;var I=(t,e,n)=>(0,S.wrapConstructor)(()=>new P(e,t,n));p.sha3_224=I(6,144,224/8);p.sha3_256=I(6,136,256/8);p.sha3_384=I(6,104,384/8);p.sha3_512=I(6,72,512/8);p.keccak_224=I(1,144,224/8);p.keccak_256=I(1,136,256/8);p.keccak_384=I(1,104,384/8);p.keccak_512=I(1,72,512/8);var Qe=(t,e,n)=>(0,S.wrapXOFConstructorWithOpts)((r={})=>new P(e,t,r.dkLen===void 0?n:r.dkLen,!0));p.shake128=Qe(31,168,128/8);p.shake256=Qe(31,136,256/8)});var it=T((er,w)=>{"use strict";var{sha3_512:_n}=Je(),et=24,v=32,ne=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function tt(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var nt=(t="")=>tt(_n(t)).toString(36).slice(1),Ze=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),Cn=t=>Ze[Math.floor(t()*Ze.length)],rt=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+ne(v,e):ne(v,e);return nt(r).substring(0,v)},st=t=>()=>t++,On=476782367,ot=({random:t=Math.random,counter:e=st(Math.floor(t()*On)),length:n=et,fingerprint:r=rt({random:t})}={})=>function(){let o=Cn(t),i=Date.now().toString(36),c=e().toString(36),u=ne(n,t),h=`${i+u+c+r}`;return`${o+nt(h).substring(1,n)}`},En=ot(),Pn=(t,{minLength:e=2,maxLength:n=v}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:et,bigLength:v});w.exports.init=ot;w.exports.createId=En;w.exports.bufToBigInt=tt;w.exports.createCounter=st;w.exports.createFingerprint=rt;w.exports.isCuid=Pn});var B=T((tr,k)=>{"use strict";var{createId:vn,init:kn,getConstants:Mn,isCuid:Nn}=it();k.exports.createId=vn;k.exports.init=kn;k.exports.getConstants=Mn;k.exports.isCuid=Nn});var qn=Date.now().toString().slice(5);var de=BigInt(1e3),ue=BigInt(1e6),pe=BigInt(1e9);async function he(t){return typeof t=="number"&&(t=BigInt(t)),t<de?`${t}ns`:t<ue?`${t/de}\u03BCs`:t<pe?`${t/ue}ms`:`${t/pe}s`}async function X(t){return{raw:Number(t),formatted:await he(t)}}var bt=Y(B(),1);var oe=Y(B(),1);var at="https://answer.api.orama.com",M="https://secure-proxy.orama.run",ct="/init",lt="/chat",dt="/summary",ut="/query",pt="/v1/indexes",re="orama_user_id";function ht(t){let[e,...n]=t.split(` | ||
`),r=n.join(` | ||
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ne(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var L=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||$e;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,re.createId)(),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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,re.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ne(this.userContext)),e.userData&&o.append("userData",ne(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let u=new TextDecoder,p=[],l="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let h=this.messages.at(-1);for(;;){let{value:m,done:I}=await r.read();if(I)break;l+=u.decode(m,{stream:!0});let q;for(;(q=l.indexOf(` | ||
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function se(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var U=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||at;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,oe.createId)(),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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,oe.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",se(this.userContext)),e.userData&&o.append("userData",se(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let u=new TextDecoder,h=[],d="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:m,done:x}=await r.read();if(x)break;d+=u.decode(m,{stream:!0});let V;for(;(V=d.indexOf(` | ||
`))!==-1;){let ie=l.slice(0,q);l=l.slice(q+2);try{let W=We(ie),g=JSON.parse(W.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(p.push(g.message);p.length>0;)h.content+=p.shift(),this.state[s].response=h.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield h.content}catch(W){console.error("Error parsing SSE event:",W),console.error("Raw message:",ie)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var B=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var Ve="1.3.19";var Ye={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:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.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/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.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",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function x(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 U=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),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};x(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){x(this.params.endpoint)?.catch(e=>console.log(e))}};var j=K(R(),1);var H=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(te);r?this.userId=r:(this.userId=(0,j.createId)(),localStorage.setItem(te,this.userId))}else this.userId=(0,j.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await x(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,j.createId)(),this.identity=void 0,this.userAlias=void 0}};function _n(t){return t!==void 0&&t?.signal!==void 0}var Xe=class{id=(0,ze.createId)();api_key;endpoint;multiIndexSearch;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e?(this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes,this.endpoint=e.endpoint||qe,this.multiIndexSearch=!0):(this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1),this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new H({endpoint:this.endpoint,apiKey:this.api_key}),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=U.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new B(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,u=n?.fresh!==!0&&this.cache?.has(s),p=async()=>{try{let l=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:!0},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let h=Date.now();o.elapsed=await V(BigInt(h*1e6-l*1e6)),i=h-l,this.cache?.set(s,o)}catch(l){if(l.name!=="AbortError")throw console.error("Search request failed",l),l}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(u&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((l,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),l(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),h(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):p();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let u=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let p=Date.now();o.elapsed=await V(BigInt(p*1e6-u*1e6)),s=p-u,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new L({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){let i=_n(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let c={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let l=r;l.version=Ve,l.id=this.id,l.visitorId=this.profile.getUserId(),c.body=Object.entries(l).filter(([h,m])=>!!m).map(([h,m])=>`${h}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let u=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||u.searchParams.append("api-key",this.api_key),o)for(let[l,h]of Object.entries(o))h&&u.searchParams.append(l,h);let p=await fetch(u,c);if(!p.ok){let l=new Error;throw l.httpResponse=p,l}return await p.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var Qe="text-embedding-ada-002",Je="text-embedding-3-small",Ze="text-embedding-3-large",et="gte-small",tt="gte-medium",nt="gte-large",rt="gpt-4o",st="gpt-4o-mini",ot="gpt-4-turbo",it="gpt-4-turbo-2024-04-09",at="gpt-4-0125-preview",ct="gpt-4-1106-preview",lt="gpt-4-turbo-preview",ut="gpt-4",dt="gpt-3.5-turbo",pt="gpt-3.5-turbo-0125",Pn={[`openai/${Qe}`]:`openai/${Qe}`,[`openai/${Je}`]:`openai/${Je}`,[`openai/${Ze}`]:`openai/${Ze}`,[`orama/${nt}`]:`orama/${nt}`,[`orama/${tt}`]:`orama/${tt}`,[`orama/${et}`]:`orama/${et}`},ht={[`openai/${dt}`]:dt,[`openai/${ut}`]:ut,[`openai/${ct}`]:ct,[`openai/${at}`]:at,[`openai/${lt}`]:lt,[`openai/${pt}`]:pt,[`openai/${it}`]:it,[`openai/${rt}`]:rt,[`openai/${st}`]:st,[`openai/${ot}`]:ot},ft=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 s=`${v}${Fe}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:Pn[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}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}${Ge}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=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:ht[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:u}=await o.read();if(u)break;yield i.decode(c,{stream:!0})}}catch(s){if(s.name!=="AbortError")throw s}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.summaryStream(e))r+=s;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.chatStream(e))r+=s;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${He}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async u=>!u.content||typeof u.content!="string"?u:{...u,content:await Dn(this.publicKey,u.content)})));let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:ht[e.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),c=new TextDecoder;for(;;){let{value:u,done:p}=await i.read();if(p)break;yield c.decode(u,{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 vn(Nn(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function vn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function kn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function Nn(t){return Uint8Array.from(t)}var yt=50;async function Dn(t,e){let n=new TextEncoder().encode(e),r=[];for(let s=0;s<n.length;s+=yt){let o=n.subarray(s,s+yt),i=await kn(t,o);r.push(Array.from(i))}return r}var oe="snapshot",G="notify",mt="deploy",gt="has-data",bt="update-schema";var Mn="https://api.askorama.ai",St=`${Mn}/api/v1`;var F=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(G,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(G,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(G,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(bt,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(mt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(gt)).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 wt=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||St}index(e){return new F({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(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};export{L as AnswerSession,wt as CloudManager,Xe as OramaClient,ft as OramaProxy}; | ||
`))!==-1;){let ce=d.slice(0,V);d=d.slice(V+2);try{let W=ht(ce),y=JSON.parse(W.data);if(y.type==="sources")this.state[s].sources=y.message,this.events?.onSourceChange&&this.events.onSourceChange(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="query-translated")this.state[s].translatedQuery=y.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="related-queries")this.state[s].relatedQueries=y.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="text")for(h.push(y.message);h.length>0;)f.content+=h.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(W){console.error("Error parsing SSE event:",W),console.error("Raw message:",ce)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var H=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 mt="1.3.20";var yt={name:"@oramacloud/client",version:mt,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 src","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:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.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/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.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",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function A(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var j=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),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:yt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};A(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){A(this.params.endpoint)?.catch(e=>console.log(e))}};var F=Y(B(),1);var G=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(re);r?this.userId=r:(this.userId=(0,F.createId)(),localStorage.setItem(re,this.userId))}else this.userId=(0,F.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await A(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,F.createId)(),this.identity=void 0,this.userAlias=void 0}};function Rn(t){return t!==void 0&&t?.signal!==void 0}var gt=class{id=(0,bt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+pt,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new G({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=j.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new H(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,u=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let d=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();i=f-d;let m=await X(BigInt(f*1e6-d*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let x of o)x.elapsed=m;this.cache?.set(s,o)}catch(d){if(d.name!=="AbortError")throw console.error("Search request failed",d),d}return this.addSearchResultsToCollector(o,i,e,c),o};if(u&&this.cache)i=0,o=this.cache.get(s),c=!0,this.addSearchResultsToCollector(o,i,e,c);else return n?.debounce?new Promise((d,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),d(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),f(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let u=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await X(BigInt(h*1e6-u*1e6)),s=h-u,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new U({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=Rn(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let c={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let d=r;d.version=mt,d.id=this.id,d.visitorId=this.profile.getUserId(),c.body=Object.entries(d).filter(([f,m])=>!!m).map(([f,m])=>`${f}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let u=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||u.searchParams.append("api-key",this.api_key),o)for(let[d,f]of Object.entries(o))f&&u.searchParams.append(d,f);let h=await fetch(u,c);if(!h.ok){let d=new Error;throw d.httpResponse=h,d}return await h.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var St="text-embedding-ada-002",xt="text-embedding-3-small",It="text-embedding-3-large",wt="gte-small",Tt="gte-medium",At="gte-large",_t="gpt-4o",Ct="gpt-4o-mini",Ot="gpt-4-turbo",Et="gpt-4-turbo-2024-04-09",Pt="gpt-4-0125-preview",vt="gpt-4-1106-preview",kt="gpt-4-turbo-preview",Mt="gpt-4",Nt="gpt-3.5-turbo",Dt="gpt-3.5-turbo-0125",Ln={[`openai/${St}`]:`openai/${St}`,[`openai/${xt}`]:`openai/${xt}`,[`openai/${It}`]:`openai/${It}`,[`orama/${At}`]:`orama/${At}`,[`orama/${Tt}`]:`orama/${Tt}`,[`orama/${wt}`]:`orama/${wt}`},Rt={[`openai/${Nt}`]:Nt,[`openai/${Mt}`]:Mt,[`openai/${vt}`]:vt,[`openai/${Pt}`]:Pt,[`openai/${kt}`]:kt,[`openai/${Dt}`]:Dt,[`openai/${Et}`]:Et,[`openai/${_t}`]:_t,[`openai/${Ct}`]:Ct,[`openai/${Ot}`]:Ot},Lt=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 s=`${M}${ut}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:Ln[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}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=`${M}${dt}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=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:Rt[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:u}=await o.read();if(u)break;yield i.decode(c,{stream:!0})}}catch(s){if(s.name!=="AbortError")throw s}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.summaryStream(e))r+=s;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.chatStream(e))r+=s;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${M}${lt}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async u=>!u.content||typeof u.content!="string"?u:{...u,content:await jn(this.publicKey,u.content)})));let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:Rt[e.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),c=new TextDecoder;for(;;){let{value:u,done:h}=await i.read();if(h)break;yield c.decode(u,{stream:!0})}}async init(){let e=`${M}${ct}?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 Bn(Hn(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 Bn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function Un(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function Hn(t){return Uint8Array.from(t)}var Bt=50;async function jn(t,e){let n=new TextEncoder().encode(e),r=[];for(let s=0;s<n.length;s+=Bt){let o=n.subarray(s,s+Bt),i=await Un(t,o);r.push(Array.from(i))}return r}var ae="snapshot",q="notify",Ut="deploy",Ht="has-data",jt="update-schema";var $n="https://api.askorama.ai",$t=`${$n}/api/v1`;var K=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(ae,[])).success}async snapshot(e){return(await this.callIndexWebhook(ae,e)).success}async insert(e){return(await this.callIndexWebhook(q,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(q,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(q,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(jt,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(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 Ft=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||$t}index(e){return new K({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(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};export{U as AnswerSession,Ft as CloudManager,gt as OramaClient,Lt as OramaProxy}; | ||
/*! Bundled license information: | ||
@@ -7,0 +7,0 @@ |
@@ -14,7 +14,7 @@ import { AnyDocument, Nullable, Results, SearchParams, AnyOrama } from '@orama/orama'; | ||
} | ||
interface IOramaClientMultiSearch extends Omit<IOramaClient, 'api_key' | 'endpoint'> { | ||
endpoint?: string; | ||
interface IOramaClientMultiSearch<M extends boolean> extends Omit<IOramaClient, 'api_key' | 'endpoint'> { | ||
mergeResults?: M; | ||
indexes: { | ||
api_key: string; | ||
id: string; | ||
endpoint: string; | ||
}[]; | ||
@@ -37,6 +37,6 @@ } | ||
type InferenceType = 'documentation'; | ||
type AnswerParams<UserContext = unknown> = { | ||
type AnswerParams<M extends boolean, UserContext = unknown> = { | ||
initialMessages: Message[]; | ||
inferenceType: InferenceType; | ||
oramaClient: OramaClient; | ||
oramaClient: OramaClient<M>; | ||
userContext?: UserContext; | ||
@@ -74,3 +74,3 @@ events?: { | ||
}; | ||
declare class AnswerSession { | ||
declare class AnswerSession<M extends boolean> { | ||
private messages; | ||
@@ -87,3 +87,3 @@ private inferenceType; | ||
private systemPrompts?; | ||
constructor(params: AnswerParams); | ||
constructor(params: AnswerParams<M>); | ||
askStream(params: AskParams): Promise<AsyncGenerator<string>>; | ||
@@ -129,2 +129,3 @@ ask(params: AskParams): Promise<string>; | ||
}> & AdditionalSearchParams; | ||
type OramaClientSearchResult<M> = M extends true ? Results<DocumentType> : Results<DocumentType>[]; | ||
type AnswerSessionParams = { | ||
@@ -147,3 +148,3 @@ inferenceType?: InferenceType; | ||
declare class OramaClient { | ||
declare class OramaClient<M extends boolean = true> { | ||
private readonly id; | ||
@@ -153,2 +154,3 @@ private readonly api_key; | ||
private readonly multiIndexSearch; | ||
private readonly mergeResults; | ||
private readonly multiIndexIndexes?; | ||
@@ -164,3 +166,3 @@ private readonly answersApiBaseURL; | ||
private initPromise?; | ||
constructor(params: IOramaClient | IOramaClientMultiSearch); | ||
constructor(params: IOramaClient | IOramaClientMultiSearch<M>); | ||
private customerUserToken; | ||
@@ -171,5 +173,6 @@ private searchToken; | ||
setOnAuthTokenExpired(onAuthTokenExpired: (token: string) => void): void; | ||
search(query: ClientSearchParams, config?: SearchConfig): Promise<Nullable<Results<AnyDocument>>>; | ||
private addSearchResultsToCollector; | ||
search(query: ClientSearchParams, config?: SearchConfig): Promise<Nullable<OramaClientSearchResult<M>>>; | ||
vectorSearch(query: ClientSearchParams, config?: SearchConfig): Promise<Pick<Results<AnyDocument>, 'hits' | 'elapsed'>>; | ||
createAnswerSession(params?: AnswerSessionParams): AnswerSession; | ||
createAnswerSession(params?: AnswerSessionParams): AnswerSession<M>; | ||
startHeartBeat(config: HeartBeatConfig): void; | ||
@@ -176,0 +179,0 @@ stopHeartBeat(): void; |
@@ -1,6 +0,6 @@ | ||
var We=Object.create;var le=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var tt=(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 Error('Dynamic require of "'+t+'" is not supported')});var A=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var nt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Je(e))!et.call(t,s)&&s!==n&&le(t,s,{get:()=>e[s],enumerable:!(r=Ge(e,s))||r.enumerable});return t};var z=(t,e,n)=>(n=t!=null?We(Ze(t)):{},nt(e||!t||!t.__esModule?le(n,"default",{value:t,enumerable:!0}):n,t));var be=A(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.output=m.exists=m.hash=m.bytes=m.bool=m.number=void 0;function D(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}m.number=D;function fe(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}m.bool=fe;function G(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}`)}m.bytes=G;function me(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");D(t.outputLen),D(t.blockLen)}m.hash=me;function ge(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")}m.exists=ge;function ye(t,e){G(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}m.output=ye;var rt={number:D,bool:fe,bytes:G,hash:me,exists:ge,output:ye};m.default=rt});var xe=A(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.add=b.toBig=b.split=b.fromBig=void 0;var U=BigInt(2**32-1),J=BigInt(32);function Z(t,e=!1){return e?{h:Number(t&U),l:Number(t>>J&U)}:{h:Number(t>>J&U)|0,l:Number(t&U)|0}}b.fromBig=Z;function we(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=Z(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}b.split=we;var st=(t,e)=>BigInt(t>>>0)<<J|BigInt(e>>>0);b.toBig=st;var ot=(t,e,n)=>t>>>n,it=(t,e,n)=>t<<32-n|e>>>n,at=(t,e,n)=>t>>>n|e<<32-n,ct=(t,e,n)=>t<<32-n|e>>>n,lt=(t,e,n)=>t<<64-n|e>>>n-32,ut=(t,e,n)=>t>>>n-32|e<<64-n,dt=(t,e)=>e,ht=(t,e)=>t,pt=(t,e,n)=>t<<n|e>>>32-n,ft=(t,e,n)=>e<<n|t>>>32-n,mt=(t,e,n)=>e<<n-32|t>>>64-n,gt=(t,e,n)=>t<<n-32|e>>>64-n;function Se(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}b.add=Se;var yt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),bt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,wt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),St=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,xt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),At=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Ct={fromBig:Z,split:we,toBig:b.toBig,shrSH:ot,shrSL:it,rotrSH:at,rotrSL:ct,rotrBH:lt,rotrBL:ut,rotr32H:dt,rotr32L:ht,rotlSH:pt,rotlSL:ft,rotlBH:mt,rotlBL:gt,add:Se,add3L:yt,add3H:bt,add4L:wt,add4H:St,add5H:At,add5L:xt};b.default=Ct});var Ae=A(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.crypto=void 0;var j=tt("node:crypto");H.crypto=j&&typeof j=="object"&&"webcrypto"in j?j.webcrypto:void 0});var ve=A(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var ee=Ae(),ne=t=>t instanceof Uint8Array,vt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=vt;var It=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=It;var Tt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=Tt;var Ot=(t,e)=>t<<32-e|t>>>e;a.rotr=Ot;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.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 Pt(t){if(!ne(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=kt[t[n]];return e}a.bytesToHex=Pt;function Et(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 s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Et;var _t=async()=>{};a.nextTick=_t;async function Rt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=Rt;function Ce(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=Ce;function $(t){if(typeof t=="string"&&(t=Ce(t)),!ne(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=$;function Mt(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!ne(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=Mt;var te=class{clone(){return this._cloneInto()}};a.Hash=te;var Nt=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function Bt(t,e){if(e!==void 0&&(typeof e!="object"||!Nt(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=Bt;function Lt(t){let e=r=>t().update($(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=Lt;function Dt(t){let e=(r,s)=>t(s).update($(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=Dt;function Ut(t){let e=(r,s)=>t(s).update($(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=Ut;function jt(t=32){if(ee.crypto&&typeof ee.crypto.getRandomValues=="function")return ee.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=jt});var Re=A(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 v=be(),R=xe(),_=ve(),[Oe,ke,Pe]=[[],[],[]],Ht=BigInt(0),E=BigInt(1),$t=BigInt(2),qt=BigInt(7),Ft=BigInt(256),Vt=BigInt(113);for(let t=0,e=E,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Oe.push(2*(5*r+n)),ke.push((t+1)*(t+2)/2%64);let s=Ht;for(let o=0;o<7;o++)e=(e<<E^(e>>qt)*Vt)%Ft,e&$t&&(s^=E<<(E<<BigInt(o))-E);Pe.push(s)}var[Kt,Qt]=R.default.split(Pe,!0),Ie=(t,e,n)=>n>32?R.default.rotlBH(t,e,n):R.default.rotlSH(t,e,n),Te=(t,e,n)=>n>32?R.default.rotlBL(t,e,n):R.default.rotlSL(t,e,n);function Ee(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,h=(i+2)%10,d=n[h],l=n[h+1],p=Ie(d,l,1)^n[c],g=Te(d,l,1)^n[c+1];for(let y=0;y<50;y+=10)t[i+y]^=p,t[i+y+1]^=g}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=ke[i],h=Ie(s,o,c),d=Te(s,o,c),l=Oe[i];s=t[l],o=t[l+1],t[l]=h,t[l+1]=d}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=Kt[r],t[1]^=Qt[r]}n.fill(0)}u.keccakP=Ee;var M=class t extends _.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,v.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,_.u32)(this.state)}keccak(){Ee(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){v.default.exists(this);let{blockLen:n,state:r}=this;e=(0,_.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){v.default.exists(this,!1),v.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return v.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(v.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:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};u.Keccak=M;var S=(t,e,n)=>(0,_.wrapConstructor)(()=>new M(e,t,n));u.sha3_224=S(6,144,224/8);u.sha3_256=S(6,136,256/8);u.sha3_384=S(6,104,384/8);u.sha3_512=S(6,72,512/8);u.keccak_224=S(1,144,224/8);u.keccak_256=S(1,136,256/8);u.keccak_384=S(1,104,384/8);u.keccak_512=S(1,72,512/8);var _e=(t,e,n)=>(0,_.wrapXOFConstructorWithOpts)((r={})=>new M(e,t,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=_e(31,168,128/8);u.shake256=_e(31,136,256/8)});var He=A((xn,x)=>{"use strict";var{sha3_512:Xt}=Re(),Ne=24,N=32,re=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Be(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Le=(t="")=>Be(Xt(t)).toString(36).slice(1),Me=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),Yt=t=>Me[Math.floor(t()*Me.length)],De=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+re(N,e):re(N,e);return Le(r).substring(0,N)},Ue=t=>()=>t++,zt=476782367,je=({random:t=Math.random,counter:e=Ue(Math.floor(t()*zt)),length:n=Ne,fingerprint:r=De({random:t})}={})=>function(){let o=Yt(t),i=Date.now().toString(36),c=e().toString(36),h=re(n,t),d=`${i+h+c+r}`;return`${o+Le(d).substring(1,n)}`},Wt=je(),Gt=(t,{minLength:e=2,maxLength:n=N}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};x.exports.getConstants=()=>({defaultLength:Ne,bigLength:N});x.exports.init=je;x.exports.createId=Wt;x.exports.bufToBigInt=Be;x.exports.createCounter=Ue;x.exports.createFingerprint=De;x.exports.isCuid=Gt});var q=A((An,B)=>{"use strict";var{createId:Jt,init:Zt,getConstants:en,isCuid:tn}=He();B.exports.createId=Jt;B.exports.init=Zt;B.exports.getConstants=en;B.exports.isCuid=tn});var dn=Date.now().toString().slice(5);var ue=BigInt(1e3),de=BigInt(1e6),he=BigInt(1e9);async function pe(t){return typeof t=="number"&&(t=BigInt(t)),t<ue?`${t}ns`:t<de?`${t/ue}\u03BCs`:t<he?`${t/de}ms`:`${t/he}s`}async function W(t){return{raw:Number(t),formatted:await pe(t)}}var Xe=z(q(),1);var ie=z(q(),1);var $e="https://answer.api.orama.com";var qe="https://cloud.orama.run/v1/indexes",se="orama_user_id";function Fe(t){let[e,...n]=t.split(` | ||
var bt=Object.create;var de=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var At=(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 Error('Dynamic require of "'+t+'" is not supported')});var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wt(e))!Ct.call(t,s)&&s!==n&&de(t,s,{get:()=>e[s],enumerable:!(r=St(e,s))||r.enumerable});return t};var J=(t,e,n)=>(n=t!=null?bt(xt(t)):{},vt(e||!t||!t.__esModule?de(n,"default",{value:t,enumerable:!0}):n,t));var ee=I(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.isBytes=ye;S.number=H;S.bool=ge;S.bytes=Z;S.hash=be;S.exists=Se;S.output=we;function H(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function ge(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function ye(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Z(t,...e){if(!ye(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function be(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");H(t.outputLen),H(t.blockLen)}function Se(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")}function we(t,e){Z(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var It={number:H,bool:ge,bytes:Z,hash:be,exists:Se,output:we};S.default=It});var qe=I(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=ne;a.split=xe;a.add=Be;var $=BigInt(2**32-1),te=BigInt(32);function ne(t,e=!1){return e?{h:Number(t&$),l:Number(t>>te&$)}:{h:Number(t>>te&$)|0,l:Number(t&$)|0}}function xe(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=ne(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var Ce=(t,e)=>BigInt(t>>>0)<<te|BigInt(e>>>0);a.toBig=Ce;var Ae=(t,e,n)=>t>>>n;a.shrSH=Ae;var ve=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=ve;var Ie=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=Ie;var Te=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Te;var Oe=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Oe;var ke=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=ke;var _e=(t,e)=>e;a.rotr32H=_e;var Pe=(t,e)=>t;a.rotr32L=Pe;var Ee=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Ee;var Me=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=Me;var Re=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=Re;var Le=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Le;function Be(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Ne=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Ne;var De=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=De;var Ue=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Ue;var je=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=je;var He=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=He;var $e=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=$e;var Tt={fromBig:ne,split:xe,toBig:Ce,shrSH:Ae,shrSL:ve,rotrSH:Ie,rotrSL:Te,rotrBH:Oe,rotrBL:ke,rotr32H:_e,rotr32L:Pe,rotlSH:Ee,rotlSL:Me,rotlBH:Re,rotlBL:Le,add:Be,add3L:Ne,add3H:De,add4L:Ue,add4H:je,add5H:$e,add5L:He};a.default=Tt});var Fe=I(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.crypto=void 0;var C=At("node:crypto");q.crypto=C&&typeof C=="object"&&"webcrypto"in C?C.webcrypto:C&&typeof C=="object"&&"randomBytes"in C?C:void 0});var Qe=I(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.Hash=l.nextTick=l.byteSwapIfBE=l.byteSwap=l.isLE=l.rotl=l.rotr=l.createView=l.u32=l.u8=void 0;l.isBytes=Ot;l.byteSwap32=Lt;l.bytesToHex=Nt;l.hexToBytes=Dt;l.asyncLoop=jt;l.utf8ToBytes=Ke;l.toBytes=F;l.concatBytes=Ht;l.checkOpts=qt;l.wrapConstructor=Ft;l.wrapConstructorWithOpts=Vt;l.wrapXOFConstructorWithOpts=Kt;l.randomBytes=Qt;var O=Fe(),se=ee();function Ot(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var kt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);l.u8=kt;var _t=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));l.u32=_t;var Pt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);l.createView=Pt;var Et=(t,e)=>t<<32-e|t>>>e;l.rotr=Et;var Mt=(t,e)=>t<<e|t>>>32-e>>>0;l.rotl=Mt;l.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Rt=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;l.byteSwap=Rt;l.byteSwapIfBE=l.isLE?t=>t:t=>(0,l.byteSwap)(t);function Lt(t){for(let e=0;e<t.length;e++)t[e]=(0,l.byteSwap)(t[e])}var Bt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Nt(t){(0,se.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Bt[t[n]];return e}var w={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Ve(t){if(t>=w._0&&t<=w._9)return t-w._0;if(t>=w._A&&t<=w._F)return t-(w._A-10);if(t>=w._a&&t<=w._f)return t-(w._a-10)}function Dt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=Ve(t.charCodeAt(o)),c=Ve(t.charCodeAt(o+1));if(i===void 0||c===void 0){let h=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+h+'" at index '+o)}r[s]=i*16+c}return r}var Ut=async()=>{};l.nextTick=Ut;async function jt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,l.nextTick)(),r+=o)}}function Ke(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function F(t){return typeof t=="string"&&(t=Ke(t)),(0,se.bytes)(t),t}function Ht(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,se.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var re=class{clone(){return this._cloneInto()}};l.Hash=re;var $t={}.toString;function qt(t,e){if(e!==void 0&&$t.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Ft(t){let e=r=>t().update(F(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Vt(t){let e=(r,s)=>t(s).update(F(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Kt(t){let e=(r,s)=>t(s).update(F(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Qt(t=32){if(O.crypto&&typeof O.crypto.getRandomValues=="function")return O.crypto.getRandomValues(new Uint8Array(t));if(O.crypto&&typeof O.crypto.randomBytes=="function")return O.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var et=I(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=We;var k=ee(),B=qe(),x=Qe(),ze=[],Ge=[],Je=[],Xt=BigInt(0),L=BigInt(1),Yt=BigInt(2),zt=BigInt(7),Gt=BigInt(256),Jt=BigInt(113);for(let t=0,e=L,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],ze.push(2*(5*r+n)),Ge.push((t+1)*(t+2)/2%64);let s=Xt;for(let o=0;o<7;o++)e=(e<<L^(e>>zt)*Jt)%Gt,e&Yt&&(s^=L<<(L<<BigInt(o))-L);Je.push(s)}var[Wt,Zt]=(0,B.split)(Je,!0),Xe=(t,e,n)=>n>32?(0,B.rotlBH)(t,e,n):(0,B.rotlSH)(t,e,n),Ye=(t,e,n)=>n>32?(0,B.rotlBL)(t,e,n):(0,B.rotlSL)(t,e,n);function We(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,h=(i+2)%10,p=n[h],u=n[h+1],f=Xe(p,u,1)^n[c],m=Ye(p,u,1)^n[c+1];for(let g=0;g<50;g+=10)t[i+g]^=f,t[i+g+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Ge[i],h=Xe(s,o,c),p=Ye(s,o,c),u=ze[i];s=t[u],o=t[u+1],t[u]=h,t[u+1]=p}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=Wt[r],t[1]^=Zt[r]}n.fill(0)}var N=class t extends x.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,k.number)(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,x.u32)(this.state)}keccak(){x.isLE||(0,x.byteSwap32)(this.state32),We(this.state32,this.rounds),x.isLE||(0,x.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,k.exists)(this);let{blockLen:n,state:r}=this;e=(0,x.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,k.exists)(this,!1),(0,k.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,k.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,k.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:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=N;var A=(t,e,n)=>(0,x.wrapConstructor)(()=>new N(e,t,n));d.sha3_224=A(6,144,224/8);d.sha3_256=A(6,136,256/8);d.sha3_384=A(6,104,384/8);d.sha3_512=A(6,72,512/8);d.keccak_224=A(1,144,224/8);d.keccak_256=A(1,136,256/8);d.keccak_384=A(1,104,384/8);d.keccak_512=A(1,72,512/8);var Ze=(t,e,n)=>(0,x.wrapXOFConstructorWithOpts)((r={})=>new N(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Ze(31,168,128/8);d.shake256=Ze(31,136,256/8)});var ct=I((kn,v)=>{"use strict";var{sha3_512:en}=et(),nt=24,D=32,oe=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function rt(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var st=(t="")=>rt(en(t)).toString(36).slice(1),tt=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),tn=t=>tt[Math.floor(t()*tt.length)],ot=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+oe(D,e):oe(D,e);return st(r).substring(0,D)},it=t=>()=>t++,nn=476782367,at=({random:t=Math.random,counter:e=it(Math.floor(t()*nn)),length:n=nt,fingerprint:r=ot({random:t})}={})=>function(){let o=tn(t),i=Date.now().toString(36),c=e().toString(36),h=oe(n,t),p=`${i+h+c+r}`;return`${o+st(p).substring(1,n)}`},rn=at(),sn=(t,{minLength:e=2,maxLength:n=D}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};v.exports.getConstants=()=>({defaultLength:nt,bigLength:D});v.exports.init=at;v.exports.createId=rn;v.exports.bufToBigInt=rt;v.exports.createCounter=it;v.exports.createFingerprint=ot;v.exports.isCuid=sn});var V=I((_n,U)=>{"use strict";var{createId:on,init:an,getConstants:cn,isCuid:ln}=ct();U.exports.createId=on;U.exports.init=an;U.exports.getConstants=cn;U.exports.isCuid=ln});var bn=Date.now().toString().slice(5);var he=BigInt(1e3),pe=BigInt(1e6),fe=BigInt(1e9);async function me(t){return typeof t=="number"&&(t=BigInt(t)),t<he?`${t}ns`:t<pe?`${t/he}\u03BCs`:t<fe?`${t/pe}ms`:`${t/fe}s`}async function W(t){return{raw:Number(t),formatted:await me(t)}}var mt=J(V(),1);var ce=J(V(),1);var lt="https://answer.api.orama.com";var ut="/v1/indexes",ie="orama_user_id";function dt(t){let[e,...n]=t.split(` | ||
`),r=n.join(` | ||
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function oe(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var I=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||$e;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,ie.createId)(),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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ie.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",oe(this.userContext)),e.userData&&o.append("userData",oe(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let h=new TextDecoder,d=[],l="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:g,done:y}=await r.read();if(y)break;l+=h.decode(g,{stream:!0});let k;for(;(k=l.indexOf(` | ||
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ae(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var _=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||lt;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,ce.createId)(),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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ce.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ae(this.userContext)),e.userData&&o.append("userData",ae(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let h=new TextDecoder,p=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:m,done:g}=await r.read();if(g)break;u+=h.decode(m,{stream:!0});let M;for(;(M=u.indexOf(` | ||
`))!==-1;){let L=l.slice(0,k);l=l.slice(k+2);try{let P=Fe(L),f=JSON.parse(P.data);if(f.type==="sources")this.state[s].sources=f.message,this.events?.onSourceChange&&this.events.onSourceChange(f.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(f.type==="query-translated")this.state[s].translatedQuery=f.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(f.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(f.type==="related-queries")this.state[s].relatedQueries=f.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(f.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(f.type==="text")for(d.push(f.message);d.length>0;)p.content+=d.shift(),this.state[s].response=p.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield p.content}catch(P){console.error("Error parsing SSE event:",P),console.error("Raw message:",L)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var F=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 Ke="1.3.19";var Qe={name:"@oramacloud/client",version:Ke,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:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.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/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.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",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function C(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 V=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:Qe.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};C(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var K=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){C(this.params.endpoint)?.catch(e=>console.log(e))}};var Q=z(q(),1);var X=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(se);r?this.userId=r:(this.userId=(0,Q.createId)(),localStorage.setItem(se,this.userId))}else this.userId=(0,Q.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await C(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,Q.createId)(),this.identity=void 0,this.userAlias=void 0}};function nn(t){return t!==void 0&&t?.signal!==void 0}var T=class{id=(0,Xe.createId)();api_key;endpoint;multiIndexSearch;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e?(this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes,this.endpoint=e.endpoint||qe,this.multiIndexSearch=!0):(this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1),this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new X({endpoint:this.endpoint,apiKey:this.api_key}),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=V.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new F(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,h=n?.fresh!==!0&&this.cache?.has(s),d=async()=>{try{let l=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:!0},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();o.elapsed=await W(BigInt(p*1e6-l*1e6)),i=p-l,this.cache?.set(s,o)}catch(l){if(l.name!=="AbortError")throw console.error("Search request failed",l),l}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(h&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((l,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await d(),l(o)}catch(g){g.name!=="AbortError"&&(console.error("Search request failed",g),p(g))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):d();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let h=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let d=Date.now();o.elapsed=await W(BigInt(d*1e6-h*1e6)),s=d-h,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new I({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new K({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){let i=nn(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let c={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let l=r;l.version=Ke,l.id=this.id,l.visitorId=this.profile.getUserId(),c.body=Object.entries(l).filter(([p,g])=>!!g).map(([p,g])=>`${p}=${encodeURIComponent(JSON.stringify(g))}`).join("&")}let h=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||h.searchParams.append("api-key",this.api_key),o)for(let[l,p]of Object.entries(o))p&&h.searchParams.append(l,p);let d=await fetch(h,c);if(!d.ok){let l=new Error;throw l.httpResponse=d,l}return await d.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};import an,{useState as Y,useEffect as Ye,createContext as cn,useContext as ln}from"react";import{useState as O,useRef as rn,useEffect as sn,useCallback as ce}from"react";function on(t){let[e,n]=O(t.initialMessages||[]),[r,s]=O(!1),[o,i]=O(null),[c,h]=O(!1),[d,l]=O(null),[p,g]=O(null),y=rn(null);sn(()=>{let f="oramaClient"in t?t.oramaClient:new T({api_key:t.apiKey,endpoint:t.endpoint});return y.current=new I({...t,initialMessages:t.initialMessages||[],inferenceType:t.inferenceType||"documentation",oramaClient:f,events:{onMessageChange:w=>{n(w)},onMessageLoading:w=>{s(w)},onAnswerAborted:w=>{h(w)},onSourceChange:w=>{l(w)},onRelatedQueries:w=>{g(w)}}}),()=>{y.current?.abortAnswer()}},[t]);let k=ce(async f=>{if(!y.current)try{h(!1),await y.current.ask(f)}catch(w){i(w)}},[]),L=ce(()=>{y?.current?.abortAnswer()},[]),P=ce(()=>{y?.current?.clearSession()},[]);return{messages:e,loading:r,aborted:c,abortAnswer:L,error:o,sources:d,relatedQueries:p,ask:k,clearSession:P}}var ze=cn({endpoint:"",apiKey:""}),rr=({children:t,endpoint:e,apiKey:n})=>an.createElement(ze.Provider,{value:{endpoint:e,apiKey:n}},t);function sr(t){let{apiKey:e,endpoint:n}=ln(ze),[r,s]=Y(!1),[o,i]=Y(null),[c,h]=Y(null),[d,l]=Y(null);return Ye(()=>{i(new T({api_key:e,endpoint:n})),s(!0)},[]),Ye(()=>{o!==null&&o.search(t).then(h).catch(l)},[o,t]),{ready:r,results:c,error:d}}export{rr as OramaCloud,on as useAnswerSession,sr as useSearch}; | ||
`))!==-1;){let j=u.slice(0,M);u=u.slice(M+2);try{let R=dt(j),y=JSON.parse(R.data);if(y.type==="sources")this.state[s].sources=y.message,this.events?.onSourceChange&&this.events.onSourceChange(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="query-translated")this.state[s].translatedQuery=y.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="related-queries")this.state[s].relatedQueries=y.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="text")for(p.push(y.message);p.length>0;)f.content+=p.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(R){console.error("Error parsing SSE event:",R),console.error("Raw message:",j)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var K=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 pt="1.3.20";var ft={name:"@oramacloud/client",version:pt,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 src","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:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.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/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.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",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function T(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 Q=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),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:ft.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};T(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var X=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(){T(this.params.endpoint)?.catch(e=>console.log(e))}};var Y=J(V(),1);var z=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ie);r?this.userId=r:(this.userId=(0,Y.createId)(),localStorage.setItem(ie,this.userId))}else this.userId=(0,Y.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await T(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,Y.createId)(),this.identity=void 0,this.userAlias=void 0}};function un(t){return t!==void 0&&t?.signal!==void 0}var P=class{id=(0,mt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+ut,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new z({endpoint:this.endpoint,apiKey:this.api_key}),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=Q.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new K(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,h=n?.fresh!==!0&&this.cache?.has(s),p=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();i=f-u;let m=await W(BigInt(f*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let g of o)g.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,c),o};if(h&&this.cache)i=0,o=this.cache.get(s),c=!0,this.addSearchResultsToCollector(o,i,e,c);else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),f(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):p();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let h=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let p=Date.now();o.elapsed=await W(BigInt(p*1e6-h*1e6)),s=p-h,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new _({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new X({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=un(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let c={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=pt,u.id=this.id,u.visitorId=this.profile.getUserId(),c.body=Object.entries(u).filter(([f,m])=>!!m).map(([f,m])=>`${f}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let h=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||h.searchParams.append("api-key",this.api_key),o)for(let[u,f]of Object.entries(o))f&&h.searchParams.append(u,f);let p=await fetch(h,c);if(!p.ok){let u=new Error;throw u.httpResponse=p,u}return await p.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};import fn,{useState as G,useEffect as gt,createContext as mn,useContext as gn}from"react";import{useState as E,useRef as dn,useEffect as hn,useCallback as ue}from"react";function pn(t){let[e,n]=E(t.initialMessages||[]),[r,s]=E(!1),[o,i]=E(null),[c,h]=E(!1),[p,u]=E(null),[f,m]=E(null),g=dn(null);hn(()=>{let y="oramaClient"in t?t.oramaClient:new P({api_key:t.apiKey,endpoint:t.endpoint});return g.current=new _({...t,initialMessages:t.initialMessages||[],inferenceType:t.inferenceType||"documentation",oramaClient:y,events:{onMessageChange:b=>{n(b)},onMessageLoading:b=>{s(b)},onAnswerAborted:b=>{h(b)},onSourceChange:b=>{u(b)},onRelatedQueries:b=>{m(b)}}}),()=>{g.current?.abortAnswer()}},[t]);let M=ue(async y=>{if(!g.current)try{h(!1),await g.current.ask(y)}catch(b){i(b)}},[]),j=ue(()=>{g?.current?.abortAnswer()},[]),R=ue(()=>{g?.current?.clearSession()},[]);return{messages:e,loading:r,aborted:c,abortAnswer:j,error:o,sources:p,relatedQueries:f,ask:M,clearSession:R}}var yt=mn({endpoint:"",apiKey:""}),ur=({children:t,endpoint:e,apiKey:n})=>fn.createElement(yt.Provider,{value:{endpoint:e,apiKey:n}},t);function dr(t){let{apiKey:e,endpoint:n}=gn(yt),[r,s]=G(!1),[o,i]=G(null),[c,h]=G(null),[p,u]=G(null);return gt(()=>{i(new P({api_key:e,endpoint:n})),s(!0)},[]),gt(()=>{o!==null&&o.search(t).then(h).catch(u)},[o,t]),{ready:r,results:c,error:p}}export{ur as OramaCloud,pn as useAnswerSession,dr as useSearch}; | ||
/*! Bundled license information: | ||
@@ -7,0 +7,0 @@ |
@@ -1,6 +0,6 @@ | ||
var Qe=Object.create;var oe=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var We=(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 Error('Dynamic require of "'+t+'" is not supported')});var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Je=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ze(e))!Xe.call(t,s)&&s!==n&&oe(t,s,{get:()=>e[s],enumerable:!(r=Ye(e,s))||r.enumerable});return t};var K=(t,e,n)=>(n=t!=null?Qe(Ge(t)):{},Je(e||!t||!t.__esModule?oe(n,"default",{value:t,enumerable:!0}):n,t));var fe=S(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.output=f.exists=f.hash=f.bytes=f.bool=f.number=void 0;function E(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}f.number=E;function ue(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}f.bool=ue;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}`)}f.bytes=Y;function he(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");E(t.outputLen),E(t.blockLen)}f.hash=he;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")}f.exists=de;function pe(t,e){Y(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=pe;var Ze={number:E,bool:ue,bytes:Y,hash:he,exists:de,output:pe};f.default=Ze});var ye=S(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.add=m.toBig=m.split=m.fromBig=void 0;var _=BigInt(2**32-1),z=BigInt(32);function G(t,e=!1){return e?{h:Number(t&_),l:Number(t>>z&_)}:{h:Number(t>>z&_)|0,l:Number(t&_)|0}}m.fromBig=G;function me(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=G(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}m.split=me;var et=(t,e)=>BigInt(t>>>0)<<z|BigInt(e>>>0);m.toBig=et;var tt=(t,e,n)=>t>>>n,nt=(t,e,n)=>t<<32-n|e>>>n,rt=(t,e,n)=>t>>>n|e<<32-n,st=(t,e,n)=>t<<32-n|e>>>n,ot=(t,e,n)=>t<<64-n|e>>>n-32,it=(t,e,n)=>t>>>n-32|e<<64-n,at=(t,e)=>e,ct=(t,e)=>t,lt=(t,e,n)=>t<<n|e>>>32-n,ut=(t,e,n)=>e<<n|t>>>32-n,ht=(t,e,n)=>e<<n-32|t>>>64-n,dt=(t,e,n)=>t<<n-32|e>>>64-n;function ge(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}m.add=ge;var pt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),ft=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,mt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),gt=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,yt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),bt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,wt={fromBig:G,split:me,toBig:m.toBig,shrSH:tt,shrSL:nt,rotrSH:rt,rotrSL:st,rotrBH:ot,rotrBL:it,rotr32H:at,rotr32L:ct,rotlSH:lt,rotlSL:ut,rotlBH:ht,rotlBL:dt,add:ge,add3L:pt,add3H:ft,add4L:mt,add4H:gt,add5H:bt,add5L:yt};m.default=wt});var be=S(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.crypto=void 0;var R=We("node:crypto");M.crypto=R&&typeof R=="object"&&"webcrypto"in R?R.webcrypto:void 0});var Se=S(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var X=be(),J=t=>t instanceof Uint8Array,St=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=St;var xt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=xt;var vt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=vt;var Ct=(t,e)=>t<<32-e|t>>>e;a.rotr=Ct;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var It=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function At(t){if(!J(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=It[t[n]];return e}a.bytesToHex=At;function Tt(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 s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Tt;var Ot=async()=>{};a.nextTick=Ot;async function kt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=kt;function we(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=we;function B(t){if(typeof t=="string"&&(t=we(t)),!J(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=B;function Pt(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!J(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=Pt;var W=class{clone(){return this._cloneInto()}};a.Hash=W;var Et=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function _t(t,e){if(e!==void 0&&(typeof e!="object"||!Et(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=_t;function Rt(t){let e=r=>t().update(B(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=Rt;function Mt(t){let e=(r,s)=>t(s).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=Mt;function Bt(t){let e=(r,s)=>t(s).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=Bt;function Lt(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")}a.randomBytes=Lt});var ke=S(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.shake256=u.shake128=u.keccak_512=u.keccak_384=u.keccak_256=u.keccak_224=u.sha3_512=u.sha3_384=u.sha3_256=u.sha3_224=u.Keccak=u.keccakP=void 0;var C=fe(),T=ye(),A=Se(),[Ce,Ie,Ae]=[[],[],[]],Nt=BigInt(0),I=BigInt(1),Dt=BigInt(2),Ut=BigInt(7),jt=BigInt(256),Ht=BigInt(113);for(let t=0,e=I,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ce.push(2*(5*r+n)),Ie.push((t+1)*(t+2)/2%64);let s=Nt;for(let o=0;o<7;o++)e=(e<<I^(e>>Ut)*Ht)%jt,e&Dt&&(s^=I<<(I<<BigInt(o))-I);Ae.push(s)}var[$t,qt]=T.default.split(Ae,!0),xe=(t,e,n)=>n>32?T.default.rotlBH(t,e,n):T.default.rotlSH(t,e,n),ve=(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 i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,h=(i+2)%10,d=n[h],l=n[h+1],p=xe(d,l,1)^n[c],g=ve(d,l,1)^n[c+1];for(let v=0;v<50;v+=10)t[i+v]^=p,t[i+v+1]^=g}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Ie[i],h=xe(s,o,c),d=ve(s,o,c),l=Ce[i];s=t[l],o=t[l+1],t[l]=h,t[l+1]=d}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=$t[r],t[1]^=qt[r]}n.fill(0)}u.keccakP=Te;var O=class t extends A.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,C.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){C.default.exists(this);let{blockLen:n,state:r}=this;e=(0,A.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){C.default.exists(this,!1),C.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return C.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(C.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:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};u.Keccak=O;var b=(t,e,n)=>(0,A.wrapConstructor)(()=>new O(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 Oe=(t,e,n)=>(0,A.wrapXOFConstructorWithOpts)((r={})=>new O(e,t,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=Oe(31,168,128/8);u.shake256=Oe(31,136,256/8)});var Ne=S((mn,w)=>{"use strict";var{sha3_512:Ft}=ke(),Ee=24,k=32,Z=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function _e(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Re=(t="")=>_e(Ft(t)).toString(36).slice(1),Pe=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),Vt=t=>Pe[Math.floor(t()*Pe.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+Z(k,e):Z(k,e);return Re(r).substring(0,k)},Be=t=>()=>t++,Kt=476782367,Le=({random:t=Math.random,counter:e=Be(Math.floor(t()*Kt)),length:n=Ee,fingerprint:r=Me({random:t})}={})=>function(){let o=Vt(t),i=Date.now().toString(36),c=e().toString(36),h=Z(n,t),d=`${i+h+c+r}`;return`${o+Re(d).substring(1,n)}`},Qt=Le(),Yt=(t,{minLength:e=2,maxLength:n=k}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:Ee,bigLength:k});w.exports.init=Le;w.exports.createId=Qt;w.exports.bufToBigInt=_e;w.exports.createCounter=Be;w.exports.createFingerprint=Me;w.exports.isCuid=Yt});var L=S((gn,P)=>{"use strict";var{createId:zt,init:Gt,getConstants:Xt,isCuid:Wt}=Ne();P.exports.createId=zt;P.exports.init=Gt;P.exports.getConstants=Xt;P.exports.isCuid=Wt});var sn=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 Q(t){return{raw:Number(t),formatted:await le(t)}}var Fe=K(L(),1);var ne=K(L(),1);var De="https://answer.api.orama.com";var Ue="https://cloud.orama.run/v1/indexes",ee="orama_user_id";function je(t){let[e,...n]=t.split(` | ||
var ft=Object.create;var ae=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var yt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var St=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var wt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gt(e))!bt.call(t,s)&&s!==n&&ae(t,s,{get:()=>e[s],enumerable:!(r=mt(e,s))||r.enumerable});return t};var X=(t,e,n)=>(n=t!=null?ft(yt(t)):{},wt(e||!t||!t.__esModule?ae(n,"default",{value:t,enumerable:!0}):n,t));var G=I(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.isBytes=pe;y.number=R;y.bool=he;y.bytes=z;y.hash=fe;y.exists=me;y.output=ge;function R(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function he(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function pe(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function z(t,...e){if(!pe(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function fe(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");R(t.outputLen),R(t.blockLen)}function me(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")}function ge(t,e){z(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var xt={number:R,bool:he,bytes:z,hash:fe,exists:me,output:ge};y.default=xt});var Ue=I(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=W;a.split=ye;a.add=Ee;var L=BigInt(2**32-1),J=BigInt(32);function W(t,e=!1){return e?{h:Number(t&L),l:Number(t>>J&L)}:{h:Number(t>>J&L)|0,l:Number(t&L)|0}}function ye(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=W(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var be=(t,e)=>BigInt(t>>>0)<<J|BigInt(e>>>0);a.toBig=be;var Se=(t,e,n)=>t>>>n;a.shrSH=Se;var we=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=we;var xe=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=xe;var Ce=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Ce;var ve=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=ve;var Ie=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=Ie;var Ae=(t,e)=>e;a.rotr32H=Ae;var Te=(t,e)=>t;a.rotr32L=Te;var Oe=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Oe;var _e=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=_e;var ke=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=ke;var Pe=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Pe;function Ee(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Me=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Me;var Re=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=Re;var Le=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Le;var Be=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=Be;var Ne=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=Ne;var De=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=De;var Ct={fromBig:W,split:ye,toBig:be,shrSH:Se,shrSL:we,rotrSH:xe,rotrSL:Ce,rotrBH:ve,rotrBL:Ie,rotr32H:Ae,rotr32L:Te,rotlSH:Oe,rotlSL:_e,rotlBH:ke,rotlBL:Pe,add:Ee,add3L:Me,add3H:Re,add4L:Le,add4H:Be,add5H:De,add5L:Ne};a.default=Ct});var je=I(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.crypto=void 0;var x=St("node:crypto");B.crypto=x&&typeof x=="object"&&"webcrypto"in x?x.webcrypto:x&&typeof x=="object"&&"randomBytes"in x?x:void 0});var qe=I(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.Hash=l.nextTick=l.byteSwapIfBE=l.byteSwap=l.isLE=l.rotl=l.rotr=l.createView=l.u32=l.u8=void 0;l.isBytes=vt;l.byteSwap32=Pt;l.bytesToHex=Mt;l.hexToBytes=Rt;l.asyncLoop=Bt;l.utf8ToBytes=$e;l.toBytes=N;l.concatBytes=Nt;l.checkOpts=Ut;l.wrapConstructor=jt;l.wrapConstructorWithOpts=Ht;l.wrapXOFConstructorWithOpts=$t;l.randomBytes=qt;var T=je(),ee=G();function vt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var It=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);l.u8=It;var At=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));l.u32=At;var Tt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);l.createView=Tt;var Ot=(t,e)=>t<<32-e|t>>>e;l.rotr=Ot;var _t=(t,e)=>t<<e|t>>>32-e>>>0;l.rotl=_t;l.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var kt=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;l.byteSwap=kt;l.byteSwapIfBE=l.isLE?t=>t:t=>(0,l.byteSwap)(t);function Pt(t){for(let e=0;e<t.length;e++)t[e]=(0,l.byteSwap)(t[e])}var Et=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Mt(t){(0,ee.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Et[t[n]];return e}var b={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function He(t){if(t>=b._0&&t<=b._9)return t-b._0;if(t>=b._A&&t<=b._F)return t-(b._A-10);if(t>=b._a&&t<=b._f)return t-(b._a-10)}function Rt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=He(t.charCodeAt(o)),c=He(t.charCodeAt(o+1));if(i===void 0||c===void 0){let h=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+h+'" at index '+o)}r[s]=i*16+c}return r}var Lt=async()=>{};l.nextTick=Lt;async function Bt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,l.nextTick)(),r+=o)}}function $e(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function N(t){return typeof t=="string"&&(t=$e(t)),(0,ee.bytes)(t),t}function Nt(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,ee.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var Z=class{clone(){return this._cloneInto()}};l.Hash=Z;var Dt={}.toString;function Ut(t,e){if(e!==void 0&&Dt.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function jt(t){let e=r=>t().update(N(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Ht(t){let e=(r,s)=>t(s).update(N(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function $t(t){let e=(r,s)=>t(s).update(N(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function qt(t=32){if(T.crypto&&typeof T.crypto.getRandomValues=="function")return T.crypto.getRandomValues(new Uint8Array(t));if(T.crypto&&typeof T.crypto.randomBytes=="function")return T.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var Ge=I(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=Ye;var O=G(),k=Ue(),S=qe(),Ke=[],Qe=[],Xe=[],Ft=BigInt(0),_=BigInt(1),Vt=BigInt(2),Kt=BigInt(7),Qt=BigInt(256),Xt=BigInt(113);for(let t=0,e=_,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ke.push(2*(5*r+n)),Qe.push((t+1)*(t+2)/2%64);let s=Ft;for(let o=0;o<7;o++)e=(e<<_^(e>>Kt)*Xt)%Qt,e&Vt&&(s^=_<<(_<<BigInt(o))-_);Xe.push(s)}var[Yt,zt]=(0,k.split)(Xe,!0),Fe=(t,e,n)=>n>32?(0,k.rotlBH)(t,e,n):(0,k.rotlSH)(t,e,n),Ve=(t,e,n)=>n>32?(0,k.rotlBL)(t,e,n):(0,k.rotlSL)(t,e,n);function Ye(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,h=(i+2)%10,p=n[h],u=n[h+1],f=Fe(p,u,1)^n[c],m=Ve(p,u,1)^n[c+1];for(let w=0;w<50;w+=10)t[i+w]^=f,t[i+w+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Qe[i],h=Fe(s,o,c),p=Ve(s,o,c),u=Ke[i];s=t[u],o=t[u+1],t[u]=h,t[u+1]=p}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=Yt[r],t[1]^=zt[r]}n.fill(0)}var P=class t extends S.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,O.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,S.u32)(this.state)}keccak(){S.isLE||(0,S.byteSwap32)(this.state32),Ye(this.state32,this.rounds),S.isLE||(0,S.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,O.exists)(this);let{blockLen:n,state:r}=this;e=(0,S.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,O.exists)(this,!1),(0,O.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,O.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,O.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:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=P;var C=(t,e,n)=>(0,S.wrapConstructor)(()=>new P(e,t,n));d.sha3_224=C(6,144,224/8);d.sha3_256=C(6,136,256/8);d.sha3_384=C(6,104,384/8);d.sha3_512=C(6,72,512/8);d.keccak_224=C(1,144,224/8);d.keccak_256=C(1,136,256/8);d.keccak_384=C(1,104,384/8);d.keccak_512=C(1,72,512/8);var ze=(t,e,n)=>(0,S.wrapXOFConstructorWithOpts)((r={})=>new P(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=ze(31,168,128/8);d.shake256=ze(31,136,256/8)});var st=I((Cn,v)=>{"use strict";var{sha3_512:Gt}=Ge(),We=24,E=32,te=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Ze(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var et=(t="")=>Ze(Gt(t)).toString(36).slice(1),Je=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),Jt=t=>Je[Math.floor(t()*Je.length)],tt=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+te(E,e):te(E,e);return et(r).substring(0,E)},nt=t=>()=>t++,Wt=476782367,rt=({random:t=Math.random,counter:e=nt(Math.floor(t()*Wt)),length:n=We,fingerprint:r=tt({random:t})}={})=>function(){let o=Jt(t),i=Date.now().toString(36),c=e().toString(36),h=te(n,t),p=`${i+h+c+r}`;return`${o+et(p).substring(1,n)}`},Zt=rt(),en=(t,{minLength:e=2,maxLength:n=E}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};v.exports.getConstants=()=>({defaultLength:We,bigLength:E});v.exports.init=rt;v.exports.createId=Zt;v.exports.bufToBigInt=Ze;v.exports.createCounter=nt;v.exports.createFingerprint=tt;v.exports.isCuid=en});var D=I((vn,M)=>{"use strict";var{createId:tn,init:nn,getConstants:rn,isCuid:sn}=st();M.exports.createId=tn;M.exports.init=nn;M.exports.getConstants=rn;M.exports.isCuid=sn});var hn=Date.now().toString().slice(5);var ce=BigInt(1e3),le=BigInt(1e6),ue=BigInt(1e9);async function de(t){return typeof t=="number"&&(t=BigInt(t)),t<ce?`${t}ns`:t<le?`${t/ce}\u03BCs`:t<ue?`${t/le}ms`:`${t/ue}s`}async function Y(t){return{raw:Number(t),formatted:await de(t)}}var dt=X(D(),1);var se=X(D(),1);var ot="https://answer.api.orama.com";var it="/v1/indexes",ne="orama_user_id";function at(t){let[e,...n]=t.split(` | ||
`),r=n.join(` | ||
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function te(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var N=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||De;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,ne.createId)(),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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ne.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",te(this.userContext)),e.userData&&o.append("userData",te(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let h=new TextDecoder,d=[],l="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:g,done:v}=await r.read();if(v)break;l+=h.decode(g,{stream:!0});let F;for(;(F=l.indexOf(` | ||
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function re(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var U=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||ot;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,se.createId)(),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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,se.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",re(this.userContext)),e.userData&&o.append("userData",re(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let h=new TextDecoder,p=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:m,done:w}=await r.read();if(w)break;u+=h.decode(m,{stream:!0});let K;for(;(K=u.indexOf(` | ||
`))!==-1;){let se=l.slice(0,F);l=l.slice(F+2);try{let V=je(se),y=JSON.parse(V.data);if(y.type==="sources")this.state[s].sources=y.message,this.events?.onSourceChange&&this.events.onSourceChange(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="query-translated")this.state[s].translatedQuery=y.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="related-queries")this.state[s].relatedQueries=y.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="text")for(d.push(y.message);d.length>0;)p.content+=d.shift(),this.state[s].response=p.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield p.content}catch(V){console.error("Error parsing SSE event:",V),console.error("Raw message:",se)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var D=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 $e="1.3.19";var qe={name:"@oramacloud/client",version:$e,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:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.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/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.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",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function x(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 U=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:qe.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};x(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var j=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){x(this.params.endpoint)?.catch(e=>console.log(e))}};var H=K(L(),1);var $=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ee);r?this.userId=r:(this.userId=(0,H.createId)(),localStorage.setItem(ee,this.userId))}else this.userId=(0,H.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await x(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,H.createId)(),this.identity=void 0,this.userAlias=void 0}};function Jt(t){return t!==void 0&&t?.signal!==void 0}var q=class{id=(0,Fe.createId)();api_key;endpoint;multiIndexSearch;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e?(this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes,this.endpoint=e.endpoint||Ue,this.multiIndexSearch=!0):(this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1),this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new $({endpoint:this.endpoint,apiKey:this.api_key}),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=U.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new D(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,h=n?.fresh!==!0&&this.cache?.has(s),d=async()=>{try{let l=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:!0},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();o.elapsed=await Q(BigInt(p*1e6-l*1e6)),i=p-l,this.cache?.set(s,o)}catch(l){if(l.name!=="AbortError")throw console.error("Search request failed",l),l}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(h&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((l,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await d(),l(o)}catch(g){g.name!=="AbortError"&&(console.error("Search request failed",g),p(g))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):d();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let h=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let d=Date.now();o.elapsed=await Q(BigInt(d*1e6-h*1e6)),s=d-h,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new N({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new j({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){let i=Jt(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let c={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let l=r;l.version=$e,l.id=this.id,l.visitorId=this.profile.getUserId(),c.body=Object.entries(l).filter(([p,g])=>!!g).map(([p,g])=>`${p}=${encodeURIComponent(JSON.stringify(g))}`).join("&")}let h=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||h.searchParams.append("api-key",this.api_key),o)for(let[l,p]of Object.entries(o))p&&h.searchParams.append(l,p);let d=await fetch(h,c);if(!d.ok){let l=new Error;throw l.httpResponse=d,l}return await d.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};import{onMounted as Zt,ref as Ve,shallowRef as Ke,toValue as en,watchEffect as tn}from"vue";import{omit as nn}from"lodash";function zn(t){let e=Ve(!1),n=Ke(null),r=Ve(null),s=Ke();return Zt(()=>{if(!t.cloudConfig)throw new Error("No config was passed");e.value=!0,s.value=new q(t.cloudConfig)}),tn(()=>{let o=Object.keys(nn(t,"cloudConfig")).reduce((i,c)=>{let h=c;return i[h]=en(t[h]),i},{});s.value&&s.value.search(o).then(i=>n.value=i).catch(i=>r.value=i)}),{ready:e,results:n,error:r}}export{zn as useSearch}; | ||
`))!==-1;){let ie=u.slice(0,K);u=u.slice(K+2);try{let Q=at(ie),g=JSON.parse(Q.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(p.push(g.message);p.length>0;)f.content+=p.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(Q){console.error("Error parsing SSE event:",Q),console.error("Raw message:",ie)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var j=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 lt="1.3.20";var ut={name:"@oramacloud/client",version:lt,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 src","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:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.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/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.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",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function A(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 H=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),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:ut.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};A(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){A(this.params.endpoint)?.catch(e=>console.log(e))}};var q=X(D(),1);var F=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ne);r?this.userId=r:(this.userId=(0,q.createId)(),localStorage.setItem(ne,this.userId))}else this.userId=(0,q.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await A(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,q.createId)(),this.identity=void 0,this.userAlias=void 0}};function on(t){return t!==void 0&&t?.signal!==void 0}var V=class{id=(0,dt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+it,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new F({endpoint:this.endpoint,apiKey:this.api_key}),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=H.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new j(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,h=n?.fresh!==!0&&this.cache?.has(s),p=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();i=f-u;let m=await Y(BigInt(f*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let w of o)w.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,c),o};if(h&&this.cache)i=0,o=this.cache.get(s),c=!0,this.addSearchResultsToCollector(o,i,e,c);else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),f(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):p();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let h=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let p=Date.now();o.elapsed=await Y(BigInt(p*1e6-h*1e6)),s=p-h,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new U({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=on(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let c={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=lt,u.id=this.id,u.visitorId=this.profile.getUserId(),c.body=Object.entries(u).filter(([f,m])=>!!m).map(([f,m])=>`${f}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let h=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||h.searchParams.append("api-key",this.api_key),o)for(let[u,f]of Object.entries(o))f&&h.searchParams.append(u,f);let p=await fetch(h,c);if(!p.ok){let u=new Error;throw u.httpResponse=p,u}return await p.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};import{onMounted as an,ref as ht,shallowRef as pt,toValue as cn,watchEffect as ln}from"vue";import{omit as un}from"lodash";function tr(t){let e=ht(!1),n=pt(null),r=ht(null),s=pt();return an(()=>{if(!t.cloudConfig)throw new Error("No config was passed");e.value=!0,s.value=new V(t.cloudConfig)}),ln(()=>{let o=Object.keys(un(t,"cloudConfig")).reduce((i,c)=>{let h=c;return i[h]=cn(t[h]),i},{});s.value&&s.value.search(o).then(i=>n.value=i).catch(i=>r.value=i)}),{ready:e,results:n,error:r}}export{tr as useSearch}; | ||
/*! Bundled license information: | ||
@@ -7,0 +7,0 @@ |
{ | ||
"name": "@oramacloud/client", | ||
"version": "1.3.19", | ||
"version": "1.3.20", | ||
"description": "Orama SDK for Node.js, Deno, and Browsers", | ||
@@ -29,2 +29,16 @@ "type": "module", | ||
}, | ||
"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 src", | ||
"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": "glob -c \"node --import tsx --no-warnings --test\" \"./tests/**/*.test.ts\"", | ||
"serve:example": "esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example", | ||
"prepare": "husky install" | ||
}, | ||
"keywords": [ | ||
@@ -76,15 +90,3 @@ "orama", | ||
}, | ||
"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": "glob -c \"node --import tsx --no-warnings --test\" \"./tests/**/*.test.ts\"", | ||
"serve:example": "esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example" | ||
} | ||
} | ||
"packageManager": "pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c" | ||
} |
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
1202992
1467