@kivox/client 0.1.0-beta.4 → 0.1.0-beta.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -83
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +2162 -618
- package/dist/index.mjs +1 -0
- package/package.json +12 -9
- package/dist/index.js +0 -1
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var YG=/\{[^{}]+\}/g,ZG=()=>{return typeof process==="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici};function $G(){return Math.random().toString(36).slice(2,11)}function i(G){let{baseUrl:V="",Request:X=globalThis.Request,fetch:Z=globalThis.fetch,querySerializer:Y,bodySerializer:$,pathSerializer:J,headers:_,requestInitExt:S=void 0,...r}={...G};S=ZG()?S:void 0,V=o(V);let T=[];async function Q(N,K){let{baseUrl:F,fetch:y=Z,Request:c=X,headers:v,params:k={},parseAs:A="json",querySerializer:j,bodySerializer:h=$??KG,pathSerializer:e,body:d,middleware:GG=[],...z}=K||{},U=V;if(F)U=o(F)??V;let g=typeof Y==="function"?Y:p(Y);if(j)g=typeof j==="function"?j:p({...typeof Y==="object"?Y:{},...j});let m=e||J||JG,P=d===void 0?void 0:h(d,l(_,v,k.header)),VG=l(P===void 0||P instanceof FormData?{}:{"Content-Type":"application/json"},_,v,k.header),O=[...T,...GG],XG={redirect:"follow",...r,...z,body:P,headers:VG},x,R,B=new c(NG(N,{baseUrl:U,params:k,querySerializer:g,pathSerializer:m}),XG),W;for(let I in z)if(!(I in B))B[I]=z[I];if(O.length){x=$G(),R=Object.freeze({baseUrl:U,fetch:y,parseAs:A,querySerializer:g,bodySerializer:h,pathSerializer:m});for(let I of O)if(I&&typeof I==="object"&&typeof I.onRequest==="function"){let D=await I.onRequest({request:B,schemaPath:N,params:k,options:R,id:x});if(D)if(D instanceof c)B=D;else if(D instanceof Response){W=D;break}else throw Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!W){try{W=await y(B,S)}catch(I){let D=I;if(O.length)for(let M=O.length-1;M>=0;M--){let E=O[M];if(E&&typeof E==="object"&&typeof E.onError==="function"){let L=await E.onError({request:B,error:D,schemaPath:N,params:k,options:R,id:x});if(L){if(L instanceof Response){D=void 0,W=L;break}if(L instanceof Error){D=L;continue}throw Error("onError: must return new Response() or instance of Error")}}}if(D)throw D}if(O.length)for(let I=O.length-1;I>=0;I--){let D=O[I];if(D&&typeof D==="object"&&typeof D.onResponse==="function"){let M=await D.onResponse({request:B,response:W,schemaPath:N,params:k,options:R,id:x});if(M){if(!(M instanceof Response))throw Error("onResponse: must return new Response() when modifying the response");W=M}}}}let u=W.headers.get("Content-Length");if(W.status===204||B.method==="HEAD"||u==="0"&&!W.headers.get("Transfer-Encoding")?.includes("chunked"))return W.ok?{data:void 0,response:W}:{error:void 0,response:W};if(W.ok)return{data:await(async()=>{if(A==="stream")return W.body;if(A==="json"&&!u){let D=await W.text();return D?JSON.parse(D):void 0}return await W[A]()})(),response:W};let f=await W.text();try{f=JSON.parse(f)}catch{}return{error:f,response:W}}return{request(N,K,F){return Q(K,{...F,method:N.toUpperCase()})},GET(N,K){return Q(N,{...K,method:"GET"})},PUT(N,K){return Q(N,{...K,method:"PUT"})},POST(N,K){return Q(N,{...K,method:"POST"})},DELETE(N,K){return Q(N,{...K,method:"DELETE"})},OPTIONS(N,K){return Q(N,{...K,method:"OPTIONS"})},HEAD(N,K){return Q(N,{...K,method:"HEAD"})},PATCH(N,K){return Q(N,{...K,method:"PATCH"})},TRACE(N,K){return Q(N,{...K,method:"TRACE"})},use(...N){for(let K of N){if(!K)continue;if(typeof K!=="object"||!(("onRequest"in K)||("onResponse"in K)||("onError"in K)))throw Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");T.push(K)}},eject(...N){for(let K of N){let F=T.indexOf(K);if(F!==-1)T.splice(F,1)}}}}function w(G,V,X){if(V===void 0||V===null)return"";if(typeof V==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${G}=${X?.allowReserved===!0?V:encodeURIComponent(V)}`}function n(G,V,X){if(!V||typeof V!=="object")return"";let Z=[],Y={simple:",",label:".",matrix:";"}[X.style]||"&";if(X.style!=="deepObject"&&X.explode===!1){for(let _ in V)Z.push(_,X.allowReserved===!0?V[_]:encodeURIComponent(V[_]));let J=Z.join(",");switch(X.style){case"form":return`${G}=${J}`;case"label":return`.${J}`;case"matrix":return`;${G}=${J}`;default:return J}}for(let J in V){let _=X.style==="deepObject"?`${G}[${J}]`:J;Z.push(w(_,V[J],X))}let $=Z.join(Y);return X.style==="label"||X.style==="matrix"?`${Y}${$}`:$}function s(G,V,X){if(!Array.isArray(V))return"";if(X.explode===!1){let $={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[X.style]||",",J=(X.allowReserved===!0?V:V.map((_)=>encodeURIComponent(_))).join($);switch(X.style){case"simple":return J;case"label":return`.${J}`;case"matrix":return`;${G}=${J}`;default:return`${G}=${J}`}}let Z={simple:",",label:".",matrix:";"}[X.style]||"&",Y=[];for(let $ of V)if(X.style==="simple"||X.style==="label")Y.push(X.allowReserved===!0?$:encodeURIComponent($));else Y.push(w(G,$,X));return X.style==="label"||X.style==="matrix"?`${Z}${Y.join(Z)}`:Y.join(Z)}function p(G){return function(X){let Z=[];if(X&&typeof X==="object")for(let Y in X){let $=X[Y];if($===void 0||$===null)continue;if(Array.isArray($)){if($.length===0)continue;Z.push(s(Y,$,{style:"form",explode:!0,...G?.array,allowReserved:G?.allowReserved||!1}));continue}if(typeof $==="object"){Z.push(n(Y,$,{style:"deepObject",explode:!0,...G?.object,allowReserved:G?.allowReserved||!1}));continue}Z.push(w(Y,$,G))}return Z.join("&")}}function JG(G,V){let X=G;for(let Z of G.match(YG)??[]){let Y=Z.substring(1,Z.length-1),$=!1,J="simple";if(Y.endsWith("*"))$=!0,Y=Y.substring(0,Y.length-1);if(Y.startsWith("."))J="label",Y=Y.substring(1);else if(Y.startsWith(";"))J="matrix",Y=Y.substring(1);if(!V||V[Y]===void 0||V[Y]===null)continue;let _=V[Y];if(Array.isArray(_)){X=X.replace(Z,s(Y,_,{style:J,explode:$}));continue}if(typeof _==="object"){X=X.replace(Z,n(Y,_,{style:J,explode:$}));continue}if(J==="matrix"){X=X.replace(Z,`;${w(Y,_)}`);continue}X=X.replace(Z,J==="label"?`.${encodeURIComponent(_)}`:encodeURIComponent(_))}return X}function KG(G,V){if(G instanceof FormData)return G;if(V){if((V.get instanceof Function?V.get("Content-Type")??V.get("content-type"):V["Content-Type"]??V["content-type"])==="application/x-www-form-urlencoded")return new URLSearchParams(G).toString()}return JSON.stringify(G)}function NG(G,V){let X=`${V.baseUrl}${G}`;if(V.params?.path)X=V.pathSerializer(X,V.params.path);let Z=V.querySerializer(V.params.query??{});if(Z.startsWith("?"))Z=Z.substring(1);if(Z)X+=`?${Z}`;return X}function l(...G){let V=new Headers;for(let X of G){if(!X||typeof X!=="object")continue;let Z=X instanceof Headers?X.entries():Object.entries(X);for(let[Y,$]of Z)if($===null)V.delete(Y);else if(Array.isArray($))for(let J of $)V.append(Y,J);else if($!==void 0)V.set(Y,$)}return V}function o(G){if(G.endsWith("/"))return G.substring(0,G.length-1);return G}class q{_transport;_conversationId;_closed=!1;_onEvent;_pendingAudioMetadata=null;_remainingMs=0;_elapsedMs=0;get conversationId(){return this._conversationId}get remainingMs(){return this._remainingMs}get elapsedMs(){return this._elapsedMs}get closed(){return this._closed}constructor(G,V,X){this._transport=G,this._conversationId=V,this._onEvent=X.onEvent,this.#G()}sendText(G){if(this._closed){console.warn("Cannot send text: session is closed");return}this._transport.send({type:"input_text",text:G})}sendAudio(G){if(this._closed){console.warn("Cannot send audio: session is closed");return}this._transport.send({type:"input_audio"}),this._transport.sendBinary(G)}streamAudio(G){if(this._closed){console.warn("Cannot stream audio: session is closed");return}this._transport.send({type:"input_audio_stream"}),this._transport.sendBinary(G)}cancelRequest(){if(this._closed){console.warn("Cannot cancel request: session is closed");return}this._transport.send({type:"cancel"})}end(){if(this._closed){console.warn("Cannot end session: session is closed");return}this._transport.send({type:"end"})}close(){if(this._closed)return;this._closed=!0,this._transport.close()}#G(){this._transport.onMessage((G)=>{let V=G;if(V.type==="audio_delta"){this._pendingAudioMetadata={size:V.size};return}if(V.type==="tick")this._remainingMs=V.remaining_ms,this._elapsedMs=V.elapsed_ms;if(V.type==="session_closed")this._closed=!0;this._onEvent?.(V)}),this._transport.onBinary((G)=>{if(this._pendingAudioMetadata){let V={type:"audio_delta",size:this._pendingAudioMetadata.size,audio:G};this._pendingAudioMetadata=null,this._onEvent?.(V)}}),this._transport.onClose(()=>{if(this._closed)return;this._closed=!0,this._onEvent?.({type:"connection_lost",reason:"socket_closed"})}),this._transport.onError(()=>{if(this._closed)return;this._closed=!0,this._onEvent?.({type:"connection_lost",reason:"socket_error"})})}}class H extends Error{code;constructor(G,V="TRANSPORT_ERROR"){super(G);this.code=V;this.name="ConversationTransportError"}}class b{_ws;_closed=!1;_onMessage=null;_onBinary=null;_onError=null;_onClose=null;constructor(G){this._ws=G}async connect(){if(this._ws.readyState===WebSocket.OPEN)throw new H("Already connected","ALREADY_CONNECTED");if(this._ws.readyState===WebSocket.CLOSING||this._ws.readyState===WebSocket.CLOSED)throw new H("Socket is closing or closed","SOCKET_CLOSED");return new Promise((G,V)=>{let X,Z;X=()=>{this._ws.removeEventListener("open",X),this._ws.removeEventListener("error",Z),this.#G(),G()},Z=()=>{this._ws.removeEventListener("open",X),this._ws.removeEventListener("error",Z),V(new H("Connection failed","CONNECTION_FAILED"))},this._ws.addEventListener("open",X),this._ws.addEventListener("error",Z)})}send(G){if(this._ws.readyState!==WebSocket.OPEN)throw new H("Not connected","NOT_CONNECTED");this._ws.send(JSON.stringify(G))}async sendBinary(G){if(this._ws.readyState!==WebSocket.OPEN)throw new H("Not connected","NOT_CONNECTED");let V=await G.arrayBuffer();this._ws.send(V)}onMessage(G){this._onMessage=G}onBinary(G){this._onBinary=G}onError(G){this._onError=G}onClose(G){this._onClose=G}close(){if(this._closed)return;if(this._closed=!0,this._ws.readyState===WebSocket.OPEN||this._ws.readyState===WebSocket.CONNECTING)this._ws.close();this._onClose?.()}#G(){this._ws.addEventListener("message",(G)=>{if(G.data instanceof Blob)this._onBinary?.(G.data);else if(G.data instanceof ArrayBuffer)this._onBinary?.(new Blob([G.data]));else if(typeof G.data==="string")try{let V=JSON.parse(G.data);this._onMessage?.(V)}catch(V){console.warn("Failed to parse JSON message:",G.data,V)}}),this._ws.addEventListener("error",()=>{if(this._closed)return;this._onError?.(new H("WebSocket error")),this.close()}),this._ws.addEventListener("close",()=>{if(this._closed)return;this.close()})}}class C{#G;constructor(G){this.#G=G}async connect(G){let V=this.#V("/conversations/ws"),X=new b(new WebSocket(V));return await X.connect(),X.send({type:"handshake",agent_id:G.agent_id,channel:G.channel}),new Promise((Z,Y)=>{let $=!1;X.onMessage((J)=>{switch(J.type){case"handshake_ok":$=!0,G.onConnection?.(J),Z(new q(X,J.conversation_id,G));break;case"handshake_error":$=!0,G.onConnection?.(J),X.close(),Y(Error(`Handshake rejected: ${J.reason}`));break;default:}}),X.onError((J)=>{if(!$)Y(J)}),X.onClose(()=>{if(!$)Y(Error("Connection lost during handshake"))})})}#V(G){return`${this.#G.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://").replace(/\/$/,"")}${G}`}}var t="https://server.kivox.com.co";function a(G){return i(G)}function FG({baseUrl:G=t}={}){return{api:a({baseUrl:G,credentials:"include"}),realtime:new C(G)}}function MG({bearerToken:G,baseUrl:V=t}){return{api:a({baseUrl:V,headers:{Authorization:`Bearer ${G}`}}),realtime:new C(V)}}export{FG as createSessionClient,MG as createBearerClient,H as ConversationTransportError,q as ConversationSession};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kivox/client",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
4
|
-
"description": "JavaScript/TypeScript client for
|
|
3
|
+
"version": "0.1.0-beta.41",
|
|
4
|
+
"description": "JavaScript/TypeScript client SDK for Kivox",
|
|
5
5
|
"homepage": "https://github.com/ekisa-team/kivox#readme",
|
|
6
6
|
"bugs": {
|
|
7
7
|
"url": "https://github.com/ekisa-team/kivox/issues"
|
|
@@ -15,17 +15,17 @@
|
|
|
15
15
|
"email": "ju4n97@proton.me",
|
|
16
16
|
"url": "https://github.com/ju4n97"
|
|
17
17
|
},
|
|
18
|
-
"sideEffects": false,
|
|
19
18
|
"type": "module",
|
|
20
19
|
"exports": {
|
|
21
20
|
".": {
|
|
22
21
|
"types": "./dist/index.d.ts",
|
|
23
|
-
"
|
|
24
|
-
"
|
|
22
|
+
"import": "./dist/index.mjs",
|
|
23
|
+
"require": "./dist/index.cjs",
|
|
24
|
+
"default": "./dist/index.mjs"
|
|
25
25
|
}
|
|
26
26
|
},
|
|
27
|
-
"main": "./dist/index.
|
|
28
|
-
"module": "./dist/index.
|
|
27
|
+
"main": "./dist/index.cjs",
|
|
28
|
+
"module": "./dist/index.mjs",
|
|
29
29
|
"types": "./dist/index.d.ts",
|
|
30
30
|
"files": [
|
|
31
31
|
"dist",
|
|
@@ -36,13 +36,16 @@
|
|
|
36
36
|
"test": "bun test",
|
|
37
37
|
"test:watch": "bun test --watch"
|
|
38
38
|
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"openapi-fetch": "^0.17.0"
|
|
41
|
+
},
|
|
39
42
|
"devDependencies": {
|
|
40
43
|
"@types/bun": "latest",
|
|
41
44
|
"bun-dts": "^0.1.70",
|
|
42
|
-
"typescript": "
|
|
45
|
+
"typescript": "6.0.2"
|
|
43
46
|
},
|
|
44
47
|
"publishConfig": {
|
|
45
48
|
"access": "public",
|
|
46
|
-
"tag": "
|
|
49
|
+
"tag": "latest"
|
|
47
50
|
}
|
|
48
51
|
}
|
package/dist/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
class J{http;constructor(x){this.http=x}async list(x={}){let K={limit:(x.limit??10).toString(),page:(x.page??1).toString()};if(x.search)K.search=x.search;let B=await this.http.get("/agents",K);return{...B,items:J.parseAgents(B.items)}}async listLive(x={}){let K={limit:(x.limit??10).toString(),page:(x.page??1).toString()};if(x.search)K.search=x.search;let B=await this.http.get("/agents/live",K);return{...B,items:J.parseAgents(B.items)}}async listDraft(x={}){let K={limit:(x.limit??10).toString(),page:(x.page??1).toString()};if(x.search)K.search=x.search;let B=await this.http.get("/agents/draft",K);return{...B,items:J.parseAgents(B.items)}}async listArchived(x={}){let K={limit:(x.limit??10).toString(),page:(x.page??1).toString()};if(x.search)K.search=x.search;let B=await this.http.get("/agents/archived",K);return{...B,items:J.parseAgents(B.items)}}async get(x){let K=await this.http.get(`/agents/${x}`);return J.parseAgent(K)}async create(x){let K=await this.http.post("/agents",x);return J.parseAgent(K)}async update(x,K){let B=await this.http.put(`/agents/${x}`,K);return J.parseAgent(B)}async markAsLive(x){let K=await this.http.patch(`/agents/${x}/live`);return J.parseAgent(K)}async markAsDraft(x){let K=await this.http.patch(`/agents/${x}/draft`);return J.parseAgent(K)}async markAsArchived(x){let K=await this.http.patch(`/agents/${x}/archived`);return J.parseAgent(K)}async delete(x){let K=await this.http.delete(`/agents/${x}`);return J.parseAgent(K)}static parseAgents(x){return x.map(J.parseAgent)}static parseAgent(x){return{...x,config:JSON.parse(x.config),blueprint:JSON.parse(x.blueprint)}}}class _{_transport;_conversationId;_maxDurationMs;_startTime;_endTime;_closed=!1;_pendingAudioMetadata=null;_onEvent;get conversationId(){return this._conversationId}get maxDurationMs(){return this._maxDurationMs}get startTime(){return this._startTime}get endTime(){return this._endTime}get closed(){return this._closed}constructor(x,K,B,F,Q,Y){this._transport=x,this._conversationId=K,this._maxDurationMs=B,this._startTime=F,this._endTime=Q,this._onEvent=Y.onEvent,this.#x()}sendText(x){if(this._closed){console.warn("Cannot send text: session is closed");return}this._transport.send({type:"input.text",conversation_id:this._conversationId,text:x})}sendAudio(x){if(this._closed){console.warn("Cannot send audio: session is closed");return}this._transport.send({type:"input.audio",conversation_id:this._conversationId}),this._transport.sendBinary(x)}streamAudio(x){if(this._closed){console.warn("Cannot stream audio: session is closed");return}this._transport.send({type:"input.audio.stream",conversation_id:this._conversationId}),this._transport.sendBinary(x)}cancelRequest(){if(this._closed){console.warn("Cannot cancel session: session is closed");return}this._transport.send({type:"request.cancel",conversation_id:this._conversationId})}end(){if(this._closed){console.warn("Cannot end session: session is closed");return}this._transport.send({type:"session.end",conversation_id:this._conversationId})}close(){if(this._closed)return;this._closed=!0,this._transport.close()}#x(){this._transport.onMessage((x)=>{let K=x;if(K.type==="response.delta.audio"){this._pendingAudioMetadata={conversation_id:K.conversation_id,size:K.size};return}if(K.type==="session.end"||K.type==="session.timeout"||K.type==="session.connection.lost")this._closed=!0;this._onEvent?.(K)}),this._transport.onBinary((x)=>{if(this._pendingAudioMetadata){let K={type:"response.delta.audio",conversation_id:this._pendingAudioMetadata.conversation_id,size:this._pendingAudioMetadata.size,audio:x};this._pendingAudioMetadata=null,this._onEvent?.(K)}}),this._transport.onClose(()=>{if(this._closed)return;this._closed=!0,this._onEvent?.({type:"session.connection.lost",conversation_id:this._conversationId,reason:"socket_closed"})}),this._transport.onError(()=>{if(this._closed)return;this._closed=!0,this._onEvent?.({type:"session.connection.lost",conversation_id:this._conversationId,reason:"socket_error"})})}}class Z extends Error{code;constructor(x,K="TRANSPORT_ERROR"){super(x);this.code=K;this.name="ConversationTransportError"}}class ${_ws;_closed=!1;_onMessage=null;_onBinary=null;_onError=null;_onClose=null;constructor(x){this._ws=x}async connect(){if(this._ws.readyState===WebSocket.OPEN)throw new Z("Already connected","ALREADY_CONNECTED");if(this._ws.readyState===WebSocket.CLOSING||this._ws.readyState===WebSocket.CLOSED)throw new Z("Socket is closing or closed","SOCKET_CLOSED");return new Promise((x,K)=>{let B=()=>{this._ws.removeEventListener("open",B),this._ws.removeEventListener("error",F),this.#x(),x()},F=()=>{this._ws.removeEventListener("open",B),this._ws.removeEventListener("error",F),K(new Z("Connection failed","CONNECTION_FAILED"))};this._ws.addEventListener("open",B),this._ws.addEventListener("error",F)})}send(x){if(this._ws.readyState!==WebSocket.OPEN)throw new Z("Not connected","NOT_CONNECTED");this._ws.send(JSON.stringify(x))}async sendBinary(x){if(this._ws.readyState!==WebSocket.OPEN)throw new Z("Not connected","NOT_CONNECTED");let K=await x.arrayBuffer();this._ws.send(K)}onMessage(x){this._onMessage=x}onBinary(x){this._onBinary=x}onError(x){this._onError=x}onClose(x){this._onClose=x}close(){if(this._closed)return;if(this._closed=!0,this._ws.readyState===WebSocket.OPEN||this._ws.readyState===WebSocket.CONNECTING)this._ws.close();this._onClose?.()}#x(){this._ws.addEventListener("message",(x)=>{if(x.data instanceof Blob)this._onBinary?.(x.data);else if(x.data instanceof ArrayBuffer)this._onBinary?.(new Blob([x.data]));else try{let K=JSON.parse(x.data);this._onMessage?.(K)}catch(K){console.warn("Failed to parse message:",x.data,K)}}),this._ws.addEventListener("error",()=>{if(this._closed)return;this._onError?.(new Z("WebSocket error")),this.close()}),this._ws.addEventListener("close",()=>{if(this._closed)return;this.close()})}}class z{http;ws;constructor(x,K){this.http=x;this.ws=K}async list(x){let K={limit:(x.limit??20).toString(),page:(x.page??1).toString()};return this.http.get(`/agents/${x.agentId}/conversations`,K)}async get(x){return this.http.get(`/conversations/${x}`)}async connect(x){let K=this.ws.connect("/conversations/websocket"),B=new $(K);return await B.connect(),B.send({type:"session.handshake.offer",agent_id:x.agentId}),new Promise((F,Q)=>{let Y=!1;B.onMessage((N)=>{switch(N.type){case"session.handshake.accept":x.onConnection?.(N);break;case"session.handshake.reject":Y=!0,x.onConnection?.(N),B.close(),Q(Error(`Handshake rejected: ${N.reason}`));break;case"session.start":{Y=!0,x.onConnection?.(N);let W=new _(B,N.conversation_id,N.max_duration_ms,N.start_time,N.end_time,x);F(W);break}default:break}}),B.onError((N)=>{if(!Y)Q(N)}),B.onClose(()=>{if(!Y)Q(Error("WebSocket connection lost during handshake"))})})}}function O(x){let K=new URL(x),B=K.protocol==="https:"?"wss:":"ws:";return{rest:`${K.origin}/v1`,ws:`${B}//${K.host}/v1`}}class G extends Error{status;statusText;body;constructor(x,K,B,F){super(x);this.status=K;this.statusText=B;this.body=F;this.name="HttpTransportError"}}class V{config;constructor(x){this.config=x}async request(x,K){let B=`${this.config.baseUrl}${x}`,F=await fetch(B,{...K,headers:{"Content-Type":"application/json",...this.config.headers,...K?.headers}});if(!F.ok){let Q=await F.text();throw new G(`HTTP ${F.status}: ${F.statusText}`,F.status,F.statusText,Q)}return F.json()}async get(x,K){let B=new URL(`${this.config.baseUrl}${x}`);if(K){let F=Object.entries(K);for(let[Q,Y]of F)B.searchParams.set(Q,Y)}return this.request(x+B.search,{method:"GET"})}async post(x,K){return this.request(x,{method:"POST",body:K?JSON.stringify(K):void 0})}async put(x,K){return this.request(x,{method:"PUT",body:K?JSON.stringify(K):void 0})}async patch(x,K){return this.request(x,{method:"PATCH",body:K?JSON.stringify(K):void 0})}async delete(x){return this.request(x,{method:"DELETE"})}}class X{config;constructor(x){this.config=x}connect(x){let K=`${this.config.baseUrl}${x}`;return new WebSocket(K)}}class L{http;constructor(x){this.http=x}async list(x={}){let K={limit:(x.limit??50).toString(),page:(x.page??1).toString()};if(x.conversationId)K.conversation_id=x.conversationId;return this.http.get("/messages",K)}async get(x){return this.http.get(`/messages/${x}`)}}class H{http;constructor(x){this.http=x}async list(x={}){let K={limit:(x.limit??10).toString(),page:(x.page??1).toString()};return this.http.get("/templates",K)}async get(x){return this.http.get(`/templates/${x}`)}async create(x){return this.http.post("/templates",x)}async update(x,K){return this.http.put(`/templates/${x}`,K)}async delete(x){return this.http.delete(`/templates/${x}`)}}class U{agents;conversations;templates;messages;constructor(x){let K=O(x.baseUrl),B=new V({baseUrl:K.rest,headers:x.headers}),F=new X({baseUrl:K.ws,headers:x.headers});this.agents=new J(B),this.templates=new H(B),this.conversations=new z(B,F),this.messages=new L(B)}}export{U as KivoxClient,G as HttpTransportError,Z as ConversationTransportError,_ as ConversationSession};
|