UNPKG

@kontext.dev/kontext-sdk

Version:

Unified SDK for AI-powered context and personalization

3 lines 6.97 kB
'use strict';var p=class extends Error{constructor(t,r,i){super(t);this.code=r;this.statusCode=i;this.name="KontextError";}};var u=class{constructor(e,t){this.apiUrl=e;this.apiKey=t;}async handleResponse(e,t){if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`${t} (${e.status}): ${r}`)}return await e.json()}async upload(e){let t=new FormData;t.append("file",e.file);let r=await fetch(`${this.apiUrl}/vault/files`,{method:"POST",headers:{"x-api-key":this.apiKey,"x-as-user":e.userId},body:t}),i=await this.handleResponse(r,"Upload failed");return {fileId:String(i?.fileId||""),status:i?.status??"pending"}}async getFileStatus(e){let t=await fetch(`${this.apiUrl}/vault/files/${e.fileId}/status`,{headers:{"x-api-key":this.apiKey}});return this.handleResponse(t,"getFileStatus failed")}async query(e){let t={userId:e.userId,query:e.query};typeof e.topK=="number"&&(t.topK=e.topK),e.fileId&&(t.fileId=e.fileId),e.includeAnswer&&(t.includeAnswer=true);let r=await fetch(`${this.apiUrl}/vault/query`,{method:"POST",headers:{"x-api-key":this.apiKey,"content-type":"application/json"},body:JSON.stringify(t)}),i=await this.handleResponse(r,"query failed"),l=s=>({id:String(s?.id??s?.row_id??s?.datasetItemId??s?.documentId??""),score:typeof s?.score=="number"?s.score:typeof s?.distance=="number"?s.distance:null,attributes:(s?.attributes&&typeof s.attributes=="object"?s.attributes:s)??{}}),y=s=>({id:String(s?.id??""),score:typeof s?.score=="number"?s.score:null,attributes:{doc_type:s?.doc_type,subject:s?.subject,timestamp:s?.timestamp,snippet:s?.snippet}}),o=Array.isArray(i?.hits)?i.hits:void 0,n=Array.isArray(i?.rows)?i.rows:void 0,d=Array.isArray(i?.sources)?i.sources:void 0,x=o?o.map(l):n?n.map(l):d?d.map(y):[],h;if(i?.answer){let s=i.answer,g=null;typeof s?.text=="string"&&(g=s.text),h={text:g,sources:Array.isArray(s?.sources)?s.sources.map(a=>({id:String(a?.id??""),score:typeof a?.score=="number"?a.score:0,doc_type:String(a?.doc_type??""),subject:a?.subject,timestamp:a?.timestamp,snippet:a?.snippet})):(d||[]).map(a=>({id:String(a?.id??""),score:typeof a?.score=="number"?a.score:0,doc_type:String(a?.doc_type??""),subject:a?.subject,timestamp:a?.timestamp,snippet:a?.snippet}))};}return {hits:x,...h?{answer:h}:{}}}async listFiles(e){let t=await fetch(`${this.apiUrl}/vault/users/${e.userId}/files`,{headers:{"x-api-key":this.apiKey}});return this.handleResponse(t,"listFiles failed")}async deleteFile(e){let t=await fetch(`${this.apiUrl}/vault/files/${e.fileId}`,{method:"DELETE",headers:{"x-api-key":this.apiKey}});return this.handleResponse(t,"deleteFile failed")}async clearVault(e){let t=await fetch(`${this.apiUrl}/vault/users/${e.userId}`,{method:"DELETE",headers:{"x-api-key":this.apiKey}});return this.handleResponse(t,"Vault namespace clear failed")}};var c=class{constructor(e,t){this.apiUrl=e;this.apiKey=t;}async getProfile(e){if(!e)throw this.createError("GetProfileOptions is required. Please provide an object with at least a userId field.","INVALID_OPTIONS",400);let{userId:t,task:r,maxTokens:i,privacyLevel:l,userQuery:y}=e;if(!t||typeof t!="string")throw this.createError("Valid userId is required. Please provide a non-empty string userId.","INVALID_USER_ID",400);if(i!==void 0&&(typeof i!="number"||i<=0))throw this.createError("maxTokens must be a positive number if provided.","INVALID_MAX_TOKENS",400);if(l&&!["strict","moderate","none"].includes(l))throw this.createError("privacyLevel must be one of: strict, moderate, none","INVALID_PRIVACY_LEVEL",400);try{let o=await fetch(`${this.apiUrl}/profile`,{method:"POST",headers:{"x-api-key":this.apiKey,"content-type":"application/json"},body:JSON.stringify({userId:t,task:r||"general",maxFacts:i?Math.min(i/10,100):void 0,cachePolicy:"fresh",includeRecentData:!0,privacyLevel:l||"none",userQuery:y})});if(!o.ok){let d=await o.text().catch(()=>"");throw new Error(d||`HTTP ${o.status}`)}let n=await o.json();return {systemPrompt:n.systemPrompt,metadata:{userId:t,timestamp:n.metadata?.generatedAt?new Date(n.metadata.generatedAt):new Date,providers:n.metadata?.providers||["gmail"]},tokenCount:typeof n.systemPrompt=="string"?n.systemPrompt.length/4:void 0}}catch(o){let n=o instanceof Error?o.message:"";throw n.includes("OAuth access")||n.includes("No OAuth")?this.createError("User has not authorized access. Please ensure the user has connected their account.","UNAUTHORIZED_USER",401):this.createError("Failed to get profile","PROFILE_FAILED",500)}}async listFacts(e){if(!e||!e.userId)throw this.createError("userId is required to list facts.","INVALID_USER_ID",400);let t=new URLSearchParams({userId:e.userId});typeof e.limit=="number"&&t.set("limit",String(e.limit)),typeof e.minConfidence=="number"&&t.set("minConfidence",String(e.minConfidence)),e.category&&t.set("category",e.category);let r=await fetch(`${this.apiUrl}/profile/facts?${t.toString()}`,{headers:{"x-api-key":this.apiKey}});if(!r.ok){let l=await r.text().catch(()=>"");throw this.createError(l||`HTTP ${r.status}`,"FACTS_LIST_FAILED",r.status)}return await r.json()}async deleteFacts(e){if(!e||!e.userId)throw this.createError("userId is required to delete facts.","INVALID_USER_ID",400);let t=await fetch(`${this.apiUrl}/profile/facts`,{method:"DELETE",headers:{"x-api-key":this.apiKey,"content-type":"application/json"},body:JSON.stringify({userId:e.userId,factIds:e.factIds})});if(!t.ok){let r=await t.text().catch(()=>"");throw this.createError(r||`HTTP ${t.status}`,"FACTS_DELETE_FAILED",t.status)}return await t.json()}createError(e,t,r){return new p(e,t,r)}};var m=class{constructor(e){if(!e.apiKey)throw new Error("Kontext API key is required");this.config={apiKey:e.apiKey,providers:e.providers||["gmail","preferences"],apiUrl:e.apiUrl||"https://api.kontext.dev",cache:{ttl:e.cache?.ttl||300,storage:e.cache?.storage||"memory"},limits:{maxTokensPerRequest:e.limits?.maxTokensPerRequest||2e3,monthlyBudget:e.limits?.monthlyBudget||0}},this.vault=new u(this.config.apiUrl,this.config.apiKey),this.profile=new c(this.config.apiUrl,this.config.apiKey),this.users={purge:async({userId:t})=>this.purgeUser(t)};}async disconnect(e){return this.purgeUser(e)}async purgeUser(e){if(!e||typeof e!="string")throw this.createError("Valid userId is required for disconnect. Please provide a non-empty string userId.","INVALID_USER_ID",400);try{let t=await fetch(`${this.config.apiUrl}/users/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"x-api-key":this.config.apiKey}});if(!t.ok){let i=await t.text().catch(()=>"")||`HTTP ${t.status}`;throw t.status===404?this.createError("User not found. The user may have already been purged.","USER_NOT_FOUND",404):this.createError(i,"DISCONNECT_FAILED",t.status||500)}}catch(t){let r=t instanceof Error?t.message:"Failed to purge user";throw this.createError(r,"DISCONNECT_FAILED",500)}}createError(e,t,r){return new p(e,t,r)}}; exports.Kontext=m;exports.ProfileClient=c;exports.VaultClient=u;//# sourceMappingURL=index.cjs.map //# sourceMappingURL=index.cjs.map