@kivox/client 0.1.0-beta.44 → 0.1.0-beta.45

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/dist/index.mjs CHANGED
@@ -1 +1,5 @@
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};
1
+ var e=/\{[^{}]+\}/g,GG=()=>{return typeof process==="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici};function KG(){return Math.random().toString(36).slice(2,11)}function u(W){let{baseUrl:G="",Request:K=globalThis.Request,fetch:X=globalThis.fetch,querySerializer:V,bodySerializer:Y,pathSerializer:J,headers:D,requestInitExt:k=void 0,...F}={...W};k=GG()?k:void 0,G=p(G);let E=[];async function I(Z,$){let{baseUrl:O,fetch:b=X,Request:P=K,headers:f,params:B={},parseAs:M="json",querySerializer:g,bodySerializer:y=Y??WG,pathSerializer:t,body:v,middleware:i=[],...U}=$||{},q=G;if(O)q=p(O)??G;let S=typeof V==="function"?V:d(V);if(g)S=typeof g==="function"?g:d({...typeof V==="object"?V:{},...g});let c=t||J||VG,w=v===void 0?void 0:y(v,m(D,f,B.header)),r=m(w===void 0||w instanceof FormData?{}:{"Content-Type":"application/json"},D,f,B.header),j=[...E,...i],a={redirect:"follow",...F,...U,body:w,headers:r},x,A,Q=new P(XG(Z,{baseUrl:q,params:B,querySerializer:S,pathSerializer:c}),a),N;for(let T in U)if(!(T in Q))Q[T]=U[T];if(j.length){x=KG(),A=Object.freeze({baseUrl:q,fetch:b,parseAs:M,querySerializer:S,bodySerializer:y,pathSerializer:c});for(let T of j)if(T&&typeof T==="object"&&typeof T.onRequest==="function"){let _=await T.onRequest({request:Q,schemaPath:Z,params:B,options:A,id:x});if(_)if(_ instanceof P)Q=_;else if(_ instanceof Response){N=_;break}else throw Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!N){try{N=await b(Q,k)}catch(T){let _=T;if(j.length)for(let H=j.length-1;H>=0;H--){let L=j[H];if(L&&typeof L==="object"&&typeof L.onError==="function"){let C=await L.onError({request:Q,error:_,schemaPath:Z,params:B,options:A,id:x});if(C){if(C instanceof Response){_=void 0,N=C;break}if(C instanceof Error){_=C;continue}throw Error("onError: must return new Response() or instance of Error")}}}if(_)throw _}if(j.length)for(let T=j.length-1;T>=0;T--){let _=j[T];if(_&&typeof _==="object"&&typeof _.onResponse==="function"){let H=await _.onResponse({request:Q,response:N,schemaPath:Z,params:B,options:A,id:x});if(H){if(!(H instanceof Response))throw Error("onResponse: must return new Response() when modifying the response");N=H}}}}let h=N.headers.get("Content-Length");if(N.status===204||Q.method==="HEAD"||h==="0"&&!N.headers.get("Transfer-Encoding")?.includes("chunked"))return N.ok?{data:void 0,response:N}:{error:void 0,response:N};if(N.ok)return{data:await(async()=>{if(M==="stream")return N.body;if(M==="json"&&!h){let _=await N.text();return _?JSON.parse(_):void 0}return await N[M]()})(),response:N};let z=await N.text();try{z=JSON.parse(z)}catch{}return{error:z,response:N}}return{request(Z,$,O){return I($,{...O,method:Z.toUpperCase()})},GET(Z,$){return I(Z,{...$,method:"GET"})},PUT(Z,$){return I(Z,{...$,method:"PUT"})},POST(Z,$){return I(Z,{...$,method:"POST"})},DELETE(Z,$){return I(Z,{...$,method:"DELETE"})},OPTIONS(Z,$){return I(Z,{...$,method:"OPTIONS"})},HEAD(Z,$){return I(Z,{...$,method:"HEAD"})},PATCH(Z,$){return I(Z,{...$,method:"PATCH"})},TRACE(Z,$){return I(Z,{...$,method:"TRACE"})},use(...Z){for(let $ of Z){if(!$)continue;if(typeof $!=="object"||!(("onRequest"in $)||("onResponse"in $)||("onError"in $)))throw Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");E.push($)}},eject(...Z){for(let $ of Z){let O=E.indexOf($);if(O!==-1)E.splice(O,1)}}}}function R(W,G,K){if(G===void 0||G===null)return"";if(typeof G==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${W}=${K?.allowReserved===!0?G:encodeURIComponent(G)}`}function o(W,G,K){if(!G||typeof G!=="object")return"";let X=[],V={simple:",",label:".",matrix:";"}[K.style]||"&";if(K.style!=="deepObject"&&K.explode===!1){for(let D in G)X.push(D,K.allowReserved===!0?G[D]:encodeURIComponent(G[D]));let J=X.join(",");switch(K.style){case"form":return`${W}=${J}`;case"label":return`.${J}`;case"matrix":return`;${W}=${J}`;default:return J}}for(let J in G){let D=K.style==="deepObject"?`${W}[${J}]`:J;X.push(R(D,G[J],K))}let Y=X.join(V);return K.style==="label"||K.style==="matrix"?`${V}${Y}`:Y}function l(W,G,K){if(!Array.isArray(G))return"";if(K.explode===!1){let Y={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[K.style]||",",J=(K.allowReserved===!0?G:G.map((D)=>encodeURIComponent(D))).join(Y);switch(K.style){case"simple":return J;case"label":return`.${J}`;case"matrix":return`;${W}=${J}`;default:return`${W}=${J}`}}let X={simple:",",label:".",matrix:";"}[K.style]||"&",V=[];for(let Y of G)if(K.style==="simple"||K.style==="label")V.push(K.allowReserved===!0?Y:encodeURIComponent(Y));else V.push(R(W,Y,K));return K.style==="label"||K.style==="matrix"?`${X}${V.join(X)}`:V.join(X)}function d(W){return function(K){let X=[];if(K&&typeof K==="object")for(let V in K){let Y=K[V];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){if(Y.length===0)continue;X.push(l(V,Y,{style:"form",explode:!0,...W?.array,allowReserved:W?.allowReserved||!1}));continue}if(typeof Y==="object"){X.push(o(V,Y,{style:"deepObject",explode:!0,...W?.object,allowReserved:W?.allowReserved||!1}));continue}X.push(R(V,Y,W))}return X.join("&")}}function VG(W,G){let K=W;for(let X of W.match(e)??[]){let V=X.substring(1,X.length-1),Y=!1,J="simple";if(V.endsWith("*"))Y=!0,V=V.substring(0,V.length-1);if(V.startsWith("."))J="label",V=V.substring(1);else if(V.startsWith(";"))J="matrix",V=V.substring(1);if(!G||G[V]===void 0||G[V]===null)continue;let D=G[V];if(Array.isArray(D)){K=K.replace(X,l(V,D,{style:J,explode:Y}));continue}if(typeof D==="object"){K=K.replace(X,o(V,D,{style:J,explode:Y}));continue}if(J==="matrix"){K=K.replace(X,`;${R(V,D)}`);continue}K=K.replace(X,J==="label"?`.${encodeURIComponent(D)}`:encodeURIComponent(D))}return K}function WG(W,G){if(W instanceof FormData)return W;if(G){if((G.get instanceof Function?G.get("Content-Type")??G.get("content-type"):G["Content-Type"]??G["content-type"])==="application/x-www-form-urlencoded")return new URLSearchParams(W).toString()}return JSON.stringify(W)}function XG(W,G){let K=`${G.baseUrl}${W}`;if(G.params?.path)K=G.pathSerializer(K,G.params.path);let X=G.querySerializer(G.params.query??{});if(X.startsWith("?"))X=X.substring(1);if(X)K+=`?${X}`;return K}function m(...W){let G=new Headers;for(let K of W){if(!K||typeof K!=="object")continue;let X=K instanceof Headers?K.entries():Object.entries(K);for(let[V,Y]of X)if(Y===null)G.delete(V);else if(Array.isArray(Y))for(let J of Y)G.append(V,J);else if(Y!==void 0)G.set(V,Y)}return G}function p(W){if(W.endsWith("/"))return W.substring(0,W.length-1);return W}function YG(W,G){if(!G)return{};try{return JSON.parse(G)}catch{return G}}async function*$G(W){let G=W.getReader(),K=new TextDecoder,X="";try{while(!0){let{done:V,value:Y}=await G.read();if(V)break;X+=K.decode(Y,{stream:!0});let J=X.split(`
2
+
3
+ `);X=J.pop()??"";for(let D of J){let k=D.split(`
4
+ `),F="message",E=[];for(let I of k)if(I.startsWith("event:"))F=I.slice(6).trim();else if(I.startsWith("data:")){let Z=I.slice(5);E.push(Z.startsWith(" ")?Z.slice(1):Z)}if(E.length>0){let I=E.join(`
5
+ `);yield{event:F,data:YG(F,I)}}}}}finally{G.releaseLock()}}var n="https://server.kivox.com.co";function s(W){return u(W)}function NG(W={}){let{baseUrl:G=n,version:K="v1",headers:X={}}=W;return{api:s({baseUrl:`${G}/${K}`,credentials:"include",headers:X})}}function _G(W){let{baseUrl:G=n,version:K="v1",headers:X={},bearerToken:V}=W;return{api:s({baseUrl:`${G}/${K}`,headers:{...X,Authorization:`Bearer ${V}`}})}}export{$G as readSSE,NG as createSessionClient,_G as createBearerClient};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kivox/client",
3
- "version": "0.1.0-beta.44",
3
+ "version": "0.1.0-beta.45",
4
4
  "description": "JavaScript/TypeScript client SDK for Kivox",
5
5
  "homepage": "https://github.com/ekisa-team/kivox#readme",
6
6
  "bugs": {