@oramacloud/client
Advanced tools
Comparing version 1.1.2 to 1.1.3
@@ -1,4 +0,59 @@ | ||
import { SearchParams, AnyOrama, Nullable, Results, AnyDocument } from '@orama/orama'; | ||
import { SearchParams, AnyOrama, AnyDocument, Results, Nullable } from '@orama/orama'; | ||
import React from 'react'; | ||
interface IOramaClient { | ||
api_key: string; | ||
endpoint: string; | ||
telemetry?: Partial<TelemetryConfig> | false; | ||
cache?: Partial<CacheConfig> | false; | ||
} | ||
interface TelemetryConfig { | ||
flushInterval: number; | ||
flushSize: number; | ||
} | ||
interface CacheConfig { | ||
} | ||
interface HeartBeatConfig { | ||
frequency: number; | ||
} | ||
type Message = { | ||
role: 'user' | 'assistant'; | ||
content: string; | ||
}; | ||
type InferenceType = 'documentation'; | ||
type AnswerParams = { | ||
initialMessages: Message[]; | ||
inferenceType: InferenceType; | ||
oramaClient: OramaClient; | ||
events?: { | ||
onMessageChange?: (messages: Message[]) => void; | ||
onMessageLoading?: (receivingMessage: boolean) => void; | ||
onAnswerAborted?: (aborted: true) => void; | ||
onSourceChange?: <T = AnyDocument>(sources: Results<T>) => void; | ||
}; | ||
}; | ||
declare class AnswerSession { | ||
private messages; | ||
private inferenceType; | ||
private oramaClient; | ||
private endpoint; | ||
private abortController?; | ||
private events; | ||
constructor(params: AnswerParams); | ||
askStream(params: SearchParams<AnyOrama>): Promise<AsyncGenerator<string>>; | ||
ask(params: SearchParams<AnyOrama>): Promise<string>; | ||
getMessages(): Message[]; | ||
clearSession(): void; | ||
private addNewEmptyAssistantMessage; | ||
abortAnswer(): void; | ||
private runInference; | ||
private fetchAnswer; | ||
} | ||
interface SearchConfig { | ||
abortController?: AbortController; | ||
fresh?: boolean; | ||
debounce?: number; | ||
} | ||
type SearchMode = 'fulltext' | 'vector' | 'hybrid'; | ||
@@ -10,3 +65,52 @@ type AdditionalSearchParams = { | ||
type ClientSearchParams = SearchParams<AnyOrama> & AdditionalSearchParams; | ||
type AnswerSessionParams = { | ||
inferenceType?: InferenceType; | ||
initialMessages?: Message[]; | ||
events?: { | ||
onMessageChange?: (messages: Message[]) => void; | ||
onMessageLoading?: (receivingMessage: boolean) => void; | ||
onAnswerAborted?: (aborted: true) => void; | ||
onSourceChange?: <T = AnyDocument>(sources: Results<T>) => void; | ||
}; | ||
}; | ||
declare class OramaClient { | ||
private readonly id; | ||
private readonly api_key; | ||
private readonly endpoint; | ||
private readonly collector?; | ||
private readonly cache?; | ||
private abortController?; | ||
private searchDebounceTimer?; | ||
private searchRequestCounter; | ||
private heartbeat?; | ||
private initPromise?; | ||
constructor(params: IOramaClient); | ||
search(query: ClientSearchParams, config?: SearchConfig): Promise<Nullable<Results<AnyDocument>>>; | ||
vectorSearch(query: ClientSearchParams, config?: SearchConfig): Promise<Pick<Results<AnyDocument>, 'hits' | 'elapsed'>>; | ||
createAnswerSession(params?: AnswerSessionParams): AnswerSession; | ||
startHeartBeat(config: HeartBeatConfig): void; | ||
stopHeartBeat(): void; | ||
getPop(): Promise<string>; | ||
private init; | ||
private fetch; | ||
} | ||
type AnswerSessionHookClientParams = { | ||
oramaClient: OramaClient; | ||
} | { | ||
apiKey: string; | ||
endpoint: string; | ||
}; | ||
type AnswerSessionHookParams = AnswerSessionParams & AnswerSessionHookClientParams; | ||
declare function useAnswerSession<Document = AnyDocument>(params: AnswerSessionHookParams): { | ||
messages: Message[]; | ||
loading: boolean; | ||
aborted: boolean; | ||
abortAnswer: () => void; | ||
error: Nullable<Error>; | ||
sources: Nullable<Results<Document>>; | ||
ask: (searchParams: SearchParams<AnyOrama>) => Promise<void>; | ||
clearSession: () => void; | ||
}; | ||
interface UseSearch { | ||
@@ -24,2 +128,2 @@ ready: boolean; | ||
export { OramaCloud, useSearch }; | ||
export { OramaCloud, useAnswerSession, useSearch }; |
@@ -1,2 +0,2 @@ | ||
import{formatElapsedTime as x}from"@orama/orama/components";import{createId as R}from"@paralleldrive/cuid2";var p=class{messages;inferenceType;oramaClient;endpoint;abortController;events;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${this.oramaClient.endpoint}/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events}async askStream(e){this.messages.push({role:"user",content:e.term??""});let t=await this.runInference(e);return this.events?.onSourceChange&&this.events.onSourceChange(t),this.fetchAnswer(e.term??"",t?.hits??[])}async ask(e){let t=await this.askStream(e),r="";for await(let n of t)r=n;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}runInference(e){return this.oramaClient.search(e)}async*fetchAnswer(e,t){this.abortController=new AbortController;let{signal:r}=this.abortController,n={type:this.inferenceType,messages:this.messages,context:t,query:e},s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:r});if(!s.ok||s.body==null)throw s.statusText;let a=s.body.getReader(),i=new TextDecoder;this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let h=this.messages.at(-1);try{for(;;){let{value:o,done:l}=await a.read();if(l)break;let u=i.decode(o,{stream:!0});h.content+=u,this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield h.content}}catch(o){if(o.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw o}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var m=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var w="1.1.2";var A={name:"@oramacloud/client",version:w,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function d(c,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(c,e);return}fetch(c,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var f=class c{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new c(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:A.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};d(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var g=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){d(this.params.endpoint)?.catch(e=>console.log(e))}};var y=class{id=R();api_key;endpoint;collector;cache;abortController;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=f.create(t)}if(e.cache!==!1){let t={};this.cache=new m(t)}this.init()}async search(e,t){await this.initPromise;let r=++this.searchRequestCounter,n=`search-${JSON.stringify(e)}`,s,a,i=!1,h=t?.fresh!==!0&&this.cache?.has(n),o=async()=>{try{let l=Date.now();s=await this.fetch("search","POST",{q:e},this.abortController);let u=Date.now();s.elapsed=await x(BigInt(u*1e6-l*1e6)),a=u-l,this.cache?.set(n,s)}catch(l){if(l.name!=="AbortError")throw console.error("Search request failed",l),l}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:a,query:e,cached:i,searchedAt:new Date}),s};if(h&&this.cache)a=0,s=this.cache.get(n),i=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:a,query:e,cached:i,searchedAt:new Date});else return t?.debounce?new Promise((l,u)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await o(),l(s)}catch(v){v.name!=="AbortError"&&(console.error("Search request failed",v),u(v))}},t?.debounce||300)}):o();return r===this.searchRequestCounter?s:null}async vectorSearch(e,t){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,n,s,a=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)n=0,s=this.cache.get(r),a=!0;else{let h=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let o=Date.now();s.elapsed=await x(BigInt(o*1e6-h*1e6)),n=o-h,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits?.length??0,roundTripTime:n,query:e,cached:a,searchedAt:new Date}),s}createAnswerSession(e){return new p({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new g({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,r,n){if(n?.signal.aborted===!0)throw new Error("Request aborted");let s={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:n?.signal};if(t==="POST"&&r!==void 0){let i=r;i.version=w,i.id=this.id,s.body=Object.entries(i).map(([h,o])=>`${h}=${encodeURIComponent(JSON.stringify(o))}`).join("&")}let a=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!a.ok){let i=new Error;throw i.httpResponse=a,i}return await a.json()}};import M,{useState as C,useEffect as T,createContext as P,useContext as D}from"react";var O=P({endpoint:"",apiKey:""}),W=({children:c,endpoint:e,apiKey:t})=>M.createElement(O.Provider,{value:{endpoint:e,apiKey:t}},c);function ee(c){let{apiKey:e,endpoint:t}=D(O),[r,n]=C(!1),[s,a]=C(null),[i,h]=C(null),[o,l]=C(null);return T(()=>{a(new y({api_key:e,endpoint:t})),n(!0)},[]),T(()=>{s!==null&&s.search(c).then(h).catch(l)},[s,c]),{ready:r,results:i,error:o}}export{W as OramaCloud,ee as useSearch}; | ||
import{formatElapsedTime as O}from"@orama/orama/components";import{createId as I}from"@paralleldrive/cuid2";var p=class{messages;inferenceType;oramaClient;endpoint;abortController;events;constructor(e){this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${this.oramaClient.endpoint}/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events}async askStream(e){this.messages.push({role:"user",content:e.term??""});let t=await this.runInference(e);return this.events?.onSourceChange&&this.events.onSourceChange(t),this.fetchAnswer(e.term??"",t?.hits??[])}async ask(e){let t=await this.askStream(e),n="";for await(let a of t)n=a;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),n}getMessages(){return this.messages}clearSession(){this.messages=[]}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}abortAnswer(){this.abortController&&(this.abortController.abort(),this.abortController=void 0,this.messages.pop())}runInference(e){return this.oramaClient.search(e)}async*fetchAnswer(e,t){this.abortController=new AbortController;let{signal:n}=this.abortController,a={type:this.inferenceType,messages:this.messages,context:t,query:e},s=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:n});if(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let l=this.messages.at(-1);try{for(;;){let{value:c,done:u}=await o.read();if(u)break;let h=i.decode(c,{stream:!0});l.content+=h,this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield l.content}}catch(c){if(c.name==="AbortError")this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw c}this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}};var C=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var P="1.1.2";var M={name:"@oramacloud/client",version:P,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function g(r,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(r,e);return}fetch(r,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var b=class r{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new r(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:M.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};g(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(n=>console.log(n))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var v=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){g(this.params.endpoint)?.catch(e=>console.log(e))}};var m=class{id=I();api_key;endpoint;collector;cache;abortController;searchDebounceTimer;searchRequestCounter=0;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=b.create(t)}if(e.cache!==!1){let t={};this.cache=new C(t)}this.init()}async search(e,t){await this.initPromise;let n=++this.searchRequestCounter,a=`search-${JSON.stringify(e)}`,s,o,i=!1,l=t?.fresh!==!0&&this.cache?.has(a),c=async()=>{try{let u=Date.now();s=await this.fetch("search","POST",{q:e},this.abortController);let h=Date.now();s.elapsed=await O(BigInt(h*1e6-u*1e6)),o=h-u,this.cache?.set(a,s)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:o,query:e,cached:i,searchedAt:new Date}),s};if(l&&this.cache)o=0,s=this.cache.get(a),i=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:o,query:e,cached:i,searchedAt:new Date});else return t?.debounce?new Promise((u,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await c(),u(s)}catch(f){f.name!=="AbortError"&&(console.error("Search request failed",f),h(f))}},t?.debounce||300)}):c();return n===this.searchRequestCounter?s:null}async vectorSearch(e,t){await this.initPromise;let n=`vectorSearch-${JSON.stringify(e)}`,a,s,o=!1;if((t?.fresh!==!0&&this.cache?.has(n))===!0&&this.cache!=null)a=0,s=this.cache.get(n),o=!0;else{let l=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let c=Date.now();s.elapsed=await O(BigInt(c*1e6-l*1e6)),a=c-l,this.cache?.set(n,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits?.length??0,roundTripTime:a,query:e,cached:o,searchedAt:new Date}),s}createAnswerSession(e){return new p({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new v({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,n,a){if(a?.signal.aborted===!0)throw new Error("Request aborted");let s={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:a?.signal};if(t==="POST"&&n!==void 0){let i=n;i.version=P,i.id=this.id,s.body=Object.entries(i).map(([l,c])=>`${l}=${encodeURIComponent(JSON.stringify(c))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!o.ok){let i=new Error;throw i.httpResponse=o,i}return await o.json()}};import _,{useState as S,useEffect as R,createContext as H,useContext as L}from"react";import{useState as y,useRef as N,useEffect as j,useCallback as x}from"react";function B(r){let[e,t]=y(r.initialMessages||[]),[n,a]=y(!1),[s,o]=y(null),[i,l]=y(!1),[c,u]=y(null),h=N(null);j(()=>{let w="oramaClient"in r?r.oramaClient:new m({api_key:r.apiKey,endpoint:r.endpoint});return h.current=new p({...r,initialMessages:r.initialMessages||[],inferenceType:r.inferenceType||"documentation",oramaClient:w,events:{onMessageChange:d=>{t(d)},onMessageLoading:d=>{a(d)},onAnswerAborted:d=>{l(d)},onSourceChange:d=>{u(d)}}}),()=>{h.current?.abortAnswer()}},[r]);let f=x(async w=>{if(!h.current)try{l(!1),await h.current.ask(w)}catch(d){o(d)}},[]),E=x(()=>{h?.current?.abortAnswer()},[]),k=x(()=>{h?.current?.clearSession()},[]);return{messages:e,loading:n,aborted:i,abortAnswer:E,error:s,sources:c,ask:f,clearSession:k}}var D=H({endpoint:"",apiKey:""}),de=({children:r,endpoint:e,apiKey:t})=>_.createElement(D.Provider,{value:{endpoint:e,apiKey:t}},r);function pe(r){let{apiKey:e,endpoint:t}=L(D),[n,a]=S(!1),[s,o]=S(null),[i,l]=S(null),[c,u]=S(null);return R(()=>{o(new m({api_key:e,endpoint:t})),a(!0)},[]),R(()=>{s!==null&&s.search(r).then(l).catch(u)},[s,r]),{ready:n,results:i,error:c}}export{de as OramaCloud,B as useAnswerSession,pe as useSearch}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@oramacloud/client", | ||
"version": "1.1.2", | ||
"version": "1.1.3", | ||
"description": "Orama SDK for Node.js, Deno, and Browsers", | ||
@@ -5,0 +5,0 @@ "type": "module", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
445918
656
33