uneeq-js 3.18.0 → 3.19.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/3.index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";(Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[]).push([[3],{3(t,e,i){i.d(e,{DeepgramSTT:()=>p});var n=i(514),s=i(838),a=i(33),o=i(388),r=i(58),c=i(260);const h="[Deepgram STT]";var u,d;!function(t){t.FinalTranscript="Final transcript (from accumulated)",t.UtteranceEndFallback="UtteranceEnd fallback",t.SafetyNet="Safety net"}(u||(u={})),function(t){t.Idle="Idle",t.Connecting="Connecting",t.Connected="Connected",t.Paused="Paused",t.Disconnected="Disconnected"}(d||(d={}));class p{options;connection=null;state=d.Idle;shouldReconnect=!0;microphone=null;stream=null;reconnectAttempts=0;reconnectDelay=1e3;reconnectTimeoutId=null;digitalHumanSpeaking=!1;isUserCurrentlySpeaking=!1;isUiShowingSpeaking=!1;accumulatedTranscript="";accumulatedConfidenceSum=0;accumulatedWordCount=0;lastDeepgramEventTime=0;safetyNetTimeoutId=null;constructor(t){this.options=t,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??3,this.options.noDelay=this.options.noDelay??!1,this.options.safetyNetTimeoutMs=this.options.safetyNetTimeoutMs??2e3,this.options.safetyNetTimeoutMs<=500?(n.A.warn(`${h} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms. This is very short and may cause premature transcript finalization. Ignoring and default the value to 2000ms.`),this.options.safetyNetTimeoutMs=2e3):this.options.safetyNetTimeoutMs<=1e3?n.A.warn(`${h} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms. This is very short and may cause premature transcript finalization. Recommended value is 2000ms.`):n.A.info(`${h} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms.`),this.handleAppMessages()}async startRecognition(){n.A.info(`${h} Starting speech recognition`),this.shouldReconnect=!0,this.resetReconnectionState(),await this.connect()}async stopRecognition(){n.A.info(`${h} Stopping speech recognition`),this.shouldReconnect=!1,this.clearReconnectTimeout(),await this.disconnect()}async pause(){return n.A.info(`${h} Pausing speech recognition`),this.state=d.Paused,this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null),this.resetAccumulatedState(),this.resetSpeakingStates(),this.stream&&(this.stream.getTracks().forEach(t=>{t.enabled=!1}),n.A.debug(`${h} Audio tracks disabled`)),!0}async resume(){if(n.A.info(`${h} Resuming speech recognition`),this.state===d.Paused){if(this.stream)return this.state=d.Connected,this.stream.getTracks().forEach(t=>{t.enabled=!0}),n.A.debug(`${h} Audio tracks re-enabled`),!0;if(this.connection)return this.state=d.Connected,await this.startMicrophone(),!0;this.state=d.Disconnected}return n.A.debug(`${h} Initiating connection`),await this.connect(),!0}setChatMetadata(t){this.options.promptMetadata=t}async connect(){if(this.state!==d.Connected)if(this.state!==d.Connecting){this.state=d.Connecting;try{const t=await this.getToken();n.A.info(`${h} Connecting to Deepgram`);const e=new c.c({accessToken:t.token,baseUrl:t.api_url}),i={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=e.listen;if(this.connection=await s.v1.connect(i),this.connection.connect(),await Promise.race([this.connection.waitForOpen(),new Promise((t,e)=>setTimeout(()=>e(new Error("Connection timeout")),1e4))]),this.state!==d.Paused&&this.state!==d.Disconnected&&(this.state=d.Connected),n.A.info(`${h} Connection opened`),this.setupEventHandlers(),this.state===d.Paused)return n.A.info(`${h} Pause requested during connection — staying paused`),void this.resetReconnectionState();if(this.state===d.Disconnected)return n.A.info(`${h} Recognition stopped during connection — aborting`),void(this.connection&&(this.connection.close(),this.connection=null));await this.startMicrophone(),n.A.info(`${h} Connected successfully`),this.resetReconnectionState()}catch(t){this.state=d.Disconnected,n.A.error(`${h} Connection error`,n.A.serialiseError(t)),this.shouldReconnect&&(this.emitTransientError(t),this.scheduleReconnect())}}else n.A.warn(`${h} Connection already in progress`);else n.A.warn(`${h} Already connected`)}async disconnect(){if(this.state!==d.Idle&&(this.state!==d.Disconnected||this.connection)){n.A.info(`${h} Disconnecting`),this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null);try{this.stopMicrophone(),this.connection&&(this.connection.close(),this.connection=null)}catch(t){n.A.error(`${h} Disconnect error`,n.A.serialiseError(t))}this.resetAccumulatedState(),this.resetSpeakingStates(),this.state=d.Disconnected,this.clientMsgSend(new s.WY(!1))}}scheduleReconnect(){if(this.reconnectAttempts>=5)return n.A.error(`${h} Max reconnection attempts (5) reached`),void this.clientMsgSend(new s.Cj("Unable to connect to speech recognition service after 5 attempts"));this.reconnectAttempts++,n.A.info(`${h} Scheduling reconnection attempt ${this.reconnectAttempts}/5 in ${this.reconnectDelay}ms`),this.reconnectTimeoutId=setTimeout(()=>{this.connect()},this.reconnectDelay),this.reconnectDelay=Math.min(2*this.reconnectDelay,3e4)}resetReconnectionState(){this.reconnectAttempts=0,this.reconnectDelay=1e3,this.clearReconnectTimeout()}clearReconnectTimeout(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null)}async getToken(){const t=this.options.model||"nova-3",e=`${this.options.connectionUrl}/speech-recognition-service/deepgram/token?model=${encodeURIComponent(t)}`,i=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.options.jwtToken}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Token fetch failed: ${i.status} ${i.statusText}`);return await i.json()}async startMicrophone(){try{if(n.A.info(`${h} 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===d.Paused)return n.A.info(`${h} Paused during getUserMedia — keeping stream but disabling tracks`),void this.stream.getTracks().forEach(t=>{t.enabled=!1});if(this.state===d.Disconnected)return n.A.info(`${h} Recognition stopped during getUserMedia — releasing stream`),this.stream.getTracks().forEach(t=>{t.stop()}),void(this.stream=null);this.microphone=new MediaRecorder(this.stream,{mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:48e3}),this.microphone.ondataavailable=t=>{t.data.size>0&&this.connection&&this.state===d.Connected&&t.data.arrayBuffer().then(t=>{this.connection?.sendMedia(t)}).catch(t=>{n.A.error(`${h} Error converting audio data`,n.A.serialiseError(t))})},this.microphone.start(250),n.A.debug(`${h} Microphone started`),this.clientMsgSend(new s.WY(!0))}catch(t){n.A.error(`${h} Microphone error`,n.A.serialiseError(t)),this.clientMsgSend(new s.co(new Error(JSON.stringify(t))))}}stopMicrophone(){this.microphone&&"recording"===this.microphone.state&&(this.microphone.stop(),this.microphone=null),this.stream&&(this.stream.getTracks().forEach(t=>{t.stop()}),this.stream=null),n.A.debug(`${h} Microphone stopped`)}setupEventHandlers(){this.connection&&(this.connection.on("open",()=>{this.handleConnectionOpen()}),this.connection.on("message",t=>{if(null!==t&&"object"==typeof t&&"type"in t){const e=t;"Results"===e.type?this.handleTranscript(t):"UtteranceEnd"===e.type?this.handleUtteranceEnd(t):"Metadata"===e.type&&n.A.debug(`${h} Metadata`,t)}}),this.connection.on("close",()=>{this.handleConnectionClose()}),this.connection.on("error",t=>{n.A.error(`${h} WebSocket error event`,n.A.serialiseError(t)),this.emitTransientError(t)}))}handleAppMessages(){this.options.messages.subscribe(t=>{switch(t.uneeqMessageType){case s.Yg.AvatarStartedSpeaking:this.digitalHumanSpeaking=!0;break;case s.Yg.PromptResult:t.promptResult.success||this.handleSpeakingEnd();break;case s.Yg.AvatarAnswer:""===t.answerSpeech.replace(/<[^>]*>/g,"")&&this.handleSpeakingEnd();break;case s.Yg.AvatarStoppedSpeaking:this.handleSpeakingEnd();break;case s.Yg.SessionEnded:this.shouldReconnect=!1,this.stopRecognition();break;case s.Yg.SessionReconnecting:this.handleSpeakingEnd(),this.pause();break;case s.Yg.CustomMetadataUpdated:this.options.promptMetadata=t.chatMetadata;break;case s.Yg.SessionBackendError:this.handleSpeakingEnd()}})}handleTranscript(t){try{this.lastDeepgramEventTime=Date.now();const e=t.channel;if(!e?.alternatives||0===e.alternatives.length)return;const i=e.alternatives[0],s=String(i.transcript||""),a=t.is_final,o=t.speech_final;if(n.A.debug(`${h} Transcript event: is_final=${a}, speech_final=${o}, 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&&o)return void(this.endsWithPunctuation(this.accumulatedTranscript)?(this.sendAccumulatedTranscript(u.FinalTranscript),this.resetSpeakingStates()):n.A.debug(`${h} speech_final with empty transcript but no punctuation, waiting for more speech or safety net`));if(""===s)return;this.processTranscriptChunk(s,i.confidence,a,o),this.updateSpeakingAndInterruptionState(s,o),this.emitTranscriptionResult(s,i.confidence,o),this.resetSafetyNetTimeout()}catch(t){n.A.error(`${h} Error processing transcript`,n.A.serialiseError(t))}}processTranscriptChunk(t,e,i,s){if(i&&!s){""!==this.accumulatedTranscript&&(this.accumulatedTranscript+=" "),this.accumulatedTranscript+=t;const i=t.trim().split(/\s+/).length,s=e??1;this.accumulatedConfidenceSum+=s*i,this.accumulatedWordCount+=i,n.A.debug(`${h} Accumulated transcript: "${this.accumulatedTranscript}"`)}}updateSpeakingAndInterruptionState(t,e){const i=(""!==this.accumulatedTranscript?this.accumulatedTranscript:t).trim().split(/\s+/).length,o=this.options.interruptionWordThreshold??3;this.isUiShowingSpeaking||(this.isUiShowingSpeaking=!0,this.clientMsgSend(new s._4));const c=!this.digitalHumanSpeaking||i>=o,u=""!==this.accumulatedTranscript?this.accumulatedTranscript+" "+t:t,d=e&&this.endsWithPunctuation(u);!this.isUserCurrentlySpeaking&&c&&(this.isUserCurrentlySpeaking=!0,this.dataChannelMsgSend(new a.A(a.f.Start))),this.digitalHumanSpeaking&&i>=o&&(n.A.debug(`${h} Interrupting digital human`),this.dataChannelMsgSend(new r.f),this.clientMsgSend(new s.tc),this.digitalHumanSpeaking=!1),this.isUserCurrentlySpeaking&&d&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new a.A(a.f.Stop))),this.isUiShowingSpeaking&&d&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new s.im))}emitTranscriptionResult(t,e,i){const a=""!==this.accumulatedTranscript?this.accumulatedTranscript+" "+t:t,o=i&&this.endsWithPunctuation(a),r={transcript:i?a:t,final:o,confidence:e??1,language_code:this.options.language||""};if(this.clientMsgSend(new s.Ux(r)),o){const t=a.trim().split(/\s+/).length,e=this.options.interruptionWordThreshold??3;this.digitalHumanSpeaking&&t<e?n.A.debug(`${h} Discarding utterance during speaking (${t} words < ${e} threshold): "${a}"`):(n.A.info(`${h} Final transcript: "${a}"`),this.sendChatPrompt(a)),this.resetAccumulatedState()}else if(i){""!==this.accumulatedTranscript&&(this.accumulatedTranscript+=" "),this.accumulatedTranscript+=t;const i=t.trim().split(/\s+/).length;this.accumulatedConfidenceSum+=(e??1)*i,this.accumulatedWordCount+=i,n.A.debug(`${h} speech_final without punctuation, accumulated for safety net: "${this.accumulatedTranscript}"`)}}handleUtteranceEnd(t){this.lastDeepgramEventTime=Date.now(),n.A.debug(`${h} UtteranceEnd event received: last_word_end=${t?.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),n.A.debug(`${h} UtteranceEnd fallback triggered with transcript: "${this.accumulatedTranscript}"`),this.sendAccumulatedTranscript(u.UtteranceEndFallback),this.resetSpeakingStates(),n.A.debug(`${h} UtteranceEnd: reset speaking states`)):n.A.debug(`${h} UtteranceEnd: no punctuation, waiting for more speech or safety net`):(this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null),this.resetSpeakingStates(),n.A.debug(`${h} 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(){n.A.warn(`${h} Safety net triggered: no Deepgram events for ${this.options.safetyNetTimeoutMs}ms while speaking`),n.A.debug(`${h} Safety net triggered: accumulated="${this.accumulatedTranscript}", uiSpeaking=${this.isUiShowingSpeaking}, userSpeaking=${this.isUserCurrentlySpeaking}, timeSinceLastEvent=${Date.now()-this.lastDeepgramEventTime}ms`),this.sendAccumulatedTranscript(u.SafetyNet),this.resetSpeakingStates(),this.safetyNetTimeoutId=null}sendAccumulatedTranscript(t){if(""===this.accumulatedTranscript.trim())return;if(t!==u.SafetyNet&&!this.endsWithPunctuation(this.accumulatedTranscript))return void n.A.debug(`${h} sendAccumulatedTranscript: not sending as source is ${t} and transcript doesn't end in punctuation: "${this.accumulatedTranscript}"`);const e=this.options.interruptionWordThreshold??3,i=this.accumulatedWordCount>0?this.accumulatedConfidenceSum/this.accumulatedWordCount:1,a={transcript:this.accumulatedTranscript,final:!0,confidence:i,language_code:this.options.language||""};this.clientMsgSend(new s.Ux(a));const o=this.accumulatedTranscript.trim().split(/\s+/).length;this.digitalHumanSpeaking&&o<e?n.A.debug(`${h} Discarding utterance during speaking (${o} words < ${e} threshold): "${this.accumulatedTranscript}"`):(n.A.info(`${h} ${t}: "${this.accumulatedTranscript}"`),this.sendChatPrompt(this.accumulatedTranscript)),this.resetAccumulatedState()}endsWithPunctuation(t){const e=t.trim();return 0!==e.length&&/[.!?;:]$/.test(e)}resetAccumulatedState(){this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0}resetSpeakingStates(){this.isUserCurrentlySpeaking&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new a.A(a.f.Stop))),this.isUiShowingSpeaking&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new s.im))}handleConnectionOpen(){this.state!==d.Paused&&(this.state=d.Connected)}handleConnectionClose(){if(n.A.info(`${h} Connection closed`),this.state===d.Paused)return n.A.info(`${h} Connection closed while paused — will reconnect on resume`),this.connection=null,void this.stopMicrophone();this.state=d.Disconnected,this.clientMsgSend(new s.WY(!1)),this.shouldReconnect&&(n.A.info(`${h} Unexpected disconnect, attempting reconnection...`),this.scheduleReconnect())}sendChatPrompt(t){t&&""!==t.trim()&&(this.options.language&&(this.options.promptMetadata.userSpokenLocale=this.options.language),this.dataChannelMsgSend(new o.D(t,this.options.promptMetadata)))}handleSpeakingEnd(){this.digitalHumanSpeaking=!1}emitTransientError(t){const e=t instanceof Error?t.message:String(t);this.clientMsgSend(new s.fP(e))}dataChannelMsgSend(t){this.options.sendMessage(t)}clientMsgSend(t){this.options.messages.next(t)}}}}]);
1
+ "use strict";(Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[]).push([[3],{3(t,e,i){i.d(e,{DeepgramSTT:()=>p});var n=i(514),s=i(838),a=i(33),o=i(388),r=i(58),c=i(622);const h="[Deepgram STT]";var u,d;!function(t){t.FinalTranscript="Final transcript (from accumulated)",t.UtteranceEndFallback="UtteranceEnd fallback",t.SafetyNet="Safety net"}(u||(u={})),function(t){t.Idle="Idle",t.Connecting="Connecting",t.Connected="Connected",t.Paused="Paused",t.Disconnected="Disconnected"}(d||(d={}));class p{options;connection=null;state=d.Idle;shouldReconnect=!0;microphone=null;stream=null;reconnectAttempts=0;reconnectDelay=1e3;reconnectTimeoutId=null;digitalHumanSpeaking=!1;isUserCurrentlySpeaking=!1;isUiShowingSpeaking=!1;accumulatedTranscript="";accumulatedConfidenceSum=0;accumulatedWordCount=0;lastDeepgramEventTime=0;safetyNetTimeoutId=null;constructor(t){this.options=t,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??3,this.options.noDelay=this.options.noDelay??!1,this.options.safetyNetTimeoutMs=this.options.safetyNetTimeoutMs??2e3,this.options.safetyNetTimeoutMs<=500?(n.A.warn(`${h} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms. This is very short and may cause premature transcript finalization. Ignoring and default the value to 2000ms.`),this.options.safetyNetTimeoutMs=2e3):this.options.safetyNetTimeoutMs<=1e3?n.A.warn(`${h} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms. This is very short and may cause premature transcript finalization. Recommended value is 2000ms.`):n.A.info(`${h} safetyNetTimeoutMs is set to ${this.options.safetyNetTimeoutMs}ms.`),this.handleAppMessages()}async startRecognition(){n.A.info(`${h} Starting speech recognition`),this.shouldReconnect=!0,this.resetReconnectionState(),await this.connect()}async stopRecognition(){n.A.info(`${h} Stopping speech recognition`),this.shouldReconnect=!1,this.clearReconnectTimeout(),await this.disconnect()}async pause(){return n.A.info(`${h} Pausing speech recognition`),this.state=d.Paused,this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null),this.resetAccumulatedState(),this.resetSpeakingStates(),this.stream&&(this.stream.getTracks().forEach(t=>{t.enabled=!1}),n.A.debug(`${h} Audio tracks disabled`)),!0}async resume(){if(n.A.info(`${h} Resuming speech recognition`),this.state===d.Paused){if(this.stream)return this.state=d.Connected,this.stream.getTracks().forEach(t=>{t.enabled=!0}),n.A.debug(`${h} Audio tracks re-enabled`),!0;if(this.connection)return this.state=d.Connected,await this.startMicrophone(),!0;this.state=d.Disconnected}return n.A.debug(`${h} Initiating connection`),await this.connect(),!0}setChatMetadata(t){this.options.promptMetadata=t}async connect(){if(this.state!==d.Connected)if(this.state!==d.Connecting){this.state=d.Connecting;try{const t=await this.getToken();n.A.info(`${h} Connecting to Deepgram`);const e=new c.c({accessToken:t.token,baseUrl:t.api_url}),i={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=e.listen;if(this.connection=await s.v1.connect(i),this.connection.connect(),await Promise.race([this.connection.waitForOpen(),new Promise((t,e)=>setTimeout(()=>e(new Error("Connection timeout")),1e4))]),this.state!==d.Paused&&this.state!==d.Disconnected&&(this.state=d.Connected),n.A.info(`${h} Connection opened`),this.setupEventHandlers(),this.state===d.Paused)return n.A.info(`${h} Pause requested during connection — staying paused`),void this.resetReconnectionState();if(this.state===d.Disconnected)return n.A.info(`${h} Recognition stopped during connection — aborting`),void(this.connection&&(this.connection.close(),this.connection=null));await this.startMicrophone(),n.A.info(`${h} Connected successfully`),this.resetReconnectionState()}catch(t){this.state=d.Disconnected,n.A.error(`${h} Connection error`,n.A.serialiseError(t)),this.shouldReconnect&&(this.emitTransientError(t),this.scheduleReconnect())}}else n.A.warn(`${h} Connection already in progress`);else n.A.warn(`${h} Already connected`)}async disconnect(){if(this.state!==d.Idle&&(this.state!==d.Disconnected||this.connection)){n.A.info(`${h} Disconnecting`),this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null);try{this.stopMicrophone(),this.connection&&(this.connection.close(),this.connection=null)}catch(t){n.A.error(`${h} Disconnect error`,n.A.serialiseError(t))}this.resetAccumulatedState(),this.resetSpeakingStates(),this.state=d.Disconnected,this.clientMsgSend(new s.WY(!1))}}scheduleReconnect(){if(this.reconnectAttempts>=5)return n.A.error(`${h} Max reconnection attempts (5) reached`),void this.clientMsgSend(new s.Cj("Unable to connect to speech recognition service after 5 attempts"));this.reconnectAttempts++,n.A.info(`${h} Scheduling reconnection attempt ${this.reconnectAttempts}/5 in ${this.reconnectDelay}ms`),this.reconnectTimeoutId=setTimeout(()=>{this.connect()},this.reconnectDelay),this.reconnectDelay=Math.min(2*this.reconnectDelay,3e4)}resetReconnectionState(){this.reconnectAttempts=0,this.reconnectDelay=1e3,this.clearReconnectTimeout()}clearReconnectTimeout(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null)}async getToken(){const t=this.options.model||"nova-3",e=`${this.options.connectionUrl}/speech-recognition-service/deepgram/token?model=${encodeURIComponent(t)}`,i=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.options.jwtToken}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Token fetch failed: ${i.status} ${i.statusText}`);return await i.json()}async startMicrophone(){try{if(n.A.info(`${h} 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===d.Paused)return n.A.info(`${h} Paused during getUserMedia — keeping stream but disabling tracks`),void this.stream.getTracks().forEach(t=>{t.enabled=!1});if(this.state===d.Disconnected)return n.A.info(`${h} Recognition stopped during getUserMedia — releasing stream`),this.stream.getTracks().forEach(t=>{t.stop()}),void(this.stream=null);this.microphone=new MediaRecorder(this.stream,{mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:48e3}),this.microphone.ondataavailable=t=>{t.data.size>0&&this.connection&&this.state===d.Connected&&t.data.arrayBuffer().then(t=>{this.connection?.sendMedia(t)}).catch(t=>{n.A.error(`${h} Error converting audio data`,n.A.serialiseError(t))})},this.microphone.start(250),n.A.debug(`${h} Microphone started`),this.clientMsgSend(new s.WY(!0))}catch(t){n.A.error(`${h} Microphone error`,n.A.serialiseError(t)),this.clientMsgSend(new s.co(new Error(JSON.stringify(t))))}}stopMicrophone(){this.microphone&&"recording"===this.microphone.state&&(this.microphone.stop(),this.microphone=null),this.stream&&(this.stream.getTracks().forEach(t=>{t.stop()}),this.stream=null),n.A.debug(`${h} Microphone stopped`)}setupEventHandlers(){this.connection&&(this.connection.on("open",()=>{this.handleConnectionOpen()}),this.connection.on("message",t=>{if(null!==t&&"object"==typeof t&&"type"in t){const e=t;"Results"===e.type?this.handleTranscript(t):"UtteranceEnd"===e.type?this.handleUtteranceEnd(t):"Metadata"===e.type&&n.A.debug(`${h} Metadata`,t)}}),this.connection.on("close",()=>{this.handleConnectionClose()}),this.connection.on("error",t=>{n.A.error(`${h} WebSocket error event`,n.A.serialiseError(t)),this.emitTransientError(t)}))}handleAppMessages(){this.options.messages.subscribe(t=>{switch(t.uneeqMessageType){case s.Yg.AvatarStartedSpeaking:this.digitalHumanSpeaking=!0;break;case s.Yg.PromptResult:t.promptResult.success||this.handleSpeakingEnd();break;case s.Yg.AvatarAnswer:""===t.answerSpeech.replace(/<[^>]*>/g,"")&&this.handleSpeakingEnd();break;case s.Yg.AvatarStoppedSpeaking:this.handleSpeakingEnd();break;case s.Yg.SessionEnded:this.shouldReconnect=!1,this.stopRecognition();break;case s.Yg.SessionReconnecting:this.handleSpeakingEnd(),this.pause();break;case s.Yg.CustomMetadataUpdated:this.options.promptMetadata=t.chatMetadata;break;case s.Yg.SessionBackendError:this.handleSpeakingEnd()}})}handleTranscript(t){try{this.lastDeepgramEventTime=Date.now();const e=t.channel;if(!e?.alternatives||0===e.alternatives.length)return;const i=e.alternatives[0],s=String(i.transcript||""),a=t.is_final,o=t.speech_final;if(n.A.debug(`${h} Transcript event: is_final=${a}, speech_final=${o}, 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&&o)return void(this.endsWithPunctuation(this.accumulatedTranscript)?(this.sendAccumulatedTranscript(u.FinalTranscript),this.resetSpeakingStates()):n.A.debug(`${h} speech_final with empty transcript but no punctuation, waiting for more speech or safety net`));if(""===s)return;this.processTranscriptChunk(s,i.confidence,a,o),this.updateSpeakingAndInterruptionState(s,o),this.emitTranscriptionResult(s,i.confidence,o),this.resetSafetyNetTimeout()}catch(t){n.A.error(`${h} Error processing transcript`,n.A.serialiseError(t))}}processTranscriptChunk(t,e,i,s){if(i&&!s){""!==this.accumulatedTranscript&&(this.accumulatedTranscript+=" "),this.accumulatedTranscript+=t;const i=t.trim().split(/\s+/).length,s=e??1;this.accumulatedConfidenceSum+=s*i,this.accumulatedWordCount+=i,n.A.debug(`${h} Accumulated transcript: "${this.accumulatedTranscript}"`)}}updateSpeakingAndInterruptionState(t,e){const i=(""!==this.accumulatedTranscript?this.accumulatedTranscript:t).trim().split(/\s+/).length,o=this.options.interruptionWordThreshold??3;this.isUiShowingSpeaking||(this.isUiShowingSpeaking=!0,this.clientMsgSend(new s._4));const c=!this.digitalHumanSpeaking||i>=o,u=""!==this.accumulatedTranscript?this.accumulatedTranscript+" "+t:t,d=e&&this.endsWithPunctuation(u);!this.isUserCurrentlySpeaking&&c&&(this.isUserCurrentlySpeaking=!0,this.dataChannelMsgSend(new a.A(a.f.Start))),this.digitalHumanSpeaking&&i>=o&&(n.A.debug(`${h} Interrupting digital human`),this.dataChannelMsgSend(new r.f),this.clientMsgSend(new s.tc),this.digitalHumanSpeaking=!1),this.isUserCurrentlySpeaking&&d&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new a.A(a.f.Stop))),this.isUiShowingSpeaking&&d&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new s.im))}emitTranscriptionResult(t,e,i){const a=""!==this.accumulatedTranscript?this.accumulatedTranscript+" "+t:t,o=i&&this.endsWithPunctuation(a),r={transcript:i?a:t,final:o,confidence:e??1,language_code:this.options.language||""};if(this.clientMsgSend(new s.Ux(r)),o){const t=a.trim().split(/\s+/).length,e=this.options.interruptionWordThreshold??3;this.digitalHumanSpeaking&&t<e?n.A.debug(`${h} Discarding utterance during speaking (${t} words < ${e} threshold): "${a}"`):(n.A.info(`${h} Final transcript: "${a}"`),this.sendChatPrompt(a)),this.resetAccumulatedState()}else if(i){""!==this.accumulatedTranscript&&(this.accumulatedTranscript+=" "),this.accumulatedTranscript+=t;const i=t.trim().split(/\s+/).length;this.accumulatedConfidenceSum+=(e??1)*i,this.accumulatedWordCount+=i,n.A.debug(`${h} speech_final without punctuation, accumulated for safety net: "${this.accumulatedTranscript}"`)}}handleUtteranceEnd(t){this.lastDeepgramEventTime=Date.now(),n.A.debug(`${h} UtteranceEnd event received: last_word_end=${t?.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),n.A.debug(`${h} UtteranceEnd fallback triggered with transcript: "${this.accumulatedTranscript}"`),this.sendAccumulatedTranscript(u.UtteranceEndFallback),this.resetSpeakingStates(),n.A.debug(`${h} UtteranceEnd: reset speaking states`)):n.A.debug(`${h} UtteranceEnd: no punctuation, waiting for more speech or safety net`):(this.safetyNetTimeoutId&&(clearTimeout(this.safetyNetTimeoutId),this.safetyNetTimeoutId=null),this.resetSpeakingStates(),n.A.debug(`${h} 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(){n.A.warn(`${h} Safety net triggered: no Deepgram events for ${this.options.safetyNetTimeoutMs}ms while speaking`),n.A.debug(`${h} Safety net triggered: accumulated="${this.accumulatedTranscript}", uiSpeaking=${this.isUiShowingSpeaking}, userSpeaking=${this.isUserCurrentlySpeaking}, timeSinceLastEvent=${Date.now()-this.lastDeepgramEventTime}ms`),this.sendAccumulatedTranscript(u.SafetyNet),this.resetSpeakingStates(),this.safetyNetTimeoutId=null}sendAccumulatedTranscript(t){if(""===this.accumulatedTranscript.trim())return;if(t!==u.SafetyNet&&!this.endsWithPunctuation(this.accumulatedTranscript))return void n.A.debug(`${h} sendAccumulatedTranscript: not sending as source is ${t} and transcript doesn't end in punctuation: "${this.accumulatedTranscript}"`);const e=this.options.interruptionWordThreshold??3,i=this.accumulatedWordCount>0?this.accumulatedConfidenceSum/this.accumulatedWordCount:1,a={transcript:this.accumulatedTranscript,final:!0,confidence:i,language_code:this.options.language||""};this.clientMsgSend(new s.Ux(a));const o=this.accumulatedTranscript.trim().split(/\s+/).length;this.digitalHumanSpeaking&&o<e?n.A.debug(`${h} Discarding utterance during speaking (${o} words < ${e} threshold): "${this.accumulatedTranscript}"`):(n.A.info(`${h} ${t}: "${this.accumulatedTranscript}"`),this.sendChatPrompt(this.accumulatedTranscript)),this.resetAccumulatedState()}endsWithPunctuation(t){const e=t.trim();return 0!==e.length&&/[.!?;:]$/.test(e)}resetAccumulatedState(){this.accumulatedTranscript="",this.accumulatedConfidenceSum=0,this.accumulatedWordCount=0}resetSpeakingStates(){this.isUserCurrentlySpeaking&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new a.A(a.f.Stop))),this.isUiShowingSpeaking&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new s.im))}handleConnectionOpen(){this.state!==d.Paused&&(this.state=d.Connected)}handleConnectionClose(){if(n.A.info(`${h} Connection closed`),this.state===d.Paused)return n.A.info(`${h} Connection closed while paused — will reconnect on resume`),this.connection=null,void this.stopMicrophone();this.state=d.Disconnected,this.clientMsgSend(new s.WY(!1)),this.shouldReconnect&&(n.A.info(`${h} Unexpected disconnect, attempting reconnection...`),this.scheduleReconnect())}sendChatPrompt(t){t&&""!==t.trim()&&(this.options.language&&(this.options.promptMetadata.userSpokenLocale=this.options.language),this.dataChannelMsgSend(new o.D(t,this.options.promptMetadata)))}handleSpeakingEnd(){this.digitalHumanSpeaking=!1}emitTransientError(t){const e=t instanceof Error?t.message:String(t);this.clientMsgSend(new s.fP(e))}dataChannelMsgSend(t){this.options.sendMessage(t)}clientMsgSend(t){this.options.messages.next(t)}}}}]);
2
2
  //# sourceMappingURL=3.index.js.map
package/dist/363.index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";(Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[]).push([[363],{363(e,t,n){n.d(t,{DeepgramFluxSTT:()=>l});var s=n(514),i=n(838),o=n(33),r=n(388),a=n(58),c=n(1),h=n(260);const d="[Deepgram Flux STT]";var u;!function(e){e.Idle="Idle",e.Connecting="Connecting",e.Connected="Connected",e.Paused="Paused",e.Disconnected="Disconnected"}(u||(u={}));class l{options;connection=null;state=u.Idle;shouldReconnect=!0;stream=null;audioContext=null;workletNode=null;reconnectAttempts=0;reconnectDelay=1e3;reconnectTimeoutId=null;digitalHumanSpeaking=!1;pendingPromptRequest=null;isUserCurrentlySpeaking=!1;isUiShowingSpeaking=!1;eagerPromptSentForTurn=!1;cancelledEagerRequestId=void 0;turnStartedAt=null;safetyNetTimeoutId=null;audioChunksSent=0;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??2e3,this.options.echoCancellation=this.options.echoCancellation??!0,this.options.noiseSuppression=this.options.noiseSuppression??!0,this.options.autoGainControl=this.options.autoGainControl??!0;const t=0===this.options.eagerEotThreshold?"disabled":`${this.options.eagerEotThreshold}`,n=0===this.options.eagerMaxTurnDurationMs?"disabled":`${this.options.eagerMaxTurnDurationMs}ms`;s.A.debug(`${d} init — features: pure-flux-event-flow, eot_threshold=${this.options.eotThreshold}, eager_eot_threshold=${t}, eot_timeout_ms=${this.options.eotTimeoutMs}, eager_max_turn_duration_ms=${n}`),this.handleAppMessages()}async startRecognition(){s.A.info(`${d} Starting speech recognition`),this.shouldReconnect=!0,this.resetReconnectionState(),await this.connect()}async stopRecognition(){s.A.info(`${d} Stopping speech recognition`),this.shouldReconnect=!1,this.clearReconnectTimeout(),await this.disconnect()}async pause(){return s.A.info(`${d} Pausing speech recognition`),this.state=u.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}),s.A.debug(`${d} Audio tracks disabled`)),!0}async resume(){if(s.A.info(`${d} Resuming speech recognition`),this.state===u.Paused){if(this.stream)return this.state=u.Connected,this.stream.getTracks().forEach(e=>{e.enabled=!0}),s.A.debug(`${d} Audio tracks re-enabled`),!0;if(this.connection)return this.state=u.Connected,await this.startMicrophone(),!0;this.state=u.Disconnected}return s.A.debug(`${d} Initiating connection`),await this.connect(),!0}setChatMetadata(e){this.options.promptMetadata=e}async connect(){if(this.state!==u.Connected)if(this.state!==u.Connecting){this.state=u.Connecting;try{const e=await this.getToken();s.A.info(`${d} Connecting to Deepgram Flux v2 — api_url="${e.api_url}", sdk_version="${e.sdk_version}", token_length=${e.token?.length??0}`);const t=new h.c({accessToken:e.token,baseUrl:e.api_url}),n={model:this.options.model,encoding:"linear16",sample_rate:String(16e3),mip_opt_out:"true",...void 0!==this.options.eotThreshold&&{eot_threshold:this.options.eotThreshold},...void 0!==this.options.eagerEotThreshold&&this.options.eagerEotThreshold>0&&{eager_eot_threshold:this.options.eagerEotThreshold},...void 0!==this.options.eotTimeoutMs&&{eot_timeout_ms:this.options.eotTimeoutMs},...this.options.keyterms&&this.options.keyterms.length>0&&{keyterm:this.options.keyterms}};if("flux-general-multi"===this.options.model&&this.options.language&&(n.language_hint=this.options.language),this.connection=await t.listen.v2.connect(n),this.connection.connect(),await Promise.race([this.connection.waitForOpen(),new Promise((e,t)=>setTimeout(()=>t(new Error("Connection timeout")),1e4))]),this.state!==u.Paused&&(this.state=u.Connected),s.A.info(`${d} Connection opened`),this.setupEventHandlers(),this.state===u.Paused)return s.A.info(`${d} Pause requested during connection — staying paused`),void this.resetReconnectionState();await this.startMicrophone(),s.A.info(`${d} Connected successfully`),this.resetReconnectionState()}catch(e){this.state=u.Disconnected,s.A.error(`${d} Connection error`,s.A.serialiseError(e)),this.shouldReconnect&&(this.emitTransientError(e),this.scheduleReconnect())}}else s.A.warn(`${d} Connection already in progress`);else s.A.warn(`${d} Already connected`)}async disconnect(){if(this.state!==u.Idle&&(this.state!==u.Disconnected||this.connection)){s.A.info(`${d} Disconnecting`);try{if(this.stopMicrophone(),this.connection){try{this.connection.sendCloseStream({type:"CloseStream"})}catch{}this.connection.close(),this.connection=null}}catch(e){s.A.error(`${d} Disconnect error`,s.A.serialiseError(e))}this.clearSafetyNet(),this.resetSpeakingStates(),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.pendingPromptRequest=null,this.cancelledEagerRequestId=void 0,this.state=u.Disconnected,this.clientMsgSend(new i.WY(!1))}}scheduleReconnect(){if(this.reconnectAttempts>=5)return s.A.error(`${d} Max reconnection attempts (5) reached`),void this.clientMsgSend(new i.Cj("Unable to connect to speech recognition service after 5 attempts"));this.reconnectAttempts++,s.A.info(`${d} Scheduling reconnection attempt ${this.reconnectAttempts}/5 in ${this.reconnectDelay}ms`),this.reconnectTimeoutId=setTimeout(()=>{this.connect()},this.reconnectDelay),this.reconnectDelay=Math.min(2*this.reconnectDelay,3e4)}resetReconnectionState(){this.reconnectAttempts=0,this.reconnectDelay=1e3,this.clearReconnectTimeout()}clearReconnectTimeout(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null)}async getToken(){const e=this.options.model||"flux-general-en",t=`${this.options.connectionUrl}/speech-recognition-service/deepgram/token?model=${encodeURIComponent(e)}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.options.jwtToken}`,"Content-Type":"application/json"}});if(!n.ok)throw new Error(`Token fetch failed: ${n.status} ${n.statusText}`);return await n.json()}async startMicrophone(){try{if(s.A.info(`${d} 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===u.Paused)return s.A.info(`${d} Paused during getUserMedia — keeping stream but disabling tracks`),void this.stream.getTracks().forEach(e=>{e.enabled=!1});this.audioContext=new AudioContext({sampleRate:16e3});const e=this.audioContext.createMediaStreamSource(this.stream),t=new Blob(["\nclass PcmCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super()\n this._buffer = new Float32Array(1280)\n this._offset = 0\n }\n process(inputs, outputs, parameters) {\n const input = inputs[0]?.[0]\n if (!input) return true\n for (let i = 0; i < input.length; i++) {\n this._buffer[this._offset++] = input[i]\n if (this._offset >= this._buffer.length) {\n const int16 = new Int16Array(this._buffer.length)\n for (let j = 0; j < this._buffer.length; j++) {\n const s = Math.max(-1, Math.min(1, this._buffer[j]))\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF\n }\n this.port.postMessage(int16.buffer, [int16.buffer])\n this._offset = 0\n }\n }\n return true\n }\n}\nregisterProcessor('pcm-capture-processor', PcmCaptureProcessor)\n"],{type:"application/javascript"}),n=URL.createObjectURL(t);await this.audioContext.audioWorklet.addModule(n),URL.revokeObjectURL(n),this.workletNode=new AudioWorkletNode(this.audioContext,"pcm-capture-processor"),this.audioChunksSent=0,this.workletNode.port.onmessage=e=>{this.connection&&this.state===u.Connected&&(this.connection.sendMedia(e.data),this.audioChunksSent++,this.audioChunksSent%50==1&&s.A.debug(`${d} Audio chunks sent: ${this.audioChunksSent}, size: ${e.data.byteLength} bytes`))},e.connect(this.workletNode),this.workletNode.connect(this.audioContext.destination),s.A.info(`${d} Microphone started (linear16 PCM @ 16000Hz)`),this.clientMsgSend(new i.WY(!0))}catch(e){s.A.error(`${d} Microphone error`,s.A.serialiseError(e)),this.clientMsgSend(new i.co(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),s.A.info(`${d} Microphone stopped`)}setupEventHandlers(){this.connection&&(this.connection.on("open",()=>{this.handleConnectionOpen()}),this.connection.on("message",e=>{if(null!==e&&"object"==typeof e&&"type"in e){const t=e;"TurnInfo"===t.type?this.handleTurnInfo(e):"Connected"===t.type?s.A.info(`${d} v2 connection confirmed`):"Error"===t.type?this.handleFatalError(e):s.A.debug(`${d} Unhandled v2 message type: ${t.type}`)}}),this.connection.on("close",e=>{this.handleConnectionClose(e)}),this.connection.on("error",e=>{const t={};e instanceof Event&&(t.type=e.type,t.target=e.target?.url??e.target?.readyState??"unknown"),s.A.error(`${d} WebSocket error event`,e,t),this.emitTransientError(e)}))}handleTurnInfo(e){try{switch(s.A.debug(`${d} 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:s.A.debug(`${d} Unknown TurnInfo event: ${e.event}`)}}catch(e){s.A.error(`${d} Error processing TurnInfo`,s.A.serialiseError(e))}finally{this.resetSafetyNet()}}handleStartOfTurn(e){s.A.debug(`${d} StartOfTurn: turn_index=${e.turn_index}`),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.cancelledEagerRequestId=void 0}handleUpdate(e){const t=e.transcript||"";if(""===t)return;if(this.isUiShowingSpeaking||(this.isUiShowingSpeaking=!0,this.turnStartedAt=Date.now(),this.clientMsgSend(new i._4)),this.isUserCurrentlySpeaking||(this.isUserCurrentlySpeaking=!0,this.dataChannelMsgSend(new o.A(o.f.Start))),this.digitalHumanSpeaking){const e=this.countWords(t);e>=3?(s.A.info(`${d} User speech detected during avatar speaking (${e} words) — interrupting`),this.dataChannelMsgSend(new a.f),this.clientMsgSend(new i.tc),this.digitalHumanSpeaking=!1):s.A.debug(`${d} User speech during avatar speaking is only ${e} word(s) — holding off barge-in (potential backchannel)`)}const n={transcript:t,final:!1,confidence:this.calculateWordConfidence(e.words),language_code:this.options.language||""};this.clientMsgSend(new i.Ux(n))}handleEagerEndOfTurn(e){const t=e.transcript||"";if(s.A.debug(`${d} EagerEndOfTurn: confidence=${e.end_of_turn_confidence}, transcript_length=${t.length}`),""===t.trim())return;if(this.digitalHumanSpeaking&&this.countWords(t)<3)return void s.A.info(`${d} EagerEndOfTurn: dropping ${this.countWords(t)}-word backchannel while avatar speaking`);const n=this.options.eagerMaxTurnDurationMs??0;if(n>0&&null!==this.turnStartedAt){const e=Date.now()-this.turnStartedAt;if(e>n)return void s.A.info(`${d} EagerEndOfTurn: suppressed — turn duration ${e}ms exceeds eagerMaxTurnDurationMs=${n}; deferring to EndOfTurn`)}s.A.info(`${d} EagerEndOfTurn: sending prompt early (${this.countWords(t)} words, ${t.length} chars)`),this.eagerPromptSentForTurn=!0,this.sendChatPromptRaw(t,this.takeCancelledEagerRequestId())}takeCancelledEagerRequestId(){const e=this.cancelledEagerRequestId;return this.cancelledEagerRequestId=void 0,e}handleTurnResumed(e){s.A.debug(`${d} TurnResumed: turn_index=${e.turn_index}`),null!==this.pendingPromptRequest&&(this.cancelledEagerRequestId=this.pendingPromptRequest.requestId),this.eagerPromptSentForTurn&&(s.A.info(`${d} TurnResumed: cancelling in-flight eager prompt via StopSpeaking`),this.dataChannelMsgSend(new a.f)),this.clearPendingPromptRequest(),this.eagerPromptSentForTurn=!1}handleEndOfTurn(e){const t=e.transcript||"";if(s.A.info(`${d} EndOfTurn: transcript_length=${t.length}, confidence=${e.end_of_turn_confidence}`),""!==t.trim()){const n={transcript:t,final:!0,confidence:this.calculateWordConfidence(e.words),language_code:this.options.language||""};this.clientMsgSend(new i.Ux(n)),this.digitalHumanSpeaking&&this.countWords(t)<3?(s.A.info(`${d} EndOfTurn: dropping ${this.countWords(t)}-word backchannel while avatar speaking`),this.clearPendingPromptRequest()):this.eagerPromptSentForTurn?(s.A.debug(`${d} EndOfTurn: skipping ChatPrompt — eager already fired for this turn`),this.emitPendingPromptRequest()):(this.sendChatPromptRaw(t,this.takeCancelledEagerRequestId()),this.emitPendingPromptRequest())}this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.cancelledEagerRequestId=void 0,this.resetSpeakingStates()}handleFatalError(e){if(this.state===u.Paused&&"INACTIVE_CLIENT"===e.code)return s.A.info(`${d} Inactivity termination while paused (${e.code}) — releasing socket; resume will reconnect`),void this.releasePausedConnection();s.A.error(`${d} Fatal error from Deepgram: ${e.code} — ${e.description}`),this.clientMsgSend(new i.Cj(`Deepgram error: ${e.code} — ${e.description}`))}calculateWordConfidence(e){return e&&0!==e.length?e.reduce((e,t)=>e+t.confidence,0)/e.length:1}countWords(e){return e.trim().split(/\s+/).filter(Boolean).length}handleAppMessages(){this.options.messages.subscribe(e=>{switch(e.uneeqMessageType){case i.Yg.AvatarStartedSpeaking:this.digitalHumanSpeaking=!0;break;case i.Yg.PromptResult:e.promptResult.success||this.handleSpeakingEnd();break;case i.Yg.AvatarAnswer:""===e.answerSpeech.replace(/<[^>]*>/g,"")&&this.handleSpeakingEnd();break;case i.Yg.AvatarStoppedSpeaking:this.handleSpeakingEnd();break;case i.Yg.SessionEnded:this.shouldReconnect=!1,this.stopRecognition();break;case i.Yg.SessionReconnecting:this.handleSpeakingEnd(),this.shouldReconnect=!1,this.stopRecognition();break;case i.Yg.CustomMetadataUpdated:this.options.promptMetadata=e.chatMetadata;break;case i.Yg.SessionBackendError:this.handleSpeakingEnd()}})}handleConnectionOpen(){this.state!==u.Paused&&(this.state=u.Connected)}handleConnectionClose(e){const t=e?.code??"unknown",n=e?.reason??"";if(s.A.info(`${d} Connection closed — code=${t}, reason="${n}"`),this.state===u.Paused)return s.A.info(`${d} Connection closed while paused — will reconnect on resume`),this.connection=null,this.stopMicrophone(),this.clearSafetyNet(),void this.resetSpeakingStates();this.state=u.Disconnected,this.clearSafetyNet(),this.resetSpeakingStates(),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.pendingPromptRequest=null,this.cancelledEagerRequestId=void 0,this.clientMsgSend(new i.WY(!1)),this.shouldReconnect&&(s.A.info(`${d} Unexpected disconnect, attempting reconnection...`),this.scheduleReconnect())}emitTransientError(e){const t=e instanceof Error?e.message:String(e);this.clientMsgSend(new i.fP(t))}sendChatPromptRaw(e,t){if(!e||""===e.trim())return;this.options.language&&(this.options.promptMetadata.userSpokenLocale=this.options.language);const n=t??(0,c.g)();void 0!==t&&s.A.info(`${d} sendChatPromptRaw: reusing requestId=${n} from cancelled eager prompt`);const i={...this.options.promptMetadata},o=this.turnStartedAt??Date.now(),a=Date.now()-o;this.pendingPromptRequest={prompt:e,requestId:n,metadata:i,speakingDurationMs:a,speechStartedAt:o},this.dataChannelMsgSend(new r.D(e,this.options.promptMetadata,n,!1))}emitPendingPromptRequest(){const e=this.pendingPromptRequest;null!==e&&(this.clientMsgSend(new i.bS({prompt:e.prompt,requestId:e.requestId,metadata:e.metadata,speakingDurationMs:e.speakingDurationMs,speechStartedAt:e.speechStartedAt})),s.A.debug(`${d} PromptRequest emitted — 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(()=>{s.A.warn(`${d} Safety net: no TurnInfo events for ${this.options.safetyNetTimeoutMs}ms while speaking — 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=u.Paused}resetSpeakingStates(){this.isUserCurrentlySpeaking&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new o.A(o.f.Stop))),this.isUiShowingSpeaking&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new i.im))}dataChannelMsgSend(e){this.options.sendMessage(e)}clientMsgSend(e){this.options.messages.next(e)}}}}]);
1
+ "use strict";(Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[]).push([[363],{363(e,t,n){n.d(t,{DeepgramFluxSTT:()=>l});var s=n(514),i=n(838),o=n(33),r=n(388),a=n(58),c=n(1),h=n(622);const d="[Deepgram Flux STT]";var u;!function(e){e.Idle="Idle",e.Connecting="Connecting",e.Connected="Connected",e.Paused="Paused",e.Disconnected="Disconnected"}(u||(u={}));class l{options;connection=null;state=u.Idle;shouldReconnect=!0;stream=null;audioContext=null;workletNode=null;reconnectAttempts=0;reconnectDelay=1e3;reconnectTimeoutId=null;digitalHumanSpeaking=!1;pendingPromptRequest=null;isUserCurrentlySpeaking=!1;isUiShowingSpeaking=!1;eagerPromptSentForTurn=!1;cancelledEagerRequestId=void 0;turnStartedAt=null;safetyNetTimeoutId=null;audioChunksSent=0;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??2e3,this.options.echoCancellation=this.options.echoCancellation??!0,this.options.noiseSuppression=this.options.noiseSuppression??!0,this.options.autoGainControl=this.options.autoGainControl??!0;const t=0===this.options.eagerEotThreshold?"disabled":`${this.options.eagerEotThreshold}`,n=0===this.options.eagerMaxTurnDurationMs?"disabled":`${this.options.eagerMaxTurnDurationMs}ms`;s.A.debug(`${d} init — features: pure-flux-event-flow, eot_threshold=${this.options.eotThreshold}, eager_eot_threshold=${t}, eot_timeout_ms=${this.options.eotTimeoutMs}, eager_max_turn_duration_ms=${n}`),this.handleAppMessages()}async startRecognition(){s.A.info(`${d} Starting speech recognition`),this.shouldReconnect=!0,this.resetReconnectionState(),await this.connect()}async stopRecognition(){s.A.info(`${d} Stopping speech recognition`),this.shouldReconnect=!1,this.clearReconnectTimeout(),await this.disconnect()}async pause(){return s.A.info(`${d} Pausing speech recognition`),this.state=u.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}),s.A.debug(`${d} Audio tracks disabled`)),!0}async resume(){if(s.A.info(`${d} Resuming speech recognition`),this.state===u.Paused){if(this.stream)return this.state=u.Connected,this.stream.getTracks().forEach(e=>{e.enabled=!0}),s.A.debug(`${d} Audio tracks re-enabled`),!0;if(this.connection)return this.state=u.Connected,await this.startMicrophone(),!0;this.state=u.Disconnected}return s.A.debug(`${d} Initiating connection`),await this.connect(),!0}setChatMetadata(e){this.options.promptMetadata=e}async connect(){if(this.state!==u.Connected)if(this.state!==u.Connecting){this.state=u.Connecting;try{const e=await this.getToken();s.A.info(`${d} Connecting to Deepgram Flux v2 — api_url="${e.api_url}", sdk_version="${e.sdk_version}", token_length=${e.token?.length??0}`);const t=new h.c({accessToken:e.token,baseUrl:e.api_url}),n={model:this.options.model,encoding:"linear16",sample_rate:String(16e3),mip_opt_out:"true",...void 0!==this.options.eotThreshold&&{eot_threshold:this.options.eotThreshold},...void 0!==this.options.eagerEotThreshold&&this.options.eagerEotThreshold>0&&{eager_eot_threshold:this.options.eagerEotThreshold},...void 0!==this.options.eotTimeoutMs&&{eot_timeout_ms:this.options.eotTimeoutMs},...this.options.keyterms&&this.options.keyterms.length>0&&{keyterm:this.options.keyterms}};if("flux-general-multi"===this.options.model&&this.options.language&&(n.language_hint=this.options.language),this.connection=await t.listen.v2.connect(n),this.connection.connect(),await Promise.race([this.connection.waitForOpen(),new Promise((e,t)=>setTimeout(()=>t(new Error("Connection timeout")),1e4))]),this.state!==u.Paused&&(this.state=u.Connected),s.A.info(`${d} Connection opened`),this.setupEventHandlers(),this.state===u.Paused)return s.A.info(`${d} Pause requested during connection — staying paused`),void this.resetReconnectionState();await this.startMicrophone(),s.A.info(`${d} Connected successfully`),this.resetReconnectionState()}catch(e){this.state=u.Disconnected,s.A.error(`${d} Connection error`,s.A.serialiseError(e)),this.shouldReconnect&&(this.emitTransientError(e),this.scheduleReconnect())}}else s.A.warn(`${d} Connection already in progress`);else s.A.warn(`${d} Already connected`)}async disconnect(){if(this.state!==u.Idle&&(this.state!==u.Disconnected||this.connection)){s.A.info(`${d} Disconnecting`);try{if(this.stopMicrophone(),this.connection){try{this.connection.sendCloseStream({type:"CloseStream"})}catch{}this.connection.close(),this.connection=null}}catch(e){s.A.error(`${d} Disconnect error`,s.A.serialiseError(e))}this.clearSafetyNet(),this.resetSpeakingStates(),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.pendingPromptRequest=null,this.cancelledEagerRequestId=void 0,this.state=u.Disconnected,this.clientMsgSend(new i.WY(!1))}}scheduleReconnect(){if(this.reconnectAttempts>=5)return s.A.error(`${d} Max reconnection attempts (5) reached`),void this.clientMsgSend(new i.Cj("Unable to connect to speech recognition service after 5 attempts"));this.reconnectAttempts++,s.A.info(`${d} Scheduling reconnection attempt ${this.reconnectAttempts}/5 in ${this.reconnectDelay}ms`),this.reconnectTimeoutId=setTimeout(()=>{this.connect()},this.reconnectDelay),this.reconnectDelay=Math.min(2*this.reconnectDelay,3e4)}resetReconnectionState(){this.reconnectAttempts=0,this.reconnectDelay=1e3,this.clearReconnectTimeout()}clearReconnectTimeout(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null)}async getToken(){const e=this.options.model||"flux-general-en",t=`${this.options.connectionUrl}/speech-recognition-service/deepgram/token?model=${encodeURIComponent(e)}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.options.jwtToken}`,"Content-Type":"application/json"}});if(!n.ok)throw new Error(`Token fetch failed: ${n.status} ${n.statusText}`);return await n.json()}async startMicrophone(){try{if(s.A.info(`${d} 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===u.Paused)return s.A.info(`${d} Paused during getUserMedia — keeping stream but disabling tracks`),void this.stream.getTracks().forEach(e=>{e.enabled=!1});this.audioContext=new AudioContext({sampleRate:16e3});const e=this.audioContext.createMediaStreamSource(this.stream),t=new Blob(["\nclass PcmCaptureProcessor extends AudioWorkletProcessor {\n constructor() {\n super()\n this._buffer = new Float32Array(1280)\n this._offset = 0\n }\n process(inputs, outputs, parameters) {\n const input = inputs[0]?.[0]\n if (!input) return true\n for (let i = 0; i < input.length; i++) {\n this._buffer[this._offset++] = input[i]\n if (this._offset >= this._buffer.length) {\n const int16 = new Int16Array(this._buffer.length)\n for (let j = 0; j < this._buffer.length; j++) {\n const s = Math.max(-1, Math.min(1, this._buffer[j]))\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF\n }\n this.port.postMessage(int16.buffer, [int16.buffer])\n this._offset = 0\n }\n }\n return true\n }\n}\nregisterProcessor('pcm-capture-processor', PcmCaptureProcessor)\n"],{type:"application/javascript"}),n=URL.createObjectURL(t);await this.audioContext.audioWorklet.addModule(n),URL.revokeObjectURL(n),this.workletNode=new AudioWorkletNode(this.audioContext,"pcm-capture-processor"),this.audioChunksSent=0,this.workletNode.port.onmessage=e=>{this.connection&&this.state===u.Connected&&(this.connection.sendMedia(e.data),this.audioChunksSent++,this.audioChunksSent%50==1&&s.A.debug(`${d} Audio chunks sent: ${this.audioChunksSent}, size: ${e.data.byteLength} bytes`))},e.connect(this.workletNode),this.workletNode.connect(this.audioContext.destination),s.A.info(`${d} Microphone started (linear16 PCM @ 16000Hz)`),this.clientMsgSend(new i.WY(!0))}catch(e){s.A.error(`${d} Microphone error`,s.A.serialiseError(e)),this.clientMsgSend(new i.co(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),s.A.info(`${d} Microphone stopped`)}setupEventHandlers(){this.connection&&(this.connection.on("open",()=>{this.handleConnectionOpen()}),this.connection.on("message",e=>{if(null!==e&&"object"==typeof e&&"type"in e){const t=e;"TurnInfo"===t.type?this.handleTurnInfo(e):"Connected"===t.type?s.A.info(`${d} v2 connection confirmed`):"Error"===t.type?this.handleFatalError(e):s.A.debug(`${d} Unhandled v2 message type: ${t.type}`)}}),this.connection.on("close",e=>{this.handleConnectionClose(e)}),this.connection.on("error",e=>{const t={};e instanceof Event&&(t.type=e.type,t.target=e.target?.url??e.target?.readyState??"unknown"),s.A.error(`${d} WebSocket error event`,e,t),this.emitTransientError(e)}))}handleTurnInfo(e){try{switch(s.A.debug(`${d} 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:s.A.debug(`${d} Unknown TurnInfo event: ${e.event}`)}}catch(e){s.A.error(`${d} Error processing TurnInfo`,s.A.serialiseError(e))}finally{this.resetSafetyNet()}}handleStartOfTurn(e){s.A.debug(`${d} StartOfTurn: turn_index=${e.turn_index}`),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.cancelledEagerRequestId=void 0}handleUpdate(e){const t=e.transcript||"";if(""===t)return;if(this.isUiShowingSpeaking||(this.isUiShowingSpeaking=!0,this.turnStartedAt=Date.now(),this.clientMsgSend(new i._4)),this.isUserCurrentlySpeaking||(this.isUserCurrentlySpeaking=!0,this.dataChannelMsgSend(new o.A(o.f.Start))),this.digitalHumanSpeaking){const e=this.countWords(t);e>=3?(s.A.info(`${d} User speech detected during avatar speaking (${e} words) — interrupting`),this.dataChannelMsgSend(new a.f),this.clientMsgSend(new i.tc),this.digitalHumanSpeaking=!1):s.A.debug(`${d} User speech during avatar speaking is only ${e} word(s) — holding off barge-in (potential backchannel)`)}const n={transcript:t,final:!1,confidence:this.calculateWordConfidence(e.words),language_code:this.options.language||""};this.clientMsgSend(new i.Ux(n))}handleEagerEndOfTurn(e){const t=e.transcript||"";if(s.A.debug(`${d} EagerEndOfTurn: confidence=${e.end_of_turn_confidence}, transcript_length=${t.length}`),""===t.trim())return;if(this.digitalHumanSpeaking&&this.countWords(t)<3)return void s.A.info(`${d} EagerEndOfTurn: dropping ${this.countWords(t)}-word backchannel while avatar speaking`);const n=this.options.eagerMaxTurnDurationMs??0;if(n>0&&null!==this.turnStartedAt){const e=Date.now()-this.turnStartedAt;if(e>n)return void s.A.info(`${d} EagerEndOfTurn: suppressed — turn duration ${e}ms exceeds eagerMaxTurnDurationMs=${n}; deferring to EndOfTurn`)}s.A.info(`${d} EagerEndOfTurn: sending prompt early (${this.countWords(t)} words, ${t.length} chars)`),this.eagerPromptSentForTurn=!0,this.sendChatPromptRaw(t,this.takeCancelledEagerRequestId())}takeCancelledEagerRequestId(){const e=this.cancelledEagerRequestId;return this.cancelledEagerRequestId=void 0,e}handleTurnResumed(e){s.A.debug(`${d} TurnResumed: turn_index=${e.turn_index}`),null!==this.pendingPromptRequest&&(this.cancelledEagerRequestId=this.pendingPromptRequest.requestId),this.eagerPromptSentForTurn&&(s.A.info(`${d} TurnResumed: cancelling in-flight eager prompt via StopSpeaking`),this.dataChannelMsgSend(new a.f)),this.clearPendingPromptRequest(),this.eagerPromptSentForTurn=!1}handleEndOfTurn(e){const t=e.transcript||"";if(s.A.info(`${d} EndOfTurn: transcript_length=${t.length}, confidence=${e.end_of_turn_confidence}`),""!==t.trim()){const n={transcript:t,final:!0,confidence:this.calculateWordConfidence(e.words),language_code:this.options.language||""};this.clientMsgSend(new i.Ux(n)),this.digitalHumanSpeaking&&this.countWords(t)<3?(s.A.info(`${d} EndOfTurn: dropping ${this.countWords(t)}-word backchannel while avatar speaking`),this.clearPendingPromptRequest()):this.eagerPromptSentForTurn?(s.A.debug(`${d} EndOfTurn: skipping ChatPrompt — eager already fired for this turn`),this.emitPendingPromptRequest()):(this.sendChatPromptRaw(t,this.takeCancelledEagerRequestId()),this.emitPendingPromptRequest())}this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.cancelledEagerRequestId=void 0,this.resetSpeakingStates()}handleFatalError(e){if(this.state===u.Paused&&"INACTIVE_CLIENT"===e.code)return s.A.info(`${d} Inactivity termination while paused (${e.code}) — releasing socket; resume will reconnect`),void this.releasePausedConnection();s.A.error(`${d} Fatal error from Deepgram: ${e.code} — ${e.description}`),this.clientMsgSend(new i.Cj(`Deepgram error: ${e.code} — ${e.description}`))}calculateWordConfidence(e){return e&&0!==e.length?e.reduce((e,t)=>e+t.confidence,0)/e.length:1}countWords(e){return e.trim().split(/\s+/).filter(Boolean).length}handleAppMessages(){this.options.messages.subscribe(e=>{switch(e.uneeqMessageType){case i.Yg.AvatarStartedSpeaking:this.digitalHumanSpeaking=!0;break;case i.Yg.PromptResult:e.promptResult.success||this.handleSpeakingEnd();break;case i.Yg.AvatarAnswer:""===e.answerSpeech.replace(/<[^>]*>/g,"")&&this.handleSpeakingEnd();break;case i.Yg.AvatarStoppedSpeaking:this.handleSpeakingEnd();break;case i.Yg.SessionEnded:this.shouldReconnect=!1,this.stopRecognition();break;case i.Yg.SessionReconnecting:this.handleSpeakingEnd(),this.shouldReconnect=!1,this.stopRecognition();break;case i.Yg.CustomMetadataUpdated:this.options.promptMetadata=e.chatMetadata;break;case i.Yg.SessionBackendError:this.handleSpeakingEnd()}})}handleConnectionOpen(){this.state!==u.Paused&&(this.state=u.Connected)}handleConnectionClose(e){const t=e?.code??"unknown",n=e?.reason??"";if(s.A.info(`${d} Connection closed — code=${t}, reason="${n}"`),this.state===u.Paused)return s.A.info(`${d} Connection closed while paused — will reconnect on resume`),this.connection=null,this.stopMicrophone(),this.clearSafetyNet(),void this.resetSpeakingStates();this.state=u.Disconnected,this.clearSafetyNet(),this.resetSpeakingStates(),this.eagerPromptSentForTurn=!1,this.turnStartedAt=null,this.pendingPromptRequest=null,this.cancelledEagerRequestId=void 0,this.clientMsgSend(new i.WY(!1)),this.shouldReconnect&&(s.A.info(`${d} Unexpected disconnect, attempting reconnection...`),this.scheduleReconnect())}emitTransientError(e){const t=e instanceof Error?e.message:String(e);this.clientMsgSend(new i.fP(t))}sendChatPromptRaw(e,t){if(!e||""===e.trim())return;this.options.language&&(this.options.promptMetadata.userSpokenLocale=this.options.language);const n=t??(0,c.g)();void 0!==t&&s.A.info(`${d} sendChatPromptRaw: reusing requestId=${n} from cancelled eager prompt`);const i={...this.options.promptMetadata},o=this.turnStartedAt??Date.now(),a=Date.now()-o;this.pendingPromptRequest={prompt:e,requestId:n,metadata:i,speakingDurationMs:a,speechStartedAt:o},this.dataChannelMsgSend(new r.D(e,this.options.promptMetadata,n,!1))}emitPendingPromptRequest(){const e=this.pendingPromptRequest;null!==e&&(this.clientMsgSend(new i.bS({prompt:e.prompt,requestId:e.requestId,metadata:e.metadata,speakingDurationMs:e.speakingDurationMs,speechStartedAt:e.speechStartedAt})),s.A.debug(`${d} PromptRequest emitted — 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(()=>{s.A.warn(`${d} Safety net: no TurnInfo events for ${this.options.safetyNetTimeoutMs}ms while speaking — 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=u.Paused}resetSpeakingStates(){this.isUserCurrentlySpeaking&&(this.isUserCurrentlySpeaking=!1,this.dataChannelMsgSend(new o.A(o.f.Stop))),this.isUiShowingSpeaking&&(this.isUiShowingSpeaking=!1,this.clientMsgSend(new i.im))}dataChannelMsgSend(e){this.options.sendMessage(e)}clientMsgSend(e){this.options.messages.next(e)}}}}]);
2
2
  //# sourceMappingURL=363.index.js.map
@@ -0,0 +1,2 @@
1
+ "use strict";(Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[]).push([[622],{591(e){e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},622(e,t,o){o.d(t,{c:()=>Gt});const n=e=>{return t=void 0,o=void 0,i=function*(){return"function"==typeof e?e():e},new((n=void 0)||(n=Promise))(function(e,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof n?o:new n(function(e){e(o)})).then(r,a)}l((i=i.apply(t,o||[])).next())});var t,o,n,i},i=(e,t,o)=>JSON.stringify(e,t,o);function s(e,t){return JSON.parse(e,t)}class r extends Error{constructor({message:e,statusCode:t,body:o,rawResponse:n,cause:s}){super(function({message:e,statusCode:t,body:o}){const n=[];return null!=e&&n.push(e),null!=t&&n.push(`Status code: ${t.toString()}`),null!=o&&n.push(`Body: ${i(o,void 0,2)}`),n.join("\n")}({message:e,statusCode:t,body:o})),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.statusCode=t,this.body=o,this.rawResponse=n,null!=s&&(this.cause=s)}}const a="apiKey",l="DEEPGRAM_API_KEY",d="Authorization";class u{constructor(e){this.options=e}static canCreate(e){var t;return null!=(null==e?void 0:e[a])||null!=(null===(t=process.env)||void 0===t?void 0:t[l])}getAuthRequest(){return e=this,t=arguments,i=function*({endpointMetadata:e}={}){var t,o;const i=null!==(t=yield n(this.options[a]))&&void 0!==t?t:null===(o=process.env)||void 0===o?void 0:o[l];if(null==i)throw new r({message:u.AUTH_CONFIG_ERROR_MESSAGE});return{headers:{[d]:i}}},new((o=void 0)||(o=Promise))(function(n,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())});var e,t,o,i}}function c(...e){const t={};for(const[o,n]of e.filter(e=>null!=e).flatMap(e=>Object.entries(e))){const e=o.toLowerCase();null!=n?t[e]=n:e in t&&delete t[e]}return t}function h(...e){const t={};for(const[o,n]of e.filter(e=>null!=e).flatMap(e=>Object.entries(e))){const e=o.toLowerCase();null!=n&&(t[e]=n)}return t}!function(e){e.AUTH_SCHEME="ApiKeyAuth",e.AUTH_CONFIG_ERROR_MESSAGE=`Please provide '${a}' when initializing the client, or set the '${l}' environment variable`,e.createInstance=function(t){return new e(t)}}(u||(u={}));const v=function(){var e,t,o,n,i;if("undefined"!=typeof window&&void 0!==window.document)return{type:"browser",version:window.navigator.userAgent};if("undefined"!=typeof globalThis&&"Cloudflare-Workers"===(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===e?void 0:e.userAgent))return{type:"workerd"};if("string"==typeof EdgeRuntime)return{type:"edge-runtime"};if("object"==typeof self&&"function"==typeof(null===self||void 0===self?void 0:self.importScripts)&&("DedicatedWorkerGlobalScope"===(null===(t=self.constructor)||void 0===t?void 0:t.name)||"ServiceWorkerGlobalScope"===(null===(o=self.constructor)||void 0===o?void 0:o.name)||"SharedWorkerGlobalScope"===(null===(n=self.constructor)||void 0===n?void 0:n.name)))return{type:"web-worker"};if("undefined"!=typeof Deno&&void 0!==Deno.version&&void 0!==Deno.version.deno)return{type:"deno",version:Deno.version.deno};if("undefined"!=typeof Bun&&void 0!==Bun.version)return{type:"bun",version:Bun.version};if("undefined"!=typeof navigator&&"ReactNative"===(null===navigator||void 0===navigator?void 0:navigator.product))return{type:"react-native"};const s="undefined"!=typeof process?process:void 0;return void 0!==s&&"string"==typeof(null===(i=s.versions)||void 0===i?void 0:i.node)?{type:"node",version:s.versions.node,parsedVersion:Number(s.versions.node.split(".")[0])}:{type:"unknown"}}(),p="debug",m="info",_="warn",f="error",g={[p]:1,[m]:2,[_]:3,[f]:4};class y{debug(e,...t){console.debug(e,...t)}info(e,...t){console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}}class w{constructor(e){this.level=g[e.level],this.logger=e.logger,this.silent=e.silent}shouldLog(e){return!this.silent&&this.level<=g[e]}isDebug(){return this.shouldLog(p)}debug(e,...t){this.isDebug()&&this.logger.debug(e,...t)}isInfo(){return this.shouldLog(m)}info(e,...t){this.isInfo()&&this.logger.info(e,...t)}isWarn(){return this.shouldLog(_)}warn(e,...t){this.isWarn()&&this.logger.warn(e,...t)}isError(){return this.shouldLog(f)}error(e,...t){this.isError()&&this.logger.error(e,...t)}}function b(e){var t,o,n;return null==e?R:e instanceof w?e:(null!==(t=(e=null!=e?e:{}).level)&&void 0!==t||(e.level=m),null!==(o=e.logger)&&void 0!==o||(e.logger=new y),null!==(n=e.silent)&&void 0!==n||(e.silent=!0),new w(e))}const R=new w({level:m,logger:new y,silent:!0});class S{getAuthRequest(){return Promise.resolve({headers:{}})}}function k(e){const t=c({"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":v.type,"X-Fern-Runtime-Version":v.version},null==e?void 0:e.headers);return Object.assign(Object.assign({},e),{logging:b(null==e?void 0:e.logging),headers:t})}function x(e){var t;const o=k(e),n=function(e){return Object.assign(Object.assign({},e),{authProvider:new S})}(o);return null!==(t=o.authProvider)&&void 0!==t||(o.authProvider=new u(n)),o}var P=o(591);const E={arrayFormat:"indices",encode:!0};function C(e,t){if(void 0===e)return"";if(null===e)return"";const o=String(e);return t?encodeURIComponent(o):o}function T(e,t="",o){const n=[];for(const[i,s]of Object.entries(e)){const e=t?`${t}[${i}]`:i;if(void 0!==s)if(Array.isArray(s)){if(0===s.length)continue;const t=o.arrayFormat;if("comma"===t){const t=o.encode?encodeURIComponent(e):e,i=s.filter(e=>null!=e).map(e=>C(e,o.encode));i.length>0&&n.push(`${t}=${i.join(",")}`)}else for(let i=0;i<s.length;i++){const r=s[i];if(void 0!==r)if("object"!=typeof r||Array.isArray(r)||null===r){const s="indices"===t?`${e}[${i}]`:e,a=o.encode?encodeURIComponent(s):s;n.push(`${a}=${C(r,o.encode)}`)}else{const s="indices"===t?`${e}[${i}]`:e;n.push(...T(r,s,o))}}}else if("object"==typeof s&&null!==s){if(0===Object.keys(s).length)continue;n.push(...T(s,e,o))}else{const t=o.encode?encodeURIComponent(e):e;n.push(`${t}=${C(s,o.encode)}`)}}return n}function j(e,t){return null==e||"object"!=typeof e?"":T(e,"",Object.assign(Object.assign({},E),t)).join("&")}class q{constructor(e,t){this.target=t,this.type=e}}class O extends q{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class A extends q{constructor(e=1e3,t="",o){super("close",o),this.wasClean=!0,this.code=e,this.reason=t}}const I=()=>"node"===v.type||"bun"===v.type||"deno"===v.type?P.WebSocket:"undefined"!=typeof WebSocket?WebSocket:void 0,L={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1};class M{constructor({url:e,protocols:t,options:o,headers:n,queryParameters:i,abortSignal:s}){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=M.CONNECTING,this.OPEN=M.OPEN,this.CLOSING=M.CLOSING,this.CLOSED=M.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 A(1e3,"aborted",this))}catch(e){}}},this._handleOpen=e=>{this._debug("open event");const{minUptime:t=L.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),t),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(e=>{var t;return null===(t=this._ws)||void 0===t?void 0:t.send(e)}),this._messageQueue=[],this.onopen&&this.onopen(e),this._listeners.open.forEach(t=>this._callEventListener(e,t))},this._handleMessage=e=>{this._debug("message event"),this.onmessage&&this.onmessage(e),this._listeners.message.forEach(t=>this._callEventListener(e,t))},this._handleError=e=>{this._debug("error event",e.message),this._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),this.onerror&&this.onerror(e),this._debug("exec error listeners"),this._listeners.error.forEach(t=>this._callEventListener(e,t)),this._connect()},this._handleClose=e=>{this._debug("close event"),this._clearTimeouts(),1e3===e.code&&(this._shouldReconnect=!1),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this._listeners.close.forEach(t=>this._callEventListener(e,t))},this._url=e,this._protocols=t,this._options=null!=o?o:L,this._headers=n,this._queryParameters=i,this._abortSignal=s,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((e,t)=>("string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e),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?M.ReadyState.CLOSED:M.ReadyState.CONNECTING}get url(){return this._ws?this._ws.url:""}close(e=1e3,t){this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")}reconnect(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{const{maxEnqueuedMessages:t=L.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&(this._debug("enqueue",e),this._messageQueue.push(e))}}addEventListener(e,t){this._listeners[e]&&this._listeners[e].push(t)}dispatchEvent(e){const t=this._listeners[e.type];if(t)for(const o of t)this._callEventListener(e,o);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(e=>e!==t))}_debug(...e){this._options.debug&&console.log.apply(console,["RWS>",...e])}_getNextDelay(){const{reconnectionDelayGrowFactor:e=L.reconnectionDelayGrowFactor,minReconnectionDelay:t=L.minReconnectionDelay,maxReconnectionDelay:o=L.maxReconnectionDelay}=this._options;let n=0;return this._retryCount>0&&(n=t*Math.pow(e,this._retryCount-1),n>o&&(n=o)),this._debug("next delay",n),n}_wait(){return new Promise(e=>{setTimeout(e,this._getNextDelay())})}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){var e;if(this._connectLock||!this._shouldReconnect)return;if(null===(e=this._abortSignal)||void 0===e?void 0:e.aborted)return void this._debug("connect aborted");this._connectLock=!0;const{maxRetries:t=L.maxRetries,connectionTimeout:o=L.connectionTimeout,WebSocket:n=I()}=this._options;if(this._retryCount>=t)this._debug("max retries reached",this._retryCount,">=",t);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),void 0===(i=n)||!i||2!==i.CLOSING)throw Error("No valid WebSocket class provided");var i;this._wait().then(()=>this._getNextUrl(this._url)).then(e=>{var t;if(this._closeCalled||(null===(t=this._abortSignal)||void 0===t?void 0:t.aborted))return void(this._connectLock=!1);const i={};if(this._headers&&(i.headers=this._headers),this._queryParameters&&Object.keys(this._queryParameters).length>0){const t=j(this._queryParameters,{arrayFormat:"repeat"});t&&(e=`${e}?${t}`)}this._ws=new n(e,this._protocols,i),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),o)})}}_handleTimeout(){this._debug("timeout event"),this._handleError(new O(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners(),this._ws.addEventListener("error",()=>{});try{this._ws.close(e,t),this._handleClose(new A(e,t,this))}catch(e){}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_callEventListener(e,t){"handleEvent"in t?t.handleEvent(e):t(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)}}function U(e,...t){if(!e)return"";if(0===t.length)return e;if(e.includes("://")){let o;try{o=new URL(e)}catch(o){return $(e,...t)}const n=t[t.length-1],i=null==n?void 0:n.endsWith("/");for(const e of t){const t=G(e);t&&(o.pathname=F(o.pathname,t))}return i&&!o.pathname.endsWith("/")&&(o.pathname+="/"),o.toString()}return $(e,...t)}function $(e,...t){if(0===t.length)return e;let o=e;const n=t[t.length-1],i=null==n?void 0:n.endsWith("/");for(const e of t){const t=G(e);t&&(o=F(o,t))}return i&&!o.endsWith("/")&&(o+="/"),o}function F(e,t){return e.endsWith("/")?e+t:`${e}/${t}`}function G(e){if(!e)return e;let t=0,o=e.length;return e.startsWith("/")&&(t=1),e.endsWith("/")&&(o=e.length-1),0===t&&o===e.length?e:e.slice(t,o)}M.CONNECTING=0,M.OPEN=1,M.CLOSING=2,M.CLOSED=3,function(e){e.ReadyState={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3}}(M||(M={}));const H={Production:{base:"https://api.deepgram.com",production:"wss://api.deepgram.com",agent:"wss://agent.deepgram.com",agentRest:"https://agent.deepgram.com"}};class D extends Promise{constructor(e){super(e=>{e(void 0)}),this.innerPromise=e}static fromFunction(e,...t){return new D(e(...t))}static interceptFunction(e){return(...t)=>D.fromPromise(e(...t))}static fromPromise(e){return new D(e)}static fromExecutor(e){const t=new Promise(e);return new D(t)}static fromResult(e){const t=Promise.resolve(e);return new D(t)}unwrap(){return this.unwrappedPromise||(this.unwrappedPromise=this.innerPromise.then(({data:e})=>e)),this.unwrappedPromise}then(e,t){return this.unwrap().then(e,t)}catch(e){return this.unwrap().catch(e)}finally(e){return this.unwrap().finally(e)}withRawResponse(){return e=this,t=void 0,n=function*(){return yield this.innerPromise},new((o=void 0)||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())});var e,t,o,n}}const z=(e,t)=>{return o=void 0,n=void 0,s=function*(){return"function"==typeof e?e(t):e},new((i=void 0)||(i=Promise))(function(e,t){function r(e){try{l(s.next(e))}catch(e){t(e)}}function a(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(o,n||[])).next())});var o,n,i,s};function N(e,t){return o=this,n=void 0,r=function*(){switch(t){case"binary-response":return function(e){const t={get bodyUsed(){return e.bodyUsed},stream:()=>e.body,arrayBuffer:e.arrayBuffer.bind(e),blob:e.blob.bind(e)};return"bytes"in e&&"function"==typeof e.bytes&&(t.bytes=e.bytes.bind(e)),t}(e);case"blob":return yield e.blob();case"arrayBuffer":return yield e.arrayBuffer();case"sse":case"streaming":return null==e.body?{ok:!1,error:{reason:"body-is-null",statusCode:e.status}}:e.body;case"text":return yield e.text()}const o=yield e.text();if(o.length>0)try{return s(o)}catch(t){return{ok:!1,error:{reason:"non-json",statusCode:e.status,rawBody:o}}}},new((i=void 0)||(i=Promise))(function(e,t){function s(e){try{l(r.next(e))}catch(e){t(e)}}function a(e){try{l(r.throw(e))}catch(e){t(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(s,a)}l((r=r.apply(o,n||[])).next())});var o,n,i,r}function B(e){return t=this,o=void 0,i=function*(){var t,o,n;let i=null===(t=e.headers.get("Content-Type"))||void 0===t?void 0:t.toLowerCase();if(null==i||0===i.length)return N(e);switch(-1!==i.indexOf(";")&&(i=null!==(n=null===(o=i.split(";")[0])||void 0===o?void 0:o.trim())&&void 0!==n?n:""),i){case"application/hal+json":case"application/json":case"application/ld+json":case"application/problem+json":case"application/vnd.api+json":case"text/json":{const t=yield e.text();return t.length>0?s(t):void 0}default:if(i.startsWith("application/vnd.")&&i.endsWith("+json")){const t=yield e.text();return t.length>0?s(t):void 0}return yield e.text()}},new((n=void 0)||(n=Promise))(function(e,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof n?o:new n(function(e){e(o)})).then(r,a)}l((i=i.apply(t,o||[])).next())});var t,o,n,i}function W(){return e=this,t=void 0,n=function*(){return fetch},new((o=void 0)||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())});var e,t,o,n}let J;J=void 0!==globalThis.Headers?globalThis.Headers:class e{constructor(t){if(this.headers=new Map,t)if(t instanceof e)t.forEach((e,t)=>this.append(t,e));else if(Array.isArray(t))for(const[e,o]of t){if("string"!=typeof e||"string"!=typeof o)throw new TypeError("Each header entry must be a [string, string] tuple");this.append(e,o)}else for(const[e,o]of Object.entries(t)){if("string"!=typeof o)throw new TypeError("Header values must be strings");this.append(e,o)}}append(e,t){const o=e.toLowerCase(),n=this.headers.get(o)||[];this.headers.set(o,[...n,t])}delete(e){const t=e.toLowerCase();this.headers.delete(t)}get(e){const t=e.toLowerCase(),o=this.headers.get(t);return o?o.join(", "):null}has(e){const t=e.toLowerCase();return this.headers.has(t)}set(e,t){const o=e.toLowerCase();this.headers.set(o,[t])}forEach(e,t){const o=t?e.bind(t):e;this.headers.forEach((e,t)=>o(e.join(", "),t,this))}getSetCookie(){return this.headers.get("set-cookie")||[]}*entries(){for(const[e,t]of this.headers.entries())yield[e,t.join(", ")]}*keys(){yield*this.headers.keys()}*values(){for(const e of this.headers.values())yield e.join(", ")}[Symbol.iterator](){return this.entries()}};let K;const X=(e,t,o,n,i,s,r,a,l,d)=>{return u=void 0,c=void 0,v=function*(){const u=[];let c;if(null!=s){const{signal:e,abortId:t}=function(e){const t=new AbortController,o=setTimeout(()=>t.abort("timeout"),e);return{signal:t.signal,abortId:o}}(s);c=t,u.push(e)}null!=r&&u.push(r);const h=function(...e){const t=1===e.length&&Array.isArray(e[0])?e[0]:e,o=new AbortController;for(const e of t){if(e.aborted){o.abort(null==e?void 0:e.reason);break}e.addEventListener("abort",()=>o.abort(null==e?void 0:e.reason),{signal:o.signal})}return o.signal}(u),v=yield e(t,Object.assign({method:o,headers:n,body:i,signal:h,credentials:a?"include":void 0,duplex:l},d&&function(){if(null!=K)return K;try{new Request("http://localhost",{cache:"no-store"}),K=!0}catch(e){K=!1}return K}()?{cache:"no-store"}:{}));return null!=c&&clearTimeout(c),v},new((h=void 0)||(h=Promise))(function(e,t){function o(e){try{i(v.next(e))}catch(e){t(e)}}function n(e){try{i(v.throw(e))}catch(e){t(e)}}function i(t){var i;t.done?e(t.value):(i=t.value,i instanceof h?i:new h(function(e){e(i)})).then(o,n)}i((v=v.apply(u,c||[])).next())});var u,c,h,v},Q={headers:new J,redirected:!1,status:499,statusText:"Client Closed Request",type:"error",url:""},V={headers:new J,redirected:!1,status:0,statusText:"Unknown Error",type:"error",url:""};function Y(e){return{headers:e.headers,redirected:e.redirected,status:e.status,statusText:e.statusText,type:e.type,url:e.url}}const Z=6e4;function ee(e,t){const o=e.headers.get("Retry-After");if(o){const e=parseInt(o,10);if(!Number.isNaN(e)&&e>0)return Math.min(1e3*e,Z);const t=new Date(o);if(!Number.isNaN(t.getTime())){const e=t.getTime()-Date.now();if(e>0)return Math.min(Math.max(e,0),Z)}}const n=e.headers.get("X-RateLimit-Reset");if(n){const e=parseInt(n,10);if(!Number.isNaN(e)){const t=1e3*e-Date.now();if(t>0)return function(e){return e*(1+.2*Math.random())}(Math.min(t,Z))}}return Math.min(1e3*Math.pow(2,t),Z)*(1+.2*(Math.random()-.5))}function te(e){return t=this,o=arguments,i=function*(e,t=2){let o=yield e();for(let n=0;n<t&&([408,429].includes(o.status)||o.status>=500);++n){const t=ee(o,n);yield new Promise(e=>setTimeout(e,t)),o=yield e()}return o},new((n=void 0)||(n=Promise))(function(e,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof n?o:new n(function(e){e(o)})).then(r,a)}l((i=i.apply(t,o||[])).next())});var t,o,n,i}var oe=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};const ne=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 ie(e){const t={};for(const[o,n]of e instanceof J?e.entries():Object.entries(e))ne.has(o.toLowerCase())?t[o]="[REDACTED]":t[o]=n;return t}const se=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 re(e){if(null==e)return;const t={};for(const[o,n]of Object.entries(e))t[o]=se.has(o.toLowerCase())?"[REDACTED]":n;return t}function ae(e){const t=e.indexOf("://");if(-1===t)return e;const o=t+3,n=e.indexOf("/",o);let i=e.indexOf("?",o),s=e.indexOf("#",o);const r=Math.min(-1===n?e.length:n,-1===i?e.length:i,-1===s?e.length:s);let a=-1;for(let t=o;t<r;t++)"@"===e[t]&&(a=t);if(-1!==a&&(e=`${e.slice(0,o)}[REDACTED]@${e.slice(a+1)}`),i=e.indexOf("?"),-1===i)return e;s=e.indexOf("#",i);const l=-1!==s?s:e.length,d=e.slice(i+1,l);if(0===d.length)return e;const u=d.toLowerCase();if(!(u.includes("token")||u.includes("key")||u.includes("password")||u.includes("passwd")||u.includes("secret")||u.includes("session")||u.includes("auth")))return e;const c=[],h=d.split("&");for(const e of h){const t=e.indexOf("=");if(-1===t){c.push(e);continue}const o=e.slice(0,t);let n=se.has(o.toLowerCase());if(!n&&o.includes("%"))try{const e=decodeURIComponent(o);n=se.has(e.toLowerCase())}catch(e){}c.push(n?`${o}=[REDACTED]`:e)}return e.slice(0,i+1)+c.join("&")+e.slice(l)}const le=function(e){return oe(this,void 0,void 0,function*(){var t,o,n;let s=e.url;s=null!=e.queryString&&e.queryString.length>0?`${s}?${e.queryString}`:function(e,t){const o=j(t,{arrayFormat:"repeat"});return o?`${e}?${o}`:e}(e.url,e.queryParameters);const r=yield function(e){return t=this,o=arguments,s=function*({body:e,type:t}){return"form"===t?j(e,{arrayFormat:"repeat",encode:!0}):t.includes("json")?i(e):e},new((n=void 0)||(n=Promise))(function(e,i){function r(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof n?o:new n(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,n,s}({body:e.body,type:null!==(t=e.requestType)&&void 0!==t?t:"other"}),a=null!==(o=e.fetchFn)&&void 0!==o?o:yield W(),l=yield function(e){return oe(this,void 0,void 0,function*(){var t;const o=new J;if(o.set("Accept","json"===e.responseType?"application/json":"text"===e.responseType?"text/plain":"sse"===e.responseType?"text/event-stream":"*/*"),void 0!==e.body&&null!=e.contentType&&o.set("Content-Type",e.contentType),null==e.headers)return o;for(const[n,i]of Object.entries(e.headers)){const s=yield z(i,{endpointMetadata:null!==(t=e.endpointMetadata)&&void 0!==t?t:{}});"string"!=typeof s?null!=s&&o.set(n,`${s}`):o.set(n,s)}return o})}(e),d=b(e.logging);if(d.isDebug()){const t={method:e.method,url:ae(s),headers:ie(l),queryParameters:re(e.queryParameters),hasBody:null!=r};d.debug("Making HTTP request",t)}try{const t=yield te(()=>oe(this,void 0,void 0,function*(){return X(a,s,e.method,l,r,e.timeoutMs,e.abortSignal,e.withCredentials,e.duplex,"streaming"===e.responseType||"sse"===e.responseType)}),e.maxRetries);if(t.status>=200&&t.status<400){if(d.isDebug()){const o={method:e.method,url:ae(s),statusCode:t.status,responseHeaders:ie(t.headers)};d.debug("HTTP request succeeded",o)}return{ok:!0,body:yield N(t,e.responseType),headers:t.headers,rawResponse:Y(t)}}if(d.isError()){const o={method:e.method,url:ae(s),statusCode:t.status,responseHeaders:ie(Object.fromEntries(t.headers.entries()))};d.error("HTTP request failed with error status",o)}return{ok:!1,error:{reason:"status-code",statusCode:t.status,body:yield B(t)},rawResponse:Y(t)}}catch(t){if(null===(n=e.abortSignal)||void 0===n?void 0:n.aborted){if(d.isError()){const t={method:e.method,url:ae(s)};d.error("HTTP request was aborted",t)}return{ok:!1,error:{reason:"unknown",errorMessage:"The user aborted a request",cause:t},rawResponse:Q}}if(t instanceof Error&&"AbortError"===t.name){if(d.isError()){const t={method:e.method,url:ae(s),timeoutMs:e.timeoutMs};d.error("HTTP request timed out",t)}return{ok:!1,error:{reason:"timeout",cause:t},rawResponse:Q}}if(t instanceof Error){if(d.isError()){const o={method:e.method,url:ae(s),errorMessage:t.message};d.error("HTTP request failed with error",o)}return{ok:!1,error:{reason:"unknown",errorMessage:t.message,cause:t},rawResponse:V}}if(d.isError()){const o={method:e.method,url:ae(s),error:i(t)};d.error("HTTP request failed with unknown error",o)}return{ok:!1,error:{reason:"unknown",errorMessage:i(t),cause:t},rawResponse:V}}})};function de(){return new ue}class ue{constructor(){this.parts=new Map}add(e,t,o){if(null==t)return this;const n=j({[e]:t},{arrayFormat:"comma"===(null==o?void 0:o.style)?"comma":"repeat"});return n.length>0&&this.parts.set(e,n),this}addMany(e){if(null!=e)for(const[t,o]of Object.entries(e))this.add(t,o);return this}mergeAdditional(e){if(null!=e)for(const[t,o]of Object.entries(e)){if(null==o)continue;const e=j({[t]:o},{arrayFormat:"repeat"});e.length>0&&this.parts.set(t,e)}return this}build(){return[...this.parts.values()].join("&")}}class ce extends Error{constructor(e,t){super(e),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,null!=(null==t?void 0:t.cause)&&(this.cause=t.cause)}}function he(e,t,o,n){switch(e.reason){case"non-json":throw new r({statusCode:e.statusCode,body:e.rawBody,rawResponse:t});case"body-is-null":throw new r({statusCode:e.statusCode,rawResponse:t});case"timeout":throw new ce(`Timeout exceeded when calling ${o} ${n}.`,{cause:e.cause});case"unknown":throw new r({message:e.errorMessage,rawResponse:t,cause:e.cause});default:throw new r({message:"Unknown error",rawResponse:t})}}class ve extends r{constructor(e,t){super({message:"BadRequestError",statusCode:400,body:e,rawResponse:t}),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class pe{constructor(e={}){this._options=k(e)}list(e){return D.fromPromise(this.__list(e))}__list(e){return t=this,o=void 0,s=function*(){var t,o,i,s,a,l,d,u,h,v;const p=c(null===(t=this._options)||void 0===t?void 0:t.headers,null==e?void 0:e.headers),m=yield(null!==(o=this._options.fetcher)&&void 0!==o?o:le)({url:U(null!==(i=yield n(this._options.baseUrl))&&void 0!==i?i:(null!==(s=yield n(this._options.environment))&&void 0!==s?s:H.Production).agentRest,"v1/agent/settings/think/models"),method:"GET",headers:p,queryString:de().mergeAdditional(null==e?void 0:e.queryParams).build(),timeoutMs:1e3*(null!==(d=null!==(a=null==e?void 0:e.timeoutInSeconds)&&void 0!==a?a:null===(l=this._options)||void 0===l?void 0:l.timeoutInSeconds)&&void 0!==d?d:60),maxRetries:null!==(u=null==e?void 0:e.maxRetries)&&void 0!==u?u:null===(h=this._options)||void 0===h?void 0:h.maxRetries,abortSignal:null==e?void 0:e.abortSignal,fetchFn:null===(v=this._options)||void 0===v?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if("status-code"===m.error.reason){if(400===m.error.statusCode)throw new ve(m.error.body,m.rawResponse);throw new r({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse})}return he(m.error,m.rawResponse,"GET","/v1/agent/settings/think/models")},new((i=void 0)||(i=Promise))(function(e,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,i,s}}class me{constructor(e={}){this._options=k(e)}get models(){var e;return null!==(e=this._models)&&void 0!==e?e:this._models=new pe(this._options)}}class _e{constructor(e={}){this._options=k(e)}get think(){var e;return null!==(e=this._think)&&void 0!==e?e:this._think=new me(this._options)}}class fe{constructor(e){this.eventHandlers={},this.handleOpen=()=>{var e,t;null===(t=(e=this.eventHandlers).open)||void 0===t||t.call(e)},this.handleMessage=e=>{var t,o;const n=s(e.data);null===(o=(t=this.eventHandlers).message)||void 0===o||o.call(t,n)},this.handleClose=e=>{var t,o;null===(o=(t=this.eventHandlers).close)||void 0===o||o.call(t,e)},this.handleError=e=>{var t,o;const n=e.message;null===(o=(t=this.eventHandlers).error)||void 0===o||o.call(t,new Error(n))},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,t){this.eventHandlers[e]=t}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 e=this,t=void 0,n=function*(){return this.socket.readyState===M.ReadyState.OPEN?this.socket:new Promise((e,t)=>{this.socket.addEventListener("open",()=>{e(this.socket)}),this.socket.addEventListener("error",e=>{t(e)})})},new((o=void 0)||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())});var e,t,o,n}assertSocketIsOpen(){if(!this.socket)throw new Error("Socket is not connected.");if(this.socket.readyState!==M.ReadyState.OPEN)throw new Error("Socket is not open.")}sendBinary(e){this.socket.send(e)}sendJson(e){const t=i(e);this.socket.send(t)}}class ge{constructor(e={}){this._options=k(e)}get settings(){var e;return null!==(e=this._settings)&&void 0!==e?e:this._settings=new _e(this._options)}connect(e){return t=this,o=void 0,s=function*(){var t,o,i;const{protocols:s,queryParams:r,headers:a,debug:l,reconnectAttempts:d,connectionTimeoutInSeconds:u,abortSignal:v}=e,p=c(null===(t=this._options)||void 0===t?void 0:t.headers,h({Authorization:e.Authorization}),a),m=new M({url:U(null!==(o=yield n(this._options.baseUrl))&&void 0!==o?o:(null!==(i=yield n(this._options.environment))&&void 0!==i?i:H.Production).agent,"/v1/agent/converse"),protocols:null!=s?s:[],queryParameters:null!=r?r:{},headers:p,options:{debug:null!=l&&l,maxRetries:null!=d?d:30,connectionTimeout:null!=u?1e3*u:void 0},abortSignal:v});return new fe({socket:m})},new((i=void 0)||(i=Promise))(function(e,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,i,s}}class ye{constructor(e={}){this._options=k(e)}get v1(){var e;return null!==(e=this._v1)&&void 0!==e?e:this._v1=new ge(this._options)}}class we{constructor(e={}){this._options=x(e)}grant(e={},t){return D.fromPromise(this.__grant(e,t))}__grant(){return e=this,t=arguments,i=function*(e={},t){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,"v1/auth/grant"),method:"POST",headers:m,contentType:"application/json",queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),requestType:"json",body:e,timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"POST","/v1/auth/grant")},new((o=void 0)||(o=Promise))(function(n,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())});var e,t,o,i}}class be{constructor(e={}){this._options=x(e)}get tokens(){var e;return null!==(e=this._tokens)&&void 0!==e?e:this._tokens=new we(this._options)}}class Re{constructor(e={}){this._options=x(e)}get v1(){var e;return null!==(e=this._v1)&&void 0!==e?e:this._v1=new be(this._options)}}var Se=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};function ke(e){return Se(this,arguments,void 0,function*(e,{noSniffFileSize:t}={}){var n,i,s,r,a,l;if(Te(l=e)||je(l)||qe(l)||function(e){return"undefined"!=typeof Uint8Array&&e instanceof Uint8Array}(l)||Oe(l)||Ae(l)||function(e){return"object"==typeof e&&null!=e&&("read"in e||"pipe"in e)}(l)||function(e){return"object"==typeof e&&null!=e&&"getReader"in e}(l))return ke({data:e},{noSniffFileSize:t});if("path"in e){const s=yield o.e(48).then(o.t.bind(o,48,19));if(!(null==s?void 0:s.createReadStream))throw new Error("File path uploads are not supported in this environment.");const r=s.createReadStream(e.path),a=null!==(n=e.contentLength)&&void 0!==n?n:!0===t?void 0:yield xe(e.path);return{data:r,filename:null!==(i=e.filename)&&void 0!==i?i:Ee(e.path),contentType:e.contentType,contentLength:a}}if("data"in e){const o=e.data,n=null!==(s=e.contentLength)&&void 0!==s?s:yield function(e){return Se(this,arguments,void 0,function*(e,{noSniffFileSize:t}={}){return Te(e)?e.length:je(e)||qe(e)?e.byteLength:Oe(e)||Ae(e)?e.size:!0!==t&&Ce(e)?yield xe(e.path.toString()):void 0})}(o,{noSniffFileSize:t}),i=null!==(r=e.filename)&&void 0!==r?r:function(e){return function(e){return"object"==typeof e&&null!=e&&"name"in e}(e)?e.name:Ce(e)?Ee(e.path.toString()):void 0}(o);return{data:o,filename:i,contentType:null!==(a=e.contentType)&&void 0!==a?a:Pe(o),contentLength:n}}throw new Error(`Invalid FileUpload of type ${typeof e}: ${JSON.stringify(e)}`)})}function xe(e){return Se(this,void 0,void 0,function*(){var t;try{const n=yield o.e(48).then(o.t.bind(o,48,19));if(!(null===(t=null==n?void 0:n.promises)||void 0===t?void 0:t.stat))return;return(yield n.promises.stat(e)).size}catch(e){return}})}function Pe(e){return Oe(e)||Ae(e)?e.type:void 0}function Ee(e){const t=e.lastIndexOf("/"),o=e.lastIndexOf("\\"),n=Math.max(t,o);return n>=0?e.substring(n+1):e}function Ce(e){return"object"==typeof e&&null!=e&&"path"in e}function Te(e){return"undefined"!=typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(e)}function je(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)}function qe(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer}function Oe(e){return"undefined"!=typeof Blob&&e instanceof Blob}function Ae(e){return"undefined"!=typeof File&&e instanceof File}var Ie=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class Le{constructor(e={}){this._options=x(e)}transcribeUrl(e,t){return D.fromPromise(this.__transcribeUrl(e,t))}__transcribeUrl(e,t){return Ie(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const{callback:m,callback_method:_,extra:f,sentiment:g,summarize:y,tag:w,topics:b,custom_topic:R,custom_topic_mode:S,intents:k,custom_intent:x,custom_intent_mode:P,detect_entities:E,detect_language:C,diarize:T,diarize_model:j,dictation:q,encoding:O,filler_words:A,keyterm:I,keywords:L,language:M,measurements:$,model:F,multichannel:G,numerals:D,paragraphs:z,profanity_filter:N,punctuate:B,redact:W,replace:J,search:K,smart_format:X,utterances:Q,utt_split:V,version:Y,mip_opt_out:Z}=e,ee=function(e,t){var o={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(o[n[i]]=e[n[i]])}return o}(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"]),te={callback:m,callback_method:null!=_?_:void 0,extra:f,sentiment:g,summarize:null!=y?y:void 0,tag:w,topics:b,custom_topic:R,custom_topic_mode:null!=S?S:void 0,intents:k,custom_intent:x,custom_intent_mode:null!=P?P:void 0,detect_entities:E,detect_language:C,diarize:T,diarize_model:null!=j?j:void 0,dictation:q,encoding:null!=O?O:void 0,filler_words:A,keyterm:I,keywords:L,language:M,measurements:$,model:null!=F?F:void 0,multichannel:G,numerals:D,paragraphs:z,profanity_filter:N,punctuate:B,redact:W,replace:J,search:K,smart_format:X,utterances:Q,utt_split:V,version:null!=Y?Y:void 0,mip_opt_out:Z},oe=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),ne=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,"v1/listen"),method:"POST",headers:oe,contentType:"application/json",queryString:de().addMany(te).mergeAdditional(null==t?void 0:t.queryParams).build(),requestType:"json",body:ee,timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(ne.ok)return{data:ne.body,rawResponse:ne.rawResponse};if("status-code"===ne.error.reason){if(400===ne.error.statusCode)throw new ve(ne.error.body,ne.rawResponse);throw new r({statusCode:ne.error.statusCode,body:ne.error.body,rawResponse:ne.rawResponse})}return he(ne.error,ne.rawResponse,"POST","/v1/listen")})}transcribeFile(e,t,o){return D.fromPromise(this.__transcribeFile(e,t,o))}__transcribeFile(e,t,o){return Ie(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _={callback:t.callback,callback_method:null!=t.callback_method?t.callback_method:void 0,extra:t.extra,sentiment:t.sentiment,summarize:null!=t.summarize?t.summarize:void 0,tag:t.tag,topics:t.topics,custom_topic:t.custom_topic,custom_topic_mode:null!=t.custom_topic_mode?t.custom_topic_mode:void 0,intents:t.intents,custom_intent:t.custom_intent,custom_intent_mode:null!=t.custom_intent_mode?t.custom_intent_mode:void 0,detect_entities:t.detect_entities,detect_language:t.detect_language,diarize:t.diarize,diarize_model:null!=t.diarize_model?t.diarize_model:void 0,dictation:t.dictation,encoding:null!=t.encoding?t.encoding:void 0,filler_words:t.filler_words,keyterm:t.keyterm,keywords:t.keywords,language:t.language,measurements:t.measurements,model:null!=t.model?t.model:void 0,multichannel:t.multichannel,numerals:t.numerals,paragraphs:t.paragraphs,profanity_filter:t.profanity_filter,punctuate:t.punctuate,redact:t.redact,replace:t.replace,search:t.search,smart_format:t.smart_format,utterances:t.utterances,utt_split:t.utt_split,version:null!=t.version?t.version:void 0,mip_opt_out:t.mip_opt_out},f=yield function(e){return Se(this,void 0,void 0,function*(){const{data:t,filename:o,contentLength:n,contentType:i}=yield ke(e),s={body:t,headers:{}};return o&&(s.headers["Content-Disposition"]=`attachment; filename="${o}"`),i&&(s.headers["Content-Type"]=i),null!=n&&(s.headers["Content-Length"]=n.toString()),s})}(e),g=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,f.headers,null==o?void 0:o.headers),y=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,"v1/listen"),method:"POST",headers:g,contentType:"application/octet-stream",queryString:de().addMany(_).mergeAdditional(null==o?void 0:o.queryParams).build(),requestType:"bytes",duplex:"half",body:f.body,timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if("status-code"===y.error.reason){if(400===y.error.statusCode)throw new ve(y.error.body,y.rawResponse);throw new r({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse})}return he(y.error,y.rawResponse,"POST","/v1/listen")})}}class Me{constructor(e){this.eventHandlers={},this.handleOpen=()=>{var e,t;null===(t=(e=this.eventHandlers).open)||void 0===t||t.call(e)},this.handleMessage=e=>{var t,o;const n=s(e.data);null===(o=(t=this.eventHandlers).message)||void 0===o||o.call(t,n)},this.handleClose=e=>{var t,o;null===(o=(t=this.eventHandlers).close)||void 0===o||o.call(t,e)},this.handleError=e=>{var t,o;const n=e.message;null===(o=(t=this.eventHandlers).error)||void 0===o||o.call(t,new Error(n))},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,t){this.eventHandlers[e]=t}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 e=this,t=void 0,n=function*(){return this.socket.readyState===M.ReadyState.OPEN?this.socket:new Promise((e,t)=>{this.socket.addEventListener("open",()=>{e(this.socket)}),this.socket.addEventListener("error",e=>{t(e)})})},new((o=void 0)||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())});var e,t,o,n}assertSocketIsOpen(){if(!this.socket)throw new Error("Socket is not connected.");if(this.socket.readyState!==M.ReadyState.OPEN)throw new Error("Socket is not open.")}sendBinary(e){this.socket.send(e)}sendJson(e){const t=i(e);this.socket.send(t)}}class Ue{constructor(e={}){this._options=x(e)}get media(){var e;return null!==(e=this._media)&&void 0!==e?e:this._media=new Le(this._options)}connect(e){return t=this,o=void 0,r=function*(){var t,o,s;const{callback:r,callback_method:a,channels:l,detect_entities:d,diarize:u,dictation:v,encoding:p,endpointing:m,extra:_,interim_results:f,keyterm:g,keywords:y,language:w,mip_opt_out:b,model:R,multichannel:S,numerals:k,profanity_filter:x,punctuate:P,redact:E,replace:C,sample_rate:T,search:j,smart_format:q,tag:O,utterance_end_ms:A,vad_events:I,version:L,protocols:$,queryParams:F,headers:G,debug:D,reconnectAttempts:z,connectionTimeoutInSeconds:N,abortSignal:B}=e,W={callback:null!=r?"string"==typeof r?r:i(r):void 0,callback_method:null!=a?a:void 0,channels:null!=l?"string"==typeof l?l:i(l):void 0,detect_entities:null!=d?d:void 0,diarize:null!=u?u:void 0,dictation:null!=v?v:void 0,encoding:null!=p?p:void 0,endpointing:null!=m?"string"==typeof m?m:i(m):void 0,extra:null!=_?"string"==typeof _?_:i(_):void 0,interim_results:null!=f?f:void 0,keyterm:null!=g?"string"==typeof g?g:i(g):void 0,keywords:null!=y?"string"==typeof y?y:i(y):void 0,language:null!=w?"string"==typeof w?w:i(w):void 0,mip_opt_out:null!=b?"string"==typeof b?b:i(b):void 0,model:R,multichannel:null!=S?S:void 0,numerals:null!=k?k:void 0,profanity_filter:null!=x?x:void 0,punctuate:null!=P?P:void 0,redact:null!=E?E:void 0,replace:null!=C?"string"==typeof C?C:i(C):void 0,sample_rate:null!=T?"string"==typeof T?T:i(T):void 0,search:null!=j?"string"==typeof j?j:i(j):void 0,smart_format:null!=q?q:void 0,tag:null!=O?"string"==typeof O?O:i(O):void 0,utterance_end_ms:null!=A?"string"==typeof A?A:i(A):void 0,vad_events:null!=I?I:void 0,version:null!=L?"string"==typeof L?L:i(L):void 0},J=c(null===(t=this._options)||void 0===t?void 0:t.headers,h({Authorization:e.Authorization}),G),K=new M({url:U(null!==(o=yield n(this._options.baseUrl))&&void 0!==o?o:(null!==(s=yield n(this._options.environment))&&void 0!==s?s:H.Production).production,"/v1/listen"),protocols:null!=$?$:[],queryParameters:Object.assign(Object.assign({},W),F),headers:J,options:{debug:null!=D&&D,maxRetries:null!=z?z:30,connectionTimeout:null!=N?1e3*N:void 0},abortSignal:B});return new Me({socket:K})},new((s=void 0)||(s=Promise))(function(e,n){function i(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof s?o:new s(function(e){e(o)})).then(i,a)}l((r=r.apply(t,o||[])).next())});var t,o,s,r}}class $e{constructor(e){this.eventHandlers={},this.handleOpen=()=>{var e,t;null===(t=(e=this.eventHandlers).open)||void 0===t||t.call(e)},this.handleMessage=e=>{var t,o;const n=s(e.data);null===(o=(t=this.eventHandlers).message)||void 0===o||o.call(t,n)},this.handleClose=e=>{var t,o;null===(o=(t=this.eventHandlers).close)||void 0===o||o.call(t,e)},this.handleError=e=>{var t,o;const n=e.message;null===(o=(t=this.eventHandlers).error)||void 0===o||o.call(t,new Error(n))},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,t){this.eventHandlers[e]=t}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 e=this,t=void 0,n=function*(){return this.socket.readyState===M.ReadyState.OPEN?this.socket:new Promise((e,t)=>{this.socket.addEventListener("open",()=>{e(this.socket)}),this.socket.addEventListener("error",e=>{t(e)})})},new((o=void 0)||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())});var e,t,o,n}assertSocketIsOpen(){if(!this.socket)throw new Error("Socket is not connected.");if(this.socket.readyState!==M.ReadyState.OPEN)throw new Error("Socket is not open.")}sendBinary(e){this.socket.send(e)}sendJson(e){const t=i(e);this.socket.send(t)}}class Fe{constructor(e={}){this._options=k(e)}connect(e){return t=this,o=void 0,r=function*(){var t,o,s;const{model:r,encoding:a,sample_rate:l,eager_eot_threshold:d,eot_threshold:u,eot_timeout_ms:v,keyterm:p,language_hint:m,mip_opt_out:_,tag:f,protocols:g,queryParams:y,headers:w,debug:b,reconnectAttempts:R,connectionTimeoutInSeconds:S,abortSignal:k}=e,x={model:r,encoding:null!=a?a:void 0,sample_rate:null!=l?"string"==typeof l?l:i(l):void 0,eager_eot_threshold:null!=d?"string"==typeof d?d:i(d):void 0,eot_threshold:null!=u?"string"==typeof u?u:i(u):void 0,eot_timeout_ms:null!=v?"string"==typeof v?v:i(v):void 0,keyterm:Array.isArray(p)?p.map(e=>"string"==typeof e?e:i(e)):null!=p?"string"==typeof p?p:i(p):void 0,language_hint:Array.isArray(m)?m.map(e=>"string"==typeof e?e:i(e)):null!=m?"string"==typeof m?m:i(m):void 0,mip_opt_out:null!=_?"string"==typeof _?_:i(_):void 0,tag:null!=f?"string"==typeof f?f:i(f):void 0},P=c(null===(t=this._options)||void 0===t?void 0:t.headers,h({Authorization:e.Authorization}),w),E=new M({url:U(null!==(o=yield n(this._options.baseUrl))&&void 0!==o?o:(null!==(s=yield n(this._options.environment))&&void 0!==s?s:H.Production).production,"/v2/listen"),protocols:null!=g?g:[],queryParameters:Object.assign(Object.assign({},x),y),headers:P,options:{debug:null!=b&&b,maxRetries:null!=R?R:30,connectionTimeout:null!=S?1e3*S:void 0},abortSignal:k});return new $e({socket:E})},new((s=void 0)||(s=Promise))(function(e,n){function i(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof s?o:new s(function(e){e(o)})).then(i,a)}l((r=r.apply(t,o||[])).next())});var t,o,s,r}}class Ge{constructor(e={}){this._options=x(e)}get v1(){var e;return null!==(e=this._v1)&&void 0!==e?e:this._v1=new Ue(this._options)}get v2(){var e;return null!==(e=this._v2)&&void 0!==e?e:this._v2=new Fe(this._options)}}function He(e){if(null===e)return"null";switch(typeof e){case"undefined":return"undefined";case"string":case"number":case"boolean":break;default:e=String(e)}return encodeURIComponent(e)}var De=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class ze{constructor(e={}){this._options=x(e)}list(e={},t){return D.fromPromise(this.__list(e,t))}__list(){return De(this,arguments,void 0,function*(e={},t){var o,i,s,a,l,d,u,h,v,p;const{include_outdated:m}=e,_={include_outdated:m},f=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),g=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,"v1/models"),method:"GET",headers:f,queryString:de().addMany(_).mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(g.ok)return{data:g.body,rawResponse:g.rawResponse};if("status-code"===g.error.reason){if(400===g.error.statusCode)throw new ve(g.error.body,g.rawResponse);throw new r({statusCode:g.error.statusCode,body:g.error.body,rawResponse:g.rawResponse})}return he(g.error,g.rawResponse,"GET","/v1/models")})}get(e,t){return D.fromPromise(this.__get(e,t))}__get(e,t){return De(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/models/${He(e)}`),method:"GET",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"GET","/v1/models/{model_id}")})}}var Ne=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class Be{constructor(e={}){this._options=x(e)}list(e,t){return D.fromPromise(this.__list(e,t))}__list(e,t){return Ne(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/projects/${He(e)}/balances`),method:"GET",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"GET","/v1/projects/{project_id}/balances")})}get(e,t,o){return D.fromPromise(this.__get(e,t,o))}__get(e,t,o){return Ne(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/balances/${He(t)}`),method:"GET",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"GET","/v1/projects/{project_id}/balances/{balance_id}")})}}class We{constructor(e={}){this._options=x(e)}list(e,t={},o){return D.fromPromise(this.__list(e,t,o))}__list(e){return t=this,o=arguments,s=function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{start:_,end:f,accessor:g,deployment:y,tag:w,line_item:b,grouping:R}=t,S={start:_,end:f,accessor:g,deployment:null!=y?y:void 0,tag:w,line_item:b,grouping:Array.isArray(R)?R.map(e=>e):null!=R?R:void 0},k=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),x=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/billing/breakdown`),method:"GET",headers:k,queryString:de().addMany(S).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(x.ok)return{data:x.body,rawResponse:x.rawResponse};if("status-code"===x.error.reason){if(400===x.error.statusCode)throw new ve(x.error.body,x.rawResponse);throw new r({statusCode:x.error.statusCode,body:x.error.body,rawResponse:x.rawResponse})}return he(x.error,x.rawResponse,"GET","/v1/projects/{project_id}/billing/breakdown")},new((i=void 0)||(i=Promise))(function(e,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,i,s}}class Je{constructor(e={}){this._options=x(e)}list(e,t={},o){return D.fromPromise(this.__list(e,t,o))}__list(e){return t=this,o=arguments,s=function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{start:_,end:f}=t,g={start:_,end:f},y=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),w=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/billing/fields`),method:"GET",headers:y,queryString:de().addMany(g).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(w.ok)return{data:w.body,rawResponse:w.rawResponse};if("status-code"===w.error.reason){if(400===w.error.statusCode)throw new ve(w.error.body,w.rawResponse);throw new r({statusCode:w.error.statusCode,body:w.error.body,rawResponse:w.rawResponse})}return he(w.error,w.rawResponse,"GET","/v1/projects/{project_id}/billing/fields")},new((i=void 0)||(i=Promise))(function(e,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,i,s}}class Ke{constructor(e={}){this._options=x(e)}list(e,t={},o){return D.fromPromise(this.__list(e,t,o))}__list(e){return t=this,o=arguments,s=function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{limit:_}=t,f={limit:_},g=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),y=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/purchases`),method:"GET",headers:g,queryString:de().addMany(f).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if("status-code"===y.error.reason){if(400===y.error.statusCode)throw new ve(y.error.body,y.rawResponse);throw new r({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse})}return he(y.error,y.rawResponse,"GET","/v1/projects/{project_id}/purchases")},new((i=void 0)||(i=Promise))(function(e,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,i,s}}class Xe{constructor(e={}){this._options=x(e)}get balances(){var e;return null!==(e=this._balances)&&void 0!==e?e:this._balances=new Be(this._options)}get breakdown(){var e;return null!==(e=this._breakdown)&&void 0!==e?e:this._breakdown=new We(this._options)}get fields(){var e;return null!==(e=this._fields)&&void 0!==e?e:this._fields=new Je(this._options)}get purchases(){var e;return null!==(e=this._purchases)&&void 0!==e?e:this._purchases=new Ke(this._options)}}var Qe=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class Ve{constructor(e={}){this._options=x(e)}list(e,t={},o){return D.fromPromise(this.__list(e,t,o))}__list(e){return Qe(this,arguments,void 0,function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{status:_}=t,f={status:null!=_?_:void 0},g=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),y=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/keys`),method:"GET",headers:g,queryString:de().addMany(f).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if("status-code"===y.error.reason){if(400===y.error.statusCode)throw new ve(y.error.body,y.rawResponse);throw new r({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse})}return he(y.error,y.rawResponse,"GET","/v1/projects/{project_id}/keys")})}create(e,t,o){return D.fromPromise(this.__create(e,t,o))}__create(e,t,o){return Qe(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/keys`),method:"POST",headers:_,contentType:"application/json",queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),requestType:"json",body:t,timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"POST","/v1/projects/{project_id}/keys")})}get(e,t,o){return D.fromPromise(this.__get(e,t,o))}__get(e,t,o){return Qe(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/keys/${He(t)}`),method:"GET",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"GET","/v1/projects/{project_id}/keys/{key_id}")})}delete(e,t,o){return D.fromPromise(this.__delete(e,t,o))}__delete(e,t,o){return Qe(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/keys/${He(t)}`),method:"DELETE",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"DELETE","/v1/projects/{project_id}/keys/{key_id}")})}}var Ye=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class Ze{constructor(e={}){this._options=x(e)}list(e,t){return D.fromPromise(this.__list(e,t))}__list(e,t){return Ye(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/projects/${He(e)}/invites`),method:"GET",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"GET","/v1/projects/{project_id}/invites")})}create(e,t,o){return D.fromPromise(this.__create(e,t,o))}__create(e,t,o){return Ye(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/invites`),method:"POST",headers:_,contentType:"application/json",queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),requestType:"json",body:t,timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"POST","/v1/projects/{project_id}/invites")})}delete(e,t,o){return D.fromPromise(this.__delete(e,t,o))}__delete(e,t,o){return Ye(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/invites/${He(t)}`),method:"DELETE",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"DELETE","/v1/projects/{project_id}/invites/{email}")})}}var et=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class tt{constructor(e={}){this._options=x(e)}list(e,t,o){return D.fromPromise(this.__list(e,t,o))}__list(e,t,o){return et(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/members/${He(t)}/scopes`),method:"GET",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"GET","/v1/projects/{project_id}/members/{member_id}/scopes")})}update(e,t,o,n){return D.fromPromise(this.__update(e,t,o,n))}__update(e,t,o,i){return et(this,void 0,void 0,function*(){var s,a,l,d,u,h,v,p,m,_;const f=c((yield this._options.authProvider.getAuthRequest()).headers,null===(s=this._options)||void 0===s?void 0:s.headers,null==i?void 0:i.headers),g=yield(null!==(a=this._options.fetcher)&&void 0!==a?a:le)({url:U(null!==(l=yield n(this._options.baseUrl))&&void 0!==l?l:(null!==(d=yield n(this._options.environment))&&void 0!==d?d:H.Production).base,`v1/projects/${He(e)}/members/${He(t)}/scopes`),method:"PUT",headers:f,contentType:"application/json",queryString:de().mergeAdditional(null==i?void 0:i.queryParams).build(),requestType:"json",body:o,timeoutMs:1e3*(null!==(v=null!==(u=null==i?void 0:i.timeoutInSeconds)&&void 0!==u?u:null===(h=this._options)||void 0===h?void 0:h.timeoutInSeconds)&&void 0!==v?v:60),maxRetries:null!==(p=null==i?void 0:i.maxRetries)&&void 0!==p?p:null===(m=this._options)||void 0===m?void 0:m.maxRetries,abortSignal:null==i?void 0:i.abortSignal,fetchFn:null===(_=this._options)||void 0===_?void 0:_.fetch,logging:this._options.logging});if(g.ok)return{data:g.body,rawResponse:g.rawResponse};if("status-code"===g.error.reason){if(400===g.error.statusCode)throw new ve(g.error.body,g.rawResponse);throw new r({statusCode:g.error.statusCode,body:g.error.body,rawResponse:g.rawResponse})}return he(g.error,g.rawResponse,"PUT","/v1/projects/{project_id}/members/{member_id}/scopes")})}}var ot=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class nt{constructor(e={}){this._options=x(e)}get invites(){var e;return null!==(e=this._invites)&&void 0!==e?e:this._invites=new Ze(this._options)}get scopes(){var e;return null!==(e=this._scopes)&&void 0!==e?e:this._scopes=new tt(this._options)}list(e,t){return D.fromPromise(this.__list(e,t))}__list(e,t){return ot(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/projects/${He(e)}/members`),method:"GET",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"GET","/v1/projects/{project_id}/members")})}delete(e,t,o){return D.fromPromise(this.__delete(e,t,o))}__delete(e,t,o){return ot(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/members/${He(t)}`),method:"DELETE",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"DELETE","/v1/projects/{project_id}/members/{member_id}")})}}var it=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class st{constructor(e={}){this._options=x(e)}list(e,t={},o){return D.fromPromise(this.__list(e,t,o))}__list(e){return it(this,arguments,void 0,function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{include_outdated:_}=t,f={include_outdated:_},g=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),y=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/models`),method:"GET",headers:g,queryString:de().addMany(f).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(y.ok)return{data:y.body,rawResponse:y.rawResponse};if("status-code"===y.error.reason){if(400===y.error.statusCode)throw new ve(y.error.body,y.rawResponse);throw new r({statusCode:y.error.statusCode,body:y.error.body,rawResponse:y.rawResponse})}return he(y.error,y.rawResponse,"GET","/v1/projects/{project_id}/models")})}get(e,t,o){return D.fromPromise(this.__get(e,t,o))}__get(e,t,o){return it(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/models/${He(t)}`),method:"GET",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"GET","/v1/projects/{project_id}/models/{model_id}")})}}var rt=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class at{constructor(e={}){this._options=x(e)}list(e,t={},o){return D.fromPromise(this.__list(e,t,o))}__list(e){return rt(this,arguments,void 0,function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{start:_,end:f,limit:g,page:y,accessor:w,request_id:b,deployment:R,endpoint:S,method:k,status:x}=t,P={start:null!=_?_:void 0,end:null!=f?f:void 0,limit:g,page:y,accessor:w,request_id:b,deployment:null!=R?R:void 0,endpoint:null!=S?S:void 0,method:null!=k?k:void 0,status:null!=x?x:void 0},E=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),C=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/requests`),method:"GET",headers:E,queryString:de().addMany(P).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(C.ok)return{data:C.body,rawResponse:C.rawResponse};if("status-code"===C.error.reason){if(400===C.error.statusCode)throw new ve(C.error.body,C.rawResponse);throw new r({statusCode:C.error.statusCode,body:C.error.body,rawResponse:C.rawResponse})}return he(C.error,C.rawResponse,"GET","/v1/projects/{project_id}/requests")})}get(e,t,o){return D.fromPromise(this.__get(e,t,o))}__get(e,t,o){return rt(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/requests/${He(t)}`),method:"GET",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"GET","/v1/projects/{project_id}/requests/{request_id}")})}}class lt{constructor(e={}){this._options=x(e)}get(e,t={},o){return D.fromPromise(this.__get(e,t,o))}__get(e){return t=this,o=arguments,s=function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{start:_,end:f,grouping:g,accessor:y,alternatives:w,callback_method:b,callback:R,channels:S,custom_intent_mode:k,custom_intent:x,custom_topic_mode:P,custom_topic:E,deployment:C,detect_entities:T,detect_language:j,diarize:q,dictation:O,encoding:A,endpoint:I,extra:L,filler_words:M,intents:$,keyterm:F,keywords:G,language:D,measurements:z,method:N,model:B,multichannel:W,numerals:J,paragraphs:K,profanity_filter:X,punctuate:Q,redact:V,replace:Y,sample_rate:Z,search:ee,sentiment:te,smart_format:oe,summarize:ne,tag:ie,topics:se,utt_split:re,utterances:ae,version:ue}=t,ce={start:_,end:f,grouping:null!=g?g:void 0,accessor:y,alternatives:w,callback_method:b,callback:R,channels:S,custom_intent_mode:k,custom_intent:x,custom_topic_mode:P,custom_topic:E,deployment:null!=C?C:void 0,detect_entities:T,detect_language:j,diarize:q,dictation:O,encoding:A,endpoint:null!=I?I:void 0,extra:L,filler_words:M,intents:$,keyterm:F,keywords:G,language:D,measurements:z,method:null!=N?N:void 0,model:B,multichannel:W,numerals:J,paragraphs:K,profanity_filter:X,punctuate:Q,redact:V,replace:Y,sample_rate:Z,search:ee,sentiment:te,smart_format:oe,summarize:ne,tag:ie,topics:se,utt_split:re,utterances:ae,version:ue},pe=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),me=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/usage/breakdown`),method:"GET",headers:pe,queryString:de().addMany(ce).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(me.ok)return{data:me.body,rawResponse:me.rawResponse};if("status-code"===me.error.reason){if(400===me.error.statusCode)throw new ve(me.error.body,me.rawResponse);throw new r({statusCode:me.error.statusCode,body:me.error.body,rawResponse:me.rawResponse})}return he(me.error,me.rawResponse,"GET","/v1/projects/{project_id}/usage/breakdown")},new((i=void 0)||(i=Promise))(function(e,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,i,s}}class dt{constructor(e={}){this._options=x(e)}list(e,t={},o){return D.fromPromise(this.__list(e,t,o))}__list(e){return t=this,o=arguments,s=function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{start:_,end:f}=t,g={start:_,end:f},y=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),w=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/usage/fields`),method:"GET",headers:y,queryString:de().addMany(g).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(w.ok)return{data:w.body,rawResponse:w.rawResponse};if("status-code"===w.error.reason){if(400===w.error.statusCode)throw new ve(w.error.body,w.rawResponse);throw new r({statusCode:w.error.statusCode,body:w.error.body,rawResponse:w.rawResponse})}return he(w.error,w.rawResponse,"GET","/v1/projects/{project_id}/usage/fields")},new((i=void 0)||(i=Promise))(function(e,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,i,s}}class ut{constructor(e={}){this._options=x(e)}get breakdown(){var e;return null!==(e=this._breakdown)&&void 0!==e?e:this._breakdown=new lt(this._options)}get fields(){var e;return null!==(e=this._fields)&&void 0!==e?e:this._fields=new dt(this._options)}get(e,t={},o){return D.fromPromise(this.__get(e,t,o))}__get(e){return t=this,o=arguments,s=function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{start:_,end:f,accessor:g,alternatives:y,callback_method:w,callback:b,channels:R,custom_intent_mode:S,custom_intent:k,custom_topic_mode:x,custom_topic:P,deployment:E,detect_entities:C,detect_language:T,diarize:j,dictation:q,encoding:O,endpoint:A,extra:I,filler_words:L,intents:M,keyterm:$,keywords:F,language:G,measurements:D,method:z,model:N,multichannel:B,numerals:W,paragraphs:J,profanity_filter:K,punctuate:X,redact:Q,replace:V,sample_rate:Y,search:Z,sentiment:ee,smart_format:te,summarize:oe,tag:ne,topics:ie,utt_split:se,utterances:re,version:ae}=t,ue={start:_,end:f,accessor:g,alternatives:y,callback_method:w,callback:b,channels:R,custom_intent_mode:S,custom_intent:k,custom_topic_mode:x,custom_topic:P,deployment:null!=E?E:void 0,detect_entities:C,detect_language:T,diarize:j,dictation:q,encoding:O,endpoint:null!=A?A:void 0,extra:I,filler_words:L,intents:M,keyterm:$,keywords:F,language:G,measurements:D,method:null!=z?z:void 0,model:N,multichannel:B,numerals:W,paragraphs:J,profanity_filter:K,punctuate:X,redact:Q,replace:V,sample_rate:Y,search:Z,sentiment:ee,smart_format:te,summarize:oe,tag:ne,topics:ie,utt_split:se,utterances:re,version:ae},ce=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),pe=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/usage`),method:"GET",headers:ce,queryString:de().addMany(ue).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(pe.ok)return{data:pe.body,rawResponse:pe.rawResponse};if("status-code"===pe.error.reason){if(400===pe.error.statusCode)throw new ve(pe.error.body,pe.rawResponse);throw new r({statusCode:pe.error.statusCode,body:pe.error.body,rawResponse:pe.rawResponse})}return he(pe.error,pe.rawResponse,"GET","/v1/projects/{project_id}/usage")},new((i=void 0)||(i=Promise))(function(e,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(e){e(o)})).then(r,a)}l((s=s.apply(t,o||[])).next())});var t,o,i,s}}var ct=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class ht{constructor(e={}){this._options=x(e)}get keys(){var e;return null!==(e=this._keys)&&void 0!==e?e:this._keys=new Ve(this._options)}get members(){var e;return null!==(e=this._members)&&void 0!==e?e:this._members=new nt(this._options)}get models(){var e;return null!==(e=this._models)&&void 0!==e?e:this._models=new st(this._options)}get requests(){var e;return null!==(e=this._requests)&&void 0!==e?e:this._requests=new at(this._options)}get usage(){var e;return null!==(e=this._usage)&&void 0!==e?e:this._usage=new ut(this._options)}get billing(){var e;return null!==(e=this._billing)&&void 0!==e?e:this._billing=new Xe(this._options)}list(e){return D.fromPromise(this.__list(e))}__list(e){return ct(this,void 0,void 0,function*(){var t,o,i,s,a,l,d,u,h,v;const p=c((yield this._options.authProvider.getAuthRequest()).headers,null===(t=this._options)||void 0===t?void 0:t.headers,null==e?void 0:e.headers),m=yield(null!==(o=this._options.fetcher)&&void 0!==o?o:le)({url:U(null!==(i=yield n(this._options.baseUrl))&&void 0!==i?i:(null!==(s=yield n(this._options.environment))&&void 0!==s?s:H.Production).base,"v1/projects"),method:"GET",headers:p,queryString:de().mergeAdditional(null==e?void 0:e.queryParams).build(),timeoutMs:1e3*(null!==(d=null!==(a=null==e?void 0:e.timeoutInSeconds)&&void 0!==a?a:null===(l=this._options)||void 0===l?void 0:l.timeoutInSeconds)&&void 0!==d?d:60),maxRetries:null!==(u=null==e?void 0:e.maxRetries)&&void 0!==u?u:null===(h=this._options)||void 0===h?void 0:h.maxRetries,abortSignal:null==e?void 0:e.abortSignal,fetchFn:null===(v=this._options)||void 0===v?void 0:v.fetch,logging:this._options.logging});if(m.ok)return{data:m.body,rawResponse:m.rawResponse};if("status-code"===m.error.reason){if(400===m.error.statusCode)throw new ve(m.error.body,m.rawResponse);throw new r({statusCode:m.error.statusCode,body:m.error.body,rawResponse:m.rawResponse})}return he(m.error,m.rawResponse,"GET","/v1/projects")})}get(e,t={},o){return D.fromPromise(this.__get(e,t,o))}__get(e){return ct(this,arguments,void 0,function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{limit:_,page:f}=t,g={limit:_,page:f},y=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),w=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}`),method:"GET",headers:y,queryString:de().addMany(g).mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(w.ok)return{data:w.body,rawResponse:w.rawResponse};if("status-code"===w.error.reason){if(400===w.error.statusCode)throw new ve(w.error.body,w.rawResponse);throw new r({statusCode:w.error.statusCode,body:w.error.body,rawResponse:w.rawResponse})}return he(w.error,w.rawResponse,"GET","/v1/projects/{project_id}")})}delete(e,t){return D.fromPromise(this.__delete(e,t))}__delete(e,t){return ct(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/projects/${He(e)}`),method:"DELETE",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"DELETE","/v1/projects/{project_id}")})}update(e,t={},o){return D.fromPromise(this.__update(e,t,o))}__update(e){return ct(this,arguments,void 0,function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}`),method:"PATCH",headers:_,contentType:"application/json",queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),requestType:"json",body:t,timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"PATCH","/v1/projects/{project_id}")})}leave(e,t){return D.fromPromise(this.__leave(e,t))}__leave(e,t){return ct(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/projects/${He(e)}/leave`),method:"DELETE",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"DELETE","/v1/projects/{project_id}/leave")})}}class vt{constructor(e={}){this._options=x(e)}get models(){var e;return null!==(e=this._models)&&void 0!==e?e:this._models=new ze(this._options)}get projects(){var e;return null!==(e=this._projects)&&void 0!==e?e:this._projects=new ht(this._options)}}class pt{constructor(e={}){this._options=x(e)}get v1(){var e;return null!==(e=this._v1)&&void 0!==e?e:this._v1=new vt(this._options)}}class mt{constructor(e={}){this._options=x(e)}analyze(e,t){return D.fromPromise(this.__analyze(e,t))}__analyze(e,t){return o=this,i=void 0,a=function*(){var o,i,s,a,l,d,u,h,v,p;const{callback:m,callback_method:_,sentiment:f,summarize:g,tag:y,topics:w,custom_topic:b,custom_topic_mode:R,intents:S,custom_intent:k,custom_intent_mode:x,language:P,body:E}=e,C={callback:m,callback_method:null!=_?_:void 0,sentiment:f,summarize:null!=g?g:void 0,tag:y,topics:w,custom_topic:b,custom_topic_mode:null!=R?R:void 0,intents:S,custom_intent:k,custom_intent_mode:null!=x?x:void 0,language:P},T=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),j=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,"v1/read"),method:"POST",headers:T,contentType:"application/json",queryString:de().addMany(C).mergeAdditional(null==t?void 0:t.queryParams).build(),requestType:"json",body:E,timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(j.ok)return{data:j.body,rawResponse:j.rawResponse};if("status-code"===j.error.reason){if(400===j.error.statusCode)throw new ve(j.error.body,j.rawResponse);throw new r({statusCode:j.error.statusCode,body:j.error.body,rawResponse:j.rawResponse})}return he(j.error,j.rawResponse,"POST","/v1/read")},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof s?o:new s(function(e){e(o)})).then(n,r)}l((a=a.apply(o,i||[])).next())});var o,i,s,a}}class _t{constructor(e={}){this._options=x(e)}get text(){var e;return null!==(e=this._text)&&void 0!==e?e:this._text=new mt(this._options)}}class ft{constructor(e={}){this._options=x(e)}get v1(){var e;return null!==(e=this._v1)&&void 0!==e?e:this._v1=new _t(this._options)}}var gt=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class yt{constructor(e={}){this._options=x(e)}list(e,t){return D.fromPromise(this.__list(e,t))}__list(e,t){return gt(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/projects/${He(e)}/self-hosted/distribution/credentials`),method:"GET",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"GET","/v1/projects/{project_id}/self-hosted/distribution/credentials")})}create(e,t={},o){return D.fromPromise(this.__create(e,t,o))}__create(e){return gt(this,arguments,void 0,function*(e,t={},o){var i,s,a,l,d,u,h,v,p,m;const{scopes:_,provider:f}=t,g=function(e,t){var o={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(o[n[i]]=e[n[i]])}return o}(t,["scopes","provider"]),y={scopes:Array.isArray(_)?_.map(e=>e):null!=_?_:void 0,provider:null!=f?f:void 0},w=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),b=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/self-hosted/distribution/credentials`),method:"POST",headers:w,contentType:"application/json",queryString:de().addMany(y).mergeAdditional(null==o?void 0:o.queryParams).build(),requestType:"json",body:g,timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(b.ok)return{data:b.body,rawResponse:b.rawResponse};if("status-code"===b.error.reason){if(400===b.error.statusCode)throw new ve(b.error.body,b.rawResponse);throw new r({statusCode:b.error.statusCode,body:b.error.body,rawResponse:b.rawResponse})}return he(b.error,b.rawResponse,"POST","/v1/projects/{project_id}/self-hosted/distribution/credentials")})}get(e,t,o){return D.fromPromise(this.__get(e,t,o))}__get(e,t,o){return gt(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/self-hosted/distribution/credentials/${He(t)}`),method:"GET",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"GET","/v1/projects/{project_id}/self-hosted/distribution/credentials/{distribution_credentials_id}")})}delete(e,t,o){return D.fromPromise(this.__delete(e,t,o))}__delete(e,t,o){return gt(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/self-hosted/distribution/credentials/${He(t)}`),method:"DELETE",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"DELETE","/v1/projects/{project_id}/self-hosted/distribution/credentials/{distribution_credentials_id}")})}}class wt{constructor(e={}){this._options=x(e)}get distributionCredentials(){var e;return null!==(e=this._distributionCredentials)&&void 0!==e?e:this._distributionCredentials=new yt(this._options)}}class bt{constructor(e={}){this._options=x(e)}get v1(){var e;return null!==(e=this._v1)&&void 0!==e?e:this._v1=new wt(this._options)}}class Rt{constructor(e={}){this._options=x(e)}generate(e,t){return D.fromPromise(this.__generate(e,t))}__generate(e,t){return o=this,i=void 0,a=function*(){var o,i,s,a,l,d,u,h,v,p;const{callback:m,callback_method:_,mip_opt_out:f,tag:g,bit_rate:y,container:w,encoding:b,model:R,sample_rate:S,speed:k}=e,x=function(e,t){var o={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(o[n[i]]=e[n[i]])}return o}(e,["callback","callback_method","mip_opt_out","tag","bit_rate","container","encoding","model","sample_rate","speed"]),P={callback:m,callback_method:null!=_?_:void 0,mip_opt_out:f,tag:g,bit_rate:y,container:null!=w?w:void 0,encoding:null!=b?b:void 0,model:null!=R?R:void 0,sample_rate:S,speed:k},E=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),C=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,"v1/speak"),method:"POST",headers:E,contentType:"application/json",queryString:de().addMany(P).mergeAdditional(null==t?void 0:t.queryParams).build(),requestType:"json",body:x,responseType:"binary-response",timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(C.ok)return{data:C.body,rawResponse:C.rawResponse};if("status-code"===C.error.reason){if(400===C.error.statusCode)throw new ve(C.error.body,C.rawResponse);throw new r({statusCode:C.error.statusCode,body:C.error.body,rawResponse:C.rawResponse})}return he(C.error,C.rawResponse,"POST","/v1/speak")},new((s=void 0)||(s=Promise))(function(e,t){function n(e){try{l(a.next(e))}catch(e){t(e)}}function r(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof s?o:new s(function(e){e(o)})).then(n,r)}l((a=a.apply(o,i||[])).next())});var o,i,s,a}}class St{constructor(e){this.eventHandlers={},this.handleOpen=()=>{var e,t;null===(t=(e=this.eventHandlers).open)||void 0===t||t.call(e)},this.handleMessage=e=>{var t,o;const n=s(e.data);null===(o=(t=this.eventHandlers).message)||void 0===o||o.call(t,n)},this.handleClose=e=>{var t,o;null===(o=(t=this.eventHandlers).close)||void 0===o||o.call(t,e)},this.handleError=e=>{var t,o;const n=e.message;null===(o=(t=this.eventHandlers).error)||void 0===o||o.call(t,new Error(n))},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,t){this.eventHandlers[e]=t}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 e=this,t=void 0,n=function*(){return this.socket.readyState===M.ReadyState.OPEN?this.socket:new Promise((e,t)=>{this.socket.addEventListener("open",()=>{e(this.socket)}),this.socket.addEventListener("error",e=>{t(e)})})},new((o=void 0)||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())});var e,t,o,n}assertSocketIsOpen(){if(!this.socket)throw new Error("Socket is not connected.");if(this.socket.readyState!==M.ReadyState.OPEN)throw new Error("Socket is not open.")}sendBinary(e){this.socket.send(e)}sendJson(e){const t=i(e);this.socket.send(t)}}class kt{constructor(e={}){this._options=x(e)}get audio(){var e;return null!==(e=this._audio)&&void 0!==e?e:this._audio=new Rt(this._options)}connect(e){return t=this,o=void 0,r=function*(){var t,o,s;const{encoding:r,mip_opt_out:a,model:l,sample_rate:d,speed:u,protocols:v,queryParams:p,headers:m,debug:_,reconnectAttempts:f,connectionTimeoutInSeconds:g,abortSignal:y}=e,w={encoding:null!=r?r:void 0,mip_opt_out:null!=a?"string"==typeof a?a:i(a):void 0,model:null!=l?l:void 0,sample_rate:null!=d?d:void 0,speed:u},b=c(null===(t=this._options)||void 0===t?void 0:t.headers,h({Authorization:e.Authorization}),m),R=new M({url:U(null!==(o=yield n(this._options.baseUrl))&&void 0!==o?o:(null!==(s=yield n(this._options.environment))&&void 0!==s?s:H.Production).production,"/v1/speak"),protocols:null!=v?v:[],queryParameters:Object.assign(Object.assign({},w),p),headers:b,options:{debug:null!=_&&_,maxRetries:null!=f?f:30,connectionTimeout:null!=g?1e3*g:void 0},abortSignal:y});return new St({socket:R})},new((s=void 0)||(s=Promise))(function(e,n){function i(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var o;t.done?e(t.value):(o=t.value,o instanceof s?o:new s(function(e){e(o)})).then(i,a)}l((r=r.apply(t,o||[])).next())});var t,o,s,r}}class xt{constructor(e={}){this._options=x(e)}get v1(){var e;return null!==(e=this._v1)&&void 0!==e?e:this._v1=new kt(this._options)}}var Pt=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class Et{constructor(e={}){this._options=x(e)}list(e,t){return D.fromPromise(this.__list(e,t))}__list(e,t){return Pt(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/projects/${He(e)}/agents`),method:"GET",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"GET","/v1/projects/{project_id}/agents")})}create(e,t,o){return D.fromPromise(this.__create(e,t,o))}__create(e,t,o){return Pt(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/agents`),method:"POST",headers:_,contentType:"application/json",queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),requestType:"json",body:t,timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"POST","/v1/projects/{project_id}/agents")})}get(e,t,o){return D.fromPromise(this.__get(e,t,o))}__get(e,t,o){return Pt(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/agents/${He(t)}`),method:"GET",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"GET","/v1/projects/{project_id}/agents/{agent_id}")})}update(e,t,o,n){return D.fromPromise(this.__update(e,t,o,n))}__update(e,t,o,i){return Pt(this,void 0,void 0,function*(){var s,a,l,d,u,h,v,p,m,_;const f=c((yield this._options.authProvider.getAuthRequest()).headers,null===(s=this._options)||void 0===s?void 0:s.headers,null==i?void 0:i.headers),g=yield(null!==(a=this._options.fetcher)&&void 0!==a?a:le)({url:U(null!==(l=yield n(this._options.baseUrl))&&void 0!==l?l:(null!==(d=yield n(this._options.environment))&&void 0!==d?d:H.Production).base,`v1/projects/${He(e)}/agents/${He(t)}`),method:"PUT",headers:f,contentType:"application/json",queryString:de().mergeAdditional(null==i?void 0:i.queryParams).build(),requestType:"json",body:o,timeoutMs:1e3*(null!==(v=null!==(u=null==i?void 0:i.timeoutInSeconds)&&void 0!==u?u:null===(h=this._options)||void 0===h?void 0:h.timeoutInSeconds)&&void 0!==v?v:60),maxRetries:null!==(p=null==i?void 0:i.maxRetries)&&void 0!==p?p:null===(m=this._options)||void 0===m?void 0:m.maxRetries,abortSignal:null==i?void 0:i.abortSignal,fetchFn:null===(_=this._options)||void 0===_?void 0:_.fetch,logging:this._options.logging});if(g.ok)return{data:g.body,rawResponse:g.rawResponse};if("status-code"===g.error.reason){if(400===g.error.statusCode)throw new ve(g.error.body,g.rawResponse);throw new r({statusCode:g.error.statusCode,body:g.error.body,rawResponse:g.rawResponse})}return he(g.error,g.rawResponse,"PUT","/v1/projects/{project_id}/agents/{agent_id}")})}delete(e,t,o){return D.fromPromise(this.__delete(e,t,o))}__delete(e,t,o){return Pt(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/agents/${He(t)}`),method:"DELETE",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"DELETE","/v1/projects/{project_id}/agents/{agent_id}")})}}var Ct=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class Tt{constructor(e={}){this._options=x(e)}list(e,t){return D.fromPromise(this.__list(e,t))}__list(e,t){return Ct(this,void 0,void 0,function*(){var o,i,s,a,l,d,u,h,v,p;const m=c((yield this._options.authProvider.getAuthRequest()).headers,null===(o=this._options)||void 0===o?void 0:o.headers,null==t?void 0:t.headers),_=yield(null!==(i=this._options.fetcher)&&void 0!==i?i:le)({url:U(null!==(s=yield n(this._options.baseUrl))&&void 0!==s?s:(null!==(a=yield n(this._options.environment))&&void 0!==a?a:H.Production).base,`v1/projects/${He(e)}/agent-variables`),method:"GET",headers:m,queryString:de().mergeAdditional(null==t?void 0:t.queryParams).build(),timeoutMs:1e3*(null!==(u=null!==(l=null==t?void 0:t.timeoutInSeconds)&&void 0!==l?l:null===(d=this._options)||void 0===d?void 0:d.timeoutInSeconds)&&void 0!==u?u:60),maxRetries:null!==(h=null==t?void 0:t.maxRetries)&&void 0!==h?h:null===(v=this._options)||void 0===v?void 0:v.maxRetries,abortSignal:null==t?void 0:t.abortSignal,fetchFn:null===(p=this._options)||void 0===p?void 0:p.fetch,logging:this._options.logging});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if("status-code"===_.error.reason){if(400===_.error.statusCode)throw new ve(_.error.body,_.rawResponse);throw new r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}return he(_.error,_.rawResponse,"GET","/v1/projects/{project_id}/agent-variables")})}create(e,t,o){return D.fromPromise(this.__create(e,t,o))}__create(e,t,o){return Ct(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/agent-variables`),method:"POST",headers:_,contentType:"application/json",queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),requestType:"json",body:t,timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"POST","/v1/projects/{project_id}/agent-variables")})}get(e,t,o){return D.fromPromise(this.__get(e,t,o))}__get(e,t,o){return Ct(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/agent-variables/${He(t)}`),method:"GET",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"GET","/v1/projects/{project_id}/agent-variables/{variable_id}")})}delete(e,t,o){return D.fromPromise(this.__delete(e,t,o))}__delete(e,t,o){return Ct(this,void 0,void 0,function*(){var i,s,a,l,d,u,h,v,p,m;const _=c((yield this._options.authProvider.getAuthRequest()).headers,null===(i=this._options)||void 0===i?void 0:i.headers,null==o?void 0:o.headers),f=yield(null!==(s=this._options.fetcher)&&void 0!==s?s:le)({url:U(null!==(a=yield n(this._options.baseUrl))&&void 0!==a?a:(null!==(l=yield n(this._options.environment))&&void 0!==l?l:H.Production).base,`v1/projects/${He(e)}/agent-variables/${He(t)}`),method:"DELETE",headers:_,queryString:de().mergeAdditional(null==o?void 0:o.queryParams).build(),timeoutMs:1e3*(null!==(h=null!==(d=null==o?void 0:o.timeoutInSeconds)&&void 0!==d?d:null===(u=this._options)||void 0===u?void 0:u.timeoutInSeconds)&&void 0!==h?h:60),maxRetries:null!==(v=null==o?void 0:o.maxRetries)&&void 0!==v?v:null===(p=this._options)||void 0===p?void 0:p.maxRetries,abortSignal:null==o?void 0:o.abortSignal,fetchFn:null===(m=this._options)||void 0===m?void 0:m.fetch,logging:this._options.logging});if(f.ok)return{data:f.body,rawResponse:f.rawResponse};if("status-code"===f.error.reason){if(400===f.error.statusCode)throw new ve(f.error.body,f.rawResponse);throw new r({statusCode:f.error.statusCode,body:f.error.body,rawResponse:f.rawResponse})}return he(f.error,f.rawResponse,"DELETE","/v1/projects/{project_id}/agent-variables/{variable_id}")})}update(e,t,o,n){return D.fromPromise(this.__update(e,t,o,n))}__update(e,t,o,i){return Ct(this,void 0,void 0,function*(){var s,a,l,d,u,h,v,p,m,_;const f=c((yield this._options.authProvider.getAuthRequest()).headers,null===(s=this._options)||void 0===s?void 0:s.headers,null==i?void 0:i.headers),g=yield(null!==(a=this._options.fetcher)&&void 0!==a?a:le)({url:U(null!==(l=yield n(this._options.baseUrl))&&void 0!==l?l:(null!==(d=yield n(this._options.environment))&&void 0!==d?d:H.Production).base,`v1/projects/${He(e)}/agent-variables/${He(t)}`),method:"PATCH",headers:f,contentType:"application/json",queryString:de().mergeAdditional(null==i?void 0:i.queryParams).build(),requestType:"json",body:o,timeoutMs:1e3*(null!==(v=null!==(u=null==i?void 0:i.timeoutInSeconds)&&void 0!==u?u:null===(h=this._options)||void 0===h?void 0:h.timeoutInSeconds)&&void 0!==v?v:60),maxRetries:null!==(p=null==i?void 0:i.maxRetries)&&void 0!==p?p:null===(m=this._options)||void 0===m?void 0:m.maxRetries,abortSignal:null==i?void 0:i.abortSignal,fetchFn:null===(_=this._options)||void 0===_?void 0:_.fetch,logging:this._options.logging});if(g.ok)return{data:g.body,rawResponse:g.rawResponse};if("status-code"===g.error.reason){if(400===g.error.statusCode)throw new ve(g.error.body,g.rawResponse);throw new r({statusCode:g.error.statusCode,body:g.error.body,rawResponse:g.rawResponse})}return he(g.error,g.rawResponse,"PATCH","/v1/projects/{project_id}/agent-variables/{variable_id}")})}}class jt{constructor(e={}){this._options=x(e)}get configurations(){var e;return null!==(e=this._configurations)&&void 0!==e?e:this._configurations=new Et(this._options)}get variables(){var e;return null!==(e=this._variables)&&void 0!==e?e:this._variables=new Tt(this._options)}}var qt=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})},Ot=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};class At{constructor(e={}){this._options=x(e)}get agent(){var e;return null!==(e=this._agent)&&void 0!==e?e:this._agent=new ye(this._options)}get auth(){var e;return null!==(e=this._auth)&&void 0!==e?e:this._auth=new Re(this._options)}get listen(){var e;return null!==(e=this._listen)&&void 0!==e?e:this._listen=new Ge(this._options)}get manage(){var e;return null!==(e=this._manage)&&void 0!==e?e:this._manage=new pt(this._options)}get read(){var e;return null!==(e=this._read)&&void 0!==e?e:this._read=new ft(this._options)}get selfHosted(){var e;return null!==(e=this._selfHosted)&&void 0!==e?e:this._selfHosted=new bt(this._options)}get speak(){var e;return null!==(e=this._speak)&&void 0!==e?e:this._speak=new xt(this._options)}get voiceAgent(){var e;return null!==(e=this._voiceAgent)&&void 0!==e?e:this._voiceAgent=new jt(this._options)}fetch(e,t,o){return Ot(this,void 0,void 0,function*(){var i;return function(e,t,o,i){return qt(this,void 0,void 0,function*(){var s,r,a,l,d,u,c;const h=b(o.logging);let v,p=t;e instanceof Request?(v=e.url,null==t&&(p={method:e.method,headers:Object.fromEntries(e.headers.entries()),body:e.body,signal:e.signal,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity,mode:e.mode})):v=e instanceof URL?e.toString():e;const m=null!==(s=null!=o.baseUrl?yield n(o.baseUrl):void 0)&&void 0!==s?s:null!=o.environment?yield n(o.environment):void 0;let _;_=v.startsWith("http://")||v.startsWith("https://")?v:null!=m?U(m,v):v;const f={};if(null!=o.headers)for(const[e,t]of Object.entries(o.headers)){const o=yield z(t,{endpointMetadata:{}});null!=o&&(f[e.toLowerCase()]=`${o}`)}if(null!=o.getAuthHeaders){const e=yield o.getAuthHeaders();for(const[t,o]of Object.entries(e))f[t.toLowerCase()]=o}if(null!=(null==p?void 0:p.headers)){const e=p.headers instanceof Headers?Object.fromEntries(p.headers.entries()):Array.isArray(p.headers)?Object.fromEntries(p.headers):p.headers;for(const[t,o]of Object.entries(e))null!=o&&(f[t.toLowerCase()]=o)}if(null!=(null==i?void 0:i.headers))for(const[e,t]of Object.entries(i.headers))f[e.toLowerCase()]=t;const g=null!==(r=null==p?void 0:p.method)&&void 0!==r?r:"GET",y=null==p?void 0:p.body,w=null!==(a=null==i?void 0:i.timeoutInSeconds)&&void 0!==a?a:o.timeoutInSeconds,R=null!=w?1e3*w:void 0,S=null!==(l=null==i?void 0:i.maxRetries)&&void 0!==l?l:o.maxRetries,k=null!==(u=null!==(d=null==i?void 0:i.abortSignal)&&void 0!==d?d:null==p?void 0:p.signal)&&void 0!==u?u:void 0,x=null!==(c=o.fetch)&&void 0!==c?c:yield W();h.isDebug()&&h.debug("Making passthrough HTTP request",{method:g,url:_,hasBody:null!=y});const P=yield te(()=>qt(this,void 0,void 0,function*(){return X(x,_,g,f,null!=y?y:void 0,R,k,"include"===(null==p?void 0:p.credentials),void 0,!1)}),S);return h.isDebug()&&h.debug("Passthrough HTTP request completed",{method:g,url:_,statusCode:P.status}),P})}(e,t,{baseUrl:null!==(i=this._options.baseUrl)&&void 0!==i?i:()=>Ot(this,void 0,void 0,function*(){var e;const t=yield n(this._options.environment);return"string"==typeof t?t:null!==(e=null==t?void 0:t.base)&&void 0!==e?e:H.Production.base}),headers:this._options.headers,timeoutInSeconds:this._options.timeoutInSeconds,maxRetries:this._options.maxRetries,fetch:this._options.fetch,logging:this._options.logging,getAuthHeaders:()=>Ot(this,void 0,void 0,function*(){return(yield this._options.authProvider.getAuthRequest()).headers})},o)})}}var It=function(e,t,o,n){return new(o||(o=Promise))(function(i,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof o?t:new o(function(e){e(t)})).then(r,a)}l((n=n.apply(e,t||[])).next())})};const Lt=new Set(["Authorization","headers","debug","reconnectAttempts","connectionTimeoutInSeconds","abortSignal","queryParams"]);let Mt,Ut=!1;class $t{constructor(e){this.originalProvider=e}getAuthRequest(e){return It(this,void 0,void 0,function*(){var t,o;const n=yield this.originalProvider.getAuthRequest(e),i=(null===(t=n.headers)||void 0===t?void 0:t.Authorization)||(null===(o=n.headers)||void 0===o?void 0:o.authorization);return!i||"string"!=typeof i||i.startsWith("Bearer ")||i.startsWith("Token ")||i.startsWith("token ")?n:{headers:Object.assign(Object.assign({},n.headers),{Authorization:`Token ${i}`})}})}}class Ft{constructor(e,t){this.originalProvider=e,this.accessToken=t}getAuthRequest(e){return It(this,void 0,void 0,function*(){var t,o;const i=null!==(t=yield n(this.accessToken))&&void 0!==t?t:null===(o=process.env)||void 0===o?void 0:o.DEEPGRAM_ACCESS_TOKEN;return null!=i?{headers:{Authorization:`Bearer ${i}`}}:this.originalProvider.getAuthRequest(e)})}}class Gt extends At{constructor(e={}){const t=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();if("node"===v.type)try{return{}.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}();super(Object.assign(Object.assign({},e),{headers:Object.assign(Object.assign({},e.headers),{"x-deepgram-session-id":t})})),this._sessionId=t,this._options.authProvider=new $t(this._options.authProvider),null!=e.accessToken&&(this._options.authProvider=new Ft(this._options.authProvider,e.accessToken))}get sessionId(){return this._sessionId}get agent(){return this._customAgent||(this._customAgent=new Ht(this._options)),this._customAgent}get listen(){return this._customListen||(this._customListen=new Dt(this._options)),this._customListen}get speak(){return this._customSpeak||(this._customSpeak=new zt(this._options)),this._customSpeak}}class Ht extends ye{get v1(){return new Xt(this._options)}}class Dt extends Ge{get v1(){return new Vt(this._options)}get v2(){return new Zt(this._options)}}class zt extends xt{get v1(){return new to(this._options)}}function Nt(e){const t={};for(const[o,n]of Object.entries(e))Lt.has(o)||null==n||(t[o]=n);return null!=e.queryParams&&"object"==typeof e.queryParams&&Object.assign(t,e.queryParams),t}function Bt(e,t){var o;const n=e=>{var o,n,i;if("string"==typeof e.data)try{const n=s(e.data);null===(o=t.message)||void 0===o||o.call(t,n)}catch(o){null===(n=t.message)||void 0===n||n.call(t,e.data)}else null===(i=t.message)||void 0===i||i.call(t,e.data)},i=e;return(null===(o=i._listeners)||void 0===o?void 0:o.message)&&i._listeners.message.forEach(t=>{e.removeEventListener("message",t)}),e.addEventListener("message",n),n}function Wt(e,t){t.handleOpen&&e.removeEventListener("open",t.handleOpen),t.handleMessage&&e.removeEventListener("message",t.handleMessage),t.handleClose&&e.removeEventListener("close",t.handleClose),t.handleError&&e.removeEventListener("error",t.handleError)}function Jt(e){e.readyState===e.CLOSED&&(e._connectLock=!1,e._shouldReconnect=!0)}function Kt(e){return It(this,arguments,void 0,function*({options:e,urlPath:t,environmentKey:o,queryParams:i,headers:s,debug:r,reconnectAttempts:a,connectionTimeoutInSeconds:l,abortSignal:d}){var u,h,p,m,_,f;yield function(){return It(this,void 0,void 0,function*(){var e;if(!Ut){Ut=!0;try{if("undefined"!=typeof require){let e=require("ws");Mt=e.WebSocket||e.default||e}else if("undefined"!=typeof process&&(null===(e=process.versions)||void 0===e?void 0:e.node)){const e=new Function("specifier","return import(specifier)"),t=yield e("ws");Mt=t.WebSocket||t.default||t}}catch(e){Mt=void 0}}})}();const g=yield null===(u=e.authProvider)||void 0===u?void 0:u.getAuthRequest(),y=c(null!==(h=e.headers)&&void 0!==h?h:{},null!==(p=null==g?void 0:g.headers)&&void 0!==p?p:{},s),w=yield function(e){return It(this,void 0,void 0,function*(){const t={};for(const[o,i]of Object.entries(e)){if(null==i)continue;const e=yield n(i);null!=e&&(t[o]=e)}return t})}(y),b=function(e){const t={},o="browser"===v.type||"web-worker"===v.type,n=e["x-deepgram-session-id"]||e["X-Deepgram-Session-Id"];if("node"===v.type&&Mt)t.WebSocket=Mt,t.headers=e;else if(o){const o=e.Authorization||e.authorization,i=Object.assign({},e);delete i.Authorization,delete i.authorization,delete i["x-deepgram-session-id"],delete i["X-Deepgram-Session-Id"],t.headers=i;const s=[];if(o&&"string"==typeof o)if(o.startsWith("Token ")){const e=o.substring(6);s.push("token",e)}else if(o.startsWith("Bearer ")){const e=o.substring(7);s.push("bearer",e)}else s.push(o);n&&"string"==typeof n&&s.push("x-deepgram-session-id",n),s.length>0&&(t.protocols=s)}else t.headers=e;return t}(w),R=null!==(m=yield n(e.baseUrl))&&void 0!==m?m:(null!==(_=yield n(e.environment))&&void 0!==_?_:H.Production)[o];return new M({url:U(R,t),protocols:null!==(f=b.protocols)&&void 0!==f?f:[],queryParameters:i,headers:b.headers,options:{WebSocket:b.WebSocket,debug:null!=r&&r,maxRetries:null!=a?a:30,startClosed:!0,connectionTimeout:null!=l?1e3*l:1e4},abortSignal:d})})}class Xt extends ge{connect(){return It(this,arguments,void 0,function*(e={}){const{headers:t,debug:o,reconnectAttempts:n,connectionTimeoutInSeconds:i,abortSignal:s}=e,r=yield Kt({options:this._options,urlPath:"/v1/agent/converse",environmentKey:"agent",queryParams:Nt(e),headers:t,debug:o,reconnectAttempts:n,connectionTimeoutInSeconds:i,abortSignal:s});return new Qt({socket:r})})}createConnection(){return It(this,arguments,void 0,function*(e={}){return this.connect(e)})}}class Qt extends fe{constructor(e){super(e),this.setupBinaryHandling()}setupBinaryHandling(){this.binaryAwareHandler=Bt(this.socket,this.eventHandlers)}connect(){const e=this;return Wt(this.socket,{handleOpen:e.handleOpen,handleMessage:e.handleMessage,handleClose:e.handleClose,handleError:e.handleError}),Jt(this.socket),super.connect(),this.setupBinaryHandling(),this}}class Vt extends Ue{connect(e){return It(this,void 0,void 0,function*(){const{headers:t,debug:o,reconnectAttempts:n,connectionTimeoutInSeconds:i,abortSignal:s}=e,r=yield Kt({options:this._options,urlPath:"/v1/listen",environmentKey:"production",queryParams:Nt(e),headers:t,debug:o,reconnectAttempts:n,connectionTimeoutInSeconds:i,abortSignal:s});return new Yt({socket:r})})}createConnection(e){return It(this,void 0,void 0,function*(){return this.connect(e)})}}class Yt extends Me{constructor(e){super(e),this.setupBinaryHandling()}setupBinaryHandling(){this.binaryAwareHandler=Bt(this.socket,this.eventHandlers)}connect(){const e=this;return Wt(this.socket,{handleOpen:e.handleOpen,handleMessage:e.handleMessage,handleClose:e.handleClose,handleError:e.handleError}),Jt(this.socket),super.connect(),this.setupBinaryHandling(),this}}class Zt extends Fe{connect(e){return It(this,void 0,void 0,function*(){const{headers:t,debug:o,reconnectAttempts:n,connectionTimeoutInSeconds:i,abortSignal:s}=e,r=yield Kt({options:this._options,urlPath:"/v2/listen",environmentKey:"production",queryParams:Nt(e),headers:t,debug:o,reconnectAttempts:n,connectionTimeoutInSeconds:i,abortSignal:s});return new eo({socket:r})})}createConnection(e){return It(this,void 0,void 0,function*(){return this.connect(e)})}}class eo extends $e{constructor(e){super(e),this.setupBinaryHandling()}setupBinaryHandling(){this.binaryAwareHandler=Bt(this.socket,this.eventHandlers)}connect(){const e=this;return Wt(this.socket,{handleOpen:e.handleOpen,handleMessage:e.handleMessage,handleClose:e.handleClose,handleError:e.handleError}),Jt(this.socket),super.connect(),this.setupBinaryHandling(),this}ping(e){const t=this.socket._ws;if(!t)throw new Error("WebSocket is not connected. Call connect() and waitForOpen() first.");if(t.readyState!==t.OPEN)throw new Error("WebSocket is not in OPEN state.");if("node"!==v.type||"function"!=typeof t.ping)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.");t.ping(e)}}class to extends kt{connect(e){return It(this,void 0,void 0,function*(){const{headers:t,debug:o,reconnectAttempts:n,connectionTimeoutInSeconds:i,abortSignal:s}=e,r=yield Kt({options:this._options,urlPath:"/v1/speak",environmentKey:"production",queryParams:Nt(e),headers:t,debug:o,reconnectAttempts:n,connectionTimeoutInSeconds:i,abortSignal:s});return new oo({socket:r})})}createConnection(e){return It(this,void 0,void 0,function*(){return this.connect(e)})}}class oo extends St{constructor(e){super(e);this.handleMessage&&this.socket.removeEventListener("message",this.handleMessage),this.setupBinaryHandling()}setupBinaryHandling(){this.binaryAwareHandler=Bt(this.socket,this.eventHandlers)}connect(){const e=this;return Wt(this.socket,{handleOpen:e.handleOpen,handleMessage:e.handleMessage,handleClose:e.handleClose,handleError:e.handleError}),Jt(this.socket),super.connect(),this.setupBinaryHandling(),this}}}}]);
2
+ //# sourceMappingURL=622.index.js.map