UNPKG

@gladiaio/sdk

Version:

Gladia JavaScript/TypeScript SDK

2 lines 19 kB
var Gladia=(function(exports){var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));function u(e,t){if(e={...e},!t)return e;for(let[n,r]of Object.entries(t)){if(r==null)continue;e[n]&&typeof e[n]==`object`&&typeof r==`object`?e[n]=u(e[n],r):e[n]=r}return e}function d(e,t){return typeof process>`u`||process.env===void 0?t:process.env[e]??t}async function f(e){await new Promise(t=>setTimeout(t,e))}function p(e){return typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}function m(e){return p(e),new Uint8Array(e)}function h(e,t){let n=new Uint8Array((e?.byteLength??0)+(t?.byteLength??0));return e&&n.set(new Uint8Array(e),0),t&&n.set(new Uint8Array(t),e?.byteLength??0),n}async function g(){if(d(`VITEST_WORKER_ID`)||!(typeof process<`u`&&process.versions?.node))return fetch;try{let{fetch:e,Agent:t}=await import(`undici`),n=new t({connectTimeout:2**53-1,connect:{timeout:2**53-1},headersTimeout:2**53-1,bodyTimeout:0});return(t,r)=>e(t,{...r,dispatcher:n})}catch{return fetch}}function _(e){"@babel/helpers - typeof";return _=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},_(e)}function v(e,t){if(_(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(_(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function y(e){var t=v(e,`string`);return _(t)==`symbol`?t:t+``}function b(e,t,n){return(t=y(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var x=class extends Error{constructor({message:e,method:t,id:n,requestId:r,responseBody:i,url:a,status:o,headers:s},c){super(e,c),b(this,`method`,void 0),b(this,`status`,void 0),b(this,`url`,void 0),b(this,`id`,void 0),b(this,`requestId`,void 0),b(this,`responseBody`,void 0),b(this,`responseHeaders`,void 0),this.name=`HttpError`,this.method=t,this.url=a,this.status=o,this.id=n,this.requestId=r,this.responseBody=i,this.responseHeaders=s}};async function S(e,t,n,r){let i,a,o,s,c;try{o=n.headers.get(`x-aipi-call-id`)??void 0,c=Object.fromEntries(n.headers.entries()),s=await n.text();try{s=JSON.parse(s),a=s?.request_id,i=s?.message}catch{}}catch{}let l=[i||n.statusText||`An error occurred`,a||o,n.status.toString(),`${e} ${new URL(t).pathname}`];return new x({method:e,message:l.filter(Boolean).join(` | `),url:t.toString(),status:n.status,id:o,requestId:a,responseBody:s,headers:c},r)}var C=class extends Error{constructor(e,t,n){super(e,n),b(this,`timeout`,void 0),this.name=`TimeoutError`,this.timeout=t}};function w(e,t){for(let n of t)if(typeof n==`number`){if(e===n)return!0}else{let[t,r]=n;if(e>=t&&e<=r)return!0}return!1}function T(e){if(!e||typeof e!=`object`)return!1;if(`name`in e&&e.name===`AbortError`)return!0;try{if(typeof DOMException<`u`&&e instanceof DOMException&&e.name===`AbortError`)return!0}catch{}return!1}var E=class{constructor(e){b(this,`baseUrl`,void 0),b(this,`defaultHeaders`,void 0),b(this,`defaultQueryParams`,void 0),b(this,`retry`,void 0),b(this,`timeout`,void 0),b(this,`fetchPromise`,void 0),this.baseUrl=e.baseUrl,this.defaultHeaders=e.headers,this.defaultQueryParams=e.queryParams,this.retry=e.retry,this.timeout=e.timeout,this.retry.maxAttempts=Math.max(0,Math.floor(this.retry.maxAttempts)),this.timeout=Math.max(0,Math.floor(this.timeout)),this.fetchPromise=g()}async get(e,t={}){return this.request(`GET`,e,t)}async post(e,t={}){return this.request(`POST`,e,t)}async put(e,t={}){return this.request(`PUT`,e,t)}async delete(e,t={}){return this.request(`DELETE`,e,t)}async request(e,t,n={}){if(t=new URL(t,this.baseUrl),this.defaultQueryParams)for(let[e,n]of Object.entries(this.defaultQueryParams))t.searchParams.has(e)||t.searchParams.set(e,n);let{signal:r,headers:i,...a}=n,o=Date.now(),s=[],c=0,l=this.retry.maxAttempts;for(;;){c+=1;let n=new AbortController,d=()=>n.abort(r?.reason),p,m=!1;try{if(r){if(r.aborted)throw Error(`Request aborted by the provided AbortSignal`,{cause:r.reason});r.addEventListener(`abort`,d,{once:!0})}this.timeout>0&&(p=setTimeout(()=>{m=!0,n.abort(new C(`Request timed out after ${this.timeout}ms`,this.timeout))},this.timeout));let o=await(await this.fetchPromise)(t,{...a,method:e,headers:this.defaultHeaders?u(this.defaultHeaders,i):i,signal:n.signal});if(p&&clearTimeout(p),r&&r.removeEventListener(`abort`,d),!o.ok){let n=await S(e,t,o);if((l===0||c<l)&&w(o.status,this.retry.statusCodes)){s.push(n);let e=this.retry.delay(c);await f(e);continue}throw n}return o.headers.get(`content-type`)?.includes(`application/json`)?await o.json():o}catch(n){if(p&&clearTimeout(p),r&&r.removeEventListener(`abort`,d),m){let r=Date.now()-o;throw new C(`Request timed out after ${this.timeout}ms on attempt ${c} (duration=${r}ms) for ${e} ${t}`,this.timeout,{cause:n})}if(T(n)||r&&r.aborted){let r=Date.now()-o;throw Error(`Request aborted by the provided AbortSignal after ${r}ms for ${e} ${t}`,{cause:n})}let i=n instanceof Error?n:Error(String(n));if(i instanceof x){if(w(i.status,this.retry.statusCodes)&&(l===0||c<l)){s.push(i),await f(this.retry.delay(c));continue}if(s.length>0){s.push(i);let n=Date.now()-o,r=AggregateError(s,`All retry attempts failed`);throw Error(`HTTP request failed after ${c} attempts over ${n}ms for ${e} ${t}`,{cause:r})}throw i}if(l===0||c<l){s.push(i),await f(this.retry.delay(c));continue}s.push(i);let a=Date.now()-o,u=AggregateError(s,`All retry attempts failed`);throw Error(`HTTP request failed after ${c} attempts over ${a}ms for ${e} ${t}`,{cause:u})}}}};let D={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function O(){if(typeof WebSocket<`u`)return WebSocket;if(typeof global<`u`&&global.WebSocket!==void 0)return global.WebSocket;if(typeof globalThis<`u`&&globalThis.WebSocket!==void 0)return globalThis.WebSocket;if(typeof window<`u`&&window.WebSocket!==void 0||typeof window<`u`&&window.WebSocket!==void 0)return window.WebSocket;if(typeof self<`u`&&self.WebSocket!==void 0)return self.WebSocket}async function k(e){let t;try{t=O()??(await import(`ws`)).WebSocket}catch{}if(!t)throw Error("WebSocket is not supported in this environment and the `ws` package is not installed");return new t(e)}function A(e,t){for(let n of t)if(typeof n==`number`){if(e===n)return!0}else{let[t,r]=n;if(e>=t&&e<=r)return!0}return!1}function j(e){e&&(e.onopen=null,e.onerror=null,e.onmessage=null,e.onclose=null)}var M=class{constructor(e){b(this,`baseUrl`,void 0),b(this,`retry`,void 0),b(this,`timeout`,void 0),this.baseUrl=e.baseUrl,this.retry=e.retry,this.timeout=e.timeout,this.retry.maxAttemptsPerConnection=Math.max(0,Math.floor(this.retry.maxAttemptsPerConnection)),this.retry.maxConnections=Math.max(0,Math.floor(this.retry.maxConnections)),this.timeout=Math.max(0,Math.floor(this.timeout))}createSession(e){return new N({retry:this.retry,timeout:this.timeout,url:new URL(e,this.baseUrl)})}},N=class{constructor({retry:e,timeout:t,url:n}){b(this,`onconnecting`,null),b(this,`onopen`,null),b(this,`onerror`,null),b(this,`onclose`,null),b(this,`onmessage`,null),b(this,`_readyState`,D.CONNECTING),b(this,`_url`,void 0),b(this,`retry`,void 0),b(this,`timeout`,void 0),b(this,`ws`,null),b(this,`connectionCount`,0),b(this,`connectionAttempt`,0),b(this,`connectionTimeoutId`,void 0),this._url=n.toString(),this.retry=e,this.timeout=t,this.connect().catch(()=>{})}get readyState(){return this._readyState}get url(){return this._url}send(e){if(this.readyState===D.OPEN){if(!this.ws)throw Error(`readyState is open but ws is not initialized`);this.ws.send(e)}else throw Error(`WebSocket is not open`)}close(e=1e3,t=``){this.readyState===D.CLOSING||this.readyState===D.CLOSED||(this.clearConnectionTimeout(),this._readyState=D.CLOSING,this.ws?.readyState===D.OPEN?this.ws.close(e):this.onWsClose(e,t))}onWsClose(e=1e3,t=``){this.clearConnectionTimeout(),this.readyState!==D.CLOSED&&(this._readyState=D.CLOSED,this.onclose?.({code:e,reason:t})),this.onconnecting=null,this.onopen=null,this.onclose=null,this.onerror=null,this.onmessage=null,j(this.ws),this.ws=null}async connect(e=!1){this.clearConnectionTimeout(),e||(this.connectionCount+=1,this.connectionAttempt=0),this.connectionAttempt+=1,this._readyState=D.CONNECTING,this.onconnecting?.({connection:this.connectionCount,attempt:this.connectionAttempt}),this.timeout>0&&(this.connectionTimeoutId=setTimeout(()=>{this.close(3008,`WebSocket connection timeout`)},this.timeout));let t=async(e,t)=>{if(this.clearConnectionTimeout(),j(e),this.readyState===D.CONNECTING){if(this.retry.maxAttemptsPerConnection>0&&this.connectionAttempt>=this.retry.maxAttemptsPerConnection){this.onerror?.(Error(`WebSocket connection error`,{cause:t})),this.close(1006,`WebSocket connection error`);return}await f(this.retry.delay(this.connectionAttempt)),this.readyState===D.CONNECTING&&this.connect(!0)}},n;try{n=await k(this.url)}catch(e){t(null,e instanceof Error?e:Error(String(e)));return}if(this.readyState!==D.CONNECTING){n.close(1001);return}n.onerror=()=>t(n),n.onopen=()=>{if(this.clearConnectionTimeout(),j(n),this.readyState!==D.CONNECTING){n.close(1001);return}n.onmessage=e=>{this.onmessage?.(e)},n.onclose=e=>{if(j(n),this.ws===n){if(this.ws=null,this.readyState===D.CLOSING){this.onWsClose(e.code,e.reason||``);return}if(this.retry.maxConnections>0&&this.connectionCount>=this.retry.maxConnections||!A(e.code,this.retry.closeCodes)){this.close(e.code,e.reason||``);return}this.connect()}},this.ws=n,this._readyState=D.OPEN,this.onopen?.({connection:this.connectionCount,attempt:this.connectionAttempt})}}clearConnectionTimeout(){this.connectionTimeoutId&&=(clearTimeout(this.connectionTimeoutId),void 0)}},P=l(s(((exports,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)}))(),1),F=class{constructor({options:e,httpClient:t,webSocketClient:n}){b(this,`sessionOptions`,void 0),b(this,`httpClient`,void 0),b(this,`webSocketClient`,void 0),b(this,`abortController`,new AbortController),b(this,`initSessionPromise`,void 0),b(this,`initSession`,null),b(this,`webSocketSession`,null),b(this,`eventEmitter`,new P.default),b(this,`bytesSent`,0),b(this,`audioBuffer`,null),b(this,`_status`,`starting`),this.sessionOptions=e,this.httpClient=t,this.webSocketClient=n,this.abortController=new AbortController,this.initSessionPromise=this.startSession(),this.initSessionPromise.then(e=>{if(this.initSession=e,!this.abortController.signal.aborted){if(this._status===`starting`&&(this._status=`started`,this.emit(`started`,e)),this.sessionOptions.messages_config?.receive_lifecycle_events){let t={type:`start_session`,session_id:e.id,created_at:e.created_at};this.emit(`message`,t)}return this.connectToWebSocket(e)}})}async getSessionId(){let{id:e}=await this.initSessionPromise;return e}get sessionId(){return this.initSession?.id??null}get status(){return this._status}sendAudio(e){if(this._status===`ended`||this._status===`ending`)return;let t=m(e);this.audioBuffer=h(this.audioBuffer,t),this.webSocketSession?.readyState===D.OPEN&&this.webSocketSession?.send(t)}stopRecording(){this.doStop(1e3)}endSession(){this.doDestroy(1e3,`Session ended by user`)}doStop(e=1006,t){this._status!==`ended`&&this._status!==`ending`&&(this._status=`ending`,this.emit(`ending`,{code:e,reason:t}),this.webSocketSession?.readyState===D.OPEN&&this.webSocketSession?.send(JSON.stringify({type:`stop_recording`})))}doDestroy(e=1006,t){this._status!==`ended`&&(this.doStop(e,t),this._status=`ended`,this.emit(`ended`,{code:e,reason:t}),this.abortController.abort(),this.audioBuffer=null,this.removeAllListeners(),this.eventEmitter=null)}connectToWebSocket(e){if(this.abortController.signal.aborted)return;let t=this.webSocketClient.createSession(e.url);this.abortController.signal.addEventListener(`abort`,()=>{this.webSocketSession=null,t.onconnecting=null,t.onopen=null,t.onmessage=null,t.onclose=null,t.onerror=null,t.close(1001,`Aborted`)}),this.webSocketSession=t,this.webSocketSession.onconnecting=({connection:e})=>{this._status=`connecting`,this.emit(`connecting`,{attempt:e})},this.webSocketSession.onopen=({connection:e})=>{if(this.audioBuffer?.byteLength&&t.send(this.audioBuffer),this.status===`ending`){t.send(JSON.stringify({type:`stop_recording`}));return}this._status=`connected`,this.emit(`connected`,{attempt:e})},this.webSocketSession.onmessage=e=>{let t=this.parseMessage(e.data.toString());if((this.sessionOptions.messages_config?.receive_acknowledgments||!(`acknowledged`in t))&&this.emit(`message`,t),t.type===`audio_chunk`&&t.acknowledged&&t.data){let e=t.data.byte_range[1],n=this.audioBuffer?.slice(e-this.bytesSent);this.audioBuffer=n?.byteLength?n:null,this.bytesSent=e}},this.webSocketSession.onclose=({code:e,reason:t})=>{this.doDestroy(e,t)},this.webSocketSession.onerror=e=>{this.emit(`error`,e)}}async startSession(){try{return await this.httpClient.post(`/v2/live`,{signal:this.abortController.signal,headers:{"Content-Type":`application/json`},body:JSON.stringify({...this.sessionOptions,messages_config:{...this.sessionOptions.messages_config,receive_acknowledgments:!0}})})}catch(e){throw this.abortController.signal.aborted||(this.emit(`error`,e instanceof Error?e:Error(`Error creating session: ${e}`,{cause:e})),this.doDestroy(1006,`Couldn't start a new session`)),e}}parseMessage(e){let t;try{t=JSON.parse(e)}catch(t){throw Error(`Invalid message received: ${e}`,{cause:t})}if(!t||typeof t!=`object`||!(`type`in t))throw Error(`Invalid message received: ${e}`);return t}on(e,t){this.eventEmitter?.on(e,t)}once(e,t){this.eventEmitter?.once(e,t)}off(e,t){this.eventEmitter?.off(e,t)}addListener(e,t){this.eventEmitter?.addListener(e,t)}removeListener(e,t){this.eventEmitter?.removeListener(e,t)}removeAllListeners(){this.eventEmitter?.removeAllListeners()}emit(e,...t){this.eventEmitter?.emit(e,...t)}},I=class{constructor(e){b(this,`httpClient`,void 0),b(this,`webSocketClient`,void 0);let t=new URL(e.apiUrl);t.protocol=t.protocol.replace(/^ws/,`http`),this.httpClient=new E({baseUrl:t,headers:e.httpHeaders,...e.region?{queryParams:{region:e.region}}:{},retry:e.httpRetry,timeout:e.httpTimeout});let n=new URL(e.apiUrl);n.protocol=n.protocol.replace(/^http/,`ws`),this.webSocketClient=new M({baseUrl:n,retry:e.wsRetry,timeout:e.wsTimeout})}startSession(e){return new F({options:e,httpClient:this.httpClient,webSocketClient:this.webSocketClient})}};function L(e){let t=Array.isArray(e)?e:Object.entries(e);return Object.fromEntries(t.map(([e,t])=>{let n=e.toLowerCase();return[n.startsWith(`x-gladia-`)?n:e,t]}))}function R(e){let t;try{t=new URL(e.apiUrl)}catch{throw Error(`Invalid url: "${e.apiUrl}".`)}if(!e?.apiKey&&t.hostname.endsWith(`.gladia.io`))throw Error(`You have to set your "apiKey" or define a proxy "apiUrl".`);if(![`https:`,`http:`,`wss:`,`ws:`].includes(t.protocol))throw Error(`Only HTTP and WebSocket protocols are supported for apiUrl (received: ${t.protocol}).`)}let z=e=>Math.min(.3*2**(e-1)*1e3,1e4),B=e=>Math.min(.3*2**(e-1)*1e3,2e3),V=`SdkJavascript/0.5.0`,H={apiKey:d(`GLADIA_API_KEY`),apiUrl:d(`GLADIA_API_URL`,`https://api.gladia.io`),region:d(`GLADIA_REGION`),httpHeaders:{"x-gladia-version":V},httpRetry:{maxAttempts:2,statusCodes:[408,413,429,[500,599]],delay:z},httpTimeout:1e4,wsRetry:{maxAttemptsPerConnection:5,closeCodes:[[1002,4399],[4500,9999]],delay:B,maxConnections:0},wsTimeout:1e4};return exports.GladiaClient=class{constructor(e){b(this,`options`,void 0),e?.httpHeaders&&(e.httpHeaders=L(e.httpHeaders)),this.options=u(H,e)}liveV2(e){e?.httpHeaders&&(e.httpHeaders=L(e.httpHeaders));let t=u(this.options,e);return t.apiKey&&(t.httpHeaders=u(t.httpHeaders,{"x-gladia-key":t.apiKey})),t.httpHeaders[`x-gladia-version`]!==V&&(t.httpHeaders[`x-gladia-version`]=`${t.httpHeaders[`x-gladia-version`].trim()} ${V}`.trim()),R(t),new I(t)}},exports})({}); //# sourceMappingURL=index.iife.js.map