uneeq-js 3.20.0 → 3.21.0
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/esm/chunks/chunk-HXVOCQLA.js +1 -0
- package/dist/esm/chunks/chunk-KD2RTEWK.js +2 -0
- package/dist/esm/chunks/deepgram-flux-stt-O7EPQ3GQ.js +27 -0
- package/dist/esm/chunks/deepgram-stt-FSBUGIVO.js +1 -0
- package/dist/esm/chunks/google-stt-QWA7C2VS.js +2486 -0
- package/dist/esm/index.js +8 -8
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/vad/frame-processor.d.ts +2 -2
- package/dist/signaling.d.ts +1 -0
- package/dist/types/UneeqMessages.d.ts +11 -0
- package/dist/types/dhop-messages.d.ts +1 -0
- package/package.json +4 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var ee=Object.create;var p=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var se=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty;var ie=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var pe=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(s){throw t=0,s}},ce=(e,t)=>{for(var s in t)p(e,s,{get:t[s],enumerable:!0})},ae=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ne(t))!re.call(e,r)&&r!==s&&p(e,r,{get:()=>t[r],enumerable:!(i=te(t,r))||i.enumerable});return e};var le=(e,t,s)=>(s=e!=null?ee(se(e)):{},ae(t||!e||!e.__esModule?p(s,"default",{value:e,enumerable:!0}):s,e));var c=(a=>(a.Fatal="fatal",a.Error="error",a.Warn="warn",a.Info="info",a.Debug="debug",a.Trace="trace",a))(c||{});var l="UneeQ SDK: ",g={fatal:0,error:1,warn:2,info:3,debug:4,trace:5},u=class e{static currentLevel="info";static shouldLog(t){return g[t]<=g[e.currentLevel]}static formatLogMessage(t,s){return s.length===0?l+t:l+t+" | "+JSON.stringify(s)}static fatal(t,...s){e.shouldLog("fatal")&&console.error(e.formatLogMessage(t,s))}static error(t,...s){e.shouldLog("error")&&console.error(e.formatLogMessage(t,s))}static warn(t,...s){e.shouldLog("warn")&&console.warn(e.formatLogMessage(t,s))}static info(t,...s){e.shouldLog("info")&&console.info(e.formatLogMessage(t,s))}static debug(t,...s){e.shouldLog("debug")&&console.debug(e.formatLogMessage(t,s))}static trace(t,...s){e.shouldLog("trace")&&console.debug(e.formatLogMessage(t,s))}static setLevel(t){Object.values(c).includes(t)?((t=="trace"||t=="debug")&&console.warn(l+"you may need to set your browser's console settings to show verbose logs to be able to see debug or trace logs"),e.currentLevel=t):e.currentLevel="info"}static serialiseError(t){return JSON.stringify(t,Object.getOwnPropertyNames(t))}};function o(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var m=class{constructor(t,s,i=o(),r=!0){this.prompt=t;this.metadata=s;this.requestId=i;this.shouldEmitPromptRequest=r}prompt;metadata;requestId;shouldEmitPromptRequest;toJSON(){return{action:"chat_prompt",data:{requestId:this.requestId,prompt:this.prompt,metadata:this.metadata}}}};var oe=(n=>(n.AvatarAnswer="AvatarAnswer",n.AvatarInterrupted="AvatarInterrupted",n.AvatarStartedSpeaking="AvatarStartedSpeaking",n.AvatarStoppedSpeaking="AvatarStoppedSpeaking",n.CustomerConcurrencyLimitReached="CustomerConcurrencyLimitReached",n.CustomMetadataUpdated="CustomMetadataUpdated",n.DeviceError="DeviceError",n.DigitalHumanMuted="DigitalHumanMuted",n.DigitalHumanPlayedInMutedModeSuccess="DigitalHumanPlayedInMutedModeSuccess",n.DigitalHumanUnmuted="DigitalHumanUnmuted",n.EnableMicrophoneUpdated="EnableMicrophoneUpdated",n.NetworkQuality="NetworkQuality",n.PromptRequest="PromptRequest",n.PromptResult="PromptResult",n.RendererError="RendererError",n.RendererVersionWarning="RendererVersionWarning",n.SceneReady="SceneReady",n.SessionBackendError="SessionBackendError",n.SessionConnecting="SessionConnecting",n.SessionDisconnected="SessionDisconnected",n.SessionEnded="SessionEnded",n.SessionError="SessionError",n.SessionLive="SessionLive",n.SessionReconnecting="SessionReconnecting",n.SessionReconnectingFinished="SessionReconnectingFinished",n.SoftSwitchFinished="SoftSwitchFinished",n.SoftSwitchStarting="SoftSwitchStarting",n.SpeechEvent="SpeechEvent",n.SpeechRecognitionTransientError="SpeechRecognitionTransientError",n.SpeechTranscription="SpeechTranscription",n.UserStartedSpeaking="UserStartedSpeaking",n.UserStoppedSpeaking="UserStoppedSpeaking",n.VadInterruptionAllowed="VadInterruptionAllowed",n.VideoAutoplayBlocked="VideoAutoplayBlocked",n.VideoLayoutConfiguring="VideoLayoutConfiguring",n.WaitingInQueue="WaitingInQueue",n.WebRtcConnected="webRtcConnected",n.WebRtcStats="WebRtcStats",n))(oe||{}),d=class{constructor(t){this.error=t}error;uneeqMessageType="DeviceError"},y=class{constructor(t,s,i,r){this.answer=t;this.answerAvatar=s;this.answerSpeech=i;this.transcriptId=r}answer;answerAvatar;answerSpeech;transcriptId;uneeqMessageType="AvatarAnswer"},q=class{constructor(t){this.speechTranscription=t}speechTranscription;uneeqMessageType="SpeechTranscription"},M=class{constructor(t){this.interruptionAllowed=t}interruptionAllowed;uneeqMessageType="VadInterruptionAllowed"},b=class{uneeqMessageType="UserStartedSpeaking"},U=class{uneeqMessageType="UserStoppedSpeaking"},T=class{uneeqMessageType="AvatarStartedSpeaking"},x=class{uneeqMessageType="AvatarStoppedSpeaking"},S=class{constructor(t){this.transcriptId=t}transcriptId;uneeqMessageType="AvatarInterrupted"},h=class{constructor(t){this.sessionId=t}sessionId;uneeqMessageType="SessionLive"},f=class{constructor(t){this.position=t}position;uneeqMessageType="WaitingInQueue"},v=class{constructor(t){this.stats=t}stats;uneeqMessageType="WebRtcStats"},D=class{constructor(t){this.error=t}error;uneeqMessageType="SessionError"},w=class{constructor(t){this.error=t}error;uneeqMessageType="SpeechRecognitionTransientError"},R=class{constructor(t){this.error=t}error;uneeqMessageType="SessionBackendError"},I=class{constructor(t){this.speechEvent=t}speechEvent;uneeqMessageType="SpeechEvent"},C=class{constructor(t){this.reason=t}reason;uneeqMessageType="SessionEnded"},E=class{uneeqMessageType="DigitalHumanPlayedInMutedModeSuccess";msg="Digital Human was successfully played in muted mode. After the user interacts with the page you will need to call unmuteDigitalHuman() to unmute the video."},k=class{uneeqMessageType="DigitalHumanUnmuted"},A=class{uneeqMessageType="DigitalHumanMuted"},L=class{constructor(t){this.enabled=t}enabled;uneeqMessageType="EnableMicrophoneUpdated"},P=class{constructor(t){this.chatMetadata=t}chatMetadata;uneeqMessageType="CustomMetadataUpdated"},V=class{constructor(t){this.promptRequest=t}promptRequest;uneeqMessageType="PromptRequest"},N=class{constructor(t){this.promptResult=t}promptResult;uneeqMessageType="PromptResult"},O=class{uneeqMessageType="SceneReady"},W=class{constructor(t){this.rendererId=t}rendererId;uneeqMessageType="SessionConnecting"},F=class{uneeqMessageType="SessionDisconnected"},H=class{uneeqMessageType="SessionReconnecting"},Q=class{uneeqMessageType="SessionReconnectingFinished"},B=class{uneeqMessageType="SoftSwitchStarting"},J=class{uneeqMessageType="SoftSwitchFinished"},j=class{uneeqMessageType="VideoLayoutConfiguring"},G=class{uneeqMessageType="webRtcConnected"},K=class{uneeqMessageType="CustomerConcurrencyLimitReached"},X=class{constructor(t){this.metrics=t}metrics;uneeqMessageType="NetworkQuality"},Y=class{constructor(t,s){this.code=t;this.error=s}code;error;uneeqMessageType="RendererError"},z=class{constructor(t,s,i){this.rendererVersion=t;this.latestVersion=s;this.message=i}rendererVersion;latestVersion;message;uneeqMessageType="RendererVersionWarning"},Z=class{uneeqMessageType="VideoAutoplayBlocked"};var $=class{constructor(t,s=o()){this.state=t;this.requestId=s}state;requestId;toJSON(){return{action:"user_speaking",data:{requestId:this.requestId,event:this.state}}}};var _=class{constructor(t=o()){this.requestId=t}requestId;toJSON(){return{action:"stop_speaking",data:{requestId:this.requestId}}}};export{ie as a,pe as b,ce as c,le as d,c as e,u as f,o as g,m as h,oe as i,d as j,y as k,q as l,M as m,b as n,U as o,T as p,x as q,S as r,h as s,f as t,v as u,D as v,w,R as x,I as y,C as z,E as A,k as B,A as C,L as D,P as E,V as F,N as G,O as H,W as I,F as J,H as K,Q as L,B as M,J as N,j as O,G as P,K as Q,X as R,Y as S,z as T,Z as U,$ as V,_ as W};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as Ft,b as Nt,c as st,d as gr}from"./chunk-HXVOCQLA.js";var wt=Nt((Vi,ar)=>{"use strict";ar.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var pr=Nt(()=>{});var We=class{getAuthRequest(){return Promise.resolve({headers:{}})}};var yr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Oe={get:(s,e)=>yr(void 0,void 0,void 0,function*(){return typeof s=="function"?s(e):s})};var A=(s,e,o)=>JSON.stringify(s,e,o);function V(s,e){return JSON.parse(s,e)}var oe={Debug:"debug",Info:"info",Warn:"warn",Error:"error"},zt={[oe.Debug]:1,[oe.Info]:2,[oe.Warn]:3,[oe.Error]:4},$e=class{debug(e,...o){console.debug(e,...o)}info(e,...o){console.info(e,...o)}warn(e,...o){console.warn(e,...o)}error(e,...o){console.error(e,...o)}},ye=class{constructor(e){this.level=zt[e.level],this.logger=e.logger,this.silent=e.silent}shouldLog(e){return!this.silent&&this.level<=zt[e]}isDebug(){return this.shouldLog(oe.Debug)}debug(e,...o){this.isDebug()&&this.logger.debug(e,...o)}isInfo(){return this.shouldLog(oe.Info)}info(e,...o){this.isInfo()&&this.logger.info(e,...o)}isWarn(){return this.shouldLog(oe.Warn)}warn(e,...o){this.isWarn()&&this.logger.warn(e,...o)}isError(){return this.shouldLog(oe.Error)}error(e,...o){this.isError()&&this.logger.error(e,...o)}};function Ge(s){var e,o,t;return s==null?wr:s instanceof ye?s:(s=s??{},(e=s.level)!==null&&e!==void 0||(s.level=oe.Info),(o=s.logger)!==null&&o!==void 0||(s.logger=new $e),(t=s.silent)!==null&&t!==void 0||(s.silent=!0),new ye(s))}var wr=new ye({level:oe.Info,logger:new $e,silent:!0});var br={arrayFormat:"indices",encode:!0};function at(s,e){if(s===void 0||s===null)return"";let o=String(s);return e?encodeURIComponent(o):o}function dt(s,e="",o){let t=[];for(let[r,i]of Object.entries(s)){let a=e?`${e}[${r}]`:r;if(i!==void 0)if(Array.isArray(i)){if(i.length===0)continue;let c=o.arrayFormat;if(c==="comma"){let u=o.encode?encodeURIComponent(a):a,d=i.filter(n=>n!=null).map(n=>at(n,o.encode));d.length>0&&t.push(`${u}=${d.join(",")}`)}else for(let u=0;u<i.length;u++){let d=i[u];if(d!==void 0)if(typeof d=="object"&&!Array.isArray(d)&&d!==null){let n=c==="indices"?`${a}[${u}]`:a;t.push(...dt(d,n,o))}else{let n=c==="indices"?`${a}[${u}]`:a,l=o.encode?encodeURIComponent(n):n;t.push(`${l}=${at(d,o.encode)}`)}}}else if(typeof i=="object"&&i!==null){if(Object.keys(i).length===0)continue;t.push(...dt(i,a,o))}else{let c=o.encode?encodeURIComponent(a):a;t.push(`${c}=${at(i,o.encode)}`)}}return t}function te(s,e){return s==null||typeof s!="object"?"":dt(s,"",Object.assign(Object.assign({},br),e)).join("&")}function Wt(s,e){let o=te(e,{arrayFormat:"repeat"});return o?`${s}?${o}`:s}function $t(s){let e={get bodyUsed(){return s.bodyUsed},stream:()=>s.body,arrayBuffer:s.arrayBuffer.bind(s),blob:s.blob.bind(s)};return"bytes"in s&&typeof s.bytes=="function"&&(e.bytes=s.bytes.bind(s)),e}var Rr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})};function eo(s,e){return Rr(this,void 0,void 0,function*(){switch(e){case"binary-response":return $t(s);case"blob":return yield s.blob();case"arrayBuffer":return yield s.arrayBuffer();case"sse":return s.body==null?{ok:!1,error:{reason:"body-is-null",statusCode:s.status}}:s.body;case"streaming":return s.body==null?{ok:!1,error:{reason:"body-is-null",statusCode:s.status}}:s.body;case"text":return yield s.text()}let o=yield s.text();if(o.length>0)try{return V(o)}catch{return{ok:!1,error:{reason:"non-json",statusCode:s.status,rawBody:o}}}})}var Sr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})};function Gt(s){return Sr(this,void 0,void 0,function*(){var e,o,t;let r=(e=s.headers.get("Content-Type"))===null||e===void 0?void 0:e.toLowerCase();if(r==null||r.length===0)return eo(s);switch(r.indexOf(";")!==-1&&(r=(t=(o=r.split(";")[0])===null||o===void 0?void 0:o.trim())!==null&&t!==void 0?t:""),r){case"application/hal+json":case"application/json":case"application/ld+json":case"application/problem+json":case"application/vnd.api+json":case"text/json":{let i=yield s.text();return i.length>0?V(i):void 0}default:if(r.startsWith("application/vnd.")&&r.endsWith("+json")){let i=yield s.text();return i.length>0?V(i):void 0}return yield s.text()}})}var Er=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})};function oo(){return Er(this,void 0,void 0,function*(){return fetch})}var xr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})};function Jt(s){return xr(this,arguments,void 0,function*({body:e,type:o}){return o==="form"?te(e,{arrayFormat:"repeat",encode:!0}):o.includes("json")?A(e):e})}var ce;typeof globalThis.Headers<"u"?ce=globalThis.Headers:ce=class Kt{constructor(e){if(this.headers=new Map,e)if(e instanceof Kt)e.forEach((o,t)=>this.append(t,o));else if(Array.isArray(e))for(let[o,t]of e)if(typeof o=="string"&&typeof t=="string")this.append(o,t);else throw new TypeError("Each header entry must be a [string, string] tuple");else for(let[o,t]of Object.entries(e))if(typeof t=="string")this.append(o,t);else throw new TypeError("Header values must be strings")}append(e,o){let t=e.toLowerCase(),r=this.headers.get(t)||[];this.headers.set(t,[...r,o])}delete(e){let o=e.toLowerCase();this.headers.delete(o)}get(e){let o=e.toLowerCase(),t=this.headers.get(o);return t?t.join(", "):null}has(e){let o=e.toLowerCase();return this.headers.has(o)}set(e,o){let t=e.toLowerCase();this.headers.set(t,[o])}forEach(e,o){let t=o?e.bind(o):e;this.headers.forEach((r,i)=>t(r.join(", "),i,this))}getSetCookie(){return this.headers.get("set-cookie")||[]}*entries(){for(let[e,o]of this.headers.entries())yield[e,o.join(", ")]}*keys(){yield*this.headers.keys()}*values(){for(let e of this.headers.values())yield e.join(", ")}[Symbol.iterator](){return this.entries()}};var kr="timeout";function Vt(s){let e=new AbortController,o=setTimeout(()=>e.abort(kr),s);return{signal:e.signal,abortId:o}}function Yt(...s){let e=s.length===1&&Array.isArray(s[0])?s[0]:s,o=new AbortController;for(let t of e){if(t.aborted){o.abort(t?.reason);break}t.addEventListener("abort",()=>o.abort(t?.reason),{signal:o.signal})}return o.signal}var Pr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Je;function Cr(){if(Je!=null)return Je;try{new Request("http://localhost",{cache:"no-store"}),Je=!0}catch{Je=!1}return Je}var to=(s,e,o,t,r,i,a,c,u,d)=>Pr(void 0,void 0,void 0,function*(){let n=[],l;if(i!=null){let{signal:f,abortId:m}=Vt(i);l=m,n.push(f)}a!=null&&n.push(a);let v=Yt(n),_=yield s(e,Object.assign({method:o,headers:t,body:r,signal:v,credentials:c?"include":void 0,duplex:u},d&&Cr()?{cache:"no-store"}:{}));return l!=null&&clearTimeout(l),_});var lt={headers:new ce,redirected:!1,status:499,statusText:"Client Closed Request",type:"error",url:""},ct={headers:new ce,redirected:!1,status:0,statusText:"Unknown Error",type:"error",url:""};function ut(s){return{headers:s.headers,redirected:s.redirected,status:s.status,statusText:s.statusText,type:s.type,url:s.url}}var jr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})};function Tr(s){let e=1+Math.random()*.2;return s*e}function Dr(s){let e=1+(Math.random()-.5)*.2;return s*e}function Ar(s,e){let o=s.headers.get("Retry-After");if(o){let r=parseInt(o,10);if(!Number.isNaN(r)&&r>0)return Math.min(r*1e3,6e4);let i=new Date(o);if(!Number.isNaN(i.getTime())){let a=i.getTime()-Date.now();if(a>0)return Math.min(Math.max(a,0),6e4)}}let t=s.headers.get("X-RateLimit-Reset");if(t){let r=parseInt(t,10);if(!Number.isNaN(r)){let i=r*1e3-Date.now();if(i>0)return Tr(Math.min(i,6e4))}}return Dr(Math.min(1e3*Math.pow(2,e),6e4))}function ro(s){return jr(this,arguments,void 0,function*(e,o=2){let t=yield e();for(let r=0;r<o&&([408,429].includes(t.status)||t.status>=500);++r){let i=Ar(t,r);yield new Promise(a=>setTimeout(a,i)),t=yield e()}return t})}var mt=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Ir=new Set(["authorization","www-authenticate","x-api-key","api-key","apikey","x-api-token","x-auth-token","auth-token","cookie","set-cookie","proxy-authorization","proxy-authenticate","x-csrf-token","x-xsrf-token","x-session-token","x-access-token"]);function ht(s){let e={};for(let[o,t]of s instanceof ce?s.entries():Object.entries(s))Ir.has(o.toLowerCase())?e[o]="[REDACTED]":e[o]=t;return e}var vt=new Set(["api_key","api-key","apikey","token","access_token","access-token","auth_token","auth-token","password","passwd","secret","api_secret","api-secret","apisecret","key","session","session_id","session-id"]);function Lr(s){if(s==null)return;let e={};for(let[o,t]of Object.entries(s))e[o]=vt.has(o.toLowerCase())?"[REDACTED]":t;return e}function fe(s){let e=s.indexOf("://");if(e===-1)return s;let o=e+3,t=s.indexOf("/",o),r=s.indexOf("?",o),i=s.indexOf("#",o),a=Math.min(t===-1?s.length:t,r===-1?s.length:r,i===-1?s.length:i),c=-1;for(let f=o;f<a;f++)s[f]==="@"&&(c=f);if(c!==-1&&(s=`${s.slice(0,o)}[REDACTED]@${s.slice(c+1)}`),r=s.indexOf("?"),r===-1)return s;i=s.indexOf("#",r);let u=i!==-1?i:s.length,d=s.slice(r+1,u);if(d.length===0)return s;let n=d.toLowerCase();if(!(n.includes("token")||n.includes("key")||n.includes("password")||n.includes("passwd")||n.includes("secret")||n.includes("session")||n.includes("auth")))return s;let v=[],_=d.split("&");for(let f of _){let m=f.indexOf("=");if(m===-1){v.push(f);continue}let h=f.slice(0,m),y=vt.has(h.toLowerCase());if(!y&&h.includes("%"))try{let T=decodeURIComponent(h);y=vt.has(T.toLowerCase())}catch{}v.push(y?`${h}=[REDACTED]`:f)}return s.slice(0,r+1)+v.join("&")+s.slice(u)}function Mr(s){return mt(this,void 0,void 0,function*(){var e;let o=new ce;if(o.set("Accept",s.responseType==="json"?"application/json":s.responseType==="text"?"text/plain":s.responseType==="sse"?"text/event-stream":"*/*"),s.body!==void 0&&s.contentType!=null&&o.set("Content-Type",s.contentType),s.headers==null)return o;for(let[t,r]of Object.entries(s.headers)){let i=yield Oe.get(r,{endpointMetadata:(e=s.endpointMetadata)!==null&&e!==void 0?e:{}});if(typeof i=="string"){o.set(t,i);continue}i!=null&&o.set(t,`${i}`)}return o})}function Br(s){return mt(this,void 0,void 0,function*(){var e,o,t;let r=s.url;s.queryString!=null&&s.queryString.length>0?r=`${r}?${s.queryString}`:r=Wt(s.url,s.queryParameters);let i=yield Jt({body:s.body,type:(e=s.requestType)!==null&&e!==void 0?e:"other"}),a=(o=s.fetchFn)!==null&&o!==void 0?o:yield oo(),c=yield Mr(s),u=Ge(s.logging);if(u.isDebug()){let d={method:s.method,url:fe(r),headers:ht(c),queryParameters:Lr(s.queryParameters),hasBody:i!=null};u.debug("Making HTTP request",d)}try{let d=yield ro(()=>mt(this,void 0,void 0,function*(){return to(a,r,s.method,c,i,s.timeoutMs,s.abortSignal,s.withCredentials,s.duplex,s.responseType==="streaming"||s.responseType==="sse")}),s.maxRetries);if(d.status>=200&&d.status<400){if(u.isDebug()){let l={method:s.method,url:fe(r),statusCode:d.status,responseHeaders:ht(d.headers)};u.debug("HTTP request succeeded",l)}return{ok:!0,body:yield eo(d,s.responseType),headers:d.headers,rawResponse:ut(d)}}else{if(u.isError()){let n={method:s.method,url:fe(r),statusCode:d.status,responseHeaders:ht(Object.fromEntries(d.headers.entries()))};u.error("HTTP request failed with error status",n)}return{ok:!1,error:{reason:"status-code",statusCode:d.status,body:yield Gt(d)},rawResponse:ut(d)}}}catch(d){if(!((t=s.abortSignal)===null||t===void 0)&&t.aborted){if(u.isError()){let n={method:s.method,url:fe(r)};u.error("HTTP request was aborted",n)}return{ok:!1,error:{reason:"unknown",errorMessage:"The user aborted a request",cause:d},rawResponse:lt}}else if(d instanceof Error&&d.name==="AbortError"){if(u.isError()){let n={method:s.method,url:fe(r),timeoutMs:s.timeoutMs};u.error("HTTP request timed out",n)}return{ok:!1,error:{reason:"timeout",cause:d},rawResponse:lt}}else if(d instanceof Error){if(u.isError()){let n={method:s.method,url:fe(r),errorMessage:d.message};u.error("HTTP request failed with error",n)}return{ok:!1,error:{reason:"unknown",errorMessage:d.message,cause:d},rawResponse:ct}}if(u.isError()){let n={method:s.method,url:fe(r),error:A(d)};u.error("HTTP request failed with unknown error",n)}return{ok:!1,error:{reason:"unknown",errorMessage:A(d),cause:d},rawResponse:ct}}})}var k=Br;var Hr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},E=class s extends Promise{constructor(e){super(o=>{o(void 0)}),this.innerPromise=e}static fromFunction(e,...o){return new s(e(...o))}static interceptFunction(e){return(...o)=>s.fromPromise(e(...o))}static fromPromise(e){return new s(e)}static fromExecutor(e){let o=new Promise(e);return new s(o)}static fromResult(e){let o=Promise.resolve(e);return new s(o)}unwrap(){return this.unwrappedPromise||(this.unwrappedPromise=this.innerPromise.then(({data:e})=>e)),this.unwrappedPromise}then(e,o){return this.unwrap().then(e,o)}catch(e){return this.unwrap().catch(e)}finally(e){return this.unwrap().finally(e)}withRawResponse(){return Hr(this,void 0,void 0,function*(){return yield this.innerPromise})}};function no(s,...e){if(!s)return"";if(e.length===0)return s;if(s.includes("://")){let o;try{o=new URL(s)}catch{return Qt(s,...e)}let t=e[e.length-1],r=t?.endsWith("/");for(let i of e){let a=Zt(i);a&&(o.pathname=Xt(o.pathname,a))}return r&&!o.pathname.endsWith("/")&&(o.pathname+="/"),o.toString()}return Qt(s,...e)}function Qt(s,...e){if(e.length===0)return s;let o=s,t=e[e.length-1],r=t?.endsWith("/");for(let i of e){let a=Zt(i);a&&(o=Xt(o,a))}return r&&!o.endsWith("/")&&(o+="/"),o}function Xt(s,e){return s.endsWith("/")?s+e:`${s}/${e}`}function Zt(s){if(!s)return s;let e=0,o=s.length;return s.startsWith("/")&&(e=1),s.endsWith("/")&&(o=s.length-1),e===0&&o===s.length?s:s.slice(e,o)}var Ur=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},g={get:s=>Ur(void 0,void 0,void 0,function*(){return typeof s=="function"?s():s})};var qt=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})};function _t(s,e,o,t){return qt(this,void 0,void 0,function*(){var r,i,a,c,u,d,n;let l=Ge(o.logging),v,_=e;s instanceof Request?(v=s.url,e==null&&(_={method:s.method,headers:Object.fromEntries(s.headers.entries()),body:s.body,signal:s.signal,credentials:s.credentials,cache:s.cache,redirect:s.redirect,referrer:s.referrer,integrity:s.integrity,mode:s.mode})):v=s instanceof URL?s.toString():s;let f=(r=o.baseUrl!=null?yield g.get(o.baseUrl):void 0)!==null&&r!==void 0?r:o.environment!=null?yield g.get(o.environment):void 0,m;v.startsWith("http://")||v.startsWith("https://")?m=v:f!=null?m=no(f,v):m=v;let h={};if(o.headers!=null)for(let[D,U]of Object.entries(o.headers)){let L=yield Oe.get(U,{endpointMetadata:{}});L!=null&&(h[D.toLowerCase()]=`${L}`)}if(o.getAuthHeaders!=null){let D=yield o.getAuthHeaders();for(let[U,L]of Object.entries(D))h[U.toLowerCase()]=L}if(_?.headers!=null){let D=_.headers instanceof Headers?Object.fromEntries(_.headers.entries()):Array.isArray(_.headers)?Object.fromEntries(_.headers):_.headers;for(let[U,L]of Object.entries(D))L!=null&&(h[U.toLowerCase()]=L)}if(t?.headers!=null)for(let[D,U]of Object.entries(t.headers))h[D.toLowerCase()]=U;let y=(i=_?.method)!==null&&i!==void 0?i:"GET",T=_?.body,S=(a=t?.timeoutInSeconds)!==null&&a!==void 0?a:o.timeoutInSeconds,j=S!=null?S*1e3:void 0,I=(c=t?.maxRetries)!==null&&c!==void 0?c:o.maxRetries,z=(d=(u=t?.abortSignal)!==null&&u!==void 0?u:_?.signal)!==null&&d!==void 0?d:void 0,J=(n=o.fetch)!==null&&n!==void 0?n:yield oo();l.isDebug()&&l.debug("Making passthrough HTTP request",{method:y,url:m,hasBody:T!=null});let W=yield ro(()=>qt(this,void 0,void 0,function*(){return to(J,m,y,h,T??void 0,j,z,_?.credentials==="include",void 0,!1)}),I);return l.isDebug()&&l.debug("Passthrough HTTP request completed",{method:y,url:m,statusCode:W.status}),W})}var io={};st(io,{toBinaryUploadRequest:()=>Fr,toMultipartDataPart:()=>Nr});var Ke=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})};function Fr(s){return Ke(this,void 0,void 0,function*(){let{data:e,filename:o,contentLength:t,contentType:r}=yield pt(s),i={body:e,headers:{}};return o&&(i.headers["Content-Disposition"]=`attachment; filename="${o}"`),r&&(i.headers["Content-Type"]=r),t!=null&&(i.headers["Content-Length"]=t.toString()),i})}function Nr(s){return Ke(this,void 0,void 0,function*(){let{data:e,filename:o,contentType:t}=yield pt(s,{noSniffFileSize:!0});return{data:e,filename:o,contentType:t}})}function pt(s){return Ke(this,arguments,void 0,function*(e,{noSniffFileSize:o}={}){var t,r,i,a,c;if(zr(e))return pt({data:e},{noSniffFileSize:o});if("path"in e){let u=yield import("./fs-TPREOTZZ.js");if(!u?.createReadStream)throw new Error("File path uploads are not supported in this environment.");let d=u.createReadStream(e.path),n=(t=e.contentLength)!==null&&t!==void 0?t:o===!0?void 0:yield Ot(e.path),l=(r=e.filename)!==null&&r!==void 0?r:er(e.path);return{data:d,filename:l,contentType:e.contentType,contentLength:n}}if("data"in e){let u=e.data,d=(i=e.contentLength)!==null&&i!==void 0?i:yield $r(u,{noSniffFileSize:o}),n=(a=e.filename)!==null&&a!==void 0?a:Wr(u);return{data:u,filename:n,contentType:(c=e.contentType)!==null&&c!==void 0?c:Gr(u),contentLength:d}}throw new Error(`Invalid FileUpload of type ${typeof e}: ${JSON.stringify(e)}`)})}function zr(s){return tr(s)||rr(s)||nr(s)||Yr(s)||ft(s)||gt(s)||Kr(s)||Vr(s)}function Ot(s){return Ke(this,void 0,void 0,function*(){var e;try{let o=yield import("./fs-TPREOTZZ.js");return!((e=o?.promises)===null||e===void 0)&&e.stat?(yield o.promises.stat(s)).size:void 0}catch{return}})}function Wr(s){if(Jr(s))return s.name;if(or(s))return er(s.path.toString())}function $r(s){return Ke(this,arguments,void 0,function*(e,{noSniffFileSize:o}={}){if(tr(e))return e.length;if(rr(e)||nr(e))return e.byteLength;if(ft(e)||gt(e))return e.size;if(o!==!0&&or(e))return yield Ot(e.path.toString())})}function Gr(s){if(ft(s)||gt(s))return s.type}function er(s){let e=s.lastIndexOf("/"),o=s.lastIndexOf("\\"),t=Math.max(e,o);return t>=0?s.substring(t+1):s}function Jr(s){return typeof s=="object"&&s!=null&&"name"in s}function or(s){return typeof s=="object"&&s!=null&&"path"in s}function Kr(s){return typeof s=="object"&&s!=null&&("read"in s||"pipe"in s)}function Vr(s){return typeof s=="object"&&s!=null&&"getReader"in s}function tr(s){return typeof Buffer<"u"&&Buffer.isBuffer&&Buffer.isBuffer(s)}function rr(s){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView(s)}function nr(s){return typeof ArrayBuffer<"u"&&s instanceof ArrayBuffer}function Yr(s){return typeof Uint8Array<"u"&&s instanceof Uint8Array}function ft(s){return typeof Blob<"u"&&s instanceof Blob}function gt(s){return typeof File<"u"&&s instanceof File}var so={};st(so,{ConsoleLogger:()=>$e,LogLevel:()=>oe,Logger:()=>ye,createLogger:()=>Ge});var Q=Qr();function Qr(){var s,e,o,t,r;if(typeof window<"u"&&typeof window.document<"u")return{type:"browser",version:window.navigator.userAgent};if(typeof globalThis<"u"&&((s=globalThis?.navigator)===null||s===void 0?void 0:s.userAgent)==="Cloudflare-Workers")return{type:"workerd"};if(typeof EdgeRuntime=="string")return{type:"edge-runtime"};if(typeof self=="object"&&typeof self?.importScripts=="function"&&(((e=self.constructor)===null||e===void 0?void 0:e.name)==="DedicatedWorkerGlobalScope"||((o=self.constructor)===null||o===void 0?void 0:o.name)==="ServiceWorkerGlobalScope"||((t=self.constructor)===null||t===void 0?void 0:t.name)==="SharedWorkerGlobalScope"))return{type:"web-worker"};if(typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u")return{type:"deno",version:Deno.version.deno};if(typeof Bun<"u"&&typeof Bun.version<"u")return{type:"bun",version:Bun.version};if(typeof navigator<"u"&&navigator?.product==="ReactNative")return{type:"react-native"};let v=typeof process<"u"?process:void 0;return typeof v<"u"&&typeof((r=v.versions)===null||r===void 0?void 0:r.node)=="string"?{type:"node",version:v.versions.node,parsedVersion:Number(v.versions.node.split(".")[0])}:{type:"unknown"}}var p={};st(p,{encodePathParam:()=>ir,join:()=>no,queryBuilder:()=>sr,toQueryString:()=>te});function ir(s){if(s===null)return"null";switch(typeof s){case"undefined":return"undefined";case"string":case"number":case"boolean":break;default:s=String(s);break}return encodeURIComponent(s)}function sr(){return new yt}var yt=class{constructor(){this.parts=new Map}add(e,o,t){if(o==null)return this;let r=te({[e]:o},{arrayFormat:t?.style==="comma"?"comma":"repeat"});return r.length>0&&this.parts.set(e,r),this}addMany(e){if(e!=null)for(let[o,t]of Object.entries(e))this.add(o,t);return this}mergeAdditional(e){if(e!=null)for(let[o,t]of Object.entries(e)){if(t==null)continue;let r=te({[o]:t},{arrayFormat:"repeat"});r.length>0&&this.parts.set(o,r)}return this}build(){return[...this.parts.values()].join("&")}};var dr=gr(wt(),1);var ao=class{constructor(e,o){this.target=o,this.type=e}},lo=class extends ao{constructor(e,o){super("error",o),this.message=e.message,this.error=e}},Ve=class extends ao{constructor(e=1e3,o="",t){super("close",t),this.wasClean=!0,this.code=e,this.reason=o}};var Zr=()=>{if(Q.type==="node"||Q.type==="bun"||Q.type==="deno")return dr.WebSocket;if(typeof WebSocket<"u")return WebSocket},qr=s=>typeof s<"u"&&!!s&&s.CLOSING===2,ue={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},B=class s{constructor({url:e,protocols:o,options:t,headers:r,queryParameters:i,abortSignal:a}){this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.CONNECTING=s.CONNECTING,this.OPEN=s.OPEN,this.CLOSING=s.CLOSING,this.CLOSED=s.CLOSED,this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleAbort=()=>{if(!this._closeCalled&&(this._debug("abort signal fired"),this._shouldReconnect=!1,this._closeCalled=!0,this._clearTimeouts(),this._ws)){this._removeListeners(),this._ws.addEventListener("error",()=>{});try{this._ws.close(1e3,"aborted"),this._handleClose(new Ve(1e3,"aborted",this))}catch{}}},this._handleOpen=c=>{this._debug("open event");let{minUptime:u=ue.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),u),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(d=>{var n;return(n=this._ws)===null||n===void 0?void 0:n.send(d)}),this._messageQueue=[],this.onopen&&this.onopen(c),this._listeners.open.forEach(d=>this._callEventListener(c,d))},this._handleMessage=c=>{this._debug("message event"),this.onmessage&&this.onmessage(c),this._listeners.message.forEach(u=>this._callEventListener(c,u))},this._handleError=c=>{this._debug("error event",c.message),this._disconnect(void 0,c.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(c),this._debug("exec error listeners"),this._listeners.error.forEach(u=>this._callEventListener(c,u)),this._connect()},this._handleClose=c=>{this._debug("close event"),this._clearTimeouts(),c.code===1e3&&(this._shouldReconnect=!1),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(c),this._listeners.close.forEach(u=>this._callEventListener(c,u))},this._url=e,this._protocols=o,this._options=t??ue,this._headers=r,this._queryParameters=i,this._abortSignal=a,this._abortSignal&&this._abortSignal.addEventListener("abort",this._handleAbort,{once:!0}),this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((o,t)=>(typeof t=="string"?o+=t.length:t instanceof Blob?o+=t.size:o+=t.byteLength,o),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?s.ReadyState.CLOSED:s.ReadyState.CONNECTING}get url(){return this._ws?this._ws.url:""}close(e=1e3,o){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(e,o)}reconnect(e,o){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,o),this._connect())}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{let{maxEnqueuedMessages:o=ue.maxEnqueuedMessages}=this._options;this._messageQueue.length<o&&(this._debug("enqueue",e),this._messageQueue.push(e))}}addEventListener(e,o){this._listeners[e]&&this._listeners[e].push(o)}dispatchEvent(e){let o=this._listeners[e.type];if(o)for(let t of o)this._callEventListener(e,t);return!0}removeEventListener(e,o){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(t=>t!==o))}_debug(...e){this._options.debug&&console.log.apply(console,["RWS>",...e])}_getNextDelay(){let{reconnectionDelayGrowFactor:e=ue.reconnectionDelayGrowFactor,minReconnectionDelay:o=ue.minReconnectionDelay,maxReconnectionDelay:t=ue.maxReconnectionDelay}=this._options,r=0;return this._retryCount>0&&(r=o*Math.pow(e,this._retryCount-1),r>t&&(r=t)),this._debug("next delay",r),r}_wait(){return new Promise(e=>{setTimeout(e,this._getNextDelay())})}_getNextUrl(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){let o=e();if(typeof o=="string")return Promise.resolve(o);if(o.then)return o}throw Error("Invalid URL")}_connect(){var e;if(this._connectLock||!this._shouldReconnect)return;if(!((e=this._abortSignal)===null||e===void 0)&&e.aborted){this._debug("connect aborted");return}this._connectLock=!0;let{maxRetries:o=ue.maxRetries,connectionTimeout:t=ue.connectionTimeout,WebSocket:r=Zr()}=this._options;if(this._retryCount>=o){this._debug("max retries reached",this._retryCount,">=",o);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!qr(r))throw Error("No valid WebSocket class provided");this._wait().then(()=>this._getNextUrl(this._url)).then(i=>{var a;if(this._closeCalled||!((a=this._abortSignal)===null||a===void 0)&&a.aborted){this._connectLock=!1;return}let c={};if(this._headers&&(c.headers=this._headers),this._queryParameters&&Object.keys(this._queryParameters).length>0){let u=te(this._queryParameters,{arrayFormat:"repeat"});u&&(i=`${i}?${u}`)}this._ws=new r(i,this._protocols,c),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),t)})}_handleTimeout(){this._debug("timeout event"),this._handleError(new lo(Error("TIMEOUT"),this))}_disconnect(e=1e3,o){if(this._clearTimeouts(),!!this._ws){this._removeListeners(),this._ws.addEventListener("error",()=>{});try{this._ws.close(e,o),this._handleClose(new Ve(e,o,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_callEventListener(e,o){"handleEvent"in o?o.handleEvent(e):o(e)}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}};B.CONNECTING=0;B.OPEN=1;B.CLOSING=2;B.CLOSED=3;(function(s){s.ReadyState={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3}})(B||(B={}));var w=class extends Error{constructor({message:e,statusCode:o,body:t,rawResponse:r,cause:i}){super(Or({message:e,statusCode:o,body:t})),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.statusCode=o,this.body=t,this.rawResponse=r,i!=null&&(this.cause=i)}};function Or({message:s,statusCode:e,body:o}){let t=[];return s!=null&&t.push(s),e!=null&&t.push(`Status code: ${e.toString()}`),o!=null&&t.push(`Body: ${A(o,void 0,2)}`),t.join(`
|
|
2
|
+
`)}var Ye=class extends Error{constructor(e,o){super(e),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,o?.cause!=null&&(this.cause=o.cause)}};var en=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},bt="apiKey",Rt="DEEPGRAM_API_KEY",on="Authorization",we=class s{constructor(e){this.options=e}static canCreate(e){var o;return e?.[bt]!=null||((o=process.env)===null||o===void 0?void 0:o[Rt])!=null}getAuthRequest(){return en(this,arguments,void 0,function*({endpointMetadata:e}={}){var o,t;let r=(o=yield g.get(this.options[bt]))!==null&&o!==void 0?o:(t=process.env)===null||t===void 0?void 0:t[Rt];if(r==null)throw new w({message:s.AUTH_CONFIG_ERROR_MESSAGE});return{headers:{[on]:r}}})}};(function(s){s.AUTH_SCHEME="ApiKeyAuth",s.AUTH_CONFIG_ERROR_MESSAGE=`Please provide '${bt}' when initializing the client, or set the '${Rt}' environment variable`;function e(o){return new s(o)}s.createInstance=e})(we||(we={}));function b(...s){let e={};for(let[o,t]of s.filter(r=>r!=null).flatMap(r=>Object.entries(r))){let r=o.toLowerCase();t!=null?e[r]=t:r in e&&delete e[r]}return e}function he(...s){let e={};for(let[o,t]of s.filter(r=>r!=null).flatMap(r=>Object.entries(r))){let r=o.toLowerCase();t!=null&&(e[r]=t)}return e}function X(s){let e=b({"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"@deepgram/sdk","X-Fern-SDK-Version":"5.2.1","User-Agent":"@deepgram/sdk/5.2.1","X-Fern-Runtime":Q.type,"X-Fern-Runtime-Version":Q.version},s?.headers);return Object.assign(Object.assign({},s),{logging:so.createLogger(s?.logging),headers:e})}function P(s){var e;let o=X(s),t=tn(o);return(e=o.authProvider)!==null&&e!==void 0||(o.authProvider=new we(t)),o}function tn(s){return Object.assign(Object.assign({},s),{authProvider:new We})}var R={Production:{base:"https://api.deepgram.com",production:"wss://api.deepgram.com",agent:"wss://agent.deepgram.com",agentRest:"https://agent.deepgram.com"}};function C(s,e,o,t){switch(s.reason){case"non-json":throw new w({statusCode:s.statusCode,body:s.rawBody,rawResponse:e});case"body-is-null":throw new w({statusCode:s.statusCode,rawResponse:e});case"timeout":throw new Ye(`Timeout exceeded when calling ${o} ${t}.`,{cause:s.cause});case"unknown":throw new w({message:s.errorMessage,rawResponse:e,cause:s.cause});default:throw new w({message:"Unknown error",rawResponse:e})}}var x=class extends w{constructor(e,o){super({message:"BadRequestError",statusCode:400,body:e,rawResponse:o}),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var rn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},co=class{constructor(e={}){this._options=X(e)}list(e){return E.fromPromise(this.__list(e))}__list(e){return rn(this,void 0,void 0,function*(){var o,t,r,i,a,c,u,d,n,l;let v=b((o=this._options)===null||o===void 0?void 0:o.headers,e?.headers),_=yield((t=this._options.fetcher)!==null&&t!==void 0?t:k)({url:p.join((r=yield g.get(this._options.baseUrl))!==null&&r!==void 0?r:((i=yield g.get(this._options.environment))!==null&&i!==void 0?i:R.Production).agentRest,"v1/agent/settings/think/models"),method:"GET",headers:v,queryString:p.queryBuilder().mergeAdditional(e?.queryParams).build(),timeoutMs:((u=(a=e?.timeoutInSeconds)!==null&&a!==void 0?a:(c=this._options)===null||c===void 0?void 0:c.timeoutInSeconds)!==null&&u!==void 0?u:60)*1e3,maxRetries:(d=e?.maxRetries)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.maxRetries,abortSignal:e?.abortSignal,fetchFn:(l=this._options)===null||l===void 0?void 0:l.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if(_.error.reason==="status-code")throw _.error.statusCode===400?new x(_.error.body,_.rawResponse):new w({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse});return C(_.error,_.rawResponse,"GET","/v1/agent/settings/think/models")})}};var uo=class{constructor(e={}){this._options=X(e)}get models(){var e;return(e=this._models)!==null&&e!==void 0?e:this._models=new co(this._options)}};var ho=class{constructor(e={}){this._options=X(e)}get think(){var e;return(e=this._think)!==null&&e!==void 0?e:this._think=new uo(this._options)}};var nn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},be=class{constructor(e){this.eventHandlers={},this.handleOpen=()=>{var o,t;(t=(o=this.eventHandlers).open)===null||t===void 0||t.call(o)},this.handleMessage=o=>{var t,r;let i=V(o.data);(r=(t=this.eventHandlers).message)===null||r===void 0||r.call(t,i)},this.handleClose=o=>{var t,r;(r=(t=this.eventHandlers).close)===null||r===void 0||r.call(t,o)},this.handleError=o=>{var t,r;let i=o.message;(r=(t=this.eventHandlers).error)===null||r===void 0||r.call(t,new Error(i))},this.socket=e.socket,this.socket.addEventListener("open",this.handleOpen),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose),this.socket.addEventListener("error",this.handleError)}get readyState(){return this.socket.readyState}on(e,o){this.eventHandlers[e]=o}sendSettings(e){this.assertSocketIsOpen(),this.sendJson(e)}sendUpdateSpeak(e){this.assertSocketIsOpen(),this.sendJson(e)}sendInjectUserMessage(e){this.assertSocketIsOpen(),this.sendJson(e)}sendInjectAgentMessage(e){this.assertSocketIsOpen(),this.sendJson(e)}sendFunctionCallResponse(e){this.assertSocketIsOpen(),this.sendJson(e)}sendKeepAlive(e){this.assertSocketIsOpen(),this.sendJson(e)}sendUpdatePrompt(e){this.assertSocketIsOpen(),this.sendJson(e)}sendUpdateThink(e){this.assertSocketIsOpen(),this.sendJson(e)}sendMedia(e){this.assertSocketIsOpen(),this.sendBinary(e)}connect(){return this.socket.reconnect(),this.socket.addEventListener("open",this.handleOpen),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose),this.socket.addEventListener("error",this.handleError),this}close(){this.socket.close(),this.handleClose({code:1e3}),this.socket.removeEventListener("open",this.handleOpen),this.socket.removeEventListener("message",this.handleMessage),this.socket.removeEventListener("close",this.handleClose),this.socket.removeEventListener("error",this.handleError)}waitForOpen(){return nn(this,void 0,void 0,function*(){return this.socket.readyState===B.ReadyState.OPEN?this.socket:new Promise((e,o)=>{this.socket.addEventListener("open",()=>{e(this.socket)}),this.socket.addEventListener("error",t=>{o(t)})})})}assertSocketIsOpen(){if(!this.socket)throw new Error("Socket is not connected.");if(this.socket.readyState!==B.ReadyState.OPEN)throw new Error("Socket is not open.")}sendBinary(e){this.socket.send(e)}sendJson(e){let o=A(e);this.socket.send(o)}};var sn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Re=class{constructor(e={}){this._options=X(e)}get settings(){var e;return(e=this._settings)!==null&&e!==void 0?e:this._settings=new ho(this._options)}connect(e){return sn(this,void 0,void 0,function*(){var o,t,r;let{protocols:i,queryParams:a,headers:c,debug:u,reconnectAttempts:d,connectionTimeoutInSeconds:n,abortSignal:l}=e,v=b((o=this._options)===null||o===void 0?void 0:o.headers,he({Authorization:e.Authorization}),c),_=new B({url:p.join((t=yield g.get(this._options.baseUrl))!==null&&t!==void 0?t:((r=yield g.get(this._options.environment))!==null&&r!==void 0?r:R.Production).agent,"/v1/agent/converse"),protocols:i??[],queryParameters:a??{},headers:v,options:{debug:u??!1,maxRetries:d??30,connectionTimeout:n!=null?n*1e3:void 0},abortSignal:l});return new be({socket:_})})}};var Se=class{constructor(e={}){this._options=X(e)}get v1(){var e;return(e=this._v1)!==null&&e!==void 0?e:this._v1=new Re(this._options)}};var an=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},mo=class{constructor(e={}){this._options=P(e)}grant(e={},o){return E.fromPromise(this.__grant(e,o))}__grant(){return an(this,arguments,void 0,function*(e={},o){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,"v1/auth/grant"),method:"POST",headers:f,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),requestType:"json",body:e,timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"POST","/v1/auth/grant")})}};var vo=class{constructor(e={}){this._options=P(e)}get tokens(){var e;return(e=this._tokens)!==null&&e!==void 0?e:this._tokens=new mo(this._options)}};var _o=class{constructor(e={}){this._options=P(e)}get v1(){var e;return(e=this._v1)!==null&&e!==void 0?e:this._v1=new vo(this._options)}};var lr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},dn=function(s,e){var o={};for(var t in s)Object.prototype.hasOwnProperty.call(s,t)&&e.indexOf(t)<0&&(o[t]=s[t]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(s);r<t.length;r++)e.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(s,t[r])&&(o[t[r]]=s[t[r]]);return o},po=class{constructor(e={}){this._options=P(e)}transcribeUrl(e,o){return E.fromPromise(this.__transcribeUrl(e,o))}__transcribeUrl(e,o){return lr(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let{callback:_,callback_method:f,extra:m,sentiment:h,summarize:y,tag:T,topics:S,custom_topic:j,custom_topic_mode:I,intents:z,custom_intent:J,custom_intent_mode:W,detect_entities:D,detect_language:U,diarize:L,diarize_model:N,dictation:$,encoding:O,filler_words:se,keyterm:ee,keywords:re,language:me,measurements:ve,model:ne,multichannel:ie,numerals:ae,paragraphs:_e,profanity_filter:de,punctuate:le,redact:pe,replace:Ae,search:Ie,smart_format:Le,utterances:Me,utt_split:Be,version:ge,mip_opt_out:He}=e,Ue=dn(e,["callback","callback_method","extra","sentiment","summarize","tag","topics","custom_topic","custom_topic_mode","intents","custom_intent","custom_intent_mode","detect_entities","detect_language","diarize","diarize_model","dictation","encoding","filler_words","keyterm","keywords","language","measurements","model","multichannel","numerals","paragraphs","profanity_filter","punctuate","redact","replace","search","smart_format","utterances","utt_split","version","mip_opt_out"]),Fe={callback:_,callback_method:f??void 0,extra:m,sentiment:h,summarize:y??void 0,tag:T,topics:S,custom_topic:j,custom_topic_mode:I??void 0,intents:z,custom_intent:J,custom_intent_mode:W??void 0,detect_entities:D,detect_language:U,diarize:L,diarize_model:N??void 0,dictation:$,encoding:O??void 0,filler_words:se,keyterm:ee,keywords:re,language:me,measurements:ve,model:ne??void 0,multichannel:ie,numerals:ae,paragraphs:_e,profanity_filter:de,punctuate:le,redact:pe,replace:Ae,search:Ie,smart_format:Le,utterances:Me,utt_split:Be,version:ge??void 0,mip_opt_out:He},Ne=yield this._options.authProvider.getAuthRequest(),ze=b(Ne.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),K=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,"v1/listen"),method:"POST",headers:ze,contentType:"application/json",queryString:p.queryBuilder().addMany(Fe).mergeAdditional(o?.queryParams).build(),requestType:"json",body:Ue,timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(K.ok)return{data:K.body,rawResponse:K.rawResponse};if(K.error.reason==="status-code")throw K.error.statusCode===400?new x(K.error.body,K.rawResponse):new w({statusCode:K.error.statusCode,body:K.error.body,rawResponse:K.rawResponse});return C(K.error,K.rawResponse,"POST","/v1/listen")})}transcribeFile(e,o,t){return E.fromPromise(this.__transcribeFile(e,o,t))}__transcribeFile(e,o,t){return lr(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f={callback:o.callback,callback_method:o.callback_method!=null?o.callback_method:void 0,extra:o.extra,sentiment:o.sentiment,summarize:o.summarize!=null?o.summarize:void 0,tag:o.tag,topics:o.topics,custom_topic:o.custom_topic,custom_topic_mode:o.custom_topic_mode!=null?o.custom_topic_mode:void 0,intents:o.intents,custom_intent:o.custom_intent,custom_intent_mode:o.custom_intent_mode!=null?o.custom_intent_mode:void 0,detect_entities:o.detect_entities,detect_language:o.detect_language,diarize:o.diarize,diarize_model:o.diarize_model!=null?o.diarize_model:void 0,dictation:o.dictation,encoding:o.encoding!=null?o.encoding:void 0,filler_words:o.filler_words,keyterm:o.keyterm,keywords:o.keywords,language:o.language,measurements:o.measurements,model:o.model!=null?o.model:void 0,multichannel:o.multichannel,numerals:o.numerals,paragraphs:o.paragraphs,profanity_filter:o.profanity_filter,punctuate:o.punctuate,redact:o.redact,replace:o.replace,search:o.search,smart_format:o.smart_format,utterances:o.utterances,utt_split:o.utt_split,version:o.version!=null?o.version:void 0,mip_opt_out:o.mip_opt_out},m=yield io.toBinaryUploadRequest(e),h=yield this._options.authProvider.getAuthRequest(),y=b(h.headers,(r=this._options)===null||r===void 0?void 0:r.headers,m.headers,t?.headers),T=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,"v1/listen"),method:"POST",headers:y,contentType:"application/octet-stream",queryString:p.queryBuilder().addMany(f).mergeAdditional(t?.queryParams).build(),requestType:"bytes",duplex:"half",body:m.body,timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(T.ok)return{data:T.body,rawResponse:T.rawResponse};if(T.error.reason==="status-code")throw T.error.statusCode===400?new x(T.error.body,T.rawResponse):new w({statusCode:T.error.statusCode,body:T.error.body,rawResponse:T.rawResponse});return C(T.error,T.rawResponse,"POST","/v1/listen")})}};var ln=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Ee=class{constructor(e){this.eventHandlers={},this.handleOpen=()=>{var o,t;(t=(o=this.eventHandlers).open)===null||t===void 0||t.call(o)},this.handleMessage=o=>{var t,r;let i=V(o.data);(r=(t=this.eventHandlers).message)===null||r===void 0||r.call(t,i)},this.handleClose=o=>{var t,r;(r=(t=this.eventHandlers).close)===null||r===void 0||r.call(t,o)},this.handleError=o=>{var t,r;let i=o.message;(r=(t=this.eventHandlers).error)===null||r===void 0||r.call(t,new Error(i))},this.socket=e.socket,this.socket.addEventListener("open",this.handleOpen),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose),this.socket.addEventListener("error",this.handleError)}get readyState(){return this.socket.readyState}on(e,o){this.eventHandlers[e]=o}sendMedia(e){this.assertSocketIsOpen(),this.sendBinary(e)}sendFinalize(e){this.assertSocketIsOpen(),this.sendJson(e)}sendCloseStream(e){this.assertSocketIsOpen(),this.sendJson(e)}sendKeepAlive(e){this.assertSocketIsOpen(),this.sendJson(e)}connect(){return this.socket.reconnect(),this.socket.addEventListener("open",this.handleOpen),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose),this.socket.addEventListener("error",this.handleError),this}close(){this.socket.close(),this.handleClose({code:1e3}),this.socket.removeEventListener("open",this.handleOpen),this.socket.removeEventListener("message",this.handleMessage),this.socket.removeEventListener("close",this.handleClose),this.socket.removeEventListener("error",this.handleError)}waitForOpen(){return ln(this,void 0,void 0,function*(){return this.socket.readyState===B.ReadyState.OPEN?this.socket:new Promise((e,o)=>{this.socket.addEventListener("open",()=>{e(this.socket)}),this.socket.addEventListener("error",t=>{o(t)})})})}assertSocketIsOpen(){if(!this.socket)throw new Error("Socket is not connected.");if(this.socket.readyState!==B.ReadyState.OPEN)throw new Error("Socket is not open.")}sendBinary(e){this.socket.send(e)}sendJson(e){let o=A(e);this.socket.send(o)}};var cn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},xe=class{constructor(e={}){this._options=P(e)}get media(){var e;return(e=this._media)!==null&&e!==void 0?e:this._media=new po(this._options)}connect(e){return cn(this,void 0,void 0,function*(){var o,t,r;let{callback:i,callback_method:a,channels:c,detect_entities:u,diarize:d,dictation:n,encoding:l,endpointing:v,extra:_,interim_results:f,keyterm:m,keywords:h,language:y,mip_opt_out:T,model:S,multichannel:j,numerals:I,profanity_filter:z,punctuate:J,redact:W,replace:D,sample_rate:U,search:L,smart_format:N,tag:$,utterance_end_ms:O,vad_events:se,version:ee,protocols:re,queryParams:me,headers:ve,debug:ne,reconnectAttempts:ie,connectionTimeoutInSeconds:ae,abortSignal:_e}=e,de={callback:i!=null?typeof i=="string"?i:A(i):void 0,callback_method:a??void 0,channels:c!=null?typeof c=="string"?c:A(c):void 0,detect_entities:u??void 0,diarize:d??void 0,dictation:n??void 0,encoding:l??void 0,endpointing:v!=null?typeof v=="string"?v:A(v):void 0,extra:_!=null?typeof _=="string"?_:A(_):void 0,interim_results:f??void 0,keyterm:m!=null?typeof m=="string"?m:A(m):void 0,keywords:h!=null?typeof h=="string"?h:A(h):void 0,language:y!=null?typeof y=="string"?y:A(y):void 0,mip_opt_out:T!=null?typeof T=="string"?T:A(T):void 0,model:S,multichannel:j??void 0,numerals:I??void 0,profanity_filter:z??void 0,punctuate:J??void 0,redact:W??void 0,replace:D!=null?typeof D=="string"?D:A(D):void 0,sample_rate:U!=null?typeof U=="string"?U:A(U):void 0,search:L!=null?typeof L=="string"?L:A(L):void 0,smart_format:N??void 0,tag:$!=null?typeof $=="string"?$:A($):void 0,utterance_end_ms:O!=null?typeof O=="string"?O:A(O):void 0,vad_events:se??void 0,version:ee!=null?typeof ee=="string"?ee:A(ee):void 0},le=b((o=this._options)===null||o===void 0?void 0:o.headers,he({Authorization:e.Authorization}),ve),pe=new B({url:p.join((t=yield g.get(this._options.baseUrl))!==null&&t!==void 0?t:((r=yield g.get(this._options.environment))!==null&&r!==void 0?r:R.Production).production,"/v1/listen"),protocols:re??[],queryParameters:Object.assign(Object.assign({},de),me),headers:le,options:{debug:ne??!1,maxRetries:ie??30,connectionTimeout:ae!=null?ae*1e3:void 0},abortSignal:_e});return new Ee({socket:pe})})}};var un=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},ke=class{constructor(e){this.eventHandlers={},this.handleOpen=()=>{var o,t;(t=(o=this.eventHandlers).open)===null||t===void 0||t.call(o)},this.handleMessage=o=>{var t,r;let i=V(o.data);(r=(t=this.eventHandlers).message)===null||r===void 0||r.call(t,i)},this.handleClose=o=>{var t,r;(r=(t=this.eventHandlers).close)===null||r===void 0||r.call(t,o)},this.handleError=o=>{var t,r;let i=o.message;(r=(t=this.eventHandlers).error)===null||r===void 0||r.call(t,new Error(i))},this.socket=e.socket,this.socket.addEventListener("open",this.handleOpen),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose),this.socket.addEventListener("error",this.handleError)}get readyState(){return this.socket.readyState}on(e,o){this.eventHandlers[e]=o}sendMedia(e){this.assertSocketIsOpen(),this.sendBinary(e)}sendCloseStream(e){this.assertSocketIsOpen(),this.sendJson(e)}sendConfigure(e){this.assertSocketIsOpen(),this.sendJson(e)}connect(){return this.socket.reconnect(),this.socket.addEventListener("open",this.handleOpen),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose),this.socket.addEventListener("error",this.handleError),this}close(){this.socket.close(),this.handleClose({code:1e3}),this.socket.removeEventListener("open",this.handleOpen),this.socket.removeEventListener("message",this.handleMessage),this.socket.removeEventListener("close",this.handleClose),this.socket.removeEventListener("error",this.handleError)}waitForOpen(){return un(this,void 0,void 0,function*(){return this.socket.readyState===B.ReadyState.OPEN?this.socket:new Promise((e,o)=>{this.socket.addEventListener("open",()=>{e(this.socket)}),this.socket.addEventListener("error",t=>{o(t)})})})}assertSocketIsOpen(){if(!this.socket)throw new Error("Socket is not connected.");if(this.socket.readyState!==B.ReadyState.OPEN)throw new Error("Socket is not open.")}sendBinary(e){this.socket.send(e)}sendJson(e){let o=A(e);this.socket.send(o)}};var hn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Pe=class{constructor(e={}){this._options=X(e)}connect(e){return hn(this,void 0,void 0,function*(){var o,t,r;let{model:i,encoding:a,sample_rate:c,eager_eot_threshold:u,eot_threshold:d,eot_timeout_ms:n,keyterm:l,language_hint:v,mip_opt_out:_,tag:f,protocols:m,queryParams:h,headers:y,debug:T,reconnectAttempts:S,connectionTimeoutInSeconds:j,abortSignal:I}=e,z={model:i,encoding:a??void 0,sample_rate:c!=null?typeof c=="string"?c:A(c):void 0,eager_eot_threshold:u!=null?typeof u=="string"?u:A(u):void 0,eot_threshold:d!=null?typeof d=="string"?d:A(d):void 0,eot_timeout_ms:n!=null?typeof n=="string"?n:A(n):void 0,keyterm:Array.isArray(l)?l.map(D=>typeof D=="string"?D:A(D)):l!=null?typeof l=="string"?l:A(l):void 0,language_hint:Array.isArray(v)?v.map(D=>typeof D=="string"?D:A(D)):v!=null?typeof v=="string"?v:A(v):void 0,mip_opt_out:_!=null?typeof _=="string"?_:A(_):void 0,tag:f!=null?typeof f=="string"?f:A(f):void 0},J=b((o=this._options)===null||o===void 0?void 0:o.headers,he({Authorization:e.Authorization}),y),W=new B({url:p.join((t=yield g.get(this._options.baseUrl))!==null&&t!==void 0?t:((r=yield g.get(this._options.environment))!==null&&r!==void 0?r:R.Production).production,"/v2/listen"),protocols:m??[],queryParameters:Object.assign(Object.assign({},z),h),headers:J,options:{debug:T??!1,maxRetries:S??30,connectionTimeout:j!=null?j*1e3:void 0},abortSignal:I});return new ke({socket:W})})}};var Ce=class{constructor(e={}){this._options=P(e)}get v1(){var e;return(e=this._v1)!==null&&e!==void 0?e:this._v1=new xe(this._options)}get v2(){var e;return(e=this._v2)!==null&&e!==void 0?e:this._v2=new Pe(this._options)}};var cr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},fo=class{constructor(e={}){this._options=P(e)}list(e={},o){return E.fromPromise(this.__list(e,o))}__list(){return cr(this,arguments,void 0,function*(e={},o){var t,r,i,a,c,u,d,n,l,v;let{include_outdated:_}=e,f={include_outdated:_},m=yield this._options.authProvider.getAuthRequest(),h=b(m.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),y=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,"v1/models"),method:"GET",headers:h,queryString:p.queryBuilder().addMany(f).mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if(y.error.reason==="status-code")throw y.error.statusCode===400?new x(y.error.body,y.rawResponse):new w({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse});return C(y.error,y.rawResponse,"GET","/v1/models")})}get(e,o){return E.fromPromise(this.__get(e,o))}__get(e,o){return cr(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/models/${p.encodePathParam(e)}`),method:"GET",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"GET","/v1/models/{model_id}")})}};var ur=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},go=class{constructor(e={}){this._options=P(e)}list(e,o){return E.fromPromise(this.__list(e,o))}__list(e,o){return ur(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/projects/${p.encodePathParam(e)}/balances`),method:"GET",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"GET","/v1/projects/{project_id}/balances")})}get(e,o,t){return E.fromPromise(this.__get(e,o,t))}__get(e,o,t){return ur(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/balances/${p.encodePathParam(o)}`),method:"GET",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"GET","/v1/projects/{project_id}/balances/{balance_id}")})}};var mn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},yo=class{constructor(e={}){this._options=P(e)}list(e,o={},t){return E.fromPromise(this.__list(e,o,t))}__list(e){return mn(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{start:m,end:h,accessor:y,deployment:T,tag:S,line_item:j,grouping:I}=t,z={start:m,end:h,accessor:y,deployment:T??void 0,tag:S,line_item:j,grouping:Array.isArray(I)?I.map(U=>U):I??void 0},J=yield this._options.authProvider.getAuthRequest(),W=b(J.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),D=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/billing/breakdown`),method:"GET",headers:W,queryString:p.queryBuilder().addMany(z).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(D.ok)return{data:D.body,rawResponse:D.rawResponse};if(D.error.reason==="status-code")throw D.error.statusCode===400?new x(D.error.body,D.rawResponse):new w({statusCode:D.error.statusCode,body:D.error.body,rawResponse:D.rawResponse});return C(D.error,D.rawResponse,"GET","/v1/projects/{project_id}/billing/breakdown")})}};var vn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},wo=class{constructor(e={}){this._options=P(e)}list(e,o={},t){return E.fromPromise(this.__list(e,o,t))}__list(e){return vn(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{start:m,end:h}=t,y={start:m,end:h},T=yield this._options.authProvider.getAuthRequest(),S=b(T.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),j=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/billing/fields`),method:"GET",headers:S,queryString:p.queryBuilder().addMany(y).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(j.ok)return{data:j.body,rawResponse:j.rawResponse};if(j.error.reason==="status-code")throw j.error.statusCode===400?new x(j.error.body,j.rawResponse):new w({statusCode:j.error.statusCode,body:j.error.body,rawResponse:j.rawResponse});return C(j.error,j.rawResponse,"GET","/v1/projects/{project_id}/billing/fields")})}};var _n=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},bo=class{constructor(e={}){this._options=P(e)}list(e,o={},t){return E.fromPromise(this.__list(e,o,t))}__list(e){return _n(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{limit:m}=t,h={limit:m},y=yield this._options.authProvider.getAuthRequest(),T=b(y.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),S=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/purchases`),method:"GET",headers:T,queryString:p.queryBuilder().addMany(h).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(S.ok)return{data:S.body,rawResponse:S.rawResponse};if(S.error.reason==="status-code")throw S.error.statusCode===400?new x(S.error.body,S.rawResponse):new w({statusCode:S.error.statusCode,body:S.error.body,rawResponse:S.rawResponse});return C(S.error,S.rawResponse,"GET","/v1/projects/{project_id}/purchases")})}};var Ro=class{constructor(e={}){this._options=P(e)}get balances(){var e;return(e=this._balances)!==null&&e!==void 0?e:this._balances=new go(this._options)}get breakdown(){var e;return(e=this._breakdown)!==null&&e!==void 0?e:this._breakdown=new yo(this._options)}get fields(){var e;return(e=this._fields)!==null&&e!==void 0?e:this._fields=new wo(this._options)}get purchases(){var e;return(e=this._purchases)!==null&&e!==void 0?e:this._purchases=new bo(this._options)}};var So=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Eo=class{constructor(e={}){this._options=P(e)}list(e,o={},t){return E.fromPromise(this.__list(e,o,t))}__list(e){return So(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{status:m}=t,h={status:m??void 0},y=yield this._options.authProvider.getAuthRequest(),T=b(y.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),S=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/keys`),method:"GET",headers:T,queryString:p.queryBuilder().addMany(h).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(S.ok)return{data:S.body,rawResponse:S.rawResponse};if(S.error.reason==="status-code")throw S.error.statusCode===400?new x(S.error.body,S.rawResponse):new w({statusCode:S.error.statusCode,body:S.error.body,rawResponse:S.rawResponse});return C(S.error,S.rawResponse,"GET","/v1/projects/{project_id}/keys")})}create(e,o,t){return E.fromPromise(this.__create(e,o,t))}__create(e,o,t){return So(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/keys`),method:"POST",headers:m,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),requestType:"json",body:o,timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"POST","/v1/projects/{project_id}/keys")})}get(e,o,t){return E.fromPromise(this.__get(e,o,t))}__get(e,o,t){return So(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/keys/${p.encodePathParam(o)}`),method:"GET",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"GET","/v1/projects/{project_id}/keys/{key_id}")})}delete(e,o,t){return E.fromPromise(this.__delete(e,o,t))}__delete(e,o,t){return So(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/keys/${p.encodePathParam(o)}`),method:"DELETE",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"DELETE","/v1/projects/{project_id}/keys/{key_id}")})}};var St=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},xo=class{constructor(e={}){this._options=P(e)}list(e,o){return E.fromPromise(this.__list(e,o))}__list(e,o){return St(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/projects/${p.encodePathParam(e)}/invites`),method:"GET",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"GET","/v1/projects/{project_id}/invites")})}create(e,o,t){return E.fromPromise(this.__create(e,o,t))}__create(e,o,t){return St(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/invites`),method:"POST",headers:m,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),requestType:"json",body:o,timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"POST","/v1/projects/{project_id}/invites")})}delete(e,o,t){return E.fromPromise(this.__delete(e,o,t))}__delete(e,o,t){return St(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/invites/${p.encodePathParam(o)}`),method:"DELETE",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"DELETE","/v1/projects/{project_id}/invites/{email}")})}};var hr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},ko=class{constructor(e={}){this._options=P(e)}list(e,o,t){return E.fromPromise(this.__list(e,o,t))}__list(e,o,t){return hr(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/members/${p.encodePathParam(o)}/scopes`),method:"GET",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"GET","/v1/projects/{project_id}/members/{member_id}/scopes")})}update(e,o,t,r){return E.fromPromise(this.__update(e,o,t,r))}__update(e,o,t,r){return hr(this,void 0,void 0,function*(){var i,a,c,u,d,n,l,v,_,f;let m=yield this._options.authProvider.getAuthRequest(),h=b(m.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),y=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(e)}/members/${p.encodePathParam(o)}/scopes`),method:"PUT",headers:h,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(r?.queryParams).build(),requestType:"json",body:t,timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if(y.error.reason==="status-code")throw y.error.statusCode===400?new x(y.error.body,y.rawResponse):new w({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse});return C(y.error,y.rawResponse,"PUT","/v1/projects/{project_id}/members/{member_id}/scopes")})}};var mr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Po=class{constructor(e={}){this._options=P(e)}get invites(){var e;return(e=this._invites)!==null&&e!==void 0?e:this._invites=new xo(this._options)}get scopes(){var e;return(e=this._scopes)!==null&&e!==void 0?e:this._scopes=new ko(this._options)}list(e,o){return E.fromPromise(this.__list(e,o))}__list(e,o){return mr(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/projects/${p.encodePathParam(e)}/members`),method:"GET",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"GET","/v1/projects/{project_id}/members")})}delete(e,o,t){return E.fromPromise(this.__delete(e,o,t))}__delete(e,o,t){return mr(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/members/${p.encodePathParam(o)}`),method:"DELETE",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"DELETE","/v1/projects/{project_id}/members/{member_id}")})}};var vr=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Co=class{constructor(e={}){this._options=P(e)}list(e,o={},t){return E.fromPromise(this.__list(e,o,t))}__list(e){return vr(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{include_outdated:m}=t,h={include_outdated:m},y=yield this._options.authProvider.getAuthRequest(),T=b(y.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),S=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/models`),method:"GET",headers:T,queryString:p.queryBuilder().addMany(h).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(S.ok)return{data:S.body,rawResponse:S.rawResponse};if(S.error.reason==="status-code")throw S.error.statusCode===400?new x(S.error.body,S.rawResponse):new w({statusCode:S.error.statusCode,body:S.error.body,rawResponse:S.rawResponse});return C(S.error,S.rawResponse,"GET","/v1/projects/{project_id}/models")})}get(e,o,t){return E.fromPromise(this.__get(e,o,t))}__get(e,o,t){return vr(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/models/${p.encodePathParam(o)}`),method:"GET",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"GET","/v1/projects/{project_id}/models/{model_id}")})}};var _r=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},jo=class{constructor(e={}){this._options=P(e)}list(e,o={},t){return E.fromPromise(this.__list(e,o,t))}__list(e){return _r(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{start:m,end:h,limit:y,page:T,accessor:S,request_id:j,deployment:I,endpoint:z,method:J,status:W}=t,D={start:m??void 0,end:h??void 0,limit:y,page:T,accessor:S,request_id:j,deployment:I??void 0,endpoint:z??void 0,method:J??void 0,status:W??void 0},U=yield this._options.authProvider.getAuthRequest(),L=b(U.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),N=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/requests`),method:"GET",headers:L,queryString:p.queryBuilder().addMany(D).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(N.ok)return{data:N.body,rawResponse:N.rawResponse};if(N.error.reason==="status-code")throw N.error.statusCode===400?new x(N.error.body,N.rawResponse):new w({statusCode:N.error.statusCode,body:N.error.body,rawResponse:N.rawResponse});return C(N.error,N.rawResponse,"GET","/v1/projects/{project_id}/requests")})}get(e,o,t){return E.fromPromise(this.__get(e,o,t))}__get(e,o,t){return _r(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/requests/${p.encodePathParam(o)}`),method:"GET",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"GET","/v1/projects/{project_id}/requests/{request_id}")})}};var pn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},To=class{constructor(e={}){this._options=P(e)}get(e,o={},t){return E.fromPromise(this.__get(e,o,t))}__get(e){return pn(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{start:m,end:h,grouping:y,accessor:T,alternatives:S,callback_method:j,callback:I,channels:z,custom_intent_mode:J,custom_intent:W,custom_topic_mode:D,custom_topic:U,deployment:L,detect_entities:N,detect_language:$,diarize:O,dictation:se,encoding:ee,endpoint:re,extra:me,filler_words:ve,intents:ne,keyterm:ie,keywords:ae,language:_e,measurements:de,method:le,model:pe,multichannel:Ae,numerals:Ie,paragraphs:Le,profanity_filter:Me,punctuate:Be,redact:ge,replace:He,sample_rate:Ue,search:Fe,sentiment:Ne,smart_format:ze,summarize:K,tag:Oo,topics:et,utt_split:ot,utterances:tt,version:rt}=t,nt={start:m,end:h,grouping:y??void 0,accessor:T,alternatives:S,callback_method:j,callback:I,channels:z,custom_intent_mode:J,custom_intent:W,custom_topic_mode:D,custom_topic:U,deployment:L??void 0,detect_entities:N,detect_language:$,diarize:O,dictation:se,encoding:ee,endpoint:re??void 0,extra:me,filler_words:ve,intents:ne,keyterm:ie,keywords:ae,language:_e,measurements:de,method:le??void 0,model:pe,multichannel:Ae,numerals:Ie,paragraphs:Le,profanity_filter:Me,punctuate:Be,redact:ge,replace:He,sample_rate:Ue,search:Fe,sentiment:Ne,smart_format:ze,summarize:K,tag:Oo,topics:et,utt_split:ot,utterances:tt,version:rt},it=yield this._options.authProvider.getAuthRequest(),Y=b(it.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),q=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/usage/breakdown`),method:"GET",headers:Y,queryString:p.queryBuilder().addMany(nt).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(q.ok)return{data:q.body,rawResponse:q.rawResponse};if(q.error.reason==="status-code")throw q.error.statusCode===400?new x(q.error.body,q.rawResponse):new w({statusCode:q.error.statusCode,body:q.error.body,rawResponse:q.rawResponse});return C(q.error,q.rawResponse,"GET","/v1/projects/{project_id}/usage/breakdown")})}};var fn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Do=class{constructor(e={}){this._options=P(e)}list(e,o={},t){return E.fromPromise(this.__list(e,o,t))}__list(e){return fn(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{start:m,end:h}=t,y={start:m,end:h},T=yield this._options.authProvider.getAuthRequest(),S=b(T.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),j=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/usage/fields`),method:"GET",headers:S,queryString:p.queryBuilder().addMany(y).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(j.ok)return{data:j.body,rawResponse:j.rawResponse};if(j.error.reason==="status-code")throw j.error.statusCode===400?new x(j.error.body,j.rawResponse):new w({statusCode:j.error.statusCode,body:j.error.body,rawResponse:j.rawResponse});return C(j.error,j.rawResponse,"GET","/v1/projects/{project_id}/usage/fields")})}};var gn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Ao=class{constructor(e={}){this._options=P(e)}get breakdown(){var e;return(e=this._breakdown)!==null&&e!==void 0?e:this._breakdown=new To(this._options)}get fields(){var e;return(e=this._fields)!==null&&e!==void 0?e:this._fields=new Do(this._options)}get(e,o={},t){return E.fromPromise(this.__get(e,o,t))}__get(e){return gn(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{start:m,end:h,accessor:y,alternatives:T,callback_method:S,callback:j,channels:I,custom_intent_mode:z,custom_intent:J,custom_topic_mode:W,custom_topic:D,deployment:U,detect_entities:L,detect_language:N,diarize:$,dictation:O,encoding:se,endpoint:ee,extra:re,filler_words:me,intents:ve,keyterm:ne,keywords:ie,language:ae,measurements:_e,method:de,model:le,multichannel:pe,numerals:Ae,paragraphs:Ie,profanity_filter:Le,punctuate:Me,redact:Be,replace:ge,sample_rate:He,search:Ue,sentiment:Fe,smart_format:Ne,summarize:ze,tag:K,topics:Oo,utt_split:et,utterances:ot,version:tt}=t,rt={start:m,end:h,accessor:y,alternatives:T,callback_method:S,callback:j,channels:I,custom_intent_mode:z,custom_intent:J,custom_topic_mode:W,custom_topic:D,deployment:U??void 0,detect_entities:L,detect_language:N,diarize:$,dictation:O,encoding:se,endpoint:ee??void 0,extra:re,filler_words:me,intents:ve,keyterm:ne,keywords:ie,language:ae,measurements:_e,method:de??void 0,model:le,multichannel:pe,numerals:Ae,paragraphs:Ie,profanity_filter:Le,punctuate:Me,redact:Be,replace:ge,sample_rate:He,search:Ue,sentiment:Fe,smart_format:Ne,summarize:ze,tag:K,topics:Oo,utt_split:et,utterances:ot,version:tt},nt=yield this._options.authProvider.getAuthRequest(),it=b(nt.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),Y=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/usage`),method:"GET",headers:it,queryString:p.queryBuilder().addMany(rt).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(Y.ok)return{data:Y.body,rawResponse:Y.rawResponse};if(Y.error.reason==="status-code")throw Y.error.statusCode===400?new x(Y.error.body,Y.rawResponse):new w({statusCode:Y.error.statusCode,body:Y.error.body,rawResponse:Y.rawResponse});return C(Y.error,Y.rawResponse,"GET","/v1/projects/{project_id}/usage")})}};var Qe=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Io=class{constructor(e={}){this._options=P(e)}get keys(){var e;return(e=this._keys)!==null&&e!==void 0?e:this._keys=new Eo(this._options)}get members(){var e;return(e=this._members)!==null&&e!==void 0?e:this._members=new Po(this._options)}get models(){var e;return(e=this._models)!==null&&e!==void 0?e:this._models=new Co(this._options)}get requests(){var e;return(e=this._requests)!==null&&e!==void 0?e:this._requests=new jo(this._options)}get usage(){var e;return(e=this._usage)!==null&&e!==void 0?e:this._usage=new Ao(this._options)}get billing(){var e;return(e=this._billing)!==null&&e!==void 0?e:this._billing=new Ro(this._options)}list(e){return E.fromPromise(this.__list(e))}__list(e){return Qe(this,void 0,void 0,function*(){var o,t,r,i,a,c,u,d,n,l;let v=yield this._options.authProvider.getAuthRequest(),_=b(v.headers,(o=this._options)===null||o===void 0?void 0:o.headers,e?.headers),f=yield((t=this._options.fetcher)!==null&&t!==void 0?t:k)({url:p.join((r=yield g.get(this._options.baseUrl))!==null&&r!==void 0?r:((i=yield g.get(this._options.environment))!==null&&i!==void 0?i:R.Production).base,"v1/projects"),method:"GET",headers:_,queryString:p.queryBuilder().mergeAdditional(e?.queryParams).build(),timeoutMs:((u=(a=e?.timeoutInSeconds)!==null&&a!==void 0?a:(c=this._options)===null||c===void 0?void 0:c.timeoutInSeconds)!==null&&u!==void 0?u:60)*1e3,maxRetries:(d=e?.maxRetries)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.maxRetries,abortSignal:e?.abortSignal,fetchFn:(l=this._options)===null||l===void 0?void 0:l.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if(f.error.reason==="status-code")throw f.error.statusCode===400?new x(f.error.body,f.rawResponse):new w({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse});return C(f.error,f.rawResponse,"GET","/v1/projects")})}get(e,o={},t){return E.fromPromise(this.__get(e,o,t))}__get(e){return Qe(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{limit:m,page:h}=t,y={limit:m,page:h},T=yield this._options.authProvider.getAuthRequest(),S=b(T.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),j=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}`),method:"GET",headers:S,queryString:p.queryBuilder().addMany(y).mergeAdditional(r?.queryParams).build(),timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(j.ok)return{data:j.body,rawResponse:j.rawResponse};if(j.error.reason==="status-code")throw j.error.statusCode===400?new x(j.error.body,j.rawResponse):new w({statusCode:j.error.statusCode,body:j.error.body,rawResponse:j.rawResponse});return C(j.error,j.rawResponse,"GET","/v1/projects/{project_id}")})}delete(e,o){return E.fromPromise(this.__delete(e,o))}__delete(e,o){return Qe(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/projects/${p.encodePathParam(e)}`),method:"DELETE",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"DELETE","/v1/projects/{project_id}")})}update(e,o={},t){return E.fromPromise(this.__update(e,o,t))}__update(e){return Qe(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let m=yield this._options.authProvider.getAuthRequest(),h=b(m.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),y=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}`),method:"PATCH",headers:h,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(r?.queryParams).build(),requestType:"json",body:t,timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if(y.error.reason==="status-code")throw y.error.statusCode===400?new x(y.error.body,y.rawResponse):new w({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse});return C(y.error,y.rawResponse,"PATCH","/v1/projects/{project_id}")})}leave(e,o){return E.fromPromise(this.__leave(e,o))}__leave(e,o){return Qe(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/projects/${p.encodePathParam(e)}/leave`),method:"DELETE",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"DELETE","/v1/projects/{project_id}/leave")})}};var Lo=class{constructor(e={}){this._options=P(e)}get models(){var e;return(e=this._models)!==null&&e!==void 0?e:this._models=new fo(this._options)}get projects(){var e;return(e=this._projects)!==null&&e!==void 0?e:this._projects=new Io(this._options)}};var Mo=class{constructor(e={}){this._options=P(e)}get v1(){var e;return(e=this._v1)!==null&&e!==void 0?e:this._v1=new Lo(this._options)}};var yn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Bo=class{constructor(e={}){this._options=P(e)}analyze(e,o){return E.fromPromise(this.__analyze(e,o))}__analyze(e,o){return yn(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let{callback:_,callback_method:f,sentiment:m,summarize:h,tag:y,topics:T,custom_topic:S,custom_topic_mode:j,intents:I,custom_intent:z,custom_intent_mode:J,language:W,body:D}=e,U={callback:_,callback_method:f??void 0,sentiment:m,summarize:h??void 0,tag:y,topics:T,custom_topic:S,custom_topic_mode:j??void 0,intents:I,custom_intent:z,custom_intent_mode:J??void 0,language:W},L=yield this._options.authProvider.getAuthRequest(),N=b(L.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),$=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,"v1/read"),method:"POST",headers:N,contentType:"application/json",queryString:p.queryBuilder().addMany(U).mergeAdditional(o?.queryParams).build(),requestType:"json",body:D,timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if($.ok)return{data:$.body,rawResponse:$.rawResponse};if($.error.reason==="status-code")throw $.error.statusCode===400?new x($.error.body,$.rawResponse):new w({statusCode:$.error.statusCode,body:$.error.body,rawResponse:$.rawResponse});return C($.error,$.rawResponse,"POST","/v1/read")})}};var Ho=class{constructor(e={}){this._options=P(e)}get text(){var e;return(e=this._text)!==null&&e!==void 0?e:this._text=new Bo(this._options)}};var Uo=class{constructor(e={}){this._options=P(e)}get v1(){var e;return(e=this._v1)!==null&&e!==void 0?e:this._v1=new Ho(this._options)}};var Fo=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},wn=function(s,e){var o={};for(var t in s)Object.prototype.hasOwnProperty.call(s,t)&&e.indexOf(t)<0&&(o[t]=s[t]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(s);r<t.length;r++)e.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(s,t[r])&&(o[t[r]]=s[t[r]]);return o},No=class{constructor(e={}){this._options=P(e)}list(e,o){return E.fromPromise(this.__list(e,o))}__list(e,o){return Fo(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/projects/${p.encodePathParam(e)}/self-hosted/distribution/credentials`),method:"GET",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"GET","/v1/projects/{project_id}/self-hosted/distribution/credentials")})}create(e,o={},t){return E.fromPromise(this.__create(e,o,t))}__create(e){return Fo(this,arguments,void 0,function*(o,t={},r){var i,a,c,u,d,n,l,v,_,f;let{scopes:m,provider:h}=t,y=wn(t,["scopes","provider"]),T={scopes:Array.isArray(m)?m.map(z=>z):m??void 0,provider:h??void 0},S=yield this._options.authProvider.getAuthRequest(),j=b(S.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),I=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(o)}/self-hosted/distribution/credentials`),method:"POST",headers:j,contentType:"application/json",queryString:p.queryBuilder().addMany(T).mergeAdditional(r?.queryParams).build(),requestType:"json",body:y,timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(I.ok)return{data:I.body,rawResponse:I.rawResponse};if(I.error.reason==="status-code")throw I.error.statusCode===400?new x(I.error.body,I.rawResponse):new w({statusCode:I.error.statusCode,body:I.error.body,rawResponse:I.rawResponse});return C(I.error,I.rawResponse,"POST","/v1/projects/{project_id}/self-hosted/distribution/credentials")})}get(e,o,t){return E.fromPromise(this.__get(e,o,t))}__get(e,o,t){return Fo(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/self-hosted/distribution/credentials/${p.encodePathParam(o)}`),method:"GET",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"GET","/v1/projects/{project_id}/self-hosted/distribution/credentials/{distribution_credentials_id}")})}delete(e,o,t){return E.fromPromise(this.__delete(e,o,t))}__delete(e,o,t){return Fo(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/self-hosted/distribution/credentials/${p.encodePathParam(o)}`),method:"DELETE",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"DELETE","/v1/projects/{project_id}/self-hosted/distribution/credentials/{distribution_credentials_id}")})}};var zo=class{constructor(e={}){this._options=P(e)}get distributionCredentials(){var e;return(e=this._distributionCredentials)!==null&&e!==void 0?e:this._distributionCredentials=new No(this._options)}};var Wo=class{constructor(e={}){this._options=P(e)}get v1(){var e;return(e=this._v1)!==null&&e!==void 0?e:this._v1=new zo(this._options)}};var bn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Rn=function(s,e){var o={};for(var t in s)Object.prototype.hasOwnProperty.call(s,t)&&e.indexOf(t)<0&&(o[t]=s[t]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(s);r<t.length;r++)e.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(s,t[r])&&(o[t[r]]=s[t[r]]);return o},$o=class{constructor(e={}){this._options=P(e)}generate(e,o){return E.fromPromise(this.__generate(e,o))}__generate(e,o){return bn(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let{callback:_,callback_method:f,mip_opt_out:m,tag:h,bit_rate:y,container:T,encoding:S,model:j,sample_rate:I,speed:z}=e,J=Rn(e,["callback","callback_method","mip_opt_out","tag","bit_rate","container","encoding","model","sample_rate","speed"]),W={callback:_,callback_method:f??void 0,mip_opt_out:m,tag:h,bit_rate:y,container:T??void 0,encoding:S??void 0,model:j??void 0,sample_rate:I,speed:z},D=yield this._options.authProvider.getAuthRequest(),U=b(D.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),L=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,"v1/speak"),method:"POST",headers:U,contentType:"application/json",queryString:p.queryBuilder().addMany(W).mergeAdditional(o?.queryParams).build(),requestType:"json",body:J,responseType:"binary-response",timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(L.ok)return{data:L.body,rawResponse:L.rawResponse};if(L.error.reason==="status-code")throw L.error.statusCode===400?new x(L.error.body,L.rawResponse):new w({statusCode:L.error.statusCode,body:L.error.body,rawResponse:L.rawResponse});return C(L.error,L.rawResponse,"POST","/v1/speak")})}};var Sn=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},je=class{constructor(e){this.eventHandlers={},this.handleOpen=()=>{var o,t;(t=(o=this.eventHandlers).open)===null||t===void 0||t.call(o)},this.handleMessage=o=>{var t,r;let i=V(o.data);(r=(t=this.eventHandlers).message)===null||r===void 0||r.call(t,i)},this.handleClose=o=>{var t,r;(r=(t=this.eventHandlers).close)===null||r===void 0||r.call(t,o)},this.handleError=o=>{var t,r;let i=o.message;(r=(t=this.eventHandlers).error)===null||r===void 0||r.call(t,new Error(i))},this.socket=e.socket,this.socket.addEventListener("open",this.handleOpen),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose),this.socket.addEventListener("error",this.handleError)}get readyState(){return this.socket.readyState}on(e,o){this.eventHandlers[e]=o}sendText(e){this.assertSocketIsOpen(),this.sendJson(e)}sendFlush(e){this.assertSocketIsOpen(),this.sendJson(e)}sendClear(e){this.assertSocketIsOpen(),this.sendJson(e)}sendClose(e){this.assertSocketIsOpen(),this.sendJson(e)}connect(){return this.socket.reconnect(),this.socket.addEventListener("open",this.handleOpen),this.socket.addEventListener("message",this.handleMessage),this.socket.addEventListener("close",this.handleClose),this.socket.addEventListener("error",this.handleError),this}close(){this.socket.close(),this.handleClose({code:1e3}),this.socket.removeEventListener("open",this.handleOpen),this.socket.removeEventListener("message",this.handleMessage),this.socket.removeEventListener("close",this.handleClose),this.socket.removeEventListener("error",this.handleError)}waitForOpen(){return Sn(this,void 0,void 0,function*(){return this.socket.readyState===B.ReadyState.OPEN?this.socket:new Promise((e,o)=>{this.socket.addEventListener("open",()=>{e(this.socket)}),this.socket.addEventListener("error",t=>{o(t)})})})}assertSocketIsOpen(){if(!this.socket)throw new Error("Socket is not connected.");if(this.socket.readyState!==B.ReadyState.OPEN)throw new Error("Socket is not open.")}sendBinary(e){this.socket.send(e)}sendJson(e){let o=A(e);this.socket.send(o)}};var En=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Te=class{constructor(e={}){this._options=P(e)}get audio(){var e;return(e=this._audio)!==null&&e!==void 0?e:this._audio=new $o(this._options)}connect(e){return En(this,void 0,void 0,function*(){var o,t,r;let{encoding:i,mip_opt_out:a,model:c,sample_rate:u,speed:d,protocols:n,queryParams:l,headers:v,debug:_,reconnectAttempts:f,connectionTimeoutInSeconds:m,abortSignal:h}=e,y={encoding:i??void 0,mip_opt_out:a!=null?typeof a=="string"?a:A(a):void 0,model:c??void 0,sample_rate:u??void 0,speed:d},T=b((o=this._options)===null||o===void 0?void 0:o.headers,he({Authorization:e.Authorization}),v),S=new B({url:p.join((t=yield g.get(this._options.baseUrl))!==null&&t!==void 0?t:((r=yield g.get(this._options.environment))!==null&&r!==void 0?r:R.Production).production,"/v1/speak"),protocols:n??[],queryParameters:Object.assign(Object.assign({},y),l),headers:T,options:{debug:_??!1,maxRetries:f??30,connectionTimeout:m!=null?m*1e3:void 0},abortSignal:h});return new je({socket:S})})}};var De=class{constructor(e={}){this._options=P(e)}get v1(){var e;return(e=this._v1)!==null&&e!==void 0?e:this._v1=new Te(this._options)}};var Xe=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Go=class{constructor(e={}){this._options=P(e)}list(e,o){return E.fromPromise(this.__list(e,o))}__list(e,o){return Xe(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agents`),method:"GET",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"GET","/v1/projects/{project_id}/agents")})}create(e,o,t){return E.fromPromise(this.__create(e,o,t))}__create(e,o,t){return Xe(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agents`),method:"POST",headers:m,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),requestType:"json",body:o,timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"POST","/v1/projects/{project_id}/agents")})}get(e,o,t){return E.fromPromise(this.__get(e,o,t))}__get(e,o,t){return Xe(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agents/${p.encodePathParam(o)}`),method:"GET",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"GET","/v1/projects/{project_id}/agents/{agent_id}")})}update(e,o,t,r){return E.fromPromise(this.__update(e,o,t,r))}__update(e,o,t,r){return Xe(this,void 0,void 0,function*(){var i,a,c,u,d,n,l,v,_,f;let m=yield this._options.authProvider.getAuthRequest(),h=b(m.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),y=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agents/${p.encodePathParam(o)}`),method:"PUT",headers:h,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(r?.queryParams).build(),requestType:"json",body:t,timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if(y.error.reason==="status-code")throw y.error.statusCode===400?new x(y.error.body,y.rawResponse):new w({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse});return C(y.error,y.rawResponse,"PUT","/v1/projects/{project_id}/agents/{agent_id}")})}delete(e,o,t){return E.fromPromise(this.__delete(e,o,t))}__delete(e,o,t){return Xe(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agents/${p.encodePathParam(o)}`),method:"DELETE",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"DELETE","/v1/projects/{project_id}/agents/{agent_id}")})}};var Ze=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Jo=class{constructor(e={}){this._options=P(e)}list(e,o){return E.fromPromise(this.__list(e,o))}__list(e,o){return Ze(this,void 0,void 0,function*(){var t,r,i,a,c,u,d,n,l,v;let _=yield this._options.authProvider.getAuthRequest(),f=b(_.headers,(t=this._options)===null||t===void 0?void 0:t.headers,o?.headers),m=yield((r=this._options.fetcher)!==null&&r!==void 0?r:k)({url:p.join((i=yield g.get(this._options.baseUrl))!==null&&i!==void 0?i:((a=yield g.get(this._options.environment))!==null&&a!==void 0?a:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agent-variables`),method:"GET",headers:f,queryString:p.queryBuilder().mergeAdditional(o?.queryParams).build(),timeoutMs:((d=(c=o?.timeoutInSeconds)!==null&&c!==void 0?c:(u=this._options)===null||u===void 0?void 0:u.timeoutInSeconds)!==null&&d!==void 0?d:60)*1e3,maxRetries:(n=o?.maxRetries)!==null&&n!==void 0?n:(l=this._options)===null||l===void 0?void 0:l.maxRetries,abortSignal:o?.abortSignal,fetchFn:(v=this._options)===null||v===void 0?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if(m.error.reason==="status-code")throw m.error.statusCode===400?new x(m.error.body,m.rawResponse):new w({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse});return C(m.error,m.rawResponse,"GET","/v1/projects/{project_id}/agent-variables")})}create(e,o,t){return E.fromPromise(this.__create(e,o,t))}__create(e,o,t){return Ze(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agent-variables`),method:"POST",headers:m,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),requestType:"json",body:o,timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"POST","/v1/projects/{project_id}/agent-variables")})}get(e,o,t){return E.fromPromise(this.__get(e,o,t))}__get(e,o,t){return Ze(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agent-variables/${p.encodePathParam(o)}`),method:"GET",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"GET","/v1/projects/{project_id}/agent-variables/{variable_id}")})}delete(e,o,t){return E.fromPromise(this.__delete(e,o,t))}__delete(e,o,t){return Ze(this,void 0,void 0,function*(){var r,i,a,c,u,d,n,l,v,_;let f=yield this._options.authProvider.getAuthRequest(),m=b(f.headers,(r=this._options)===null||r===void 0?void 0:r.headers,t?.headers),h=yield((i=this._options.fetcher)!==null&&i!==void 0?i:k)({url:p.join((a=yield g.get(this._options.baseUrl))!==null&&a!==void 0?a:((c=yield g.get(this._options.environment))!==null&&c!==void 0?c:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agent-variables/${p.encodePathParam(o)}`),method:"DELETE",headers:m,queryString:p.queryBuilder().mergeAdditional(t?.queryParams).build(),timeoutMs:((n=(u=t?.timeoutInSeconds)!==null&&u!==void 0?u:(d=this._options)===null||d===void 0?void 0:d.timeoutInSeconds)!==null&&n!==void 0?n:60)*1e3,maxRetries:(l=t?.maxRetries)!==null&&l!==void 0?l:(v=this._options)===null||v===void 0?void 0:v.maxRetries,abortSignal:t?.abortSignal,fetchFn:(_=this._options)===null||_===void 0?void 0:_.fetch,logging:this._options.logging});if(h.ok)return{data:h.body,rawResponse:h.rawResponse};if(h.error.reason==="status-code")throw h.error.statusCode===400?new x(h.error.body,h.rawResponse):new w({statusCode:h.error.statusCode,body:h.error.body,rawResponse:h.rawResponse});return C(h.error,h.rawResponse,"DELETE","/v1/projects/{project_id}/agent-variables/{variable_id}")})}update(e,o,t,r){return E.fromPromise(this.__update(e,o,t,r))}__update(e,o,t,r){return Ze(this,void 0,void 0,function*(){var i,a,c,u,d,n,l,v,_,f;let m=yield this._options.authProvider.getAuthRequest(),h=b(m.headers,(i=this._options)===null||i===void 0?void 0:i.headers,r?.headers),y=yield((a=this._options.fetcher)!==null&&a!==void 0?a:k)({url:p.join((c=yield g.get(this._options.baseUrl))!==null&&c!==void 0?c:((u=yield g.get(this._options.environment))!==null&&u!==void 0?u:R.Production).base,`v1/projects/${p.encodePathParam(e)}/agent-variables/${p.encodePathParam(o)}`),method:"PATCH",headers:h,contentType:"application/json",queryString:p.queryBuilder().mergeAdditional(r?.queryParams).build(),requestType:"json",body:t,timeoutMs:((l=(d=r?.timeoutInSeconds)!==null&&d!==void 0?d:(n=this._options)===null||n===void 0?void 0:n.timeoutInSeconds)!==null&&l!==void 0?l:60)*1e3,maxRetries:(v=r?.maxRetries)!==null&&v!==void 0?v:(_=this._options)===null||_===void 0?void 0:_.maxRetries,abortSignal:r?.abortSignal,fetchFn:(f=this._options)===null||f===void 0?void 0:f.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if(y.error.reason==="status-code")throw y.error.statusCode===400?new x(y.error.body,y.rawResponse):new w({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse});return C(y.error,y.rawResponse,"PATCH","/v1/projects/{project_id}/agent-variables/{variable_id}")})}};var Ko=class{constructor(e={}){this._options=P(e)}get configurations(){var e;return(e=this._configurations)!==null&&e!==void 0?e:this._configurations=new Go(this._options)}get variables(){var e;return(e=this._variables)!==null&&e!==void 0?e:this._variables=new Jo(this._options)}};var Et=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},Vo=class{constructor(e={}){this._options=P(e)}get agent(){var e;return(e=this._agent)!==null&&e!==void 0?e:this._agent=new Se(this._options)}get auth(){var e;return(e=this._auth)!==null&&e!==void 0?e:this._auth=new _o(this._options)}get listen(){var e;return(e=this._listen)!==null&&e!==void 0?e:this._listen=new Ce(this._options)}get manage(){var e;return(e=this._manage)!==null&&e!==void 0?e:this._manage=new Mo(this._options)}get read(){var e;return(e=this._read)!==null&&e!==void 0?e:this._read=new Uo(this._options)}get selfHosted(){var e;return(e=this._selfHosted)!==null&&e!==void 0?e:this._selfHosted=new Wo(this._options)}get speak(){var e;return(e=this._speak)!==null&&e!==void 0?e:this._speak=new De(this._options)}get voiceAgent(){var e;return(e=this._voiceAgent)!==null&&e!==void 0?e:this._voiceAgent=new Ko(this._options)}fetch(e,o,t){return Et(this,void 0,void 0,function*(){var r;return _t(e,o,{baseUrl:(r=this._options.baseUrl)!==null&&r!==void 0?r:(()=>Et(this,void 0,void 0,function*(){var i;let a=yield g.get(this._options.environment);return typeof a=="string"?a:(i=a?.base)!==null&&i!==void 0?i:R.Production.base})),headers:this._options.headers,timeoutInSeconds:this._options.timeoutInSeconds,maxRetries:this._options.maxRetries,fetch:this._options.fetch,logging:this._options.logging,getAuthHeaders:()=>Et(this,void 0,void 0,function*(){return(yield this._options.authProvider.getAuthRequest()).headers})},t)})}};var Z=function(s,e,o,t){function r(i){return i instanceof o?i:new o(function(a){a(i)})}return new(o||(o=Promise))(function(i,a){function c(n){try{d(t.next(n))}catch(l){a(l)}}function u(n){try{d(t.throw(n))}catch(l){a(l)}}function d(n){n.done?i(n.value):r(n.value).then(c,u)}d((t=t.apply(s,e||[])).next())})},xn=1e4,kn=new Set(["Authorization","headers","debug","reconnectAttempts","connectionTimeoutInSeconds","abortSignal","queryParams"]),qe,fr=!1;function Pn(){return Z(this,void 0,void 0,function*(){var s;if(!fr){fr=!0;try{if(typeof Ft<"u"){let e=wt();qe=e.WebSocket||e.default||e}else if(typeof process<"u"&&(!((s=process.versions)===null||s===void 0)&&s.node)){let o=yield new Function("specifier","return import(specifier)")("ws");qe=o.WebSocket||o.default||o}}catch{qe=void 0}}})}function Cn(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(Q.type==="node")try{return pr().randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}var xt=class{constructor(e){this.originalProvider=e}getAuthRequest(e){return Z(this,void 0,void 0,function*(){var o,t;let r=yield this.originalProvider.getAuthRequest(e),i=((o=r.headers)===null||o===void 0?void 0:o.Authorization)||((t=r.headers)===null||t===void 0?void 0:t.authorization);return i&&typeof i=="string"&&!i.startsWith("Bearer ")&&!i.startsWith("Token ")&&!i.startsWith("token ")?{headers:Object.assign(Object.assign({},r.headers),{Authorization:`Token ${i}`})}:r})}},kt=class{constructor(e,o){this.originalProvider=e,this.accessToken=o}getAuthRequest(e){return Z(this,void 0,void 0,function*(){var o,t;let r=(o=yield g.get(this.accessToken))!==null&&o!==void 0?o:(t=process.env)===null||t===void 0?void 0:t.DEEPGRAM_ACCESS_TOKEN;return r!=null?{headers:{Authorization:`Bearer ${r}`}}:this.originalProvider.getAuthRequest(e)})}},Pt=class extends Vo{constructor(e={}){let o=Cn(),t=Object.assign(Object.assign({},e),{headers:Object.assign(Object.assign({},e.headers),{"x-deepgram-session-id":o})});super(t),this._sessionId=o,this._options.authProvider=new xt(this._options.authProvider),e.accessToken!=null&&(this._options.authProvider=new kt(this._options.authProvider,e.accessToken))}get sessionId(){return this._sessionId}get agent(){return this._customAgent||(this._customAgent=new Ct(this._options)),this._customAgent}get listen(){return this._customListen||(this._customListen=new jt(this._options)),this._customListen}get speak(){return this._customSpeak||(this._customSpeak=new Tt(this._options)),this._customSpeak}},Ct=class extends Se{get v1(){return new Dt(this._options)}},jt=class extends Ce{get v1(){return new It(this._options)}get v2(){return new Mt(this._options)}},Tt=class extends De{get v1(){return new Ht(this._options)}};function jn(s){return Z(this,void 0,void 0,function*(){let e={};for(let[o,t]of Object.entries(s)){if(t==null)continue;let r=yield g.get(t);r!=null&&(e[o]=r)}return e})}function Yo(s){let e={};for(let[o,t]of Object.entries(s))!kn.has(o)&&t!=null&&(e[o]=t);return s.queryParams!=null&&typeof s.queryParams=="object"&&Object.assign(e,s.queryParams),e}function Tn(s){let e={},o=Q.type==="browser"||Q.type==="web-worker",t=s["x-deepgram-session-id"]||s["X-Deepgram-Session-Id"];if(Q.type==="node"&&qe)e.WebSocket=qe,e.headers=s;else if(o){let r=s.Authorization||s.authorization,i=Object.assign({},s);delete i.Authorization,delete i.authorization,delete i["x-deepgram-session-id"],delete i["X-Deepgram-Session-Id"],e.headers=i;let a=[];if(r&&typeof r=="string")if(r.startsWith("Token ")){let c=r.substring(6);a.push("token",c)}else if(r.startsWith("Bearer ")){let c=r.substring(7);a.push("bearer",c)}else a.push(r);t&&typeof t=="string"&&a.push("x-deepgram-session-id",t),a.length>0&&(e.protocols=a)}else e.headers=s;return e}function Qo(s,e){var o;let t=i=>{var a,c,u;if(typeof i.data=="string")try{let d=V(i.data);(a=e.message)===null||a===void 0||a.call(e,d)}catch{(c=e.message)===null||c===void 0||c.call(e,i.data)}else(u=e.message)===null||u===void 0||u.call(e,i.data)},r=s;return!((o=r._listeners)===null||o===void 0)&&o.message&&r._listeners.message.forEach(i=>{s.removeEventListener("message",i)}),s.addEventListener("message",t),t}function Xo(s,e){e.handleOpen&&s.removeEventListener("open",e.handleOpen),e.handleMessage&&s.removeEventListener("message",e.handleMessage),e.handleClose&&s.removeEventListener("close",e.handleClose),e.handleError&&s.removeEventListener("error",e.handleError)}function Zo(s){s.readyState===s.CLOSED&&(s._connectLock=!1,s._shouldReconnect=!0)}function qo(s){return Z(this,arguments,void 0,function*({options:e,urlPath:o,environmentKey:t,queryParams:r,headers:i,debug:a,reconnectAttempts:c,connectionTimeoutInSeconds:u,abortSignal:d}){var n,l,v,_,f,m;yield Pn();let h=yield(n=e.authProvider)===null||n===void 0?void 0:n.getAuthRequest(),y=b((l=e.headers)!==null&&l!==void 0?l:{},(v=h?.headers)!==null&&v!==void 0?v:{},i),T=yield jn(y),S=Tn(T),j=(_=yield g.get(e.baseUrl))!==null&&_!==void 0?_:((f=yield g.get(e.environment))!==null&&f!==void 0?f:R.Production)[t];return new B({url:p.join(j,o),protocols:(m=S.protocols)!==null&&m!==void 0?m:[],queryParameters:r,headers:S.headers,options:{WebSocket:S.WebSocket,debug:a??!1,maxRetries:c??30,startClosed:!0,connectionTimeout:u!=null?u*1e3:xn},abortSignal:d})})}var Dt=class extends Re{connect(){return Z(this,arguments,void 0,function*(e={}){let{headers:o,debug:t,reconnectAttempts:r,connectionTimeoutInSeconds:i,abortSignal:a}=e,c=yield qo({options:this._options,urlPath:"/v1/agent/converse",environmentKey:"agent",queryParams:Yo(e),headers:o,debug:t,reconnectAttempts:r,connectionTimeoutInSeconds:i,abortSignal:a});return new At({socket:c})})}createConnection(){return Z(this,arguments,void 0,function*(e={}){return this.connect(e)})}},At=class extends be{constructor(e){super(e),this.setupBinaryHandling()}setupBinaryHandling(){this.binaryAwareHandler=Qo(this.socket,this.eventHandlers)}connect(){let e=this;return Xo(this.socket,{handleOpen:e.handleOpen,handleMessage:e.handleMessage,handleClose:e.handleClose,handleError:e.handleError}),Zo(this.socket),super.connect(),this.setupBinaryHandling(),this}},It=class extends xe{connect(e){return Z(this,void 0,void 0,function*(){let{headers:o,debug:t,reconnectAttempts:r,connectionTimeoutInSeconds:i,abortSignal:a}=e,c=yield qo({options:this._options,urlPath:"/v1/listen",environmentKey:"production",queryParams:Yo(e),headers:o,debug:t,reconnectAttempts:r,connectionTimeoutInSeconds:i,abortSignal:a});return new Lt({socket:c})})}createConnection(e){return Z(this,void 0,void 0,function*(){return this.connect(e)})}},Lt=class extends Ee{constructor(e){super(e),this.setupBinaryHandling()}setupBinaryHandling(){this.binaryAwareHandler=Qo(this.socket,this.eventHandlers)}connect(){let e=this;return Xo(this.socket,{handleOpen:e.handleOpen,handleMessage:e.handleMessage,handleClose:e.handleClose,handleError:e.handleError}),Zo(this.socket),super.connect(),this.setupBinaryHandling(),this}},Mt=class extends Pe{connect(e){return Z(this,void 0,void 0,function*(){let{headers:o,debug:t,reconnectAttempts:r,connectionTimeoutInSeconds:i,abortSignal:a}=e,c=yield qo({options:this._options,urlPath:"/v2/listen",environmentKey:"production",queryParams:Yo(e),headers:o,debug:t,reconnectAttempts:r,connectionTimeoutInSeconds:i,abortSignal:a});return new Bt({socket:c})})}createConnection(e){return Z(this,void 0,void 0,function*(){return this.connect(e)})}},Bt=class extends ke{constructor(e){super(e),this.setupBinaryHandling()}setupBinaryHandling(){this.binaryAwareHandler=Qo(this.socket,this.eventHandlers)}connect(){let e=this;return Xo(this.socket,{handleOpen:e.handleOpen,handleMessage:e.handleMessage,handleClose:e.handleClose,handleError:e.handleError}),Zo(this.socket),super.connect(),this.setupBinaryHandling(),this}ping(e){let o=this.socket._ws;if(!o)throw new Error("WebSocket is not connected. Call connect() and waitForOpen() first.");if(o.readyState!==o.OPEN)throw new Error("WebSocket is not in OPEN state.");if(Q.type==="node"&&typeof o.ping=="function")o.ping(e);else throw new Error("WebSocket ping is not supported in browser environments. Browser WebSocket connections handle ping/pong automatically. If you need keepalive in the browser, consider sending periodic audio data or using a timer.")}},Ht=class extends Te{connect(e){return Z(this,void 0,void 0,function*(){let{headers:o,debug:t,reconnectAttempts:r,connectionTimeoutInSeconds:i,abortSignal:a}=e,c=yield qo({options:this._options,urlPath:"/v1/speak",environmentKey:"production",queryParams:Yo(e),headers:o,debug:t,reconnectAttempts:r,connectionTimeoutInSeconds:i,abortSignal:a});return new Ut({socket:c})})}createConnection(e){return Z(this,void 0,void 0,function*(){return this.connect(e)})}},Ut=class extends je{constructor(e){super(e);let o=this;o.handleMessage&&this.socket.removeEventListener("message",o.handleMessage),this.setupBinaryHandling()}setupBinaryHandling(){this.binaryAwareHandler=Qo(this.socket,this.eventHandlers)}connect(){let e=this;return Xo(this.socket,{handleOpen:e.handleOpen,handleMessage:e.handleMessage,handleClose:e.handleClose,handleError:e.handleError}),Zo(this.socket),super.connect(),this.setupBinaryHandling(),this}};export{Pt as a};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import{a as E}from"./chunk-KD2RTEWK.js";import{D as a,F as y,V as p,W as g,f as t,g as S,h as T,j as k,l as h,n as M,o as C,r as v,v as l,w as b}from"./chunk-HXVOCQLA.js";var i="[Deepgram Flux STT]",R=1e4,f=16e3,P=1280,_=`
|
|
2
|
+
class PcmCaptureProcessor extends AudioWorkletProcessor {
|
|
3
|
+
constructor() {
|
|
4
|
+
super()
|
|
5
|
+
this._buffer = new Float32Array(${P})
|
|
6
|
+
this._offset = 0
|
|
7
|
+
}
|
|
8
|
+
process(inputs, outputs, parameters) {
|
|
9
|
+
const input = inputs[0]?.[0]
|
|
10
|
+
if (!input) return true
|
|
11
|
+
for (let i = 0; i < input.length; i++) {
|
|
12
|
+
this._buffer[this._offset++] = input[i]
|
|
13
|
+
if (this._offset >= this._buffer.length) {
|
|
14
|
+
const int16 = new Int16Array(this._buffer.length)
|
|
15
|
+
for (let j = 0; j < this._buffer.length; j++) {
|
|
16
|
+
const s = Math.max(-1, Math.min(1, this._buffer[j]))
|
|
17
|
+
int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF
|
|
18
|
+
}
|
|
19
|
+
this.port.postMessage(int16.buffer, [int16.buffer])
|
|
20
|
+
this._offset = 0
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return true
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
registerProcessor('pcm-capture-processor', PcmCaptureProcessor)
|
|
27
|
+
`,I=2e3,$=1e3,D=3e4,x=2,c=5,m=3;var w=class d{constructor(e){this.options=e;this.options.model=this.options.model||"flux-general-en",this.options.language=this.options.language||"en",this.options.eotThreshold=this.options.eotThreshold??.9,this.options.eagerEotThreshold=this.options.eagerEotThreshold??.5,this.options.eotTimeoutMs=this.options.eotTimeoutMs??3e3,this.options.eagerMaxTurnDurationMs=this.options.eagerMaxTurnDurationMs??5e3,this.options.safetyNetTimeoutMs=this.options.safetyNetTimeoutMs??I,this.options.echoCancellation=this.options.echoCancellation??!0,this.options.noiseSuppression=this.options.noiseSuppression??!0,this.options.autoGainControl=this.options.autoGainControl??!0;let n=this.options.eagerEotThreshold===0?"disabled":`${this.options.eagerEotThreshold}`,s=this.options.eagerMaxTurnDurationMs===0?"disabled":`${this.options.eagerMaxTurnDurationMs}ms`;t.debug(`${i} init \u2014 features: pure-flux-event-flow, eot_threshold=${this.options.eotThreshold}, eager_eot_threshold=${n}, eot_timeout_ms=${this.options.eotTimeoutMs}, eager_max_turn_duration_ms=${s}`),this.handleAppMessages()}options;connection=null;state="Idle";shouldReconnect=!0;stream=null;audioContext=null;workletNode=null;reconnectAttempts=0;reconnectDelay=$;reconnectTimeoutId=null;digitalHumanSpeaking=!1;pendingPromptRequest=null;isUserCurrentlySpeaking=!1;isUiShowingSpeaking=!1;eagerPromptSentForTurn=!1;cancelledEagerRequestId=void 0;pendingConfigRollback=null;turnStartedAt=null;safetyNetTimeoutId=null;audioChunksSent=0;async startRecognition(){t.info(`${i} Starting speech recognition`),this.shouldReconnect=!0,this.resetReconnectionState(),await this.connect()}async stopRecognition(){t.info(`${i} Stopping speech recognition`),this.shouldReconnect=!1,this.clearReconnectTimeout(),await this.disconnect()}async pause(){return t.info(`${i} Pausing speech recognition`),this.state="Paused",this.clearSafetyNet(),this.resetSpeakingStates(),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.pendingPromptRequest=null,this.cancelledEagerRequestId=void 0,this.stream&&(this.stream.getTracks().forEach(e=>{e.enabled=!1}),t.debug(`${i} Audio tracks disabled`)),!0}async resume(){if(t.info(`${i} Resuming speech recognition`),this.state==="Paused"){if(this.stream)return this.state="Connected",this.stream.getTracks().forEach(e=>{e.enabled=!0}),t.debug(`${i} Audio tracks re-enabled`),!0;if(this.connection)return this.state="Connected",await this.startMicrophone(),!0;this.state="Disconnected"}return t.debug(`${i} Initiating connection`),await this.connect(),!0}setChatMetadata(e){this.options.promptMetadata=e}updateConfig(e){let n=d.pickDefined(e);if(Object.keys(n).length===0)return t.info(`${i} updateConfig: no fields supplied, nothing to update`),!0;let s={eotThreshold:this.options.eotThreshold,eagerEotThreshold:this.options.eagerEotThreshold,eotTimeoutMs:this.options.eotTimeoutMs,keyterms:this.options.keyterms};Object.assign(this.options,n);let o=d.pickDefined({eot_threshold:n.eotThreshold,eager_eot_threshold:(n.eagerEotThreshold??0)>0?n.eagerEotThreshold:void 0,eot_timeout_ms:n.eotTimeoutMs}),r={type:"Configure",...d.pickDefined({thresholds:Object.keys(o).length>0?o:void 0,keyterms:n.keyterms})};if(!this.connection||this.state!=="Connected")return t.info(`${i} updateConfig: stored for next connection, not sent now (state=${this.state})`),!0;if(r.thresholds===void 0&&r.keyterms===void 0)return t.info(`${i} updateConfig: no sendable params (eager can't be disabled mid-stream); stored for next connection`),!0;try{return this.pendingConfigRollback=s,this.connection.sendConfigure(r),t.info(`${i} updateConfig: sent Configure ${JSON.stringify(r)}`),!0}catch(u){return this.rollbackPendingConfig(),t.error(`${i} updateConfig: failed to send Configure`,t.serialiseError(u)),!1}}rollbackPendingConfig(){this.pendingConfigRollback&&(Object.assign(this.options,this.pendingConfigRollback),this.pendingConfigRollback=null)}static pickDefined(e){let n={};for(let s of Object.keys(e))e[s]!==void 0&&(n[s]=e[s]);return n}async connect(){if(this.state==="Connected"){t.warn(`${i} Already connected`);return}if(this.state==="Connecting"){t.warn(`${i} Connection already in progress`);return}this.state="Connecting";try{let e=await this.getToken();t.info(`${i} Connecting to Deepgram Flux v2 \u2014 api_url="${e.api_url}", sdk_version="${e.sdk_version}", token_length=${e.token?.length??0}`);let n=new E({accessToken:e.token,baseUrl:e.api_url}),s={model:this.options.model,encoding:"linear16",sample_rate:String(f),mip_opt_out:"true",...this.options.eotThreshold!==void 0&&{eot_threshold:this.options.eotThreshold},...this.options.eagerEotThreshold!==void 0&&this.options.eagerEotThreshold>0&&{eager_eot_threshold:this.options.eagerEotThreshold},...this.options.eotTimeoutMs!==void 0&&{eot_timeout_ms:this.options.eotTimeoutMs},...this.options.keyterms&&this.options.keyterms.length>0&&{keyterm:this.options.keyterms}};if(this.options.model==="flux-general-multi"&&this.options.language&&(s.language_hint=this.options.language),this.connection=await n.listen.v2.connect(s),this.connection.connect(),await Promise.race([this.connection.waitForOpen(),new Promise((o,r)=>setTimeout(()=>r(new Error("Connection timeout")),R))]),this.state!=="Paused"&&(this.state="Connected"),t.info(`${i} Connection opened`),this.setupEventHandlers(),this.state==="Paused"){t.info(`${i} Pause requested during connection \u2014 staying paused`),this.resetReconnectionState();return}await this.startMicrophone(),t.info(`${i} Connected successfully`),this.resetReconnectionState()}catch(e){this.state="Disconnected",t.error(`${i} Connection error`,t.serialiseError(e)),this.shouldReconnect&&(this.emitTransientError(e),this.scheduleReconnect())}}async disconnect(){if(!(this.state==="Idle"||this.state==="Disconnected"&&!this.connection)){t.info(`${i} Disconnecting`);try{if(this.stopMicrophone(),this.connection){try{this.connection.sendCloseStream({type:"CloseStream"})}catch{}this.connection.close(),this.connection=null}}catch(e){t.error(`${i} Disconnect error`,t.serialiseError(e))}this.clearSafetyNet(),this.resetSpeakingStates(),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.pendingPromptRequest=null,this.cancelledEagerRequestId=void 0,this.state="Disconnected",this.clientMsgSend(new a(!1))}}scheduleReconnect(){if(this.reconnectAttempts>=c){t.error(`${i} Max reconnection attempts (${c}) reached`),this.clientMsgSend(new l(`Unable to connect to speech recognition service after ${c} attempts`));return}this.reconnectAttempts++,t.info(`${i} Scheduling reconnection attempt ${this.reconnectAttempts}/${c} in ${this.reconnectDelay}ms`),this.reconnectTimeoutId=setTimeout(()=>{this.connect()},this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*x,D)}resetReconnectionState(){this.reconnectAttempts=0,this.reconnectDelay=$,this.clearReconnectTimeout()}clearReconnectTimeout(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null)}async getToken(){let e=this.options.model||"flux-general-en",n=`${this.options.connectionUrl}/speech-recognition-service/deepgram/token?model=${encodeURIComponent(e)}`,s=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${this.options.jwtToken}`,"Content-Type":"application/json"}});if(!s.ok)throw new Error(`Token fetch failed: ${s.status} ${s.statusText}`);return await s.json()}async startMicrophone(){try{if(t.info(`${i} Starting microphone`),this.stopMicrophone(),this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:this.options.microphoneDeviceId?{exact:this.options.microphoneDeviceId}:void 0,echoCancellation:this.options.echoCancellation,noiseSuppression:this.options.noiseSuppression,autoGainControl:this.options.autoGainControl}}),this.state==="Paused"){t.info(`${i} Paused during getUserMedia \u2014 keeping stream but disabling tracks`),this.stream.getTracks().forEach(o=>{o.enabled=!1});return}this.audioContext=new AudioContext({sampleRate:f});let e=this.audioContext.createMediaStreamSource(this.stream),n=new Blob([_],{type:"application/javascript"}),s=URL.createObjectURL(n);await this.audioContext.audioWorklet.addModule(s),URL.revokeObjectURL(s),this.workletNode=new AudioWorkletNode(this.audioContext,"pcm-capture-processor"),this.audioChunksSent=0,this.workletNode.port.onmessage=o=>{!this.connection||this.state!=="Connected"||(this.connection.sendMedia(o.data),this.audioChunksSent++,this.audioChunksSent%50===1&&t.debug(`${i} Audio chunks sent: ${this.audioChunksSent}, size: ${o.data.byteLength} bytes`))},e.connect(this.workletNode),this.workletNode.connect(this.audioContext.destination),t.info(`${i} Microphone started (linear16 PCM @ ${f}Hz)`),this.clientMsgSend(new a(!0))}catch(e){t.error(`${i} Microphone error`,t.serialiseError(e)),this.clientMsgSend(new k(new Error(JSON.stringify(e))))}}stopMicrophone(){this.workletNode&&(this.workletNode.port.close(),this.workletNode.disconnect(),this.workletNode=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(e=>{e.stop()}),this.stream=null),t.info(`${i} Microphone stopped`)}setupEventHandlers(){this.connection&&(this.connection.on("open",()=>{this.handleConnectionOpen()}),this.connection.on("message",e=>{if(e!==null&&typeof e=="object"&&"type"in e){let n=e;n.type==="TurnInfo"?this.handleTurnInfo(e):n.type==="Connected"?t.info(`${i} v2 connection confirmed`):n.type==="ConfigureSuccess"?(this.pendingConfigRollback=null,t.info(`${i} Configure applied: ${JSON.stringify(e)}`)):n.type==="ConfigureFailure"?(this.rollbackPendingConfig(),t.warn(`${i} Configure rejected by Deepgram; rolled back persisted values`,e)):n.type==="Error"?this.handleFatalError(e):t.debug(`${i} Unhandled v2 message type: ${n.type}`)}}),this.connection.on("close",e=>{this.handleConnectionClose(e)}),this.connection.on("error",e=>{let n={};e instanceof Event&&(n.type=e.type,n.target=e.target?.url??e.target?.readyState??"unknown"),t.error(`${i} WebSocket error event`,e,n),this.emitTransientError(e)}))}handleTurnInfo(e){try{switch(t.debug(`${i} TurnInfo event: ${e.event}, transcript_length=${(e.transcript||"").length}, turn_index=${e.turn_index}, eot_confidence=${e.end_of_turn_confidence??"n/a"}`),e.event){case"StartOfTurn":this.handleStartOfTurn(e);break;case"Update":this.handleUpdate(e);break;case"EagerEndOfTurn":this.handleEagerEndOfTurn(e);break;case"TurnResumed":this.handleTurnResumed(e);break;case"EndOfTurn":this.handleEndOfTurn(e);break;default:t.debug(`${i} Unknown TurnInfo event: ${e.event}`)}}catch(n){t.error(`${i} Error processing TurnInfo`,t.serialiseError(n))}finally{this.resetSafetyNet()}}handleStartOfTurn(e){t.debug(`${i} StartOfTurn: turn_index=${e.turn_index}`),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.cancelledEagerRequestId=void 0}handleUpdate(e){let n=e.transcript||"";if(n==="")return;if(this.isUiShowingSpeaking||(this.isUiShowingSpeaking=!0,this.turnStartedAt=Date.now(),this.clientMsgSend(new M)),this.isUserCurrentlySpeaking||(this.isUserCurrentlySpeaking=!0,this.dataChannelMsgSend(new p("start"))),this.digitalHumanSpeaking){let o=this.countWords(n);o>=m?(t.info(`${i} User speech detected during avatar speaking (${o} words) \u2014 interrupting`),this.dataChannelMsgSend(new g),this.clientMsgSend(new v),this.digitalHumanSpeaking=!1):t.debug(`${i} User speech during avatar speaking is only ${o} word(s) \u2014 holding off barge-in (potential backchannel)`)}let s={transcript:n,final:!1,confidence:this.calculateWordConfidence(e.words),language_code:this.options.language||""};this.clientMsgSend(new h(s))}handleEagerEndOfTurn(e){let n=e.transcript||"";if(t.debug(`${i} EagerEndOfTurn: confidence=${e.end_of_turn_confidence}, transcript_length=${n.length}`),n.trim()==="")return;if(this.digitalHumanSpeaking&&this.countWords(n)<m){t.info(`${i} EagerEndOfTurn: dropping ${this.countWords(n)}-word backchannel while avatar speaking`);return}let s=this.options.eagerMaxTurnDurationMs??0;if(s>0&&this.turnStartedAt!==null){let o=Date.now()-this.turnStartedAt;if(o>s){t.info(`${i} EagerEndOfTurn: suppressed \u2014 turn duration ${o}ms exceeds eagerMaxTurnDurationMs=${s}; deferring to EndOfTurn`);return}}t.info(`${i} EagerEndOfTurn: sending prompt early (${this.countWords(n)} words, ${n.length} chars)`),this.eagerPromptSentForTurn=!0,this.sendChatPromptRaw(n,this.takeCancelledEagerRequestId())}takeCancelledEagerRequestId(){let e=this.cancelledEagerRequestId;return this.cancelledEagerRequestId=void 0,e}handleTurnResumed(e){t.debug(`${i} TurnResumed: turn_index=${e.turn_index}`),this.pendingPromptRequest!==null&&(this.cancelledEagerRequestId=this.pendingPromptRequest.requestId),this.eagerPromptSentForTurn&&(t.info(`${i} TurnResumed: cancelling in-flight eager prompt via StopSpeaking`),this.dataChannelMsgSend(new g)),this.clearPendingPromptRequest(),this.eagerPromptSentForTurn=!1}handleEndOfTurn(e){let n=e.transcript||"";if(t.info(`${i} EndOfTurn: transcript_length=${n.length}, confidence=${e.end_of_turn_confidence}`),n.trim()!==""){let s={transcript:n,final:!0,confidence:this.calculateWordConfidence(e.words),language_code:this.options.language||""};this.clientMsgSend(new h(s)),this.digitalHumanSpeaking&&this.countWords(n)<m?(t.info(`${i} EndOfTurn: dropping ${this.countWords(n)}-word backchannel while avatar speaking`),this.clearPendingPromptRequest()):this.eagerPromptSentForTurn?(t.debug(`${i} EndOfTurn: skipping ChatPrompt \u2014 eager already fired for this turn`),this.emitPendingPromptRequest()):(this.sendChatPromptRaw(n,this.takeCancelledEagerRequestId()),this.emitPendingPromptRequest())}this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.cancelledEagerRequestId=void 0,this.resetSpeakingStates()}handleFatalError(e){if(this.state==="Paused"&&e.code==="INACTIVE_CLIENT"){t.info(`${i} Inactivity termination while paused (${e.code}) \u2014 releasing socket; resume will reconnect`),this.releasePausedConnection();return}t.error(`${i} Fatal error from Deepgram: ${e.code} \u2014 ${e.description}`),this.clientMsgSend(new l(`Deepgram error: ${e.code} \u2014 ${e.description}`))}calculateWordConfidence(e){return!e||e.length===0?1:e.reduce((s,o)=>s+o.confidence,0)/e.length}countWords(e){return e.trim().split(/\s+/).filter(Boolean).length}handleAppMessages(){this.options.messages.subscribe(e=>{switch(e.uneeqMessageType){case"AvatarStartedSpeaking":this.digitalHumanSpeaking=!0;break;case"PromptResult":{e.promptResult.success||this.handleSpeakingEnd();break}case"AvatarAnswer":{e.answerSpeech.replace(/<[^>]*>/g,"")===""&&this.handleSpeakingEnd();break}case"AvatarStoppedSpeaking":{this.handleSpeakingEnd();break}case"SessionEnded":{this.shouldReconnect=!1,this.stopRecognition();break}case"SessionReconnecting":{this.handleSpeakingEnd(),this.shouldReconnect=!1,this.stopRecognition();break}case"CustomMetadataUpdated":{this.options.promptMetadata=e.chatMetadata;break}case"SessionBackendError":{this.handleSpeakingEnd();break}default:}})}handleConnectionOpen(){this.state!=="Paused"&&(this.state="Connected")}handleConnectionClose(e){let n=e?.code??"unknown",s=e?.reason??"";if(t.info(`${i} Connection closed \u2014 code=${n}, reason="${s}"`),this.state==="Paused"){t.info(`${i} Connection closed while paused \u2014 will reconnect on resume`),this.connection=null,this.stopMicrophone(),this.clearSafetyNet(),this.resetSpeakingStates();return}this.state="Disconnected",this.clearSafetyNet(),this.resetSpeakingStates(),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.pendingPromptRequest=null,this.cancelledEagerRequestId=void 0,this.clientMsgSend(new a(!1)),this.shouldReconnect&&(t.info(`${i} Unexpected disconnect, attempting reconnection...`),this.scheduleReconnect())}emitTransientError(e){let n=e instanceof Error?e.message:String(e);this.clientMsgSend(new b(n))}sendChatPromptRaw(e,n){if(!e||e.trim()==="")return;this.options.language&&(this.options.promptMetadata.userSpokenLocale=this.options.language);let s=n??S();n!==void 0&&t.info(`${i} sendChatPromptRaw: reusing requestId=${s} from cancelled eager prompt`);let o={...this.options.promptMetadata},r=this.turnStartedAt??Date.now(),u=Date.now()-r;this.pendingPromptRequest={prompt:e,requestId:s,metadata:o,speakingDurationMs:u,speechStartedAt:r},this.dataChannelMsgSend(new T(e,this.options.promptMetadata,s,!1))}emitPendingPromptRequest(){let e=this.pendingPromptRequest;e!==null&&(this.clientMsgSend(new y({prompt:e.prompt,requestId:e.requestId,metadata:e.metadata,speakingDurationMs:e.speakingDurationMs,speechStartedAt:e.speechStartedAt})),t.debug(`${i} PromptRequest emitted \u2014 speakingDurationMs=${e.speakingDurationMs}, requestId=${e.requestId}`),this.pendingPromptRequest=null)}clearPendingPromptRequest(){this.pendingPromptRequest=null}handleSpeakingEnd(){this.digitalHumanSpeaking=!1}resetSafetyNet(){this.clearSafetyNet(),(this.isUiShowingSpeaking||this.isUserCurrentlySpeaking)&&(this.safetyNetTimeoutId=setTimeout(()=>{t.warn(`${i} Safety net: no TurnInfo events for ${this.options.safetyNetTimeoutMs}ms while speaking \u2014 resetting`),this.resetSpeakingStates()},this.options.safetyNetTimeoutMs))}clearSafetyNet(){this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null)}releasePausedConnection(){if(this.connection){try{this.connection.close()}catch{}this.connection=null}this.stopMicrophone(),this.clearSafetyNet(),this.resetSpeakingStates(),this.state="Paused"}resetSpeakingStates(){this.isUserCurrentlySpeaking&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new p("stop"))),this.isUiShowingSpeaking&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new C))}dataChannelMsgSend(e){this.options.sendMessage(e)}clientMsgSend(e){this.options.messages.next(e)}};export{w as DeepgramFluxSTT};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as b}from"./chunk-KD2RTEWK.js";import{D as p,V as h,W as C,f as t,h as f,j as T,l as g,n as v,o as S,r as k,v as y,w as M}from"./chunk-HXVOCQLA.js";var n="[Deepgram STT]",E=1e4,R=250,U=48e3,$=1e3,D=3e4,N=2,d=5,l=2e3;var m=3,w=class{constructor(e){this.options=e;this.options.model=this.options.model||"nova-3",this.options.language=this.options.language||"en",this.options.smartFormat=this.options.smartFormat??!0,this.options.interimResults=this.options.interimResults??!0,this.options.utteranceEndMs=this.options.utteranceEndMs??1500,this.options.vadEvents=this.options.vadEvents??!0,this.options.fillerWords=this.options.fillerWords??!1,this.options.endpointing=this.options.endpointing??500,this.options.echoCancellation=this.options.echoCancellation??!0,this.options.noiseSuppression=this.options.noiseSuppression??!0,this.options.autoGainControl=this.options.autoGainControl??!0,this.options.interruptionWordThreshold=this.options.interruptionWordThreshold??m,this.options.noDelay=this.options.noDelay??!1,this.options.safetyNetTimeoutMs=this.options.safetyNetTimeoutMs??l,this.options.safetyNetTimeoutMs<=500?(t.warn(`${n} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms. This is very short and may cause premature transcript finalization. Ignoring and default the value to ${l}ms.`),this.options.safetyNetTimeoutMs=l):this.options.safetyNetTimeoutMs<=1e3?t.warn(`${n} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms. This is very short and may cause premature transcript finalization. Recommended value is ${l}ms.`):t.info(`${n} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms.`),this.handleAppMessages()}options;connection=null;state="Idle";shouldReconnect=!0;microphone=null;stream=null;reconnectAttempts=0;reconnectDelay=$;reconnectTimeoutId=null;digitalHumanSpeaking=!1;isUserCurrentlySpeaking=!1;isUiShowingSpeaking=!1;accumulatedTranscript="";accumulatedConfidenceSum=0;accumulatedWordCount=0;lastDeepgramEventTime=0;safetyNetTimeoutId=null;async startRecognition(){t.info(`${n} Starting speech recognition`),this.shouldReconnect=!0,this.resetReconnectionState(),await this.connect()}async stopRecognition(){t.info(`${n} Stopping speech recognition`),this.shouldReconnect=!1,this.clearReconnectTimeout(),await this.disconnect()}async pause(){return t.info(`${n} Pausing speech recognition`),this.state="Paused",this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null),this.resetAccumulatedState(),this.resetSpeakingStates(),this.stream&&(this.stream.getTracks().forEach(e=>{e.enabled=!1}),t.debug(`${n} Audio tracks disabled`)),!0}async resume(){if(t.info(`${n} Resuming speech recognition`),this.state==="Paused"){if(this.stream)return this.state="Connected",this.stream.getTracks().forEach(e=>{e.enabled=!0}),t.debug(`${n} Audio tracks re-enabled`),!0;if(this.connection)return this.state="Connected",await this.startMicrophone(),!0;this.state="Disconnected"}return t.debug(`${n} Initiating connection`),await this.connect(),!0}setChatMetadata(e){this.options.promptMetadata=e}async connect(){if(this.state==="Connected"){t.warn(`${n} Already connected`);return}if(this.state==="Connecting"){t.warn(`${n} Connection already in progress`);return}this.state="Connecting";try{let e=await this.getToken();t.info(`${n} Connecting to Deepgram`);let i=new b({accessToken:e.token,baseUrl:e.api_url}),a={model:this.options.model,language:this.options.language,smart_format:String(this.options.smartFormat),interim_results:String(this.options.interimResults),utterance_end_ms:this.options.utteranceEndMs,vad_events:String(this.options.vadEvents),filler_words:String(this.options.fillerWords),endpointing:this.options.endpointing,mip_opt_out:"true",...this.options.keyterms&&this.options.keyterms.length>0&&{keyterm:this.options.keyterms},...this.options.noDelay&&{queryParams:{no_delay:"true"}}},s=i.listen;if(this.connection=await s.v1.connect(a),this.connection.connect(),await Promise.race([this.connection.waitForOpen(),new Promise((o,r)=>setTimeout(()=>r(new Error("Connection timeout")),E))]),this.state!=="Paused"&&this.state!=="Disconnected"&&(this.state="Connected"),t.info(`${n} Connection opened`),this.setupEventHandlers(),this.state==="Paused"){t.info(`${n} Pause requested during connection \u2014 staying paused`),this.resetReconnectionState();return}if(this.state==="Disconnected"){t.info(`${n} Recognition stopped during connection \u2014 aborting`),this.connection&&(this.connection.close(),this.connection=null);return}await this.startMicrophone(),t.info(`${n} Connected successfully`),this.resetReconnectionState()}catch(e){this.state="Disconnected",t.error(`${n} Connection error`,t.serialiseError(e)),this.shouldReconnect&&(this.emitTransientError(e),this.scheduleReconnect())}}async disconnect(){if(!(this.state==="Idle"||this.state==="Disconnected"&&!this.connection)){t.info(`${n} Disconnecting`),this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null);try{this.stopMicrophone(),this.connection&&(this.connection.close(),this.connection=null)}catch(e){t.error(`${n} Disconnect error`,t.serialiseError(e))}this.resetAccumulatedState(),this.resetSpeakingStates(),this.state="Disconnected",this.clientMsgSend(new p(!1))}}scheduleReconnect(){if(this.reconnectAttempts>=d){t.error(`${n} Max reconnection attempts (${d}) reached`),this.clientMsgSend(new y(`Unable to connect to speech recognition service after ${d} attempts`));return}this.reconnectAttempts++,t.info(`${n} Scheduling reconnection attempt ${this.reconnectAttempts}/${d} in ${this.reconnectDelay}ms`),this.reconnectTimeoutId=setTimeout(()=>{this.connect()},this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*N,D)}resetReconnectionState(){this.reconnectAttempts=0,this.reconnectDelay=$,this.clearReconnectTimeout()}clearReconnectTimeout(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null)}async getToken(){let e=this.options.model||"nova-3",i=`${this.options.connectionUrl}/speech-recognition-service/deepgram/token?model=${encodeURIComponent(e)}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${this.options.jwtToken}`,"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Token fetch failed: ${a.status} ${a.statusText}`);return await a.json()}async startMicrophone(){try{if(t.info(`${n} Starting microphone`),this.stopMicrophone(),!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone access is not available in this context");if(this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:this.options.microphoneDeviceId?{exact:this.options.microphoneDeviceId}:void 0,echoCancellation:this.options.echoCancellation,noiseSuppression:this.options.noiseSuppression,autoGainControl:this.options.autoGainControl}}),this.state==="Paused"){t.info(`${n} Paused during getUserMedia \u2014 keeping stream but disabling tracks`),this.stream.getTracks().forEach(e=>{e.enabled=!1});return}if(this.state==="Disconnected"){t.info(`${n} Recognition stopped during getUserMedia \u2014 releasing stream`),this.stream.getTracks().forEach(e=>{e.stop()}),this.stream=null;return}this.microphone=new MediaRecorder(this.stream,{mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:U}),this.microphone.ondataavailable=e=>{e.data.size>0&&this.connection&&this.state==="Connected"&&e.data.arrayBuffer().then(i=>{this.connection?.sendMedia(i)}).catch(i=>{t.error(`${n} Error converting audio data`,t.serialiseError(i))})},this.microphone.start(R),t.debug(`${n} Microphone started`),this.clientMsgSend(new p(!0))}catch(e){t.error(`${n} Microphone error`,t.serialiseError(e)),this.clientMsgSend(new T(new Error(JSON.stringify(e))))}}stopMicrophone(){this.microphone&&this.microphone.state==="recording"&&(this.microphone.stop(),this.microphone=null),this.stream&&(this.stream.getTracks().forEach(e=>{e.stop()}),this.stream=null),t.debug(`${n} Microphone stopped`)}setupEventHandlers(){this.connection&&(this.connection.on("open",()=>{this.handleConnectionOpen()}),this.connection.on("message",e=>{if(e!==null&&typeof e=="object"&&"type"in e){let i=e;i.type==="Results"?this.handleTranscript(e):i.type==="UtteranceEnd"?this.handleUtteranceEnd(e):i.type==="Metadata"&&t.debug(`${n} Metadata`,e)}}),this.connection.on("close",()=>{this.handleConnectionClose()}),this.connection.on("error",e=>{t.error(`${n} WebSocket error event`,t.serialiseError(e)),this.emitTransientError(e)}))}handleAppMessages(){this.options.messages.subscribe(e=>{switch(e.uneeqMessageType){case"AvatarStartedSpeaking":this.digitalHumanSpeaking=!0;break;case"PromptResult":{e.promptResult.success||this.handleSpeakingEnd();break}case"AvatarAnswer":{e.answerSpeech.replace(/<[^>]*>/g,"")===""&&this.handleSpeakingEnd();break}case"AvatarStoppedSpeaking":{this.handleSpeakingEnd();break}case"SessionEnded":{this.shouldReconnect=!1,this.stopRecognition();break}case"SessionReconnecting":{this.handleSpeakingEnd(),this.pause();break}case"CustomMetadataUpdated":{this.options.promptMetadata=e.chatMetadata;break}case"SessionBackendError":{this.handleSpeakingEnd();break}default:}})}handleTranscript(e){try{this.lastDeepgramEventTime=Date.now();let i=e.channel;if(!i?.alternatives||i.alternatives.length===0)return;let a=i.alternatives[0],s=String(a.transcript||""),o=e.is_final,r=e.speech_final;if(t.debug(`${n} Transcript event: is_final=${o}, speech_final=${r}, transcript="${s.substring(0,50)}${s.length>50?"...":""}", accumulated="${this.accumulatedTranscript.substring(0,30)}${this.accumulatedTranscript.length>30?"...":""}", uiSpeaking=${this.isUiShowingSpeaking}, userSpeaking=${this.isUserCurrentlySpeaking}`),s===""&&r){this.endsWithPunctuation(this.accumulatedTranscript)?(this.sendAccumulatedTranscript("Final transcript (from accumulated)"),this.resetSpeakingStates()):t.debug(`${n} speech_final with empty transcript but no punctuation, waiting for more speech or safety net`);return}if(s==="")return;this.processTranscriptChunk(s,a.confidence,o,r),this.updateSpeakingAndInterruptionState(s,r),this.emitTranscriptionResult(s,a.confidence,r),this.resetSafetyNetTimeout()}catch(i){t.error(`${n} Error processing transcript`,t.serialiseError(i))}}processTranscriptChunk(e,i,a,s){if(a&&!s){this.accumulatedTranscript!==""&&(this.accumulatedTranscript+=" "),this.accumulatedTranscript+=e;let o=e.trim().split(/\s+/).length,r=i??1;this.accumulatedConfidenceSum+=r*o,this.accumulatedWordCount+=o,t.debug(`${n} Accumulated transcript: "${this.accumulatedTranscript}"`)}}updateSpeakingAndInterruptionState(e,i){let s=(this.accumulatedTranscript!==""?this.accumulatedTranscript:e).trim().split(/\s+/).length,o=this.options.interruptionWordThreshold??m;this.isUiShowingSpeaking||(this.isUiShowingSpeaking=!0,this.clientMsgSend(new v));let r=!this.digitalHumanSpeaking||s>=o,c=this.accumulatedTranscript!==""?this.accumulatedTranscript+" "+e:e,u=i&&this.endsWithPunctuation(c);!this.isUserCurrentlySpeaking&&r&&(this.isUserCurrentlySpeaking=!0,this.dataChannelMsgSend(new h("start"))),this.digitalHumanSpeaking&&s>=o&&(t.debug(`${n} Interrupting digital human`),this.dataChannelMsgSend(new C),this.clientMsgSend(new k),this.digitalHumanSpeaking=!1),this.isUserCurrentlySpeaking&&u&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new h("stop"))),this.isUiShowingSpeaking&&u&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new S))}emitTranscriptionResult(e,i,a){let s=this.accumulatedTranscript!==""?this.accumulatedTranscript+" "+e:e,o=a&&this.endsWithPunctuation(s),r={transcript:a?s:e,final:o,confidence:i??1,language_code:this.options.language||""};if(this.clientMsgSend(new g(r)),o){let c=s.trim().split(/\s+/).length,u=this.options.interruptionWordThreshold??m;this.digitalHumanSpeaking&&c<u?t.debug(`${n} Discarding utterance during speaking (${c} words < ${u} threshold): "${s}"`):(t.info(`${n} Final transcript: "${s}"`),this.sendChatPrompt(s)),this.resetAccumulatedState()}else if(a){this.accumulatedTranscript!==""&&(this.accumulatedTranscript+=" "),this.accumulatedTranscript+=e;let c=e.trim().split(/\s+/).length;this.accumulatedConfidenceSum+=(i??1)*c,this.accumulatedWordCount+=c,t.debug(`${n} speech_final without punctuation, accumulated for safety net: "${this.accumulatedTranscript}"`)}}handleUtteranceEnd(e){this.lastDeepgramEventTime=Date.now(),t.debug(`${n} UtteranceEnd event received: last_word_end=${e?.last_word_end}, accumulated="${this.accumulatedTranscript.substring(0,50)}...", uiSpeaking=${this.isUiShowingSpeaking}, userSpeaking=${this.isUserCurrentlySpeaking}`),this.accumulatedTranscript.trim()!==""?this.endsWithPunctuation(this.accumulatedTranscript)?(this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null),t.debug(`${n} UtteranceEnd fallback triggered with transcript: "${this.accumulatedTranscript}"`),this.sendAccumulatedTranscript("UtteranceEnd fallback"),this.resetSpeakingStates(),t.debug(`${n} UtteranceEnd: reset speaking states`)):t.debug(`${n} UtteranceEnd: no punctuation, waiting for more speech or safety net`):(this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null),this.resetSpeakingStates(),t.debug(`${n} UtteranceEnd: no transcript, reset speaking states`))}resetSafetyNetTimeout(){this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null),(this.isUiShowingSpeaking||this.isUserCurrentlySpeaking)&&this.accumulatedTranscript.trim()!==""&&(this.safetyNetTimeoutId=setTimeout(()=>{this.triggerSafetyNet()},this.options.safetyNetTimeoutMs))}triggerSafetyNet(){t.warn(`${n} Safety net triggered: no Deepgram events for ${this.options.safetyNetTimeoutMs}ms while speaking`),t.debug(`${n} Safety net triggered: accumulated="${this.accumulatedTranscript}", uiSpeaking=${this.isUiShowingSpeaking}, userSpeaking=${this.isUserCurrentlySpeaking}, timeSinceLastEvent=${Date.now()-this.lastDeepgramEventTime}ms`),this.sendAccumulatedTranscript("Safety net"),this.resetSpeakingStates(),this.safetyNetTimeoutId=null}sendAccumulatedTranscript(e){if(this.accumulatedTranscript.trim()==="")return;if(e!=="Safety net"&&!this.endsWithPunctuation(this.accumulatedTranscript)){t.debug(`${n} sendAccumulatedTranscript: not sending as source is ${e} and transcript doesn't end in punctuation: "${this.accumulatedTranscript}"`);return}let i=this.options.interruptionWordThreshold??m,a=this.accumulatedWordCount>0?this.accumulatedConfidenceSum/this.accumulatedWordCount:1,s={transcript:this.accumulatedTranscript,final:!0,confidence:a,language_code:this.options.language||""};this.clientMsgSend(new g(s));let o=this.accumulatedTranscript.trim().split(/\s+/).length;this.digitalHumanSpeaking&&o<i?t.debug(`${n} Discarding utterance during speaking (${o} words < ${i} threshold): "${this.accumulatedTranscript}"`):(t.info(`${n} ${e}: "${this.accumulatedTranscript}"`),this.sendChatPrompt(this.accumulatedTranscript)),this.resetAccumulatedState()}endsWithPunctuation(e){let i=e.trim();return i.length===0?!1:/[.!?;:]$/.test(i)}resetAccumulatedState(){this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0}resetSpeakingStates(){this.isUserCurrentlySpeaking&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new h("stop"))),this.isUiShowingSpeaking&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new S))}handleConnectionOpen(){this.state!=="Paused"&&(this.state="Connected")}handleConnectionClose(){if(t.info(`${n} Connection closed`),this.state==="Paused"){t.info(`${n} Connection closed while paused \u2014 will reconnect on resume`),this.connection=null,this.stopMicrophone();return}this.state="Disconnected",this.clientMsgSend(new p(!1)),this.shouldReconnect&&(t.info(`${n} Unexpected disconnect, attempting reconnection...`),this.scheduleReconnect())}sendChatPrompt(e){e&&e.trim()!==""&&(this.options.language&&(this.options.promptMetadata.userSpokenLocale=this.options.language),this.dataChannelMsgSend(new f(e,this.options.promptMetadata)))}handleSpeakingEnd(){this.digitalHumanSpeaking=!1}emitTransientError(e){let i=e instanceof Error?e.message:String(e);this.clientMsgSend(new M(i))}dataChannelMsgSend(e){this.options.sendMessage(e)}clientMsgSend(e){this.options.messages.next(e)}};export{w as DeepgramSTT};
|