@creativeorange/azure-text-to-speech 3.0.4 → 4.0.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/README.md +3 -1
- package/dist/co-azure-tts.es.js +10141 -9636
- package/dist/co-azure-tts.umd.js +23 -21
- package/package.json +14 -14
package/dist/co-azure-tts.umd.js
CHANGED
|
@@ -1,27 +1,29 @@
|
|
|
1
|
-
(function(k,U){typeof exports=="object"&&typeof module!="undefined"?U(exports):typeof define=="function"&&define.amd?define(["exports"],U):(k=typeof globalThis!="undefined"?globalThis:k||self,U(k.CreativeOrangeAzureTextToSpeech={}))})(this,function(k){"use strict";function Y(r){var s;const e=typeof r.tokenEndpoint=="string"&&r.tokenEndpoint.trim()!=="",t=typeof r.getAuthorizationToken=="function";if(e&&t)throw new Error("Provide either tokenEndpoint or getAuthorizationToken, not both.");if(!e&&!t)throw new Error("A tokenEndpoint or getAuthorizationToken provider is required.");if(t)return r.getAuthorizationToken;const i=r.tokenEndpoint.trim(),n=(s=r.tokenRequestOptions)!=null?s:{};return async()=>{var u,h,c;let o;try{o=await fetch(i,{method:"GET",cache:(u=n.cache)!=null?u:"no-store",credentials:(h=n.credentials)!=null?h:"same-origin",headers:{Accept:"application/json",...(c=n.headers)!=null?c:{}}})}catch{throw oe("Could not reach the speech token endpoint.","TOKEN_ENDPOINT_UNREACHABLE")}if(!o.ok)throw oe(`Speech token endpoint returned HTTP ${o.status}.`,"TOKEN_ENDPOINT_HTTP_ERROR");let a;try{a=await o.json()}catch{throw oe("Speech token endpoint returned invalid JSON.","TOKEN_ENDPOINT_INVALID_JSON")}return ut(a)}}function ut(r){if(!r||typeof r!="object")throw oe("Speech authorization response must be an object.","TOKEN_INVALID_RESPONSE");const e=r,t=typeof e.token=="string"?e.token.trim():"",i=typeof e.region=="string"?e.region.trim():"";if(t==="")throw oe("Speech authorization token is missing or empty.","TOKEN_EMPTY");if(i==="")throw oe("Speech authorization region is missing or empty.","TOKEN_REGION_MISSING");return{token:t,region:i}}function oe(r,e){const t=new Error(Ee(r));return t.message=Ee(r),e&&(t.code=e),t}function Ce(r){if(typeof r=="string")return{message:r.trim()!==""?Ee(r):"An unexpected speech error occurred."};if(r&&typeof r=="object"){const e=r,t=[typeof e.message=="string"?e.message:"",typeof e.errorDetails=="string"?e.errorDetails:"",typeof e.reason=="string"?e.reason:""].filter(s=>s.trim()!=="").join(" "),n={message:t!==""?Ee(t):"An unexpected speech error occurred."};return typeof e.code=="string"&&e.code.trim()!==""?n.code=e.code:typeof e.code=="number"&&(n.code=String(e.code)),n}return{message:"An unexpected speech error occurred."}}function Ee(r){return r.replace(/Authorization\s*:\s*Bearer\s+\S+/gi,"Authorization: Bearer [redacted]").replace(/Bearer\s+\S+/gi,"Bearer [redacted]").replace(/authorization[_-]?token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"authorizationToken=[redacted]").replace(/access[_-]?token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"accessToken=[redacted]").replace(/["']token["']\s*:\s*["'][^"']+["']/gi,'"token":"[redacted]"').replace(/token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"token=[redacted]")}function ae(r){var i;const e=Ce(r),t=`${e.message} ${(i=e.code)!=null?i:""}`.toLowerCase();return t.includes("unauthorized")||t.includes("authentication")||t.includes("authorization")||t.includes("invalid token")||t.includes("token expired")||t.includes("expired token")||t.includes("403")||t.includes("401")||e.code==="TOKEN_REFRESH_ERROR"}class pt{constructor(e){m(this,"authorization");m(this,"authorizationExpiresAt",0);m(this,"authorizationRequest");m(this,"provider");m(this,"tokenLifetimeMs");this.provider=Y(e),this.tokenLifetimeMs=e.tokenLifetimeMs&&e.tokenLifetimeMs>0?e.tokenLifetimeMs:48e4}getTokenLifetimeMs(){return this.tokenLifetimeMs}async getAuthorization(){return this.authorization&&Date.now()<this.authorizationExpiresAt?this.authorization:this.authorizationRequest?this.authorizationRequest:(this.authorizationRequest=this.fetchAuthorization().then(e=>(this.authorization=e,this.authorizationExpiresAt=Date.now()+this.tokenLifetimeMs,e)).finally(()=>{this.authorizationRequest=void 0}),this.authorizationRequest)}async refreshAuthorization(){return this.authorization=void 0,this.authorizationExpiresAt=0,this.authorizationRequest?this.authorizationRequest:this.getAuthorization()}clearAuthorization(){this.authorization=void 0,this.authorizationExpiresAt=0}async fetchAuthorization(){try{const e=await this.provider();return ut(e)}catch(e){this.clearAuthorization();const t=Ce(e);throw oe(t.message,t.code)}}}var Be={},_e,Mi=new Uint8Array(16);function ki(){if(!_e&&(_e=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!_e))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return _e(Mi)}var zi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Di(r){return typeof r=="string"&&zi.test(r)}for(var L=[],dt=0;dt<256;++dt)L.push((dt+256).toString(16).substr(1));function xi(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(L[r[e+0]]+L[r[e+1]]+L[r[e+2]]+L[r[e+3]]+"-"+L[r[e+4]]+L[r[e+5]]+"-"+L[r[e+6]]+L[r[e+7]]+"-"+L[r[e+8]]+L[r[e+9]]+"-"+L[r[e+10]]+L[r[e+11]]+L[r[e+12]]+L[r[e+13]]+L[r[e+14]]+L[r[e+15]]).toLowerCase();if(!Di(t))throw TypeError("Stringified UUID is invalid");return t}function Ni(r,e,t){r=r||{};var i=r.random||(r.rng||ki)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(var n=0;n<16;++n)e[t+n]=i[n];return e}return xi(i)}const Li=()=>Ni(),A=()=>Li().replace(new RegExp("-","g"),"").toUpperCase();var C;(function(r){r[r.Debug=0]="Debug",r[r.Info=1]="Info",r[r.Warning=2]="Warning",r[r.Error=3]="Error",r[r.None=4]="None"})(C||(C={}));class ce{constructor(e,t){this.privName=e,this.privEventId=A(),this.privEventTime=new Date().toISOString(),this.privEventType=t,this.privMetadata={}}get name(){return this.privName}get eventId(){return this.privEventId}get eventTime(){return this.privEventTime}get eventType(){return this.privEventType}get metadata(){return this.privMetadata}}class Te extends ce{constructor(e,t,i=C.Info){super(e,i),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class He extends Te{constructor(e){super("AudioSourceInitializingEvent",e)}}class be extends Te{constructor(e){super("AudioSourceReadyEvent",e)}}class Kt extends Te{constructor(e){super("AudioSourceOffEvent",e)}}class Ke extends Te{constructor(e,t){super("AudioSourceErrorEvent",e,C.Error),this.privError=t}get error(){return this.privError}}class qe extends Te{constructor(e,t,i){super(e,t),this.privAudioNodeId=i}get audioNodeId(){return this.privAudioNodeId}}class Re extends qe{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class Ae extends qe{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class J extends qe{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class lt extends qe{constructor(e,t,i){super("AudioStreamNodeErrorEvent",e,t),this.privError=i}get error(){return this.privError}}class qt extends ce{constructor(e,t,i=C.Info){super(e,i),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class he extends ce{constructor(e,t,i=C.Info){super(e,i),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class Ut extends he{constructor(e,t,i){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=i}get uri(){return this.privUri}get headers(){return this.privHeaders}}class Wt extends he{constructor(e){super("ConnectionEstablishedEvent",e)}}class Oi extends he{constructor(e,t,i){super("ConnectionClosedEvent",e,C.Debug),this.privReason=i,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class Bi extends he{constructor(e,t,i){super("ConnectionErrorEvent",e,C.Debug),this.privMessage=t,this.privType=i}get message(){return this.privMessage}get type(){return this.privType}}class _i extends he{constructor(e,t,i){super("ConnectionEstablishErrorEvent",e,C.Error),this.privStatusCode=t,this.privReason=i}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class vt extends he{constructor(e,t,i){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=i}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class Hi extends he{constructor(e,t,i){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=i}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class z extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class W extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class ft extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var y;(function(r){r[r.Text=0]="Text",r[r.Binary=1]="Binary"})(y||(y={}));class gt{constructor(e,t,i,n){if(this.privBody=null,e===y.Text&&t&&typeof t!="string")throw new W("Payload must be a string");if(e===y.Binary&&t&&!(t instanceof ArrayBuffer))throw new W("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=i||{},this.privId=n||A(),this.messageType){case y.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case y.Text:this.privSize=this.textBody.length}}get messageType(){return this.privMessageType}get headers(){return this.privHeaders}get body(){return this.privBody}get textBody(){if(this.privMessageType===y.Binary)throw new W("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===y.Text)throw new W("Not supported for text message");return this.privBody}get id(){return this.privId}}class St{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}class j{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new ft("EventSource");if(this.metadata)for(const t in this.metadata)t&&e.metadata&&(e.metadata[t]||(e.metadata[t]=this.metadata[t]));for(const t in this.privEventListeners)t&&this.privEventListeners[t]&&this.privEventListeners[t](e)}attach(e){const t=A();return this.privEventListeners[t]=e,{detach:()=>(delete this.privEventListeners[t],Promise.resolve())}}attachListener(e){return this.attach(t=>e.onEvent(t))}attachConsoleListener(e){return this.privConsoleListener&&this.privConsoleListener.detach(),this.privConsoleListener=this.attach(t=>e.onEvent(t)),this.privConsoleListener}isDisposed(){return this.privIsDisposed}dispose(){this.privEventListeners=null,this.privIsDisposed=!0}get metadata(){return this.privMetadata}}class O{static setEventSource(e){if(!e)throw new z("eventSource");O.privInstance=e}static get instance(){return O.privInstance}}O.privInstance=new j;var D;(function(r){r[r.None=0]="None",r[r.Connected=1]="Connected",r[r.Connecting=2]="Connecting",r[r.Disconnected=3]="Disconnected"})(D||(D={}));class G{constructor(e){if(this.privSubscriptionIdCounter=0,this.privAddSubscriptions={},this.privRemoveSubscriptions={},this.privDisposedSubscriptions={},this.privDisposeReason=null,this.privList=[],e)for(const t of e)this.privList.push(t)}get(e){return this.throwIfDisposed(),this.privList[e]}first(){return this.get(0)}last(){return this.get(this.length()-1)}add(e){this.throwIfDisposed(),this.insertAt(this.privList.length,e)}insertAt(e,t){this.throwIfDisposed(),e===0?this.privList.unshift(t):e===this.privList.length?this.privList.push(t):this.privList.splice(e,0,t),this.triggerSubscriptions(this.privAddSubscriptions)}removeFirst(){return this.throwIfDisposed(),this.removeAt(0)}removeLast(){return this.throwIfDisposed(),this.removeAt(this.length()-1)}removeAt(e){return this.throwIfDisposed(),this.remove(e,1)[0]}remove(e,t){this.throwIfDisposed();const i=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),i}clear(){this.throwIfDisposed(),this.remove(0,this.length())}length(){return this.throwIfDisposed(),this.privList.length}onAdded(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privAddSubscriptions[t]=e,{detach:()=>(delete this.privAddSubscriptions[t],Promise.resolve())}}onRemoved(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privRemoveSubscriptions[t]=e,{detach:()=>(delete this.privRemoveSubscriptions[t],Promise.resolve())}}onDisposed(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privDisposedSubscriptions[t]=e,{detach:()=>(delete this.privDisposedSubscriptions[t],Promise.resolve())}}join(e){return this.throwIfDisposed(),this.privList.join(e)}toArray(){const e=Array();return this.privList.forEach(t=>{e.push(t)}),e}any(e){return this.throwIfDisposed(),e?this.where(e).length()>0:this.length()>0}all(e){return this.throwIfDisposed(),this.where(e).length()===this.length()}forEach(e){this.throwIfDisposed();for(let t=0;t<this.length();t++)e(this.privList[t],t)}select(e){this.throwIfDisposed();const t=[];for(let i=0;i<this.privList.length;i++)t.push(e(this.privList[i],i));return new G(t)}where(e){this.throwIfDisposed();const t=new G;for(let i=0;i<this.privList.length;i++)e(this.privList[i],i)&&t.add(this.privList[i]);return t}orderBy(e){this.throwIfDisposed();const i=this.toArray().sort(e);return new G(i)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,i)=>e(i,t))}clone(){return this.throwIfDisposed(),new G(this.toArray())}concat(e){return this.throwIfDisposed(),new G(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new G(this.privList.concat(e))}isDisposed(){return this.privList==null}dispose(e){this.isDisposed()||(this.privDisposeReason=e,this.privList=null,this.privAddSubscriptions=null,this.privRemoveSubscriptions=null,this.triggerSubscriptions(this.privDisposedSubscriptions))}throwIfDisposed(){if(this.isDisposed())throw new ft("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var Vt;(function(r){r[r.None=0]="None",r[r.Resolved=1]="Resolved",r[r.Rejected=2]="Rejected"})(Vt||(Vt={}));class x{constructor(){this.resolve=e=>(this.privResolve(e),this),this.reject=e=>(this.privReject(e),this),this.privPromise=new Promise((e,t)=>{this.privResolve=e,this.privReject=t})}get promise(){return this.privPromise}}function Q(r,e,t){r.then(i=>{try{e&&e(i)}catch(n){if(t)try{if(n instanceof Error){const s=n;t(s.name+": "+s.message)}else t(n)}catch{}}},i=>{if(t)try{if(i instanceof Error){const n=i;t(n.name+": "+n.message)}else t(i)}catch{}})}var Ft=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})},Pe;(function(r){r[r.Dequeue=0]="Dequeue",r[r.Peek=1]="Peek"})(Pe||(Pe={}));class Ie{constructor(e){this.privPromiseStore=new G,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new G,this.privDetachables=[],this.privSubscribers=new G,this.privDetachables.push(this.privList.onAdded(()=>this.drain()))}enqueue(e){this.throwIfDispose(),this.enqueueFromPromise(new Promise(t=>t(e)))}enqueueFromPromise(e){this.throwIfDispose(),e.then(t=>{this.privList.add(t)},()=>{})}dequeue(){this.throwIfDispose();const e=new x;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Pe.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new x;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Pe.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return Ft(this,void 0,void 0,function*(){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;const i=this.privSubscribers;if(i){for(;i.length()>0;)i.removeFirst().deferral.resolve(void 0);this.privSubscribers===i&&(this.privSubscribers=i)}for(const n of this.privDetachables)yield n.detach();if(this.privPromiseStore.length()>0&&e){const n=[];return this.privPromiseStore.toArray().forEach(s=>{n.push(s)}),Promise.all(n).finally(()=>{this.privSubscribers=null,this.privList.forEach(s=>{e(s)}),this.privList=null}).then()}else this.privSubscribers=null,this.privList=null}})}dispose(e){return Ft(this,void 0,void 0,function*(){yield this.drainAndDispose(null,e)})}drain(){if(!this.privIsDrainInProgress&&!this.privIsDisposing){this.privIsDrainInProgress=!0;const e=this.privSubscribers,t=this.privList;if(e&&t){for(;t.length()>0&&e.length()>0&&!this.privIsDisposing;){const i=e.removeFirst();if(i.type===Pe.Peek)i.deferral.resolve(t.first());else{const n=t.removeFirst();i.deferral.resolve(n)}}this.privSubscribers===e&&(this.privSubscribers=e),this.privList===t&&(this.privList=t)}this.privIsDrainInProgress=!1}}throwIfDispose(){if(this.isDisposed())throw this.privDisposeReason?new W(this.privDisposeReason):new ft("Queue");if(this.privIsDisposing)throw new W("Queue disposing")}}class Ue{constructor(e,t,i){if(this.privPayload=null,!t)throw new z("payload");if(e===y.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new W("Payload must be ArrayBuffer");if(e===y.Text&&typeof t!="string")throw new W("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=i||A()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===y.Binary)throw new W("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===y.Text)throw new W("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Ki{constructor(e,t){this.privActualSampleRate=e,this.privDesiredSampleRate=t}encode(e){const t=this.downSampleAudioFrame(e,this.privActualSampleRate,this.privDesiredSampleRate);if(!t)return null;const i=t.length*2,n=new ArrayBuffer(i),s=new DataView(n);return this.floatTo16BitPCM(s,0,t),n}setString(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}floatTo16BitPCM(e,t,i){for(let n=0;n<i.length;n++,t+=2){const s=Math.max(-1,Math.min(1,i[n]));e.setInt16(t,s<0?s*32768:s*32767,!0)}}downSampleAudioFrame(e,t,i){if(!e)return null;if(i===t||i>t)return e;const n=t/i,s=Math.round(e.length/n),o=new Float32Array(s);let a=0,u=0;for(;u<s;){const h=Math.round((u+1)*n);let c=0,d=0;for(;a<h&&a<e.length;)c+=e[a++],d++;o[u++]=c/d}return o}}var qi=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class jt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||A(),this.privReaderQueue=new Ie}get isClosed(){return this.privIsWriteEnded}get isReadEnded(){return this.privIsReadEnded}get id(){return this.privId}close(){this.privIsWriteEnded||(this.writeStreamChunk({buffer:null,isEnd:!0,timeReceived:Date.now()}),this.privIsWriteEnded=!0)}writeStreamChunk(e){if(this.throwIfClosed(),!this.privReaderQueue.isDisposed())try{this.privReaderQueue.enqueue(e)}catch{}}read(){if(this.privIsReadEnded)throw new W("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>qi(this,void 0,void 0,function*(){return(e===void 0||e.isEnd)&&(yield this.privReaderQueue.dispose("End of stream reached")),e}))}readEnded(){this.privIsReadEnded||(this.privIsReadEnded=!0,this.privReaderQueue=new Ie)}throwIfClosed(){if(this.privIsWriteEnded)throw new W("Stream closed")}}var Me;(function(r){r[r.Success=0]="Success",r[r.Error=1]="Error"})(Me||(Me={}));class mt extends jt{constructor(e,t){super(t),this.privTargetChunkSize=e,this.privNextBufferReadyBytes=0}writeStreamChunk(e){if(e.isEnd||this.privNextBufferReadyBytes===0&&e.buffer.byteLength===this.privTargetChunkSize){super.writeStreamChunk(e);return}let t=0;for(;t<e.buffer.byteLength;){this.privNextBufferToWrite===void 0&&(this.privNextBufferToWrite=new ArrayBuffer(this.privTargetChunkSize),this.privNextBufferStartTime=e.timeReceived);const i=Math.min(e.buffer.byteLength-t,this.privTargetChunkSize-this.privNextBufferReadyBytes),n=new Uint8Array(this.privNextBufferToWrite),s=new Uint8Array(e.buffer.slice(t,i+t));n.set(s,this.privNextBufferReadyBytes),this.privNextBufferReadyBytes+=i,t+=i,this.privNextBufferReadyBytes===this.privTargetChunkSize&&(super.writeStreamChunk({buffer:this.privNextBufferToWrite,isEnd:!1,timeReceived:this.privNextBufferStartTime}),this.privNextBufferReadyBytes=0,this.privNextBufferToWrite=void 0)}}close(){this.privNextBufferReadyBytes!==0&&!this.isClosed&&super.writeStreamChunk({buffer:this.privNextBufferToWrite.slice(0,this.privNextBufferReadyBytes),isEnd:!1,timeReceived:this.privNextBufferStartTime}),super.close()}}class B{static load(e){const t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(e);return n.addEventListener("message",({data:a})=>{if(B.isCallNotification(a)){const{params:{timerId:u}}=a,h=t.get(u);if(typeof h=="number"){const c=i.get(h);if(c===void 0||c!==u)throw new Error("The timer is in an undefined state.")}else if(typeof h!="undefined")h(),t.delete(u);else throw new Error("The timer is in an undefined state.")}else if(B.isClearResponse(a)){const{id:u}=a,h=i.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");i.delete(u),t.delete(h)}else{const{error:{message:u}}=a;throw new Error(u)}}),{clearTimeout:a=>{const u=Math.random();i.set(u,a),t.set(a,u),n.postMessage({id:u,method:"clear",params:{timerId:a}})},setTimeout:(a,u)=>{const h=Math.random();return t.set(h,a),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h}}),h}}}static loadWorkerTimers(){const e=`!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=14)}([function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return d}));const r=new Map,o=new Map,i=e=>{const t=r.get(e);if(void 0===t)throw new Error('There is no interval scheduled with the given id "'.concat(e,'".'));clearTimeout(t),r.delete(e)},u=e=>{const t=o.get(e);if(void 0===t)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(t),o.delete(e)},f=(e,t)=>{let n,r;if("performance"in self){const o=performance.now();n=o,r=e-Math.max(0,o-t)}else n=Date.now(),r=e;return{expected:n+r,remainingDelay:r}},c=(e,t,n,r)=>{const o="performance"in self?performance.now():Date.now();o>n?postMessage({id:null,method:"call",params:{timerId:t}}):e.set(t,setTimeout(c,n-o,e,t,n))},a=(e,t,n)=>{const{expected:o,remainingDelay:i}=f(e,n);r.set(t,setTimeout(c,i,r,t,o))},d=(e,t,n)=>{const{expected:r,remainingDelay:i}=f(e,n);o.set(t,setTimeout(c,i,o,t,r))}},function(e,t,n){"use strict";n.r(t);var r=n(2);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(3);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(4);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o);var f=n(5);for(var o in f)"default"!==o&&function(e){n.d(t,e,(function(){return f[e]}))}(o);var c=n(6);for(var o in c)"default"!==o&&function(e){n.d(t,e,(function(){return c[e]}))}(o);var a=n(7);for(var o in a)"default"!==o&&function(e){n.d(t,e,(function(){return a[e]}))}(o);var d=n(8);for(var o in d)"default"!==o&&function(e){n.d(t,e,(function(){return d[e]}))}(o);var s=n(9);for(var o in s)"default"!==o&&function(e){n.d(t,e,(function(){return s[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(11);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(12);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(13);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";var $r=Object.defineProperty;var Jr=(k,U,Y)=>U in k?$r(k,U,{enumerable:!0,configurable:!0,writable:!0,value:Y}):k[U]=Y;var m=(k,U,Y)=>(Jr(k,typeof U!="symbol"?U+"":U,Y),Y);n.r(t);var r=n(0),o=n(1);for(var i in o)"default"!==i&&function(e){n.d(t,e,(function(){return o[e]}))}(i);var u=n(10);for(var i in u)"default"!==i&&function(e){n.d(t,e,(function(){return u[e]}))}(i);addEventListener("message",({data:e})=>{try{if("clear"===e.method){const{id:t,params:{timerId:n}}=e;Object(r.b)(n),postMessage({error:null,id:t})}else{if("set"!==e.method)throw new Error('The given method "'.concat(e.method,'" is not supported'));{const{params:{delay:t,now:n,timerId:o}}=e;Object(r.d)(t,o,n)}}}catch(t){postMessage({error:{message:t.message},id:e.id,result:null})}})}]);`;return()=>{if(B.workerTimers!==null)return B.workerTimers;const t=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(t);return B.workerTimers=B.load(i),B.workerTimers.setTimeout(()=>URL.revokeObjectURL(i),0),B.workerTimers}}static isCallNotification(e){return e.method!==void 0&&e.method==="call"}static isClearResponse(e){return e.error===null&&typeof e.id=="number"}}B.workerTimers=null,B.clearTimeout=r=>B.timers().clearTimeout(r),B.setTimeout=(r,e)=>B.timers().setTimeout(r,e),B.timers=B.loadWorkerTimers();class _ extends ce{constructor(e,t,i){super(e,t),this.privSignature=i}}class Ui extends _{constructor(e){super("OCSPMemoryCacheHitEvent",C.Debug,e)}}class Wi extends _{constructor(e){super("OCSPCacheMissEvent",C.Debug,e)}}class Vi extends _{constructor(e){super("OCSPDiskCacheHitEvent",C.Debug,e)}}class Fi extends _{constructor(e){super("OCSPCacheUpdateNeededEvent",C.Debug,e)}}class ji extends _{constructor(e){super("OCSPMemoryCacheStoreEvent",C.Debug,e)}}class Gi extends _{constructor(e){super("OCSPDiskCacheStoreEvent",C.Debug,e)}}class $i extends _{constructor(e){super("OCSPCacheUpdateCompleteEvent",C.Debug,e)}}class Ji extends _{constructor(){super("OCSPStapleReceivedEvent",C.Debug,"")}}class Qi extends _{constructor(e,t){super("OCSPCacheEntryExpiredEvent",C.Debug,e),this.privExpireTime=t}}class Xi extends _{constructor(e,t,i){super("OCSPCacheEntryNeedsRefreshEvent",C.Debug,e),this.privExpireTime=i,this.privStartTime=t}}class Zi extends _{constructor(e,t,i){super("OCSPCacheHitEvent",C.Debug,e),this.privExpireTime=i,this.privExpireTimeString=new Date(i).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class Yi extends _{constructor(e,t){super("OCSPVerificationFailedEvent",C.Debug,e),this.privError=t}}class Gt extends _{constructor(e,t){super("OCSPCacheFetchErrorEvent",C.Debug,e),this.privError=t}}class er extends _{constructor(e){super("OCSPResponseRetrievedEvent",C.Debug,e)}}class tr extends _{constructor(e,t){super("OCSPCacheUpdateErrorEvent",C.Debug,e),this.privError=t}}class ke extends ce{constructor(e){super("BackgroundEvent",C.Error),this.privError=e}get error(){return this.privError}}class f{static throwIfNullOrUndefined(e,t){if(e==null)throw new Error("throwIfNullOrUndefined:"+t)}static throwIfNull(e,t){if(e===null)throw new Error("throwIfNull:"+t)}static throwIfNullOrWhitespace(e,t){if(f.throwIfNullOrUndefined(e,t),(""+e).trim().length<1)throw new Error("throwIfNullOrWhitespace:"+t)}static throwIfDisposed(e){if(e)throw new Error("the object is already disposed")}static throwIfArrayEmptyOrWhitespace(e,t){if(f.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const i of e)f.throwIfNullOrWhitespace(i,t)}static throwIfFileDoesNotExist(e,t){f.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class R{}R.AuthKey="Ocp-Apim-Subscription-Key",R.ConnectionId="X-ConnectionId",R.ContentType="Content-Type",R.CustomCommandsAppId="X-CommandsAppId",R.Path="Path",R.RequestId="X-RequestId",R.RequestStreamId="X-StreamId",R.RequestTimestamp="X-Timestamp";class yt{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class $t{constructor(e){if(!e)throw new z("subscriptionKey");this.privAuthInfo=new yt(R.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}const Jt="Authorization";class ve{constructor(e,t){if(!e)throw new z("fetchCallback");if(!t)throw new z("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new yt(Jt,ve.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new yt(Jt,ve.privTokenPrefix+t))}}ve.privTokenPrefix="bearer ";class Qt{constructor(e){f.throwIfNullOrUndefined(void 0,`
|
|
2
|
-
File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){f.throwIfNotUndefined(this.privAudioFormat,"format is already set"),this.privAudioFormat=e;let t=0;this.privAudioFormat.hasHeader&&(t=this.privAudioFormat.header.byteLength),this.privFd!==void 0&&(this.privWriteStream=(void 0)("",{fd:this.privFd,start:t,autoClose:!1}))}write(e){f.throwIfNullOrUndefined(this.privAudioFormat,"must set format before writing."),this.privWriteStream!==void 0&&this.privWriteStream.write(new Uint8Array(e.slice(0)))}close(){this.privFd!==void 0&&(this.privWriteStream.on("finish",()=>{this.privAudioFormat.hasHeader&&(this.privAudioFormat.updateHeader(this.privWriteStream.bytesWritten),(void 0)(this.privFd,new Int8Array(this.privAudioFormat.header),0,this.privAudioFormat.header.byteLength,0)),(void 0)(this.privFd),this.privFd=void 0}),this.privWriteStream.end())}id(){return this.privId}}var l;(function(r){r[r.PCM=1]="PCM",r[r.MuLaw=2]="MuLaw",r[r.Siren=3]="Siren",r[r.MP3=4]="MP3",r[r.SILKSkype=5]="SILKSkype",r[r.OGG_OPUS=6]="OGG_OPUS",r[r.WEBM_OPUS=7]="WEBM_OPUS",r[r.ALaw=8]="ALaw",r[r.FLAC=9]="FLAC",r[r.OPUS=10]="OPUS"})(l||(l={}));class We{static getDefaultInputFormat(){return ee.getDefaultInputFormat()}static getWaveFormat(e,t,i,n){return new ee(e,t,i,n)}static getWaveFormatPCM(e,t,i){return new ee(e,t,i)}}class ee extends We{constructor(e=16e3,t=16,i=1,n=l.PCM){super();let s=!0;switch(n){case l.PCM:this.formatTag=1;break;case l.ALaw:this.formatTag=6;break;case l.MuLaw:this.formatTag=7;break;default:s=!1}if(this.bitsPerSample=t,this.samplesPerSec=e,this.channels=i,this.avgBytesPerSec=this.samplesPerSec*this.channels*(this.bitsPerSample/8),this.blockAlign=this.channels*Math.max(this.bitsPerSample,8),s){this.privHeader=new ArrayBuffer(44);const o=new DataView(this.privHeader);this.setString(o,0,"RIFF"),o.setUint32(4,0,!0),this.setString(o,8,"WAVEfmt "),o.setUint32(16,16,!0),o.setUint16(20,this.formatTag,!0),o.setUint16(22,this.channels,!0),o.setUint32(24,this.samplesPerSec,!0),o.setUint32(28,this.avgBytesPerSec,!0),o.setUint16(32,this.channels*(this.bitsPerSample/8),!0),o.setUint16(34,this.bitsPerSample,!0),this.setString(o,36,"data"),o.setUint32(40,0,!0)}}static getDefaultInputFormat(){return new ee}static getAudioContext(e){const t=window.AudioContext||window.webkitAudioContext||!1;if(t)return e!==void 0&&navigator.mediaDevices.getSupportedConstraints().sampleRate?new t({sampleRate:e}):new t;throw new Error("Browser does not support Web Audio API (AudioContext is not available).")}close(){}get header(){return this.privHeader}setString(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}}var wt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Ct{constructor(){}static createPushStream(e){return Xt.create(e)}static createPullStream(e,t){return Zt.create(e,t)}}class Xt extends Ct{static create(e){return new ir(e)}}class ir extends Xt{constructor(e){super(),e===void 0?this.privFormat=ee.getDefaultInputFormat():this.privFormat=e,this.privEvents=new j,this.privId=A(),this.privStream=new mt(this.privFormat.avgBytesPerSec/10)}get format(){return Promise.resolve(this.privFormat)}write(e){this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}id(){return this.privId}get blob(){return this.attach("id").then(e=>{const t=[];let i=Buffer.from("");const n=()=>e.read().then(s=>!s||s.isEnd?typeof XMLHttpRequest!="undefined"&&typeof Blob!="undefined"?Promise.resolve(new Blob(t)):Promise.resolve(Buffer.from(i)):(typeof Blob!="undefined"?t.push(s.buffer):i=Buffer.concat([i,this.toBuffer(s.buffer)]),n()));return n()})}turnOn(){this.onEvent(new He(this.privId)),this.onEvent(new be(this.privId))}attach(e){return wt(this,void 0,void 0,function*(){this.onEvent(new Re(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new Ae(this.privId,e)),{detach:()=>wt(this,void 0,void 0,function*(){return this.onEvent(new J(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new J(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ye.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:pe.Stream})}onEvent(e){this.privEvents.onEvent(e),O.instance.onEvent(e)}toBuffer(e){const t=Buffer.alloc(e.byteLength),i=new Uint8Array(e);for(let n=0;n<t.length;++n)t[n]=i[n];return t}}class Zt extends Ct{constructor(){super()}static create(e,t){return new Yt(e,t)}}class Yt extends Zt{constructor(e,t){super(),t===void 0?this.privFormat=We.getDefaultInputFormat():this.privFormat=t,this.privEvents=new j,this.privId=A(),this.privCallback=e,this.privIsClosed=!1,this.privBufferSize=this.privFormat.avgBytesPerSec/10}get format(){return Promise.resolve(this.privFormat)}close(){this.privIsClosed=!0,this.privCallback.close()}id(){return this.privId}get blob(){return Promise.reject("Not implemented")}turnOn(){this.onEvent(new He(this.privId)),this.onEvent(new be(this.privId))}attach(e){return wt(this,void 0,void 0,function*(){return this.onEvent(new Re(this.privId,e)),yield this.turnOn(),this.onEvent(new Ae(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new J(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let t=0,i;for(;t<this.privBufferSize;){const n=new ArrayBuffer(this.privBufferSize-t),s=this.privCallback.read(n);if(i===void 0?i=n:new Int8Array(i).set(new Int8Array(n),t),s===0)break;t+=s}return Promise.resolve({buffer:i.slice(0,t),isEnd:this.privIsClosed||t===0,timeReceived:Date.now()})}}})}detach(e){this.onEvent(new J(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ye.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:pe.Stream})}onEvent(e){this.privEvents.onEvent(e),O.instance.onEvent(e)}}var S;(function(r){r[r.Raw8Khz8BitMonoMULaw=0]="Raw8Khz8BitMonoMULaw",r[r.Riff16Khz16KbpsMonoSiren=1]="Riff16Khz16KbpsMonoSiren",r[r.Audio16Khz16KbpsMonoSiren=2]="Audio16Khz16KbpsMonoSiren",r[r.Audio16Khz32KBitRateMonoMp3=3]="Audio16Khz32KBitRateMonoMp3",r[r.Audio16Khz128KBitRateMonoMp3=4]="Audio16Khz128KBitRateMonoMp3",r[r.Audio16Khz64KBitRateMonoMp3=5]="Audio16Khz64KBitRateMonoMp3",r[r.Audio24Khz48KBitRateMonoMp3=6]="Audio24Khz48KBitRateMonoMp3",r[r.Audio24Khz96KBitRateMonoMp3=7]="Audio24Khz96KBitRateMonoMp3",r[r.Audio24Khz160KBitRateMonoMp3=8]="Audio24Khz160KBitRateMonoMp3",r[r.Raw16Khz16BitMonoTrueSilk=9]="Raw16Khz16BitMonoTrueSilk",r[r.Riff16Khz16BitMonoPcm=10]="Riff16Khz16BitMonoPcm",r[r.Riff8Khz16BitMonoPcm=11]="Riff8Khz16BitMonoPcm",r[r.Riff24Khz16BitMonoPcm=12]="Riff24Khz16BitMonoPcm",r[r.Riff8Khz8BitMonoMULaw=13]="Riff8Khz8BitMonoMULaw",r[r.Raw16Khz16BitMonoPcm=14]="Raw16Khz16BitMonoPcm",r[r.Raw24Khz16BitMonoPcm=15]="Raw24Khz16BitMonoPcm",r[r.Raw8Khz16BitMonoPcm=16]="Raw8Khz16BitMonoPcm",r[r.Ogg16Khz16BitMonoOpus=17]="Ogg16Khz16BitMonoOpus",r[r.Ogg24Khz16BitMonoOpus=18]="Ogg24Khz16BitMonoOpus",r[r.Raw48Khz16BitMonoPcm=19]="Raw48Khz16BitMonoPcm",r[r.Riff48Khz16BitMonoPcm=20]="Riff48Khz16BitMonoPcm",r[r.Audio48Khz96KBitRateMonoMp3=21]="Audio48Khz96KBitRateMonoMp3",r[r.Audio48Khz192KBitRateMonoMp3=22]="Audio48Khz192KBitRateMonoMp3",r[r.Ogg48Khz16BitMonoOpus=23]="Ogg48Khz16BitMonoOpus",r[r.Webm16Khz16BitMonoOpus=24]="Webm16Khz16BitMonoOpus",r[r.Webm24Khz16BitMonoOpus=25]="Webm24Khz16BitMonoOpus",r[r.Raw24Khz16BitMonoTrueSilk=26]="Raw24Khz16BitMonoTrueSilk",r[r.Raw8Khz8BitMonoALaw=27]="Raw8Khz8BitMonoALaw",r[r.Riff8Khz8BitMonoALaw=28]="Riff8Khz8BitMonoALaw",r[r.Webm24Khz16Bit24KbpsMonoOpus=29]="Webm24Khz16Bit24KbpsMonoOpus",r[r.Audio16Khz16Bit32KbpsMonoOpus=30]="Audio16Khz16Bit32KbpsMonoOpus",r[r.Audio24Khz16Bit48KbpsMonoOpus=31]="Audio24Khz16Bit48KbpsMonoOpus",r[r.Audio24Khz16Bit24KbpsMonoOpus=32]="Audio24Khz16Bit24KbpsMonoOpus",r[r.Raw22050Hz16BitMonoPcm=33]="Raw22050Hz16BitMonoPcm",r[r.Riff22050Hz16BitMonoPcm=34]="Riff22050Hz16BitMonoPcm",r[r.Raw44100Hz16BitMonoPcm=35]="Raw44100Hz16BitMonoPcm",r[r.Riff44100Hz16BitMonoPcm=36]="Riff44100Hz16BitMonoPcm"})(S||(S={}));class g extends ee{constructor(e,t,i,n,s,o,a,u,h){super(i,o,t,e),this.formatTag=e,this.avgBytesPerSec=n,this.blockAlign=s,this.priAudioFormatString=a,this.priRequestAudioFormatString=u,this.priHasHeader=h}static fromSpeechSynthesisOutputFormat(e){return e===void 0?g.getDefaultOutputFormat():g.fromSpeechSynthesisOutputFormatString(g.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new g(l.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new g(l.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new g(l.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new g(l.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new g(l.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new g(l.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new g(l.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new g(l.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new g(l.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new g(l.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new g(l.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new g(l.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new g(l.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new g(l.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new g(l.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new g(l.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new g(l.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new g(l.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new g(l.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new g(l.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new g(l.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new g(l.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new g(l.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new g(l.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new g(l.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new g(l.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new g(l.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new g(l.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new g(l.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new g(l.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new g(l.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new g(l.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new g(l.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new g(l.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new g(l.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new g(l.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new g(l.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new g(l.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new g(l.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return g.fromSpeechSynthesisOutputFormatString(typeof window!="undefined"?"audio-24khz-48kbitrate-mono-mp3":"riff-16khz-16bit-mono-pcm")}get hasHeader(){return this.priHasHeader}get header(){if(this.hasHeader)return this.privHeader}updateHeader(e){if(this.priHasHeader){const t=new DataView(this.privHeader);t.setUint32(4,e+this.privHeader.byteLength-8,!0),t.setUint32(40,e,!0)}}get requestAudioFormatString(){return this.priRequestAudioFormatString}}g.SpeechSynthesisOutputFormatToString={[S.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[S.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[S.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[S.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[S.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[S.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[S.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[S.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[S.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[S.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[S.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[S.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[S.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[S.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[S.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[S.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[S.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[S.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[S.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[S.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[S.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[S.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[S.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[S.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[S.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[S.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[S.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[S.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[S.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[S.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[S.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[S.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[S.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[S.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[S.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[S.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[S.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var rr=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ei{constructor(){}static createPullStream(){return Ve.create()}}class Ve extends ei{static create(){return new Et}}class Et extends Ve{constructor(){super(),this.privId=A(),this.privStream=new jt}set format(e){e==null&&(this.privFormat=g.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return rr(this,void 0,void 0,function*(){const t=new Int8Array(e);let i=0;if(this.privLastChunkView!==void 0){if(this.privLastChunkView.length>e.byteLength)return t.set(this.privLastChunkView.slice(0,e.byteLength)),this.privLastChunkView=this.privLastChunkView.slice(e.byteLength),Promise.resolve(e.byteLength);t.set(this.privLastChunkView),i=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;i<e.byteLength&&!this.privStream.isReadEnded;){const n=yield this.privStream.read();if(n!==void 0&&!n.isEnd){let s;n.buffer.byteLength>e.byteLength-i?(s=n.buffer.slice(0,e.byteLength-i),this.privLastChunkView=new Int8Array(n.buffer.slice(e.byteLength-i))):s=n.buffer,t.set(new Int8Array(s),i),i+=s.byteLength}else this.privStream.readEnded()}return i})}write(e){f.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class ti extends ei{constructor(){super()}static create(e){return new Tt(e)}}class Tt extends ti{constructor(e){super(),this.privId=A(),this.privCallback=e}set format(e){}write(e){this.privCallback.write&&this.privCallback.write(e)}close(){this.privCallback.close&&this.privCallback.close()}id(){return this.privId}}class te{static fromDefaultMicrophoneInput(){const e=new Bt(!0);return new fe(new F(e))}static fromMicrophoneInput(e){const t=new Bt(!0);return new fe(new F(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new fe(new Lr(e,t))}static fromStreamInput(e){if(e instanceof nr)return new fe(new Yt(e));if(e instanceof Ct)return new fe(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new Bt(!1);return new fe(new F(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new ge(new Mt)}static fromSpeakerOutput(e){if(e===void 0)return te.fromDefaultSpeakerOutput();if(e instanceof Mt)return new ge(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new ge(new Qt(e))}static fromStreamOutput(e){if(e instanceof ii)return new ge(new Tt(e));if(e instanceof ti)return new ge(e);if(e instanceof Ve)return new ge(e);throw new Error("Not Supported Type")}}class fe extends te{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then(()=>{e&&e()},i=>{t&&t(i)})}id(){return this.privSource.id()}get blob(){return this.privSource.blob}turnOn(){return this.privSource.turnOn()}attach(e){return this.privSource.attach(e)}detach(e){return this.privSource.detach(e)}turnOff(){return this.privSource.turnOff()}get events(){return this.privSource.events}setProperty(e,t){if(f.throwIfNull(t,"value"),this.privSource.setProperty!==void 0)this.privSource.setProperty(e,t);else throw new Error("This AudioConfig instance does not support setting properties.")}getProperty(e,t){if(this.privSource.getProperty!==void 0)return this.privSource.getProperty(e,t);throw new Error("This AudioConfig instance does not support getting properties.")}get deviceInfo(){return this.privSource.deviceInfo}}class ge extends te{constructor(e){super(),this.privDestination=e}set format(e){this.privDestination.format=e}write(e){this.privDestination.write(e)}close(){this.privDestination.close()}id(){return this.privDestination.id()}setProperty(){throw new Error("This AudioConfig instance does not support setting properties.")}getProperty(){throw new Error("This AudioConfig instance does not support getting properties.")}}var q;(function(r){r[r.Error=0]="Error",r[r.EndOfStream=1]="EndOfStream"})(q||(q={}));class nr{}class ii{}class Se{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}class bt extends Se{constructor(e,t){super(t),this.privOffset=e}get offset(){return this.privOffset}}var ie;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(ie||(ie={}));class sr{constructor(e,t,i,n,s,o,a,u,h,c){this.privResultId=e,this.privReason=t,this.privText=i,this.privDuration=n,this.privOffset=s,this.privLanguage=o,this.privLanguageDetectionConfidence=a,this.privErrorDetails=u,this.privJson=h,this.privProperties=c}get resultId(){return this.privResultId}get reason(){return this.privReason}get text(){return this.privText}get duration(){return this.privDuration}get offset(){return this.privOffset}get language(){return this.privLanguage}get languageDetectionConfidence(){return this.privLanguageDetectionConfidence}get errorDetails(){return this.privErrorDetails}get json(){return this.privJson}get properties(){return this.privProperties}}class or extends sr{constructor(e,t,i,n,s,o,a,u,h,c,d){super(e,t,i,n,s,o,a,h,c,d),this.privSpeakerId=u}get speakerId(){return this.privSpeakerId}}class ri extends bt{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}class ni extends Se{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}class Rt extends or{constructor(e,t,i,n,s,o,a,u,h){super(t,i,n,s,o,void 0,void 0,void 0,a,u,h),this.privTranslations=e}get translations(){return this.privTranslations}}class si{constructor(e,t){this.privReason=e,this.privAudio=t}get audio(){return this.privAudio}get reason(){return this.privReason}}var I;(function(r){r[r.NoMatch=0]="NoMatch",r[r.Canceled=1]="Canceled",r[r.RecognizingSpeech=2]="RecognizingSpeech",r[r.RecognizedSpeech=3]="RecognizedSpeech",r[r.RecognizedKeyword=4]="RecognizedKeyword",r[r.RecognizingIntent=5]="RecognizingIntent",r[r.RecognizedIntent=6]="RecognizedIntent",r[r.TranslatingSpeech=7]="TranslatingSpeech",r[r.TranslatedSpeech=8]="TranslatedSpeech",r[r.SynthesizingAudio=9]="SynthesizingAudio",r[r.SynthesizingAudioCompleted=10]="SynthesizingAudioCompleted",r[r.SynthesizingAudioStarted=11]="SynthesizingAudioStarted",r[r.EnrollingVoiceProfile=12]="EnrollingVoiceProfile",r[r.EnrolledVoiceProfile=13]="EnrolledVoiceProfile",r[r.RecognizedSpeakers=14]="RecognizedSpeakers",r[r.RecognizedSpeaker=15]="RecognizedSpeaker",r[r.ResetVoiceProfile=16]="ResetVoiceProfile",r[r.DeletedVoiceProfile=17]="DeletedVoiceProfile",r[r.VoicesListRetrieved=18]="VoicesListRetrieved"})(I||(I={}));class At{constructor(){}static fromSubscription(e,t){f.throwIfNullOrWhitespace(e,"subscriptionKey"),f.throwIfNullOrWhitespace(t,"region");const i=new me;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.setProperty(p.SpeechServiceConnection_Key,e),i}static fromEndpoint(e,t){f.throwIfNull(e,"endpoint");const i=new me;return i.setProperty(p.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromHost(e,t){f.throwIfNull(e,"hostName");const i=new me;return i.setProperty(p.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromAuthorizationToken(e,t){f.throwIfNull(e,"authorizationToken"),f.throwIfNullOrWhitespace(t,"region");const i=new me;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.authorizationToken=e,i}close(){}}class me extends At{constructor(){super(),this.privProperties=new V,this.speechRecognitionLanguage="en-US",this.outputFormat=ie.Simple}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(p.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(p.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(p.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(p.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(p.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(p.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return ie[this.privProperties.getProperty(st,void 0)]}set outputFormat(e){this.privProperties.setProperty(st,ie[e])}get endpointId(){return this.privProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){f.throwIfNull(t,"value"),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,i,n){this.setProperty(p[p.SpeechServiceConnection_ProxyHostName],e),this.setProperty(p[p.SpeechServiceConnection_ProxyPort],t),this.setProperty(p[p.SpeechServiceConnection_ProxyUserName],i),this.setProperty(p[p.SpeechServiceConnection_ProxyPassword],n)}setServiceProperty(e,t){const i=JSON.parse(this.privProperties.getProperty(Le,"{}"));i[e]=t,this.privProperties.setProperty(Le,JSON.stringify(i))}setProfanity(e){this.privProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,$e[e])}enableAudioLogging(){this.privProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(Ri,"true")}clone(){const e=new me;return e.privProperties=this.privProperties.clone(),e}get speechSynthesisLanguage(){return this.privProperties.getProperty(p.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(p.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return S[this.privProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,S[e])}}class oi extends At{constructor(){super()}static fromSubscription(e,t){f.throwIfNullOrWhitespace(e,"subscriptionKey"),f.throwIfNullOrWhitespace(t,"region");const i=new Fe;return i.properties.setProperty(p.SpeechServiceConnection_Key,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromAuthorizationToken(e,t){f.throwIfNullOrWhitespace(e,"authorizationToken"),f.throwIfNullOrWhitespace(t,"region");const i=new Fe;return i.properties.setProperty(p.SpeechServiceAuthorization_Token,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromHost(e,t){f.throwIfNull(e,"hostName");const i=new Fe;return i.setProperty(p.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromEndpoint(e,t){f.throwIfNull(e,"endpoint"),f.throwIfNull(t,"subscriptionKey");const i=new Fe;return i.properties.setProperty(p.SpeechServiceConnection_Endpoint,e.href),i.properties.setProperty(p.SpeechServiceConnection_Key,t),i}}class Fe extends oi{constructor(){super(),this.privSpeechProperties=new V,this.outputFormat=ie.Simple}set authorizationToken(e){f.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceAuthorization_Token,e)}set speechRecognitionLanguage(e){f.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_RecoLanguage,e)}get speechRecognitionLanguage(){return this.privSpeechProperties.getProperty(p[p.SpeechServiceConnection_RecoLanguage])}get subscriptionKey(){return this.privSpeechProperties.getProperty(p[p.SpeechServiceConnection_Key])}get outputFormat(){return ie[this.privSpeechProperties.getProperty(st,void 0)]}set outputFormat(e){this.privSpeechProperties.setProperty(st,ie[e])}get endpointId(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}addTargetLanguage(e){f.throwIfNullOrWhitespace(e,"value");const t=this.targetLanguages;t.push(e),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(","))}get targetLanguages(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0?this.privSpeechProperties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","):[]}get voiceName(){return this.getProperty(p[p.SpeechServiceConnection_TranslationVoice])}set voiceName(e){f.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceConnection_TranslationVoice,e)}get region(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_Region)}setProxy(e,t,i,n){this.setProperty(p[p.SpeechServiceConnection_ProxyHostName],e),this.setProperty(p[p.SpeechServiceConnection_ProxyPort],t),this.setProperty(p[p.SpeechServiceConnection_ProxyUserName],i),this.setProperty(p[p.SpeechServiceConnection_ProxyPassword],n)}getProperty(e,t){return this.privSpeechProperties.getProperty(e,t)}setProperty(e,t){this.privSpeechProperties.setProperty(e,t)}get properties(){return this.privSpeechProperties}close(){}setServiceProperty(e,t){const i=JSON.parse(this.privSpeechProperties.getProperty(Le,"{}"));i[e]=t,this.privSpeechProperties.setProperty(Le,JSON.stringify(i))}setProfanity(e){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,$e[e])}enableAudioLogging(){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privSpeechProperties.setProperty(Ri,"true")}get speechSynthesisLanguage(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return S[this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,S[e])}}class V{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,t){let i;typeof e=="string"?i=e:i=p[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===i)return this.privValues[n];if(t!==void 0)return String(t)}setProperty(e,t){let i;typeof e=="string"?i=e:i=p[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===i){this.privValues[n]=t;return}this.privKeys.push(i),this.privValues.push(t)}clone(){const e=new V;for(let t=0;t<this.privKeys.length;t++)e.privKeys.push(this.privKeys[t]),e.privValues.push(this.privValues[t]);return e}mergeTo(e){this.privKeys.forEach(t=>{if(e.getProperty(t,void 0)===void 0){const i=this.getProperty(t);e.setProperty(t,i)}})}get keys(){return this.privKeys}}var p;(function(r){r[r.SpeechServiceConnection_Key=0]="SpeechServiceConnection_Key",r[r.SpeechServiceConnection_Endpoint=1]="SpeechServiceConnection_Endpoint",r[r.SpeechServiceConnection_Region=2]="SpeechServiceConnection_Region",r[r.SpeechServiceAuthorization_Token=3]="SpeechServiceAuthorization_Token",r[r.SpeechServiceAuthorization_Type=4]="SpeechServiceAuthorization_Type",r[r.SpeechServiceConnection_EndpointId=5]="SpeechServiceConnection_EndpointId",r[r.SpeechServiceConnection_TranslationToLanguages=6]="SpeechServiceConnection_TranslationToLanguages",r[r.SpeechServiceConnection_TranslationVoice=7]="SpeechServiceConnection_TranslationVoice",r[r.SpeechServiceConnection_TranslationFeatures=8]="SpeechServiceConnection_TranslationFeatures",r[r.SpeechServiceConnection_IntentRegion=9]="SpeechServiceConnection_IntentRegion",r[r.SpeechServiceConnection_ProxyHostName=10]="SpeechServiceConnection_ProxyHostName",r[r.SpeechServiceConnection_ProxyPort=11]="SpeechServiceConnection_ProxyPort",r[r.SpeechServiceConnection_ProxyUserName=12]="SpeechServiceConnection_ProxyUserName",r[r.SpeechServiceConnection_ProxyPassword=13]="SpeechServiceConnection_ProxyPassword",r[r.SpeechServiceConnection_RecoMode=14]="SpeechServiceConnection_RecoMode",r[r.SpeechServiceConnection_RecoLanguage=15]="SpeechServiceConnection_RecoLanguage",r[r.Speech_SessionId=16]="Speech_SessionId",r[r.SpeechServiceConnection_SynthLanguage=17]="SpeechServiceConnection_SynthLanguage",r[r.SpeechServiceConnection_SynthVoice=18]="SpeechServiceConnection_SynthVoice",r[r.SpeechServiceConnection_SynthOutputFormat=19]="SpeechServiceConnection_SynthOutputFormat",r[r.SpeechServiceConnection_AutoDetectSourceLanguages=20]="SpeechServiceConnection_AutoDetectSourceLanguages",r[r.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]="SpeechServiceResponse_RequestDetailedResultTrueFalse",r[r.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]="SpeechServiceResponse_RequestProfanityFilterTrueFalse",r[r.SpeechServiceResponse_JsonResult=23]="SpeechServiceResponse_JsonResult",r[r.SpeechServiceResponse_JsonErrorDetails=24]="SpeechServiceResponse_JsonErrorDetails",r[r.CancellationDetails_Reason=25]="CancellationDetails_Reason",r[r.CancellationDetails_ReasonText=26]="CancellationDetails_ReasonText",r[r.CancellationDetails_ReasonDetailedText=27]="CancellationDetails_ReasonDetailedText",r[r.LanguageUnderstandingServiceResponse_JsonResult=28]="LanguageUnderstandingServiceResponse_JsonResult",r[r.SpeechServiceConnection_Url=29]="SpeechServiceConnection_Url",r[r.SpeechServiceConnection_InitialSilenceTimeoutMs=30]="SpeechServiceConnection_InitialSilenceTimeoutMs",r[r.SpeechServiceConnection_EndSilenceTimeoutMs=31]="SpeechServiceConnection_EndSilenceTimeoutMs",r[r.Speech_SegmentationSilenceTimeoutMs=32]="Speech_SegmentationSilenceTimeoutMs",r[r.SpeechServiceConnection_EnableAudioLogging=33]="SpeechServiceConnection_EnableAudioLogging",r[r.SpeechServiceConnection_AtStartLanguageIdPriority=34]="SpeechServiceConnection_AtStartLanguageIdPriority",r[r.SpeechServiceConnection_ContinuousLanguageIdPriority=35]="SpeechServiceConnection_ContinuousLanguageIdPriority",r[r.SpeechServiceConnection_RecognitionEndpointVersion=36]="SpeechServiceConnection_RecognitionEndpointVersion",r[r.SpeechServiceResponse_ProfanityOption=37]="SpeechServiceResponse_ProfanityOption",r[r.SpeechServiceResponse_PostProcessingOption=38]="SpeechServiceResponse_PostProcessingOption",r[r.SpeechServiceResponse_RequestWordLevelTimestamps=39]="SpeechServiceResponse_RequestWordLevelTimestamps",r[r.SpeechServiceResponse_StablePartialResultThreshold=40]="SpeechServiceResponse_StablePartialResultThreshold",r[r.SpeechServiceResponse_OutputFormatOption=41]="SpeechServiceResponse_OutputFormatOption",r[r.SpeechServiceResponse_TranslationRequestStablePartialResult=42]="SpeechServiceResponse_TranslationRequestStablePartialResult",r[r.SpeechServiceResponse_RequestWordBoundary=43]="SpeechServiceResponse_RequestWordBoundary",r[r.SpeechServiceResponse_RequestPunctuationBoundary=44]="SpeechServiceResponse_RequestPunctuationBoundary",r[r.SpeechServiceResponse_RequestSentenceBoundary=45]="SpeechServiceResponse_RequestSentenceBoundary",r[r.Conversation_ApplicationId=46]="Conversation_ApplicationId",r[r.Conversation_DialogType=47]="Conversation_DialogType",r[r.Conversation_Initial_Silence_Timeout=48]="Conversation_Initial_Silence_Timeout",r[r.Conversation_From_Id=49]="Conversation_From_Id",r[r.Conversation_Conversation_Id=50]="Conversation_Conversation_Id",r[r.Conversation_Custom_Voice_Deployment_Ids=51]="Conversation_Custom_Voice_Deployment_Ids",r[r.Conversation_Speech_Activity_Template=52]="Conversation_Speech_Activity_Template",r[r.Conversation_Request_Bot_Status_Messages=53]="Conversation_Request_Bot_Status_Messages",r[r.Conversation_Agent_Connection_Id=54]="Conversation_Agent_Connection_Id",r[r.SpeechServiceConnection_Host=55]="SpeechServiceConnection_Host",r[r.ConversationTranslator_Host=56]="ConversationTranslator_Host",r[r.ConversationTranslator_Name=57]="ConversationTranslator_Name",r[r.ConversationTranslator_CorrelationId=58]="ConversationTranslator_CorrelationId",r[r.ConversationTranslator_Token=59]="ConversationTranslator_Token",r[r.PronunciationAssessment_ReferenceText=60]="PronunciationAssessment_ReferenceText",r[r.PronunciationAssessment_GradingSystem=61]="PronunciationAssessment_GradingSystem",r[r.PronunciationAssessment_Granularity=62]="PronunciationAssessment_Granularity",r[r.PronunciationAssessment_EnableMiscue=63]="PronunciationAssessment_EnableMiscue",r[r.PronunciationAssessment_Json=64]="PronunciationAssessment_Json",r[r.PronunciationAssessment_Params=65]="PronunciationAssessment_Params",r[r.SpeakerRecognition_Api_Version=66]="SpeakerRecognition_Api_Version"})(p||(p={}));var ze=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Pt{constructor(e,t,i){this.audioConfig=e!==void 0?e:te.fromDefaultMicrophoneInput(),this.privDisposed=!1,this.privProperties=t.clone(),this.privConnectionFactory=i,this.implCommonRecognizerSetup()}close(e,t){f.throwIfDisposed(this.privDisposed),Q(this.dispose(!0),e,t)}get internalData(){return this.privReco}dispose(e){return ze(this,void 0,void 0,function*(){this.privDisposed||(this.privDisposed=!0,e&&this.privReco&&(yield this.privReco.audioSource.turnOff(),yield this.privReco.dispose()))})}static get telemetryEnabled(){return $.telemetryDataEnabled}static enableTelemetry(e){$.telemetryDataEnabled=e}implCommonRecognizerSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",i="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,i=navigator.appVersion);const n=this.createRecognizerConfig(new et(new tt(new yi(e,t,i))));this.privReco=this.createServiceRecognizer(Pt.getAuthFromProperties(this.privProperties),this.privConnectionFactory,this.audioConfig,n)}recognizeOnceAsyncImpl(e){return ze(this,void 0,void 0,function*(){f.throwIfDisposed(this.privDisposed);const t=new x;yield this.implRecognizerStop(),yield this.privReco.recognize(e,t.resolve,t.reject);const i=yield t.promise;return yield this.implRecognizerStop(),i})}startContinuousRecognitionAsyncImpl(e){return ze(this,void 0,void 0,function*(){f.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop(),yield this.privReco.recognize(e,void 0,void 0)})}stopContinuousRecognitionAsyncImpl(){return ze(this,void 0,void 0,function*(){f.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop()})}implRecognizerStop(){return ze(this,void 0,void 0,function*(){this.privReco&&(yield this.privReco.stopRecognizing())})}static getAuthFromProperties(e){const t=e.getProperty(p.SpeechServiceConnection_Key,void 0);return t&&t!==""?new $t(t):new ve(()=>{const n=e.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(n)},()=>{const n=e.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(n)})}}class ai{constructor(e){this.privConnectionMessage=e,this.privProperties=new V,this.privConnectionMessage.headers[R.ConnectionId]&&this.privProperties.setProperty(p.Speech_SessionId,this.privConnectionMessage.headers[R.ConnectionId]),Object.keys(this.privConnectionMessage.headers).forEach(t=>{this.privProperties.setProperty(t,this.privConnectionMessage.headers[t])})}get path(){return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find(e=>e.toLowerCase()==="path".toLowerCase())]}get isTextMessage(){return this.privConnectionMessage.messageType===y.Text}get isBinaryMessage(){return this.privConnectionMessage.messageType===y.Binary}get TextMessage(){return this.privConnectionMessage.textBody}get binaryMessage(){return this.privConnectionMessage.binaryBody}get properties(){return this.privProperties}toString(){return""}}class je{static fromRecognizer(e){const t=e.internalData,i=new je;return i.privInternalData=t,i.setupEvents(),i}static fromSynthesizer(e){const t=e.internalData,i=new je;return i.privInternalData=t,i.setupEvents(),i}openConnection(e,t){Q(this.privInternalData.connect(),e,t)}closeConnection(e,t){if(this.privInternalData instanceof se)throw new Error("Disconnecting a synthesizer's connection is currently not supported");Q(this.privInternalData.disconnect(),e,t)}setMessageProperty(e,t,i){if(f.throwIfNullOrWhitespace(t,"propertyName"),this.privInternalData instanceof $){if(e.toLowerCase()!=="speech.context")throw new Error("Only speech.context message property sets are currently supported for recognizer");this.privInternalData.speechContext.setSection(t,i)}else if(this.privInternalData instanceof se){if(e.toLowerCase()!=="synthesis.context")throw new Error("Only synthesis.context message property sets are currently supported for synthesizer");this.privInternalData.synthesisContext.setSection(t,i)}}sendMessageAsync(e,t,i,n){Q(this.privInternalData.sendNetworkMessage(e,t),i,n)}close(){}setupEvents(){this.privEventListener=this.privInternalData.connectionEvents.attach(e=>{e.name==="ConnectionEstablishedEvent"?this.connected&&this.connected(new ui(e.connectionId)):e.name==="ConnectionClosedEvent"?this.disconnected&&this.disconnected(new ui(e.connectionId)):e.name==="ConnectionMessageSentEvent"?this.messageSent&&this.messageSent(new pi(new ai(e.message))):e.name==="ConnectionMessageReceivedEvent"&&this.messageReceived&&this.messageReceived(new pi(new ai(e.message)))}),this.privServiceEventListener=this.privInternalData.serviceEvents.attach(e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new hr(e.jsonString,e.name))})}}var ci=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ar extends Pt{constructor(e,t){const i=e;f.throwIfNull(i,"speechConfig"),super(t,i.properties,new wr),this.privDisposedTranslationRecognizer=!1,this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&f.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice),p[p.SpeechServiceConnection_TranslationVoice]),f.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages),p[p.SpeechServiceConnection_TranslationToLanguages]),f.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage),p[p.SpeechServiceConnection_RecoLanguage])}get speechRecognitionLanguage(){return f.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage)}get targetLanguages(){return f.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(",")}get voiceName(){return f.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)}get properties(){return this.privProperties}get authorizationToken(){return this.properties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.properties.setProperty(p.SpeechServiceAuthorization_Token,e)}recognizeOnceAsync(e,t){f.throwIfDisposed(this.privDisposedTranslationRecognizer),Q(this.recognizeOnceAsyncImpl(ue.Conversation),e,t)}startContinuousRecognitionAsync(e,t){Q(this.startContinuousRecognitionAsyncImpl(ue.Conversation),e,t)}stopContinuousRecognitionAsync(e,t){Q(this.stopContinuousRecognitionAsyncImpl(),e,t)}removeTargetLanguage(e){if(f.throwIfNullOrUndefined(e,"language to be removed"),this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0){const t=this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","),i=t.indexOf(e);i>-1&&(t.splice(i,1),this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(",")),this.updateLanguages(t))}}addTargetLanguage(e){f.throwIfNullOrUndefined(e,"language to be added");let t=[];this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0?(t=this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(","),t.includes(e)||(t.push(e),this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,t.join(",")))):(this.properties.setProperty(p.SpeechServiceConnection_TranslationToLanguages,e),t=[e]),this.updateLanguages(t)}close(e,t){f.throwIfDisposed(this.privDisposedTranslationRecognizer),Q(this.dispose(!0),e,t)}onConnection(){}onDisconnection(){return ci(this,void 0,void 0,function*(){})}dispose(e){const t=Object.create(null,{dispose:{get:()=>super.dispose}});return ci(this,void 0,void 0,function*(){this.privDisposedTranslationRecognizer||(this.privDisposedTranslationRecognizer=!0,e&&(yield this.implRecognizerStop(),yield t.dispose.call(this,e)))})}createRecognizerConfig(e){return new mr(e,this.properties)}createServiceRecognizer(e,t,i,n){const s=i;return new Er(e,t,s,n,this)}updateLanguages(e){const t=je.fromRecognizer(this);t&&(t.setMessageProperty("speech.context","translationcontext",{to:e}),t.sendMessageAsync("event",JSON.stringify({id:"translation",name:"updateLanguage",to:e})))}}class cr{constructor(){this.privMap=new V}get languages(){return this.privMap.keys}get(e,t){return this.privMap.getProperty(e,t)}set(e,t){this.privMap.setProperty(e,t)}}class hi{constructor(e,t,i,n,s){this.privCancelReason=t,this.privErrorDetails=i,this.privResult=s,this.privSessionId=e,this.privErrorCode=n}get result(){return this.privResult}get sessionId(){return this.privSessionId}get reason(){return this.privCancelReason}get errorCode(){return this.privErrorCode}get errorDetails(){return this.privErrorDetails}}var P;(function(r){r[r.NoError=0]="NoError",r[r.AuthenticationFailure=1]="AuthenticationFailure",r[r.BadRequestParameters=2]="BadRequestParameters",r[r.TooManyRequests=3]="TooManyRequests",r[r.ConnectionFailure=4]="ConnectionFailure",r[r.ServiceTimeout=5]="ServiceTimeout",r[r.ServiceError=6]="ServiceError",r[r.RuntimeError=7]="RuntimeError",r[r.Forbidden=8]="Forbidden"})(P||(P={}));class ui extends Se{}class hr extends Se{constructor(e,t,i){super(i),this.privJsonResult=e,this.privEventName=t}get jsonString(){return this.privJsonResult}get eventName(){return this.privEventName}}class E{}E.BotId="botid",E.CustomSpeechDeploymentId="cid",E.CustomVoiceDeploymentId="deploymentId",E.EnableAudioLogging="storeAudio",E.EnableLanguageId="lidEnabled",E.EnableWordLevelTimestamps="wordLevelTimestamps",E.EndSilenceTimeoutMs="endSilenceTimeoutMs",E.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",E.Format="format",E.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",E.Language="language",E.Profanity="profanity",E.RequestBotStatusMessages="enableBotMessageStatus",E.StableIntermediateThreshold="stableIntermediateThreshold",E.StableTranslation="stableTranslation",E.TestHooks="testhooks",E.Postprocessing="postprocessing";class Ge{static getHostSuffix(e){if(e){if(e.toLowerCase().startsWith("china"))return".azure.cn";if(e.toLowerCase().startsWith("usgov"))return".azure.us"}return".microsoft.com"}setCommonUrlParams(e,t,i){new Map([[p.Speech_SegmentationSilenceTimeoutMs,E.SegmentationSilenceTimeoutMs],[p.SpeechServiceConnection_EnableAudioLogging,E.EnableAudioLogging],[p.SpeechServiceConnection_EndSilenceTimeoutMs,E.EndSilenceTimeoutMs],[p.SpeechServiceConnection_InitialSilenceTimeoutMs,E.InitialSilenceTimeoutMs],[p.SpeechServiceResponse_PostProcessingOption,E.Postprocessing],[p.SpeechServiceResponse_ProfanityOption,E.Profanity],[p.SpeechServiceResponse_RequestWordLevelTimestamps,E.EnableWordLevelTimestamps],[p.SpeechServiceResponse_StablePartialResultThreshold,E.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,i)});const s=JSON.parse(e.parameters.getProperty(Le,"{}"));Object.keys(s).forEach(o=>{t[o]=s[o]})}setUrlParameter(e,t,i,n,s){const o=i.parameters.getProperty(e,void 0);o&&(!s||s.search(t)===-1)&&(n[t]=o.toLocaleLowerCase())}}var $e;(function(r){r[r.Masked=0]="Masked",r[r.Removed=1]="Removed",r[r.Raw=2]="Raw"})($e||($e={}));class pi{constructor(e){this.privConnectionMessage=e}get message(){return this.privConnectionMessage}toString(){return"Message: "+this.privConnectionMessage.toString()}}var Je=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class De{constructor(e,t){const i=e;f.throwIfNull(i,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:te.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=i.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new Cr,this.synthesisRequestQueue=new Ie,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){f.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(p.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages)===xr}static FromConfig(e,t,i){const n=e;return t.properties.mergeTo(n.properties),new De(e,i)}buildSsml(e){const t={["af-ZA"]:"af-ZA-AdriNeural",["am-ET"]:"am-ET-AmehaNeural",["ar-AE"]:"ar-AE-FatimaNeural",["ar-BH"]:"ar-BH-AliNeural",["ar-DZ"]:"ar-DZ-AminaNeural",["ar-EG"]:"ar-EG-SalmaNeural",["ar-IQ"]:"ar-IQ-BasselNeural",["ar-JO"]:"ar-JO-SanaNeural",["ar-KW"]:"ar-KW-FahedNeural",["ar-LY"]:"ar-LY-ImanNeural",["ar-MA"]:"ar-MA-JamalNeural",["ar-QA"]:"ar-QA-AmalNeural",["ar-SA"]:"ar-SA-HamedNeural",["ar-SY"]:"ar-SY-AmanyNeural",["ar-TN"]:"ar-TN-HediNeural",["ar-YE"]:"ar-YE-MaryamNeural",["bg-BG"]:"bg-BG-BorislavNeural",["bn-BD"]:"bn-BD-NabanitaNeural",["bn-IN"]:"bn-IN-BashkarNeural",["ca-ES"]:"ca-ES-JoanaNeural",["cs-CZ"]:"cs-CZ-AntoninNeural",["cy-GB"]:"cy-GB-AledNeural",["da-DK"]:"da-DK-ChristelNeural",["de-AT"]:"de-AT-IngridNeural",["de-CH"]:"de-CH-JanNeural",["de-DE"]:"de-DE-KatjaNeural",["el-GR"]:"el-GR-AthinaNeural",["en-AU"]:"en-AU-NatashaNeural",["en-CA"]:"en-CA-ClaraNeural",["en-GB"]:"en-GB-LibbyNeural",["en-HK"]:"en-HK-SamNeural",["en-IE"]:"en-IE-ConnorNeural",["en-IN"]:"en-IN-NeerjaNeural",["en-KE"]:"en-KE-AsiliaNeural",["en-NG"]:"en-NG-AbeoNeural",["en-NZ"]:"en-NZ-MitchellNeural",["en-PH"]:"en-PH-JamesNeural",["en-SG"]:"en-SG-LunaNeural",["en-TZ"]:"en-TZ-ElimuNeural",["en-US"]:"en-US-JennyNeural",["en-ZA"]:"en-ZA-LeahNeural",["es-AR"]:"es-AR-ElenaNeural",["es-BO"]:"es-BO-MarceloNeural",["es-CL"]:"es-CL-CatalinaNeural",["es-CO"]:"es-CO-GonzaloNeural",["es-CR"]:"es-CR-JuanNeural",["es-CU"]:"es-CU-BelkysNeural",["es-DO"]:"es-DO-EmilioNeural",["es-EC"]:"es-EC-AndreaNeural",["es-ES"]:"es-ES-AlvaroNeural",["es-GQ"]:"es-GQ-JavierNeural",["es-GT"]:"es-GT-AndresNeural",["es-HN"]:"es-HN-CarlosNeural",["es-MX"]:"es-MX-DaliaNeural",["es-NI"]:"es-NI-FedericoNeural",["es-PA"]:"es-PA-MargaritaNeural",["es-PE"]:"es-PE-AlexNeural",["es-PR"]:"es-PR-KarinaNeural",["es-PY"]:"es-PY-MarioNeural",["es-SV"]:"es-SV-LorenaNeural",["es-US"]:"es-US-AlonsoNeural",["es-UY"]:"es-UY-MateoNeural",["es-VE"]:"es-VE-PaolaNeural",["et-EE"]:"et-EE-AnuNeural",["fa-IR"]:"fa-IR-DilaraNeural",["fi-FI"]:"fi-FI-SelmaNeural",["fil-PH"]:"fil-PH-AngeloNeural",["fr-BE"]:"fr-BE-CharlineNeural",["fr-CA"]:"fr-CA-SylvieNeural",["fr-CH"]:"fr-CH-ArianeNeural",["fr-FR"]:"fr-FR-DeniseNeural",["ga-IE"]:"ga-IE-ColmNeural",["gl-ES"]:"gl-ES-RoiNeural",["gu-IN"]:"gu-IN-DhwaniNeural",["he-IL"]:"he-IL-AvriNeural",["hi-IN"]:"hi-IN-MadhurNeural",["hr-HR"]:"hr-HR-GabrijelaNeural",["hu-HU"]:"hu-HU-NoemiNeural",["id-ID"]:"id-ID-ArdiNeural",["is-IS"]:"is-IS-GudrunNeural",["it-IT"]:"it-IT-IsabellaNeural",["ja-JP"]:"ja-JP-NanamiNeural",["jv-ID"]:"jv-ID-DimasNeural",["kk-KZ"]:"kk-KZ-AigulNeural",["km-KH"]:"km-KH-PisethNeural",["kn-IN"]:"kn-IN-GaganNeural",["ko-KR"]:"ko-KR-SunHiNeural",["lo-LA"]:"lo-LA-ChanthavongNeural",["lt-LT"]:"lt-LT-LeonasNeural",["lv-LV"]:"lv-LV-EveritaNeural",["mk-MK"]:"mk-MK-AleksandarNeural",["ml-IN"]:"ml-IN-MidhunNeural",["mr-IN"]:"mr-IN-AarohiNeural",["ms-MY"]:"ms-MY-OsmanNeural",["mt-MT"]:"mt-MT-GraceNeural",["my-MM"]:"my-MM-NilarNeural",["nb-NO"]:"nb-NO-PernilleNeural",["nl-BE"]:"nl-BE-ArnaudNeural",["nl-NL"]:"nl-NL-ColetteNeural",["pl-PL"]:"pl-PL-AgnieszkaNeural",["ps-AF"]:"ps-AF-GulNawazNeural",["pt-BR"]:"pt-BR-FranciscaNeural",["pt-PT"]:"pt-PT-DuarteNeural",["ro-RO"]:"ro-RO-AlinaNeural",["ru-RU"]:"ru-RU-SvetlanaNeural",["si-LK"]:"si-LK-SameeraNeural",["sk-SK"]:"sk-SK-LukasNeural",["sl-SI"]:"sl-SI-PetraNeural",["so-SO"]:"so-SO-MuuseNeural",["sr-RS"]:"sr-RS-NicholasNeural",["su-ID"]:"su-ID-JajangNeural",["sv-SE"]:"sv-SE-SofieNeural",["sw-KE"]:"sw-KE-RafikiNeural",["sw-TZ"]:"sw-TZ-DaudiNeural",["ta-IN"]:"ta-IN-PallaviNeural",["ta-LK"]:"ta-LK-KumarNeural",["ta-SG"]:"ta-SG-AnbuNeural",["te-IN"]:"te-IN-MohanNeural",["th-TH"]:"th-TH-PremwadeeNeural",["tr-TR"]:"tr-TR-AhmetNeural",["uk-UA"]:"uk-UA-OstapNeural",["ur-IN"]:"ur-IN-GulNeural",["ur-PK"]:"ur-PK-AsadNeural",["uz-UZ"]:"uz-UZ-MadinaNeural",["vi-VN"]:"vi-VN-HoaiMyNeural",["zh-CN"]:"zh-CN-XiaoxiaoNeural",["zh-HK"]:"zh-HK-HiuMaanNeural",["zh-TW"]:"zh-TW-HsiaoChenNeural",["zu-ZA"]:"zu-ZA-ThandoNeural"};let i=this.properties.getProperty(p.SpeechServiceConnection_SynthLanguage,"en-US"),n=this.properties.getProperty(p.SpeechServiceConnection_SynthVoice,""),s=De.XMLEncode(e);return this.autoDetectSourceLanguage?i="en-US":n=n||t[i],n&&(s=`<voice name='${n}'>${s}</voice>`),s=`<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='http://www.w3.org/2001/mstts' xmlns:emo='http://www.w3.org/2009/10/emotionml' xml:lang='${i}'>${s}</speak>`,s}speakTextAsync(e,t,i,n){this.speakImpl(e,!1,t,i,n)}speakSsmlAsync(e,t,i,n){this.speakImpl(e,!0,t,i,n)}getVoicesAsync(e=""){return Je(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){f.throwIfDisposed(this.privDisposed),Q(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return Je(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new zr(e,this.privProperties)}createSynthesisAdapter(e,t,i,n){return new se(e,t,n,this,this.audioConfig)}implCommonSynthesizeSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",i="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,i=navigator.appVersion);const n=this.createSynthesizerConfig(new et(new tt(new yi(e,t,i)))),s=this.privProperties.getProperty(p.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new $t(s):new ve(()=>{const a=this.privProperties.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)},()=>{const a=this.privProperties.getProperty(p.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)});this.privAdapter=this.createSynthesisAdapter(o,this.privConnectionFactory,this.audioConfig,n),this.privAdapter.audioOutputFormat=g.fromSpeechSynthesisOutputFormat(S[this.properties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new kr(n)}speakImpl(e,t,i,n,s){try{f.throwIfDisposed(this.privDisposed);const o=A();let a;s instanceof ii?a=new Tt(s):s instanceof Ve?a=s:s!==void 0?a=new Qt(s):a=void 0,this.synthesisRequestQueue.enqueue(new ur(o,e,t,u=>{if(this.privSynthesizing=!1,i)try{i(u)}catch(h){n&&n(h)}i=void 0,this.adapterSpeak().catch(()=>{})},u=>{n&&n(u)},a)),this.adapterSpeak().catch(()=>{})}catch(o){if(n)if(o instanceof Error){const a=o;n(a.name+": "+a.message)}else n(o);this.dispose(!0).catch(()=>{})}}getVoices(e){return Je(this,void 0,void 0,function*(){const t=A(),i=yield this.privRestAdapter.getVoicesList(t);if(i.ok&&Array.isArray(i.json)){let n=i.json;return!!e&&e.length>0&&(n=n.filter(s=>!!s.Locale&&s.Locale.toLowerCase()===e.toLowerCase())),new li(t,n,void 0)}else return new li(t,void 0,`Error: ${i.status}: ${i.statusText}`)})}adapterSpeak(){return Je(this,void 0,void 0,function*(){if(!this.privDisposed&&!this.privSynthesizing){this.privSynthesizing=!0;const e=yield this.synthesisRequestQueue.dequeue();return this.privAdapter.Speak(e.text,e.isSSML,e.requestId,e.cb,e.err,e.dataStream)}})}static XMLEncode(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}}class ur{constructor(e,t,i,n,s,o){this.requestId=e,this.text=t,this.isSSML=i,this.cb=n,this.err=s,this.dataStream=o}}class di{constructor(e,t,i,n){this.privResultId=e,this.privReason=t,this.privErrorDetails=i,this.privProperties=n}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}class Qe extends di{constructor(e,t,i,n,s,o){super(e,t,n,s),this.privAudioData=i,this.privAudioDuration=o}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}class Xe{constructor(e){this.privResult=e}get result(){return this.privResult}}class pr{constructor(e,t,i,n,s,o){this.privAudioOffset=e,this.privDuration=t,this.privText=i,this.privWordLength=n,this.privTextOffset=s,this.privBoundaryType=o}get audioOffset(){return this.privAudioOffset}get duration(){return this.privDuration}get text(){return this.privText}get wordLength(){return this.privWordLength}get textOffset(){return this.privTextOffset}get boundaryType(){return this.privBoundaryType}}class dr{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class lr{constructor(e,t,i){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=i}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}class li extends di{constructor(e,t,i){if(Array.isArray(t)){super(e,I.VoicesListRetrieved,void 0,new V),this.privVoices=[];for(const n of t)this.privVoices.push(new vr(n))}else super(e,I.Canceled,i||"Error information unavailable",new V)}get voices(){return this.privVoices}}var xe;(function(r){r[r.Unknown=0]="Unknown",r[r.Female=1]="Female",r[r.Male=2]="Male"})(xe||(xe={}));var Ze;(function(r){r[r.OnlineNeural=1]="OnlineNeural",r[r.OnlineStandard=2]="OnlineStandard",r[r.OfflineNeural=3]="OfflineNeural",r[r.OfflineStandard=4]="OfflineStandard"})(Ze||(Ze={}));class vr{constructor(e){if(this.privStyleList=[],this.privVoicePath="",e&&(this.privName=e.Name,this.privLocale=e.Locale,this.privShortName=e.ShortName,this.privLocalName=e.LocalName,this.privVoiceType=e.VoiceType.endsWith("Standard")?Ze.OnlineStandard:Ze.OnlineNeural,this.privGender=e.Gender==="Male"?xe.Male:e.Gender==="Female"?xe.Female:xe.Unknown,!!e.StyleList&&Array.isArray(e.StyleList)))for(const t of e.StyleList)this.privStyleList.push(t)}get name(){return this.privName}get locale(){return this.privLocale}get shortName(){return this.privShortName}get localName(){return this.privLocalName}get gender(){return this.privGender}get voiceType(){return this.privVoiceType}get styleList(){return this.privStyleList}get voicePath(){return this.privVoicePath}}var It=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};const fr=60*30,vi={[l.PCM]:"audio/wav",[l.MuLaw]:"audio/x-wav",[l.MP3]:"audio/mpeg",[l.OGG_OPUS]:"audio/ogg",[l.WEBM_OPUS]:"audio/webm; codecs=opus",[l.ALaw]:"audio/x-wav",[l.FLAC]:"audio/flac"};class Mt{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||A(),this.privIsPaused=!1,this.privIsClosed=!1}id(){return this.privId}write(e,t,i){this.privAudioBuffer!==void 0?(this.privAudioBuffer.push(e),this.updateSourceBuffer().then(()=>{t&&t()},n=>{i&&i(n)})):this.privAudioOutputStream!==void 0&&(this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength)}close(e,t){if(this.privIsClosed=!0,this.privSourceBuffer!==void 0)this.handleSourceBufferUpdateEnd().then(()=>{e&&e()},i=>{t&&t(i)});else if(this.privAudioOutputStream!==void 0&&typeof window!="undefined")if((this.privFormat.formatTag===l.PCM||this.privFormat.formatTag===l.MuLaw||this.privFormat.formatTag===l.ALaw)&&this.privFormat.hasHeader===!1)console.warn("Play back is not supported for raw PCM, mulaw or alaw format without header."),this.onAudioEnd&&this.onAudioEnd(this);else{let i=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(i).then(()=>{i=se.addHeader(i,this.privFormat);const n=new Blob([i],{type:vi[this.privFormat.formatTag]});this.privAudio.src=window.URL.createObjectURL(n),this.notifyPlayback().then(()=>{e&&e()},s=>{t&&t(s)})},n=>{t&&t(n)})}else this.onAudioEnd&&this.onAudioEnd(this)}set format(e){if(typeof AudioContext!="undefined"||typeof window!="undefined"&&typeof window.webkitAudioContext!="undefined"){this.privFormat=e;const t=vi[this.privFormat.formatTag];t===void 0?console.warn(`Unknown mimeType for format ${l[this.privFormat.formatTag]}; playback is not supported.`):typeof MediaSource!="undefined"&&MediaSource.isTypeSupported(t)?(this.privAudio=new Audio,this.privAudioBuffer=[],this.privMediaSource=new MediaSource,this.privAudio.src=URL.createObjectURL(this.privMediaSource),this.privAudio.load(),this.privMediaSource.onsourceopen=()=>{this.privMediaSourceOpened=!0,this.privMediaSource.duration=fr,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(i=>{O.instance.onEvent(new ke(i))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(i=>{O.instance.onEvent(new ke(i))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(i=>{O.instance.onEvent(new ke(i))})):(console.warn(`Format ${l[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new Et,this.privAudioOutputStream.format=this.privFormat,this.privAudio=new Audio)}}get volume(){var e,t;return(t=(e=this.privAudio)===null||e===void 0?void 0:e.volume)!==null&&t!==void 0?t:-1}set volume(e){this.privAudio&&(this.privAudio.volume=e)}mute(){this.privAudio&&(this.privAudio.muted=!0)}unmute(){this.privAudio&&(this.privAudio.muted=!1)}get isClosed(){return this.privIsClosed}get currentTime(){return this.privAudio!==void 0?this.privAudio.currentTime:-1}pause(){!this.privIsPaused&&this.privAudio!==void 0&&(this.privAudio.pause(),this.privIsPaused=!0)}resume(e,t){this.privIsPaused&&this.privAudio!==void 0&&(this.privAudio.play().then(()=>{e&&e()},i=>{t&&t(i)}),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}updateSourceBuffer(){return It(this,void 0,void 0,function*(){if(this.privAudioBuffer!==void 0&&this.privAudioBuffer.length>0&&this.sourceBufferAvailable()){this.privAppendingToBuffer=!0;const e=this.privAudioBuffer.shift();try{this.privSourceBuffer.appendBuffer(e)}catch{this.privAudioBuffer.unshift(e),console.log("buffer filled, pausing addition of binaries until space is made");return}yield this.notifyPlayback()}else this.canEndStream()&&(yield this.handleSourceBufferUpdateEnd())})}handleSourceBufferUpdateEnd(){return It(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return It(this,void 0,void 0,function*(){!this.privPlaybackStarted&&this.privAudio!==void 0&&(this.privPlaybackStarted=!0,this.onAudioStart&&this.onAudioStart(this),this.privAudio.onended=()=>{this.onAudioEnd&&this.onAudioEnd(this)},this.privIsPaused||(yield this.privAudio.play()))})}canEndStream(){return this.isClosed&&this.privSourceBuffer!==void 0&&this.privAudioBuffer.length===0&&this.privMediaSourceOpened&&!this.privAppendingToBuffer&&this.privMediaSource.readyState==="open"}sourceBufferAvailable(){return this.privSourceBuffer!==void 0&&!this.privSourceBuffer.updating}}class Ye extends ce{constructor(e,t,i,n=C.Info){super(e,n),this.privRequestId=t,this.privSessionId=i}get requestId(){return this.privRequestId}get sessionId(){return this.privSessionId}}class fi extends Ye{constructor(e,t,i,n){super("RecognitionTriggeredEvent",e,t),this.privAudioSourceId=i,this.privAudioNodeId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}}class gr extends Ye{constructor(e,t,i,n){super("ListeningStartedEvent",e,t),this.privAudioSourceId=i,this.privAudioNodeId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}}class gi extends Ye{constructor(e,t,i){super("ConnectingToServiceEvent",e,i),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}}class Sr extends Ye{constructor(e,t,i,n,s){super("RecognitionStartedEvent",e,s),this.privAudioSourceId=t,this.privAudioNodeId=i,this.privAuthFetchEventId=n}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}get authFetchEventId(){return this.privAuthFetchEventId}}var Si;(function(r){r[r.Success=0]="Success",r[r.AudioSourceError=1]="AudioSourceError",r[r.AudioSourceTimeout=2]="AudioSourceTimeout",r[r.AuthTokenFetchError=3]="AuthTokenFetchError",r[r.AuthTokenFetchTimeout=4]="AuthTokenFetchTimeout",r[r.UnAuthorized=5]="UnAuthorized",r[r.ConnectTimeout=6]="ConnectTimeout",r[r.ConnectError=7]="ConnectError",r[r.ClientRecognitionActivityTimeout=8]="ClientRecognitionActivityTimeout",r[r.UnknownError=9]="UnknownError"})(Si||(Si={}));class H extends gt{constructor(e,t,i,n,s,o,a,u){if(!t)throw new z("path");if(!i)throw new z("requestId");const h={};if(h[R.Path]=t,h[R.RequestId]=i,h[R.RequestTimestamp]=new Date().toISOString(),n&&(h[R.ContentType]=n),o&&(h[R.RequestStreamId]=o),a)for(const c in a)c&&(h[c]=a[c]);u?super(e,s,h,u):super(e,s,h),this.privPath=t,this.privRequestId=i,this.privContentType=n,this.privStreamId=o,this.privAdditionalHeaders=a}get path(){return this.privPath}get requestId(){return this.privRequestId}get contentType(){return this.privContentType}get streamId(){return this.privStreamId}get additionalHeaders(){return this.privAdditionalHeaders}static fromConnectionMessage(e){let t=null,i=null,n=null,s=null;const o={};if(e.headers)for(const a in e.headers)a&&(a.toLowerCase()===R.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===R.RequestId.toLowerCase()?i=e.headers[a]:a.toLowerCase()===R.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===R.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new H(e.messageType,t,i,n,e.body,s,o,e.id)}}var N=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class ${constructor(e,t,i,n,s){if(this.privConnectionConfigurationPromise=void 0,this.privConnectionPromise=void 0,this.privSetTimeout=setTimeout,this.privIsLiveAudio=!1,this.recognizeOverride=void 0,this.disconnectOverride=void 0,this.receiveMessageOverride=void 0,this.sendPrePayloadJSONOverride=void 0,this.postConnectImplOverride=void 0,this.configConnectionOverride=void 0,!e)throw new z("authentication");if(!t)throw new z("connectionFactory");if(!i)throw new z("audioSource");if(!n)throw new z("recognizerConfig");this.privMustReportEndOfStream=!1,this.privAuthentication=e,this.privConnectionFactory=t,this.privAudioSource=i,this.privRecognizerConfig=n,this.privIsDisposed=!1,this.privRecognizer=s,this.privRequestSession=new br(this.privAudioSource.id()),this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privDynamicGrammar=new Ar,this.privSpeechContext=new Rr(this.privDynamicGrammar),this.privAgentConfig=new Ti,typeof Blob!="undefined"&&typeof Worker!="undefined"&&(this.privSetTimeout=B.setTimeout),this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;(a.statusCode===1003||a.statusCode===1007||a.statusCode===1002||a.statusCode===4e3||this.privRequestSession.numConnectionAttempts>this.privRecognizerConfig.maxRetryCount)&&this.cancelRecognitionLocal(q.Error,a.statusCode===1007?P.BadRequestParameters:P.ConnectionFailure,`${a.reason} websocket error code: ${a.statusCode}`)}})}get audioSource(){return this.privAudioSource}get speechContext(){return this.privSpeechContext}get dynamicGrammar(){return this.privDynamicGrammar}get agentConfig(){return this.privAgentConfig}set conversationTranslatorToken(e){this.privRecognizerConfig.parameters.setProperty(p.ConversationTranslator_Token,e)}set authentication(e){this.privAuthentication=this.authentication}isDisposed(){return this.privIsDisposed}dispose(e){return N(this,void 0,void 0,function*(){if(this.privIsDisposed=!0,this.privConnectionConfigurationPromise!==void 0)try{yield(yield this.privConnectionConfigurationPromise).dispose(e)}catch{return}})}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}get recognitionMode(){return this.privRecognizerConfig.recognitionMode}recognize(e,t,i){return N(this,void 0,void 0,function*(){if(this.recognizeOverride!==void 0){yield this.recognizeOverride(e,t,i);return}this.privConnectionConfigurationPromise=void 0,this.privRecognizerConfig.recognitionMode=e,this.privSuccessCallback=t,this.privErrorCallback=i,this.privRequestSession.startNewRecognition(),this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events);const n=this.connectImpl();let s;try{const u=yield this.audioSource.attach(this.privRequestSession.audioNodeId),h=yield this.audioSource.format,c=yield this.audioSource.deviceInfo;this.privIsLiveAudio=c.type&&c.type===pe.Microphones,s=new Br(u,h.avgBytesPerSec),yield this.privRequestSession.onAudioSourceAttachCompleted(s,!1),this.privRecognizerConfig.SpeechServiceConfig.Context.audio={source:c}}catch(u){throw yield this.privRequestSession.onStopRecognizing(),u}try{yield n}catch(u){yield this.cancelRecognitionLocal(q.Error,P.ConnectionFailure,u);return}const o=new Se(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,o),this.receiveMessage(),this.sendAudio(s).catch(u=>N(this,void 0,void 0,function*(){yield this.cancelRecognitionLocal(q.Error,P.RuntimeError,u)}))})}stopRecognizing(){return N(this,void 0,void 0,function*(){if(this.privRequestSession.isRecognizing)try{yield this.audioSource.turnOff(),yield this.sendFinalAudio(),yield this.privRequestSession.onStopRecognizing(),yield this.privRequestSession.turnCompletionPromise}finally{yield this.privRequestSession.dispose()}})}connect(){return N(this,void 0,void 0,function*(){return yield this.connectImpl(),Promise.resolve()})}connectAsync(e,t){this.connectImpl().then(()=>{try{e&&e()}catch(i){t&&t(i)}},i=>{try{t&&t(i)}catch{}})}disconnect(){return N(this,void 0,void 0,function*(){if(yield this.cancelRecognitionLocal(q.Error,P.NoError,"Disconnecting"),this.disconnectOverride!==void 0&&(yield this.disconnectOverride()),this.privConnectionPromise!==void 0)try{yield(yield this.privConnectionPromise).dispose()}catch{}this.privConnectionPromise=void 0})}sendMessage(e){}sendNetworkMessage(e,t){return N(this,void 0,void 0,function*(){const i=typeof t=="string"?y.Text:y.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new H(i,e,this.privRequestSession.requestId,n,t))})}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}sendTelemetryData(){return N(this,void 0,void 0,function*(){const e=this.privRequestSession.getTelemetry();if($.telemetryDataEnabled!==!0||this.privIsDisposed||e===null)return;if($.telemetryData)try{$.telemetryData(e)}catch{}yield(yield this.fetchConnection()).send(new H(y.Text,"telemetry",this.privRequestSession.requestId,"application/json",e))})}cancelRecognitionLocal(e,t,i){return N(this,void 0,void 0,function*(){this.privRequestSession.isRecognizing&&(yield this.privRequestSession.onStopRecognizing(),this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,e,t,i))})}receiveMessage(){return N(this,void 0,void 0,function*(){try{if(this.privIsDisposed)return;let e=yield this.fetchConnection();const t=yield e.read();if(this.receiveMessageOverride!==void 0)return this.receiveMessageOverride();if(!t)return this.privRequestSession.isRecognizing?this.receiveMessage():void 0;this.privServiceHasSentMessage=!0;const i=H.fromConnectionMessage(t);if(i.requestId.toLowerCase()===this.privRequestSession.requestId.toLowerCase())switch(i.path.toLowerCase()){case"turn.start":this.privMustReportEndOfStream=!0,this.privRequestSession.onServiceTurnStartResponse();break;case"speech.startdetected":const n=rt.fromJSON(i.textBody),s=new bt(n.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechStartDetected&&this.privRecognizer.speechStartDetected(this.privRecognizer,s);break;case"speech.enddetected":let o;i.textBody.length>0?o=i.textBody:o="{ Offset: 0 }";const a=rt.fromJSON(o);this.privRecognizerConfig.isContinuousRecognition&&this.privRequestSession.onServiceRecognized(a.Offset+this.privRequestSession.currentTurnAudioOffset);const u=new bt(a.Offset+this.privRequestSession.currentTurnAudioOffset,this.privRequestSession.sessionId);this.privRecognizer.speechEndDetected&&this.privRecognizer.speechEndDetected(this.privRecognizer,u);break;case"turn.end":yield this.sendTelemetryData(),this.privRequestSession.isSpeechEnded&&this.privMustReportEndOfStream&&(this.privMustReportEndOfStream=!1,yield this.cancelRecognitionLocal(q.EndOfStream,P.NoError,void 0));const h=new Se(this.privRequestSession.sessionId);if(yield this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition),!this.privRecognizerConfig.isContinuousRecognition||this.privRequestSession.isSpeechEnded||!this.privRequestSession.isRecognizing){this.privRecognizer.sessionStopped&&this.privRecognizer.sessionStopped(this.privRecognizer,h);return}else e=yield this.fetchConnection(),yield this.sendPrePayloadJSON(e);break;default:(yield this.processTypeSpecificMessages(i))||this.privServiceEvents&&this.serviceEvents.onEvent(new qt(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{return null}})}sendSpeechContext(e,t){const i=this.speechContext.toJSON();if(t&&this.privRequestSession.onSpeechContext(),i)return e.send(new H(y.Text,"speech.context",this.privRequestSession.requestId,"application/json",i))}sendPrePayloadJSON(e,t=!0){return N(this,void 0,void 0,function*(){if(this.sendPrePayloadJSONOverride!==void 0)return this.sendPrePayloadJSONOverride(e);yield this.sendSpeechContext(e,t),yield this.sendWaveHeader(e)})}sendWaveHeader(e){return N(this,void 0,void 0,function*(){const t=yield this.audioSource.format;return e.send(new H(y.Binary,"audio",this.privRequestSession.requestId,"audio/x-wav",t.header))})}connectImpl(){return this.privConnectionPromise!==void 0?this.privConnectionPromise.then(e=>e.state()===D.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=void 0,this.privServiceHasSentMessage=!1,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=void 0,this.privServiceHasSentMessage=!1,this.connectImpl())):(this.privConnectionPromise=this.retryableConnect(),this.privConnectionPromise.catch(()=>{}),this.postConnectImplOverride!==void 0?this.postConnectImplOverride(this.privConnectionPromise):this.privConnectionPromise)}sendSpeechServiceConfig(e,t,i){if(t.onSpeechContext(),$.telemetryDataEnabled!==!0){const s={context:{system:JSON.parse(i).context.system}};i=JSON.stringify(s)}if(this.privRecognizerConfig.parameters.getProperty("TranscriptionService_SingleChannel","false").toLowerCase()==="true"){const n=JSON.parse(i);n.context.DisableReferenceChannel="True",n.context.MicSpec="1_0_0",i=JSON.stringify(n)}if(i)return e.send(new H(y.Text,"speech.config",t.requestId,"application/json",i))}fetchConnection(){return N(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===D.Disconnected?(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.privServiceHasSentMessage=!1,this.fetchConnection()):this.privConnectionConfigurationPromise,()=>(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.privServiceHasSentMessage=!1,this.fetchConnection())):(this.privConnectionConfigurationPromise=this.configureConnection(),yield this.privConnectionConfigurationPromise)})}sendAudio(e){return N(this,void 0,void 0,function*(){const t=yield this.audioSource.format;let i=Date.now();const n=this.privRecognizerConfig.parameters.getProperty("SPEECH-TransmitLengthBeforThrottleMs","5000"),s=t.avgBytesPerSec/1e3*parseInt(n,10),o=this.privRequestSession.recogNumber,a=()=>N(this,void 0,void 0,function*(){if(!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===o){const u=yield this.fetchConnection(),h=yield e.read();if(this.privRequestSession.isSpeechEnded)return;let c,d;if(!h||h.isEnd?(c=null,d=0):(c=h.buffer,this.privRequestSession.onAudioSent(c.byteLength),s>=this.privRequestSession.bytesSent?d=0:d=Math.max(0,i-Date.now())),d!==0&&(yield this.delay(d)),c!==null&&(i=Date.now()+c.byteLength*1e3/(t.avgBytesPerSec*2)),!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===o)if(u.send(new H(y.Binary,"audio",this.privRequestSession.requestId,null,c)).catch(()=>{this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch(()=>{})}),h!=null&&h.isEnd)this.privIsLiveAudio||this.privRequestSession.onSpeechEnded();else return a()}});return a()})}retryableConnect(){return N(this,void 0,void 0,function*(){let e=!1;this.privAuthFetchEventId=A();const t=this.privRequestSession.sessionId;this.privConnectionId=t!==void 0?t:A(),this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId,this.privConnectionId);let i=0,n="";for(;this.privRequestSession.numConnectionAttempts<=this.privRecognizerConfig.maxRetryCount;){const o=yield e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);yield this.privRequestSession.onAuthCompleted(!1);const a=this.privConnectionFactory.create(this.privRecognizerConfig,o,this.privConnectionId);this.privRequestSession.listenForServiceTelemetry(a.events),a.events.attach(h=>{this.connectionEvents.onEvent(h)});const u=yield a.open();if(u.statusCode===200)return yield this.privRequestSession.onConnectionEstablishCompleted(u.statusCode),Promise.resolve(a);u.statusCode===1006&&(e=!0),i=u.statusCode,n=u.reason,this.privRequestSession.onRetryConnection()}return yield this.privRequestSession.onConnectionEstablishCompleted(i,n),Promise.reject(`Unable to contact server. StatusCode: ${i}, ${this.privRecognizerConfig.parameters.getProperty(p.SpeechServiceConnection_Endpoint)} Reason: ${n}`)})}delay(e){return new Promise(t=>this.privSetTimeout(t,e))}writeBufferToConsole(e){let t="Buffer Size: ";if(e===null)t+="null";else{const i=new Uint8Array(e);t+=`${e.byteLength}\r
|
|
3
|
-
`;for(let n=0;n<e.byteLength;n++)t+=i[n].toString(16).padStart(2,"0")+" "}console.info(t)}sendFinalAudio(){return N(this,void 0,void 0,function*(){yield(yield this.fetchConnection()).send(new H(y.Binary,"audio",this.privRequestSession.requestId,null,null))})}configureConnection(){return N(this,void 0,void 0,function*(){const e=yield this.connectImpl();return this.configConnectionOverride!==void 0?this.configConnectionOverride(e):(yield this.sendSpeechServiceConfig(e,this.privRequestSession,this.privRecognizerConfig.SpeechServiceConfig.serialize()),yield this.sendPrePayloadJSON(e,!1),e)})}}$.telemetryDataEnabled=!0;var ue;(function(r){r[r.Interactive=0]="Interactive",r[r.Conversation=1]="Conversation",r[r.Dictation=2]="Dictation"})(ue||(ue={}));var mi;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(mi||(mi={}));class mr{constructor(e,t){this.privSpeechServiceConfig=e||new et(new tt(null)),this.privParameters=t,this.privMaxRetryCount=parseInt(t.getProperty("SPEECH-Error-MaxRetryCount","4"),10),this.privLanguageIdPriority=t.getProperty(p.SpeechServiceConnection_ContinuousLanguageIdPriority,void 0),this.privLanguageIdMode=this.privLanguageIdPriority==="Latency"?"DetectContinuous":"DetectAtAudioStart",this.privLanguageIdMode==="DetectAtAudioStart"&&(this.privLanguageIdPriority=t.getProperty(p.SpeechServiceConnection_AtStartLanguageIdPriority,void 0))}get parameters(){return this.privParameters}get recognitionMode(){return this.privRecognitionMode}set recognitionMode(e){this.privRecognitionMode=e,this.privRecognitionActivityTimeout=e===ue.Interactive?8e3:25e3,this.privSpeechServiceConfig.Recognition=ue[e]}get SpeechServiceConfig(){return this.privSpeechServiceConfig}get recognitionActivityTimeout(){return this.privRecognitionActivityTimeout}get isContinuousRecognition(){return this.privRecognitionMode!==ue.Interactive}get languageIdPriority(){return this.privLanguageIdPriority?`Prioritize${this.privLanguageIdPriority}`:""}get languageIdMode(){return this.privLanguageIdMode}get autoDetectSourceLanguages(){return this.parameters.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)}get recognitionEndpointVersion(){return this.parameters.getProperty(p.SpeechServiceConnection_RecognitionEndpointVersion,void 0)}get sourceLanguageModels(){const e=[];let t=!1;if(this.autoDetectSourceLanguages!==void 0)for(const i of this.autoDetectSourceLanguages.split(",")){const n=i+p.SpeechServiceConnection_EndpointId.toString(),s=this.parameters.getProperty(n,void 0);s!==void 0?(e.push({language:i,endpoint:s}),t=!0):e.push({language:i,endpoint:""})}return t?e:void 0}get maxRetryCount(){return this.privMaxRetryCount}}class et{constructor(e){this.context=e}serialize(){return JSON.stringify(this,(e,t)=>{if(t&&typeof t=="object"){const i={};for(const n in t)Object.hasOwnProperty.call(t,n)&&(i[n&&n.charAt(0).toLowerCase()+n.substring(1)]=t[n]);return i}return t})}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}}class tt{constructor(e){this.system=new yr,this.os=e}}class yr{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class yi{constructor(e,t,i){this.platform=e,this.name=t,this.version=i}}var ye;(function(r){r.Bluetooth="Bluetooth",r.Wired="Wired",r.WiFi="WiFi",r.Cellular="Cellular",r.InBuilt="InBuilt",r.Unknown="Unknown"})(ye||(ye={}));var pe;(function(r){r.Phone="Phone",r.Speaker="Speaker",r.Car="Car",r.Headset="Headset",r.Thermostat="Thermostat",r.Microphones="Microphones",r.Deskphone="Deskphone",r.RemoteControl="RemoteControl",r.Unknown="Unknown",r.File="File",r.Stream="Stream"})(pe||(pe={}));const wi=`\r
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
`);o&&o.length>0&&(n=this.parseHeaders(o[0]),o.length>1&&(s=o[1]))}t.resolve(new gt(e.messageType,s,n,e.id))}else if(e.messageType===y.Binary){const i=e.binaryContent;let n={},s=null;if(!i||i.byteLength<2)throw new Error("Invalid binary message format. Header length missing.");const o=new DataView(i),a=o.getInt16(0);if(i.byteLength<a+2)throw new Error("Invalid binary message format. Header content missing.");let u="";for(let h=0;h<a;h++)u+=String.fromCharCode(o.getInt8(h+2));n=this.parseHeaders(u),i.byteLength>a+2&&(s=i.slice(2+a)),t.resolve(new gt(e.messageType,s,n,e.id))}}catch(i){t.reject(`Error formatting the message. Error: ${i}`)}return t.promise}fromConnectionMessage(e){const t=new x;try{if(e.messageType===y.Text){const i=`${this.makeHeaders(e)}${wi}${e.textBody?e.textBody:""}`;t.resolve(new Ue(y.Text,i,e.id))}else if(e.messageType===y.Binary){const i=this.makeHeaders(e),n=e.binaryBody,s=this.stringToArrayBuffer(i),o=new Int8Array(s),a=o.byteLength,u=new Int8Array(2+a+(n?n.byteLength:0));if(u[0]=a>>8&255,u[1]=a&255,u.set(o,2),n){const c=new Int8Array(n);u.set(c,2+a)}const h=u.buffer;t.resolve(new Ue(y.Binary,h,e.id))}}catch(i){t.reject(`Error formatting the message. ${i}`)}return t.promise}makeHeaders(e){let t="";if(e.headers)for(const i in e.headers)i&&(t+=`${i}: ${e.headers[i]}${wi}`);return t}parseHeaders(e){const t={};if(e){const i=e.match(/[^\r\n]+/g);if(t){for(const n of i)if(n){const s=n.indexOf(":"),o=s>0?n.substr(0,s).trim().toLowerCase():n,a=s>0&&n.length>s+1?n.substr(s+1).trim():"";t[o]=a}}}return t}stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),i=new DataView(t);for(let n=0;n<e.length;n++)i.setUint8(n,e.charCodeAt(n));return t}}class wr extends Ge{create(e,t,i){let n=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!n){const c=e.parameters.getProperty(p.SpeechServiceConnection_Region,void 0),d=Ge.getHostSuffix(c);n=e.parameters.getProperty(p.SpeechServiceConnection_Host,"wss://"+c+".s2s.speech"+d)+"/speech/translation/cognitiveservices/v1"}const s={from:e.parameters.getProperty(p.SpeechServiceConnection_RecoLanguage),to:e.parameters.getProperty(p.SpeechServiceConnection_TranslationToLanguages)};this.setCommonUrlParams(e,s,n),this.setUrlParameter(p.SpeechServiceResponse_TranslationRequestStablePartialResult,E.StableTranslation,e,s,n);const o="voice",a="features";e.parameters.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&(s[o]=e.parameters.getProperty(p.SpeechServiceConnection_TranslationVoice),s[a]="texttospeech");const u={};t.token!==void 0&&t.token!==""&&(u[t.headerName]=t.token),u[R.ConnectionId]=i,e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const h=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new Pi(n,s,u,new Ci,ct.fromRecognizerConfig(e),h,i)}}class Cr{constructor(){this.synthesisUri="/cognitiveservices/websocket/v1"}create(e,t,i){let n=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);const s=e.parameters.getProperty(p.SpeechServiceConnection_Region,void 0),o=Ge.getHostSuffix(s),a=e.parameters.getProperty(p.SpeechServiceConnection_EndpointId,void 0),u=a===void 0?"tts":"voice",h=e.parameters.getProperty(p.SpeechServiceConnection_Host,"wss://"+s+"."+u+".speech"+o),c={};n||(n=h+this.synthesisUri);const d={};t.token!==void 0&&t.token!==""&&(d[t.headerName]=t.token),d[R.ConnectionId]=i,a!==void 0&&(d[E.CustomVoiceDeploymentId]=a),e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const v=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new Pi(n,c,d,new Ci,ct.fromParameters(e.parameters),v,i)}}class it{static implTranslateRecognitionResult(e){let t=I.Canceled;switch(e){case b.Success:t=I.RecognizedSpeech;break;case b.NoMatch:case b.InitialSilenceTimeout:case b.BabbleTimeout:case b.EndOfDictation:t=I.NoMatch;break;case b.Error:case b.BadRequest:case b.Forbidden:default:t=I.Canceled;break}return t}static implTranslateCancelResult(e){let t=q.EndOfStream;switch(e){case b.Success:case b.EndOfDictation:case b.NoMatch:t=q.EndOfStream;break;case b.InitialSilenceTimeout:case b.BabbleTimeout:case b.Error:case b.BadRequest:case b.Forbidden:default:t=q.Error;break}return t}static implTranslateCancelErrorCode(e){let t=P.NoError;switch(e){case b.Error:t=P.ServiceError;break;case b.TooManyRequests:t=P.TooManyRequests;break;case b.BadRequest:t=P.BadRequestParameters;break;case b.Forbidden:t=P.Forbidden;break;default:t=P.NoError;break}return t}static implTranslateErrorDetails(e){let t="The speech service encountered an internal error and could not continue.";switch(e){case P.Forbidden:t="The recognizer is using a free subscription that ran out of quota.";break;case P.BadRequestParameters:t="Invalid parameter or unsupported audio format in the request.";break;case P.TooManyRequests:t="The number of parallel requests exceeded the number of allowed concurrent transcriptions.";break}return t}}var Ne;(function(r){r[r.Success=0]="Success",r[r.SynthesisEnd=1]="SynthesisEnd",r[r.Error=2]="Error"})(Ne||(Ne={}));var b;(function(r){r[r.Success=0]="Success",r[r.NoMatch=1]="NoMatch",r[r.InitialSilenceTimeout=2]="InitialSilenceTimeout",r[r.BabbleTimeout=3]="BabbleTimeout",r[r.Error=4]="Error",r[r.EndOfDictation=5]="EndOfDictation",r[r.TooManyRequests=6]="TooManyRequests",r[r.BadRequest=7]="BadRequest",r[r.Forbidden=8]="Forbidden"})(b||(b={}));class kt{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus=Ne[this.privSynthesisEnd.SynthesisStatus]}static fromJSON(e){return new kt(e)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}class zt{constructor(e){this.privTranslationHypothesis=JSON.parse(e),this.privTranslationHypothesis.Translation.TranslationStatus=Me[this.privTranslationHypothesis.Translation.TranslationStatus]}static fromJSON(e){return new zt(e)}get Duration(){return this.privTranslationHypothesis.Duration}get Offset(){return this.privTranslationHypothesis.Offset}get Text(){return this.privTranslationHypothesis.Text}get Translation(){return this.privTranslationHypothesis.Translation}}class we{constructor(e){this.privTranslationPhrase=e,this.privTranslationPhrase.RecognitionStatus=b[this.privTranslationPhrase.RecognitionStatus],this.privTranslationPhrase.Translation!==void 0&&(this.privTranslationPhrase.Translation.TranslationStatus=Me[this.privTranslationPhrase.Translation.TranslationStatus])}static fromJSON(e){return new we(JSON.parse(e))}static fromTranslationResponse(e){f.throwIfNullOrUndefined(e,"translationResponse");const t=e.SpeechPhrase;return e.SpeechPhrase=void 0,t.Translation=e,t.Text=t.DisplayText,new we(t)}get RecognitionStatus(){return this.privTranslationPhrase.RecognitionStatus}get Offset(){return this.privTranslationPhrase.Offset}get Duration(){return this.privTranslationPhrase.Duration}get Text(){return this.privTranslationPhrase.Text}get Translation(){return this.privTranslationPhrase.Translation}}var Ei=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Er extends ${constructor(e,t,i,n,s){super(e,t,i,n,s),this.privTranslationRecognizer=s,this.connectionEvents.attach(o=>{o.name==="ConnectionEstablishedEvent"?this.privTranslationRecognizer.onConnection():o.name==="ConnectionClosedEvent"&&this.privTranslationRecognizer.onDisconnection()})}processTypeSpecificMessages(e){return Ei(this,void 0,void 0,function*(){const t=new V;let i=!1;const n=s=>Ei(this,void 0,void 0,function*(){if(this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset+s.Offset+s.Duration),s.RecognitionStatus===b.Success){const o=this.fireEventForResult(s,t);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,o)}catch{}if(this.privSuccessCallback){try{this.privSuccessCallback(o.result)}catch(a){this.privErrorCallback&&this.privErrorCallback(a)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}else{const o=it.implTranslateRecognitionResult(s.RecognitionStatus),a=new Rt(void 0,this.privRequestSession.requestId,o,s.Text,s.Duration,this.privRequestSession.currentTurnAudioOffset+s.Offset,void 0,e.textBody,t);if(o===I.Canceled){const u=it.implTranslateCancelResult(s.RecognitionStatus),h=it.implTranslateCancelErrorCode(s.RecognitionStatus);yield this.cancelRecognitionLocal(u,h,it.implTranslateErrorDetails(h))}else{if(!(this.privRequestSession.isSpeechEnded&&o===I.NoMatch&&s.RecognitionStatus!==b.InitialSilenceTimeout)){const u=new ri(a,a.offset,this.privRequestSession.sessionId);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,u)}catch{}}if(this.privSuccessCallback){try{this.privSuccessCallback(a)}catch(u){this.privErrorCallback&&this.privErrorCallback(u)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}i=!0}});switch(e.messageType===y.Text&&t.setProperty(p.SpeechServiceResponse_JsonResult,e.textBody),e.path.toLowerCase()){case"translation.hypothesis":const s=this.fireEventForResult(zt.fromJSON(e.textBody),t);if(this.privRequestSession.onHypothesis(this.privRequestSession.currentTurnAudioOffset+s.offset),this.privTranslationRecognizer.recognizing)try{this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer,s)}catch{}i=!0;break;case"translation.response":const o=JSON.parse(e.textBody);o.SpeechPhrase&&(yield n(we.fromTranslationResponse(o)));break;case"translation.phrase":yield n(we.fromJSON(e.textBody));break;case"translation.synthesis":this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),i=!0;break;case"translation.synthesis.end":const a=kt.fromJSON(e.textBody);switch(a.SynthesisStatus){case Ne.Error:if(this.privTranslationRecognizer.synthesizing){const u=new si(I.Canceled,void 0),h=new ni(u,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,h)}catch{}}if(this.privTranslationRecognizer.canceled){const u=new hi(this.privRequestSession.sessionId,q.Error,a.FailureReason,P.ServiceError,null);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,u)}catch{}}break;case Ne.Success:this.sendSynthesisAudio(void 0,this.privRequestSession.sessionId);break}i=!0;break}return i})}cancelRecognition(e,t,i,n,s){const o=new V;if(o.setProperty(bi,P[n]),this.privTranslationRecognizer.canceled){const a=new hi(e,i,s,n,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,a)}catch{}}if(this.privSuccessCallback){const a=new Rt(void 0,t,I.Canceled,void 0,void 0,void 0,s,void 0,o);try{this.privSuccessCallback(a),this.privSuccessCallback=void 0}catch{}}}fireEventForResult(e,t){let i;if(e.Translation.Translations!==void 0){i=new cr;for(const u of e.Translation.Translations)i.set(u.Language,u.Text||u.DisplayText)}let n;e instanceof we?e.Translation.TranslationStatus===Me.Success?n=I.TranslatedSpeech:n=I.RecognizedSpeech:n=I.TranslatingSpeech;const s=e.Offset+this.privRequestSession.currentTurnAudioOffset,o=new Rt(i,this.privRequestSession.requestId,n,e.Text,e.Duration,s,e.Translation.FailureReason,JSON.stringify(e),t);return new ri(o,s,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){const i=e===void 0?I.SynthesizingAudioCompleted:I.SynthesizingAudio,n=new si(i,e),s=new ni(n,t);if(this.privTranslationRecognizer.synthesizing)try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,s)}catch{}}}class rt{constructor(e){this.privSpeechStartDetected=JSON.parse(e)}static fromJSON(e){return new rt(e)}get Offset(){return this.privSpeechStartDetected.Offset}}class Tr{constructor(e,t,i){this.privIsDisposed=!1,this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privRequestId=e,this.privAudioSourceId=t,this.privAudioNodeId=i,this.privReceivedMessages={},this.privPhraseLatencies=[],this.privHypothesisLatencies=[]}phraseReceived(e){e>0&&this.privPhraseLatencies.push(Date.now()-e)}hypothesisReceived(e){e>0&&this.privHypothesisLatencies.push(Date.now()-e)}onEvent(e){if(!this.privIsDisposed&&(e instanceof fi&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:"ListeningTrigger",Start:e.eventTime}),e instanceof Re&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof Ae&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof Ke&&e.audioSourceId===this.privAudioSourceId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof lt&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof J&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Name:"Microphone",Start:this.privMicStartTime})),e instanceof gi&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof Ut&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof Wt&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof _i&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Error:this.getConnectionError(e.statusCode),Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof vt&&e.connectionId===this.privConnectionId&&e.message&&e.message.headers&&e.message.headers.path)){this.privReceivedMessages[e.message.headers.path]||(this.privReceivedMessages[e.message.headers.path]=new Array);const t=50;this.privReceivedMessages[e.message.headers.path].length<t&&this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime)}}getTelemetry(){const e=new Array;this.privListeningTriggerMetric&&e.push(this.privListeningTriggerMetric),this.privMicMetric&&e.push(this.privMicMetric),this.privConnectionEstablishMetric&&e.push(this.privConnectionEstablishMetric),this.privPhraseLatencies.length>0&&e.push({PhraseLatencyMs:this.privPhraseLatencies}),this.privHypothesisLatencies.length>0&&e.push({FirstHypothesisLatencyMs:this.privHypothesisLatencies});const t={Metrics:e,ReceivedMessages:this.privReceivedMessages},i=JSON.stringify(t);return this.privReceivedMessages={},this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privPhraseLatencies=[],this.privHypothesisLatencies=[],i}get hasTelemetry(){return Object.keys(this.privReceivedMessages).length!==0||this.privListeningTriggerMetric!==null||this.privMicMetric!==null||this.privConnectionEstablishMetric!==null||this.privPhraseLatencies.length!==0||this.privHypothesisLatencies.length!==0}dispose(){this.privIsDisposed=!0}getConnectionError(e){switch(e){case 400:case 1002:case 1003:case 1005:case 1007:case 1008:case 1009:return"BadRequest";case 401:return"Unauthorized";case 403:return"Forbidden";case 503:case 1001:return"ServerUnavailable";case 500:case 1011:return"ServerError";case 408:case 504:return"Timeout";default:return"statuscode:"+e.toString()}}}var re=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class br{constructor(e){this.privIsDisposed=!1,this.privDetachables=new Array,this.privIsAudioNodeDetached=!1,this.privIsRecognizing=!1,this.privIsSpeechEnded=!1,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privHypothesisReceived=!1,this.privBytesSent=0,this.privRecogNumber=0,this.privInTurn=!1,this.privConnectionAttempts=0,this.privAudioSourceId=e,this.privRequestId=A(),this.privAudioNodeId=A(),this.privTurnDeferral=new x,this.privTurnDeferral.resolve()}get sessionId(){return this.privSessionId}get requestId(){return this.privRequestId}get audioNodeId(){return this.privAudioNodeId}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSpeechEnded(){return this.privIsSpeechEnded}get isRecognizing(){return this.privIsRecognizing}get currentTurnAudioOffset(){return this.privTurnStartAudioOffset}get recogNumber(){return this.privRecogNumber}get numConnectionAttempts(){return this.privConnectionAttempts}get bytesSent(){return this.privBytesSent}listenForServiceTelemetry(e){this.privServiceTelemetryListener&&this.privDetachables.push(e.attachListener(this.privServiceTelemetryListener))}startNewRecognition(){this.privIsSpeechEnded=!1,this.privIsRecognizing=!0,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privRecogNumber++,this.privServiceTelemetryListener=new Tr(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new fi(this.requestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}onAudioSourceAttachCompleted(e,t){return re(this,void 0,void 0,function*(){this.privAudioNode=e,this.privIsAudioNodeDetached=!1,t?yield this.onComplete():this.onEvent(new gr(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))})}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new gi(this.privRequestId,this.privAuthFetchEventId,this.privSessionId))}onAuthCompleted(e){return re(this,void 0,void 0,function*(){e&&(yield this.onComplete())})}onConnectionEstablishCompleted(e,t){return re(this,void 0,void 0,function*(){if(e===200){this.onEvent(new Sr(this.requestId,this.privAudioSourceId,this.privAudioNodeId,this.privAuthFetchEventId,this.privSessionId)),this.privAudioNode&&this.privAudioNode.replay(),this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privBytesSent=0;return}else e===403&&(yield this.onComplete())})}onServiceTurnEndResponse(e){return re(this,void 0,void 0,function*(){this.privTurnDeferral.resolve(),!e||this.isSpeechEnded?(yield this.onComplete(),this.privInTurn=!1):(this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privAudioNode.replay())})}onSpeechContext(){this.privRequestId=A()}onServiceTurnStartResponse(){!!this.privTurnDeferral&&!!this.privInTurn&&(this.privTurnDeferral.reject("Another turn started before current completed."),this.privTurnDeferral.promise.then().catch(()=>{})),this.privInTurn=!0,this.privTurnDeferral=new x}onHypothesis(e){this.privHypothesisReceived||(this.privHypothesisReceived=!0,this.privServiceTelemetryListener.hypothesisReceived(this.privAudioNode.findTimeAtOffset(e)))}onPhraseRecognized(e){this.privServiceTelemetryListener.phraseReceived(this.privAudioNode.findTimeAtOffset(e)),this.onServiceRecognized(e)}onServiceRecognized(e){this.privLastRecoOffset=e,this.privHypothesisReceived=!1,this.privAudioNode.shrinkBuffers(e),this.privConnectionAttempts=0}onAudioSent(e){this.privBytesSent+=e}onRetryConnection(){this.privConnectionAttempts++}dispose(){return re(this,void 0,void 0,function*(){if(!this.privIsDisposed){this.privIsDisposed=!0;for(const e of this.privDetachables)yield e.detach();this.privServiceTelemetryListener&&this.privServiceTelemetryListener.dispose(),this.privIsRecognizing=!1}})}getTelemetry(){return this.privServiceTelemetryListener.hasTelemetry?this.privServiceTelemetryListener.getTelemetry():null}onStopRecognizing(){return re(this,void 0,void 0,function*(){yield this.onComplete()})}onSpeechEnded(){this.privIsSpeechEnded=!0}onEvent(e){this.privServiceTelemetryListener&&this.privServiceTelemetryListener.onEvent(e),O.instance.onEvent(e)}onComplete(){return re(this,void 0,void 0,function*(){this.privIsRecognizing&&(this.privIsRecognizing=!1,yield this.detachAudioNode())})}detachAudioNode(){return re(this,void 0,void 0,function*(){this.privIsAudioNodeDetached||(this.privIsAudioNodeDetached=!0,this.privAudioNode&&(yield this.privAudioNode.detach()))})}}class Rr{constructor(e){this.privContext={},this.privDynamicGrammar=e}setSection(e,t){this.privContext[e]=t}setPronunciationAssessmentParams(e){this.privContext.phraseDetection===void 0&&(this.privContext.phraseDetection={enrichment:{pronunciationAssessment:{}}}),this.privContext.phraseDetection.enrichment.pronunciationAssessment=JSON.parse(e),this.setWordLevelTimings(),this.privContext.phraseOutput.detailed.options.push("PronunciationAssessment"),this.privContext.phraseOutput.detailed.options.indexOf("SNR")===-1&&this.privContext.phraseOutput.detailed.options.push("SNR")}setWordLevelTimings(){this.privContext.phraseOutput===void 0&&(this.privContext.phraseOutput={detailed:{options:[]},format:{}}),this.privContext.phraseOutput.detailed===void 0&&(this.privContext.phraseOutput.detailed={options:[]}),this.privContext.phraseOutput.format="Detailed",this.privContext.phraseOutput.detailed.options.indexOf("WordTimings")===-1&&this.privContext.phraseOutput.detailed.options.push("WordTimings")}toJSON(){const e=this.privDynamicGrammar.generateGrammarObject();return this.setSection("dgi",e),JSON.stringify(this.privContext)}}class Ar{addPhrase(e){this.privPhrases||(this.privPhrases=[]),e instanceof Array?this.privPhrases=this.privPhrases.concat(e):this.privPhrases.push(e)}clearPhrases(){this.privPhrases=void 0}addReferenceGrammar(e){this.privGrammars||(this.privGrammars=[]),e instanceof Array?this.privGrammars=this.privGrammars.concat(e):this.privGrammars.push(e)}clearGrammars(){this.privGrammars=void 0}generateGrammarObject(){if(this.privGrammars===void 0&&this.privPhrases===void 0)return;const e={};if(e.ReferenceGrammars=this.privGrammars,this.privPhrases!==void 0&&this.privPhrases.length!==0){const t=[];this.privPhrases.forEach(i=>{t.push({Text:i})}),e.Groups=[{Type:"Generic",Items:t}]}return e}}class Ti{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class X{static get requestOptions(){return X.privDefaultRequestOptions}static get configParams(){return X.privDefaultParams}static get restErrors(){return X.privRestErrors}}X.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},X.privRestErrors={authInvalidSubscriptionKey:"You must specify either an authentication token to use, or a Cognitive Speech subscription key.",authInvalidSubscriptionRegion:"You must specify the Cognitive Speech region to use.",invalidArgs:"Required input not found: {arg}.",invalidCreateJoinConversationResponse:"Creating/Joining conversation failed with HTTP {status}.",invalidParticipantRequest:"The requested participant was not found.",permissionDeniedConnect:"Required credentials not found.",permissionDeniedConversation:"Invalid operation: only the host can {command} the conversation.",permissionDeniedParticipant:"Invalid operation: only the host can {command} a participant.",permissionDeniedSend:"Invalid operation: the conversation is not in a connected state.",permissionDeniedStart:"Invalid operation: there is already an active conversation."},X.privDefaultParams={apiVersion:"api-version",authorization:"Authorization",clientAppId:"X-ClientAppId",contentTypeKey:"Content-Type",correlationId:"X-CorrelationId",languageCode:"language",nickname:"nickname",profanity:"profanity",requestId:"X-RequestId",roomId:"roomid",sessionToken:"token",subscriptionKey:"Ocp-Apim-Subscription-Key",subscriptionRegion:"Ocp-Apim-Subscription-Region",token:"X-CapitoToken"};var Z;(function(r){r.WordBoundary="WordBoundary",r.Bookmark="Bookmark",r.Viseme="Viseme",r.SentenceBoundary="SentenceBoundary",r.SessionEnd="SessionEnd"})(Z||(Z={}));class Dt{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new Dt(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var ne=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class se{constructor(e,t,i,n,s){if(this.speakOverride=void 0,this.receiveMessageOverride=void 0,this.connectImplOverride=void 0,this.configConnectionOverride=void 0,this.privConnectionConfigurationPromise=void 0,!e)throw new z("authentication");if(!t)throw new z("connectionFactory");if(!i)throw new z("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=i,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new nt,this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privSynthesisContext=new Dr(this.privSpeechSynthesizer),this.privAgentConfig=new Ti,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(q.Error,a.statusCode===1007?P.BadRequestParameters:P.ConnectionFailure,`${a.reason} websocket error code: ${a.statusCode}`)}})}get synthesisContext(){return this.privSynthesisContext}get agentConfig(){return this.privAgentConfig}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}set audioOutputFormat(e){this.privAudioOutputFormat=e,this.privSynthesisTurn.audioOutputFormat=e,this.privSessionAudioDestination!==void 0&&(this.privSessionAudioDestination.format=e),this.synthesisContext!==void 0&&(this.synthesisContext.audioOutputFormat=e)}static addHeader(e,t){if(!t.hasHeader)return e;t.updateHeader(e.byteLength);const i=new Uint8Array(e.byteLength+t.header.byteLength);return i.set(new Uint8Array(t.header),0),i.set(new Uint8Array(e),t.header.byteLength),i.buffer}isDisposed(){return this.privIsDisposed}dispose(e){return ne(this,void 0,void 0,function*(){this.privIsDisposed=!0,this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.close(),this.privConnectionConfigurationPromise!==void 0&&(yield(yield this.privConnectionConfigurationPromise).dispose(e))})}connect(){return ne(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return ne(this,void 0,void 0,function*(){const i=typeof t=="string"?y.Text:y.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new H(i,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,i,n,s,o){return ne(this,void 0,void 0,function*(){let a;if(t?a=e:a=this.privSpeechSynthesizer.buildSsml(e),this.speakOverride!==void 0)return this.speakOverride(a,i,n,s);this.privSuccessCallback=n,this.privErrorCallback=s,this.privSynthesisTurn.startNewSynthesis(i,e,t,o);try{yield this.connectImpl();const u=yield this.fetchConnection();yield this.sendSynthesisContext(u),yield this.sendSsmlMessage(u,a,i);const h=new Xe(new Qe(i,I.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,h),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(q.Error,P.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,i,n){const s=new V;s.setProperty(bi,P[i]);const o=new Qe(e,I.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new Xe(o);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,a)}catch{}}if(this.privSuccessCallback)try{this.privSuccessCallback(o)}catch{}}cancelSynthesisLocal(e,t,i){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,i))}processTypeSpecificMessages(e){return!0}receiveMessage(){return ne(this,void 0,void 0,function*(){try{const t=yield(yield this.fetchConnection()).read();if(this.receiveMessageOverride!==void 0)return this.receiveMessageOverride();if(this.privIsDisposed)return;if(!t)return this.privSynthesisTurn.isSynthesizing?this.receiveMessage():void 0;const i=H.fromConnectionMessage(t);if(i.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(i.path.toLowerCase()){case"turn.start":this.privSynthesisTurn.onServiceTurnStartResponse();break;case"response":this.privSynthesisTurn.onServiceResponseMessage(i.textBody);break;case"audio":if(this.privSynthesisTurn.streamId.toLowerCase()===i.streamId.toLowerCase()&&!!i.binaryBody){if(this.privSynthesisTurn.onAudioChunkReceived(i.binaryBody),this.privSpeechSynthesizer.synthesizing)try{const o=se.addHeader(i.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new Xe(new Qe(this.privSynthesisTurn.requestId,I.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(i.binaryBody)}break;case"audio.metadata":const n=Dt.fromJSON(i.textBody).Metadata;for(const o of n)switch(o.Type){case Z.WordBoundary:case Z.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new pr(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===Z.WordBoundary?this.privSynthesisTurn.currentTextOffset:this.privSynthesisTurn.currentSentenceOffset,o.Data.text.BoundaryType);if(this.privSpeechSynthesizer.wordBoundary)try{this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer,a)}catch{}break;case Z.Bookmark:const u=new dr(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case Z.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const h=new lr(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,h)}catch{}}break;case Z.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Qe(this.privSynthesisTurn.requestId,I.SynthesizingAudioCompleted,o,void 0,void 0,this.privSynthesisTurn.audioDuration),this.privSuccessCallback&&this.privSuccessCallback(s)}catch(o){this.privErrorCallback&&this.privErrorCallback(o)}if(this.privSpeechSynthesizer.synthesisCompleted)try{this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer,new Xe(s))}catch{}break;default:this.processTypeSpecificMessages(i)||this.privServiceEvents&&this.serviceEvents.onEvent(new qt(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new H(y.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(i=>i.state()===D.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()));this.privAuthFetchEventId=A(),this.privConnectionId=A(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=t.then(i=>ne(this,void 0,void 0,function*(){this.privSynthesisTurn.onAuthCompleted(!1);const n=this.privConnectionFactory.create(this.privSynthesizerConfig,i,this.privConnectionId);n.events.attach(o=>{this.connectionEvents.onEvent(o)});const s=yield n.open();return s.statusCode===200?(this.privSynthesisTurn.onConnectionEstablishCompleted(s.statusCode),Promise.resolve(n)):s.statusCode===403&&!e?this.connectImpl(!0):(this.privSynthesisTurn.onConnectionEstablishCompleted(s.statusCode),Promise.reject(`Unable to contact server. StatusCode: ${s.statusCode}, ${this.privSynthesizerConfig.parameters.getProperty(p.SpeechServiceConnection_Endpoint)} Reason: ${s.reason}`))}),i=>{throw this.privSynthesisTurn.onAuthCompleted(!0),new Error(i)}),this.privConnectionPromise.catch(()=>{}),this.privConnectionPromise}sendSpeechServiceConfig(e,t){if(t)return e.send(new H(y.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,i){return e.send(new H(y.Text,"ssml",i,"application/ssml+xml",t))}fetchConnection(){return ne(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===D.Disconnected?(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.fetchConnection()):this.privConnectionConfigurationPromise,()=>(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.fetchConnection())):(this.privConnectionConfigurationPromise=this.configureConnection(),yield this.privConnectionConfigurationPromise)})}configureConnection(){return ne(this,void 0,void 0,function*(){const e=yield this.connectImpl();return this.configConnectionOverride!==void 0?this.configConnectionOverride(e):(yield this.sendSpeechServiceConfig(e,this.privSynthesizerConfig.SpeechServiceConfig.serialize()),e)})}}se.telemetryDataEnabled=!0;class xt extends ce{constructor(e,t,i=C.Info){super(e,i),this.privRequestId=t}get requestId(){return this.privRequestId}}class Pr extends xt{constructor(e,t,i){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=i}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class Ir extends xt{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class Mr extends xt{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var Nt=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class nt{constructor(){this.privIsDisposed=!1,this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!1,this.privBytesReceived=0,this.privInTurn=!1,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privRequestId=A(),this.privTurnDeferral=new x,this.privTurnDeferral.resolve()}get requestId(){return this.privRequestId}get streamId(){return this.privStreamId}set streamId(e){this.privStreamId=e}get audioOutputFormat(){return this.privAudioOutputFormat}set audioOutputFormat(e){this.privAudioOutputFormat=e}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSynthesisEnded(){return this.privIsSynthesisEnded}get isSynthesizing(){return this.privIsSynthesizing}get currentTextOffset(){return this.privTextOffset}get currentSentenceOffset(){return this.privSentenceOffset}get bytesReceived(){return this.privBytesReceived}get audioDuration(){return this.privAudioDuration}getAllReceivedAudio(){return Nt(this,void 0,void 0,function*(){return this.privReceivedAudio?Promise.resolve(this.privReceivedAudio):this.privIsSynthesisEnded?(yield this.readAllAudioFromStream(),Promise.resolve(this.privReceivedAudio)):null})}getAllReceivedAudioWithHeader(){return Nt(this,void 0,void 0,function*(){if(this.privReceivedAudioWithHeader)return this.privReceivedAudioWithHeader;if(!this.privIsSynthesisEnded)return null;if(this.audioOutputFormat.hasHeader){const e=yield this.getAllReceivedAudio();return this.privReceivedAudioWithHeader=se.addHeader(e,this.audioOutputFormat),this.privReceivedAudioWithHeader}else return this.getAllReceivedAudio()})}startNewSynthesis(e,t,i,n){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=i,this.privAudioOutputStream=new Et,this.privAudioOutputStream.format=this.privAudioOutputFormat,this.privReceivedAudio=null,this.privReceivedAudioWithHeader=null,this.privBytesReceived=0,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privPartialVisemeAnimation="",n!==void 0&&(this.privTurnAudioDestination=n,this.privTurnAudioDestination.format=this.privAudioOutputFormat),this.onEvent(new Pr(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new Ir(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new Mr(this.requestId,this.privAuthFetchEventId)),this.privBytesReceived=0;return}else e===403&&this.onComplete()}onServiceResponseMessage(e){const t=JSON.parse(e);this.streamId=t.audio.streamId}onServiceTurnEndResponse(){this.privInTurn=!1,this.privTurnDeferral.resolve(),this.onComplete()}onServiceTurnStartResponse(){!!this.privTurnDeferral&&!!this.privInTurn&&(this.privTurnDeferral.reject("Another turn started before current completed."),this.privTurnDeferral.promise.then().catch(()=>{})),this.privInTurn=!0,this.privTurnDeferral=new x}onAudioChunkReceived(e){this.isSynthesizing&&(this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength,this.privTurnAudioDestination!==void 0&&this.privTurnAudioDestination.write(e))}onTextBoundaryEvent(e){this.updateTextOffset(e.Data.text.Text,e.Type)}onVisemeMetadataReceived(e){e.Data.AnimationChunk!==void 0&&(this.privPartialVisemeAnimation+=e.Data.AnimationChunk)}onSessionEnd(e){this.privAudioDuration=e.Data.Offset}dispose(){this.privIsDisposed||(this.privIsDisposed=!0)}onStopSynthesizing(){this.onComplete()}getAndClearVisemeAnimation(){const e=this.privPartialVisemeAnimation;return this.privPartialVisemeAnimation="",e}onEvent(e){O.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===Z.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!nt.isXmlTag(e)&&this.updateTextOffset(e,t))):(this.privSentenceOffset=this.privRawText.indexOf(e,this.privNextSearchSentenceIndex),this.privSentenceOffset>=0&&(this.privNextSearchSentenceIndex=this.privSentenceOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privSentenceOffset)&&!nt.isXmlTag(e)&&this.updateTextOffset(e,t)))}onComplete(){this.privIsSynthesizing&&(this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!0,this.privAudioOutputStream.close(),this.privInTurn=!1,this.privTurnAudioDestination!==void 0&&(this.privTurnAudioDestination.close(),this.privTurnAudioDestination=void 0))}readAllAudioFromStream(){return Nt(this,void 0,void 0,function*(){if(this.privIsSynthesisEnded){this.privReceivedAudio=new ArrayBuffer(this.bytesReceived);try{yield this.privAudioOutputStream.read(this.privReceivedAudio)}catch{this.privReceivedAudio=new ArrayBuffer(0)}}})}withinXmlTag(e){return this.privRawText.indexOf("<",e+1)>this.privRawText.indexOf(">",e+1)}}class kr{constructor(e){let t=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(p.SpeechServiceConnection_Region,"westus"),s=Ge.getHostSuffix(n);t=e.parameters.getProperty(p.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const i=X.requestOptions;i.headers[X.configParams.subscriptionKey]=e.parameters.getProperty(p.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new Vr(i)}getVoicesList(e){return this.privRestAdapter.setHeaders(R.ConnectionId,e),this.privRestAdapter.request(de.Get,this.privUri)}}var Lt;(function(r){r[r.Standard=0]="Standard",r[r.Custom=1]="Custom"})(Lt||(Lt={}));class zr{constructor(e,t){this.privSynthesisServiceType=Lt.Standard,this.privSpeechServiceConfig=e||new et(new tt(null)),this.privParameters=t}get parameters(){return this.privParameters}get synthesisServiceType(){return this.privSynthesisServiceType}set synthesisServiceType(e){this.privSynthesisServiceType=e}get SpeechServiceConfig(){return this.privSpeechServiceConfig}}class Dr{constructor(e){this.privContext={},this.privSpeechSynthesizer=e}setSection(e,t){this.privContext[e]=t}set audioOutputFormat(e){this.privAudioOutputFormat=e}toJSON(){const e=this.buildSynthesisContext();return this.setSection("synthesis",e),JSON.stringify(this.privContext)}buildSynthesisContext(){return{audio:{metadataOptions:{bookmarkEnabled:!!this.privSpeechSynthesizer.bookmarkReached,punctuationBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestPunctuationBoundary,!!this.privSpeechSynthesizer.wordBoundary),sentenceBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!this.privSpeechSynthesizer.visemeReceived,wordBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(p.SpeechServiceResponse_RequestWordBoundary,!!this.privSpeechSynthesizer.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:this.privSpeechSynthesizer.autoDetectSourceLanguage}}}}const st="OutputFormat",bi="CancellationErrorCode",Le="ServiceProperties",Ri="ForceDictation",xr="OpenRange";var ot=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};const Nr="MICROPHONE-WorkletSourceUrl";class F{constructor(e,t,i,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=F.AUDIOFORMAT.avgBytesPerSec/10,this.privId=i||A(),this.privEvents=new j,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(F.AUDIOFORMAT)}get blob(){return Promise.reject("Not implemented for Mic input")}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new x;try{this.createAudioContext()}catch(i){if(i instanceof Error){const n=i;this.privInitializeDeferral.reject(n.name+": "+n.message)}else this.privInitializeDeferral.reject(i);return this.privInitializeDeferral.promise}const e=window.navigator;let t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(i,n,s)=>{e.mediaDevices.getUserMedia(i).then(n).catch(s)}),t){const i=()=>{this.onEvent(new He(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new be(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new be(this.privId)),this.privInitializeDeferral.resolve()},n=>{const s=`Error occurred during microphone initialization: ${n}`;this.privInitializeDeferral.reject(s),this.onEvent(new Ke(this.privId,s))})};this.privContext.state==="suspended"?this.privContext.resume().then(i).catch(n=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${n}`)}):i()}else{const i="Browser does not support getUserMedia.";this.privInitializeDeferral.reject(i),this.onEvent(new Ke(i,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new Re(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new Ae(this.privId,e)),{detach:()=>ot(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new J(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}))}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new J(this.privId,e)))}turnOff(){return ot(this,void 0,void 0,function*(){for(const e in this.privStreams)if(e){const t=this.privStreams[e];t&&t.close()}this.onEvent(new Kt(this.privId)),this.privInitializeDeferral&&(yield this.privInitializeDeferral,this.privInitializeDeferral=null),yield this.destroyAudioContext()})}get events(){return this.privEvents}get deviceInfo(){return this.getMicrophoneLabel().then(e=>({bitspersample:F.AUDIOFORMAT.bitsPerSample,channelcount:F.AUDIOFORMAT.channels,connectivity:ye.Unknown,manufacturer:"Speech SDK",model:e,samplerate:F.AUDIOFORMAT.samplesPerSec,type:pe.Microphones}))}setProperty(e,t){if(e===Nr)this.privRecorder.setWorkletUrl(t);else throw new Error("Property '"+e+"' is not supported on Microphone.")}getMicrophoneLabel(){const e="microphone";if(this.privMicrophoneLabel!==void 0)return Promise.resolve(this.privMicrophoneLabel);if(this.privMediaStream===void 0||!this.privMediaStream.active)return Promise.resolve(e);this.privMicrophoneLabel=e;const t=this.privMediaStream.getTracks()[0].getSettings().deviceId;if(t===void 0)return Promise.resolve(this.privMicrophoneLabel);const i=new x;return navigator.mediaDevices.enumerateDevices().then(n=>{for(const s of n)if(s.deviceId===t){this.privMicrophoneLabel=s.label;break}i.resolve(this.privMicrophoneLabel)},()=>i.resolve(this.privMicrophoneLabel)),i.promise}listen(e){return ot(this,void 0,void 0,function*(){yield this.turnOn();const t=new mt(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new lt(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),O.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=ee.getAudioContext(F.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return ot(this,void 0,void 0,function*(){if(!this.privContext)return;this.privRecorder.releaseMediaResources(this.privContext);let e=!1;"close"in this.privContext&&(e=!0),e?this.privIsClosing||(this.privIsClosing=!0,yield this.privContext.close(),this.privContext=null,this.privIsClosing=!1):this.privContext!==null&&this.privContext.state==="running"&&(yield this.privContext.suspend())})}}F.AUDIOFORMAT=We.getDefaultInputFormat();var Ot=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Lr{constructor(e,t,i){this.privStreams={},this.privHeaderEnd=44,this.privId=i||A(),this.privEvents=new j,this.privSource=e,typeof window!="undefined"&&typeof Blob!="undefined"&&this.privSource instanceof Blob?this.privFilename=e.name:this.privFilename=t||"unknown.wav",this.privAudioFormatPromise=this.readHeader()}get format(){return this.privAudioFormatPromise}get blob(){return Promise.resolve(this.privSource)}turnOn(){if(this.privFilename.lastIndexOf(".wav")!==this.privFilename.length-4){const e=this.privFilename+" is not supported. Only WAVE files are allowed at the moment.";return this.onEvent(new Ke(e,"")),Promise.reject(e)}this.onEvent(new He(this.privId)),this.onEvent(new be(this.privId))}id(){return this.privId}attach(e){return Ot(this,void 0,void 0,function*(){this.onEvent(new Re(this.privId,e));const t=yield this.upload(e);return this.onEvent(new Ae(this.privId,e)),Promise.resolve({detach:()=>Ot(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new J(this.privId,e)),yield this.turnOff()}),id:()=>e,read:()=>t.read()})})}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new J(this.privId,e)))}turnOff(){for(const e in this.privStreams)if(e){const t=this.privStreams[e];t&&!t.isClosed&&t.close()}return this.onEvent(new Kt(this.privId)),Promise.resolve()}get events(){return this.privEvents}get deviceInfo(){return this.privAudioFormatPromise.then(e=>Promise.resolve({bitspersample:e.bitsPerSample,channelcount:e.channels,connectivity:ye.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:pe.File}))}readHeader(){const t=this.privSource.slice(0,512),i=new x,n=s=>{const o=new DataView(s),a=w=>String.fromCharCode(o.getUint8(w),o.getUint8(w+1),o.getUint8(w+2),o.getUint8(w+3));if(a(0)!=="RIFF"){i.reject("Invalid WAV header in file, RIFF was not found");return}if(a(8)!=="WAVE"||a(12)!=="fmt "){i.reject("Invalid WAV header in file, WAVEfmt was not found");return}const u=o.getInt32(16,!0),h=o.getUint16(22,!0),c=o.getUint32(24,!0),d=o.getUint16(34,!0);let v=36+Math.max(u-16,0);for(;a(v)!=="data";v+=2)if(v>512-8){i.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=v+8,i.resolve(We.getWaveFormatPCM(c,d,h))};if(typeof window!="undefined"&&typeof Blob!="undefined"&&t instanceof Blob){const s=new FileReader;s.onload=o=>{const a=o.target.result;n(a)},s.readAsArrayBuffer(t)}else{const s=t;n(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength))}return i.promise}upload(e){return Ot(this,void 0,void 0,function*(){const t=i=>{const n=`Error occurred while processing '${this.privFilename}'. ${i}`;throw this.onEvent(new lt(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const i=yield this.privAudioFormatPromise,n=new mt(i.avgBytesPerSec/10,e);this.privStreams[e]=n;const s=this.privSource.slice(this.privHeaderEnd),o=a=>{n.isClosed||(n.writeStreamChunk({buffer:a,isEnd:!1,timeReceived:Date.now()}),n.close())};if(typeof window!="undefined"&&typeof Blob!="undefined"&&s instanceof Blob){const a=new FileReader;a.onerror=u=>t(u.toString()),a.onload=u=>{const h=u.target.result;o(h)},a.readAsArrayBuffer(s)}else{const a=s;o(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength))}return n}catch(i){t(i)}})}onEvent(e){this.privEvents.onEvent(e),O.instance.onEvent(e)}}class Bt{constructor(e){this.privStopInputOnRelease=e}record(e,t,i){const s=new Ki(e.sampleRate,16e3),o=e.createMediaStreamSource(t);if(!this.privSpeechProcessorScript){const u=`class SP extends AudioWorkletProcessor {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CreativeOrangeAzureTextToSpeech={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),n=48e4;function r(e){let t=typeof e.tokenEndpoint==`string`&&e.tokenEndpoint.trim()!==``,n=typeof e.getAuthorizationToken==`function`;if(t&&n)throw Error(`Provide either tokenEndpoint or getAuthorizationToken, not both.`);if(!t&&!n)throw Error(`A tokenEndpoint or getAuthorizationToken provider is required.`);if(n)return e.getAuthorizationToken;let r=e.tokenEndpoint.trim(),o=e.tokenRequestOptions??{};return async()=>{let e;try{e=await fetch(r,{method:`GET`,cache:o.cache??`no-store`,credentials:o.credentials??`same-origin`,headers:{Accept:`application/json`,...o.headers??{}}})}catch{throw a(`Could not reach the speech token endpoint.`,`TOKEN_ENDPOINT_UNREACHABLE`)}if(!e.ok)throw a(`Speech token endpoint returned HTTP ${e.status}.`,`TOKEN_ENDPOINT_HTTP_ERROR`);let t;try{t=await e.json()}catch{throw a(`Speech token endpoint returned invalid JSON.`,`TOKEN_ENDPOINT_INVALID_JSON`)}return i(t)}}function i(e){if(!e||typeof e!=`object`)throw a(`Speech authorization response must be an object.`,`TOKEN_INVALID_RESPONSE`);let t=e,n=typeof t.token==`string`?t.token.trim():``,r=typeof t.region==`string`?t.region.trim():``;if(n===``)throw a(`Speech authorization token is missing or empty.`,`TOKEN_EMPTY`);if(r===``)throw a(`Speech authorization region is missing or empty.`,`TOKEN_REGION_MISSING`);return{token:n,region:r}}function a(e,t){let n=Error(s(e));return n.message=s(e),t&&(n.code=t),n}function o(e){if(typeof e==`string`)return{message:e.trim()===``?`An unexpected speech error occurred.`:s(e)};if(e&&typeof e==`object`){let t=e,n=[typeof t.message==`string`?t.message:``,typeof t.errorDetails==`string`?t.errorDetails:``,typeof t.reason==`string`?t.reason:``].filter(e=>e.trim()!==``).join(` `),r={message:n===``?`An unexpected speech error occurred.`:s(n)};return typeof t.code==`string`&&t.code.trim()!==``?r.code=t.code:typeof t.code==`number`&&(r.code=String(t.code)),r}return{message:`An unexpected speech error occurred.`}}function s(e){return e.replace(/Authorization\s*:\s*Bearer\s+\S+/gi,`Authorization: Bearer [redacted]`).replace(/Bearer\s+\S+/gi,`Bearer [redacted]`).replace(/authorization[_-]?token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,`authorizationToken=[redacted]`).replace(/access[_-]?token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,`accessToken=[redacted]`).replace(/["']token["']\s*:\s*["'][^"']+["']/gi,`"token":"[redacted]"`).replace(/token["']?\s*[:=]\s*["']?[^"',\s}]+/gi,`token=[redacted]`)}function c(e){let t=o(e),n=`${t.message} ${t.code??``}`.toLowerCase();return n.includes(`unauthorized`)||n.includes(`authentication`)||n.includes(`authorization`)||n.includes(`invalid token`)||n.includes(`token expired`)||n.includes(`expired token`)||n.includes(`403`)||n.includes(`401`)||t.code===`TOKEN_REFRESH_ERROR`}var l=class{authorization;authorizationExpiresAt=0;authorizationRequest;provider;tokenLifetimeMs;constructor(e){this.provider=r(e),this.tokenLifetimeMs=e.tokenLifetimeMs&&e.tokenLifetimeMs>0?e.tokenLifetimeMs:n}getTokenLifetimeMs(){return this.tokenLifetimeMs}async getAuthorization(){return this.authorization&&Date.now()<this.authorizationExpiresAt?this.authorization:(this.authorizationRequest||=this.fetchAuthorization().then(e=>(this.authorization=e,this.authorizationExpiresAt=Date.now()+this.tokenLifetimeMs,e)).finally(()=>{this.authorizationRequest=void 0}),this.authorizationRequest)}async refreshAuthorization(){return this.authorization=void 0,this.authorizationExpiresAt=0,this.authorizationRequest?this.authorizationRequest:this.getAuthorization()}clearAuthorization(){this.authorization=void 0,this.authorizationExpiresAt=0}async fetchAuthorization(){try{return i(await this.provider())}catch(e){this.clearAuthorization();let t=o(e);throw a(t.message,t.code)}}},u=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=`ffffffff-ffff-ffff-ffff-ffffffffffff`})),d=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=`00000000-0000-0000-0000-000000000000`})),f=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i})),p=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=f();function n(e){return typeof e==`string`&&t.default.test(e)}e.default=n})),m=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=p();function n(e){if(!(0,t.default)(e))throw TypeError(`Invalid UUID`);let n;return Uint8Array.of((n=parseInt(e.slice(0,8),16))>>>24,n>>>16&255,n>>>8&255,n&255,(n=parseInt(e.slice(9,13),16))>>>8,n&255,(n=parseInt(e.slice(14,18),16))>>>8,n&255,(n=parseInt(e.slice(19,23),16))>>>8,n&255,(n=parseInt(e.slice(24,36),16))/1099511627776&255,n/4294967296&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255)}e.default=n})),h=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.unsafeStringify=void 0;var t=p(),n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));function r(e,t=0){return(n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+`-`+n[e[t+4]]+n[e[t+5]]+`-`+n[e[t+6]]+n[e[t+7]]+`-`+n[e[t+8]]+n[e[t+9]]+`-`+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]).toLowerCase()}e.unsafeStringify=r;function i(e,n=0){let i=r(e,n);if(!(0,t.default)(i))throw TypeError(`Stringified UUID is invalid`);return i}e.default=i})),g=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t,n=new Uint8Array(16);function r(){if(!t){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);t=crypto.getRandomValues.bind(crypto)}return t(n)}e.default=r})),_=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.updateV1State=void 0;var t=g(),n=h(),r={};function i(e,i,s){let c,l=e?._v6??!1;if(e){let t=Object.keys(e);t.length===1&&t[0]===`_v6`&&(e=void 0)}if(e)c=o(e.random??e.rng?.()??(0,t.default)(),e.msecs,e.nsecs,e.clockseq,e.node,i,s);else{let e=Date.now(),n=(0,t.default)();a(r,e,n),c=o(n,r.msecs,r.nsecs,l?void 0:r.clockseq,l?void 0:r.node,i,s)}return i??(0,n.unsafeStringify)(c)}function a(e,t,n){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=n.slice(10,16),e.node[0]|=1,e.clockseq=(n[8]<<8|n[9])&16383),e.msecs=t,e}e.updateV1State=a;function o(e,t,n,r,i,a,o=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!a)a=new Uint8Array(16),o=0;else if(o<0||o+16>a.length)throw RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);t??=Date.now(),n??=0,r??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=0xb1d069b5400;let s=((t&268435455)*1e4+n)%4294967296;a[o++]=s>>>24&255,a[o++]=s>>>16&255,a[o++]=s>>>8&255,a[o++]=s&255;let c=t/4294967296*1e4&268435455;a[o++]=c>>>8&255,a[o++]=c&255,a[o++]=c>>>24&15|16,a[o++]=c>>>16&255,a[o++]=r>>>8|128,a[o++]=r&255;for(let e=0;e<6;++e)a[o++]=i[e];return a}e.default=i})),v=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=m(),n=h();function r(e){let r=i(typeof e==`string`?(0,t.default)(e):e);return typeof e==`string`?(0,n.unsafeStringify)(r):r}e.default=r;function i(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}})),y=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return n(i(a(e),e.length*8))}function n(e){let t=new Uint8Array(e.length*4);for(let n=0;n<e.length*4;n++)t[n]=e[n>>2]>>>n%4*8&255;return t}function r(e){return(e+64>>>9<<4)+14+1}function i(e,t){let n=new Uint32Array(r(t)).fill(0);n.set(e),n[t>>5]|=128<<t%32,n[n.length-1]=t,e=n;let i=1732584193,a=-271733879,s=-1732584194,c=271733878;for(let t=0;t<e.length;t+=16){let n=i,r=a,p=s,m=c;i=l(i,a,s,c,e[t],7,-680876936),c=l(c,i,a,s,e[t+1],12,-389564586),s=l(s,c,i,a,e[t+2],17,606105819),a=l(a,s,c,i,e[t+3],22,-1044525330),i=l(i,a,s,c,e[t+4],7,-176418897),c=l(c,i,a,s,e[t+5],12,1200080426),s=l(s,c,i,a,e[t+6],17,-1473231341),a=l(a,s,c,i,e[t+7],22,-45705983),i=l(i,a,s,c,e[t+8],7,1770035416),c=l(c,i,a,s,e[t+9],12,-1958414417),s=l(s,c,i,a,e[t+10],17,-42063),a=l(a,s,c,i,e[t+11],22,-1990404162),i=l(i,a,s,c,e[t+12],7,1804603682),c=l(c,i,a,s,e[t+13],12,-40341101),s=l(s,c,i,a,e[t+14],17,-1502002290),a=l(a,s,c,i,e[t+15],22,1236535329),i=u(i,a,s,c,e[t+1],5,-165796510),c=u(c,i,a,s,e[t+6],9,-1069501632),s=u(s,c,i,a,e[t+11],14,643717713),a=u(a,s,c,i,e[t],20,-373897302),i=u(i,a,s,c,e[t+5],5,-701558691),c=u(c,i,a,s,e[t+10],9,38016083),s=u(s,c,i,a,e[t+15],14,-660478335),a=u(a,s,c,i,e[t+4],20,-405537848),i=u(i,a,s,c,e[t+9],5,568446438),c=u(c,i,a,s,e[t+14],9,-1019803690),s=u(s,c,i,a,e[t+3],14,-187363961),a=u(a,s,c,i,e[t+8],20,1163531501),i=u(i,a,s,c,e[t+13],5,-1444681467),c=u(c,i,a,s,e[t+2],9,-51403784),s=u(s,c,i,a,e[t+7],14,1735328473),a=u(a,s,c,i,e[t+12],20,-1926607734),i=d(i,a,s,c,e[t+5],4,-378558),c=d(c,i,a,s,e[t+8],11,-2022574463),s=d(s,c,i,a,e[t+11],16,1839030562),a=d(a,s,c,i,e[t+14],23,-35309556),i=d(i,a,s,c,e[t+1],4,-1530992060),c=d(c,i,a,s,e[t+4],11,1272893353),s=d(s,c,i,a,e[t+7],16,-155497632),a=d(a,s,c,i,e[t+10],23,-1094730640),i=d(i,a,s,c,e[t+13],4,681279174),c=d(c,i,a,s,e[t],11,-358537222),s=d(s,c,i,a,e[t+3],16,-722521979),a=d(a,s,c,i,e[t+6],23,76029189),i=d(i,a,s,c,e[t+9],4,-640364487),c=d(c,i,a,s,e[t+12],11,-421815835),s=d(s,c,i,a,e[t+15],16,530742520),a=d(a,s,c,i,e[t+2],23,-995338651),i=f(i,a,s,c,e[t],6,-198630844),c=f(c,i,a,s,e[t+7],10,1126891415),s=f(s,c,i,a,e[t+14],15,-1416354905),a=f(a,s,c,i,e[t+5],21,-57434055),i=f(i,a,s,c,e[t+12],6,1700485571),c=f(c,i,a,s,e[t+3],10,-1894986606),s=f(s,c,i,a,e[t+10],15,-1051523),a=f(a,s,c,i,e[t+1],21,-2054922799),i=f(i,a,s,c,e[t+8],6,1873313359),c=f(c,i,a,s,e[t+15],10,-30611744),s=f(s,c,i,a,e[t+6],15,-1560198380),a=f(a,s,c,i,e[t+13],21,1309151649),i=f(i,a,s,c,e[t+4],6,-145523070),c=f(c,i,a,s,e[t+11],10,-1120210379),s=f(s,c,i,a,e[t+2],15,718787259),a=f(a,s,c,i,e[t+9],21,-343485551),i=o(i,n),a=o(a,r),s=o(s,p),c=o(c,m)}return Uint32Array.of(i,a,s,c)}function a(e){if(e.length===0)return new Uint32Array;let t=new Uint32Array(r(e.length*8)).fill(0);for(let n=0;n<e.length;n++)t[n>>2]|=(e[n]&255)<<n%4*8;return t}function o(e,t){let n=(e&65535)+(t&65535);return(e>>16)+(t>>16)+(n>>16)<<16|n&65535}function s(e,t){return e<<t|e>>>32-t}function c(e,t,n,r,i,a){return o(s(o(o(t,e),o(r,a)),i),n)}function l(e,t,n,r,i,a,o){return c(t&n|~t&r,e,t,i,a,o)}function u(e,t,n,r,i,a,o){return c(t&r|n&~r,e,t,i,a,o)}function d(e,t,n,r,i,a,o){return c(t^n^r,e,t,i,a,o)}function f(e,t,n,r,i,a,o){return c(n^(t|~r),e,t,i,a,o)}e.default=t})),b=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=e.stringToBytes=void 0;var t=m(),n=h();function r(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}e.stringToBytes=r,e.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,e.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function i(e,i,a,o,s,c){let l=typeof a==`string`?r(a):a,u=typeof o==`string`?(0,t.default)(o):o;if(typeof o==`string`&&(o=(0,t.default)(o)),o?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let d=new Uint8Array(16+l.length);if(d.set(u),d.set(l,u.length),d=i(d),d[6]=d[6]&15|e,d[8]=d[8]&63|128,s){if(c||=0,c<0||c+16>s.length)throw RangeError(`UUID byte range ${c}:${c+15} is out of buffer bounds`);for(let e=0;e<16;++e)s[c+e]=d[e];return s}return(0,n.unsafeStringify)(d)}e.default=i})),x=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;var t=y(),n=b(),r=b();Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return r.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return r.URL}});function i(e,r,i,a){return(0,n.default)(48,t.default,e,r,i,a)}i.DNS=n.DNS,i.URL=n.URL,e.default=i})),S=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)}})),ee=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=S(),n=g(),r=h();function i(e,i,a){if(t.default.randomUUID&&!i&&!e)return t.default.randomUUID();e||={};let o=e.random??e.rng?.()??(0,n.default)();if(o.length<16)throw Error(`Random bytes length must be >= 16`);if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,i){if(a||=0,a<0||a+16>i.length)throw RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let e=0;e<16;++e)i[a+e]=o[e];return i}return(0,r.unsafeStringify)(o)}e.default=i})),te=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function n(e,t){return e<<t|e>>>32-t}function r(e){let r=[1518500249,1859775393,2400959708,3395469782],i=[1732584193,4023233417,2562383102,271733878,3285377520],a=new Uint8Array(e.length+1);a.set(e),a[e.length]=128,e=a;let o=e.length/4+2,s=Math.ceil(o/16),c=Array(s);for(let t=0;t<s;++t){let n=new Uint32Array(16);for(let r=0;r<16;++r)n[r]=e[t*64+r*4]<<24|e[t*64+r*4+1]<<16|e[t*64+r*4+2]<<8|e[t*64+r*4+3];c[t]=n}c[s-1][14]=(e.length-1)*8/2**32,c[s-1][14]=Math.floor(c[s-1][14]),c[s-1][15]=(e.length-1)*8&4294967295;for(let e=0;e<s;++e){let a=new Uint32Array(80);for(let t=0;t<16;++t)a[t]=c[e][t];for(let e=16;e<80;++e)a[e]=n(a[e-3]^a[e-8]^a[e-14]^a[e-16],1);let o=i[0],s=i[1],l=i[2],u=i[3],d=i[4];for(let e=0;e<80;++e){let i=Math.floor(e/20),c=n(o,5)+t(i,s,l,u)+d+r[i]+a[e]>>>0;d=u,u=l,l=n(s,30)>>>0,s=o,o=c}i[0]=i[0]+o>>>0,i[1]=i[1]+s>>>0,i[2]=i[2]+l>>>0,i[3]=i[3]+u>>>0,i[4]=i[4]+d>>>0}return Uint8Array.of(i[0]>>24,i[0]>>16,i[0]>>8,i[0],i[1]>>24,i[1]>>16,i[1]>>8,i[1],i[2]>>24,i[2]>>16,i[2]>>8,i[2],i[3]>>24,i[3]>>16,i[3]>>8,i[3],i[4]>>24,i[4]>>16,i[4]>>8,i[4])}e.default=r})),ne=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;var t=te(),n=b(),r=b();Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return r.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return r.URL}});function i(e,r,i,a){return(0,n.default)(80,t.default,e,r,i,a)}i.DNS=n.DNS,i.URL=n.URL,e.default=i})),re=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=h(),n=_(),r=v();function i(e,i,a){e??={},a??=0;let o=(0,n.default)({...e,_v6:!0},new Uint8Array(16));if(o=(0,r.default)(o),i){if(a<0||a+16>i.length)throw RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let e=0;e<16;e++)i[a+e]=o[e];return i}return(0,t.unsafeStringify)(o)}e.default=i})),ie=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=m(),n=h();function r(e){let r=i(typeof e==`string`?(0,t.default)(e):e);return typeof e==`string`?(0,n.unsafeStringify)(r):r}e.default=r;function i(e){return Uint8Array.of((e[3]&15)<<4|e[4]>>4&15,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|e[6]&15,e[7],(e[1]&15)<<4|(e[2]&240)>>4,(e[2]&15)<<4|(e[3]&240)>>4,16|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}})),ae=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.updateV7State=void 0;var t=g(),n=h(),r={};function i(e,i,s){let c;if(e)c=o(e.random??e.rng?.()??(0,t.default)(),e.msecs,e.seq,i,s);else{let e=Date.now(),n=(0,t.default)();a(r,e,n),c=o(n,r.msecs,r.seq,i,s)}return i??(0,n.unsafeStringify)(c)}function a(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}e.updateV7State=a;function o(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}e.default=i})),oe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=p();function n(e){if(!(0,t.default)(e))throw TypeError(`Invalid UUID`);return parseInt(e.slice(14,15),16)}e.default=n})),se=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.version=e.validate=e.v7=e.v6ToV1=e.v6=e.v5=e.v4=e.v3=e.v1ToV6=e.v1=e.stringify=e.parse=e.NIL=e.MAX=void 0;var t=u();Object.defineProperty(e,"MAX",{enumerable:!0,get:function(){return t.default}});var n=d();Object.defineProperty(e,"NIL",{enumerable:!0,get:function(){return n.default}});var r=m();Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return r.default}});var i=h();Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.default}});var a=_();Object.defineProperty(e,"v1",{enumerable:!0,get:function(){return a.default}});var o=v();Object.defineProperty(e,"v1ToV6",{enumerable:!0,get:function(){return o.default}});var s=x();Object.defineProperty(e,"v3",{enumerable:!0,get:function(){return s.default}});var c=ee();Object.defineProperty(e,"v4",{enumerable:!0,get:function(){return c.default}});var l=ne();Object.defineProperty(e,"v5",{enumerable:!0,get:function(){return l.default}});var f=re();Object.defineProperty(e,"v6",{enumerable:!0,get:function(){return f.default}});var g=ie();Object.defineProperty(e,"v6ToV1",{enumerable:!0,get:function(){return g.default}});var y=ae();Object.defineProperty(e,"v7",{enumerable:!0,get:function(){return y.default}});var b=p();Object.defineProperty(e,"validate",{enumerable:!0,get:function(){return b.default}});var S=oe();Object.defineProperty(e,"version",{enumerable:!0,get:function(){return S.default}})})),C=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createNoDashGuid=e.createGuid=void 0;var t=se(),n=()=>(0,t.v4)();e.createGuid=n,e.createNoDashGuid=()=>n().replace(RegExp(`-`,`g`),``).toUpperCase()})),w=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PlatformEvent=e.EventType=void 0;var t=C();(function(e){e[e.Debug=0]=`Debug`,e[e.Info=1]=`Info`,e[e.Warning=2]=`Warning`,e[e.Error=3]=`Error`,e[e.None=4]=`None`})(e.EventType||={}),e.PlatformEvent=class{constructor(e,n){this.privName=e,this.privEventId=(0,t.createNoDashGuid)(),this.privEventTime=new Date().toISOString(),this.privEventType=n,this.privMetadata={}}get name(){return this.privName}get eventId(){return this.privEventId}get eventTime(){return this.privEventTime}get eventType(){return this.privEventType}get metadata(){return this.privMetadata}}})),ce=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AudioStreamNodeErrorEvent=e.AudioStreamNodeDetachedEvent=e.AudioStreamNodeAttachedEvent=e.AudioStreamNodeAttachingEvent=e.AudioStreamNodeEvent=e.AudioSourceErrorEvent=e.AudioSourceOffEvent=e.AudioSourceReadyEvent=e.AudioSourceInitializingEvent=e.AudioSourceEvent=void 0;var t=w(),n=class extends t.PlatformEvent{constructor(e,n,r=t.EventType.Info){super(e,r),this.privAudioSourceId=n}get audioSourceId(){return this.privAudioSourceId}};e.AudioSourceEvent=n,e.AudioSourceInitializingEvent=class extends n{constructor(e){super(`AudioSourceInitializingEvent`,e)}},e.AudioSourceReadyEvent=class extends n{constructor(e){super(`AudioSourceReadyEvent`,e)}},e.AudioSourceOffEvent=class extends n{constructor(e){super(`AudioSourceOffEvent`,e)}},e.AudioSourceErrorEvent=class extends n{constructor(e,n){super(`AudioSourceErrorEvent`,e,t.EventType.Error),this.privError=n}get error(){return this.privError}};var r=class extends n{constructor(e,t,n){super(e,t),this.privAudioNodeId=n}get audioNodeId(){return this.privAudioNodeId}};e.AudioStreamNodeEvent=r,e.AudioStreamNodeAttachingEvent=class extends r{constructor(e,t){super(`AudioStreamNodeAttachingEvent`,e,t)}},e.AudioStreamNodeAttachedEvent=class extends r{constructor(e,t){super(`AudioStreamNodeAttachedEvent`,e,t)}},e.AudioStreamNodeDetachedEvent=class extends r{constructor(e,t){super(`AudioStreamNodeDetachedEvent`,e,t)}},e.AudioStreamNodeErrorEvent=class extends r{constructor(e,t,n){super(`AudioStreamNodeErrorEvent`,e,t),this.privError=n}get error(){return this.privError}}})),le=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionRedirectEvent=e.ConnectionMessageSentEvent=e.ConnectionMessageReceivedEvent=e.ConnectionEstablishErrorEvent=e.ConnectionErrorEvent=e.ConnectionClosedEvent=e.ConnectionEstablishedEvent=e.ConnectionStartEvent=e.ConnectionEvent=e.ServiceEvent=void 0;var t=w();e.ServiceEvent=class extends t.PlatformEvent{constructor(e,n,r=t.EventType.Info){super(e,r),this.privJsonResult=n}get jsonString(){return this.privJsonResult}};var n=class extends t.PlatformEvent{constructor(e,n,r=t.EventType.Info){super(e,r),this.privConnectionId=n}get connectionId(){return this.privConnectionId}};e.ConnectionEvent=n,e.ConnectionStartEvent=class extends n{constructor(e,t,n){super(`ConnectionStartEvent`,e),this.privUri=t,this.privHeaders=n}get uri(){return this.privUri}get headers(){return this.privHeaders}},e.ConnectionEstablishedEvent=class extends n{constructor(e){super(`ConnectionEstablishedEvent`,e)}},e.ConnectionClosedEvent=class extends n{constructor(e,n,r){super(`ConnectionClosedEvent`,e,t.EventType.Debug),this.privReason=r,this.privStatusCode=n}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}},e.ConnectionErrorEvent=class extends n{constructor(e,n,r){super(`ConnectionErrorEvent`,e,t.EventType.Debug),this.privMessage=n,this.privType=r}get message(){return this.privMessage}get type(){return this.privType}},e.ConnectionEstablishErrorEvent=class extends n{constructor(e,n,r){super(`ConnectionEstablishErrorEvent`,e,t.EventType.Error),this.privStatusCode=n,this.privReason=r}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}},e.ConnectionMessageReceivedEvent=class extends n{constructor(e,t,n){super(`ConnectionMessageReceivedEvent`,e),this.privNetworkReceivedTime=t,this.privMessage=n}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}},e.ConnectionMessageSentEvent=class extends n{constructor(e,t,n){super(`ConnectionMessageSentEvent`,e),this.privNetworkSentTime=t,this.privMessage=n}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}},e.ConnectionRedirectEvent=class extends n{constructor(e,n,r,i){super(`ConnectionRedirectEvent`,e,t.EventType.Info),this.privRedirectUrl=n,this.privOriginalUrl=r,this.privContext=i}get redirectUrl(){return this.privRedirectUrl}get originalUrl(){return this.privOriginalUrl}get context(){return this.privContext}}})),T=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ObjectDisposedError=e.InvalidOperationError=e.ArgumentNullError=void 0,e.ArgumentNullError=class extends Error{constructor(e){super(e),this.name=`ArgumentNull`,this.message=e}},e.InvalidOperationError=class extends Error{constructor(e){super(e),this.name=`InvalidOperation`,this.message=e}},e.ObjectDisposedError=class extends Error{constructor(e,t){super(t),this.name=e+`ObjectDisposed`,this.message=t}}})),E=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionMessage=e.MessageType=void 0;var t=T(),n=C(),r;(function(e){e[e.Text=0]=`Text`,e[e.Binary=1]=`Binary`})(r=e.MessageType||={}),e.ConnectionMessage=class{constructor(e,i,a,o){if(this.privBody=null,e===r.Text&&i&&typeof i!=`string`)throw new t.InvalidOperationError(`Payload must be a string`);if(e===r.Binary&&i&&!(i instanceof ArrayBuffer))throw new t.InvalidOperationError(`Payload must be ArrayBuffer`);switch(this.privMessageType=e,this.privBody=i,this.privHeaders=a||{},this.privId=o||(0,n.createNoDashGuid)(),this.messageType){case r.Binary:this.privSize=this.binaryBody===null?0:this.binaryBody.byteLength;break;case r.Text:this.privSize=this.textBody.length}}get messageType(){return this.privMessageType}get headers(){return this.privHeaders}get body(){return this.privBody}get textBody(){if(this.privMessageType===r.Binary)throw new t.InvalidOperationError(`Not supported for binary message`);return this.privBody}get binaryBody(){if(this.privMessageType===r.Text)throw new t.InvalidOperationError(`Not supported for text message`);return this.privBody}get id(){return this.privId}}})),ue=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionOpenResponse=void 0,e.ConnectionOpenResponse=class{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}})),de=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DeferralMap=void 0,e.DeferralMap=class{constructor(){this.privMap={}}add(e,t){this.privMap[e]=t}getId(e){return this.privMap[e]}complete(e,t){try{this.privMap[e].resolve(t)}catch(t){this.privMap[e].reject(t)}finally{this.privMap[e]=void 0}}}})),fe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SendingAgentContextMessageEvent=e.DialogEvent=void 0;var t=w(),n=class extends t.PlatformEvent{constructor(e,n=t.EventType.Info){super(e,n)}};e.DialogEvent=n,e.SendingAgentContextMessageEvent=class extends n{constructor(e){super(`SendingAgentContextMessageEvent`),this.privAgentConfig=e}get agentConfig(){return this.privAgentConfig}}})),pe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.EventSource=void 0;var t=T(),n=C();e.EventSource=class{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new t.ObjectDisposedError(`EventSource`);if(this.metadata)for(let t in this.metadata)t&&e.metadata&&(e.metadata[t]||(e.metadata[t]=this.metadata[t]));for(let t in this.privEventListeners)t&&this.privEventListeners[t]&&this.privEventListeners[t](e)}attach(e){let t=(0,n.createNoDashGuid)();return this.privEventListeners[t]=e,{detach:()=>(delete this.privEventListeners[t],Promise.resolve())}}attachListener(e){return this.attach(t=>e.onEvent(t))}attachConsoleListener(e){return this.privConsoleListener&&this.privConsoleListener.detach(),this.privConsoleListener=this.attach(t=>e.onEvent(t)),this.privConsoleListener}isDisposed(){return this.privIsDisposed}dispose(){this.privEventListeners=null,this.privIsDisposed=!0}get metadata(){return this.privMetadata}}})),me=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Events=void 0;var t=T(),n=pe(),r=class e{static setEventSource(n){if(!n)throw new t.ArgumentNullError(`eventSource`);e.privInstance=n}static get instance(){return e.privInstance}};e.Events=r,r.privInstance=new n.EventSource})),he=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),ge=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionState=void 0,(function(e){e[e.None=0]=`None`,e[e.Connected=1]=`Connected`,e[e.Connecting=2]=`Connecting`,e[e.Disconnected=3]=`Disconnected`})(e.ConnectionState||={})})),_e=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),ve=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),ye=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),be=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),xe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),Se=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),Ce=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),we=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),Te=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.List=void 0;var t=T();e.List=class e{constructor(e){if(this.privSubscriptionIdCounter=0,this.privAddSubscriptions={},this.privRemoveSubscriptions={},this.privDisposedSubscriptions={},this.privDisposeReason=null,this.privList=[],e)for(let t of e)this.privList.push(t)}get(e){return this.throwIfDisposed(),this.privList[e]}first(){return this.get(0)}last(){return this.get(this.length()-1)}add(e){this.throwIfDisposed(),this.insertAt(this.privList.length,e)}insertAt(e,t){this.throwIfDisposed(),e===0?this.privList.unshift(t):e===this.privList.length?this.privList.push(t):this.privList.splice(e,0,t),this.triggerSubscriptions(this.privAddSubscriptions)}removeFirst(){return this.throwIfDisposed(),this.removeAt(0)}removeLast(){return this.throwIfDisposed(),this.removeAt(this.length()-1)}removeAt(e){return this.throwIfDisposed(),this.remove(e,1)[0]}remove(e,t){this.throwIfDisposed();let n=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),n}clear(){this.throwIfDisposed(),this.remove(0,this.length())}length(){return this.throwIfDisposed(),this.privList.length}onAdded(e){this.throwIfDisposed();let t=this.privSubscriptionIdCounter++;return this.privAddSubscriptions[t]=e,{detach:()=>(delete this.privAddSubscriptions[t],Promise.resolve())}}onRemoved(e){this.throwIfDisposed();let t=this.privSubscriptionIdCounter++;return this.privRemoveSubscriptions[t]=e,{detach:()=>(delete this.privRemoveSubscriptions[t],Promise.resolve())}}onDisposed(e){this.throwIfDisposed();let t=this.privSubscriptionIdCounter++;return this.privDisposedSubscriptions[t]=e,{detach:()=>(delete this.privDisposedSubscriptions[t],Promise.resolve())}}join(e){return this.throwIfDisposed(),this.privList.join(e)}toArray(){let e=[];return this.privList.forEach(t=>{e.push(t)}),e}any(e){return this.throwIfDisposed(),e?this.where(e).length()>0:this.length()>0}all(e){return this.throwIfDisposed(),this.where(e).length()===this.length()}forEach(e){this.throwIfDisposed();for(let t=0;t<this.length();t++)e(this.privList[t],t)}select(t){this.throwIfDisposed();let n=[];for(let e=0;e<this.privList.length;e++)n.push(t(this.privList[e],e));return new e(n)}where(t){this.throwIfDisposed();let n=new e;for(let e=0;e<this.privList.length;e++)t(this.privList[e],e)&&n.add(this.privList[e]);return n}orderBy(t){this.throwIfDisposed();let n=this.toArray().sort(t);return new e(n)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,n)=>e(n,t))}clone(){return this.throwIfDisposed(),new e(this.toArray())}concat(t){return this.throwIfDisposed(),new e(this.privList.concat(t.toArray()))}concatArray(t){return this.throwIfDisposed(),new e(this.privList.concat(t))}isDisposed(){return this.privList==null}dispose(e){this.isDisposed()||(this.privDisposeReason=e,this.privList=null,this.privAddSubscriptions=null,this.privRemoveSubscriptions=null,this.triggerSubscriptions(this.privDisposedSubscriptions))}throwIfDisposed(){if(this.isDisposed())throw new t.ObjectDisposedError(`List`,this.privDisposeReason)}triggerSubscriptions(e){if(e)for(let t in e)t&&e[t]()}}})),D=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.marshalPromiseToCallbacks=e.Sink=e.Deferred=e.PromiseResultEventSource=e.PromiseResult=e.PromiseState=void 0;var t;(function(e){e[e.None=0]=`None`,e[e.Resolved=1]=`Resolved`,e[e.Rejected=2]=`Rejected`})(t=e.PromiseState||={});var n=class{constructor(e){this.throwIfError=()=>{if(this.isError)throw this.error},e.on(e=>{this.privIsCompleted||(this.privIsCompleted=!0,this.privIsError=!1,this.privResult=e)},e=>{this.privIsCompleted||(this.privIsCompleted=!0,this.privIsError=!0,this.privError=e)})}get isCompleted(){return this.privIsCompleted}get isError(){return this.privIsError}get error(){return this.privError}get result(){return this.privResult}};e.PromiseResult=n;var r=class{constructor(){this.setResult=e=>{this.privOnSetResult(e)},this.setError=e=>{this.privOnSetError(e)},this.on=(e,t)=>{this.privOnSetResult=e,this.privOnSetError=t}}};e.PromiseResultEventSource=r,e.Deferred=class{constructor(){this.resolve=e=>(this.privResolve(e),this),this.reject=e=>(this.privReject(e),this),this.privPromise=new Promise((e,t)=>{this.privResolve=e,this.privReject=t})}get promise(){return this.privPromise}},e.Sink=class{constructor(){this.privState=t.None,this.privPromiseResult=null,this.privPromiseResultEvents=null,this.privSuccessHandlers=[],this.privErrorHandlers=[],this.privPromiseResultEvents=new r,this.privPromiseResult=new n(this.privPromiseResultEvents)}get state(){return this.privState}get result(){return this.privPromiseResult}resolve(e){if(this.privState!==t.None)throw Error(`'Cannot resolve a completed promise'`);this.privState=t.Resolved,this.privPromiseResultEvents.setResult(e);for(let t=0;t<this.privSuccessHandlers.length;t++)this.executeSuccessCallback(e,this.privSuccessHandlers[t],this.privErrorHandlers[t]);this.detachHandlers()}reject(e){if(this.privState!==t.None)throw Error(`'Cannot reject a completed promise'`);this.privState=t.Rejected,this.privPromiseResultEvents.setError(e);for(let t of this.privErrorHandlers)this.executeErrorCallback(e,t);this.detachHandlers()}on(e,n){e??=()=>{},this.privState===t.None?(this.privSuccessHandlers.push(e),this.privErrorHandlers.push(n)):(this.privState===t.Resolved?this.executeSuccessCallback(this.privPromiseResult.result,e,n):this.privState===t.Rejected&&this.executeErrorCallback(this.privPromiseResult.error,n),this.detachHandlers())}executeSuccessCallback(e,t,n){try{t(e)}catch(e){this.executeErrorCallback(`'Unhandled callback error: ${e}'`,n)}}executeErrorCallback(e,t){if(t)try{t(e)}catch(t){throw Error(`'Unhandled callback error: ${t}. InnerError: ${e}'`)}else throw Error(`'Unhandled error: ${e}'`)}detachHandlers(){this.privErrorHandlers=[],this.privSuccessHandlers=[]}};function i(e,t,n){e.then(e=>{try{t&&t(e)}catch(e){if(n)try{if(e instanceof Error){let t=e;n(t.name+`: `+t.message)}else n(e)}catch{}}},e=>{if(n)try{if(e instanceof Error){let t=e;n(t.name+`: `+t.message)}else n(e)}catch{}})}e.marshalPromiseToCallbacks=i})),Ee=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Queue=void 0;var t=T(),n=Te(),r=D(),i;(function(e){e[e.Dequeue=0]=`Dequeue`,e[e.Peek=1]=`Peek`})(i||={}),e.Queue=class{constructor(e){this.privPromiseStore=new n.List,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new n.List,this.privDetachables=[],this.privSubscribers=new n.List,this.privDetachables.push(this.privList.onAdded(()=>this.drain()))}enqueue(e){this.throwIfDispose(),this.enqueueFromPromise(new Promise(t=>t(e)))}enqueueFromPromise(e){this.throwIfDispose(),e.then(e=>{this.privList.add(e)},()=>{})}dequeue(){this.throwIfDispose();let e=new r.Deferred;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:i.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();let e=new r.Deferred;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:i.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}async drainAndDispose(e,t){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;let n=this.privSubscribers;if(n){for(;n.length()>0;)n.removeFirst().deferral.resolve(void 0);this.privSubscribers===n&&(this.privSubscribers=n)}for(let e of this.privDetachables)await e.detach();if(this.privPromiseStore.length()>0&&e){let t=[];return this.privPromiseStore.toArray().forEach(e=>{t.push(e)}),Promise.all(t).finally(()=>{this.privSubscribers=null,this.privList.forEach(t=>{e(t)}),this.privList=null}).then()}this.privSubscribers=null,this.privList=null}}async dispose(e){await this.drainAndDispose(null,e)}drain(){if(!this.privIsDrainInProgress&&!this.privIsDisposing){this.privIsDrainInProgress=!0;let e=this.privSubscribers,t=this.privList;if(e&&t){for(;t.length()>0&&e.length()>0&&!this.privIsDisposing;){let n=e.removeFirst();if(n.type===i.Peek)n.deferral.resolve(t.first());else{let e=t.removeFirst();n.deferral.resolve(e)}}this.privSubscribers===e&&(this.privSubscribers=e),this.privList===t&&(this.privList=t)}this.privIsDrainInProgress=!1}}throwIfDispose(){if(this.isDisposed())throw this.privDisposeReason?new t.InvalidOperationError(this.privDisposeReason):new t.ObjectDisposedError(`Queue`);if(this.privIsDisposing)throw new t.InvalidOperationError(`Queue disposing`)}}})),De=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RawWebsocketMessage=void 0;var t=E(),n=T(),r=C();e.RawWebsocketMessage=class{constructor(e,i,a){if(this.privPayload=null,!i)throw new n.ArgumentNullError(`payload`);if(e===t.MessageType.Binary&&Object.getPrototypeOf(i).constructor.name!==`ArrayBuffer`)throw new n.InvalidOperationError(`Payload must be ArrayBuffer`);if(e===t.MessageType.Text&&typeof i!=`string`)throw new n.InvalidOperationError(`Payload must be a string`);this.privMessageType=e,this.privPayload=i,this.privId=a||(0,r.createNoDashGuid)()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===t.MessageType.Binary)throw new n.InvalidOperationError(`Not supported for binary message`);return this.privPayload}get binaryContent(){if(this.privMessageType===t.MessageType.Text)throw new n.InvalidOperationError(`Not supported for text message`);return this.privPayload}get id(){return this.privId}}})),Oe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RiffPcmEncoder=void 0,e.RiffPcmEncoder=class{constructor(e,t){this.privActualSampleRate=e,this.privDesiredSampleRate=t}encode(e){let t=this.downSampleAudioFrame(e,this.privActualSampleRate,this.privDesiredSampleRate);if(!t)return null;let n=t.length*2,r=new ArrayBuffer(n),i=new DataView(r);return this.floatTo16BitPCM(i,0,t),r}setString(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}floatTo16BitPCM(e,t,n){for(let r=0;r<n.length;r++,t+=2){let i=Math.max(-1,Math.min(1,n[r]));e.setInt16(t,i<0?i*32768:i*32767,!0)}}downSampleAudioFrame(e,t,n){if(!e)return null;if(n===t||n>t)return e;let r=t/n,i=Math.round(e.length/r),a=new Float32Array(i),o=0,s=0;for(;s<i;){let t=Math.round((s+1)*r),n=0,i=0;for(;o<t&&o<e.length;)n+=e[o++],i++;a[s++]=n/i}return a}}})),ke=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Stream=void 0;var t=T(),n=C(),r=Ee();e.Stream=class{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||(0,n.createNoDashGuid)(),this.privReaderQueue=new r.Queue}get isClosed(){return this.privIsWriteEnded}get isReadEnded(){return this.privIsReadEnded}get id(){return this.privId}close(){this.privIsWriteEnded||=(this.writeStreamChunk({buffer:null,isEnd:!0,timeReceived:Date.now()}),!0)}writeStreamChunk(e){if(this.throwIfClosed(),!this.privReaderQueue.isDisposed())try{this.privReaderQueue.enqueue(e)}catch{}}read(){if(this.privIsReadEnded)throw new t.InvalidOperationError(`Stream read has already finished`);return this.privReaderQueue.dequeue().then(async e=>((e===void 0||e.isEnd)&&await this.privReaderQueue.dispose(`End of stream reached`),e))}readEnded(){this.privIsReadEnded||(this.privIsReadEnded=!0,this.privReaderQueue=new r.Queue)}throwIfClosed(){if(this.privIsWriteEnded)throw new t.InvalidOperationError(`Stream closed`)}}})),O=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationStatus=void 0,(function(e){e[e.Success=0]=`Success`,e[e.Error=1]=`Error`})(e.TranslationStatus||={})})),Ae=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ChunkedArrayBufferStream=void 0;var t=k();e.ChunkedArrayBufferStream=class extends t.Stream{constructor(e,t){super(t),this.privTargetChunkSize=Math.round(e),this.privNextBufferReadyBytes=0}writeStreamChunk(e){if(e.isEnd||this.privNextBufferReadyBytes===0&&e.buffer.byteLength===this.privTargetChunkSize){super.writeStreamChunk(e);return}let t=0;for(;t<e.buffer.byteLength;){this.privNextBufferToWrite===void 0&&(this.privNextBufferToWrite=new ArrayBuffer(this.privTargetChunkSize),this.privNextBufferStartTime=e.timeReceived);let n=Math.min(e.buffer.byteLength-t,this.privTargetChunkSize-this.privNextBufferReadyBytes),r=new Uint8Array(this.privNextBufferToWrite),i=new Uint8Array(e.buffer.slice(t,n+t));r.set(i,this.privNextBufferReadyBytes),this.privNextBufferReadyBytes+=n,t+=n,this.privNextBufferReadyBytes===this.privTargetChunkSize&&(super.writeStreamChunk({buffer:this.privNextBufferToWrite,isEnd:!1,timeReceived:this.privNextBufferStartTime}),this.privNextBufferReadyBytes=0,this.privNextBufferToWrite=void 0)}}close(){this.privNextBufferReadyBytes!==0&&!this.isClosed&&super.writeStreamChunk({buffer:this.privNextBufferToWrite.slice(0,this.privNextBufferReadyBytes),isEnd:!1,timeReceived:this.privNextBufferStartTime}),super.close()}}})),je=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),Me=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Timeout=void 0;var t=class e{static load(){let t=new Map([[0,()=>{}]]),n=new Map,r=`data:text/javascript;base64,`+btoa(`!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=14)}([function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return d}));const r=new Map,o=new Map,i=e=>{const t=r.get(e);if(void 0===t)throw new Error('There is no interval scheduled with the given id "'.concat(e,'".'));clearTimeout(t),r.delete(e)},u=e=>{const t=o.get(e);if(void 0===t)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(t),o.delete(e)},f=(e,t)=>{let n,r;if("performance"in self){const o=performance.now();n=o,r=e-Math.max(0,o-t)}else n=Date.now(),r=e;return{expected:n+r,remainingDelay:r}},c=(e,t,n,r)=>{const o="performance"in self?performance.now():Date.now();o>n?postMessage({id:null,method:"call",params:{timerId:t}}):e.set(t,setTimeout(c,n-o,e,t,n))},a=(e,t,n)=>{const{expected:o,remainingDelay:i}=f(e,n);r.set(t,setTimeout(c,i,r,t,o))},d=(e,t,n)=>{const{expected:r,remainingDelay:i}=f(e,n);o.set(t,setTimeout(c,i,o,t,r))}},function(e,t,n){"use strict";n.r(t);var r=n(2);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(3);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(4);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o);var f=n(5);for(var o in f)"default"!==o&&function(e){n.d(t,e,(function(){return f[e]}))}(o);var c=n(6);for(var o in c)"default"!==o&&function(e){n.d(t,e,(function(){return c[e]}))}(o);var a=n(7);for(var o in a)"default"!==o&&function(e){n.d(t,e,(function(){return a[e]}))}(o);var d=n(8);for(var o in d)"default"!==o&&function(e){n.d(t,e,(function(){return d[e]}))}(o);var s=n(9);for(var o in s)"default"!==o&&function(e){n.d(t,e,(function(){return s[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(11);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(12);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(13);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(0),o=n(1);for(var i in o)"default"!==i&&function(e){n.d(t,e,(function(){return o[e]}))}(i);var u=n(10);for(var i in u)"default"!==i&&function(e){n.d(t,e,(function(){return u[e]}))}(i);addEventListener("message",({data:e})=>{try{if("clear"===e.method){const{id:t,params:{timerId:n}}=e;Object(r.b)(n),postMessage({error:null,id:t})}else{if("set"!==e.method)throw new Error('The given method "'.concat(e.method,'" is not supported'));{const{params:{delay:t,now:n,timerId:o}}=e;Object(r.d)(t,o,n)}}}catch(t){postMessage({error:{message:t.message},id:e.id,result:null})}})}]);`),i=new Worker(r);return i.addEventListener(`message`,({data:r})=>{if(e.isCallNotification(r)){let{params:{timerId:e}}=r,i=t.get(e);if(typeof i==`number`){let t=n.get(i);if(t===void 0||t!==e)throw Error(`The timer is in an undefined state.`)}else if(i!==void 0)i(),t.delete(e);else throw Error(`The timer is in an undefined state.`)}else if(e.isClearResponse(r)){let{id:e}=r,i=n.get(e);if(i===void 0)throw Error(`The timer is in an undefined state.`);n.delete(e),t.delete(i)}else{let{error:{message:e}}=r;throw Error(e)}}),{clearTimeout:e=>{let r=Math.random();n.set(r,e),t.set(e,r),i.postMessage({id:r,method:`clear`,params:{timerId:e}})},setTimeout:(e,n)=>{let r=Math.random();return t.set(r,e),i.postMessage({id:null,method:`set`,params:{delay:n,now:performance.now(),timerId:r}}),r}}}static loadWorkerTimers(){return()=>(e.workerTimers===null&&(e.workerTimers=e.load()),e.workerTimers)}static isCallNotification(e){return e.method!==void 0&&e.method===`call`}static isClearResponse(e){return e.error===null&&typeof e.id==`number`}};e.Timeout=t,t.workerTimers=null,t.clearTimeout=e=>t.timers().clearTimeout(e),t.setTimeout=(e,n)=>t.timers().setTimeout(e,n),t.timers=t.loadWorkerTimers()})),Ne=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OCSPCacheUpdateErrorEvent=e.OCSPResponseRetrievedEvent=e.OCSPCacheFetchErrorEvent=e.OCSPVerificationFailedEvent=e.OCSPCacheHitEvent=e.OCSPCacheEntryNeedsRefreshEvent=e.OCSPCacheEntryExpiredEvent=e.OCSPWSUpgradeStartedEvent=e.OCSPStapleReceivedEvent=e.OCSPCacheUpdateCompleteEvent=e.OCSPDiskCacheStoreEvent=e.OCSPMemoryCacheStoreEvent=e.OCSPCacheUpdateNeededEvent=e.OCSPDiskCacheHitEvent=e.OCSPCacheMissEvent=e.OCSPMemoryCacheHitEvent=e.OCSPEvent=void 0;var t=w(),n=class extends t.PlatformEvent{constructor(e,t,n){super(e,t),this.privSignature=n}};e.OCSPEvent=n,e.OCSPMemoryCacheHitEvent=class extends n{constructor(e){super(`OCSPMemoryCacheHitEvent`,t.EventType.Debug,e)}},e.OCSPCacheMissEvent=class extends n{constructor(e){super(`OCSPCacheMissEvent`,t.EventType.Debug,e)}},e.OCSPDiskCacheHitEvent=class extends n{constructor(e){super(`OCSPDiskCacheHitEvent`,t.EventType.Debug,e)}},e.OCSPCacheUpdateNeededEvent=class extends n{constructor(e){super(`OCSPCacheUpdateNeededEvent`,t.EventType.Debug,e)}},e.OCSPMemoryCacheStoreEvent=class extends n{constructor(e){super(`OCSPMemoryCacheStoreEvent`,t.EventType.Debug,e)}},e.OCSPDiskCacheStoreEvent=class extends n{constructor(e){super(`OCSPDiskCacheStoreEvent`,t.EventType.Debug,e)}},e.OCSPCacheUpdateCompleteEvent=class extends n{constructor(e){super(`OCSPCacheUpdateCompleteEvent`,t.EventType.Debug,e)}},e.OCSPStapleReceivedEvent=class extends n{constructor(){super(`OCSPStapleReceivedEvent`,t.EventType.Debug,``)}},e.OCSPWSUpgradeStartedEvent=class extends n{constructor(e){super(`OCSPWSUpgradeStartedEvent`,t.EventType.Debug,e)}},e.OCSPCacheEntryExpiredEvent=class extends n{constructor(e,n){super(`OCSPCacheEntryExpiredEvent`,t.EventType.Debug,e),this.privExpireTime=n}},e.OCSPCacheEntryNeedsRefreshEvent=class extends n{constructor(e,n,r){super(`OCSPCacheEntryNeedsRefreshEvent`,t.EventType.Debug,e),this.privExpireTime=r,this.privStartTime=n}},e.OCSPCacheHitEvent=class extends n{constructor(e,n,r){super(`OCSPCacheHitEvent`,t.EventType.Debug,e),this.privExpireTime=r,this.privExpireTimeString=new Date(r).toLocaleDateString(),this.privStartTime=n,this.privStartTimeString=new Date(n).toLocaleTimeString()}},e.OCSPVerificationFailedEvent=class extends n{constructor(e,n){super(`OCSPVerificationFailedEvent`,t.EventType.Debug,e),this.privError=n}},e.OCSPCacheFetchErrorEvent=class extends n{constructor(e,n){super(`OCSPCacheFetchErrorEvent`,t.EventType.Debug,e),this.privError=n}},e.OCSPResponseRetrievedEvent=class extends n{constructor(e){super(`OCSPResponseRetrievedEvent`,t.EventType.Debug,e)}},e.OCSPCacheUpdateErrorEvent=class extends n{constructor(e,n){super(`OCSPCacheUpdateErrorEvent`,t.EventType.Debug,e),this.privError=n}}})),Pe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BackgroundEvent=void 0;var t=k();e.BackgroundEvent=class extends t.PlatformEvent{constructor(e){super(`BackgroundEvent`,t.EventType.Error),this.privError=e}get error(){return this.privError}}})),k=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationStatus=void 0,n(ce(),e),n(le(),e),n(E(),e),n(ue(),e),n(de(),e),n(fe(),e),n(T(),e),n(me(),e),n(pe(),e),n(C(),e),n(he(),e),n(ge(),e),n(_e(),e),n(ve(),e),n(ye(),e),n(be(),e),n(xe(),e),n(Se(),e),n(Ce(),e),n(we(),e),n(Te(),e),n(w(),e),n(D(),e),n(Ee(),e),n(De(),e),n(Oe(),e),n(ke(),e);var r=O();Object.defineProperty(e,"TranslationStatus",{enumerable:!0,get:function(){return r.TranslationStatus}}),n(Ae(),e),n(je(),e),n(Me(),e),n(Ne(),e),n(Pe(),e)})),A=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HeaderNames=void 0;var t=class{};e.HeaderNames=t,t.AuthKey=`Ocp-Apim-Subscription-Key`,t.Authorization=`Authorization`,t.SpIDAuthKey=`Apim-Subscription-Id`,t.ConnectionId=`X-ConnectionId`,t.ContentType=`Content-Type`,t.CustomCommandsAppId=`X-CommandsAppId`,t.Path=`Path`,t.RequestId=`X-RequestId`,t.RequestStreamId=`X-StreamId`,t.RequestTimestamp=`X-Timestamp`,t.ContinuationToken=`X-Continuation-Token`,t.ContinuationAudioStreamOffset=`X-Continuation-Audio-Streams-1-Offset`})),j=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthInfo=void 0,e.AuthInfo=class{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}})),M=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CognitiveSubscriptionKeyAuthentication=void 0;var t=k(),n=A(),r=j();e.CognitiveSubscriptionKeyAuthentication=class{constructor(e){if(!e)throw new t.ArgumentNullError(`subscriptionKey`);this.privAuthInfo=new r.AuthInfo(n.HeaderNames.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}})),Fe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CognitiveTokenAuthentication=void 0;var t=k(),n=j(),r=A(),i=class e{constructor(e,n){if(!e)throw new t.ArgumentNullError(`fetchCallback`);if(!n)throw new t.ArgumentNullError(`fetchOnExpiryCallback`);this.privFetchCallback=e,this.privFetchOnExpiryCallback=n}fetch(t){return this.privFetchCallback(t).then(t=>new n.AuthInfo(r.HeaderNames.Authorization,t===void 0?void 0:e.privTokenPrefix+t))}fetchOnExpiry(t){return this.privFetchOnExpiryCallback(t).then(t=>new n.AuthInfo(r.HeaderNames.Authorization,t===void 0?void 0:e.privTokenPrefix+t))}};e.CognitiveTokenAuthentication=i,i.privTokenPrefix=`Bearer `})),Ie=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),Le=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),N=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RecognitionEndedEvent=e.RecognitionCompletionStatus=e.RecognitionStartedEvent=e.ConnectingToServiceEvent=e.ListeningStartedEvent=e.RecognitionTriggeredEvent=e.SpeechRecognitionEvent=void 0;var t=k(),n=class extends t.PlatformEvent{constructor(e,n,r,i=t.EventType.Info){super(e,i),this.privRequestId=n,this.privSessionId=r}get requestId(){return this.privRequestId}get sessionId(){return this.privSessionId}};e.SpeechRecognitionEvent=n,e.RecognitionTriggeredEvent=class extends n{constructor(e,t,n,r){super(`RecognitionTriggeredEvent`,e,t),this.privAudioSourceId=n,this.privAudioNodeId=r}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}},e.ListeningStartedEvent=class extends n{constructor(e,t,n,r){super(`ListeningStartedEvent`,e,t),this.privAudioSourceId=n,this.privAudioNodeId=r}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}},e.ConnectingToServiceEvent=class extends n{constructor(e,t,n){super(`ConnectingToServiceEvent`,e,n),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}},e.RecognitionStartedEvent=class extends n{constructor(e,t,n,r,i){super(`RecognitionStartedEvent`,e,i),this.privAudioSourceId=t,this.privAudioNodeId=n,this.privAuthFetchEventId=r}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}get authFetchEventId(){return this.privAuthFetchEventId}};var r;(function(e){e[e.Success=0]=`Success`,e[e.AudioSourceError=1]=`AudioSourceError`,e[e.AudioSourceTimeout=2]=`AudioSourceTimeout`,e[e.AuthTokenFetchError=3]=`AuthTokenFetchError`,e[e.AuthTokenFetchTimeout=4]=`AuthTokenFetchTimeout`,e[e.UnAuthorized=5]=`UnAuthorized`,e[e.ConnectTimeout=6]=`ConnectTimeout`,e[e.ConnectError=7]=`ConnectError`,e[e.ClientRecognitionActivityTimeout=8]=`ClientRecognitionActivityTimeout`,e[e.UnknownError=9]=`UnknownError`})(r=e.RecognitionCompletionStatus||={}),e.RecognitionEndedEvent=class extends n{constructor(e,n,i,a,o,s,c,l){super(`RecognitionEndedEvent`,e,o,c===r.Success?t.EventType.Info:t.EventType.Error),this.privAudioSourceId=n,this.privAudioNodeId=i,this.privAuthFetchEventId=a,this.privStatus=c,this.privError=l,this.privServiceTag=s}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}get authFetchEventId(){return this.privAuthFetchEventId}get serviceTag(){return this.privServiceTag}get status(){return this.privStatus}get error(){return this.privError}}})),P=t(((e,t)=>{t.exports={}})),Re=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.LogLevel=void 0;var t=k();Object.defineProperty(e,"LogLevel",{enumerable:!0,get:function(){return t.EventType}})})),F=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Contracts=void 0,e.Contracts=class e{static throwIfNullOrUndefined(e,t){if(e==null)throw Error(`throwIfNullOrUndefined:`+t)}static throwIfNull(e,t){if(e===null)throw Error(`throwIfNull:`+t)}static throwIfNullOrWhitespace(t,n){if(e.throwIfNullOrUndefined(t,n),(``+t).trim().length<1)throw Error(`throwIfNullOrWhitespace:`+n)}static throwIfNullOrTooLong(t,n,r){if(e.throwIfNullOrUndefined(t,n),(``+t).length>r)throw Error(`throwIfNullOrTooLong:`+n+` (more than `+r.toString()+` characters)`)}static throwIfNullOrTooShort(t,n,r){if(e.throwIfNullOrUndefined(t,n),(``+t).length<r)throw Error(`throwIfNullOrTooShort:`+n+` (less than `+r.toString()+` characters)`)}static throwIfDisposed(e){if(e)throw Error(`the object is already disposed`)}static throwIfArrayEmptyOrWhitespace(t,n){if(e.throwIfNullOrUndefined(t,n),t.length===0)throw Error(`throwIfArrayEmptyOrWhitespace:`+n);for(let r of t)e.throwIfNullOrWhitespace(r,n)}static throwIfFileDoesNotExist(t,n){e.throwIfNullOrWhitespace(t,n)}static throwIfNotUndefined(e,t){if(e!==void 0)throw Error(`throwIfNotUndefined:`+t)}static throwIfNumberOutOfRange(t,n,r,i){if(e.throwIfNullOrUndefined(t,n),t<r||t>i)throw Error(`throwIfNumberOutOfRange:`+n+` (must be between `+r.toString()+` and `+i.toString()+`)`)}}})),ze=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.ConsoleLoggingListener=void 0;var i=r(P()),a=Re(),o=F();e.ConsoleLoggingListener=class{constructor(e=a.LogLevel.None){this.privLogPath=void 0,this.privEnableConsoleOutput=!0,this.privLogLevelFilter=e}set logPath(e){o.Contracts.throwIfNullOrUndefined(i.openSync,`
|
|
2
|
+
File System access not available`),this.privLogPath=e}set enableConsoleOutput(e){this.privEnableConsoleOutput=e}onEvent(e){if(e.eventType>=this.privLogLevelFilter){let t=this.toString(e);if(this.logCallback&&this.logCallback(t),this.privLogPath&&i.writeFileSync(this.privLogPath,t+`
|
|
3
|
+
`,{flag:`a+`}),this.privEnableConsoleOutput)switch(e.eventType){case a.LogLevel.Debug:console.debug(t);break;case a.LogLevel.Info:console.info(t);break;case a.LogLevel.Warning:console.warn(t);break;case a.LogLevel.Error:console.error(t);break;default:console.log(t)}}}toString(e){let t=[`${e.eventTime}`,`${e.name}`],n=e;for(let r in n)if(r&&e.hasOwnProperty(r)&&r!==`eventTime`&&r!==`eventType`&&r!==`eventId`&&r!==`name`&&r!==`constructor`){let e=n[r],i=`<NULL>`;e!=null&&(i=typeof e==`number`||typeof e==`string`?e.toString():JSON.stringify(e)),t.push(`${r}: ${i}`)}return t.join(` | `)}}})),Be=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),I=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AudioStreamFormatImpl=e.AudioStreamFormat=e.AudioFormatTag=void 0;var t;(function(e){e[e.PCM=1]=`PCM`,e[e.MuLaw=2]=`MuLaw`,e[e.Siren=3]=`Siren`,e[e.MP3=4]=`MP3`,e[e.SILKSkype=5]=`SILKSkype`,e[e.OGG_OPUS=6]=`OGG_OPUS`,e[e.WEBM_OPUS=7]=`WEBM_OPUS`,e[e.ALaw=8]=`ALaw`,e[e.FLAC=9]=`FLAC`,e[e.OPUS=10]=`OPUS`,e[e.AMR_WB=11]=`AMR_WB`,e[e.G722=12]=`G722`})(t=e.AudioFormatTag||={});var n=class{static getDefaultInputFormat(){return r.getDefaultInputFormat()}static getWaveFormat(e,t,n,i){return new r(e,t,n,i)}static getWaveFormatPCM(e,t,n){return new r(e,t,n)}};e.AudioStreamFormat=n;var r=class e extends n{constructor(e=16e3,n=16,r=1,i=t.PCM){super();let a=!0;switch(i){case t.PCM:this.formatTag=1;break;case t.ALaw:this.formatTag=6;break;case t.MuLaw:this.formatTag=7;break;default:a=!1}if(this.bitsPerSample=n,this.samplesPerSec=e,this.channels=r,this.avgBytesPerSec=this.samplesPerSec*this.channels*(this.bitsPerSample/8),this.blockAlign=this.channels*Math.max(this.bitsPerSample,8),a){this.privHeader=new ArrayBuffer(44);let e=new DataView(this.privHeader);this.setString(e,0,`RIFF`),e.setUint32(4,0,!0),this.setString(e,8,`WAVEfmt `),e.setUint32(16,16,!0),e.setUint16(20,this.formatTag,!0),e.setUint16(22,this.channels,!0),e.setUint32(24,this.samplesPerSec,!0),e.setUint32(28,this.avgBytesPerSec,!0),e.setUint16(32,this.channels*(this.bitsPerSample/8),!0),e.setUint16(34,this.bitsPerSample,!0),this.setString(e,36,`data`),e.setUint32(40,0,!0)}}static getDefaultInputFormat(){return new e}static getAudioContext(e){let t=window.AudioContext||window.webkitAudioContext||!1;if(t)return e!==void 0&&navigator.mediaDevices.getSupportedConstraints().sampleRate?new t({sampleRate:e}):new t;throw Error(`Browser does not support Web Audio API (AudioContext is not available).`)}close(){}get header(){return this.privHeader}setString(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}};e.AudioStreamFormatImpl=r})),Ve=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MicAudioSource=e.AudioWorkletSourceURLPropertyName=void 0;var t=Q(),n=k(),r=I();e.AudioWorkletSourceURLPropertyName=`MICROPHONE-WorkletSourceUrl`;var i=class i{constructor(e,t,r,a){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=i.AUDIOFORMAT.avgBytesPerSec/10,this.privId=r||(0,n.createNoDashGuid)(),this.privEvents=new n.EventSource,this.privMediaStream=a||null,this.privIsClosing=!1}get format(){return Promise.resolve(i.AUDIOFORMAT)}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new n.Deferred;try{this.createAudioContext()}catch(e){if(e instanceof Error){let t=e;this.privInitializeDeferral.reject(t.name+`: `+t.message)}else this.privInitializeDeferral.reject(e);return this.privInitializeDeferral.promise}let e=window.navigator,t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(t,n,r)=>{e.mediaDevices.getUserMedia(t).then(n).catch(r)}),t){let e=()=>{this.onEvent(new n.AudioSourceInitializingEvent(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new n.AudioSourceReadyEvent(this.privId)),this.privInitializeDeferral.resolve()):t({audio:!this.deviceId||{deviceId:this.deviceId},video:!1},e=>{this.privMediaStream=e,this.onEvent(new n.AudioSourceReadyEvent(this.privId)),this.privInitializeDeferral.resolve()},e=>{let t=`Error occurred during microphone initialization: ${e}`;this.privInitializeDeferral.reject(t),this.onEvent(new n.AudioSourceErrorEvent(this.privId,t))})};this.privContext.state===`suspended`?this.privContext.resume().then(e).catch(e=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${e}`)}):e()}else{let e=`Browser does not support getUserMedia.`;this.privInitializeDeferral.reject(e),this.onEvent(new n.AudioSourceErrorEvent(e,``))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new n.AudioStreamNodeAttachingEvent(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new n.AudioStreamNodeAttachedEvent(this.privId,e)),{detach:async()=>(t.readEnded(),delete this.privStreams[e],this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)),this.turnOff()),id:()=>e,read:()=>t.read()}))}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)))}async turnOff(){for(let e in this.privStreams)if(e){let t=this.privStreams[e];t&&t.close()}this.onEvent(new n.AudioSourceOffEvent(this.privId)),this.privInitializeDeferral&&=(await this.privInitializeDeferral,null),await this.destroyAudioContext()}get events(){return this.privEvents}get deviceInfo(){return this.getMicrophoneLabel().then(e=>({bitspersample:i.AUDIOFORMAT.bitsPerSample,channelcount:i.AUDIOFORMAT.channels,connectivity:t.connectivity.Unknown,manufacturer:`Speech SDK`,model:e,samplerate:i.AUDIOFORMAT.samplesPerSec,type:t.type.Microphones}))}setProperty(t,n){if(t===e.AudioWorkletSourceURLPropertyName)this.privRecorder.setWorkletUrl(n);else throw Error(`Property '`+t+`' is not supported on Microphone.`)}getMicrophoneLabel(){let e=`microphone`;if(this.privMicrophoneLabel!==void 0)return Promise.resolve(this.privMicrophoneLabel);if(this.privMediaStream===void 0||!this.privMediaStream.active)return Promise.resolve(e);this.privMicrophoneLabel=e;let t=this.privMediaStream.getTracks()[0].getSettings().deviceId;if(t===void 0)return Promise.resolve(this.privMicrophoneLabel);let r=new n.Deferred;return navigator.mediaDevices.enumerateDevices().then(e=>{for(let n of e)if(n.deviceId===t){this.privMicrophoneLabel=n.label;break}r.resolve(this.privMicrophoneLabel)},()=>r.resolve(this.privMicrophoneLabel)),r.promise}async listen(e){await this.turnOn();let t=new n.ChunkedArrayBufferStream(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(t){throw this.onEvent(new n.AudioStreamNodeErrorEvent(this.privId,e,t)),t}return t}onEvent(e){this.privEvents.onEvent(e),n.Events.instance.onEvent(e)}createAudioContext(){this.privContext||=r.AudioStreamFormatImpl.getAudioContext(i.AUDIOFORMAT.samplesPerSec)}async destroyAudioContext(){if(!this.privContext)return;this.privRecorder.releaseMediaResources(this.privContext);let e=!1;`close`in this.privContext&&(e=!0),e?this.privIsClosing||=(this.privIsClosing=!0,await this.privContext.close(),this.privContext=null,!1):this.privContext!==null&&this.privContext.state===`running`&&await this.privContext.suspend()}};e.MicAudioSource=i,i.AUDIOFORMAT=r.AudioStreamFormat.getDefaultInputFormat()})),He=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FileAudioSource=void 0;var t=Q(),n=k(),r=I();e.FileAudioSource=class{constructor(e,t,r){this.privStreams={},this.privHeaderEnd=44,this.privId=r||(0,n.createNoDashGuid)(),this.privEvents=new n.EventSource,this.privSource=e,this.privFilename=typeof window<`u`&&typeof Blob<`u`&&this.privSource instanceof Blob?e.name:t||`unknown.wav`,this.privAudioFormatPromise=this.readHeader()}get format(){return this.privAudioFormatPromise}turnOn(){if(this.privFilename.lastIndexOf(`.wav`)!==this.privFilename.length-4){let e=this.privFilename+` is not supported. Only WAVE files are allowed at the moment.`;return this.onEvent(new n.AudioSourceErrorEvent(e,``)),Promise.reject(e)}this.onEvent(new n.AudioSourceInitializingEvent(this.privId)),this.onEvent(new n.AudioSourceReadyEvent(this.privId))}id(){return this.privId}async attach(e){this.onEvent(new n.AudioStreamNodeAttachingEvent(this.privId,e));let t=await this.upload(e);return this.onEvent(new n.AudioStreamNodeAttachedEvent(this.privId,e)),Promise.resolve({detach:async()=>{t.readEnded(),delete this.privStreams[e],this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)),await this.turnOff()},id:()=>e,read:()=>t.read()})}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)))}turnOff(){for(let e in this.privStreams)if(e){let t=this.privStreams[e];t&&!t.isClosed&&t.close()}return this.onEvent(new n.AudioSourceOffEvent(this.privId)),Promise.resolve()}get events(){return this.privEvents}get deviceInfo(){return this.privAudioFormatPromise.then(e=>Promise.resolve({bitspersample:e.bitsPerSample,channelcount:e.channels,connectivity:t.connectivity.Unknown,manufacturer:`Speech SDK`,model:`File`,samplerate:e.samplesPerSec,type:t.type.File}))}readHeader(){let e=this.privSource.slice(0,4296),t=new n.Deferred,i=e=>{let n=new DataView(e),i=e=>String.fromCharCode(n.getUint8(e),n.getUint8(e+1),n.getUint8(e+2),n.getUint8(e+3));if(i(0)!==`RIFF`){t.reject(`Invalid WAV header in file, RIFF was not found`);return}if(i(8)!==`WAVE`||i(12)!==`fmt `){t.reject(`Invalid WAV header in file, WAVEfmt was not found`);return}let a=n.getInt32(16,!0),o=n.getUint16(22,!0),s=n.getUint32(24,!0),c=n.getUint16(34,!0),l=36+Math.max(a-16,0);for(;i(l)!==`data`;l+=2)if(l>4288){t.reject(`Invalid WAV header in file, data block was not found`);return}this.privHeaderEnd=l+8,t.resolve(r.AudioStreamFormat.getWaveFormatPCM(s,c,o))};if(typeof window<`u`&&typeof Blob<`u`&&e instanceof Blob){let t=new FileReader;t.onload=e=>{let t=e.target.result;i(t)},t.readAsArrayBuffer(e)}else{let t=e;i(t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength))}return t.promise}async upload(e){let t=t=>{let r=`Error occurred while processing '${this.privFilename}'. ${t}`;throw this.onEvent(new n.AudioStreamNodeErrorEvent(this.privId,e,r)),Error(r)};try{await this.turnOn();let r=await this.privAudioFormatPromise,i=new n.ChunkedArrayBufferStream(r.avgBytesPerSec/10,e);this.privStreams[e]=i;let a=this.privSource.slice(this.privHeaderEnd),o=e=>{i.isClosed||(i.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()}),i.close())};if(typeof window<`u`&&typeof Blob<`u`&&a instanceof Blob){let e=new FileReader;e.onerror=e=>t(e.toString()),e.onload=e=>{let t=e.target.result;o(t)},e.readAsArrayBuffer(a)}else{let e=a;o(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}return i}catch(e){t(e)}}onEvent(e){this.privEvents.onEvent(e),n.Events.instance.onEvent(e)}}})),Ue=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PcmRecorder=void 0;var t=k();e.PcmRecorder=class{constructor(e){this.privStopInputOnRelease=e}record(e,n,r){let i=16e3,a=new t.RiffPcmEncoder(e.sampleRate,i),o=e.createMediaStreamSource(n),s=()=>{let t=(()=>{let t=0;try{return e.createScriptProcessor(t,1,1)}catch{t=2048;let n=e.sampleRate;for(;t<16384&&n>=2*i;)t<<=1,n>>=1;return e.createScriptProcessor(t,1,1)}})();t.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0);if(r&&!r.isClosed){let e=a.encode(t);e&&r.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}},o.connect(t),t.connect(e.destination),this.privMediaResources={scriptProcessorNode:t,source:o,stream:n}},c=!!this.privSpeechProcessorScript&&this.privSpeechProcessorScript.toLowerCase()===`ignore`;if(e.audioWorklet&&!c){if(!this.privSpeechProcessorScript){let e=new Blob([`class SP extends AudioWorkletProcessor {
|
|
4
|
+
constructor(options) {
|
|
5
|
+
super(options);
|
|
6
|
+
}
|
|
7
|
+
process(inputs, outputs) {
|
|
8
|
+
const input = inputs[0];
|
|
9
|
+
const output = [];
|
|
10
|
+
for (let channel = 0; channel < input.length; channel += 1) {
|
|
11
|
+
output[channel] = input[channel];
|
|
12
|
+
}
|
|
13
|
+
this.port.postMessage(output[0]);
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
15
16
|
}
|
|
16
|
-
this.port.postMessage(output[0]);
|
|
17
|
-
return true;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
registerProcessor('speech-processor', SP);`,h=new Blob([u],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(h)}const a=()=>{const u=(()=>{let h=0;try{return e.createScriptProcessor(h,1,1)}catch{h=2048;let d=e.sampleRate;for(;h<16384&&d>=32e3;)h<<=1,d>>=1;return e.createScriptProcessor(h,1,1)}})();u.onaudioprocess=h=>{const c=h.inputBuffer.getChannelData(0);if(i&&!i.isClosed){const d=s.encode(c);d&&i.writeStreamChunk({buffer:d,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}};if(!!this.privSpeechProcessorScript&&!!e.audioWorklet)e.audioWorklet.addModule(this.privSpeechProcessorScript).then(()=>{const u=new AudioWorkletNode(e,"speech-processor");u.port.onmessage=h=>{const c=h.data;if(i&&!i.isClosed){const d=s.encode(c);d&&i.writeStreamChunk({buffer:d,isEnd:!1,timeReceived:Date.now()})}},o.connect(u),u.connect(e.destination),this.privMediaResources={scriptProcessorNode:u,source:o,stream:t}}).catch(()=>{a()});else try{a()}catch(u){throw new Error(`Unable to start audio worklet node for PCMRecorder: ${u}`)}}releaseMediaResources(e){this.privMediaResources&&(this.privMediaResources.scriptProcessorNode&&(this.privMediaResources.scriptProcessorNode.disconnect(e.destination),this.privMediaResources.scriptProcessorNode=null),this.privMediaResources.source&&(this.privMediaResources.source.disconnect(),this.privStopInputOnRelease&&this.privMediaResources.stream.getTracks().forEach(t=>t.stop()),this.privMediaResources.source=null))}setWorkletUrl(e){this.privSpeechProcessorScript=e}}var Oe=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class M{constructor(e){e&&(this.privProxyInfo=e),M.privDiskCache||(M.privDiskCache=new Be("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){M.privDiskCache=void 0,M.privMemCache={}}GetAgent(e){const t=new Be.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const i="privProxyInfo";t[i]=this.privProxyInfo}return t}static GetProxyAgent(e){const t={host:e.HostName,port:e.Port};return e.UserName?t.headers={"Proxy-Authentication":"Basic "+new Buffer(`${e.UserName}:${e.Password===void 0?"":e.Password}`).toString("base64")}:t.headers={},t.headers.requestOCSP="true",new Be(t)}static OCSPCheck(e,t){return Oe(this,void 0,void 0,function*(){let i,n,s=!1;const o=yield e;o.cork();const a=o;return new Promise((u,h)=>{o.on("OCSPResponse",c=>{c&&(this.onEvent(new Ji),n=c)}),o.on("error",c=>{s||(s=!0,o.destroy(),h(c))}),a.on("secure",()=>Oe(this,void 0,void 0,function*(){const c=a.getPeerCertificate(!0);try{const d=yield this.GetIssuer(c);i=(void 0)(c.raw,d.raw);const v=i.id.toString("hex");n||(n=yield M.GetResponseFromCache(v,i,t)),yield this.VerifyOCSPResponse(n,i,t),o.uncork(),s=!0,u(o)}catch(d){o.destroy(),s=!0,h(d)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,i)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){i(s);return}t(o)})})}static GetResponseFromCache(e,t,i){return Oe(this,void 0,void 0,function*(){let n=M.privMemCache[e];if(n&&this.onEvent(new Ui(e)),!n)try{const s=yield M.privDiskCache.get(e);s.isCached&&(M.onEvent(new Vi(e)),M.StoreMemoryCacheEntry(e,s.value),n=s.value)}catch{n=null}if(!n)return n;try{const a=(void 0)(n).value.tbsResponseData;if(a.responses.length<1){this.onEvent(new Gt(e,"Not enough data in cached response"));return}const u=a.responses[0].thisUpdate,h=a.responses[0].nextUpdate;if(h<Date.now()+this.testTimeOffset-6e4)this.onEvent(new Qi(e,h)),n=null;else{const c=Math.min(864e5,(h-u)/2);h-(Date.now()+this.testTimeOffset)<c?(this.onEvent(new Xi(e,u,h)),this.UpdateCache(t,i).catch(d=>{this.onEvent(new tr(e,d.toString()))})):this.onEvent(new Zi(e,u,h))}}catch(s){this.onEvent(new Gt(e,s)),n=null}return n||this.onEvent(new Wi(e)),n})}static VerifyOCSPResponse(e,t,i){return Oe(this,void 0,void 0,function*(){let n=e;return n||(n=yield M.GetOCSPResponse(t,i)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(M.onEvent(new Yi(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,i).then(()=>{s()},u=>{o(u)}):o(a)):(e||M.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return Oe(this,void 0,void 0,function*(){const i=e.id.toString("hex");this.onEvent(new Fi(i));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(i,n),this.onEvent(new $i(e.id.toString("hex")))})}static StoreCacheEntry(e,t){this.StoreMemoryCacheEntry(e,t),this.StoreDiskCacheEntry(e,t)}static StoreMemoryCacheEntry(e,t){this.privMemCache[e]=t,this.onEvent(new ji(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Gi(e))})}static GetOCSPResponse(e,t){const i="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=M.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,i,(a,u)=>{if(a){o(a);return}const h=new URL(u);n=Object.assign(Object.assign({},n),{host:h.host,protocol:h.protocol,port:h.port,path:h.pathname,hostname:h.host}),(void 0)(n,e.data,(c,d)=>{if(c){o(c);return}const v=e.certID;this.onEvent(new er(v.toString("hex"))),s(d)})})})}static onEvent(e){O.instance.onEvent(e)}CreateConnection(e,t){const i=typeof process!="undefined"&&{}.NODE_TLS_REJECT_UNAUTHORIZED!=="0"&&{}.SPEECH_CONDUCT_OCSP_CHECK!=="0"&&t.secureEndpoint;let n;if(t=Object.assign(Object.assign({},t),{requestOCSP:!M.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=M.GetProxyAgent(this.privProxyInfo);n=new Promise((a,u)=>{o.callback(e,t,(h,c)=>{h?u(h):a(c)})})}else t.secureEndpoint,n=Promise.resolve((void 0)(t));return i?M.OCSPCheck(n,this.privProxyInfo):n}}M.testTimeOffset=0,M.forceDisableOCSPStapling=!1,M.privMemCache={};var Ai=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class at{constructor(e,t,i,n,s,o){if(!e)throw new z("uri");if(!i)throw new z("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new j,this.privConnectionId=t,this.privMessageFormatter=i,this.privConnectionState=D.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[R.ConnectionId]=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===D.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new x,this.privCertificateValidatedDeferral=new x,this.privConnectionState=D.Connecting;try{if(typeof WebSocket!="undefined"&&!at.forceNpmWebSocket)this.privCertificateValidatedDeferral.resolve(),this.privWebsocketClient=new WebSocket(this.privUri);else{const e={headers:this.privHeaders,perMessageDeflate:this.privEnableCompression};this.privCertificateValidatedDeferral.resolve();const t=new M(this.proxyInfo);e.agent=t.GetAgent();let n=new URL(this.privUri).protocol;(n==null?void 0:n.toLocaleLowerCase())==="wss:"?n="https:":(n==null?void 0:n.toLocaleLowerCase())==="ws:"&&(n="http:"),e.agent.protocol=n,this.privWebsocketClient=new Be(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new Ie,this.privDisconnectDeferral=new x,this.privSendMessageQueue=new Ie,this.processSendQueue().catch(e=>{O.instance.onEvent(new ke(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new St(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Ut(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=D.Connected,this.onEvent(new Wt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new St(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Bi(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===D.Connecting?(this.privConnectionState=D.Disconnected,this.privConnectionEstablishDeferral.resolve(new St(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=D.Disconnected,this.privWebsocketClient=null,this.onEvent(new Oi(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{O.instance.onEvent(new ke(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===D.Connected){const i=new x;if(this.privReceivingMessageQueue.enqueueFromPromise(i.promise),e.data instanceof ArrayBuffer){const n=new Ue(y.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new vt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new Ue(y.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new vt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid text message format. Error: ${s}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==D.Connected)return Promise.reject(`Cannot send on connection that is in ${D[this.privConnectionState]} state`);const t=new x,i=new x;return this.privSendMessageQueue.enqueueFromPromise(i.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{i.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{i.reject(`Error formatting the message. ${n}`)}),t.promise}read(){return this.privConnectionState!==D.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){if(this.privWebsocketClient)this.privConnectionState!==D.Disconnected&&this.privWebsocketClient.close(1e3,e||"Normal closure by client");else return Promise.resolve();return this.privDisconnectDeferral.promise}get events(){return this.privConnectionEvents}sendRawMessage(e){try{if(!e)return Promise.resolve();if(this.onEvent(new Hi(this.privConnectionId,new Date().toISOString(),e.Message)),this.isWebsocketOpen)this.privWebsocketClient.send(e.RawWebsocketMessage.payload);else return Promise.reject("websocket send error: Websocket not ready "+this.privConnectionId+" "+e.Message.id+" "+new Error().stack);return Promise.resolve()}catch(t){return Promise.reject(`websocket send error: ${t}`)}}onClose(e,t){return Ai(this,void 0,void 0,function*(){const i=`Connection closed. ${e}: ${t}`;this.privConnectionState=D.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},i),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(i)},i)})}processSendQueue(){return Ai(this,void 0,void 0,function*(){for(;;){const t=yield this.privSendMessageQueue.dequeue();if(!t)return;try{yield this.sendRawMessage(t),t.sendStatusDeferral.resolve()}catch(i){t.sendStatusDeferral.reject(i)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),O.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}at.forceNpmWebSocket=!1;var Or=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})};class Pi{constructor(e,t,i,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new z("uri");if(!n)throw new z("messageFormatter");this.privMessageFormatter=n;let u="",h=0;if(t){for(const c in t)if(c){u+=h===0&&e.indexOf("?")===-1?"?":"&";const d=encodeURIComponent(t[c]);u+=`${c}=${d}`,h++}}if(i){for(const c in i)if(c){u+=h===0&&e.indexOf("?")===-1?"?":"&";const d=encodeURIComponent(i[c]);u+=`${c}=${d}`,h++}}this.privUri=e+u,this.privId=a||A(),this.privConnectionMessageAdapter=new at(this.privUri,this.id,this.privMessageFormatter,s,i,o)}dispose(){return Or(this,void 0,void 0,function*(){this.privIsDisposed=!0,this.privConnectionMessageAdapter&&(yield this.privConnectionMessageAdapter.close())})}isDisposed(){return this.privIsDisposed}get id(){return this.privId}state(){return this.privConnectionMessageAdapter.state}open(){return this.privConnectionMessageAdapter.open()}send(e){return this.privConnectionMessageAdapter.send(e)}read(){return this.privConnectionMessageAdapter.read()}get events(){return this.privConnectionMessageAdapter.events}}class Br{constructor(e,t){this.privBuffers=[],this.privReplayOffset=0,this.privLastShrinkOffset=0,this.privBufferStartOffset=0,this.privBufferSerial=0,this.privBufferedBytes=0,this.privReplay=!1,this.privLastChunkAcquiredTime=0,this.privAudioNode=e,this.privBytesPerSecond=t}id(){return this.privAudioNode.id()}read(){if(!!this.privReplay&&this.privBuffers.length!==0){const e=this.privReplayOffset-this.privBufferStartOffset;let t=Math.round(e*this.privBytesPerSecond*1e-7);t%2!==0&&t++;let i=0;for(;i<this.privBuffers.length&&t>=this.privBuffers[i].chunk.buffer.byteLength;)t-=this.privBuffers[i++].chunk.buffer.byteLength;if(i<this.privBuffers.length){const n=this.privBuffers[i].chunk.buffer.slice(t);return this.privReplayOffset+=n.byteLength/this.privBytesPerSecond*1e7,i===this.privBuffers.length-1&&(this.privReplay=!1),Promise.resolve({buffer:n,isEnd:!1,timeReceived:this.privBuffers[i].chunk.timeReceived})}}return this.privAudioNode.read().then(e=>(e&&e.buffer&&(this.privBuffers.push(new _r(e,this.privBufferSerial++,this.privBufferedBytes)),this.privBufferedBytes+=e.buffer.byteLength),e))}detach(){return this.privBuffers=void 0,this.privAudioNode.detach()}replay(){this.privBuffers&&this.privBuffers.length!==0&&(this.privReplay=!0,this.privReplayOffset=this.privLastShrinkOffset)}shrinkBuffers(e){if(this.privBuffers===void 0||this.privBuffers.length===0)return;this.privLastShrinkOffset=e;const t=e-this.privBufferStartOffset;let i=Math.round(t*this.privBytesPerSecond*1e-7),n=0;for(;n<this.privBuffers.length&&i>=this.privBuffers[n].chunk.buffer.byteLength;)i-=this.privBuffers[n++].chunk.buffer.byteLength;this.privBufferStartOffset=Math.round(e-i/this.privBytesPerSecond*1e7),this.privBuffers=this.privBuffers.slice(n)}findTimeAtOffset(e){if(e<this.privBufferStartOffset||this.privBuffers===void 0)return 0;for(const t of this.privBuffers){const i=t.byteOffset/this.privBytesPerSecond*1e7,n=i+t.chunk.buffer.byteLength/this.privBytesPerSecond*1e7;if(e>=i&&e<=n)return t.chunk.timeReceived}return 0}}class _r{constructor(e,t,i){this.chunk=e,this.serial=t,this.byteOffset=i}}class ct{constructor(e,t,i,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=i,this.privProxyPassword=n}static fromParameters(e){return new ct(e.getProperty(p.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(p.SpeechServiceConnection_ProxyPort),10),e.getProperty(p.SpeechServiceConnection_ProxyUserName),e.getProperty(p.SpeechServiceConnection_ProxyPassword))}static fromRecognizerConfig(e){return this.fromParameters(e.parameters)}get HostName(){return this.privProxyHostName}get Port(){return this.privProxyPort}get UserName(){return this.privProxyUserName}get Password(){return this.privProxyPassword}}const Hr=new Set(["json","buffer","string"]);var Kr=r=>(...e)=>{const t=new Set;let i,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(i){const u=`Can't set method to ${a}, already set to ${i}.`;throw new Error(u)}else i=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(Hr.has(a))n=a;else throw new Error(`Unknown encoding, ${a}`);else if(typeof a=="number")t.add(a);else if(typeof a=="object")if(Array.isArray(a)||a instanceof Set)a.forEach(u=>t.add(u));else{if(s)throw new Error("Cannot set headers twice.");s=a}else throw new Error(`Unknown type: ${typeof a}`)}),i||(i="GET"),t.size===0&&t.add(200),r(t,i,n,s,o)};const qr=Kr;class _t extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,_t),this.name="StatusError",this.message=e.statusMessage,this.statusCode=e.status,this.res=e,this.json=e.json.bind(e),this.text=e.text.bind(e),this.arrayBuffer=e.arrayBuffer.bind(e);let i;Object.defineProperty(this,"responseBody",{get:()=>(i||(i=this.arrayBuffer()),i)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var Ur=qr((r,e,t,i,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(i||(i={}),u.username&&(i.Authorization="Basic "+btoa(u.username+":"+u.password),u=new URL(u.protocol+"//"+u.host+u.pathname+u.search)),u.protocol!=="https:"&&u.protocol!=="http:")throw new Error(`Unknown protocol, ${u.protocol}`);if(o&&!(o instanceof ArrayBuffer||ArrayBuffer.isView(o)||typeof o=="string"))if(typeof o=="object")o=JSON.stringify(o),i["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...i||{},...a});const h=await fetch(u,{method:e,headers:a,body:o});if(h.statusCode=h.status,!r.has(h.status))throw new _t(h);return t==="json"?h.json():t==="buffer"?h.arrayBuffer():t==="string"?h.text():h}),Wr=globalThis&&globalThis.__awaiter||function(r,e,t,i){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{h(i.next(c))}catch(d){o(d)}}function u(c){try{h(i.throw(c))}catch(d){o(d)}}function h(c){c.done?s(c.value):n(c.value).then(a,u)}h((i=i.apply(r,e||[])).next())})},de;(function(r){r.Get="GET",r.Post="POST",r.Delete="DELETE",r.File="file"})(de||(de={}));class Vr{constructor(e){if(!e)throw new z("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let i="";try{const n=t.trim().split(/[\r\n]+/),s={};n.forEach(o=>{const a=o.split(": "),u=a.shift().toLowerCase(),h=a.join(": ");s[u]=h}),i=s[e.toLowerCase()]}catch{}return i}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,i={},n=null,s=null){const o=new x,a=e===de.File?"POST":e,u=(d,v={})=>{const w=d;return{data:JSON.stringify(v),headers:JSON.stringify(d.headers),json:v,ok:d.statusCode>=200&&d.statusCode<300,status:d.statusCode,statusText:v.error?v.error.message:w.statusText?w.statusText:w.statusMessage}},h=d=>{const v=new FileReader;return v.readAsArrayBuffer(d),new Promise(w=>{v.onloadend=()=>{w(v.result)}})},c=d=>{const v=Ur(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),w=this.queryParams(i)===""?"":`?${this.queryParams(i)}`;v(w,d).then(T=>Wr(this,void 0,void 0,function*(){if(e===de.Delete||T.statusCode===204)o.resolve(u(T));else try{const K=yield T.json();o.resolve(u(T,K))}catch{o.resolve(u(T))}})).catch(T=>{o.reject(T)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===de.File&&s){const d="multipart/form-data";this.privHeaders["content-type"]=d,this.privHeaders["Content-Type"]=d,typeof Blob!="undefined"&&s instanceof Blob?h(s).then(v=>{c(v)}).catch(v=>{o.reject(v)}):c(s)}else e===de.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),c(n);return o.promise}withQuery(e,t={}){const i=this.queryParams(t);return i?e+(e.indexOf("?")===-1?"?":"&")+i:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class Fr{constructor(e){m(this,"region","");m(this,"sourceLanguage");m(this,"targetLanguage");m(this,"recognizer");m(this,"authorizationManager");m(this,"authorizationRefreshIntervalMs");m(this,"authorizationRefreshTimer");m(this,"stopPromise");var t;if(!e||typeof e.sourceLanguage!="string"||e.sourceLanguage.trim()==="")throw new Error("A sourceLanguage is required.");this.authorizationManager=new pt(e),this.authorizationRefreshIntervalMs=e.tokenLifetimeMs&&e.tokenLifetimeMs>0?e.tokenLifetimeMs:48e4,this.sourceLanguage=e.sourceLanguage,this.targetLanguage=(t=e.targetLanguage)!=null?t:e.sourceLanguage}async start(){await this.registerBindings(document)}async registerBindings(e){const t=e.childNodes;for(let i=0;i<t.length;i++){if(!t[i])continue;const n=t[i];n.attributes&&(n.attributes.getNamedItem("co-stt.start")?await this.handleStartModifier(n,n.attributes.getNamedItem("co-stt.start")):n.attributes.getNamedItem("co-stt.stop")&&await this.handleStopModifier(n,n.attributes.getNamedItem("co-stt.stop"))),n.childNodes.length>0&&await this.registerBindings(n)}}async createSpeechTranslationConfig(){const e=await this.authorizationManager.getAuthorization(),t=oi.fromAuthorizationToken(e.token,e.region);return t.speechRecognitionLanguage=this.sourceLanguage,t.addTargetLanguage(this.targetLanguage),this.region=e.region,t}async handleStartModifier(e,t){e.addEventListener("click",async i=>{try{await this.stop();const n=await this.createSpeechTranslationConfig(),s=te.fromDefaultMicrophoneInput();this.recognizer=new ar(n,s),document.dispatchEvent(new CustomEvent("COAzureSTTStartedRecording",{}));const o={};this.recognizer.recognizing=(a,u)=>{const h=u.result;if(h&&h.reason===I.TranslatingSpeech){const c=h.translations.get(this.targetLanguage);o["result_"+h.privOffset.toString()]=c;const d=Object.values(o).join(". "),v=document.getElementById(t.value);v!==null&&(v instanceof HTMLInputElement?v.value=`${d} `:v.innerHTML=`${d} `)}},this.recognizer.startContinuousRecognitionAsync(()=>{this.scheduleAuthorizationRefresh()},a=>{ae(a)&&this.authorizationManager.clearAuthorization(),this.dispatchError(a,"RECOGNITION_ERROR"),this.stop()})}catch(n){this.clearAuthorizationRefreshTimer(),ae(n)&&this.authorizationManager.clearAuthorization(),this.dispatchError(n),await this.stop()}})}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stop()})}async stop(){if(this.stopPromise)return this.stopPromise;this.clearAuthorizationRefreshTimer();const e=this.recognizer;if(!!e)return this.recognizer=void 0,this.stopPromise=this.stopRecognizer(e).finally(()=>{this.stopPromise=void 0,document.dispatchEvent(new CustomEvent("COAzureSTTStoppedRecording",{}))}),this.stopPromise}scheduleAuthorizationRefresh(){this.clearAuthorizationRefreshTimer(),this.authorizationRefreshTimer=setTimeout(async()=>{if(!!this.recognizer)try{const e=await this.authorizationManager.refreshAuthorization();if(!this.recognizer)return;this.recognizer.authorizationToken=e.token,this.region=e.region,this.scheduleAuthorizationRefresh()}catch(e){this.dispatchError(e,"TOKEN_REFRESH_ERROR"),await this.stop()}},this.authorizationRefreshIntervalMs)}clearAuthorizationRefreshTimer(){!this.authorizationRefreshTimer||(clearTimeout(this.authorizationRefreshTimer),this.authorizationRefreshTimer=void 0)}stopRecognizer(e){return new Promise(t=>{let i=!1;const n=()=>{if(i){t();return}i=!0;try{e.close()}catch{}finally{t()}};try{e.stopContinuousRecognitionAsync(()=>{n()},()=>{n()})}catch{n()}})}dispatchError(e,t){const i=Ce(e);t&&!i.code&&(i.code=t),document.dispatchEvent(new CustomEvent("COAzureSTTError",{detail:{error:i}}))}}const Ii=[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"];class jr{constructor(e){m(this,"region","");m(this,"voice");m(this,"rate");m(this,"pitch");m(this,"textToRead","");m(this,"wordBoundryList",[]);m(this,"clickedNode");m(this,"highlightDiv");m(this,"speechConfig");m(this,"audioConfig");m(this,"player");m(this,"synthesizer");m(this,"previousWordBoundary");m(this,"originalHighlightDivInnerHTML","");m(this,"currentWord","");m(this,"currentOffset",0);m(this,"wordBoundaryOffset",0);m(this,"playbackTextOffsetBase");m(this,"prevTextOffset",0);m(this,"url","");m(this,"prefetchedAudio",new Map);m(this,"prefetchPromises",new Map);m(this,"activePrefetchedAudioUrl","");m(this,"playbackSegments",[]);m(this,"authorizationManager");m(this,"stopPromise");m(this,"playbackSessionId",0);m(this,"highlightInterval");var t,i,n;if(!e||typeof e.voice!="string"||e.voice.trim()==="")throw new Error("A voice is required.");this.authorizationManager=new pt(e),this.voice=e.voice,this.rate=(t=e.rate)!=null?t:0,this.pitch=(i=e.pitch)!=null?i:0,this.url=(n=e.url)!=null?n:""}async start(){await this.registerBindings(document)}setVoice(e){return this.voice=e,this.clearPrefetchedAudio(),this}setRate(e){return this.rate=e,this.clearPrefetchedAudio(),this}setPitch(e){return this.pitch=e,this.clearPrefetchedAudio(),this}async registerBindings(e){const t=e.childNodes;for(let i=0;i<t.length;i++){if(!t[i])continue;const n=t[i];n.attributes&&(n.attributes.getNamedItem("co-tts.id")?await this.handleIdModifier(n,n.attributes.getNamedItem("co-tts.id")):n.attributes.getNamedItem("co-tts.ajax")?await this.handleAjaxModifier(n,n.attributes.getNamedItem("co-tts.ajax")):n.attributes.getNamedItem("co-tts")?await this.handleDefault(n,n.attributes.getNamedItem("co-tts")):n.attributes.getNamedItem("co-tts.stop")?await this.handleStopModifier(n,n.attributes.getNamedItem("co-tts.stop")):n.attributes.getNamedItem("co-tts.resume")?await this.handleResumeModifier(n,n.attributes.getNamedItem("co-tts.resume")):n.attributes.getNamedItem("co-tts.pause")&&await this.handlePauseModifier(n,n.attributes.getNamedItem("co-tts.pause"))),n.childNodes.length>0&&await this.registerBindings(n)}}async handleIdModifier(e,t){e.addEventListener("click",async i=>{var s,o,a;await this.stopPlayer();const n=document.getElementById(t.value);this.clickedNode=n,n&&(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=(a=(o=n.innerText)!=null?o:n.textContent)!=null?a:"",this.setHighlightTargetFromNode(n),await this.startSynthesizer(e,t))})}async handleAjaxModifier(e,t){e.addEventListener("click",async i=>{await this.stopPlayer(),this.clickedNode=e;const n=await fetch(t.value,{method:"GET"});this.textToRead=await n.text(),this.setHighlightTargetFromNode(e),await this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener("click",async i=>{var n,s;await this.stopPlayer(),this.clickedNode=e,this.setHighlightTargetFromNode(e),t.value===""?this.textToRead=(s=(n=e.innerText)!=null?n:e.textContent)!=null?s:"":this.textToRead=t.value,await this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){var i,n;await this.stopPlayer(),this.clickedNode=e,this.setHighlightTargetFromNode(e),t.value===""?this.textToRead=(n=(i=e.innerText)!=null?i:e.textContent)!=null?n:"":this.textToRead=t.value,await this.startSynthesizer(e,t)}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying",{}))})}async handlePauseModifier(e,t){e.addEventListener("click",async i=>{!this.player||typeof this.player.pause!="function"||(this.stopHighlightingInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{})))})}async handleResumeModifier(e,t){e.addEventListener("click",async i=>{if(!!this.player){if(this.shouldHighlight()&&this.startHighlightingInterval(this.playbackSessionId),typeof this.player.resume=="function")await this.player.resume();else if(typeof this.player.play=="function")await this.player.play();else return;document.dispatchEvent(new CustomEvent("COAzureTTSResumedPlaying",{}))}})}async stopPlayer(){return this.stopPromise?this.stopPromise:(this.stopPromise=this.performStopPlayer().finally(()=>{this.stopPromise=void 0}),this.stopPromise)}async performStopPlayer(){this.invalidatePlaybackSession(),this.stopHighlightingInterval(),this.highlightDiv&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML),this.resetPlaybackSegments();const e=this.player,t=this.activePrefetchedAudioUrl,i=this.synthesizer;if(this.textToRead="",this.currentWord="",this.currentOffset=0,this.wordBoundaryOffset=0,this.originalHighlightDivInnerHTML="",this.wordBoundryList=[],this.playbackSegments=[],this.previousWordBoundary=void 0,this.highlightDiv=void 0,this.prevTextOffset=0,this.playbackTextOffsetBase=void 0,this.audioConfig=void 0,this.speechConfig=void 0,this.player===e&&(this.player=void 0),this.activePrefetchedAudioUrl===t&&(this.activePrefetchedAudioUrl=""),this.synthesizer===i&&(this.synthesizer=void 0),e!==void 0&&typeof e.pause=="function")try{e.pause()}catch{}t!==""&&URL.revokeObjectURL(t),this.closeResource(i)}async createSpeechConfig(){const e=await this.authorizationManager.getAuthorization(),t=At.fromAuthorizationToken(e.token,e.region);return t.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,t.speechSynthesisOutputFormat=S.Audio24Khz160KBitRateMonoMp3,this.region=e.region,t}async startSynthesizer(e,t){try{this.speechConfig=await this.createSpeechConfig();const i=this.createPlaybackSession();this.resetHighlightState();const n=new Mt,s=te.fromSpeakerOutput(n),o=new De(this.speechConfig,s);this.player=n,this.audioConfig=s,this.synthesizer=o,o.wordBoundary=(c,d)=>{!this.isActivePlaybackSession(i)||this.wordBoundryList.push(d)};const a=this.collectPlaybackChain(this.clickedNode),u=a.length>1;u?this.preparePlaybackChain(a):this.playbackSegments=[],n.onAudioEnd=async()=>{var w;if(!this.isActivePlaybackSession(i))return;const c=this.clickedNode,d=this.playbackSegments.length>0,v=(w=c==null?void 0:c.hasAttribute)!=null&&w.call(c,"co-tts.next")?c.getAttribute("co-tts.next"):null;if(await this.stopPlayer(),d){document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}));return}if(v){const T=document.getElementById(v);if(T&&await this.playPrefetchedNode(T))return;const K=T==null?void 0:T.attributes.getNamedItem("co-tts.text");T&&K?await this.handleWithoutClick(T,K):T&&T.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},n.onAudioStart=async()=>{!this.isActivePlaybackSession(i)||document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},this.shouldHighlight()&&this.startHighlightingInterval(i),u||this.prefetchNextNode(this.clickedNode);const h=this.buildSSML(this.textToRead);o.speakSsmlAsync(h,()=>{this.closeResource(o),this.isActivePlaybackSession(i)&&this.synthesizer===o&&(this.synthesizer=void 0)},c=>{this.closeResource(o),this.isActivePlaybackSession(i)&&(this.synthesizer===o&&(this.synthesizer=void 0),ae(c)&&this.authorizationManager.clearAuthorization(),this.dispatchError(c,"SYNTHESIS_ERROR"),this.stopPlayer())})}catch(i){ae(i)&&this.authorizationManager.clearAuthorization(),this.dispatchError(i),await this.stopPlayer()}}collectPlaybackChain(e){var o,a;const t=[],i=new Set;let n=e,s=0;for(;n&&!i.has(n.id);){i.add(n.id);const u=(o=n.attributes.getNamedItem("co-tts.text"))!=null?o:n.attributes.getNamedItem("co-tts"),h=this.getNodeText(n,u);if(h==="")break;const c=this.getHighlightDivForNode(n);if(t.push({node:n,text:h,start:s,end:s+h.length,highlightDiv:c,originalHighlightDivInnerHTML:(a=c==null?void 0:c.innerHTML)!=null?a:""}),s+=h.length+1,!n.hasAttribute("co-tts.next"))break;n=document.getElementById(n.getAttribute("co-tts.next"))}return t}preparePlaybackChain(e){this.playbackSegments=e,this.textToRead=e.map(t=>t.text).join(" "),this.highlightDiv=void 0,this.originalHighlightDivInnerHTML="",this.resetHighlightState()}getHighlightDivForNode(e){var i,n,s,o;if(!((i=e==null?void 0:e.hasAttribute)!=null&&i.call(e,"co-tts.highlight")))return;const t=(s=(n=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:n.value)!=null?s:"";return t!==""?(o=document.getElementById(t))!=null?o:void 0:e}resetPlaybackSegments(){this.playbackSegments.forEach(e=>{e.highlightDiv&&(e.highlightDiv.innerHTML=e.originalHighlightDivInnerHTML)})}updateChainedHighlight(e){var s,o;if(~Ii.indexOf(e.text)&&(e=(s=this.previousWordBoundary)!=null?s:void 0),!e){this.resetPlaybackSegments();return}this.ensurePlaybackTextOffsetBase();const t=Math.max(0,e.textOffset-((o=this.playbackTextOffsetBase)!=null?o:0)),i=this.playbackSegments.find(a=>t>=a.start&&t<a.end);if(this.resetPlaybackSegments(),!(i!=null&&i.highlightDiv)){this.previousWordBoundary=e;return}const n=t-i.start;this.highlightTextRange(i.highlightDiv,i.originalHighlightDivInnerHTML,n,e.wordLength,i.text),this.previousWordBoundary=e}getNodeText(e,t){var i,n,s;return t&&t.value!==""?t.value:e.hasAttribute("co-tts.text")&&e.getAttribute("co-tts.text")!==""?(i=e.getAttribute("co-tts.text"))!=null?i:"":(s=(n=e.innerText)!=null?n:e.textContent)!=null?s:""}getPrefetchKey(e,t){return[e.id,t,this.voice,this.rate,this.pitch,this.url].join("|")}clearPrefetchedAudio(){this.prefetchedAudio.forEach(e=>{e.url&&URL.revokeObjectURL(e.url)}),this.prefetchedAudio.clear(),this.prefetchPromises.clear()}async prefetchNextNode(e){var u;if(!e||!e.hasAttribute("co-tts.next"))return;const t=document.getElementById(e.getAttribute("co-tts.next"));if(!t)return;const i=(u=t.attributes.getNamedItem("co-tts.text"))!=null?u:t.attributes.getNamedItem("co-tts"),n=this.getNodeText(t,i);if(n==="")return;const s=this.getPrefetchKey(t,n);if(this.prefetchedAudio.has(s)||this.prefetchPromises.has(s))return;let o;const a=(async()=>{try{const h=await this.createSpeechConfig();o=new De(h,void 0);const c=[];return o.wordBoundary=(d,v)=>{c.push(v)},await new Promise(d=>{o==null||o.speakSsmlAsync(this.buildSSML(n),v=>{if(this.closeResource(o),o=void 0,!(v!=null&&v.audioData)){d(null);return}const w=new Blob([v.audioData],{type:"audio/mpeg"}),T=URL.createObjectURL(w),K={key:s,nodeId:t.id,text:n,url:T,wordBoundryList:c};this.prefetchedAudio.set(s,K),d(K)},v=>{this.closeResource(o),o=void 0,ae(v)&&this.authorizationManager.clearAuthorization(),this.dispatchError(v,"PREFETCH_ERROR"),d(null)})})}catch(h){return this.closeResource(o),o=void 0,ae(h)&&this.authorizationManager.clearAuthorization(),this.dispatchError(h),null}})().finally(()=>{this.prefetchPromises.delete(s)});this.prefetchPromises.set(s,a)}async playPrefetchedNode(e){var a,u;const t=(a=e.attributes.getNamedItem("co-tts.text"))!=null?a:e.attributes.getNamedItem("co-tts"),i=this.getNodeText(e,t),n=this.getPrefetchKey(e,i),s=(u=this.prefetchedAudio.get(n))!=null?u:await this.prefetchPromises.get(n);if(!s)return!1;this.prefetchedAudio.delete(n);const o=this.createPlaybackSession();this.resetHighlightState(),this.clickedNode=e,this.textToRead=s.text,this.wordBoundryList=s.wordBoundryList,this.playbackSegments=[],this.setHighlightTargetFromNode(e);try{const h=new Audio(s.url);return this.activePrefetchedAudioUrl=s.url,this.player=h,h.addEventListener("play",()=>{!this.isActivePlaybackSession(o)||document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},{once:!0}),h.addEventListener("ended",async()=>{var v;if(!this.isActivePlaybackSession(o))return;const c=this.clickedNode,d=(v=c==null?void 0:c.hasAttribute)!=null&&v.call(c,"co-tts.next")?c.getAttribute("co-tts.next"):null;if(await this.stopPlayer(),d){const w=document.getElementById(d);if(w&&await this.playPrefetchedNode(w))return;const T=w==null?void 0:w.attributes.getNamedItem("co-tts.text");w&&T?await this.handleWithoutClick(w,T):w&&w.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},{once:!0}),h.addEventListener("error",()=>{!this.isActivePlaybackSession(o)||(this.dispatchError(new Error("Prefetched audio resource closed unexpectedly."),"AUDIO_RESOURCE_ERROR"),this.stopPlayer())},{once:!0}),this.shouldHighlight()&&this.startHighlightingInterval(o),this.prefetchNextNode(e),await h.play(),!0}catch(h){return this.stopHighlightingInterval(),this.dispatchError(h,"AUDIO_RESOURCE_ERROR"),await this.stopPlayer(),!1}}createPlaybackSession(){return this.playbackSessionId+=1,this.playbackSessionId}isActivePlaybackSession(e){return e===this.playbackSessionId}invalidatePlaybackSession(){this.playbackSessionId+=1}stopHighlightingInterval(){!this.highlightInterval||(clearInterval(this.highlightInterval),this.highlightInterval=void 0)}startHighlightingInterval(e){this.stopHighlightingInterval(),this.highlightInterval=setInterval(()=>{if(!this.isActivePlaybackSession(e)){this.stopHighlightingInterval();return}this.updateHighlightForCurrentTime(e)},50)}updateHighlightForCurrentTime(e){var s,o;if(!this.isActivePlaybackSession(e)||this.player===void 0||!this.shouldHighlight())return;const t=this.player.currentTime;let i;for(const a of this.wordBoundryList)if(t*1e3>a.audioOffset/1e4)i=a;else break;if(i===void 0){this.resetCurrentHighlight();return}if(this.playbackSegments.length>0){this.updateChainedHighlight(i);return}if(~Ii.indexOf(i.text)&&(i=(s=this.previousWordBoundary)!=null?s:void 0),i===void 0||this.prevTextOffset>i.textOffset){this.resetCurrentHighlight();return}this.prevTextOffset=i.textOffset,this.ensurePlaybackTextOffsetBase();const n=Math.max(0,i.textOffset-((o=this.playbackTextOffsetBase)!=null?o:0));this.highlightTextRange(this.highlightDiv,this.originalHighlightDivInnerHTML,n,i.wordLength,this.textToRead),this.previousWordBoundary=i,this.currentWord=i.text,this.wordBoundaryOffset=i.textOffset}highlightTextRange(e,t,i,n,s){if(!e||n<=0||i<0)return;e.innerHTML=t;const o=this.getSpokenTextDomOffset(e,s),a=i+o,u=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let h=0,c,d,v=0,w=0;const T=a+n;for(;u.nextNode();){const le=u.currentNode,Gr=le.data.length,ht=h,Ht=h+Gr;if(!c&&a>=ht&&a<Ht&&(c=le,v=a-ht),T>ht&&T<=Ht){d=le,w=T-ht;break}h=Ht}if(!c||!d)return;const K=document.createRange();try{if(K.setStart(c,v),K.setEnd(d,w),!this.isRangeVisuallyVisible(K,e))return;const le=document.createElement("mark");le.className="co-tts-highlight",le.appendChild(K.extractContents()),K.insertNode(le)}catch{e.innerHTML=t}}getSpokenTextDomOffset(e,t){var s;if(!t)return 0;const i=(s=e.textContent)!=null?s:"";if(i===""||i===t)return 0;const n=i.indexOf(t);return n>=0?n:0}isRangeVisuallyVisible(e,t){if(typeof e.getClientRects!="function")return!0;let i;try{i=Array.from(e.getClientRects()).filter(s=>s.width>0&&s.height>0)}catch{return!0}if(i.length===0)return!0;const n=this.getClippingRect(t);return i.some(s=>this.rectsOverlap(s,n))}getClippingRect(e){let t=e;for(;t;){if(this.isClippingElement(t))return t.getBoundingClientRect();t=t.parentElement}return e.getBoundingClientRect()}isClippingElement(e){var a;const t=(a=globalThis.getComputedStyle)==null?void 0:a.call(globalThis,e);if(!t)return!1;const i=t.overflowX||t.overflow,n=t.overflowY||t.overflow;if(this.isClippingOverflowValue(i)||this.isClippingOverflowValue(n))return!0;const o=t.getPropertyValue("-webkit-line-clamp").trim();return o!==""&&o!=="none"}isClippingOverflowValue(e){return e==="hidden"||e==="auto"||e==="scroll"||e==="clip"}rectsOverlap(e,t){return e.right>t.left&&e.left<t.right&&e.bottom>t.top&&e.top<t.bottom}setHighlightTargetFromNode(e){var i;const t=this.getHighlightDivForNode(e);this.highlightDiv=t,this.originalHighlightDivInnerHTML=(i=t==null?void 0:t.innerHTML)!=null?i:""}shouldHighlight(){return this.highlightDiv?!0:this.playbackSegments.some(e=>Boolean(e.highlightDiv))}resetHighlightState(){this.prevTextOffset=0,this.previousWordBoundary=void 0,this.currentWord="",this.currentOffset=0,this.wordBoundaryOffset=0,this.playbackTextOffsetBase=void 0}ensurePlaybackTextOffsetBase(){this.playbackTextOffsetBase!==void 0||this.wordBoundryList.length===0||(this.playbackTextOffsetBase=this.wordBoundryList.reduce((e,t)=>Math.min(e,t.textOffset),this.wordBoundryList[0].textOffset))}resetCurrentHighlight(){if(this.playbackSegments.length>0){this.resetPlaybackSegments();return}this.highlightDiv&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML)}buildSSML(e){let t=`<speak xmlns="http://www.w3.org/2001/10/synthesis"
|
|
17
|
+
registerProcessor('speech-processor', SP);`],{type:`application/javascript; charset=utf-8`});this.privSpeechProcessorScript=URL.createObjectURL(e)}e.audioWorklet.addModule(this.privSpeechProcessorScript).then(()=>{let t=new AudioWorkletNode(e,`speech-processor`);t.port.onmessage=e=>{let t=e.data;if(r&&!r.isClosed){let e=a.encode(t);e&&r.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}},o.connect(t),t.connect(e.destination),this.privMediaResources={scriptProcessorNode:t,source:o,stream:n}}).catch(()=>{s()})}else try{s()}catch(e){throw Error(`Unable to start audio worklet node for PCMRecorder: ${e}`)}}releaseMediaResources(e){this.privMediaResources&&(this.privMediaResources.scriptProcessorNode&&(this.privMediaResources.scriptProcessorNode.disconnect(e.destination),this.privMediaResources.scriptProcessorNode=null),this.privMediaResources.source&&(this.privMediaResources.source.disconnect(),this.privStopInputOnRelease&&this.privMediaResources.stream.getTracks().forEach(e=>e.stop()),this.privMediaResources.source=null))}setWorkletUrl(e){this.privSpeechProcessorScript=e}}})),L=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.WebsocketMessageAdapter=void 0;var a=r(P()),o=r(P()),s=i(P()),c=i(P()),l=i(P()),u=A(),d=k(),f=class e{constructor(e,t,n,r,i,a){if(!e)throw new d.ArgumentNullError(`uri`);if(!n)throw new d.ArgumentNullError(`messageFormatter`);this.proxyInfo=r,this.privConnectionEvents=new d.EventSource,this.privConnectionId=t,this.privMessageFormatter=n,this.privConnectionState=d.ConnectionState.None,this.privUri=e,this.privHeaders=i,this.privEnableCompression=a,this.privHeaders[u.HeaderNames.ConnectionId]=this.privConnectionId,this.privHeaders.connectionId=this.privConnectionId,this.privLastErrorReceived=``}get state(){return this.privConnectionState}open(){if(this.privConnectionState===d.ConnectionState.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new d.Deferred,this.privCertificateValidatedDeferral=new d.Deferred,this.privConnectionState=d.ConnectionState.Connecting;try{let t=typeof window>`u`&&!!this.proxyInfo?.HostName;if(typeof WebSocket<`u`&&!e.forceNpmWebSocket&&!t)this.privCertificateValidatedDeferral.resolve(),this.privWebsocketClient=new WebSocket(this.privUri);else{let e=new URL(this.privUri).protocol;e?.toLocaleLowerCase()===`wss:`?e=`https:`:e?.toLocaleLowerCase()===`ws:`&&(e=`http:`);let t={headers:this.privHeaders,perMessageDeflate:this.privEnableCompression,followRedirects:e.toLocaleLowerCase()===`https:`};this.privCertificateValidatedDeferral.resolve(),t.agent=this.getAgent(),t.agent.protocol=e,this.privWebsocketClient=new l.default(this.privUri,t),this.privWebsocketClient.on(`redirect`,e=>{let t=new d.ConnectionRedirectEvent(this.privConnectionId,e,this.privUri,`Getting redirect URL from endpoint ${this.privUri} with redirect URL '${e}'`);d.Events.instance.onEvent(t)})}this.privWebsocketClient.binaryType=`arraybuffer`,this.privReceivingMessageQueue=new d.Queue,this.privDisconnectDeferral=new d.Deferred,this.privSendMessageQueue=new d.Queue,this.processSendQueue().catch(e=>{d.Events.instance.onEvent(new d.BackgroundEvent(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new d.ConnectionOpenResponse(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new d.ConnectionStartEvent(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=d.ConnectionState.Connected,this.onEvent(new d.ConnectionEstablishedEvent(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new d.ConnectionOpenResponse(200,``))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new d.ConnectionErrorEvent(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===d.ConnectionState.Connecting?(this.privConnectionState=d.ConnectionState.Disconnected,this.privConnectionEstablishDeferral.resolve(new d.ConnectionOpenResponse(e.code,e.reason+` `+this.privLastErrorReceived))):(this.privConnectionState=d.ConnectionState.Disconnected,this.privWebsocketClient=null,this.onEvent(new d.ConnectionClosedEvent(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(e=>{d.Events.instance.onEvent(new d.BackgroundEvent(e))})},this.privWebsocketClient.onmessage=e=>{let t=new Date().toISOString();if(this.privConnectionState===d.ConnectionState.Connected){let n=new d.Deferred;if(this.privReceivingMessageQueue.enqueueFromPromise(n.promise),e.data instanceof ArrayBuffer){let r=new d.RawWebsocketMessage(d.MessageType.Binary,e.data);this.privMessageFormatter.toConnectionMessage(r).then(e=>{this.onEvent(new d.ConnectionMessageReceivedEvent(this.privConnectionId,t,e)),n.resolve(e)},e=>{n.reject(`Invalid binary message format. Error: ${e}`)})}else{let r=new d.RawWebsocketMessage(d.MessageType.Text,e.data);this.privMessageFormatter.toConnectionMessage(r).then(e=>{this.onEvent(new d.ConnectionMessageReceivedEvent(this.privConnectionId,t,e)),n.resolve(e)},e=>{n.reject(`Invalid text message format. Error: ${e}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==d.ConnectionState.Connected)return Promise.reject(`Cannot send on connection that is in ${d.ConnectionState[this.privConnectionState]} state`);let t=new d.Deferred,n=new d.Deferred;return this.privSendMessageQueue.enqueueFromPromise(n.promise),this.privMessageFormatter.fromConnectionMessage(e).then(r=>{n.resolve({Message:e,RawWebsocketMessage:r,sendStatusDeferral:t})},e=>{n.reject(`Error formatting the message. ${e}`)}),t.promise}read(){return this.privConnectionState===d.ConnectionState.Connected?this.privReceivingMessageQueue.dequeue():Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`)}close(e){if(this.privWebsocketClient)this.privConnectionState!==d.ConnectionState.Disconnected&&this.privWebsocketClient.close(1e3,e||`Normal closure by client`);else return Promise.resolve();return this.privDisconnectDeferral.promise}get events(){return this.privConnectionEvents}sendRawMessage(e){try{if(!e)return Promise.resolve();if(this.onEvent(new d.ConnectionMessageSentEvent(this.privConnectionId,new Date().toISOString(),e.Message)),this.isWebsocketOpen)this.privWebsocketClient.send(e.RawWebsocketMessage.payload);else return Promise.reject(`websocket send error: Websocket not ready `+this.privConnectionId+` `+e.Message.id+` `+Error().stack);return Promise.resolve()}catch(e){return Promise.reject(`websocket send error: ${e}`)}}async onClose(e,t){let n=`Connection closed. ${e}: ${t}`;this.privConnectionState=d.ConnectionState.Disconnected,this.privDisconnectDeferral.resolve(),await this.privReceivingMessageQueue.drainAndDispose(()=>{},n),await this.privSendMessageQueue.drainAndDispose(e=>{e.sendStatusDeferral.reject(n)},n)}async processSendQueue(){for(;;){let e=await this.privSendMessageQueue.dequeue();if(!e)return;try{await this.sendRawMessage(e),e.sendStatusDeferral.resolve()}catch(t){e.sendStatusDeferral.reject(t)}}}onEvent(e){this.privConnectionEvents.onEvent(e),d.Events.instance.onEvent(e)}getAgent(){let e=new s.default.Agent(this.createConnection);return this.proxyInfo!==void 0&&this.proxyInfo.HostName!==void 0&&this.proxyInfo.Port>0&&(e.proxyInfo=this.proxyInfo),e}static GetProxyAgent(e){let t={host:e.HostName,port:e.Port};return t.headers=e.UserName?{"Proxy-Authentication":`Basic `+Buffer.from(`${e.UserName}:${e.Password===void 0?``:e.Password}`).toString(`base64`)}:{},t.headers.requestOCSP=`true`,new c.default(t)}createConnection(t,n){let r;if(n={...n,requestOCSP:!0,servername:n.host},this.proxyInfo){let i=e.GetProxyAgent(this.proxyInfo);r=new Promise((e,r)=>{i.callback(t,n,(t,n)=>{t?r(t):e(n)})})}else r=n.secureEndpoint?Promise.resolve(o.connect(n)):Promise.resolve(a.connect(n));return r}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}};e.WebsocketMessageAdapter=f,f.forceNpmWebSocket=!1})),R=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebsocketConnection=void 0;var t=k(),n=L();e.WebsocketConnection=class{constructor(e,r,i,a,o,s=!1,c){if(this.privIsDisposed=!1,!e)throw new t.ArgumentNullError(`uri`);if(!a)throw new t.ArgumentNullError(`messageFormatter`);this.privMessageFormatter=a;let l=``,u=0;if(r){for(let t in r)if(t){l+=u===0&&e.indexOf(`?`)===-1?`?`:`&`,l+=encodeURIComponent(t);let n=r[t];n&&(n=encodeURIComponent(n),l+=`=${n}`),u++}}if(i){for(let t in i)if(t){l+=u===0&&e.indexOf(`?`)===-1?`?`:`&`;let n=encodeURIComponent(i[t]);l+=`${t}=${n}`,u++}}this.privUri=e+l,this.privId=c||(0,t.createNoDashGuid)(),this.privConnectionMessageAdapter=new n.WebsocketMessageAdapter(this.privUri,this.id,this.privMessageFormatter,o,i,s)}async dispose(){this.privIsDisposed=!0,this.privConnectionMessageAdapter&&await this.privConnectionMessageAdapter.close()}isDisposed(){return this.privIsDisposed}get id(){return this.privId}get uri(){return this.privUri}state(){return this.privConnectionMessageAdapter.state}open(){return this.privConnectionMessageAdapter.open()}send(e){return this.privConnectionMessageAdapter.send(e)}read(){return this.privConnectionMessageAdapter.read()}get events(){return this.privConnectionMessageAdapter.events}}})),We=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReplayableAudioNode=void 0,e.ReplayableAudioNode=class{constructor(e,t){this.privBuffers=[],this.privReplayOffset=0,this.privLastShrinkOffset=0,this.privBufferStartOffset=0,this.privBufferSerial=0,this.privBufferedBytes=0,this.privReplay=!1,this.privLastChunkAcquiredTime=0,this.privAudioNode=e,this.privBytesPerSecond=t}id(){return this.privAudioNode.id()}read(){if(this.privReplay&&this.privBuffers.length!==0){let e=this.privReplayOffset-this.privBufferStartOffset,t=Math.round(e*this.privBytesPerSecond*1e-7);t%2!=0&&t++;let n=0;for(;n<this.privBuffers.length&&t>=this.privBuffers[n].chunk.buffer.byteLength;)t-=this.privBuffers[n++].chunk.buffer.byteLength;if(n<this.privBuffers.length){let e=this.privBuffers[n].chunk.buffer.slice(t);return this.privReplayOffset+=e.byteLength/this.privBytesPerSecond*1e7,n===this.privBuffers.length-1&&(this.privReplay=!1),Promise.resolve({buffer:e,isEnd:!1,timeReceived:this.privBuffers[n].chunk.timeReceived})}}return this.privAudioNode.read().then(e=>(e&&e.buffer&&this.privBuffers&&(this.privBuffers.push(new t(e,this.privBufferSerial++,this.privBufferedBytes)),this.privBufferedBytes+=e.buffer.byteLength),e))}detach(){return this.privBuffers=void 0,this.privAudioNode.detach()}replay(){this.privBuffers&&this.privBuffers.length!==0&&(this.privReplay=!0,this.privReplayOffset=this.privLastShrinkOffset)}shrinkBuffers(e){if(this.privBuffers===void 0||this.privBuffers.length===0||e<=this.privLastShrinkOffset)return;this.privLastShrinkOffset=e;let t=e-this.privBufferStartOffset,n=Math.round(t*this.privBytesPerSecond*1e-7),r=0;for(;r<this.privBuffers.length&&n>=this.privBuffers[r].chunk.buffer.byteLength;)n-=this.privBuffers[r++].chunk.buffer.byteLength;this.privBufferStartOffset=Math.round(e-n/this.privBytesPerSecond*1e7),this.privBuffers=this.privBuffers.slice(r)}findTimeAtOffset(e){if(e<this.privBufferStartOffset||this.privBuffers===void 0)return 0;for(let t of this.privBuffers){let n=t.byteOffset/this.privBytesPerSecond*1e7,r=n+t.chunk.buffer.byteLength/this.privBytesPerSecond*1e7;if(e>=n&&e<=r)return t.chunk.timeReceived}return 0}};var t=class{constructor(e,t,n){this.chunk=e,this.serial=t,this.byteOffset=n}}})),z=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.AudioFileWriter=void 0;var i=r(P()),a=F();e.AudioFileWriter=class{constructor(e){a.Contracts.throwIfNullOrUndefined(i.openSync,`
|
|
18
|
+
File System access not available, please use Push or PullAudioOutputStream`),this.privFd=i.openSync(e,`w`)}set format(e){a.Contracts.throwIfNotUndefined(this.privAudioFormat,`format is already set`),this.privAudioFormat=e;let t=0;this.privAudioFormat.hasHeader&&(t=this.privAudioFormat.header.byteLength),this.privFd!==void 0&&(this.privWriteStream=i.createWriteStream(``,{fd:this.privFd,start:t,autoClose:!1}))}write(e){a.Contracts.throwIfNullOrUndefined(this.privAudioFormat,`must set format before writing.`),this.privWriteStream!==void 0&&this.privWriteStream.write(new Uint8Array(e.slice(0)))}close(){this.privFd!==void 0&&(this.privWriteStream.on(`finish`,()=>{this.privAudioFormat.hasHeader&&(this.privAudioFormat.updateHeader(this.privWriteStream.bytesWritten),i.writeSync(this.privFd,new Int8Array(this.privAudioFormat.header),0,this.privAudioFormat.header.byteLength,0)),i.closeSync(this.privFd),this.privFd=void 0}),this.privWriteStream.end())}id(){return this.privId}}})),Ge=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PullAudioInputStreamImpl=e.PullAudioInputStream=e.PushAudioInputStreamImpl=e.PushAudioInputStream=e.AudioInputStream=void 0;var t=Q(),n=k(),r=C(),i=Y(),a=I(),o=class{constructor(){}static createPushStream(e){return s.create(e)}static createPullStream(e,t){return l.create(e,t)}};e.AudioInputStream=o;var s=class extends o{static create(e){return new c(e)}};e.PushAudioInputStream=s;var c=class extends s{constructor(e){super(),this.privFormat=e===void 0?a.AudioStreamFormatImpl.getDefaultInputFormat():e,this.privEvents=new n.EventSource,this.privId=(0,r.createNoDashGuid)(),this.privStream=new n.ChunkedArrayBufferStream(this.privFormat.avgBytesPerSec/10)}get format(){return Promise.resolve(this.privFormat)}write(e){this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}id(){return this.privId}turnOn(){this.onEvent(new n.AudioSourceInitializingEvent(this.privId)),this.onEvent(new n.AudioSourceReadyEvent(this.privId))}async attach(e){this.onEvent(new n.AudioStreamNodeAttachingEvent(this.privId,e)),await this.turnOn();let t=this.privStream;return this.onEvent(new n.AudioStreamNodeAttachedEvent(this.privId,e)),{detach:async()=>(this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)),this.turnOff()),id:()=>e,read:()=>t.read()}}detach(e){this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:t.connectivity.Unknown,manufacturer:`Speech SDK`,model:`PushStream`,samplerate:this.privFormat.samplesPerSec,type:t.type.Stream})}onEvent(e){this.privEvents.onEvent(e),n.Events.instance.onEvent(e)}toBuffer(e){let t=Buffer.alloc(e.byteLength),n=new Uint8Array(e);for(let e=0;e<t.length;++e)t[e]=n[e];return t}};e.PushAudioInputStreamImpl=c;var l=class extends o{constructor(){super()}static create(e,t){return new u(e,t)}};e.PullAudioInputStream=l;var u=class extends l{constructor(e,t){super(),this.privFormat=t===void 0?i.AudioStreamFormat.getDefaultInputFormat():t,this.privEvents=new n.EventSource,this.privId=(0,r.createNoDashGuid)(),this.privCallback=e,this.privIsClosed=!1,this.privBufferSize=this.privFormat.avgBytesPerSec/10}get format(){return Promise.resolve(this.privFormat)}close(){this.privIsClosed=!0,this.privCallback.close()}id(){return this.privId}turnOn(){this.onEvent(new n.AudioSourceInitializingEvent(this.privId)),this.onEvent(new n.AudioSourceReadyEvent(this.privId))}async attach(e){return this.onEvent(new n.AudioStreamNodeAttachingEvent(this.privId,e)),await this.turnOn(),this.onEvent(new n.AudioStreamNodeAttachedEvent(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let e=0,t;for(;e<this.privBufferSize;){let n=new ArrayBuffer(this.privBufferSize-e),r=this.privCallback.read(n);if(t===void 0?t=n:new Int8Array(t).set(new Int8Array(n),e),r===0)break;e+=r}return Promise.resolve({buffer:t.slice(0,e),isEnd:this.privIsClosed||e===0,timeReceived:Date.now()})}}}detach(e){this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:t.connectivity.Unknown,manufacturer:`Speech SDK`,model:`PullStream`,samplerate:this.privFormat.samplesPerSec,type:t.type.Stream})}onEvent(e){this.privEvents.onEvent(e),n.Events.instance.onEvent(e)}};e.PullAudioInputStreamImpl=u})),Ke=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisOutputFormat=void 0,(function(e){e[e.Raw8Khz8BitMonoMULaw=0]=`Raw8Khz8BitMonoMULaw`,e[e.Riff16Khz16KbpsMonoSiren=1]=`Riff16Khz16KbpsMonoSiren`,e[e.Audio16Khz16KbpsMonoSiren=2]=`Audio16Khz16KbpsMonoSiren`,e[e.Audio16Khz32KBitRateMonoMp3=3]=`Audio16Khz32KBitRateMonoMp3`,e[e.Audio16Khz128KBitRateMonoMp3=4]=`Audio16Khz128KBitRateMonoMp3`,e[e.Audio16Khz64KBitRateMonoMp3=5]=`Audio16Khz64KBitRateMonoMp3`,e[e.Audio24Khz48KBitRateMonoMp3=6]=`Audio24Khz48KBitRateMonoMp3`,e[e.Audio24Khz96KBitRateMonoMp3=7]=`Audio24Khz96KBitRateMonoMp3`,e[e.Audio24Khz160KBitRateMonoMp3=8]=`Audio24Khz160KBitRateMonoMp3`,e[e.Raw16Khz16BitMonoTrueSilk=9]=`Raw16Khz16BitMonoTrueSilk`,e[e.Riff16Khz16BitMonoPcm=10]=`Riff16Khz16BitMonoPcm`,e[e.Riff8Khz16BitMonoPcm=11]=`Riff8Khz16BitMonoPcm`,e[e.Riff24Khz16BitMonoPcm=12]=`Riff24Khz16BitMonoPcm`,e[e.Riff8Khz8BitMonoMULaw=13]=`Riff8Khz8BitMonoMULaw`,e[e.Raw16Khz16BitMonoPcm=14]=`Raw16Khz16BitMonoPcm`,e[e.Raw24Khz16BitMonoPcm=15]=`Raw24Khz16BitMonoPcm`,e[e.Raw8Khz16BitMonoPcm=16]=`Raw8Khz16BitMonoPcm`,e[e.Ogg16Khz16BitMonoOpus=17]=`Ogg16Khz16BitMonoOpus`,e[e.Ogg24Khz16BitMonoOpus=18]=`Ogg24Khz16BitMonoOpus`,e[e.Raw48Khz16BitMonoPcm=19]=`Raw48Khz16BitMonoPcm`,e[e.Riff48Khz16BitMonoPcm=20]=`Riff48Khz16BitMonoPcm`,e[e.Audio48Khz96KBitRateMonoMp3=21]=`Audio48Khz96KBitRateMonoMp3`,e[e.Audio48Khz192KBitRateMonoMp3=22]=`Audio48Khz192KBitRateMonoMp3`,e[e.Ogg48Khz16BitMonoOpus=23]=`Ogg48Khz16BitMonoOpus`,e[e.Webm16Khz16BitMonoOpus=24]=`Webm16Khz16BitMonoOpus`,e[e.Webm24Khz16BitMonoOpus=25]=`Webm24Khz16BitMonoOpus`,e[e.Raw24Khz16BitMonoTrueSilk=26]=`Raw24Khz16BitMonoTrueSilk`,e[e.Raw8Khz8BitMonoALaw=27]=`Raw8Khz8BitMonoALaw`,e[e.Riff8Khz8BitMonoALaw=28]=`Riff8Khz8BitMonoALaw`,e[e.Webm24Khz16Bit24KbpsMonoOpus=29]=`Webm24Khz16Bit24KbpsMonoOpus`,e[e.Audio16Khz16Bit32KbpsMonoOpus=30]=`Audio16Khz16Bit32KbpsMonoOpus`,e[e.Audio24Khz16Bit48KbpsMonoOpus=31]=`Audio24Khz16Bit48KbpsMonoOpus`,e[e.Audio24Khz16Bit24KbpsMonoOpus=32]=`Audio24Khz16Bit24KbpsMonoOpus`,e[e.Raw22050Hz16BitMonoPcm=33]=`Raw22050Hz16BitMonoPcm`,e[e.Riff22050Hz16BitMonoPcm=34]=`Riff22050Hz16BitMonoPcm`,e[e.Raw44100Hz16BitMonoPcm=35]=`Raw44100Hz16BitMonoPcm`,e[e.Riff44100Hz16BitMonoPcm=36]=`Riff44100Hz16BitMonoPcm`,e[e.AmrWb16000Hz=37]=`AmrWb16000Hz`,e[e.G72216Khz64Kbps=38]=`G72216Khz64Kbps`})(e.SpeechSynthesisOutputFormat||={})})),B=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AudioOutputFormatImpl=void 0;var t=Ke(),n=I(),r=class e extends n.AudioStreamFormatImpl{constructor(e,t,n,r,i,a,o,s,c){super(n,a,t,e),this.formatTag=e,this.avgBytesPerSec=r,this.blockAlign=i,this.priAudioFormatString=o,this.priRequestAudioFormatString=s,this.priHasHeader=c}static fromSpeechSynthesisOutputFormat(t){return t===void 0?e.getDefaultOutputFormat():e.fromSpeechSynthesisOutputFormatString(e.SpeechSynthesisOutputFormatToString[t])}static fromSpeechSynthesisOutputFormatString(t){switch(t){case`raw-8khz-8bit-mono-mulaw`:return new e(n.AudioFormatTag.MuLaw,1,8e3,8e3,1,8,t,t,!1);case`riff-16khz-16kbps-mono-siren`:return new e(n.AudioFormatTag.Siren,1,16e3,2e3,40,0,t,`audio-16khz-16kbps-mono-siren`,!0);case`audio-16khz-16kbps-mono-siren`:return new e(n.AudioFormatTag.Siren,1,16e3,2e3,40,0,t,t,!1);case`audio-16khz-32kbitrate-mono-mp3`:return new e(n.AudioFormatTag.MP3,1,16e3,4096,2,16,t,t,!1);case`audio-16khz-128kbitrate-mono-mp3`:return new e(n.AudioFormatTag.MP3,1,16e3,16384,2,16,t,t,!1);case`audio-16khz-64kbitrate-mono-mp3`:return new e(n.AudioFormatTag.MP3,1,16e3,8192,2,16,t,t,!1);case`audio-24khz-48kbitrate-mono-mp3`:return new e(n.AudioFormatTag.MP3,1,24e3,6144,2,16,t,t,!1);case`audio-24khz-96kbitrate-mono-mp3`:return new e(n.AudioFormatTag.MP3,1,24e3,12288,2,16,t,t,!1);case`audio-24khz-160kbitrate-mono-mp3`:return new e(n.AudioFormatTag.MP3,1,24e3,20480,2,16,t,t,!1);case`raw-16khz-16bit-mono-truesilk`:return new e(n.AudioFormatTag.SILKSkype,1,16e3,32e3,2,16,t,t,!1);case`riff-8khz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,8e3,16e3,2,16,t,`raw-8khz-16bit-mono-pcm`,!0);case`riff-24khz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,24e3,48e3,2,16,t,`raw-24khz-16bit-mono-pcm`,!0);case`riff-8khz-8bit-mono-mulaw`:return new e(n.AudioFormatTag.MuLaw,1,8e3,8e3,1,8,t,`raw-8khz-8bit-mono-mulaw`,!0);case`raw-16khz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,16e3,32e3,2,16,t,`raw-16khz-16bit-mono-pcm`,!1);case`raw-24khz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,24e3,48e3,2,16,t,`raw-24khz-16bit-mono-pcm`,!1);case`raw-8khz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,8e3,16e3,2,16,t,`raw-8khz-16bit-mono-pcm`,!1);case`ogg-16khz-16bit-mono-opus`:return new e(n.AudioFormatTag.OGG_OPUS,1,16e3,8192,2,16,t,t,!1);case`ogg-24khz-16bit-mono-opus`:return new e(n.AudioFormatTag.OGG_OPUS,1,24e3,8192,2,16,t,t,!1);case`raw-48khz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,48e3,96e3,2,16,t,`raw-48khz-16bit-mono-pcm`,!1);case`riff-48khz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,48e3,96e3,2,16,t,`raw-48khz-16bit-mono-pcm`,!0);case`audio-48khz-96kbitrate-mono-mp3`:return new e(n.AudioFormatTag.MP3,1,48e3,12288,2,16,t,t,!1);case`audio-48khz-192kbitrate-mono-mp3`:return new e(n.AudioFormatTag.MP3,1,48e3,24576,2,16,t,t,!1);case`ogg-48khz-16bit-mono-opus`:return new e(n.AudioFormatTag.OGG_OPUS,1,48e3,12e3,2,16,t,t,!1);case`webm-16khz-16bit-mono-opus`:return new e(n.AudioFormatTag.WEBM_OPUS,1,16e3,4e3,2,16,t,t,!1);case`webm-24khz-16bit-mono-opus`:return new e(n.AudioFormatTag.WEBM_OPUS,1,24e3,6e3,2,16,t,t,!1);case`webm-24khz-16bit-24kbps-mono-opus`:return new e(n.AudioFormatTag.WEBM_OPUS,1,24e3,3e3,2,16,t,t,!1);case`audio-16khz-16bit-32kbps-mono-opus`:return new e(n.AudioFormatTag.OPUS,1,16e3,4e3,2,16,t,t,!1);case`audio-24khz-16bit-48kbps-mono-opus`:return new e(n.AudioFormatTag.OPUS,1,24e3,6e3,2,16,t,t,!1);case`audio-24khz-16bit-24kbps-mono-opus`:return new e(n.AudioFormatTag.OPUS,1,24e3,3e3,2,16,t,t,!1);case`audio-24khz-16bit-mono-flac`:return new e(n.AudioFormatTag.FLAC,1,24e3,24e3,2,16,t,t,!1);case`audio-48khz-16bit-mono-flac`:return new e(n.AudioFormatTag.FLAC,1,48e3,3e4,2,16,t,t,!1);case`raw-24khz-16bit-mono-truesilk`:return new e(n.AudioFormatTag.SILKSkype,1,24e3,48e3,2,16,t,t,!1);case`raw-8khz-8bit-mono-alaw`:return new e(n.AudioFormatTag.ALaw,1,8e3,8e3,1,8,t,t,!1);case`riff-8khz-8bit-mono-alaw`:return new e(n.AudioFormatTag.ALaw,1,8e3,8e3,1,8,t,`raw-8khz-8bit-mono-alaw`,!0);case`raw-22050hz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,22050,44100,2,16,t,t,!1);case`riff-22050hz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,22050,44100,2,16,t,`raw-22050hz-16bit-mono-pcm`,!0);case`raw-44100hz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,44100,88200,2,16,t,t,!1);case`riff-44100hz-16bit-mono-pcm`:return new e(n.AudioFormatTag.PCM,1,44100,88200,2,16,t,`raw-44100hz-16bit-mono-pcm`,!0);case`amr-wb-16000h`:return new e(n.AudioFormatTag.AMR_WB,1,16e3,3052,2,16,t,t,!1);case`g722-16khz-64kbps`:return new e(n.AudioFormatTag.G722,1,16e3,8e3,2,16,t,t,!1);default:return new e(n.AudioFormatTag.PCM,1,16e3,32e3,2,16,`riff-16khz-16bit-mono-pcm`,`raw-16khz-16bit-mono-pcm`,!0)}}static getDefaultOutputFormat(){return e.fromSpeechSynthesisOutputFormatString(typeof window<`u`?`audio-24khz-48kbitrate-mono-mp3`:`riff-16khz-16bit-mono-pcm`)}get hasHeader(){return this.priHasHeader}get header(){if(this.hasHeader)return this.privHeader}updateHeader(e){if(this.priHasHeader){let t=new DataView(this.privHeader);t.setUint32(4,e+this.privHeader.byteLength-8,!0),t.setUint32(40,e,!0)}}get requestAudioFormatString(){return this.priRequestAudioFormatString}addHeader(e){if(!this.hasHeader)return e;this.updateHeader(e.byteLength);let t=new Uint8Array(e.byteLength+this.header.byteLength);return t.set(new Uint8Array(this.header),0),t.set(new Uint8Array(e),this.header.byteLength),t.buffer}};e.AudioOutputFormatImpl=r,r.SpeechSynthesisOutputFormatToString={[t.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw]:`raw-8khz-8bit-mono-mulaw`,[t.SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren]:`riff-16khz-16kbps-mono-siren`,[t.SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren]:`audio-16khz-16kbps-mono-siren`,[t.SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3]:`audio-16khz-32kbitrate-mono-mp3`,[t.SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3]:`audio-16khz-128kbitrate-mono-mp3`,[t.SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3]:`audio-16khz-64kbitrate-mono-mp3`,[t.SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3]:`audio-24khz-48kbitrate-mono-mp3`,[t.SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3]:`audio-24khz-96kbitrate-mono-mp3`,[t.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3]:`audio-24khz-160kbitrate-mono-mp3`,[t.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk]:`raw-16khz-16bit-mono-truesilk`,[t.SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm]:`riff-16khz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm]:`riff-8khz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm]:`riff-24khz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw]:`riff-8khz-8bit-mono-mulaw`,[t.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm]:`raw-16khz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm]:`raw-24khz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm]:`raw-8khz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus]:`ogg-16khz-16bit-mono-opus`,[t.SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus]:`ogg-24khz-16bit-mono-opus`,[t.SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm]:`raw-48khz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm]:`riff-48khz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3]:`audio-48khz-96kbitrate-mono-mp3`,[t.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3]:`audio-48khz-192kbitrate-mono-mp3`,[t.SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus]:`ogg-48khz-16bit-mono-opus`,[t.SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus]:`webm-16khz-16bit-mono-opus`,[t.SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus]:`webm-24khz-16bit-mono-opus`,[t.SpeechSynthesisOutputFormat.Webm24Khz16Bit24KbpsMonoOpus]:`webm-24khz-16bit-24kbps-mono-opus`,[t.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk]:`raw-24khz-16bit-mono-truesilk`,[t.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw]:`raw-8khz-8bit-mono-alaw`,[t.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw]:`riff-8khz-8bit-mono-alaw`,[t.SpeechSynthesisOutputFormat.Audio16Khz16Bit32KbpsMonoOpus]:`audio-16khz-16bit-32kbps-mono-opus`,[t.SpeechSynthesisOutputFormat.Audio24Khz16Bit48KbpsMonoOpus]:`audio-24khz-16bit-48kbps-mono-opus`,[t.SpeechSynthesisOutputFormat.Audio24Khz16Bit24KbpsMonoOpus]:`audio-24khz-16bit-24kbps-mono-opus`,[t.SpeechSynthesisOutputFormat.Raw22050Hz16BitMonoPcm]:`raw-22050hz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Riff22050Hz16BitMonoPcm]:`riff-22050hz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Raw44100Hz16BitMonoPcm]:`raw-44100hz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.Riff44100Hz16BitMonoPcm]:`riff-44100hz-16bit-mono-pcm`,[t.SpeechSynthesisOutputFormat.AmrWb16000Hz]:`amr-wb-16000hz`,[t.SpeechSynthesisOutputFormat.G72216Khz64Kbps]:`g722-16khz-64kbps`}})),V=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PushAudioOutputStreamImpl=e.PushAudioOutputStream=e.PullAudioOutputStreamImpl=e.PullAudioOutputStream=e.AudioOutputStream=void 0;var t=k(),n=F(),r=B(),i=class{constructor(){}static createPullStream(){return a.create()}};e.AudioOutputStream=i;var a=class extends i{static create(){return new o}};e.PullAudioOutputStream=a;var o=class extends a{constructor(){super(),this.privId=(0,t.createNoDashGuid)(),this.privStream=new t.Stream}set format(e){e??(this.privFormat=r.AudioOutputFormatImpl.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}async read(e){let t=new Int8Array(e),n=0;if(this.privLastChunkView!==void 0){if(this.privLastChunkView.length>e.byteLength)return t.set(this.privLastChunkView.slice(0,e.byteLength)),this.privLastChunkView=this.privLastChunkView.slice(e.byteLength),Promise.resolve(e.byteLength);t.set(this.privLastChunkView),n=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;n<e.byteLength&&!this.privStream.isReadEnded;){let r=await this.privStream.read();if(r!==void 0&&!r.isEnd){let i;r.buffer.byteLength>e.byteLength-n?(i=r.buffer.slice(0,e.byteLength-n),this.privLastChunkView=new Int8Array(r.buffer.slice(e.byteLength-n))):i=r.buffer,t.set(new Int8Array(i),n),n+=i.byteLength}else this.privStream.readEnded()}return n}write(e){n.Contracts.throwIfNullOrUndefined(this.privStream,`must set format before writing`),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}};e.PullAudioOutputStreamImpl=o;var s=class extends i{constructor(){super()}static create(e){return new c(e)}};e.PushAudioOutputStream=s;var c=class extends s{constructor(e){super(),this.privId=(0,t.createNoDashGuid)(),this.privCallback=e}set format(e){}write(e){this.privCallback.write&&this.privCallback.write(e)}close(){this.privCallback.close&&this.privCallback.close()}id(){return this.privId}};e.PushAudioOutputStreamImpl=c})),qe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AudioOutputConfigImpl=e.AudioConfigImpl=e.AudioConfig=void 0;var t=X(),n=F(),r=Y(),i=z(),a=Ge(),o=V(),s=class e{static fromDefaultMicrophoneInput(){let e=new t.PcmRecorder(!0);return new c(new t.MicAudioSource(e))}static fromMicrophoneInput(e){let n=new t.PcmRecorder(!0);return new c(new t.MicAudioSource(n,e))}static fromWavFileInput(e,n=`unnamedBuffer.wav`){return new c(new t.FileAudioSource(e,n))}static fromStreamInput(e){if(e instanceof r.PullAudioInputStreamCallback)return new c(new a.PullAudioInputStreamImpl(e));if(e instanceof r.AudioInputStream)return new c(e);if(typeof MediaStream<`u`&&e instanceof MediaStream){let n=new t.PcmRecorder(!1);return new c(new t.MicAudioSource(n,null,null,e))}throw Error(`Not Supported Type`)}static fromDefaultSpeakerOutput(){return new l(new r.SpeakerAudioDestination)}static fromSpeakerOutput(t){if(t===void 0)return e.fromDefaultSpeakerOutput();if(t instanceof r.SpeakerAudioDestination)return new l(t);throw Error(`Not Supported Type`)}static fromAudioFileOutput(e){return new l(new i.AudioFileWriter(e))}static fromStreamOutput(e){if(e instanceof r.PushAudioOutputStreamCallback)return new l(new o.PushAudioOutputStreamImpl(e));if(e instanceof r.PushAudioOutputStream||e instanceof r.PullAudioOutputStream)return new l(e);throw Error(`Not Supported Type`)}};e.AudioConfig=s;var c=class extends s{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then(()=>{e&&e()},e=>{t&&t(e)})}id(){return this.privSource.id()}turnOn(){return this.privSource.turnOn()}attach(e){return this.privSource.attach(e)}detach(e){return this.privSource.detach(e)}turnOff(){return this.privSource.turnOff()}get events(){return this.privSource.events}setProperty(e,t){if(n.Contracts.throwIfNull(t,`value`),this.privSource.setProperty!==void 0)this.privSource.setProperty(e,t);else throw Error(`This AudioConfig instance does not support setting properties.`)}getProperty(e,t){if(this.privSource.getProperty!==void 0)return this.privSource.getProperty(e,t);throw Error(`This AudioConfig instance does not support getting properties.`)}get deviceInfo(){return this.privSource.deviceInfo}};e.AudioConfigImpl=c;var l=class extends s{constructor(e){super(),this.privDestination=e}set format(e){this.privDestination.format=e}write(e){this.privDestination.write(e)}close(){this.privDestination.close()}id(){return this.privDestination.id()}setProperty(){throw Error(`This AudioConfig instance does not support setting properties.`)}getProperty(){throw Error(`This AudioConfig instance does not support getting properties.`)}};e.AudioOutputConfigImpl=l})),Je=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationReason=void 0,(function(e){e[e.Error=0]=`Error`,e[e.EndOfStream=1]=`EndOfStream`})(e.CancellationReason||={})})),Ye=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PullAudioInputStreamCallback=void 0,e.PullAudioInputStreamCallback=class{}})),Xe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PushAudioOutputStreamCallback=void 0,e.PushAudioOutputStreamCallback=class{}})),Ze=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.KeywordRecognitionModel=void 0;var t=F();e.KeywordRecognitionModel=class{constructor(){this.privDisposed=!1}static fromFile(e){throw t.Contracts.throwIfFileDoesNotExist(e,`fileName`),Error(`Not yet implemented.`)}static fromStream(e){throw t.Contracts.throwIfNull(e,`file`),Error(`Not yet implemented.`)}close(){this.privDisposed||=!0}}})),Qe=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SessionEventArgs=void 0,e.SessionEventArgs=class{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}})),$e=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RecognitionEventArgs=void 0;var t=Y();e.RecognitionEventArgs=class extends t.SessionEventArgs{constructor(e,t){super(t),this.privOffset=e}get offset(){return this.privOffset}}})),et=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OutputFormat=void 0,(function(e){e[e.Simple=0]=`Simple`,e[e.Detailed=1]=`Detailed`})(e.OutputFormat||={})})),tt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RecognitionResult=void 0,e.RecognitionResult=class{constructor(e,t,n,r,i,a,o,s,c,l,u){this.privResultId=e,this.privReason=t,this.privText=n,this.privDuration=r,this.privOffset=i,this.privLanguage=a,this.privLanguageDetectionConfidence=o,this.privErrorDetails=s,this.privJson=c,this.privProperties=l,this.privChannel=u===void 0?0:u}get resultId(){return this.privResultId}get reason(){return this.privReason}get text(){return this.privText}get duration(){return this.privDuration}get offset(){return this.privOffset}get language(){return this.privLanguage}get languageDetectionConfidence(){return this.privLanguageDetectionConfidence}get errorDetails(){return this.privErrorDetails}get json(){return this.privJson}get properties(){return this.privProperties}get channel(){return this.privChannel}}})),nt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechRecognitionResult=void 0;var t=Y();e.SpeechRecognitionResult=class extends t.RecognitionResult{constructor(e,t,n,r,i,a,o,s,c,l,u,d){super(e,t,n,r,i,a,o,c,l,u,d),this.privSpeakerId=s}get speakerId(){return this.privSpeakerId}}})),rt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MeetingTranscriptionEventArgs=e.ConversationTranscriptionEventArgs=e.SpeechRecognitionEventArgs=void 0;var t=Y(),n=class extends t.RecognitionEventArgs{constructor(e,t,n){super(t,n),this.privResult=e}get result(){return this.privResult}};e.SpeechRecognitionEventArgs=n,e.ConversationTranscriptionEventArgs=class extends t.RecognitionEventArgs{constructor(e,t,n){super(t,n),this.privResult=e}get result(){return this.privResult}},e.MeetingTranscriptionEventArgs=class extends n{}})),H=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationEventArgsBase=void 0;var t=Y();e.CancellationEventArgsBase=class extends t.RecognitionEventArgs{constructor(e,t,n,r,i){super(r,i),this.privReason=e,this.privErrorDetails=t,this.privErrorCode=n}get reason(){return this.privReason}get errorCode(){return this.privErrorCode}get errorDetails(){return this.privErrorDetails}}})),it=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechRecognitionCanceledEventArgs=void 0;var t=H();e.SpeechRecognitionCanceledEventArgs=class extends t.CancellationEventArgsBase{}})),at=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationRecognitionEventArgs=void 0;var t=Y();e.TranslationRecognitionEventArgs=class extends t.RecognitionEventArgs{constructor(e,t,n){super(t,n),this.privResult=e}get result(){return this.privResult}}})),ot=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationSynthesisEventArgs=void 0;var t=Y();e.TranslationSynthesisEventArgs=class extends t.SessionEventArgs{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}})),st=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationRecognitionResult=void 0;var t=Y();e.TranslationRecognitionResult=class e extends t.SpeechRecognitionResult{constructor(e,t,n,r,i,a,o,s,c,l,u){super(t,n,r,i,a,o,s,void 0,c,l,u),this.privTranslations=e}static fromSpeechRecognitionResult(t){return new e(void 0,t.resultId,t.reason,t.text,t.duration,t.offset,t.language,t.languageDetectionConfidence,t.errorDetails,t.json,t.properties)}get translations(){return this.privTranslations}}})),ct=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationSynthesisResult=void 0,e.TranslationSynthesisResult=class{constructor(e,t){this.privReason=e,this.privAudio=t}get audio(){return this.privAudio}get reason(){return this.privReason}}})),lt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ResultReason=void 0,(function(e){e[e.NoMatch=0]=`NoMatch`,e[e.Canceled=1]=`Canceled`,e[e.RecognizingSpeech=2]=`RecognizingSpeech`,e[e.RecognizedSpeech=3]=`RecognizedSpeech`,e[e.RecognizedKeyword=4]=`RecognizedKeyword`,e[e.TranslatingSpeech=5]=`TranslatingSpeech`,e[e.TranslatedSpeech=6]=`TranslatedSpeech`,e[e.SynthesizingAudio=7]=`SynthesizingAudio`,e[e.SynthesizingAudioCompleted=8]=`SynthesizingAudioCompleted`,e[e.SynthesizingAudioStarted=9]=`SynthesizingAudioStarted`,e[e.VoicesListRetrieved=10]=`VoicesListRetrieved`,e[e.TranslatingParticipantSpeech=11]=`TranslatingParticipantSpeech`,e[e.TranslatedParticipantSpeech=12]=`TranslatedParticipantSpeech`,e[e.TranslatedInstantMessage=13]=`TranslatedInstantMessage`,e[e.TranslatedParticipantInstantMessage=14]=`TranslatedParticipantInstantMessage`})(e.ResultReason||={})})),ut=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechConfigImpl=e.SpeechConfig=void 0;var t=Q(),n=F(),r=Y(),i=class{constructor(){}static fromSubscription(e,t){n.Contracts.throwIfNullOrWhitespace(e,`subscriptionKey`),n.Contracts.throwIfNullOrWhitespace(t,`region`);let i=new a;return i.setProperty(r.PropertyId.SpeechServiceConnection_Region,t),i.setProperty(r.PropertyId.SpeechServiceConnection_Key,e),i}static fromEndpoint(e,t){n.Contracts.throwIfNull(e,`endpoint`);let i=typeof t==`string`&&t.trim().length>0,o=typeof t==`object`&&!!t&&typeof t.getToken==`function`,s=typeof t==`object`&&!!t&&typeof t.key==`string`;if(t!==void 0&&!i&&!o&&!s)throw Error(`Invalid 'auth' parameter: expected a non-empty API key string, a TokenCredential, or a KeyCredential.`);let c;return typeof t==`string`?(c=new a,c.setProperty(r.PropertyId.SpeechServiceConnection_Key,t)):typeof t==`object`&&typeof t.getToken==`function`?c=new a(t):typeof t==`object`&&typeof t.key==`string`?(c=new a,c.setProperty(r.PropertyId.SpeechServiceConnection_Key,t.key)):c=new a,c.setProperty(r.PropertyId.SpeechServiceConnection_Endpoint,e.href),c}static fromHost(e,t){n.Contracts.throwIfNull(e,`hostName`);let i=new a;return i.setProperty(r.PropertyId.SpeechServiceConnection_Host,e.protocol+`//`+e.hostname+(e.port===``?``:`:`+e.port)),i.setProperty(r.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,`1`),t!==void 0&&i.setProperty(r.PropertyId.SpeechServiceConnection_Key,t),i}static fromAuthorizationToken(e,t){n.Contracts.throwIfNull(e,`authorizationToken`),n.Contracts.throwIfNullOrWhitespace(t,`region`);let i=new a;return i.setProperty(r.PropertyId.SpeechServiceConnection_Region,t),i.authorizationToken=e,i}close(){}};e.SpeechConfig=i;var a=class e extends i{constructor(e){super(),this.privProperties=new r.PropertyCollection,this.speechRecognitionLanguage=`en-US`,this.outputFormat=r.OutputFormat.Simple,this.privTokenCredential=e}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(r.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(r.PropertyId.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return r.OutputFormat[this.privProperties.getProperty(t.OutputFormatPropertyName,void 0)]}set outputFormat(e){this.privProperties.setProperty(t.OutputFormatPropertyName,r.OutputFormat[e])}get endpointId(){return this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_EndpointId,e)}get tokenCredential(){return this.privTokenCredential}setProperty(e,t){n.Contracts.throwIfNull(t,`value`),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,n,i){this.setProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_ProxyHostName],e),this.setProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_ProxyPort],t),this.setProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_ProxyUserName],n),this.setProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_ProxyPassword],i)}setServiceProperty(e,n){let r=JSON.parse(this.privProperties.getProperty(t.ServicePropertiesPropertyName,`{}`));r[e]=n,this.privProperties.setProperty(t.ServicePropertiesPropertyName,JSON.stringify(r))}setProfanity(e){this.privProperties.setProperty(r.PropertyId.SpeechServiceResponse_ProfanityOption,r.ProfanityOption[e])}enableAudioLogging(){this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_EnableAudioLogging,`true`)}requestWordLevelTimestamps(){this.privProperties.setProperty(r.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,`true`),this.privProperties.setProperty(t.OutputFormatPropertyName,r.OutputFormat[r.OutputFormat.Detailed])}enableDictation(){this.privProperties.setProperty(t.ForceDictationPropertyName,`true`)}clone(){let t=new e(this.tokenCredential);return t.privProperties=this.privProperties.clone(),t}get speechSynthesisLanguage(){return this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return r.SpeechSynthesisOutputFormat[this.privProperties.getProperty(r.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_SynthOutputFormat,r.SpeechSynthesisOutputFormat[e])}};e.SpeechConfigImpl=a})),dt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechTranslationConfigImpl=e.SpeechTranslationConfig=void 0;var t=Q(),n=F(),r=Y(),i=class extends r.SpeechConfig{constructor(){super()}static fromSubscription(e,t){n.Contracts.throwIfNullOrWhitespace(e,`subscriptionKey`),n.Contracts.throwIfNullOrWhitespace(t,`region`);let i=new a;return i.properties.setProperty(r.PropertyId.SpeechServiceConnection_Key,e),i.properties.setProperty(r.PropertyId.SpeechServiceConnection_Region,t),i}static fromAuthorizationToken(e,t){n.Contracts.throwIfNullOrWhitespace(e,`authorizationToken`),n.Contracts.throwIfNullOrWhitespace(t,`region`);let i=new a;return i.properties.setProperty(r.PropertyId.SpeechServiceAuthorization_Token,e),i.properties.setProperty(r.PropertyId.SpeechServiceConnection_Region,t),i}static fromHost(e,t){n.Contracts.throwIfNull(e,`hostName`);let i=new a;return i.setProperty(r.PropertyId.SpeechServiceConnection_Host,e.protocol+`//`+e.hostname+(e.port===``?``:`:`+e.port)),t!==void 0&&i.setProperty(r.PropertyId.SpeechServiceConnection_Key,t),i}static fromEndpoint(e,t){n.Contracts.throwIfNull(e,`endpoint`);let i=typeof t==`string`&&t.trim().length>0,o=typeof t==`object`&&!!t&&typeof t.getToken==`function`,s=typeof t==`object`&&!!t&&typeof t.key==`string`;if(t!==void 0&&!i&&!o&&!s)throw Error(`Invalid 'auth' parameter: expected a non-empty API key string, a TokenCredential, or a KeyCredential.`);let c;return typeof t==`string`?(c=new a,c.setProperty(r.PropertyId.SpeechServiceConnection_Key,t)):typeof t==`object`&&typeof t.getToken==`function`?c=new a(t):typeof t==`object`&&typeof t.key==`string`?(c=new a,c.setProperty(r.PropertyId.SpeechServiceConnection_Key,t.key)):c=new a,c.setProperty(r.PropertyId.SpeechServiceConnection_Endpoint,e.href),c}};e.SpeechTranslationConfig=i;var a=class extends i{constructor(e){super(),this.privSpeechProperties=new r.PropertyCollection,this.outputFormat=r.OutputFormat.Simple,this.privTokenCredential=e}set authorizationToken(e){n.Contracts.throwIfNullOrWhitespace(e,`value`),this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceAuthorization_Token,e)}set speechRecognitionLanguage(e){n.Contracts.throwIfNullOrWhitespace(e,`value`),this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage,e)}get speechRecognitionLanguage(){return this.privSpeechProperties.getProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_RecoLanguage])}get subscriptionKey(){return this.privSpeechProperties.getProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_Key])}get outputFormat(){return r.OutputFormat[this.privSpeechProperties.getProperty(t.OutputFormatPropertyName,void 0)]}set outputFormat(e){this.privSpeechProperties.setProperty(t.OutputFormatPropertyName,r.OutputFormat[e])}get endpointId(){return this.privSpeechProperties.getProperty(r.PropertyId.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceConnection_EndpointId,e)}addTargetLanguage(e){n.Contracts.throwIfNullOrWhitespace(e,`value`);let t=this.targetLanguages;t.includes(e)||(t.push(e),this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceConnection_TranslationToLanguages,t.join(`,`)))}get targetLanguages(){return this.privSpeechProperties.getProperty(r.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0)===void 0?[]:this.privSpeechProperties.getProperty(r.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(`,`)}get voiceName(){return this.getProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_TranslationVoice])}set voiceName(e){n.Contracts.throwIfNullOrWhitespace(e,`value`),this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceConnection_TranslationVoice,e)}get region(){return this.privSpeechProperties.getProperty(r.PropertyId.SpeechServiceConnection_Region)}get tokenCredential(){return this.privTokenCredential}setProxy(e,t,n,i){this.setProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_ProxyHostName],e),this.setProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_ProxyPort],t),this.setProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_ProxyUserName],n),this.setProperty(r.PropertyId[r.PropertyId.SpeechServiceConnection_ProxyPassword],i)}getProperty(e,t){return this.privSpeechProperties.getProperty(e,t)}setProperty(e,t){this.privSpeechProperties.setProperty(e,t)}get properties(){return this.privSpeechProperties}close(){}setServiceProperty(e,n){let r=JSON.parse(this.privSpeechProperties.getProperty(t.ServicePropertiesPropertyName,`{}`));r[e]=n,this.privSpeechProperties.setProperty(t.ServicePropertiesPropertyName,JSON.stringify(r))}setProfanity(e){this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceResponse_ProfanityOption,r.ProfanityOption[e])}enableAudioLogging(){this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceConnection_EnableAudioLogging,`true`)}requestWordLevelTimestamps(){this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,`true`)}enableDictation(){this.privSpeechProperties.setProperty(t.ForceDictationPropertyName,`true`)}get speechSynthesisLanguage(){return this.privSpeechProperties.getProperty(r.PropertyId.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privSpeechProperties.getProperty(r.PropertyId.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return r.SpeechSynthesisOutputFormat[this.privSpeechProperties.getProperty(r.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privSpeechProperties.setProperty(r.PropertyId.SpeechServiceConnection_SynthOutputFormat,r.SpeechSynthesisOutputFormat[e])}};e.SpeechTranslationConfigImpl=a})),ft=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PropertyCollection=void 0;var t=Y();e.PropertyCollection=class e{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,n){let r;r=typeof e==`string`?e:t.PropertyId[e];for(let e=0;e<this.privKeys.length;e++)if(this.privKeys[e]===r)return this.privValues[e];if(n!==void 0)return String(n)}setProperty(e,n){let r;r=typeof e==`string`?e:t.PropertyId[e];for(let e=0;e<this.privKeys.length;e++)if(this.privKeys[e]===r){this.privValues[e]=n;return}this.privKeys.push(r),this.privValues.push(n)}clone(){let t=new e;for(let e=0;e<this.privKeys.length;e++)t.privKeys.push(this.privKeys[e]),t.privValues.push(this.privValues[e]);return t}mergeTo(e){this.privKeys.forEach(t=>{if(e.getProperty(t,void 0)===void 0){let n=this.getProperty(t);e.setProperty(t,n)}})}get keys(){return this.privKeys}}})),U=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PropertyId=void 0,(function(e){e[e.SpeechServiceConnection_Key=0]=`SpeechServiceConnection_Key`,e[e.SpeechServiceConnection_Endpoint=1]=`SpeechServiceConnection_Endpoint`,e[e.SpeechServiceConnection_Region=2]=`SpeechServiceConnection_Region`,e[e.SpeechServiceAuthorization_Token=3]=`SpeechServiceAuthorization_Token`,e[e.SpeechServiceAuthorization_Type=4]=`SpeechServiceAuthorization_Type`,e[e.SpeechServiceConnection_EndpointId=5]=`SpeechServiceConnection_EndpointId`,e[e.SpeechServiceConnection_TranslationToLanguages=6]=`SpeechServiceConnection_TranslationToLanguages`,e[e.SpeechServiceConnection_TranslationVoice=7]=`SpeechServiceConnection_TranslationVoice`,e[e.SpeechServiceConnection_TranslationFeatures=8]=`SpeechServiceConnection_TranslationFeatures`,e[e.SpeechServiceConnection_TranslationCategoryId=9]=`SpeechServiceConnection_TranslationCategoryId`,e[e.SpeechServiceConnection_ProxyHostName=10]=`SpeechServiceConnection_ProxyHostName`,e[e.SpeechServiceConnection_ProxyPort=11]=`SpeechServiceConnection_ProxyPort`,e[e.SpeechServiceConnection_ProxyUserName=12]=`SpeechServiceConnection_ProxyUserName`,e[e.SpeechServiceConnection_ProxyPassword=13]=`SpeechServiceConnection_ProxyPassword`,e[e.SpeechServiceConnection_RecoMode=14]=`SpeechServiceConnection_RecoMode`,e[e.SpeechServiceConnection_RecoLanguage=15]=`SpeechServiceConnection_RecoLanguage`,e[e.Speech_SessionId=16]=`Speech_SessionId`,e[e.SpeechServiceConnection_SynthLanguage=17]=`SpeechServiceConnection_SynthLanguage`,e[e.SpeechServiceConnection_SynthVoice=18]=`SpeechServiceConnection_SynthVoice`,e[e.SpeechServiceConnection_SynthOutputFormat=19]=`SpeechServiceConnection_SynthOutputFormat`,e[e.SpeechServiceConnection_AutoDetectSourceLanguages=20]=`SpeechServiceConnection_AutoDetectSourceLanguages`,e[e.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]=`SpeechServiceResponse_RequestDetailedResultTrueFalse`,e[e.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]=`SpeechServiceResponse_RequestProfanityFilterTrueFalse`,e[e.SpeechServiceResponse_JsonResult=23]=`SpeechServiceResponse_JsonResult`,e[e.SpeechServiceResponse_JsonErrorDetails=24]=`SpeechServiceResponse_JsonErrorDetails`,e[e.CancellationDetails_Reason=25]=`CancellationDetails_Reason`,e[e.CancellationDetails_ReasonText=26]=`CancellationDetails_ReasonText`,e[e.CancellationDetails_ReasonDetailedText=27]=`CancellationDetails_ReasonDetailedText`,e[e.SpeechServiceConnection_Url=28]=`SpeechServiceConnection_Url`,e[e.SpeechServiceConnection_InitialSilenceTimeoutMs=29]=`SpeechServiceConnection_InitialSilenceTimeoutMs`,e[e.SpeechServiceConnection_EndSilenceTimeoutMs=30]=`SpeechServiceConnection_EndSilenceTimeoutMs`,e[e.Speech_SegmentationSilenceTimeoutMs=31]=`Speech_SegmentationSilenceTimeoutMs`,e[e.Speech_SegmentationMaximumTimeMs=32]=`Speech_SegmentationMaximumTimeMs`,e[e.Speech_SegmentationStrategy=33]=`Speech_SegmentationStrategy`,e[e.Speech_StartEventSensitivity=34]=`Speech_StartEventSensitivity`,e[e.Speech_EnableMultiChannelProcessing=35]=`Speech_EnableMultiChannelProcessing`,e[e.SpeechServiceConnection_EnableAudioLogging=36]=`SpeechServiceConnection_EnableAudioLogging`,e[e.SpeechServiceConnection_LanguageIdMode=37]=`SpeechServiceConnection_LanguageIdMode`,e[e.SpeechServiceConnection_RecognitionEndpointVersion=38]=`SpeechServiceConnection_RecognitionEndpointVersion`,e[e.SpeechServiceResponse_ProfanityOption=39]=`SpeechServiceResponse_ProfanityOption`,e[e.SpeechServiceResponse_PostProcessingOption=40]=`SpeechServiceResponse_PostProcessingOption`,e[e.SpeechServiceResponse_RequestWordLevelTimestamps=41]=`SpeechServiceResponse_RequestWordLevelTimestamps`,e[e.SpeechServiceResponse_StablePartialResultThreshold=42]=`SpeechServiceResponse_StablePartialResultThreshold`,e[e.SpeechServiceResponse_OutputFormatOption=43]=`SpeechServiceResponse_OutputFormatOption`,e[e.SpeechServiceResponse_TranslationRequestStablePartialResult=44]=`SpeechServiceResponse_TranslationRequestStablePartialResult`,e[e.SpeechServiceResponse_RequestWordBoundary=45]=`SpeechServiceResponse_RequestWordBoundary`,e[e.SpeechServiceResponse_RequestPunctuationBoundary=46]=`SpeechServiceResponse_RequestPunctuationBoundary`,e[e.SpeechServiceResponse_RequestSentenceBoundary=47]=`SpeechServiceResponse_RequestSentenceBoundary`,e[e.SpeechServiceResponse_DiarizeIntermediateResults=48]=`SpeechServiceResponse_DiarizeIntermediateResults`,e[e.Conversation_ApplicationId=49]=`Conversation_ApplicationId`,e[e.Conversation_DialogType=50]=`Conversation_DialogType`,e[e.Conversation_Initial_Silence_Timeout=51]=`Conversation_Initial_Silence_Timeout`,e[e.Conversation_From_Id=52]=`Conversation_From_Id`,e[e.Conversation_Conversation_Id=53]=`Conversation_Conversation_Id`,e[e.Conversation_Custom_Voice_Deployment_Ids=54]=`Conversation_Custom_Voice_Deployment_Ids`,e[e.Conversation_Speech_Activity_Template=55]=`Conversation_Speech_Activity_Template`,e[e.Conversation_Request_Bot_Status_Messages=56]=`Conversation_Request_Bot_Status_Messages`,e[e.Conversation_Agent_Connection_Id=57]=`Conversation_Agent_Connection_Id`,e[e.SpeechServiceConnection_Host=58]=`SpeechServiceConnection_Host`,e[e.PronunciationAssessment_ReferenceText=59]=`PronunciationAssessment_ReferenceText`,e[e.PronunciationAssessment_GradingSystem=60]=`PronunciationAssessment_GradingSystem`,e[e.PronunciationAssessment_Granularity=61]=`PronunciationAssessment_Granularity`,e[e.PronunciationAssessment_EnableMiscue=62]=`PronunciationAssessment_EnableMiscue`,e[e.PronunciationAssessment_Json=63]=`PronunciationAssessment_Json`,e[e.PronunciationAssessment_Params=64]=`PronunciationAssessment_Params`,e[e.WebWorkerLoadType=65]=`WebWorkerLoadType`,e[e.TalkingAvatarService_WebRTC_SDP=66]=`TalkingAvatarService_WebRTC_SDP`,e[e.Recognizer_StopTimeoutMs=67]=`Recognizer_StopTimeoutMs`,e[e.SpeechServiceResponse_RecognitionLatencyMs=68]=`SpeechServiceResponse_RecognitionLatencyMs`,e[e.SpeechServiceResponse_SynthesisFirstByteLatencyMs=69]=`SpeechServiceResponse_SynthesisFirstByteLatencyMs`,e[e.SpeechServiceResponse_SynthesisFinishLatencyMs=70]=`SpeechServiceResponse_SynthesisFinishLatencyMs`,e[e.SpeechServiceResponse_SynthesisConnectionLatencyMs=71]=`SpeechServiceResponse_SynthesisConnectionLatencyMs`,e[e.SpeechServiceResponse_SynthesisNetworkLatencyMs=72]=`SpeechServiceResponse_SynthesisNetworkLatencyMs`,e[e.SpeechServiceResponse_SynthesisServiceLatencyMs=73]=`SpeechServiceResponse_SynthesisServiceLatencyMs`,e[e.SpeechSynthesisRequest_Pitch=74]=`SpeechSynthesisRequest_Pitch`,e[e.SpeechSynthesisRequest_Rate=75]=`SpeechSynthesisRequest_Rate`,e[e.SpeechSynthesisRequest_Volume=76]=`SpeechSynthesisRequest_Volume`,e[e.SpeechSynthesisRequest_Style=77]=`SpeechSynthesisRequest_Style`,e[e.SpeechSynthesisRequest_Temperature=78]=`SpeechSynthesisRequest_Temperature`,e[e.SpeechSynthesisRequest_CustomLexiconUrl=79]=`SpeechSynthesisRequest_CustomLexiconUrl`,e[e.SpeechSynthesisRequest_PreferLocales=80]=`SpeechSynthesisRequest_PreferLocales`,e[e.SpeechSynthesis_FrameTimeoutInterval=81]=`SpeechSynthesis_FrameTimeoutInterval`,e[e.SpeechSynthesis_RtfTimeoutThreshold=82]=`SpeechSynthesis_RtfTimeoutThreshold`})(e.PropertyId||={})})),pt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Recognizer=void 0;var t=Q(),n=k(),r=F(),i=Y();e.Recognizer=class e{constructor(e,t,n,r){this.audioConfig=e===void 0?i.AudioConfig.fromDefaultMicrophoneInput():e,this.privDisposed=!1,this.privProperties=t.clone(),this.privConnectionFactory=n,this.tokenCredential=r,this.implCommonRecognizerSetup()}close(e,t){r.Contracts.throwIfDisposed(this.privDisposed),(0,n.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}get internalData(){return this.privReco}async dispose(e){this.privDisposed||(this.privDisposed=!0,e&&this.privReco&&(await this.privReco.audioSource.turnOff(),await this.privReco.dispose()))}static get telemetryEnabled(){return t.ServiceRecognizerBase.telemetryDataEnabled}static enableTelemetry(e){t.ServiceRecognizerBase.telemetryDataEnabled=e}implCommonRecognizerSetup(){let n=typeof window<`u`?`Browser`:`Node`,r=`unknown`,i=`unknown`;typeof navigator<`u`&&(n=n+`/`+navigator.platform,r=navigator.userAgent,i=navigator.appVersion);let a=this.createRecognizerConfig(new t.SpeechServiceConfig(new t.Context(new t.OS(n,r,i))));this.privReco=this.createServiceRecognizer(e.getAuth(this.privProperties,this.tokenCredential),this.privConnectionFactory,this.audioConfig,a)}async recognizeOnceAsyncImpl(e){r.Contracts.throwIfDisposed(this.privDisposed);let t=new n.Deferred;await this.implRecognizerStop(),await this.privReco.recognize(e,t.resolve,t.reject);let i=await t.promise;return await this.implRecognizerStop(),i}async startContinuousRecognitionAsyncImpl(e){r.Contracts.throwIfDisposed(this.privDisposed),await this.implRecognizerStop(),await this.privReco.recognize(e,void 0,void 0)}async stopContinuousRecognitionAsyncImpl(){r.Contracts.throwIfDisposed(this.privDisposed),await this.implRecognizerStop()}async implRecognizerStop(){if(this.privReco){let e=this.privProperties.getProperty(i.PropertyId.Recognizer_StopTimeoutMs,void 0);if(e!==void 0&&e!==``){let t=parseInt(e,10);if(t>0){try{await this.withTimeout(this.privReco.stopRecognizing(),t,`Stop operation timed out after ${t}ms waiting for service to complete turn`)}catch(e){throw await this.privReco.disconnect(),e}return}}await this.privReco.stopRecognizing()}}withTimeout(e,t,n){return Promise.race([e,new Promise((e,r)=>{setTimeout(()=>{r(Error(n))},t)})])}static getAuth(e,n){let r=e.getProperty(i.PropertyId.SpeechServiceConnection_Key,void 0);return r&&r!==``?new t.CognitiveSubscriptionKeyAuthentication(r):n?new t.CognitiveTokenAuthentication(async()=>{try{return(await n.getToken(`https://cognitiveservices.azure.com/.default`))?.token??``}catch(e){throw e}},async()=>{try{return(await n.getToken(`https://cognitiveservices.azure.com/.default`))?.token??``}catch(e){throw e}}):new t.CognitiveTokenAuthentication(()=>{let t=e.getProperty(i.PropertyId.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(t)},()=>{let t=e.getProperty(i.PropertyId.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(t)})}}})),W=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechStartEventSensitivity=e.RecognitionMode=void 0,(function(e){e.Interactive=`Interactive`,e.Dictation=`Dictation`,e.Conversation=`Conversation`,e.None=`None`})(e.RecognitionMode||={}),(function(e){e.Low=`low`,e.Medium=`medium`,e.High=`high`})(e.SpeechStartEventSensitivity||={})})),mt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechRecognizer=void 0;var t=Q(),n=W(),r=k(),i=F(),a=Y();e.SpeechRecognizer=class e extends a.Recognizer{constructor(e,n){let r=e;i.Contracts.throwIfNull(r,`speechConfig`),i.Contracts.throwIfNullOrWhitespace(r.properties.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage),a.PropertyId[a.PropertyId.SpeechServiceConnection_RecoLanguage]),super(n,r.properties,new t.SpeechConnectionFactory,e.tokenCredential),this.privDisposedRecognizer=!1}static FromConfig(t,n,r){let i=t;return n.properties.mergeTo(i.properties),new e(t,r)}get endpointId(){return i.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(a.PropertyId.SpeechServiceConnection_EndpointId,`00000000-0000-0000-0000-000000000000`)}get authorizationToken(){return this.properties.getProperty(a.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){i.Contracts.throwIfNullOrWhitespace(e,`token`),this.properties.setProperty(a.PropertyId.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return i.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage)}get outputFormat(){return i.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(t.OutputFormatPropertyName,a.OutputFormat[a.OutputFormat.Simple])===a.OutputFormat[a.OutputFormat.Simple]?a.OutputFormat.Simple:a.OutputFormat.Detailed}get properties(){return this.privProperties}recognizeOnceAsync(e,t){(0,r.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(n.RecognitionMode.Interactive),e,t)}startContinuousRecognitionAsync(e,i){(0,r.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(this.properties.getProperty(t.ForceDictationPropertyName,void 0)===void 0?n.RecognitionMode.Conversation:n.RecognitionMode.Dictation),e,i)}stopContinuousRecognitionAsync(e,t){(0,r.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(),e,t)}startKeywordRecognitionAsync(e,t,n){i.Contracts.throwIfNull(e,`model`),n&&n(`Not yet implemented.`)}stopKeywordRecognitionAsync(e){e&&e()}close(e,t){i.Contracts.throwIfDisposed(this.privDisposedRecognizer),(0,r.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}async dispose(e){this.privDisposedRecognizer||(e&&(this.privDisposedRecognizer=!0,await this.implRecognizerStop()),await super.dispose(e))}createRecognizerConfig(e){return new t.RecognizerConfig(e,this.privProperties)}createServiceRecognizer(e,n,r,i){let a=r;return new t.SpeechServiceRecognizer(e,n,a,i,this)}}})),ht=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionMessageImpl=e.ConnectionMessage=void 0;var t=A(),n=k(),r=ft(),i=U();e.ConnectionMessage=class{},e.ConnectionMessageImpl=class{constructor(e){this.privConnectionMessage=e,this.privProperties=new r.PropertyCollection,this.privConnectionMessage.headers[t.HeaderNames.ConnectionId]&&this.privProperties.setProperty(i.PropertyId.Speech_SessionId,this.privConnectionMessage.headers[t.HeaderNames.ConnectionId]),Object.keys(this.privConnectionMessage.headers).forEach(e=>{this.privProperties.setProperty(e,this.privConnectionMessage.headers[e])})}get path(){return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find(e=>e.toLowerCase()===`path`)]}get isTextMessage(){return this.privConnectionMessage.messageType===n.MessageType.Text}get isBinaryMessage(){return this.privConnectionMessage.messageType===n.MessageType.Binary}get TextMessage(){return this.privConnectionMessage.textBody}get binaryMessage(){return this.privConnectionMessage.binaryBody}get properties(){return this.privProperties}toString(){return``}}})),gt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Connection=void 0;var t=Q(),n=k(),r=ht(),i=F(),a=Y();e.Connection=class e{static fromRecognizer(t){let n=t.internalData,r=new e;return r.privInternalData=n,r.setupEvents(),r}static fromSynthesizer(t){let n=t.internalData,r=new e;return r.privInternalData=n,r.setupEvents(),r}openConnection(e,t){(0,n.marshalPromiseToCallbacks)(this.privInternalData.connect(),e,t)}closeConnection(e,r){if(this.privInternalData instanceof t.SynthesisAdapterBase)throw Error(`Disconnecting a synthesizer's connection is currently not supported`);(0,n.marshalPromiseToCallbacks)(this.privInternalData.disconnect(),e,r)}setMessageProperty(e,n,r){if(i.Contracts.throwIfNullOrWhitespace(n,`propertyName`),this.privInternalData instanceof t.ServiceRecognizerBase){if(e.toLowerCase()!==`speech.context`)throw Error(`Only speech.context message property sets are currently supported for recognizer`);{let e=this.privInternalData.speechContext.getContext();e[n]=r}}else if(this.privInternalData instanceof t.SynthesisAdapterBase){if(e.toLowerCase()!==`speech.config`&&e.toLowerCase()!==`synthesis.context`)throw Error(`Only speech.config and synthesis.context message paths are currently supported for synthesizer`);if(e.toLowerCase()===`speech.config`){if(n.toLowerCase()!==`context`)throw Error(`Only context property is currently supported for speech.config message path for synthesizer`);this.privInternalData.synthesizerConfig.setContextFromJson(r)}else this.privInternalData.synthesisContext.setSection(n,r)}}sendMessageAsync(e,t,r,i){(0,n.marshalPromiseToCallbacks)(this.privInternalData.sendNetworkMessage(e,t),r,i)}close(){}setupEvents(){this.privEventListener=this.privInternalData.connectionEvents.attach(e=>{e.name===`ConnectionEstablishedEvent`?this.connected&&this.connected(new a.ConnectionEventArgs(e.connectionId)):e.name===`ConnectionClosedEvent`?this.disconnected&&this.disconnected(new a.ConnectionEventArgs(e.connectionId)):e.name===`ConnectionMessageSentEvent`?this.messageSent&&this.messageSent(new a.ConnectionMessageEventArgs(new r.ConnectionMessageImpl(e.message))):e.name===`ConnectionMessageReceivedEvent`&&this.messageReceived&&this.messageReceived(new a.ConnectionMessageEventArgs(new r.ConnectionMessageImpl(e.message)))}),this.privServiceEventListener=this.privInternalData.serviceEvents.attach(e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new a.ServiceEventArgs(e.jsonString,e.name))})}}})),_t=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationRecognizer=void 0;var t=Q(),n=W(),r=k(),i=gt(),a=F(),o=Y();e.TranslationRecognizer=class e extends o.Recognizer{constructor(e,n,r){let i=e;a.Contracts.throwIfNull(i,`speechConfig`),super(n,i.properties,r||new t.TranslationConnectionFactory,e.tokenCredential),this.privDisposedTranslationRecognizer=!1,this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&a.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationVoice),o.PropertyId[o.PropertyId.SpeechServiceConnection_TranslationVoice]),a.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages),o.PropertyId[o.PropertyId.SpeechServiceConnection_TranslationToLanguages]),this.properties.getProperty(o.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)===void 0&&a.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(o.PropertyId.SpeechServiceConnection_RecoLanguage),o.PropertyId[o.PropertyId.SpeechServiceConnection_RecoLanguage])}static FromConfig(n,r,i){let a=n;return r.properties.mergeTo(a.properties),r.properties.getProperty(o.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)===t.AutoDetectSourceLanguagesOpenRangeOptionName&&a.properties.setProperty(o.PropertyId.SpeechServiceConnection_RecoLanguage,`en-US`),new e(n,i)}get speechRecognitionLanguage(){return a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(o.PropertyId.SpeechServiceConnection_RecoLanguage)}get targetLanguages(){return a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(`,`)}get voiceName(){return a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationVoice,void 0)}get properties(){return this.privProperties}get authorizationToken(){return this.properties.getProperty(o.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.properties.setProperty(o.PropertyId.SpeechServiceAuthorization_Token,e)}recognizeOnceAsync(e,t){a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),(0,r.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(n.RecognitionMode.Interactive),e,t)}startContinuousRecognitionAsync(e,t){(0,r.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(n.RecognitionMode.Conversation),e,t)}stopContinuousRecognitionAsync(e,t){(0,r.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(),e,t)}removeTargetLanguage(e){if(a.Contracts.throwIfNullOrUndefined(e,`language to be removed`),this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0){let t=this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(`,`),n=t.indexOf(e);n>-1&&(t.splice(n,1),this.properties.setProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages,t.join(`,`)),this.updateLanguages(t))}}addTargetLanguage(e){a.Contracts.throwIfNullOrUndefined(e,`language to be added`);let t=[];this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0)===void 0?(this.properties.setProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages,e),t=[e]):(t=this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(`,`),t.includes(e)||(t.push(e),this.properties.setProperty(o.PropertyId.SpeechServiceConnection_TranslationToLanguages,t.join(`,`)))),this.updateLanguages(t)}close(e,t){a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),(0,r.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}onConnection(){}async dispose(e){this.privDisposedTranslationRecognizer||(this.privDisposedTranslationRecognizer=!0,e&&(await this.implRecognizerStop(),await super.dispose(e)))}createRecognizerConfig(e){return new t.RecognizerConfig(e,this.privProperties)}createServiceRecognizer(e,n,r,i){let a=r;return new t.TranslationServiceRecognizer(e,n,a,i,this)}updateLanguages(e){let t=i.Connection.fromRecognizer(this);if(t){t.setMessageProperty(`speech.context`,`translationcontext`,{to:e});let n=this.properties.getProperty(o.PropertyId.SpeechServiceConnection_TranslationVoice,void 0),r;if(n){let t={};for(let r of e)t[r]=n;r=JSON.stringify({id:`translation`,name:`updateLanguage`,synthesis:{defaultVoices:t},to:e})}else r=JSON.stringify({id:`translation`,name:`updateLanguage`,to:e});t.sendMessageAsync(`event`,r)}}}})),vt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Translations=void 0;var t=Y();e.Translations=class{constructor(){this.privMap=new t.PropertyCollection}get languages(){return this.privMap.keys}get(e,t){return this.privMap.getProperty(e,t)}set(e,t){this.privMap.setProperty(e,t)}}})),yt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoMatchReason=void 0,(function(e){e[e.NotRecognized=0]=`NotRecognized`,e[e.InitialSilenceTimeout=1]=`InitialSilenceTimeout`,e[e.InitialBabbleTimeout=2]=`InitialBabbleTimeout`})(e.NoMatchReason||={})})),bt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoMatchDetails=void 0;var t=Q(),n=Y();e.NoMatchDetails=class e{constructor(e){this.privReason=e}static fromResult(r){let i=t.SimpleSpeechPhrase.fromJSON(r.json,0),a=n.NoMatchReason.NotRecognized;switch(i.RecognitionStatus){case t.RecognitionStatus.BabbleTimeout:a=n.NoMatchReason.InitialBabbleTimeout;break;case t.RecognitionStatus.InitialSilenceTimeout:a=n.NoMatchReason.InitialSilenceTimeout;break;default:a=n.NoMatchReason.NotRecognized}return new e(a)}get reason(){return this.privReason}}})),xt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationRecognitionCanceledEventArgs=void 0,e.TranslationRecognitionCanceledEventArgs=class{constructor(e,t,n,r,i){this.privCancelReason=t,this.privErrorDetails=n,this.privResult=i,this.privSessionId=e,this.privErrorCode=r}get result(){return this.privResult}get sessionId(){return this.privSessionId}get reason(){return this.privCancelReason}get errorCode(){return this.privErrorCode}get errorDetails(){return this.privErrorDetails}}})),St=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationDetailsBase=void 0,e.CancellationDetailsBase=class{constructor(e,t,n){this.privReason=e,this.privErrorDetails=t,this.privErrorCode=n}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get ErrorCode(){return this.privErrorCode}}})),Ct=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationDetails=void 0;var t=Q(),n=St(),r=Y();e.CancellationDetails=class e extends n.CancellationDetailsBase{constructor(e,t,n){super(e,t,n)}static fromResult(n){let i=r.CancellationReason.Error,a=r.CancellationErrorCode.NoError;if(n instanceof r.RecognitionResult&&n.json){let e=t.SimpleSpeechPhrase.fromJSON(n.json,0);i=t.EnumTranslation.implTranslateCancelResult(e.RecognitionStatus)}return n.properties&&(a=r.CancellationErrorCode[n.properties.getProperty(t.CancellationErrorCodePropertyName,r.CancellationErrorCode[r.CancellationErrorCode.NoError])]),new e(i,n.errorDetails||t.EnumTranslation.implTranslateErrorDetails(a),a)}}})),wt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationErrorCode=void 0,(function(e){e[e.NoError=0]=`NoError`,e[e.AuthenticationFailure=1]=`AuthenticationFailure`,e[e.BadRequestParameters=2]=`BadRequestParameters`,e[e.TooManyRequests=3]=`TooManyRequests`,e[e.ConnectionFailure=4]=`ConnectionFailure`,e[e.ServiceTimeout=5]=`ServiceTimeout`,e[e.ServiceError=6]=`ServiceError`,e[e.RuntimeError=7]=`RuntimeError`,e[e.Forbidden=8]=`Forbidden`})(e.CancellationErrorCode||={})})),Tt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionEventArgs=void 0;var t=Y();e.ConnectionEventArgs=class extends t.SessionEventArgs{}})),Et=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ServiceEventArgs=void 0;var t=Y();e.ServiceEventArgs=class extends t.SessionEventArgs{constructor(e,t,n){super(n),this.privJsonResult=e,this.privEventName=t}get jsonString(){return this.privJsonResult}get eventName(){return this.privEventName}}})),Dt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PhraseListGrammar=void 0;var t=F();e.PhraseListGrammar=class e{constructor(e){this.privGrammerBuilder=e.dynamicGrammar}static fromRecognizer(t){let n=t.internalData;return new e(n)}addPhrase(e){this.privGrammerBuilder.addPhrase(e)}addPhrases(e){this.privGrammerBuilder.addPhrase(e)}clear(){this.privGrammerBuilder.clearPhrases()}setWeight(e){t.Contracts.throwIfNumberOutOfRange(e,`weight`,0,2),this.privGrammerBuilder.setWeight(e)}}})),G=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DialogServiceConfigImpl=e.DialogServiceConfig=void 0;var t=F(),n=Y(),r=class{constructor(){}set applicationId(e){}static get DialogTypes(){return{BotFramework:`bot_framework`,CustomCommands:`custom_commands`}}};e.DialogServiceConfig=r,e.DialogServiceConfigImpl=class extends r{constructor(){super(),this.privSpeechConfig=new n.SpeechConfigImpl}get properties(){return this.privSpeechConfig.properties}get speechRecognitionLanguage(){return this.privSpeechConfig.speechRecognitionLanguage}set speechRecognitionLanguage(e){t.Contracts.throwIfNullOrWhitespace(e,`value`),this.privSpeechConfig.speechRecognitionLanguage=e}get outputFormat(){return this.privSpeechConfig.outputFormat}set outputFormat(e){this.privSpeechConfig.outputFormat=e}setProperty(e,t){this.privSpeechConfig.setProperty(e,t)}getProperty(e,t){return this.privSpeechConfig.getProperty(e)}setProxy(e,t,r,i){this.setProperty(n.PropertyId.SpeechServiceConnection_ProxyHostName,e),this.setProperty(n.PropertyId.SpeechServiceConnection_ProxyPort,`${t}`),r&&this.setProperty(n.PropertyId.SpeechServiceConnection_ProxyUserName,r),i&&this.setProperty(n.PropertyId.SpeechServiceConnection_ProxyPassword,i)}setServiceProperty(e,t,n){this.privSpeechConfig.setServiceProperty(e,t)}close(){}}})),Ot=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BotFrameworkConfig=void 0;var t=F(),n=G(),r=Y();e.BotFrameworkConfig=class extends n.DialogServiceConfigImpl{constructor(){super()}static fromSubscription(e,i,a){t.Contracts.throwIfNullOrWhitespace(e,`subscription`),t.Contracts.throwIfNullOrWhitespace(i,`region`);let o=new n.DialogServiceConfigImpl;return o.setProperty(r.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.BotFramework),o.setProperty(r.PropertyId.SpeechServiceConnection_Key,e),o.setProperty(r.PropertyId.SpeechServiceConnection_Region,i),a&&o.setProperty(r.PropertyId.Conversation_ApplicationId,a),o}static fromAuthorizationToken(e,i,a){t.Contracts.throwIfNullOrWhitespace(e,`authorizationToken`),t.Contracts.throwIfNullOrWhitespace(i,`region`);let o=new n.DialogServiceConfigImpl;return o.setProperty(r.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.BotFramework),o.setProperty(r.PropertyId.SpeechServiceAuthorization_Token,e),o.setProperty(r.PropertyId.SpeechServiceConnection_Region,i),a&&o.setProperty(r.PropertyId.Conversation_ApplicationId,a),o}static fromHost(e,i,a){t.Contracts.throwIfNullOrUndefined(e,`host`);let o=e instanceof URL?e:new URL(`wss://${e}.convai.speech.azure.us`);t.Contracts.throwIfNullOrUndefined(o,`resolvedHost`);let s=new n.DialogServiceConfigImpl;return s.setProperty(r.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.BotFramework),s.setProperty(r.PropertyId.SpeechServiceConnection_Host,o.toString()),i!==void 0&&s.setProperty(r.PropertyId.SpeechServiceConnection_Key,i),s}static fromEndpoint(e,i){t.Contracts.throwIfNull(e,`endpoint`);let a=new n.DialogServiceConfigImpl;return a.setProperty(r.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.BotFramework),a.setProperty(r.PropertyId.SpeechServiceConnection_Endpoint,e.toString()),i!==void 0&&a.setProperty(r.PropertyId.SpeechServiceConnection_Key,i),a}}})),kt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CustomCommandsConfig=void 0;var t=F(),n=G(),r=Y();e.CustomCommandsConfig=class extends n.DialogServiceConfigImpl{constructor(){super()}static fromSubscription(e,i,a){t.Contracts.throwIfNullOrWhitespace(e,`applicationId`),t.Contracts.throwIfNullOrWhitespace(i,`subscription`),t.Contracts.throwIfNullOrWhitespace(a,`region`);let o=new n.DialogServiceConfigImpl;return o.setProperty(r.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.CustomCommands),o.setProperty(r.PropertyId.Conversation_ApplicationId,e),o.setProperty(r.PropertyId.SpeechServiceConnection_Key,i),o.setProperty(r.PropertyId.SpeechServiceConnection_Region,a),o}static fromAuthorizationToken(e,i,a){t.Contracts.throwIfNullOrWhitespace(e,`applicationId`),t.Contracts.throwIfNullOrWhitespace(i,`authorizationToken`),t.Contracts.throwIfNullOrWhitespace(a,`region`);let o=new n.DialogServiceConfigImpl;return o.setProperty(r.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.CustomCommands),o.setProperty(r.PropertyId.Conversation_ApplicationId,e),o.setProperty(r.PropertyId.SpeechServiceAuthorization_Token,i),o.setProperty(r.PropertyId.SpeechServiceConnection_Region,a),o}set applicationId(e){t.Contracts.throwIfNullOrWhitespace(e,`value`),this.setProperty(r.PropertyId.Conversation_ApplicationId,e)}get applicationId(){return this.getProperty(r.PropertyId.Conversation_ApplicationId)}}})),K=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.QueryParameterNames=void 0;var t=class{};e.QueryParameterNames=t,t.BotId=`botid`,t.CustomSpeechDeploymentId=`cid`,t.CustomVoiceDeploymentId=`deploymentId`,t.EnableAudioLogging=`storeAudio`,t.EnableLanguageId=`lidEnabled`,t.EnableWordLevelTimestamps=`wordLevelTimestamps`,t.EndSilenceTimeoutMs=`endSilenceTimeoutMs`,t.SegmentationSilenceTimeoutMs=`segmentationSilenceTimeoutMs`,t.SegmentationMaximumTimeMs=`segmentationMaximumTimeMs`,t.SegmentationStrategy=`segmentationStrategy`,t.Format=`format`,t.InitialSilenceTimeoutMs=`initialSilenceTimeoutMs`,t.Language=`language`,t.Profanity=`profanity`,t.RequestBotStatusMessages=`enableBotMessageStatus`,t.StableIntermediateThreshold=`stableIntermediateThreshold`,t.StableTranslation=`stableTranslation`,t.TestHooks=`testhooks`,t.Postprocessing=`postprocessing`,t.CtsMeetingId=`meetingId`,t.CtsDeviceId=`deviceId`,t.CtsIsParticipant=`isParticipant`,t.EnableAvatar=`enableTalkingAvatar`})),q=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactoryBase=void 0;var t=Q(),n=k(),r=Y(),i=K();e.ConnectionFactoryBase=class{static getHostSuffix(e){if(e){if(e.toLowerCase().startsWith(`china`))return`.azure.cn`;if(e.toLowerCase().startsWith(`usgov`))return`.azure.us`}return`.microsoft.com`}setCommonUrlParams(e,n,a){new Map([[r.PropertyId.Speech_SegmentationSilenceTimeoutMs,i.QueryParameterNames.SegmentationSilenceTimeoutMs],[r.PropertyId.SpeechServiceConnection_EnableAudioLogging,i.QueryParameterNames.EnableAudioLogging],[r.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs,i.QueryParameterNames.EndSilenceTimeoutMs],[r.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs,i.QueryParameterNames.InitialSilenceTimeoutMs],[r.PropertyId.SpeechServiceResponse_ProfanityOption,i.QueryParameterNames.Profanity],[r.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,i.QueryParameterNames.EnableWordLevelTimestamps],[r.PropertyId.SpeechServiceResponse_StablePartialResultThreshold,i.QueryParameterNames.StableIntermediateThreshold]]).forEach((t,r)=>{this.setUrlParameter(r,t,e,n,a)});let o=JSON.parse(e.parameters.getProperty(t.ServicePropertiesPropertyName,`{}`));Object.keys(o).forEach(e=>{n[e]=o[e]})}setUrlParameter(e,t,n,r,i){let a=n.parameters.getProperty(e,void 0);a&&(!i||i.search(t)===-1)&&(r[t]=a.toLocaleLowerCase())}static async getRedirectUrlFromEndpoint(e,t=!0){let r=new URL(e);r.protocol=`https:`,r.port=`443`,r.searchParams.append(`GenerateRedirectResponse`,`true`);let i=r.toString();n.Events.instance.onEvent(new n.ConnectionRedirectEvent(``,i,void 0,`ConnectionFactoryBase: redirectUrl request`));let a=await fetch(i);if(a.status!==200)return e;let o=await a.text();n.Events.instance.onEvent(new n.ConnectionRedirectEvent(``,o,e,`ConnectionFactoryBase: redirectUrlString`));try{let e=new URL(o.trim());return t&&(e.protocol===`https:`?e.protocol=`wss:`:e.protocol===`http:`&&(e.protocol=`ws:`)),e.toString()}catch{return e}}}})),At=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DialogConnectionFactory=void 0;var t=X(),n=Q(),r=Y(),i=q(),a=Q(),o=A(),s=K(),c=class e extends i.ConnectionFactoryBase{create(c,l,u){let d=c.parameters.getProperty(r.PropertyId.Conversation_ApplicationId,``),f=c.parameters.getProperty(r.PropertyId.Conversation_DialogType),p=c.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Region),m=c.parameters.getProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage,`en-US`),h=c.parameters.getProperty(r.PropertyId.Conversation_Request_Bot_Status_Messages,`true`),g={};g[o.HeaderNames.ConnectionId]=u,g[s.QueryParameterNames.Format]=c.parameters.getProperty(n.OutputFormatPropertyName,r.OutputFormat[r.OutputFormat.Simple]).toLowerCase(),g[s.QueryParameterNames.Language]=m,g[s.QueryParameterNames.RequestBotStatusMessages]=h,d&&(g[s.QueryParameterNames.BotId]=d,f===r.DialogServiceConfig.DialogTypes.CustomCommands&&(g[o.HeaderNames.CustomCommandsAppId]=d));let _=f===r.DialogServiceConfig.DialogTypes.CustomCommands?`commands/`:``,v=f===r.DialogServiceConfig.DialogTypes.CustomCommands?`v1`:f===r.DialogServiceConfig.DialogTypes.BotFramework?`v3`:`v0`,y={};l.token!=null&&l.token!==``&&(y[l.headerName]=l.token);let b=c.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Endpoint,``);if(!b){let t=i.ConnectionFactoryBase.getHostSuffix(p),n=c.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Host,`wss://${p}.${e.BaseUrl}${t}`);b=`${n.endsWith(`/`)?n:n+`/`}${_}${e.ApiKey}/${v}`}this.setCommonUrlParams(c,g,b);let x=c.parameters.getProperty(`SPEECH-EnableWebsocketCompression`,`false`)===`true`;return Promise.resolve(new t.WebsocketConnection(b,g,y,new a.WebsocketMessageFormatter,t.ProxyInfo.fromRecognizerConfig(c),x,u))}};e.DialogConnectionFactory=c,c.ApiKey=`api`,c.BaseUrl=`convai.speech`})),jt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DialogServiceConnector=void 0;var t=At(),n=Q(),r=W(),i=k(),a=F(),o=Y(),s=U();e.DialogServiceConnector=class extends o.Recognizer{constructor(e,n){let r=e;a.Contracts.throwIfNull(e,`dialogConfig`),super(n,r.properties,new t.DialogConnectionFactory),this.isTurnComplete=!0,this.privIsDisposed=!1,this.privProperties=r.properties.clone();let i=this.buildAgentConfig();this.privReco.agentConfig.set(i)}connect(e,t){(0,i.marshalPromiseToCallbacks)(this.privReco.connect(),e,t)}disconnect(e,t){(0,i.marshalPromiseToCallbacks)(this.privReco.disconnect(),e,t)}get authorizationToken(){return this.properties.getProperty(s.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){a.Contracts.throwIfNullOrWhitespace(e,`token`),this.properties.setProperty(s.PropertyId.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get speechActivityTemplate(){return this.properties.getProperty(s.PropertyId.Conversation_Speech_Activity_Template)}set speechActivityTemplate(e){this.properties.setProperty(s.PropertyId.Conversation_Speech_Activity_Template,e)}listenOnceAsync(e,t){if(this.isTurnComplete){a.Contracts.throwIfDisposed(this.privIsDisposed);let n=(async()=>{await this.privReco.connect(),await this.implRecognizerStop(),this.isTurnComplete=!1;let e=new i.Deferred;await this.privReco.recognize(r.RecognitionMode.Conversation,e.resolve,e.reject);let t=await e.promise;return await this.implRecognizerStop(),t})();n.catch(()=>{this.dispose(!0).catch(()=>{})}),(0,i.marshalPromiseToCallbacks)(n.finally(()=>{this.isTurnComplete=!0}),e,t)}}sendActivityAsync(e,t,n){(0,i.marshalPromiseToCallbacks)(this.privReco.sendMessage(e),t,n)}close(e,t){a.Contracts.throwIfDisposed(this.privIsDisposed),(0,i.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}async dispose(e){this.privIsDisposed||e&&(this.privIsDisposed=!0,await this.implRecognizerStop(),await super.dispose(e))}createRecognizerConfig(e){return new n.RecognizerConfig(e,this.privProperties)}createServiceRecognizer(e,t,r,i){let a=r;return new n.DialogServiceAdapter(e,t,a,i,this)}buildAgentConfig(){return{botInfo:{commType:this.properties.getProperty(`Conversation_Communication_Type`,`Default`),commandsCulture:void 0,connectionId:this.properties.getProperty(s.PropertyId.Conversation_Agent_Connection_Id),conversationId:this.properties.getProperty(s.PropertyId.Conversation_Conversation_Id,void 0),fromId:this.properties.getProperty(s.PropertyId.Conversation_From_Id,void 0),ttsAudioFormat:this.properties.getProperty(s.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0)},version:.2}}}})),Mt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ActivityReceivedEventArgs=void 0,e.ActivityReceivedEventArgs=class{constructor(e,t){this.privActivity=e,this.privAudioStream=t}get activity(){return this.privActivity}get audioStream(){return this.privAudioStream}}})),Nt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TurnStatusResponsePayload=void 0,e.TurnStatusResponsePayload=class e{constructor(e){this.privMessageStatusResponse=JSON.parse(e)}static fromJSON(t){return new e(t)}get interactionId(){return this.privMessageStatusResponse.interactionId}get conversationId(){return this.privMessageStatusResponse.conversationId}get statusCode(){switch(this.privMessageStatusResponse.statusCode){case`Success`:return 200;case`Failed`:return 400;case`TimedOut`:return 429;default:return this.privMessageStatusResponse.statusCode}}}})),Pt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TurnStatusReceivedEventArgs=void 0;var t=Nt();e.TurnStatusReceivedEventArgs=class{constructor(e){this.privTurnStatus=t.TurnStatusResponsePayload.fromJSON(e)}get interactionId(){return this.privTurnStatus.interactionId}get conversationId(){return this.privTurnStatus.conversationId}get statusCode(){return this.privTurnStatus.statusCode}}})),Ft=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ServicePropertyChannel=void 0,(function(e){e[e.UriQueryParameter=0]=`UriQueryParameter`})(e.ServicePropertyChannel||={})})),It=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProfanityOption=void 0,(function(e){e[e.Masked=0]=`Masked`,e[e.Removed=1]=`Removed`,e[e.Raw=2]=`Raw`})(e.ProfanityOption||={})})),Lt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BaseAudioPlayer=void 0;var t=T(),n=Y(),r=I();e.BaseAudioPlayer=class{constructor(e){this.audioContext=null,this.gainNode=null,this.autoUpdateBufferTimer=0,e===void 0&&(e=n.AudioStreamFormat.getDefaultInputFormat()),this.init(e)}playAudioSample(e,t,n){try{this.ensureInitializedContext();let n=this.formatAudioData(e),r=new Float32Array(this.samples.length+n.length);r.set(this.samples,0),r.set(n,this.samples.length),this.samples=r,t&&t()}catch(e){n&&n(e)}}stopAudio(e,t){this.audioContext!==null&&(this.samples=new Float32Array,clearInterval(this.autoUpdateBufferTimer),this.audioContext.close().then(()=>{e&&e()},e=>{t&&t(e)}),this.audioContext=null)}init(e){this.audioFormat=e,this.samples=new Float32Array}ensureInitializedContext(){this.audioContext===null&&(this.createAudioContext(),this.autoUpdateBufferTimer=setInterval(()=>{this.updateAudioBuffer()},200))}createAudioContext(){this.audioContext=r.AudioStreamFormatImpl.getAudioContext(),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioContext.destination),this.startTime=this.audioContext.currentTime}formatAudioData(e){switch(this.audioFormat.bitsPerSample){case 8:return this.formatArrayBuffer(new Int8Array(e),128);case 16:return this.formatArrayBuffer(new Int16Array(e),32768);case 32:return this.formatArrayBuffer(new Int32Array(e),2147483648);default:throw new t.InvalidOperationError(`Only WAVE_FORMAT_PCM (8/16/32 bps) format supported at this time`)}}formatArrayBuffer(e,t){let n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]/t;return n}updateAudioBuffer(){if(this.samples.length===0)return;let e=this.audioFormat.channels,t=this.audioContext.createBufferSource(),n=this.samples.length/e,r=this.audioContext.createBuffer(e,n,this.audioFormat.samplesPerSec);for(let t=0;t<e;t++){let n=t,i=r.getChannelData(t);for(let t=0;t<this.samples.length;t++,n+=e)i[t]=this.samples[n]}this.startTime<this.audioContext.currentTime&&(this.startTime=this.audioContext.currentTime),t.buffer=r,t.connect(this.gainNode),t.start(this.startTime),this.startTime+=r.duration,this.samples=new Float32Array}async playAudio(e){this.audioContext===null&&this.createAudioContext();let t=this.audioContext.createBufferSource(),n=this.audioContext.destination;await this.audioContext.decodeAudioData(e,e=>{t.buffer=e,t.connect(n),t.start(0)})}}})),Rt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionMessageEventArgs=void 0,e.ConnectionMessageEventArgs=class{constructor(e){this.privConnectionMessage=e}get message(){return this.privConnectionMessage}toString(){return`Message: `+this.privConnectionMessage.toString()}}})),zt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.LanguageIdMode=void 0,(function(e){e[e.AtStart=0]=`AtStart`,e[e.Continuous=1]=`Continuous`})(e.LanguageIdMode||={})})),Bt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AutoDetectSourceLanguageConfig=void 0;var t=Q(),n=F(),r=Y(),i=zt();e.AutoDetectSourceLanguageConfig=class e{constructor(){this.privProperties=new r.PropertyCollection,this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_LanguageIdMode,`AtStart`),this.privLanguageIdMode=i.LanguageIdMode.AtStart}static fromOpenRange(){let n=new e;return n.properties.setProperty(r.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,t.AutoDetectSourceLanguagesOpenRangeOptionName),n.properties.setProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage,`en-US`),n}static fromLanguages(t){n.Contracts.throwIfArrayEmptyOrWhitespace(t,`languages`);let i=new e;return i.properties.setProperty(r.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,t.join()),i}static fromSourceLanguageConfigs(t){if(t.length<1)throw Error(`Expected non-empty SourceLanguageConfig array.`);let n=new e,i=[];return t.forEach(e=>{if(i.push(e.language),e.endpointId!==void 0&&e.endpointId!==``){let t=e.language+r.PropertyId.SpeechServiceConnection_EndpointId.toString();n.properties.setProperty(t,e.endpointId)}}),n.properties.setProperty(r.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,i.join()),n}get properties(){return this.privProperties}set mode(e){e===i.LanguageIdMode.Continuous?(this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,`2`),this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_LanguageIdMode,`Continuous`)):(this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,`1`),this.privProperties.setProperty(r.PropertyId.SpeechServiceConnection_LanguageIdMode,`AtStart`)),this.privLanguageIdMode=e}}})),Vt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AutoDetectSourceLanguageResult=void 0;var t=F();e.AutoDetectSourceLanguageResult=class e{constructor(e,n){t.Contracts.throwIfNullOrUndefined(e,`language`),t.Contracts.throwIfNullOrUndefined(n,`languageDetectionConfidence`),this.privLanguage=e,this.privLanguageDetectionConfidence=n}static fromResult(t){return new e(t.language,t.languageDetectionConfidence)}static fromConversationTranscriptionResult(t){return new e(t.language,t.languageDetectionConfidence)}get language(){return this.privLanguage}get languageDetectionConfidence(){return this.privLanguageDetectionConfidence}}})),Ht=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SourceLanguageConfig=void 0;var t=F();e.SourceLanguageConfig=class e{constructor(e,n){t.Contracts.throwIfNullOrUndefined(e,`language`),this.privLanguage=e,this.privEndpointId=n}static fromLanguage(t,n){return new e(t,n)}get language(){return this.privLanguage}get endpointId(){return this.privEndpointId}}})),Ut=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationTranscriber=void 0;var t=Q(),n=W(),r=k(),i=F(),a=Y();e.ConversationTranscriber=class e extends a.Recognizer{constructor(e,n){let r=e;i.Contracts.throwIfNull(r,`speechConfig`),i.Contracts.throwIfNullOrWhitespace(r.properties.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage),a.PropertyId[a.PropertyId.SpeechServiceConnection_RecoLanguage]),super(n,r.properties,new t.ConversationTranscriberConnectionFactory,e.tokenCredential),this.privProperties.setProperty(a.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,`2`),this.privDisposedRecognizer=!1}static FromConfig(t,n,r){let i=t;return n.properties.mergeTo(i.properties),new e(t,r)}get endpointId(){return i.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(a.PropertyId.SpeechServiceConnection_EndpointId,`00000000-0000-0000-0000-000000000000`)}get authorizationToken(){return this.properties.getProperty(a.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){i.Contracts.throwIfNullOrWhitespace(e,`token`),this.properties.setProperty(a.PropertyId.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return i.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage)}get outputFormat(){return i.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(t.OutputFormatPropertyName,a.OutputFormat[a.OutputFormat.Simple])===a.OutputFormat[a.OutputFormat.Simple]?a.OutputFormat.Simple:a.OutputFormat.Detailed}get properties(){return this.privProperties}startTranscribingAsync(e,t){(0,r.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(n.RecognitionMode.Conversation),e,t)}stopTranscribingAsync(e,t){(0,r.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(),e,t)}close(e,t){i.Contracts.throwIfDisposed(this.privDisposedRecognizer),(0,r.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}async dispose(e){this.privDisposedRecognizer||(e&&(this.privDisposedRecognizer=!0,await this.implRecognizerStop()),await super.dispose(e))}createRecognizerConfig(e){return new t.RecognizerConfig(e,this.privProperties)}createServiceRecognizer(e,n,r,i){let a=r;return i.isSpeakerDiarizationEnabled=!0,new t.ConversationTranscriptionServiceRecognizer(e,n,a,i,this)}}})),Wt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Participant=e.User=void 0;var t=Y();e.User=class{constructor(e){this.privUserId=e}get userId(){return this.privUserId}},e.Participant=class e{constructor(e,n,r){this.privId=e,this.privPreferredLanguage=n,this.privVoice=r,this.privProperties=new t.PropertyCollection}get id(){return this.privId}get preferredLanguage(){return this.privPreferredLanguage}get voice(){return this.privVoice}get properties(){return this.privProperties}static From(t,n,r){return new e(t,n,r)}}})),Gt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MeetingImpl=e.Meeting=void 0;var t=Q(),n=k(),r=F(),i=Y(),a=class{constructor(){}static createMeetingAsync(e,a,s,c){if(r.Contracts.throwIfNullOrUndefined(e,t.ConversationConnectionConfig.restErrors.invalidArgs.replace(`{arg}`,`config`)),r.Contracts.throwIfNullOrUndefined(e.region,t.ConversationConnectionConfig.restErrors.invalidArgs.replace(`{arg}`,`SpeechServiceConnection_Region`)),r.Contracts.throwIfNull(a,`meetingId`),a.length===0)throw Error(`meetingId cannot be empty`);!e.subscriptionKey&&!e.getProperty(i.PropertyId[i.PropertyId.SpeechServiceAuthorization_Token])&&r.Contracts.throwIfNullOrUndefined(e.subscriptionKey,t.ConversationConnectionConfig.restErrors.invalidArgs.replace(`{arg}`,`SpeechServiceConnection_Key`));let l=new o(e,a);return(0,n.marshalPromiseToCallbacks)((async()=>{})(),s,c),l}};e.Meeting=a;var o=class extends a{constructor(e,n){super(),this.privErrors=t.ConversationConnectionConfig.restErrors,this.privIsDisposed=!1,this.privMeetingId=``,this.privProperties=new i.PropertyCollection,e.getProperty(i.PropertyId[i.PropertyId.SpeechServiceConnection_RecoLanguage])||e.setProperty(i.PropertyId[i.PropertyId.SpeechServiceConnection_RecoLanguage],t.ConversationConnectionConfig.defaultLanguageCode),this.privLanguage=e.getProperty(i.PropertyId[i.PropertyId.SpeechServiceConnection_RecoLanguage]),this.privMeetingId=n,this.privConfig=e;let a=e;r.Contracts.throwIfNull(a,`speechConfig`),this.privProperties=a.properties.clone(),this.privParticipants=new t.InternalParticipants}get config(){return this.privConfig}get meetingId(){return this.privMeetingId}get properties(){return this.privProperties}get speechRecognitionLanguage(){return this.privLanguage}get participants(){return this.privParticipants.participants.map(e=>this.toParticipant(e))}get transcriberRecognizer(){return this.privTranscriberRecognizer}get meetingInfo(){let e=this.meetingId,n=this.participants.map(e=>({id:e.id,preferredLanguage:e.preferredLanguage,voice:e.voice})),r={};for(let e of t.ConversationConnectionConfig.transcriptionEventKeys){let t=this.properties.getProperty(e,``);t!==``&&(r[e]=t)}return{id:e,participants:n,meetingProperties:r}}get authorizationToken(){return this.privToken}set authorizationToken(e){r.Contracts.throwIfNullOrWhitespace(e,`authorizationToken`),this.privToken=e}addParticipantAsync(e,t,i){r.Contracts.throwIfNullOrUndefined(e,`Participant`),(0,n.marshalPromiseToCallbacks)(this.addParticipantImplAsync(e),t,i)}removeParticipantAsync(e,t,i){r.Contracts.throwIfDisposed(this.privIsDisposed),r.Contracts.throwIfNullOrUndefined(this.privTranscriberRecognizer,`Recognizer`),r.Contracts.throwIfNullOrUndefined(e,this.privErrors.invalidArgs.replace(`{arg}`,`userId`)),(0,n.marshalPromiseToCallbacks)(this.removeParticipantImplAsync(e),t,i)}isDisposed(){return this.privIsDisposed}dispose(){this.isDisposed||(this.privIsDisposed=!0,this.config&&this.config.close(),this.privConfig=void 0,this.privLanguage=void 0,this.privProperties=void 0,this.privToken=void 0,this.privParticipants=void 0)}async connectTranscriberRecognizer(e){this.privTranscriberRecognizer&&await this.privTranscriberRecognizer.close(),await e.enforceAudioGating(),this.privTranscriberRecognizer=e,this.privTranscriberRecognizer.meeting=this}addParticipantImplAsync(e){if(this.privParticipants.addOrUpdateParticipant(e)!==void 0&&this.privTranscriberRecognizer){let t=this.meetingInfo;return t.participants=[e],this.privTranscriberRecognizer.pushMeetingEvent(t,`join`)}}removeParticipantImplAsync(e){this.privParticipants.deleteParticipant(e.id);let t=this.meetingInfo;return t.participants=[e],this.privTranscriberRecognizer.pushMeetingEvent(t,`leave`)}toParticipant(e){return new i.Participant(e.id,e.preferredLanguage,e.voice)}};e.MeetingImpl=o})),Kt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MeetingTranscriptionCanceledEventArgs=void 0;var t=H();e.MeetingTranscriptionCanceledEventArgs=class extends t.CancellationEventArgsBase{}})),qt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MeetingTranscriber=void 0;var t=Q(),n=k(),r=F(),i=Y(),a=Yt();e.MeetingTranscriber=class{constructor(e){this.privAudioConfig=e,this.privProperties=new i.PropertyCollection,this.privRecognizer=void 0,this.privDisposedRecognizer=!1}get speechRecognitionLanguage(){return r.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(i.PropertyId.SpeechServiceConnection_RecoLanguage)}get properties(){return this.privProperties}get internalData(){return this.privRecognizer.internalData}get connection(){return i.Connection.fromRecognizer(this.privRecognizer)}get authorizationToken(){return this.properties.getProperty(i.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){r.Contracts.throwIfNullOrWhitespace(e,`token`),this.properties.setProperty(i.PropertyId.SpeechServiceAuthorization_Token,e)}joinMeetingAsync(e,i,o){let s=e;r.Contracts.throwIfNullOrUndefined(a.MeetingImpl,`Meeting`),this.privRecognizer=new t.TranscriberRecognizer(e.config,this.privAudioConfig),r.Contracts.throwIfNullOrUndefined(this.privRecognizer,`Recognizer`),this.privRecognizer.connectMeetingCallbacks(this),(0,n.marshalPromiseToCallbacks)(s.connectTranscriberRecognizer(this.privRecognizer),i,o)}startTranscribingAsync(e,t){this.privRecognizer.startContinuousRecognitionAsync(e,t)}stopTranscribingAsync(e,t){this.privRecognizer.stopContinuousRecognitionAsync(e,t)}leaveMeetingAsync(e,t){this.privRecognizer.disconnectCallbacks(),(0,n.marshalPromiseToCallbacks)((async()=>{})(),e,t)}close(e,t){r.Contracts.throwIfDisposed(this.privDisposedRecognizer),(0,n.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}async dispose(e){this.privDisposedRecognizer||(this.privRecognizer&&=(await this.privRecognizer.close(),void 0),e&&(this.privDisposedRecognizer=!0))}}})),Jt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationTranscriptionResult=void 0;var t=Y();e.ConversationTranscriptionResult=class extends t.RecognitionResult{constructor(e,t,n,r,i,a,o,s,c,l,u){super(e,t,n,r,i,a,o,c,l,u),this.privSpeakerId=s}get speakerId(){return this.privSpeakerId}}})),Yt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationTranscriptionResult=e.MeetingTranscriber=e.MeetingTranscriptionCanceledEventArgs=e.MeetingImpl=e.Meeting=e.User=e.Participant=e.ConversationTranscriber=void 0;var t=Ut();Object.defineProperty(e,"ConversationTranscriber",{enumerable:!0,get:function(){return t.ConversationTranscriber}});var n=Wt();Object.defineProperty(e,"Participant",{enumerable:!0,get:function(){return n.Participant}}),Object.defineProperty(e,"User",{enumerable:!0,get:function(){return n.User}});var r=Gt();Object.defineProperty(e,"Meeting",{enumerable:!0,get:function(){return r.Meeting}}),Object.defineProperty(e,"MeetingImpl",{enumerable:!0,get:function(){return r.MeetingImpl}});var i=Kt();Object.defineProperty(e,"MeetingTranscriptionCanceledEventArgs",{enumerable:!0,get:function(){return i.MeetingTranscriptionCanceledEventArgs}});var a=qt();Object.defineProperty(e,"MeetingTranscriber",{enumerable:!0,get:function(){return a.MeetingTranscriber}});var o=Jt();Object.defineProperty(e,"ConversationTranscriptionResult",{enumerable:!0,get:function(){return o.ConversationTranscriptionResult}})})),J=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.StreamingSynthesisRequest=e.SynthesisRequest=e.Synthesizer=void 0;var t=Q(),n=k(),r=F(),i=Y();e.Synthesizer=class e{constructor(e){let t=e;r.Contracts.throwIfNull(t,`speechConfig`),this.privProperties=t.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.synthesisRequestQueue=new n.Queue,this.tokenCredential=e.tokenCredential}get authorizationToken(){return this.properties.getProperty(i.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){r.Contracts.throwIfNullOrWhitespace(e,`token`),this.properties.setProperty(i.PropertyId.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(i.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages)===t.AutoDetectSourceLanguagesOpenRangeOptionName}buildSsml(t){let n={"af-ZA":`af-ZA-AdriNeural`,"am-ET":`am-ET-AmehaNeural`,"ar-AE":`ar-AE-FatimaNeural`,"ar-BH":`ar-BH-AliNeural`,"ar-DZ":`ar-DZ-AminaNeural`,"ar-EG":`ar-EG-SalmaNeural`,"ar-IQ":`ar-IQ-BasselNeural`,"ar-JO":`ar-JO-SanaNeural`,"ar-KW":`ar-KW-FahedNeural`,"ar-LY":`ar-LY-ImanNeural`,"ar-MA":`ar-MA-JamalNeural`,"ar-QA":`ar-QA-AmalNeural`,"ar-SA":`ar-SA-HamedNeural`,"ar-SY":`ar-SY-AmanyNeural`,"ar-TN":`ar-TN-HediNeural`,"ar-YE":`ar-YE-MaryamNeural`,"bg-BG":`bg-BG-BorislavNeural`,"bn-BD":`bn-BD-NabanitaNeural`,"bn-IN":`bn-IN-BashkarNeural`,"ca-ES":`ca-ES-JoanaNeural`,"cs-CZ":`cs-CZ-AntoninNeural`,"cy-GB":`cy-GB-AledNeural`,"da-DK":`da-DK-ChristelNeural`,"de-AT":`de-AT-IngridNeural`,"de-CH":`de-CH-JanNeural`,"de-DE":`de-DE-KatjaNeural`,"el-GR":`el-GR-AthinaNeural`,"en-AU":`en-AU-NatashaNeural`,"en-CA":`en-CA-ClaraNeural`,"en-GB":`en-GB-LibbyNeural`,"en-HK":`en-HK-SamNeural`,"en-IE":`en-IE-ConnorNeural`,"en-IN":`en-IN-NeerjaNeural`,"en-KE":`en-KE-AsiliaNeural`,"en-NG":`en-NG-AbeoNeural`,"en-NZ":`en-NZ-MitchellNeural`,"en-PH":`en-PH-JamesNeural`,"en-SG":`en-SG-LunaNeural`,"en-TZ":`en-TZ-ElimuNeural`,"en-US":`en-US-AvaMultilingualNeural`,"en-ZA":`en-ZA-LeahNeural`,"es-AR":`es-AR-ElenaNeural`,"es-BO":`es-BO-MarceloNeural`,"es-CL":`es-CL-CatalinaNeural`,"es-CO":`es-CO-GonzaloNeural`,"es-CR":`es-CR-JuanNeural`,"es-CU":`es-CU-BelkysNeural`,"es-DO":`es-DO-EmilioNeural`,"es-EC":`es-EC-AndreaNeural`,"es-ES":`es-ES-AlvaroNeural`,"es-GQ":`es-GQ-JavierNeural`,"es-GT":`es-GT-AndresNeural`,"es-HN":`es-HN-CarlosNeural`,"es-MX":`es-MX-DaliaNeural`,"es-NI":`es-NI-FedericoNeural`,"es-PA":`es-PA-MargaritaNeural`,"es-PE":`es-PE-AlexNeural`,"es-PR":`es-PR-KarinaNeural`,"es-PY":`es-PY-MarioNeural`,"es-SV":`es-SV-LorenaNeural`,"es-US":`es-US-AlonsoNeural`,"es-UY":`es-UY-MateoNeural`,"es-VE":`es-VE-PaolaNeural`,"et-EE":`et-EE-AnuNeural`,"fa-IR":`fa-IR-DilaraNeural`,"fi-FI":`fi-FI-SelmaNeural`,"fil-PH":`fil-PH-AngeloNeural`,"fr-BE":`fr-BE-CharlineNeural`,"fr-CA":`fr-CA-SylvieNeural`,"fr-CH":`fr-CH-ArianeNeural`,"fr-FR":`fr-FR-DeniseNeural`,"ga-IE":`ga-IE-ColmNeural`,"gl-ES":`gl-ES-RoiNeural`,"gu-IN":`gu-IN-DhwaniNeural`,"he-IL":`he-IL-AvriNeural`,"hi-IN":`hi-IN-MadhurNeural`,"hr-HR":`hr-HR-GabrijelaNeural`,"hu-HU":`hu-HU-NoemiNeural`,"id-ID":`id-ID-ArdiNeural`,"is-IS":`is-IS-GudrunNeural`,"it-IT":`it-IT-IsabellaNeural`,"ja-JP":`ja-JP-NanamiNeural`,"jv-ID":`jv-ID-DimasNeural`,"kk-KZ":`kk-KZ-AigulNeural`,"km-KH":`km-KH-PisethNeural`,"kn-IN":`kn-IN-GaganNeural`,"ko-KR":`ko-KR-SunHiNeural`,"lo-LA":`lo-LA-ChanthavongNeural`,"lt-LT":`lt-LT-LeonasNeural`,"lv-LV":`lv-LV-EveritaNeural`,"mk-MK":`mk-MK-AleksandarNeural`,"ml-IN":`ml-IN-MidhunNeural`,"mr-IN":`mr-IN-AarohiNeural`,"ms-MY":`ms-MY-OsmanNeural`,"mt-MT":`mt-MT-GraceNeural`,"my-MM":`my-MM-NilarNeural`,"nb-NO":`nb-NO-PernilleNeural`,"nl-BE":`nl-BE-ArnaudNeural`,"nl-NL":`nl-NL-ColetteNeural`,"pl-PL":`pl-PL-AgnieszkaNeural`,"ps-AF":`ps-AF-GulNawazNeural`,"pt-BR":`pt-BR-FranciscaNeural`,"pt-PT":`pt-PT-DuarteNeural`,"ro-RO":`ro-RO-AlinaNeural`,"ru-RU":`ru-RU-SvetlanaNeural`,"si-LK":`si-LK-SameeraNeural`,"sk-SK":`sk-SK-LukasNeural`,"sl-SI":`sl-SI-PetraNeural`,"so-SO":`so-SO-MuuseNeural`,"sr-RS":`sr-RS-NicholasNeural`,"su-ID":`su-ID-JajangNeural`,"sv-SE":`sv-SE-SofieNeural`,"sw-KE":`sw-KE-RafikiNeural`,"sw-TZ":`sw-TZ-DaudiNeural`,"ta-IN":`ta-IN-PallaviNeural`,"ta-LK":`ta-LK-KumarNeural`,"ta-SG":`ta-SG-AnbuNeural`,"te-IN":`te-IN-MohanNeural`,"th-TH":`th-TH-PremwadeeNeural`,"tr-TR":`tr-TR-AhmetNeural`,"uk-UA":`uk-UA-OstapNeural`,"ur-IN":`ur-IN-GulNeural`,"ur-PK":`ur-PK-AsadNeural`,"uz-UZ":`uz-UZ-MadinaNeural`,"vi-VN":`vi-VN-HoaiMyNeural`,"zh-CN":`zh-CN-XiaoxiaoNeural`,"zh-HK":`zh-HK-HiuMaanNeural`,"zh-TW":`zh-TW-HsiaoChenNeural`,"zu-ZA":`zu-ZA-ThandoNeural`},r=this.properties.getProperty(i.PropertyId.SpeechServiceConnection_SynthLanguage,`en-US`),a=this.properties.getProperty(i.PropertyId.SpeechServiceConnection_SynthVoice,``),o=e.XMLEncode(t);return this.autoDetectSourceLanguage?r=`en-US`:a||=n[r],a&&(o=`<voice name='${a}'>${o}</voice>`),o=`<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='http://www.w3.org/2001/mstts' xmlns:emo='http://www.w3.org/2009/10/emotionml' xml:lang='${r}'>${o}</speak>`,o}async dispose(e){this.privDisposed||=(e&&this.privAdapter&&await this.privAdapter.dispose(),!0)}async adapterSpeak(){if(!this.privDisposed&&!this.privSynthesizing){this.privSynthesizing=!0;let e=await this.synthesisRequestQueue.dequeue();return e instanceof a?this.privAdapter.SpeakStream(e.speechSynthesisRequest,e.requestId,e.cb,e.err,e.dataStream):this.privAdapter.Speak(e.text,e.isSSML,e.requestId,e.cb,e.err,e.dataStream)}}createSynthesizerConfig(e){return new t.SynthesizerConfig(e,this.privProperties)}implCommonSynthesizeSetup(){let e=typeof window<`u`?`Browser`:`Node`,n=`unknown`,r=`unknown`;typeof navigator<`u`&&(e=e+`/`+navigator.platform,n=navigator.userAgent,r=navigator.appVersion);let a=this.createSynthesizerConfig(new t.SpeechServiceConfig(new t.Context(new t.OS(e,n,r)))),o=this.privProperties.getProperty(i.PropertyId.SpeechServiceConnection_Key,void 0),s=o&&o!==``?new t.CognitiveSubscriptionKeyAuthentication(o):this.tokenCredential?new t.CognitiveTokenAuthentication(async()=>{try{return(await this.tokenCredential.getToken(`https://cognitiveservices.azure.com/.default`))?.token??``}catch(e){throw e}},async()=>{try{return(await this.tokenCredential.getToken(`https://cognitiveservices.azure.com/.default`))?.token??``}catch(e){throw e}}):new t.CognitiveTokenAuthentication(()=>{let e=this.privProperties.getProperty(i.PropertyId.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(e)},()=>{let e=this.privProperties.getProperty(i.PropertyId.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(e)});this.privAdapter=this.createSynthesisAdapter(s,this.privConnectionFactory,a),this.privRestAdapter=this.createRestSynthesisAdapter(s,a)}static XMLEncode(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}},e.SynthesisRequest=class{constructor(e,t,n,r,i,a){this.requestId=e,this.text=t,this.isSSML=n,this.cb=r??(()=>{}),this.err=i??(()=>{}),this.dataStream=a??void 0}};var a=class{constructor(e,t,n,r,i){this.requestId=e,this.speechSynthesisRequest=t,this.cb=n??(()=>{}),this.err=r??(()=>{}),this.dataStream=i??void 0}};e.StreamingSynthesisRequest=a})),Xt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesizer=void 0;var t=Q(),n=k(),r=z(),i=B(),a=V(),o=F(),s=Y(),c=J();e.SpeechSynthesizer=class e extends s.Synthesizer{constructor(e,n){super(e),n!==null&&(this.audioConfig=n===void 0?typeof window>`u`?void 0:s.AudioConfig.fromDefaultSpeakerOutput():n),this.privConnectionFactory=new t.SpeechSynthesisConnectionFactory,this.implCommonSynthesizeSetup()}static FromConfig(t,n,r){let i=t;return n.properties.mergeTo(i.properties),new e(t,r)}speakTextAsync(e,t,n,r){this.speakImpl(e,!1,t,n,r)}speakSsmlAsync(e,t,n,r){this.speakImpl(e,!0,t,n,r)}speakAsync(e,t,r,i){try{o.Contracts.throwIfDisposed(this.privDisposed);let a=(0,n.createNoDashGuid)(),s=this.resolveAudioDestination(i),{onSuccess:l,onError:u}=this.createSynthesisCallbacks(t,r,()=>{this.adapterSpeak().catch(()=>{})});this.synthesisRequestQueue.enqueue(new c.StreamingSynthesisRequest(a,e,l,u,s)),this.adapterSpeak().catch(()=>{})}catch(e){this.handleSpeakError(e,r)}}async getVoicesAsync(e=``){return this.getVoices(e)}close(e,t){o.Contracts.throwIfDisposed(this.privDisposed),(0,n.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}createSynthesisAdapter(e,n,r){return new t.SpeechSynthesisAdapter(e,n,r,this,this.audioConfig)}createRestSynthesisAdapter(e,n){return new t.SynthesisRestAdapter(n,e)}implCommonSynthesizeSetup(){super.implCommonSynthesizeSetup(),this.privAdapter.audioOutputFormat=i.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(s.SpeechSynthesisOutputFormat[this.properties.getProperty(s.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0)])}speakImpl(e,t,r,i,a){try{o.Contracts.throwIfDisposed(this.privDisposed);let s=(0,n.createNoDashGuid)(),l=this.resolveAudioDestination(a),{onSuccess:u,onError:d}=this.createSynthesisCallbacks(r,i,()=>{this.adapterSpeak().catch(()=>{})});this.synthesisRequestQueue.enqueue(new c.SynthesisRequest(s,e,t,u,d,l)),this.adapterSpeak().catch(()=>{})}catch(e){this.handleSpeakError(e,i)}}resolveAudioDestination(e){if(e instanceof s.PushAudioOutputStreamCallback)return new a.PushAudioOutputStreamImpl(e);if(e instanceof s.PullAudioOutputStream)return e;if(e!==void 0)return new r.AudioFileWriter(e)}createSynthesisCallbacks(e,t,n){let r=e;return{onError:e=>{this.privSynthesizing=!1,t&&t(e),n&&n()},onSuccess:e=>{if(this.privSynthesizing=!1,r)try{r(e)}catch(e){t&&t(e)}r=void 0,n&&n()}}}handleSpeakError(e,t){if(t){if(e instanceof Error){let n=e;t(n.name+`: `+n.message)}else t(e)}this.dispose(!0).catch(()=>{})}async getVoices(e){let t=(0,n.createNoDashGuid)(),r=await this.privRestAdapter.getVoicesList(t);if(r.ok&&Array.isArray(r.json)){let n=r.json;return e&&e.length>0&&(n=n.filter(t=>!!t.Locale&&t.Locale.toLowerCase()===e.toLowerCase())),new s.SynthesisVoicesResult(t,n,void 0)}return new s.SynthesisVoicesResult(t,void 0,`Error: ${r.status}: ${r.statusText}`)}}})),Zt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesisResult=void 0,e.SynthesisResult=class{constructor(e,t,n,r){this.privResultId=e,this.privReason=t,this.privErrorDetails=n,this.privProperties=r}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}})),Qt=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisResult=void 0;var t=Y();e.SpeechSynthesisResult=class extends t.SynthesisResult{constructor(e,t,n,r,i,a){super(e,t,r,i),this.privAudioData=n,this.privAudioDuration=a}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}})),$t=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisEventArgs=void 0,e.SpeechSynthesisEventArgs=class{constructor(e){this.privResult=e}get result(){return this.privResult}}})),en=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisWordBoundaryEventArgs=void 0,e.SpeechSynthesisWordBoundaryEventArgs=class{constructor(e,t,n,r,i,a){this.privAudioOffset=e,this.privDuration=t,this.privText=n,this.privWordLength=r,this.privTextOffset=i,this.privBoundaryType=a}get audioOffset(){return this.privAudioOffset}get duration(){return this.privDuration}get text(){return this.privText}get wordLength(){return this.privWordLength}get textOffset(){return this.privTextOffset}get boundaryType(){return this.privBoundaryType}}})),tn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisBookmarkEventArgs=void 0,e.SpeechSynthesisBookmarkEventArgs=class{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}})),nn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisVisemeEventArgs=void 0,e.SpeechSynthesisVisemeEventArgs=class{constructor(e,t,n){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=n}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}})),rn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisBoundaryType=void 0,(function(e){e.Word=`WordBoundary`,e.Punctuation=`PunctuationBoundary`,e.Sentence=`SentenceBoundary`})(e.SpeechSynthesisBoundaryType||={})})),an=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisRequestInputType=void 0,(function(e){e[e.Text=1]=`Text`,e[e.SSML=2]=`SSML`,e[e.TextStream=3]=`TextStream`})(e.SpeechSynthesisRequestInputType||={})})),on=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisRequestInputStream=void 0,e.SpeechSynthesisRequestInputStream=class{constructor(e){this.privClosed=!1,this.privParent=e}write(e){if(this.privClosed)throw Error(`Cannot write to a closed input stream.`);this.privParent.onTextPieceReceived(e)}close(){this.privClosed||(this.privClosed=!0,this.privParent.onInputStreamClosed())}get isClosed(){return this.privClosed}}})),sn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisRequest=e.SpeechSynthesisRequestInputStream=void 0;var t=Y(),n=an(),r=on(),i=on();Object.defineProperty(e,"SpeechSynthesisRequestInputStream",{enumerable:!0,get:function(){return i.SpeechSynthesisRequestInputStream}}),e.SpeechSynthesisRequest=class{constructor(e){if(this.privBufferedTextPieces=[],this.privStreamClosedBeforeReady=!1,e!==n.SpeechSynthesisRequestInputType.TextStream)throw Error(`Only TextStream input type is supported in this version.`);this.privInputType=e,this.privInputStream=new r.SpeechSynthesisRequestInputStream(this),this.privProperties=new t.PropertyCollection}get inputType(){return this.privInputType}get inputStream(){return this.privInputStream}get properties(){return this.privProperties}set pitch(e){this.privProperties.setProperty(t.PropertyId.SpeechSynthesisRequest_Pitch,e)}set rate(e){this.privProperties.setProperty(t.PropertyId.SpeechSynthesisRequest_Rate,e)}set volume(e){this.privProperties.setProperty(t.PropertyId.SpeechSynthesisRequest_Volume,e)}set style(e){this.privProperties.setProperty(t.PropertyId.SpeechSynthesisRequest_Style,e)}set temperature(e){this.privProperties.setProperty(t.PropertyId.SpeechSynthesisRequest_Temperature,e.toString())}set customLexiconUrl(e){this.privProperties.setProperty(t.PropertyId.SpeechSynthesisRequest_CustomLexiconUrl,e)}set preferLocales(e){this.privProperties.setProperty(t.PropertyId.SpeechSynthesisRequest_PreferLocales,e)}onTextPieceReceived(e){this.privTextPieceCallback?this.privTextPieceCallback(e):this.privBufferedTextPieces.push(e)}onInputStreamClosed(){this.privStreamCloseCallback?this.privStreamCloseCallback():this.privStreamClosedBeforeReady=!0}set onTextPiece(e){this.privTextPieceCallback=e;for(let t of this.privBufferedTextPieces)e(t);this.privBufferedTextPieces=[]}set onClose(e){this.privStreamCloseCallback=e,this.privStreamClosedBeforeReady&&(this.privStreamClosedBeforeReady=!1,e())}}})),cn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesisVoicesResult=void 0;var t=Y();e.SynthesisVoicesResult=class extends t.SynthesisResult{constructor(e,n,r){if(Array.isArray(n)){super(e,t.ResultReason.VoicesListRetrieved,void 0,new t.PropertyCollection),this.privVoices=[];for(let e of n)this.privVoices.push(new t.VoiceInfo(e))}else super(e,t.ResultReason.Canceled,r||`Error information unavailable`,new t.PropertyCollection)}get voices(){return this.privVoices}}})),ln=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.VoiceInfo=e.SynthesisVoiceType=e.SynthesisVoiceGender=void 0;var t;(function(e){e[e.Unknown=0]=`Unknown`,e[e.Female=1]=`Female`,e[e.Male=2]=`Male`,e[e.Neutral=3]=`Neutral`})(t=e.SynthesisVoiceGender||={});var n;(function(e){e[e.Unknown=0]=`Unknown`,e[e.OnlineNeural=1]=`OnlineNeural`,e[e.OnlineStandard=2]=`OnlineStandard`,e[e.OfflineNeural=3]=`OfflineNeural`,e[e.OfflineStandard=4]=`OfflineStandard`,e[e.OnlineNeuralHD=5]=`OnlineNeuralHD`})(n=e.SynthesisVoiceType||={});var r={[t[t.Neutral]]:t.Neutral,[t[t.Male]]:t.Male,[t[t.Female]]:t.Female},i={Neural:n.OnlineNeural,NeuralHD:n.OnlineNeuralHD};e.VoiceInfo=class{constructor(e){if(this.privStyleList=[],e){if(this.privName=e.Name,this.privLocale=e.Locale,this.privShortName=e.ShortName,this.privLocaleName=e.LocaleName,this.privDisplayName=e.DisplayName,this.privLocalName=e.LocalName,this.privVoiceType=i[e.VoiceType]||n.Unknown,this.privGender=r[e.Gender]||t.Unknown,e.StyleList&&Array.isArray(e.StyleList))for(let t of e.StyleList)this.privStyleList.push(t);this.privSampleRateHertz=e.SampleRateHertz,this.privStatus=e.Status,e.ExtendedPropertyMap&&(this.privExtendedPropertyMap=e.ExtendedPropertyMap),this.privWordsPerMinute=e.WordsPerMinute,Array.isArray(e.SecondaryLocaleList)&&(this.privSecondaryLocaleList=[...e.SecondaryLocaleList]),Array.isArray(e.RolePlayList)&&(this.privRolePlayList=[...e.RolePlayList]),e.VoiceTag&&(this.privVoiceTag=e.VoiceTag)}}get name(){return this.privName}get locale(){return this.privLocale}get shortName(){return this.privShortName}get displayName(){return this.privDisplayName}get localName(){return this.privLocalName}get localeName(){return this.privLocaleName}get gender(){return this.privGender}get voiceType(){return this.privVoiceType}get styleList(){return this.privStyleList}get sampleRateHertz(){return this.privSampleRateHertz}get status(){return this.privStatus}get extendedPropertyMap(){return this.privExtendedPropertyMap}get wordsPerMinute(){return this.privWordsPerMinute}get secondaryLocaleList(){return this.privSecondaryLocaleList}get rolePlayList(){return this.privRolePlayList}get voiceTag(){return this.privVoiceTag}}})),un=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeakerAudioDestination=void 0;var t=k(),n=V(),r=I(),i=1800,a={[r.AudioFormatTag.PCM]:`audio/wav`,[r.AudioFormatTag.MuLaw]:`audio/x-wav`,[r.AudioFormatTag.MP3]:`audio/mpeg`,[r.AudioFormatTag.OGG_OPUS]:`audio/ogg`,[r.AudioFormatTag.WEBM_OPUS]:`audio/webm; codecs=opus`,[r.AudioFormatTag.ALaw]:`audio/x-wav`,[r.AudioFormatTag.FLAC]:`audio/flac`,[r.AudioFormatTag.AMR_WB]:`audio/amr-wb`,[r.AudioFormatTag.G722]:`audio/G722`};e.SpeakerAudioDestination=class{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||(0,t.createNoDashGuid)(),this.privIsPaused=!1,this.privIsClosed=!1}id(){return this.privId}write(e,t,n){this.privAudioBuffer===void 0?this.privAudioOutputStream!==void 0&&(this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength):(this.privAudioBuffer.push(e),this.updateSourceBuffer().then(()=>{t&&t()},e=>{n&&n(e)}))}close(e,t){if(this.privIsClosed=!0,this.privSourceBuffer!==void 0)this.handleSourceBufferUpdateEnd().then(()=>{e&&e()},e=>{t&&t(e)});else if(this.privAudioOutputStream!==void 0&&typeof window<`u`){if((this.privFormat.formatTag===r.AudioFormatTag.PCM||this.privFormat.formatTag===r.AudioFormatTag.MuLaw||this.privFormat.formatTag===r.AudioFormatTag.ALaw)&&this.privFormat.hasHeader===!1)console.warn(`Play back is not supported for raw PCM, mulaw or alaw format without header.`),this.onAudioEnd&&this.onAudioEnd(this);else{let n=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(n).then(()=>{n=this.privFormat.addHeader(n);let r=new Blob([n],{type:a[this.privFormat.formatTag]});this.privAudio.src=window.URL.createObjectURL(r),this.notifyPlayback().then(()=>{e&&e()},e=>{t&&t(e)})},e=>{t&&t(e)})}}else this.onAudioEnd&&this.onAudioEnd(this)}set format(e){if(typeof AudioContext<`u`||typeof window<`u`&&window.webkitAudioContext!==void 0){this.privFormat=e;let o=a[this.privFormat.formatTag];o===void 0?console.warn(`Unknown mimeType for format ${r.AudioFormatTag[this.privFormat.formatTag]}; playback is not supported.`):typeof MediaSource<`u`&&MediaSource.isTypeSupported(o)?(this.privAudio=new Audio,this.privAudioBuffer=[],this.privMediaSource=new MediaSource,this.privAudio.src=URL.createObjectURL(this.privMediaSource),this.privAudio.load(),this.privMediaSource.onsourceopen=()=>{this.privMediaSourceOpened=!0,this.privMediaSource.duration=i,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(o),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(e=>{t.Events.instance.onEvent(new t.BackgroundEvent(e))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(e=>{t.Events.instance.onEvent(new t.BackgroundEvent(e))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(e=>{t.Events.instance.onEvent(new t.BackgroundEvent(e))})):(console.warn(`Format ${r.AudioFormatTag[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new n.PullAudioOutputStreamImpl,this.privAudioOutputStream.format=this.privFormat,this.privAudio=new Audio)}}get volume(){return this.privAudio?.volume??-1}set volume(e){this.privAudio&&(this.privAudio.volume=e)}mute(){this.privAudio&&(this.privAudio.muted=!0)}unmute(){this.privAudio&&(this.privAudio.muted=!1)}get isClosed(){return this.privIsClosed}get currentTime(){return this.privAudio===void 0?-1:this.privAudio.currentTime}pause(){!this.privIsPaused&&this.privAudio!==void 0&&(this.privAudio.pause(),this.privIsPaused=!0)}resume(e,t){this.privIsPaused&&this.privAudio!==void 0&&(this.privAudio.play().then(()=>{e&&e()},e=>{t&&t(e)}),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}async updateSourceBuffer(){if(this.privAudioBuffer!==void 0&&this.privAudioBuffer.length>0&&this.sourceBufferAvailable()){this.privAppendingToBuffer=!0;let e=this.privAudioBuffer.shift();try{this.privSourceBuffer.appendBuffer(e)}catch{this.privAudioBuffer.unshift(e),console.log(`buffer filled, pausing addition of binaries until space is made`);return}await this.notifyPlayback()}else this.canEndStream()&&await this.handleSourceBufferUpdateEnd()}async handleSourceBufferUpdateEnd(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),await this.notifyPlayback())}async notifyPlayback(){!this.privPlaybackStarted&&this.privAudio!==void 0&&(this.privPlaybackStarted=!0,this.onAudioStart&&this.onAudioStart(this),this.privAudio.onended=()=>{this.onAudioEnd&&this.onAudioEnd(this)},this.privIsPaused||await this.privAudio.play())}canEndStream(){return this.isClosed&&this.privSourceBuffer!==void 0&&this.privAudioBuffer.length===0&&this.privMediaSourceOpened&&!this.privAppendingToBuffer&&this.privMediaSource.readyState===`open`}sourceBufferAvailable(){return this.privSourceBuffer!==void 0&&!this.privSourceBuffer.updating}}})),dn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationTranscriptionCanceledEventArgs=void 0;var t=H();e.ConversationTranscriptionCanceledEventArgs=class extends t.CancellationEventArgsBase{}})),fn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MeetingTranscriptionCanceledEventArgs=void 0;var t=H();e.MeetingTranscriptionCanceledEventArgs=class extends t.CancellationEventArgsBase{}})),pn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PronunciationAssessmentGradingSystem=void 0,(function(e){e[e.FivePoint=1]=`FivePoint`,e[e.HundredMark=2]=`HundredMark`})(e.PronunciationAssessmentGradingSystem||={})})),mn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PronunciationAssessmentGranularity=void 0,(function(e){e[e.Phoneme=1]=`Phoneme`,e[e.Word=2]=`Word`,e[e.FullText=3]=`FullText`})(e.PronunciationAssessmentGranularity||={})})),hn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PronunciationAssessmentConfig=void 0;var t=F(),n=Y();e.PronunciationAssessmentConfig=class e{constructor(e,r=n.PronunciationAssessmentGradingSystem.FivePoint,i=n.PronunciationAssessmentGranularity.Phoneme,a=!1){t.Contracts.throwIfNullOrUndefined(e,`referenceText`),this.privProperties=new n.PropertyCollection,this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_ReferenceText,e),this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_GradingSystem,n.PronunciationAssessmentGradingSystem[r]),this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_Granularity,n.PronunciationAssessmentGranularity[i]),this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_EnableMiscue,String(a))}static fromJSON(r){t.Contracts.throwIfNullOrUndefined(r,`json`);let i=new e(``);return i.privProperties=new n.PropertyCollection,i.properties.setProperty(n.PropertyId.PronunciationAssessment_Json,r),i}toJSON(){return this.updateJson(),this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_Params)}applyTo(e){this.updateJson();let t=e.internalData;t.speechContext.setPronunciationAssessmentParams(this.properties.getProperty(n.PropertyId.PronunciationAssessment_Params),t.isSpeakerDiarizationEnabled)}get referenceText(){return this.properties.getProperty(n.PropertyId.PronunciationAssessment_ReferenceText)}set referenceText(e){t.Contracts.throwIfNullOrWhitespace(e,`referenceText`),this.properties.setProperty(n.PropertyId.PronunciationAssessment_ReferenceText,e)}set phonemeAlphabet(e){t.Contracts.throwIfNullOrWhitespace(e,`phonemeAlphabet`),this.privPhonemeAlphabet=e}set enableMiscue(e){let t=e?`true`:`false`;this.properties.setProperty(n.PropertyId.PronunciationAssessment_EnableMiscue,t)}get enableMiscue(){return this.properties.getProperty(n.PropertyId.PronunciationAssessment_EnableMiscue,`false`).toLowerCase()===`true`}set nbestPhonemeCount(e){this.privNBestPhonemeCount=e}set enableProsodyAssessment(e){this.privEnableProsodyAssessment=e}get properties(){return this.privProperties}updateJson(){let e=this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_Json,`{}`),t=JSON.parse(e),r=this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_ReferenceText);r&&(t.referenceText=r);let i=this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_GradingSystem);i&&(t.gradingSystem=i);let a=this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_Granularity);a&&(t.granularity=a),this.privPhonemeAlphabet&&(t.phonemeAlphabet=this.privPhonemeAlphabet),this.privNBestPhonemeCount&&(t.nbestPhonemeCount=this.privNBestPhonemeCount),t.enableProsodyAssessment=this.privEnableProsodyAssessment,t.dimension=`Comprehensive`,this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_EnableMiscue)&&(t.enableMiscue=this.enableMiscue),this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_Params,JSON.stringify(t))}}})),gn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PronunciationAssessmentResult=void 0;var t=F(),n=Y();e.PronunciationAssessmentResult=class e{constructor(e){let n=JSON.parse(e);t.Contracts.throwIfNullOrUndefined(n.NBest[0],`NBest`),this.privPronJson=n.NBest[0]}static fromResult(r){t.Contracts.throwIfNullOrUndefined(r,`result`);let i=r.properties.getProperty(n.PropertyId.SpeechServiceResponse_JsonResult);return t.Contracts.throwIfNullOrUndefined(i,`json`),new e(i)}get detailResult(){return this.privPronJson}get accuracyScore(){return this.detailResult.PronunciationAssessment?.AccuracyScore}get pronunciationScore(){return this.detailResult.PronunciationAssessment?.PronScore}get completenessScore(){return this.detailResult.PronunciationAssessment?.CompletenessScore}get fluencyScore(){return this.detailResult.PronunciationAssessment?.FluencyScore}get prosodyScore(){return this.detailResult.PronunciationAssessment?.ProsodyScore}}})),_n=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AvatarConfig=void 0;var t=F(),n=Y();e.AvatarConfig=class{constructor(e,r,i){this.privCustomized=!1,this.privUseBuiltInVoice=!1,t.Contracts.throwIfNullOrWhitespace(e,`character`),this.character=e,this.style=r,i===void 0&&(i=new n.AvatarVideoFormat),this.videoFormat=i}get customized(){return this.privCustomized}set customized(e){this.privCustomized=e}get useBuiltInVoice(){return this.privUseBuiltInVoice}set useBuiltInVoice(e){this.privUseBuiltInVoice=e}get photoAvatarBaseModel(){return this.privPhotoAvatarBaseModel}set photoAvatarBaseModel(e){this.privPhotoAvatarBaseModel=e}get backgroundColor(){return this.privBackgroundColor}set backgroundColor(e){this.privBackgroundColor=e}get backgroundImage(){return this.privBackgroundImage}set backgroundImage(e){this.privBackgroundImage=e}get remoteIceServers(){return this.privRemoteIceServers}set remoteIceServers(e){this.privRemoteIceServers=e}get scene(){return this.privScene}set scene(e){this.privScene=e}}})),vn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AvatarEventArgs=e.AvatarEventTypes=void 0,(function(e){e.SwitchedToSpeaking=`SwitchedToSpeaking`,e.SwitchedToIdle=`SwitchedToIdle`,e.SessionClosed=`SessionClosed`})(e.AvatarEventTypes||={}),e.AvatarEventArgs=class{constructor(e,t){this.privOffset=e,this.privDescription=t}get type(){return this.privType}get offset(){return this.privOffset}get description(){return this.privDescription}}})),yn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AvatarSceneConfig=void 0,e.AvatarSceneConfig=class{constructor(e=1,t=0,n=0,r=0,i=0,a=0,o=1){this.zoom=e,this.positionX=t,this.positionY=n,this.rotationX=r,this.rotationY=i,this.rotationZ=a,this.amplitude=o}}})),bn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisConnectionFactory=void 0;var t=X(),n=Y(),r=q(),i=Q(),a=A(),o=K();e.SpeechSynthesisConnectionFactory=class{constructor(){this.synthesisUri=`/tts/cognitiveservices/websocket/v1`}async create(e,s,c){let l=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Endpoint,void 0),u=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Region,void 0),d=r.ConnectionFactoryBase.getHostSuffix(u),f=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_EndpointId,void 0),p=f===void 0?`tts`:`voice`,m=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Host,`wss://`+u+`.`+p+`.speech`+d),h={},g={};if(s.token!==void 0&&s.token!==``&&(g[s.headerName]=s.token),g[a.HeaderNames.ConnectionId]=c,f!==void 0&&f!==``&&(!l||l.search(o.QueryParameterNames.CustomVoiceDeploymentId)===-1)&&(h[o.QueryParameterNames.CustomVoiceDeploymentId]=f),e.avatarEnabled&&(!l||l.search(o.QueryParameterNames.EnableAvatar)===-1)&&(h[o.QueryParameterNames.EnableAvatar]=`true`),l){let e=new URL(l),t=e.pathname;(t===``||t===`/`||t.toLowerCase()===this.synthesisUri)&&(e.pathname=this.synthesisUri,l=await r.ConnectionFactoryBase.getRedirectUrlFromEndpoint(e.toString()))}l||=m+this.synthesisUri,e.parameters.setProperty(n.PropertyId.SpeechServiceConnection_Url,l);let _=e.parameters.getProperty(`SPEECH-EnableWebsocketCompression`,`false`)===`true`;return new t.WebsocketConnection(l,h,g,new i.WebsocketMessageFormatter,t.ProxyInfo.fromParameters(e.parameters),_,c)}}})),xn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AvatarSynthesizer=void 0;var t=bn(),n=Q(),r=k(),i=B(),a=Y(),o=F(),s=J();e.AvatarSynthesizer=class extends a.Synthesizer{constructor(e,n){super(e),o.Contracts.throwIfNullOrUndefined(n,`avatarConfig`),this.privConnectionFactory=new t.SpeechSynthesisConnectionFactory,this.privAvatarConfig=n,this.implCommonSynthesizeSetup()}implCommonSynthesizeSetup(){super.implCommonSynthesizeSetup(),this.privAdapter.audioOutputFormat=i.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(a.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm)}async startAvatarAsync(e){o.Contracts.throwIfNullOrUndefined(e,`peerConnection`),this.privIceServers=e.getConfiguration().iceServers,o.Contracts.throwIfNullOrUndefined(this.privIceServers,`Ice servers must be set.`);let t=new r.Deferred;e.onicegatheringstatechange=()=>{r.Events.instance.onEvent(new r.PlatformEvent(`peer connection: ice gathering state: `+e.iceGatheringState,r.EventType.Debug)),e.iceGatheringState===`complete`&&(r.Events.instance.onEvent(new r.PlatformEvent(`peer connection: ice gathering complete.`,r.EventType.Info)),t.resolve())},e.onicecandidate=e=>{e.candidate?r.Events.instance.onEvent(new r.PlatformEvent(`peer connection: ice candidate: `+e.candidate.candidate,r.EventType.Debug)):(r.Events.instance.onEvent(new r.PlatformEvent(`peer connection: ice candidate: complete`,r.EventType.Debug)),t.resolve())},setTimeout(()=>{e.iceGatheringState!==`complete`&&(r.Events.instance.onEvent(new r.PlatformEvent(`peer connection: ice gathering timeout.`,r.EventType.Warning)),t.resolve())},2e3);let n=await e.createOffer();await e.setLocalDescription(n),await t.promise,r.Events.instance.onEvent(new r.PlatformEvent(`peer connection: got local SDP.`,r.EventType.Info)),this.privProperties.setProperty(a.PropertyId.TalkingAvatarService_WebRTC_SDP,JSON.stringify(e.localDescription));let i=await this.speak(``,!1);if(i.reason!==a.ResultReason.SynthesizingAudioCompleted)return new a.SynthesisResult(i.resultId,i.reason,i.errorDetails,i.properties);let s=atob(i.properties.getProperty(a.PropertyId.TalkingAvatarService_WebRTC_SDP)),c=new RTCSessionDescription(JSON.parse(s));return await e.setRemoteDescription(c),new a.SynthesisResult(i.resultId,i.reason,void 0,i.properties)}async speakTextAsync(e){let t=await this.speak(e,!1);return new a.SynthesisResult(t.resultId,t.reason,t.errorDetails,t.properties)}async speakSsmlAsync(e){let t=await this.speak(e,!0);return new a.SynthesisResult(t.resultId,t.reason,t.errorDetails,t.properties)}async stopSpeakingAsync(){for(;this.synthesisRequestQueue.length()>0;)(await this.synthesisRequestQueue.dequeue()).err(`Synthesis is canceled by user.`);return this.privAdapter.stopSpeaking()}async updateSceneAsync(e){o.Contracts.throwIfDisposed(this.privDisposed),o.Contracts.throwIfNullOrUndefined(e,`sceneConfig`);let t={avatarScene:{amplitude:e.amplitude,positionX:e.positionX,positionY:e.positionY,rotationX:e.rotationX,rotationY:e.rotationY,rotationZ:e.rotationZ,zoom:e.zoom}};return this.privAdapter.sendNetworkMessage(`synthesis.control`,JSON.stringify(t))}async stopAvatarAsync(){return o.Contracts.throwIfDisposed(this.privDisposed),this.dispose(!0)}async close(){if(!this.privDisposed)return this.dispose(!0)}get iceServers(){return this.privIceServers}createSynthesisAdapter(e,t,r){return new n.AvatarSynthesisAdapter(e,t,r,this,this.privAvatarConfig)}createRestSynthesisAdapter(e,t){}createSynthesizerConfig(e){let t=super.createSynthesizerConfig(e);return t.avatarEnabled=!0,t}async speak(e,t){let n=(0,r.createNoDashGuid)(),i=new r.Deferred;return this.synthesisRequestQueue.enqueue(new s.SynthesisRequest(n,e,t,e=>{i.resolve(e),this.privSynthesizing=!1,this.adapterSpeak()},e=>{i.reject(e),this.privSynthesizing=!1})),this.adapterSpeak(),i.promise}}})),Sn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AvatarVideoFormat=e.Coordinate=void 0,e.Coordinate=class{constructor(e,t){this.x=e,this.y=t}},e.AvatarVideoFormat=class{constructor(e=`H264`,t=2e6,n=1920,r=1080){this.codec=e,this.bitrate=t,this.width=n,this.height=r}setCropRange(e,t){this.cropRange={bottomRight:t,topLeft:e}}}})),Cn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AvatarWebRTCConnectionResult=void 0;var t=Y();e.AvatarWebRTCConnectionResult=class extends t.SynthesisResult{constructor(e,t,n,r,i){super(t,n,r,i),this.privSDPAnswer=e}get SDPAnswer(){return this.privSDPAnswer}}})),wn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Diagnostics=void 0;var t=X(),n=k(),r=class{static SetLoggingLevel(e){this.privListener=new t.ConsoleLoggingListener(e),n.Events.instance.attachConsoleListener(this.privListener)}static StartConsoleOutput(){this.privListener&&(this.privListener.enableConsoleOutput=!0)}static StopConsoleOutput(){this.privListener&&(this.privListener.enableConsoleOutput=!1)}static SetLogOutputPath(e){if(typeof window>`u`)this.privListener&&(this.privListener.logPath=e);else throw Error(`File system logging not available in browser.`)}static set onLogOutput(e){this.privListener&&(this.privListener.logCallback=e)}};e.Diagnostics=r,r.privListener=void 0})),Y=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CustomCommandsConfig=e.BotFrameworkConfig=e.DialogServiceConfig=e.PhraseListGrammar=e.Connection=e.ServiceEventArgs=e.ConnectionEventArgs=e.CancellationErrorCode=e.CancellationDetails=e.CancellationDetailsBase=e.TranslationRecognitionCanceledEventArgs=e.NoMatchDetails=e.NoMatchReason=e.Translations=e.TranslationRecognizer=e.SpeechRecognizer=e.Recognizer=e.PropertyId=e.PropertyCollection=e.SpeechTranslationConfigImpl=e.SpeechTranslationConfig=e.SpeechConfigImpl=e.SpeechConfig=e.ResultReason=e.TranslationSynthesisResult=e.TranslationRecognitionResult=e.TranslationSynthesisEventArgs=e.TranslationRecognitionEventArgs=e.SpeechRecognitionCanceledEventArgs=e.MeetingTranscriptionEventArgs=e.ConversationTranscriptionEventArgs=e.SpeechRecognitionEventArgs=e.SpeechRecognitionResult=e.RecognitionResult=e.OutputFormat=e.RecognitionEventArgs=e.SessionEventArgs=e.KeywordRecognitionModel=e.PushAudioOutputStreamCallback=e.PullAudioInputStreamCallback=e.CancellationReason=e.PushAudioOutputStream=e.PullAudioOutputStream=e.AudioOutputStream=e.PushAudioInputStream=e.PullAudioInputStream=e.AudioInputStream=e.AudioFormatTag=e.AudioStreamFormat=e.AudioConfig=void 0,e.Diagnostics=e.AvatarWebRTCConnectionResult=e.Coordinate=e.AvatarVideoFormat=e.AvatarSynthesizer=e.AvatarSceneConfig=e.AvatarEventArgs=e.AvatarConfig=e.LanguageIdMode=e.PronunciationAssessmentResult=e.PronunciationAssessmentConfig=e.PronunciationAssessmentGranularity=e.PronunciationAssessmentGradingSystem=e.MeetingTranscriptionCanceledEventArgs=e.ConversationTranscriptionCanceledEventArgs=e.SpeakerAudioDestination=e.VoiceInfo=e.SynthesisVoiceType=e.SynthesisVoiceGender=e.SynthesisVoicesResult=e.SpeechSynthesisRequestInputType=e.SpeechSynthesisRequestInputStream=e.SpeechSynthesisRequest=e.SpeechSynthesisBoundaryType=e.SpeechSynthesisVisemeEventArgs=e.SpeechSynthesisBookmarkEventArgs=e.SpeechSynthesisWordBoundaryEventArgs=e.SpeechSynthesisEventArgs=e.SpeechSynthesisResult=e.SynthesisResult=e.SpeechSynthesizer=e.SpeechSynthesisOutputFormat=e.Synthesizer=e.User=e.Participant=e.MeetingTranscriber=e.Meeting=e.ConversationTranscriptionResult=e.ConversationTranscriber=e.SourceLanguageConfig=e.AutoDetectSourceLanguageResult=e.AutoDetectSourceLanguageConfig=e.ConnectionMessage=e.ConnectionMessageEventArgs=e.BaseAudioPlayer=e.ProfanityOption=e.ServicePropertyChannel=e.TurnStatusReceivedEventArgs=e.ActivityReceivedEventArgs=e.DialogServiceConnector=void 0,e.LogLevel=void 0;var t=qe();Object.defineProperty(e,"AudioConfig",{enumerable:!0,get:function(){return t.AudioConfig}});var n=I();Object.defineProperty(e,"AudioStreamFormat",{enumerable:!0,get:function(){return n.AudioStreamFormat}}),Object.defineProperty(e,"AudioFormatTag",{enumerable:!0,get:function(){return n.AudioFormatTag}});var r=Ge();Object.defineProperty(e,"AudioInputStream",{enumerable:!0,get:function(){return r.AudioInputStream}}),Object.defineProperty(e,"PullAudioInputStream",{enumerable:!0,get:function(){return r.PullAudioInputStream}}),Object.defineProperty(e,"PushAudioInputStream",{enumerable:!0,get:function(){return r.PushAudioInputStream}});var i=V();Object.defineProperty(e,"AudioOutputStream",{enumerable:!0,get:function(){return i.AudioOutputStream}}),Object.defineProperty(e,"PullAudioOutputStream",{enumerable:!0,get:function(){return i.PullAudioOutputStream}}),Object.defineProperty(e,"PushAudioOutputStream",{enumerable:!0,get:function(){return i.PushAudioOutputStream}});var a=Je();Object.defineProperty(e,"CancellationReason",{enumerable:!0,get:function(){return a.CancellationReason}});var o=Ye();Object.defineProperty(e,"PullAudioInputStreamCallback",{enumerable:!0,get:function(){return o.PullAudioInputStreamCallback}});var s=Xe();Object.defineProperty(e,"PushAudioOutputStreamCallback",{enumerable:!0,get:function(){return s.PushAudioOutputStreamCallback}});var c=Ze();Object.defineProperty(e,"KeywordRecognitionModel",{enumerable:!0,get:function(){return c.KeywordRecognitionModel}});var l=Qe();Object.defineProperty(e,"SessionEventArgs",{enumerable:!0,get:function(){return l.SessionEventArgs}});var u=$e();Object.defineProperty(e,"RecognitionEventArgs",{enumerable:!0,get:function(){return u.RecognitionEventArgs}});var d=et();Object.defineProperty(e,"OutputFormat",{enumerable:!0,get:function(){return d.OutputFormat}});var f=tt();Object.defineProperty(e,"RecognitionResult",{enumerable:!0,get:function(){return f.RecognitionResult}});var p=nt();Object.defineProperty(e,"SpeechRecognitionResult",{enumerable:!0,get:function(){return p.SpeechRecognitionResult}});var m=rt();Object.defineProperty(e,"SpeechRecognitionEventArgs",{enumerable:!0,get:function(){return m.SpeechRecognitionEventArgs}}),Object.defineProperty(e,"ConversationTranscriptionEventArgs",{enumerable:!0,get:function(){return m.ConversationTranscriptionEventArgs}}),Object.defineProperty(e,"MeetingTranscriptionEventArgs",{enumerable:!0,get:function(){return m.MeetingTranscriptionEventArgs}});var h=it();Object.defineProperty(e,"SpeechRecognitionCanceledEventArgs",{enumerable:!0,get:function(){return h.SpeechRecognitionCanceledEventArgs}});var g=at();Object.defineProperty(e,"TranslationRecognitionEventArgs",{enumerable:!0,get:function(){return g.TranslationRecognitionEventArgs}});var _=ot();Object.defineProperty(e,"TranslationSynthesisEventArgs",{enumerable:!0,get:function(){return _.TranslationSynthesisEventArgs}});var v=st();Object.defineProperty(e,"TranslationRecognitionResult",{enumerable:!0,get:function(){return v.TranslationRecognitionResult}});var y=ct();Object.defineProperty(e,"TranslationSynthesisResult",{enumerable:!0,get:function(){return y.TranslationSynthesisResult}});var b=lt();Object.defineProperty(e,"ResultReason",{enumerable:!0,get:function(){return b.ResultReason}});var x=ut();Object.defineProperty(e,"SpeechConfig",{enumerable:!0,get:function(){return x.SpeechConfig}}),Object.defineProperty(e,"SpeechConfigImpl",{enumerable:!0,get:function(){return x.SpeechConfigImpl}});var S=dt();Object.defineProperty(e,"SpeechTranslationConfig",{enumerable:!0,get:function(){return S.SpeechTranslationConfig}}),Object.defineProperty(e,"SpeechTranslationConfigImpl",{enumerable:!0,get:function(){return S.SpeechTranslationConfigImpl}});var ee=ft();Object.defineProperty(e,"PropertyCollection",{enumerable:!0,get:function(){return ee.PropertyCollection}});var te=U();Object.defineProperty(e,"PropertyId",{enumerable:!0,get:function(){return te.PropertyId}});var ne=pt();Object.defineProperty(e,"Recognizer",{enumerable:!0,get:function(){return ne.Recognizer}});var re=mt();Object.defineProperty(e,"SpeechRecognizer",{enumerable:!0,get:function(){return re.SpeechRecognizer}});var ie=_t();Object.defineProperty(e,"TranslationRecognizer",{enumerable:!0,get:function(){return ie.TranslationRecognizer}});var ae=vt();Object.defineProperty(e,"Translations",{enumerable:!0,get:function(){return ae.Translations}});var oe=yt();Object.defineProperty(e,"NoMatchReason",{enumerable:!0,get:function(){return oe.NoMatchReason}});var se=bt();Object.defineProperty(e,"NoMatchDetails",{enumerable:!0,get:function(){return se.NoMatchDetails}});var C=xt();Object.defineProperty(e,"TranslationRecognitionCanceledEventArgs",{enumerable:!0,get:function(){return C.TranslationRecognitionCanceledEventArgs}});var w=St();Object.defineProperty(e,"CancellationDetailsBase",{enumerable:!0,get:function(){return w.CancellationDetailsBase}});var ce=Ct();Object.defineProperty(e,"CancellationDetails",{enumerable:!0,get:function(){return ce.CancellationDetails}});var le=wt();Object.defineProperty(e,"CancellationErrorCode",{enumerable:!0,get:function(){return le.CancellationErrorCode}});var T=Tt();Object.defineProperty(e,"ConnectionEventArgs",{enumerable:!0,get:function(){return T.ConnectionEventArgs}});var E=Et();Object.defineProperty(e,"ServiceEventArgs",{enumerable:!0,get:function(){return E.ServiceEventArgs}});var ue=gt();Object.defineProperty(e,"Connection",{enumerable:!0,get:function(){return ue.Connection}});var de=Dt();Object.defineProperty(e,"PhraseListGrammar",{enumerable:!0,get:function(){return de.PhraseListGrammar}});var fe=G();Object.defineProperty(e,"DialogServiceConfig",{enumerable:!0,get:function(){return fe.DialogServiceConfig}});var pe=Ot();Object.defineProperty(e,"BotFrameworkConfig",{enumerable:!0,get:function(){return pe.BotFrameworkConfig}});var me=kt();Object.defineProperty(e,"CustomCommandsConfig",{enumerable:!0,get:function(){return me.CustomCommandsConfig}});var he=jt();Object.defineProperty(e,"DialogServiceConnector",{enumerable:!0,get:function(){return he.DialogServiceConnector}});var ge=Mt();Object.defineProperty(e,"ActivityReceivedEventArgs",{enumerable:!0,get:function(){return ge.ActivityReceivedEventArgs}});var _e=Pt();Object.defineProperty(e,"TurnStatusReceivedEventArgs",{enumerable:!0,get:function(){return _e.TurnStatusReceivedEventArgs}});var ve=Ft();Object.defineProperty(e,"ServicePropertyChannel",{enumerable:!0,get:function(){return ve.ServicePropertyChannel}});var ye=It();Object.defineProperty(e,"ProfanityOption",{enumerable:!0,get:function(){return ye.ProfanityOption}});var be=Lt();Object.defineProperty(e,"BaseAudioPlayer",{enumerable:!0,get:function(){return be.BaseAudioPlayer}});var xe=Rt();Object.defineProperty(e,"ConnectionMessageEventArgs",{enumerable:!0,get:function(){return xe.ConnectionMessageEventArgs}});var Se=ht();Object.defineProperty(e,"ConnectionMessage",{enumerable:!0,get:function(){return Se.ConnectionMessage}});var Ce=Bt();Object.defineProperty(e,"AutoDetectSourceLanguageConfig",{enumerable:!0,get:function(){return Ce.AutoDetectSourceLanguageConfig}});var we=Vt();Object.defineProperty(e,"AutoDetectSourceLanguageResult",{enumerable:!0,get:function(){return we.AutoDetectSourceLanguageResult}});var Te=Ht();Object.defineProperty(e,"SourceLanguageConfig",{enumerable:!0,get:function(){return Te.SourceLanguageConfig}});var D=Yt();Object.defineProperty(e,"ConversationTranscriber",{enumerable:!0,get:function(){return D.ConversationTranscriber}}),Object.defineProperty(e,"ConversationTranscriptionResult",{enumerable:!0,get:function(){return D.ConversationTranscriptionResult}}),Object.defineProperty(e,"Meeting",{enumerable:!0,get:function(){return D.Meeting}}),Object.defineProperty(e,"MeetingTranscriber",{enumerable:!0,get:function(){return D.MeetingTranscriber}}),Object.defineProperty(e,"Participant",{enumerable:!0,get:function(){return D.Participant}}),Object.defineProperty(e,"User",{enumerable:!0,get:function(){return D.User}});var Ee=J();Object.defineProperty(e,"Synthesizer",{enumerable:!0,get:function(){return Ee.Synthesizer}});var De=Ke();Object.defineProperty(e,"SpeechSynthesisOutputFormat",{enumerable:!0,get:function(){return De.SpeechSynthesisOutputFormat}});var Oe=Xt();Object.defineProperty(e,"SpeechSynthesizer",{enumerable:!0,get:function(){return Oe.SpeechSynthesizer}});var ke=Zt();Object.defineProperty(e,"SynthesisResult",{enumerable:!0,get:function(){return ke.SynthesisResult}});var O=Qt();Object.defineProperty(e,"SpeechSynthesisResult",{enumerable:!0,get:function(){return O.SpeechSynthesisResult}});var Ae=$t();Object.defineProperty(e,"SpeechSynthesisEventArgs",{enumerable:!0,get:function(){return Ae.SpeechSynthesisEventArgs}});var je=en();Object.defineProperty(e,"SpeechSynthesisWordBoundaryEventArgs",{enumerable:!0,get:function(){return je.SpeechSynthesisWordBoundaryEventArgs}});var Me=tn();Object.defineProperty(e,"SpeechSynthesisBookmarkEventArgs",{enumerable:!0,get:function(){return Me.SpeechSynthesisBookmarkEventArgs}});var Ne=nn();Object.defineProperty(e,"SpeechSynthesisVisemeEventArgs",{enumerable:!0,get:function(){return Ne.SpeechSynthesisVisemeEventArgs}});var Pe=rn();Object.defineProperty(e,"SpeechSynthesisBoundaryType",{enumerable:!0,get:function(){return Pe.SpeechSynthesisBoundaryType}});var k=sn();Object.defineProperty(e,"SpeechSynthesisRequest",{enumerable:!0,get:function(){return k.SpeechSynthesisRequest}}),Object.defineProperty(e,"SpeechSynthesisRequestInputStream",{enumerable:!0,get:function(){return k.SpeechSynthesisRequestInputStream}});var A=an();Object.defineProperty(e,"SpeechSynthesisRequestInputType",{enumerable:!0,get:function(){return A.SpeechSynthesisRequestInputType}});var j=cn();Object.defineProperty(e,"SynthesisVoicesResult",{enumerable:!0,get:function(){return j.SynthesisVoicesResult}});var M=ln();Object.defineProperty(e,"SynthesisVoiceGender",{enumerable:!0,get:function(){return M.SynthesisVoiceGender}}),Object.defineProperty(e,"SynthesisVoiceType",{enumerable:!0,get:function(){return M.SynthesisVoiceType}}),Object.defineProperty(e,"VoiceInfo",{enumerable:!0,get:function(){return M.VoiceInfo}});var Fe=un();Object.defineProperty(e,"SpeakerAudioDestination",{enumerable:!0,get:function(){return Fe.SpeakerAudioDestination}});var Ie=dn();Object.defineProperty(e,"ConversationTranscriptionCanceledEventArgs",{enumerable:!0,get:function(){return Ie.ConversationTranscriptionCanceledEventArgs}});var Le=fn();Object.defineProperty(e,"MeetingTranscriptionCanceledEventArgs",{enumerable:!0,get:function(){return Le.MeetingTranscriptionCanceledEventArgs}});var N=pn();Object.defineProperty(e,"PronunciationAssessmentGradingSystem",{enumerable:!0,get:function(){return N.PronunciationAssessmentGradingSystem}});var P=mn();Object.defineProperty(e,"PronunciationAssessmentGranularity",{enumerable:!0,get:function(){return P.PronunciationAssessmentGranularity}});var F=hn();Object.defineProperty(e,"PronunciationAssessmentConfig",{enumerable:!0,get:function(){return F.PronunciationAssessmentConfig}});var ze=gn();Object.defineProperty(e,"PronunciationAssessmentResult",{enumerable:!0,get:function(){return ze.PronunciationAssessmentResult}});var Be=zt();Object.defineProperty(e,"LanguageIdMode",{enumerable:!0,get:function(){return Be.LanguageIdMode}});var Ve=_n();Object.defineProperty(e,"AvatarConfig",{enumerable:!0,get:function(){return Ve.AvatarConfig}});var He=vn();Object.defineProperty(e,"AvatarEventArgs",{enumerable:!0,get:function(){return He.AvatarEventArgs}});var Ue=yn();Object.defineProperty(e,"AvatarSceneConfig",{enumerable:!0,get:function(){return Ue.AvatarSceneConfig}});var L=xn();Object.defineProperty(e,"AvatarSynthesizer",{enumerable:!0,get:function(){return L.AvatarSynthesizer}});var R=Sn();Object.defineProperty(e,"AvatarVideoFormat",{enumerable:!0,get:function(){return R.AvatarVideoFormat}}),Object.defineProperty(e,"Coordinate",{enumerable:!0,get:function(){return R.Coordinate}});var We=Cn();Object.defineProperty(e,"AvatarWebRTCConnectionResult",{enumerable:!0,get:function(){return We.AvatarWebRTCConnectionResult}});var z=wn();Object.defineProperty(e,"Diagnostics",{enumerable:!0,get:function(){return z.Diagnostics}});var B=Re();Object.defineProperty(e,"LogLevel",{enumerable:!0,get:function(){return B.LogLevel}})})),Tn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProxyInfo=void 0;var t=Y();e.ProxyInfo=class e{constructor(e,t,n,r){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=n,this.privProxyPassword=r}static fromParameters(n){return new e(n.getProperty(t.PropertyId.SpeechServiceConnection_ProxyHostName),parseInt(n.getProperty(t.PropertyId.SpeechServiceConnection_ProxyPort),10),n.getProperty(t.PropertyId.SpeechServiceConnection_ProxyUserName),n.getProperty(t.PropertyId.SpeechServiceConnection_ProxyPassword))}static fromRecognizerConfig(e){return this.fromParameters(e.parameters)}get HostName(){return this.privProxyHostName}get Port(){return this.privProxyPort}get UserName(){return this.privProxyUserName}get Password(){return this.privProxyPassword}}})),En=t(((e,t)=>{var n=new Set([`json`,`buffer`,`string`]);t.exports=e=>(...t)=>{let r=new Set,i,a,o,s=``;return t.forEach(e=>{if(typeof e==`string`){if(e.toUpperCase()===e){if(i){let t=`Can't set method to ${e}, already set to ${i}.`;throw Error(t)}i=e}else if(e.startsWith(`http:`)||e.startsWith(`https:`))s=e;else if(n.has(e))a=e;else throw Error(`Unknown encoding, ${e}`)}else if(typeof e==`number`)r.add(e);else if(typeof e==`object`){if(Array.isArray(e)||e instanceof Set)e.forEach(e=>r.add(e));else{if(o)throw Error(`Cannot set headers twice.`);o=e}}else throw Error(`Unknown type: ${typeof e}`)}),i||=`GET`,r.size===0&&r.add(200),e(r,i,a,o,s)}})),Dn=t(((e,t)=>{var n=En(),r=class e extends Error{constructor(t,...n){super(...n),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name=`StatusError`,this.message=t.statusMessage,this.statusCode=t.status,this.res=t,this.json=t.json.bind(t),this.text=t.text.bind(t),this.arrayBuffer=t.arrayBuffer.bind(t);let r;Object.defineProperty(this,"responseBody",{get:()=>(r||=this.arrayBuffer(),r)}),this.headers={};for(let[e,n]of t.headers.entries())this.headers[e.toLowerCase()]=n}};t.exports=n((e,t,n,i,a)=>async(o,s,c={})=>{o=a+(o||``);let l=new URL(o);if(i||={},l.username&&(i.Authorization=`Basic `+btoa(l.username+`:`+l.password),l=new URL(l.protocol+`//`+l.host+l.pathname+l.search)),l.protocol!==`https:`&&l.protocol!==`http:`)throw Error(`Unknown protocol, ${l.protocol}`);if(s&&!(s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof s==`string`)){if(typeof s==`object`)s=JSON.stringify(s),i[`Content-Type`]=`application/json`;else throw Error(`Unknown body type.`)}c=new Headers({...i||{},...c});let u=await fetch(l,{method:t,headers:c,body:s});if(u.statusCode=u.status,!e.has(u.status))throw new r(u);return n===`json`?u.json():n===`buffer`?u.arrayBuffer():n===`string`?u.text():u})})),On=t((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.RestMessageAdapter=e.RestRequestType=void 0;var n=t(Dn()),r=k(),i;(function(e){e.Get=`GET`,e.Post=`POST`,e.Delete=`DELETE`,e.File=`file`})(i=e.RestRequestType||={}),e.RestMessageAdapter=class{constructor(e){if(!e)throw new r.ArgumentNullError(`configParams`);this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let n=``;try{let r=t.trim().split(/[\r\n]+/),i={};r.forEach(e=>{let t=e.split(`: `),n=t.shift().toLowerCase(),r=t.join(`: `);i[n]=r}),n=i[e.toLowerCase()]}catch{}return n}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,a={},o=null){let s=new r.Deferred,c=e===i.File?`POST`:e,l=(e,t={})=>{let n=e;return{data:JSON.stringify(t),headers:JSON.stringify(e.headers),json:t,ok:e.statusCode>=200&&e.statusCode<300,status:e.statusCode,statusText:t.error?t.error.message:n.statusText?n.statusText:n.statusMessage}},u=r=>{(0,n.default)(t,c,this.privHeaders,200,201,202,204,400,401,402,403,404)(this.queryParams(a)===``?``:`?${this.queryParams(a)}`,r).then(async t=>{if(e===i.Delete||t.statusCode===204)s.resolve(l(t));else try{let e=await t.json();s.resolve(l(t,e))}catch{s.resolve(l(t))}}).catch(e=>{s.reject(e)})};return this.privIgnoreCache&&(this.privHeaders[`Cache-Control`]=`no-cache`),e===i.Post&&o&&(this.privHeaders[`content-type`]=`application/json`,this.privHeaders[`Content-Type`]=`application/json`),u(o),s.promise}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+`=`+encodeURIComponent(e[t])).join(`&`)}}})),kn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RestConfigBase=void 0;var t=class e{static get requestOptions(){return e.privDefaultRequestOptions}static get configParams(){return e.privDefaultParams}static get restErrors(){return e.privRestErrors}};e.RestConfigBase=t,t.privDefaultRequestOptions={headers:{Accept:`application/json`},ignoreCache:!1,timeout:1e4},t.privRestErrors={authInvalidSubscriptionKey:`You must specify either an authentication token to use, or a Cognitive Speech subscription key.`,authInvalidSubscriptionRegion:`You must specify the Cognitive Speech region to use.`,invalidArgs:`Required input not found: {arg}.`,invalidCreateJoinConversationResponse:`Creating/Joining conversation failed with HTTP {status}.`,invalidParticipantRequest:`The requested participant was not found.`,permissionDeniedConnect:`Required credentials not found.`,permissionDeniedConversation:`Invalid operation: only the host can {command} the conversation.`,permissionDeniedParticipant:`Invalid operation: only the host can {command} a participant.`,permissionDeniedSend:`Invalid operation: the conversation is not in a connected state.`,permissionDeniedStart:`Invalid operation: there is already an active conversation.`},t.privDefaultParams={apiVersion:`api-version`,authorization:`Authorization`,clientAppId:`X-ClientAppId`,contentTypeKey:`Content-Type`,correlationId:`X-CorrelationId`,languageCode:`language`,nickname:`nickname`,profanity:`profanity`,requestId:`X-RequestId`,roomId:`roomid`,sessionToken:`token`,subscriptionKey:`Ocp-Apim-Subscription-Key`,subscriptionRegion:`Ocp-Apim-Subscription-Region`,token:`X-CapitoToken`}})),X=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),n(ze(),e),n(Be(),e),n(Ve(),e),n(He(),e),n(Ue(),e),n(R(),e),n(L(),e),n(We(),e),n(Tn(),e),n(On(),e),n(kn(),e)})),Z=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechConnectionMessage=void 0;var t=k(),n=A();e.SpeechConnectionMessage=class e extends t.ConnectionMessage{constructor(e,r,i,a,o,s,c,l){if(!r)throw new t.ArgumentNullError(`path`);if(!i)throw new t.ArgumentNullError(`requestId`);let u={};if(u[n.HeaderNames.Path]=r,u[n.HeaderNames.RequestId]=i,u[n.HeaderNames.RequestTimestamp]=new Date().toISOString(),a&&(u[n.HeaderNames.ContentType]=a),s&&(u[n.HeaderNames.RequestStreamId]=s),c)for(let e in c)e&&(u[e]=c[e]);l?super(e,o,u,l):super(e,o,u),this.privPath=r,this.privRequestId=i,this.privContentType=a,this.privStreamId=s,this.privAdditionalHeaders=c}get path(){return this.privPath}get requestId(){return this.privRequestId}get contentType(){return this.privContentType}get streamId(){return this.privStreamId}get additionalHeaders(){return this.privAdditionalHeaders}static fromConnectionMessage(t){let r=null,i=null,a=null,o=null,s={};if(t.headers)for(let e in t.headers)e&&(e.toLowerCase()===n.HeaderNames.Path.toLowerCase()?r=t.headers[e]:e.toLowerCase()===n.HeaderNames.RequestId.toLowerCase()?i=t.headers[e]:e.toLowerCase()===n.HeaderNames.ContentType.toLowerCase()?a=t.headers[e]:e.toLowerCase()===n.HeaderNames.RequestStreamId.toLowerCase()?o=t.headers[e]:s[e]=t.headers[e]);return new e(t.messageType,r,i,a,t.body,o,s,t.id)}}})),An=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SegmentationMode=void 0,(function(e){e.Normal=`Normal`,e.Disabled=`Disabled`,e.Custom=`Custom`,e.Semantic=`Semantic`})(e.SegmentationMode||={})})),jn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NextAction=void 0,(function(e){e.None=`None`,e.Synthesize=`Synthesize`})(e.NextAction||={})})),Mn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Mode=void 0,(function(e){e.None=`None`,e.Always=`Always`})(e.Mode||={})})),Nn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.LanguageIdDetectionPriority=e.LanguageIdDetectionMode=void 0,(function(e){e.DetectAtAudioStart=`DetectAtAudioStart`,e.DetectContinuous=`DetectContinuous`,e.DetectSegments=`DetectSegments`})(e.LanguageIdDetectionMode||={}),(function(e){e.Auto=`Auto`,e.PrioritizeLatency=`PrioritizeLatency`,e.PrioritizeAccuracy=`PrioritizeAccuracy`})(e.LanguageIdDetectionPriority||={})})),Pn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NextAction=void 0,(function(e){e.Recognize=`Recognize`,e.None=`None`})(e.NextAction||={})})),Fn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OnUnknownAction=void 0,(function(e){e.RecognizeWithDefaultLanguage=`RecognizeWithDefaultLanguage`,e.None=`None`})(e.OnUnknownAction||={})})),In=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ResultType=void 0,(function(e){e.Auto=`Auto`,e.StableFragment=`StableFragment`,e.Hypothesis=`Hypothesis`,e.None=`None`})(e.ResultType||={})})),Ln=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PhraseResultOutputType=void 0,(function(e){e.Always=`Always`,e.None=`None`})(e.PhraseResultOutputType||={})})),Rn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NextAction=void 0,(function(e){e.None=`None`,e.Translate=`Translate`})(e.NextAction||={})})),zn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.InteractivePunctuationMode=void 0,(function(e){e.None=`None`,e.Implicit=`Implicit`,e.Explicit=`Explicit`,e.Intelligent=`Intelligent`})(e.InteractivePunctuationMode||={})})),Bn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationPunctuationMode=void 0,(function(e){e.None=`None`,e.Intelligent=`Intelligent`,e.Implicit=`Implicit`,e.Explicit=`Explicit`})(e.ConversationPunctuationMode||={})})),Vn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DictationPunctuationMode=void 0,(function(e){e.None=`None`,e.Intelligent=`Intelligent`,e.Implicit=`Implicit`,e.Explicit=`Explicit`})(e.DictationPunctuationMode||={})})),Hn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DisfluencyMode=void 0,(function(e){e.Raw=`Raw`,e.Removed=`Removed`,e.Labeled=`Labeled`})(e.DisfluencyMode||={})})),Un=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ServiceRecognizerBase=void 0;var t=X(),n=k(),r=Y(),i=Q(),a=Z(),o=An(),s=W(),c=jn(),l=Mn(),u=Nn(),d=Pn(),f=Fn(),p=In(),m=Ln(),h=Rn(),g=zn(),_=Bn(),v=Vn(),y=Hn(),b=class e{constructor(e,t,a,o,s){if(this.privConnectionConfigurationPromise=void 0,this.privConnectionPromise=void 0,this.privSetTimeout=setTimeout,this.privIsLiveAudio=!1,this.privAverageBytesPerMs=0,this.privEnableReliableReconnect=!1,this.privEnableSpeakerId=!1,this.privExpectContentAssessmentResponse=!1,this.recognizeOverride=void 0,this.disconnectOverride=void 0,this.receiveMessageOverride=void 0,this.sendPrePayloadJSONOverride=void 0,this.postConnectImplOverride=void 0,this.configConnectionOverride=void 0,this.handleSpeechPhraseMessage=void 0,this.handleSpeechHypothesisMessage=void 0,!e)throw new n.ArgumentNullError(`authentication`);if(!t)throw new n.ArgumentNullError(`connectionFactory`);if(!a)throw new n.ArgumentNullError(`audioSource`);if(!o)throw new n.ArgumentNullError(`recognizerConfig`);this.privEnableSpeakerId=o.isSpeakerDiarizationEnabled,this.privMustReportEndOfStream=!1,this.privAuthentication=e,this.privConnectionFactory=t,this.privAudioSource=a,this.privRecognizerConfig=o,this.privIsDisposed=!1,this.privRecognizer=s,this.privRequestSession=new i.RequestSession(this.privAudioSource.id()),this.privConnectionEvents=new n.EventSource,this.privServiceEvents=new n.EventSource,this.privDynamicGrammar=new i.DynamicGrammarBuilder,this.privSpeechContext=new i.SpeechContext(this.privDynamicGrammar),this.privAgentConfig=new i.AgentConfig,this.privEnableReliableReconnect=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.Speech_EnableMultiChannelProcessing,`false`).toLowerCase()===`true`,this.privContinuationState=new i.ReconnectContinuationState,this.privRecognizerConfig.parameters.getProperty(r.PropertyId.WebWorkerLoadType,`on`).toLowerCase()===`on`&&typeof Blob<`u`&&typeof Worker<`u`?this.privSetTimeout=n.Timeout.setTimeout:(typeof window<`u`&&(this.privSetTimeout=window.setTimeout.bind(window)),typeof globalThis<`u`&&(this.privSetTimeout=globalThis.setTimeout.bind(globalThis))),this.connectionEvents.attach(e=>{if(e.name===`ConnectionClosedEvent`){let t=e;(t.statusCode===1003||t.statusCode===1007||t.statusCode===1002||t.statusCode===4e3||this.privRequestSession.numConnectionAttempts>this.privRecognizerConfig.maxRetryCount)&&this.cancelRecognitionLocal(r.CancellationReason.Error,t.statusCode===1007?r.CancellationErrorCode.BadRequestParameters:r.CancellationErrorCode.ConnectionFailure,`${t.reason} websocket error code: ${t.statusCode}`)}}),this.privEnableSpeakerId&&(this.privDiarizationSessionId=(0,n.createNoDashGuid)())}setTranslationJson(){let e=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0);if(e!==void 0){let t=e.split(`,`),n=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_TranslationVoice,void 0),i=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_TranslationCategoryId,void 0),a=n===void 0?c.NextAction.None:c.NextAction.Synthesize;if(this.privSpeechContext.getContext().translation={onPassthrough:{action:a},onSuccess:{action:a},output:{includePassThroughResults:!0,interimResults:{mode:l.Mode.Always}},targetLanguages:t},i!==void 0&&(this.privSpeechContext.getContext().translation.category=i),n!==void 0){let e={};for(let r of t)e[r]=n;this.privSpeechContext.getContext().synthesis={defaultVoices:e}}let o=this.privSpeechContext.getContext().phraseDetection||{};o.onSuccess={action:h.NextAction.Translate},o.onInterim={action:h.NextAction.Translate},this.privSpeechContext.getContext().phraseDetection=o}}setSpeechSegmentationTimeoutJson(){let e=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.Speech_SegmentationSilenceTimeoutMs,void 0),t=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.Speech_SegmentationMaximumTimeMs,void 0),n=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.Speech_SegmentationStrategy,void 0),i={mode:o.SegmentationMode.Normal},a=!1;if(n!==void 0){a=!0;let e=o.SegmentationMode.Normal;switch(n.toLowerCase()){case`default`:break;case`time`:e=o.SegmentationMode.Custom;break;case`semantic`:e=o.SegmentationMode.Semantic}i.mode=e}if(e!==void 0){a=!0;let t=parseInt(e,10);i.mode=o.SegmentationMode.Custom,i.segmentationSilenceTimeoutMs=t}if(t!==void 0){a=!0;let e=parseInt(t,10);i.mode=o.SegmentationMode.Custom,i.segmentationForcedTimeoutMs=e}if(a){let e=this.privSpeechContext.getContext().phraseDetection||{};switch(e.mode=this.recognitionMode,this.recognitionMode){case s.RecognitionMode.Conversation:e.conversation=e.conversation??{segmentation:{}},e.conversation.segmentation=i;break;case s.RecognitionMode.Interactive:e.interactive=e.interactive??{segmentation:{}},e.interactive.segmentation=i;break;case s.RecognitionMode.Dictation:e.dictation=e.dictation??{},e.dictation.segmentation=i}this.privSpeechContext.getContext().phraseDetection=e}}setLanguageIdJson(){let e=this.privSpeechContext.getContext().phraseDetection||{};if(this.privRecognizerConfig.autoDetectSourceLanguages!==void 0){let t=this.privRecognizerConfig.autoDetectSourceLanguages.split(`,`);t.length===1&&t[0]===i.AutoDetectSourceLanguagesOpenRangeOptionName&&(t[0]=`UND`);let n;n=this.privRecognizerConfig.languageIdMode===`Continuous`?u.LanguageIdDetectionMode.DetectContinuous:u.LanguageIdDetectionMode.DetectAtAudioStart,this.privSpeechContext.getContext().languageId={languages:t,mode:n,onSuccess:{action:d.NextAction.Recognize},onUnknown:{action:f.OnUnknownAction.None},priority:u.LanguageIdDetectionPriority.PrioritizeLatency},this.privSpeechContext.getContext().phraseOutput={interimResults:{resultType:p.ResultType.Auto},phraseResults:{resultType:m.PhraseResultOutputType.Always}};let r=this.privRecognizerConfig.sourceLanguageModels;r!==void 0&&(e.customModels=r,e.onInterim={action:h.NextAction.None},e.onSuccess={action:h.NextAction.None})}this.privSpeechContext.getContext().phraseDetection=e}setOutputDetailLevelJson(){this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,`false`).toLowerCase()===`true`?this.privSpeechContext.setWordLevelTimings():this.privRecognizerConfig.parameters.getProperty(i.OutputFormatPropertyName,r.OutputFormat[r.OutputFormat.Simple]).toLowerCase()===r.OutputFormat[r.OutputFormat.Detailed].toLocaleLowerCase()&&this.privSpeechContext.setDetailedOutputFormat()}setSpeechStartEventSensitivityJson(){let e=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.Speech_StartEventSensitivity,void 0);if(e!==void 0){let t=!1;switch(e.toLowerCase()){case s.SpeechStartEventSensitivity.Low:case s.SpeechStartEventSensitivity.Medium:case s.SpeechStartEventSensitivity.High:t=!0}if(t){let t=this.privSpeechContext.getContext().phraseDetection||{};t.voiceOnsetSensitivity=e.toLowerCase(),this.privSpeechContext.getContext().phraseDetection=t}}}setPostProcessingOptionJson(){let e=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceResponse_PostProcessingOption,void 0),t=this.privSpeechContext.getContext().phraseDetection||{};t.enrichment=t.enrichment||{};let n=this.recognitionMode===s.RecognitionMode.Conversation?t.enrichment.conversation:this.recognitionMode===s.RecognitionMode.Interactive?t.enrichment.interactive:t.enrichment.dictation;if(n&&(delete n.postprocessingoption,delete n.punctuationMode,delete n.disfluencyMode,delete n.intermediatePunctuationMode,delete n.intermediatedisfluencymode),e!==void 0){if(e.toLowerCase()===`truetext`)switch(this.recognitionMode){case s.RecognitionMode.Conversation:t.enrichment.conversation=t.enrichment.conversation||{},t.enrichment.conversation.punctuationMode=_.ConversationPunctuationMode.Implicit,t.enrichment.conversation.disfluencyMode=y.DisfluencyMode.Removed,t.enrichment.conversation.intermediatePunctuationMode=_.ConversationPunctuationMode.Implicit,t.enrichment.conversation.intermediatedisfluencymode=y.DisfluencyMode.Removed;break;case s.RecognitionMode.Interactive:t.enrichment.interactive=t.enrichment.interactive||{},t.enrichment.interactive.punctuationMode=g.InteractivePunctuationMode.Implicit,t.enrichment.interactive.disfluencyMode=y.DisfluencyMode.Removed,t.enrichment.interactive.intermediatePunctuationMode=g.InteractivePunctuationMode.Implicit,t.enrichment.interactive.intermediatedisfluencymode=y.DisfluencyMode.Removed;break;case s.RecognitionMode.Dictation:t.enrichment.dictation=t.enrichment.dictation||{},t.enrichment.dictation.punctuationMode=v.DictationPunctuationMode.Implicit,t.enrichment.dictation.disfluencyMode=y.DisfluencyMode.Removed,t.enrichment.dictation.intermediatePunctuationMode=v.DictationPunctuationMode.Implicit,t.enrichment.dictation.intermediatedisfluencymode=y.DisfluencyMode.Removed}else switch(this.recognitionMode){case s.RecognitionMode.Conversation:t.enrichment.conversation=t.enrichment.conversation||{},t.enrichment.conversation.postprocessingoption=e;break;case s.RecognitionMode.Interactive:t.enrichment.interactive=t.enrichment.interactive||{},t.enrichment.interactive.postprocessingoption=e;break;case s.RecognitionMode.Dictation:t.enrichment.dictation=t.enrichment.dictation||{},t.enrichment.dictation.postprocessingoption=e}}this.privSpeechContext.getContext().phraseDetection=t}setLanguageJson(){let e=this.privSpeechContext.getContext().phraseDetection||{};if(this.privRecognizerConfig.autoDetectSourceLanguages!==void 0)delete e.language;else{let t=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage,void 0);t===void 0?delete e.language:e.language=t}this.privSpeechContext.getContext().phraseDetection=e}setInitialSilenceTimeoutJson(){let e=this.privSpeechContext.getContext().phraseDetection||{},t=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs,void 0);t===void 0?delete e.initialSilenceTimeout:e.initialSilenceTimeout=parseInt(t,10),this.privSpeechContext.getContext().phraseDetection=e}setEndSilenceTimeoutJson(){let e=this.privSpeechContext.getContext().phraseDetection||{},t=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs,void 0);t===void 0?delete e.trailingSilenceTimeout:e.trailingSilenceTimeout=parseInt(t,10),this.privSpeechContext.getContext().phraseDetection=e}setProfanityOptionJson(){let e=this.privSpeechContext.getContext().phraseDetection||{},t=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceResponse_ProfanityOption,void 0);t===void 0?e.enrichment&&delete e.enrichment.profanity:(e.enrichment=e.enrichment||{},e.enrichment.profanity=t),this.privSpeechContext.getContext().phraseDetection=e}setStableIntermediateThresholdJson(){let e=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceResponse_StablePartialResultThreshold,void 0),t=this.privSpeechContext.getContext().phraseOutput||{};e===void 0?t.interimResults&&delete t.interimResults.stableThreshold:(t.interimResults=t.interimResults||{},t.interimResults.stableThreshold=parseInt(e,10)),this.privSpeechContext.getContext().phraseOutput=t}get isSpeakerDiarizationEnabled(){return this.privEnableSpeakerId}get audioSource(){return this.privAudioSource}get speechContext(){return this.privSpeechContext}get dynamicGrammar(){return this.privDynamicGrammar}get agentConfig(){return this.privAgentConfig}set authentication(e){this.privAuthentication=e}isDisposed(){return this.privIsDisposed}async dispose(e){if(this.privIsDisposed=!0,this.privConnectionPromise!==void 0)try{await(await this.privConnectionPromise).dispose(e)}catch{return}}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}get recognitionMode(){return this.privRecognizerConfig.recognitionMode}async recognize(e,n,a){if(this.recognizeOverride!==void 0){await this.recognizeOverride(e,n,a);return}if(this.privConnectionConfigurationPromise=void 0,this.privRecognizerConfig.recognitionMode=e,this.privRecognizerConfig.recognitionEndpointVersion===`2`){let t=this.privSpeechContext.getContext().phraseDetection||{};t.mode=e,this.privSpeechContext.getContext().phraseDetection=t}this.setLanguageIdJson(),this.setTranslationJson(),this.privRecognizerConfig.autoDetectSourceLanguages!==void 0&&this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0)!==void 0&&this.setupTranslationWithLanguageId(),this.setLanguageJson(),this.setInitialSilenceTimeoutJson(),this.setEndSilenceTimeoutJson(),this.setSpeechSegmentationTimeoutJson(),this.setOutputDetailLevelJson(),this.setSpeechStartEventSensitivityJson(),this.setProfanityOptionJson(),this.setPostProcessingOptionJson(),this.setStableIntermediateThresholdJson(),this.privSuccessCallback=n,this.privErrorCallback=a,this.privRequestSession.startNewRecognition(),this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events),this.privEnableReliableReconnect&&this.privContinuationState.reset();let o=this.connectImpl(),s;try{let e=await this.audioSource.attach(this.privRequestSession.audioNodeId),n=await this.audioSource.format,r=await this.audioSource.deviceInfo;this.privIsLiveAudio=r.type&&r.type===i.type.Microphones,this.privEnableReliableReconnect&&(r.SeparateChannelProcessing=`true`),s=new t.ReplayableAudioNode(e,n.avgBytesPerSec),await this.privRequestSession.onAudioSourceAttachCompleted(s,!1),this.privRecognizerConfig.SpeechServiceConfig.Context.audio={source:r}}catch(e){throw await this.privRequestSession.onStopRecognizing(),e}try{await o}catch(e){await this.cancelRecognitionLocal(r.CancellationReason.Error,r.CancellationErrorCode.ConnectionFailure,e);return}let c=new r.SessionEventArgs(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,c),this.receiveMessage(),this.sendAudio(s).catch(async e=>{await this.cancelRecognitionLocal(r.CancellationReason.Error,r.CancellationErrorCode.RuntimeError,e)})}async stopRecognizing(){if(this.privRequestSession.isRecognizing)try{await this.audioSource.turnOff(),await this.sendFinalAudio(),await this.privRequestSession.onStopRecognizing(),await this.privRequestSession.turnCompletionPromise}finally{await this.privRequestSession.dispose()}}async connect(){return await this.connectImpl(),Promise.resolve()}connectAsync(e,t){this.connectImpl().then(()=>{try{e&&e()}catch(e){t&&t(e)}},e=>{try{t&&t(e)}catch{}})}async disconnect(){if(await this.cancelRecognitionLocal(r.CancellationReason.Error,r.CancellationErrorCode.NoError,`Disconnecting`),this.disconnectOverride!==void 0&&await this.disconnectOverride(),this.privConnectionPromise!==void 0)try{await(await this.privConnectionPromise).dispose()}catch{}this.privConnectionPromise=void 0}sendMessage(e){}async sendNetworkMessage(e,t){let r=typeof t==`string`?n.MessageType.Text:n.MessageType.Binary,i=typeof t==`string`?`application/json`:``;return(await this.fetchConnection()).send(new a.SpeechConnectionMessage(r,e,this.privRequestSession.requestId,i,t))}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}set expectContentAssessmentResponse(e){this.privExpectContentAssessmentResponse=e}async sendTelemetryData(){let t=this.privRequestSession.getTelemetry();if(!(e.telemetryDataEnabled!==!0||this.privIsDisposed||t===null)){if(e.telemetryData)try{e.telemetryData(t)}catch{}await(await this.fetchConnection()).send(new a.SpeechConnectionMessage(n.MessageType.Text,`telemetry`,this.privRequestSession.requestId,`application/json`,t))}}async cancelRecognitionLocal(e,t,n){this.privRequestSession.isRecognizing&&(await this.privRequestSession.onStopRecognizing(),this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,e,t,n))}async receiveMessage(){try{if(this.privIsDisposed)return;let e=await this.fetchConnection(),t=await e.read();if(this.receiveMessageOverride!==void 0)return this.receiveMessageOverride();if(!t)return this.receiveMessage();this.privServiceHasSentMessage=!0;let o=a.SpeechConnectionMessage.fromConnectionMessage(t);if(o.requestId.toLowerCase()===this.privRequestSession.requestId.toLowerCase()){if(this.privEnableReliableReconnect){this.privContinuationState.updateFromHeaders(o.additionalHeaders,this.privRequestSession.currentTurnAudioOffset);let e=this.privContinuationState.streamOffset;e!==void 0&&this.privRequestSession.onServiceAcknowledgedAudio(e)}switch(o.path.toLowerCase()){case`turn.start`:if(this.privMustReportEndOfStream=!0,this.privRequestSession.onServiceTurnStartResponse(),this.privEnableReliableReconnect){let e;try{o.textBody&&o.textBody.length>0&&(e=JSON.parse(o.textBody)?.context?.serviceTag)}catch{e=void 0}this.privContinuationState.onTurnStart(e)}break;case`speech.startdetected`:let t=i.SpeechDetected.fromJSON(o.textBody,this.privRequestSession.currentTurnAudioOffset),a=new r.RecognitionEventArgs(t.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechStartDetected&&this.privRecognizer.speechStartDetected(this.privRecognizer,a);break;case`speech.enddetected`:let s;s=o.textBody.length>0?o.textBody:`{ Offset: 0 }`;let c=i.SpeechDetected.fromJSON(s,this.privRequestSession.currentTurnAudioOffset),l=new r.RecognitionEventArgs(c.Offset+this.privRequestSession.currentTurnAudioOffset,this.privRequestSession.sessionId);this.privRecognizer.speechEndDetected&&this.privRecognizer.speechEndDetected(this.privRecognizer,l);break;case`turn.end`:await this.sendTelemetryData(),this.privRequestSession.isSpeechEnded&&this.privMustReportEndOfStream&&(this.privMustReportEndOfStream=!1,await this.cancelRecognitionLocal(r.CancellationReason.EndOfStream,r.CancellationErrorCode.NoError,void 0));let u=new r.SessionEventArgs(this.privRequestSession.sessionId);if(await this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition),!this.privRecognizerConfig.isContinuousRecognition||this.privRequestSession.isSpeechEnded||!this.privRequestSession.isRecognizing){this.privRecognizer.sessionStopped&&this.privRecognizer.sessionStopped(this.privRecognizer,u);return}e=await this.fetchConnection(),await this.sendPrePayloadJSON(e);break;default:await this.processTypeSpecificMessages(o)||this.privServiceEvents&&this.serviceEvents.onEvent(new n.ServiceEvent(o.path.toLowerCase(),o.textBody))}}return this.receiveMessage()}catch{return null}}updateSpeakerDiarizationAudioOffset(){let e=this.privRequestSession.recognitionBytesSent,t=this.privAverageBytesPerMs===0?0:e/this.privAverageBytesPerMs;this.privSpeechContext.setSpeakerDiarizationAudioOffsetMs(t)}get audioStreamId(){return this.privEnableReliableReconnect?this.privContinuationState.defaultStreamId:void 0}applyReconnectContinuation(){let e=this.privSpeechContext.getContext();e.audio=this.privContinuationState.buildAudioStreamsMetadata();let t=this.privContinuationState.buildContinuationContext();t===void 0?delete e.continuation:e.continuation=t}sendSpeechContext(e,t){this.privEnableSpeakerId&&this.updateSpeakerDiarizationAudioOffset(),this.privEnableReliableReconnect&&this.applyReconnectContinuation();let r=this.speechContext.toJSON();if(t&&this.privRequestSession.onSpeechContext(),r)return e.send(new a.SpeechConnectionMessage(n.MessageType.Text,`speech.context`,this.privRequestSession.requestId,`application/json`,r))}setupTranslationWithLanguageId(){let e=this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0),t=this.privRecognizerConfig.autoDetectSourceLanguages!==void 0;if(e!==void 0&&t){this.privSpeechContext.getContext().phraseOutput={interimResults:{resultType:p.ResultType.None},phraseResults:{resultType:m.PhraseResultOutputType.None}};let e=this.privSpeechContext.getContext().translation;if(e){let t=this.privRecognizerConfig.sourceLanguageModels;if(t!==void 0&&t.length>0){let e=this.privSpeechContext.getContext().phraseDetection||{};e.customModels=t,this.privSpeechContext.getContext().phraseDetection=e}this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&(e.onSuccess={action:c.NextAction.Synthesize},e.onPassthrough={action:c.NextAction.Synthesize})}}}noOp(){}async sendPrePayloadJSON(e,t=!0){if(this.sendPrePayloadJSONOverride!==void 0)return this.sendPrePayloadJSONOverride(e);await this.sendSpeechContext(e,t),await this.sendWaveHeader(e)}async sendWaveHeader(e){let t=await this.audioSource.format;return e.send(new a.SpeechConnectionMessage(n.MessageType.Binary,`audio`,this.privRequestSession.requestId,`audio/x-wav`,t.header,this.audioStreamId))}reconnect(){return this.privConnectionPromise!==void 0&&!this.privServiceHasSentMessage?this.privConnectionPromise:(this.privConnectionId=null,this.privConnectionPromise=void 0,this.privServiceHasSentMessage=!1,this.connectImpl())}connectImpl(){return this.privConnectionPromise===void 0?(this.privConnectionPromise=this.retryableConnect(),this.privConnectionPromise.catch(()=>{}),this.postConnectImplOverride===void 0?this.privConnectionPromise:this.postConnectImplOverride(this.privConnectionPromise)):this.privConnectionPromise.then(e=>e.state()===n.ConnectionState.Disconnected?this.reconnect():this.privConnectionPromise,()=>this.reconnect())}sendSpeechServiceConfig(t,r,i){if(r.onSpeechContext(),e.telemetryDataEnabled!==!0){let e={context:{system:JSON.parse(i).context.system}};i=JSON.stringify(e)}if(this.privRecognizerConfig.parameters.getProperty(`f0f5debc-f8c9-4892-ac4b-90a7ab359fd2`,`false`).toLowerCase()===`true`){let e=JSON.parse(i);e.context.DisableReferenceChannel=`True`,e.context.MicSpec=`1_0_0`,i=JSON.stringify(e)}if(i)return t.send(new a.SpeechConnectionMessage(n.MessageType.Text,`speech.config`,r.requestId,`application/json`,i))}async fetchConnection(){return this.privConnectionConfigurationPromise===void 0?(this.privConnectionConfigurationPromise=this.configureConnection(),await this.privConnectionConfigurationPromise):this.privConnectionConfigurationPromise.then(e=>e.state()===n.ConnectionState.Disconnected?(this.privConnectionConfigurationPromise=void 0,this.fetchConnection()):this.privConnectionConfigurationPromise,()=>(this.privConnectionConfigurationPromise=void 0,this.fetchConnection()))}async sendAudio(e){let t=await this.audioSource.format;this.privAverageBytesPerMs=t.avgBytesPerSec/1e3;let r=Date.now(),i=this.privRecognizerConfig.parameters.getProperty(`SPEECH-TransmitLengthBeforThrottleMs`,`5000`),o=t.avgBytesPerSec/1e3*parseInt(i,10),s=this.privRequestSession.recogNumber,c=async()=>{if(!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===s){let i=await this.fetchConnection(),l=await e.read();if(this.privRequestSession.isSpeechEnded)return;let u,d;if(!l||l.isEnd?(u=null,d=0):(u=l.buffer,this.privRequestSession.onAudioSent(u.byteLength),d=o>=this.privRequestSession.bytesSent?0:Math.max(0,r-Date.now())),d!==0&&await this.delay(d),u!==null&&(r=Date.now()+u.byteLength*1e3/(t.avgBytesPerSec*2)),!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===s){if(i.send(new a.SpeechConnectionMessage(n.MessageType.Binary,`audio`,this.privRequestSession.requestId,null,u,this.audioStreamId)).catch(()=>{this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch(()=>{})}),l?.isEnd)this.privIsLiveAudio||this.privRequestSession.onSpeechEnded();else return c()}}};return c()}async retryableConnect(){let e=!1;this.privAuthFetchEventId=(0,n.createNoDashGuid)();let t=this.privRequestSession.sessionId;this.privConnectionId=t===void 0?(0,n.createNoDashGuid)():t,this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId,this.privConnectionId);let i=0,a=``;for(;this.privRequestSession.numConnectionAttempts<=this.privRecognizerConfig.maxRetryCount;){this.privRequestSession.onRetryConnection();let t=await(e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId));await this.privRequestSession.onAuthCompleted(!1);let n=await this.privConnectionFactory.create(this.privRecognizerConfig,t,this.privConnectionId);this.privRequestSession.listenForServiceTelemetry(n.events),n.events.attach(e=>{this.connectionEvents.onEvent(e)});let r=await n.open();if(r.statusCode===200)return await this.privRequestSession.onConnectionEstablishCompleted(r.statusCode),Promise.resolve(n);r.statusCode===1006&&(e=!0),i=r.statusCode,a=r.reason}return await this.privRequestSession.onConnectionEstablishCompleted(i,a),Promise.reject(`Unable to contact server. StatusCode: ${i}, ${this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Endpoint)} Reason: ${a}`)}delay(e){return new Promise(t=>this.privSetTimeout(t,e))}writeBufferToConsole(e){let t=`Buffer Size: `;if(e===null)t+=`null`;else{let n=new Uint8Array(e);t+=`${e.byteLength}\r\n`;for(let r=0;r<e.byteLength;r++)t+=n[r].toString(16).padStart(2,`0`)+` `,(r+1)%16==0&&(console.info(t),t=``)}console.info(t)}async sendFinalAudio(){await(await this.fetchConnection()).send(new a.SpeechConnectionMessage(n.MessageType.Binary,`audio`,this.privRequestSession.requestId,null,null,this.audioStreamId))}async configureConnection(){let e=await this.connectImpl();return this.configConnectionOverride===void 0?(await this.sendSpeechServiceConfig(e,this.privRequestSession,this.privRecognizerConfig.SpeechServiceConfig.serialize()),await this.sendPrePayloadJSON(e,!1),e):this.configConnectionOverride(e)}};e.ServiceRecognizerBase=b,b.telemetryDataEnabled=!0})),Wn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationServiceRecognizer=void 0;var t=Y(),n=Q();e.ConversationServiceRecognizer=class extends n.ServiceRecognizerBase{constructor(e,t,n,r,i){super(e,t,n,r,i),this.handleSpeechPhraseMessage=async e=>this.handleSpeechPhrase(e),this.handleSpeechHypothesisMessage=e=>this.handleSpeechHypothesis(e)}processTypeSpecificMessages(e){}handleRecognizedCallback(e,t,n){}handleRecognizingCallback(e,t,n){}async processSpeechMessages(e){let t=!1;switch(e.path.toLowerCase()){case`speech.hypothesis`:case`speech.fragment`:this.handleSpeechHypothesisMessage&&this.handleSpeechHypothesisMessage(e.textBody),t=!0;break;case`speech.phrase`:this.handleSpeechPhraseMessage&&await this.handleSpeechPhraseMessage(e.textBody),t=!0}return t}cancelRecognition(e,t,n,r,i){}async handleSpeechPhrase(e){let r=n.SimpleSpeechPhrase.fromJSON(e,this.privRequestSession.currentTurnAudioOffset),i=n.EnumTranslation.implTranslateRecognitionResult(r.RecognitionStatus),a,o=new t.PropertyCollection;if(o.setProperty(t.PropertyId.SpeechServiceResponse_JsonResult,e),this.privRequestSession.onPhraseRecognized(r.Offset+r.Duration),t.ResultReason.Canceled===i){let e=n.EnumTranslation.implTranslateCancelResult(r.RecognitionStatus),t=n.EnumTranslation.implTranslateCancelErrorCode(r.RecognitionStatus);await this.cancelRecognitionLocal(e,t,n.EnumTranslation.implTranslateErrorDetails(t))}else if(r.RecognitionStatus!==n.RecognitionStatus.EndOfDictation){if(this.privRecognizerConfig.parameters.getProperty(n.OutputFormatPropertyName)===t.OutputFormat[t.OutputFormat.Simple])a=new t.SpeechRecognitionResult(this.privRequestSession.requestId,i,r.DisplayText,r.Duration,r.Offset,r.Language,r.LanguageDetectionConfidence,r.SpeakerId,void 0,r.asJson(),o);else{let r=n.DetailedSpeechPhrase.fromJSON(e,this.privRequestSession.currentTurnAudioOffset);a=new t.SpeechRecognitionResult(this.privRequestSession.requestId,i,r.Text,r.Duration,r.Offset,r.Language,r.LanguageDetectionConfidence,r.SpeakerId,void 0,r.asJson(),o)}this.handleRecognizedCallback(a,a.offset,this.privRequestSession.sessionId)}}handleSpeechHypothesis(e){let r=n.SpeechHypothesis.fromJSON(e,this.privRequestSession.currentTurnAudioOffset),i=new t.PropertyCollection;i.setProperty(t.PropertyId.SpeechServiceResponse_JsonResult,e);let a=new t.SpeechRecognitionResult(this.privRequestSession.requestId,t.ResultReason.RecognizingSpeech,r.Text,r.Duration,r.Offset,r.Language,r.LanguageDetectionConfidence,r.SpeakerId,void 0,r.asJson(),i);this.privRequestSession.onHypothesis(r.Offset),this.handleRecognizingCallback(a,r.Duration,this.privRequestSession.sessionId)}}})),Gn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RecognizerConfig=e.SpeechResultFormat=void 0;var t=Y(),n=Q(),r=W();(function(e){e[e.Simple=0]=`Simple`,e[e.Detailed=1]=`Detailed`})(e.SpeechResultFormat||={}),e.RecognizerConfig=class{constructor(e,r){this.privSpeechServiceConfig=e||new n.SpeechServiceConfig(new n.Context(null)),this.privParameters=r,this.privMaxRetryCount=parseInt(r.getProperty(`SPEECH-Error-MaxRetryCount`,`4`),10),this.privLanguageIdMode=r.getProperty(t.PropertyId.SpeechServiceConnection_LanguageIdMode,void 0),this.privEnableSpeakerId=!1}get parameters(){return this.privParameters}get recognitionMode(){return this.privRecognitionMode}set recognitionMode(e){this.privRecognitionMode=e,this.privRecognitionActivityTimeout=e===r.RecognitionMode.Interactive?8e3:25e3,this.privSpeechServiceConfig.Recognition=r.RecognitionMode[e]}get SpeechServiceConfig(){return this.privSpeechServiceConfig}get recognitionActivityTimeout(){return this.privRecognitionActivityTimeout}get isContinuousRecognition(){return this.privRecognitionMode!==r.RecognitionMode.Interactive}get languageIdMode(){return this.privLanguageIdMode}get autoDetectSourceLanguages(){return this.parameters.getProperty(t.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)}get recognitionEndpointVersion(){return this.parameters.getProperty(t.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,`2`)}set recognitionEndpointVersion(e){this.parameters.setProperty(t.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,e)}get sourceLanguageModels(){let e=[],n=!1;if(this.autoDetectSourceLanguages!==void 0)for(let r of this.autoDetectSourceLanguages.split(`,`)){let i=r+t.PropertyId.SpeechServiceConnection_EndpointId.toString(),a=this.parameters.getProperty(i,void 0);a===void 0?e.push({language:r,endpoint:``}):(e.push({language:r,endpoint:a}),n=!0)}return n?e:void 0}get maxRetryCount(){return this.privMaxRetryCount}get isSpeakerDiarizationEnabled(){return this.privEnableSpeakerId}set isSpeakerDiarizationEnabled(e){this.privEnableSpeakerId=e}}})),Kn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),qn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebsocketMessageFormatter=void 0;var t=k(),n=`\r
|
|
19
|
+
`;e.WebsocketMessageFormatter=class{toConnectionMessage(e){let n=new t.Deferred;try{if(e.messageType===t.MessageType.Text){let r=e.textContent,i={},a=null;if(r){let e=r.split(`\r
|
|
20
|
+
\r
|
|
21
|
+
`);e&&e.length>0&&(i=this.parseHeaders(e[0]),e.length>1&&(a=e[1]))}n.resolve(new t.ConnectionMessage(e.messageType,a,i,e.id))}else if(e.messageType===t.MessageType.Binary){let r=e.binaryContent,i={},a=null;if(!r||r.byteLength<2)throw Error(`Invalid binary message format. Header length missing.`);let o=new DataView(r),s=o.getInt16(0);if(r.byteLength<s+2)throw Error(`Invalid binary message format. Header content missing.`);let c=``;for(let e=0;e<s;e++)c+=String.fromCharCode(o.getInt8(e+2));i=this.parseHeaders(c),r.byteLength>s+2&&(a=r.slice(2+s)),n.resolve(new t.ConnectionMessage(e.messageType,a,i,e.id))}}catch(e){n.reject(`Error formatting the message. Error: ${e}`)}return n.promise}fromConnectionMessage(e){let r=new t.Deferred;try{if(e.messageType===t.MessageType.Text){let i=`${this.makeHeaders(e)}${n}${e.textBody?e.textBody:``}`;r.resolve(new t.RawWebsocketMessage(t.MessageType.Text,i,e.id))}else if(e.messageType===t.MessageType.Binary){let n=this.makeHeaders(e),i=e.binaryBody,a=this.stringToArrayBuffer(n),o=new Int8Array(a),s=o.byteLength,c=new Int8Array(2+s+(i?i.byteLength:0));if(c[0]=s>>8&255,c[1]=s&255,c.set(o,2),i){let e=new Int8Array(i);c.set(e,2+s)}let l=c.buffer;r.resolve(new t.RawWebsocketMessage(t.MessageType.Binary,l,e.id))}}catch(e){r.reject(`Error formatting the message. ${e}`)}return r.promise}makeHeaders(e){let t=``;if(e.headers)for(let r in e.headers)r&&(t+=`${r}: ${e.headers[r]}${n}`);return t}parseHeaders(e){let t={};if(e){let n=e.match(/[^\r\n]+/g);if(t){for(let e of n)if(e){let n=e.indexOf(`:`),r=n>0?e.substr(0,n).trim().toLowerCase():e;t[r]=n>0&&e.length>n+1?e.substr(n+1).trim():``}}}return t}stringToArrayBuffer(e){let t=new ArrayBuffer(e.length),n=new DataView(t);for(let t=0;t<e.length;t++)n.setUint8(t,e.charCodeAt(t));return t}}})),Jn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechConnectionFactory=void 0;var t=X(),n=Q(),r=Y(),i=q(),a=Q(),o=A(),s=K(),c=W();e.SpeechConnectionFactory=class extends i.ConnectionFactoryBase{constructor(){super(...arguments),this.interactiveRelativeUri=`/speech/recognition/interactive/cognitiveservices/v1`,this.conversationRelativeUri=`/speech/recognition/conversation/cognitiveservices/v1`,this.dictationRelativeUri=`/speech/recognition/dictation/cognitiveservices/v1`,this.universalUri=`/stt/speech/universal/v`}async create(e,l,u){let d=e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Endpoint,void 0),f=e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Region,void 0),p=i.ConnectionFactoryBase.getHostSuffix(f),m=e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Host,`wss://`+f+`.stt.speech`+p),h={},g=e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_EndpointId,void 0),_=e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage,void 0),v=e.parameters.getProperty(r.PropertyId.Speech_EnableMultiChannelProcessing,`false`).toLowerCase()===`true`;if(g?(!d||d.search(s.QueryParameterNames.CustomSpeechDeploymentId)===-1)&&(h[s.QueryParameterNames.CustomSpeechDeploymentId]=g):_&&!v&&(!d||d.search(s.QueryParameterNames.Language)===-1)&&(h[s.QueryParameterNames.Language]=_),!v&&(!d||d.search(s.QueryParameterNames.Format)===-1)&&(h[s.QueryParameterNames.Format]=e.parameters.getProperty(n.OutputFormatPropertyName,r.OutputFormat[r.OutputFormat.Simple]).toLowerCase()),e.autoDetectSourceLanguages!==void 0&&(h[s.QueryParameterNames.EnableLanguageId]=`true`),this.setCommonUrlParams(e,h,d),d){let t=new URL(d),n=t.pathname;(n===``||n===`/`)&&(t.pathname=this.universalUri+e.recognitionEndpointVersion,d=await i.ConnectionFactoryBase.getRedirectUrlFromEndpoint(t.toString()))}if(!d)switch(e.recognitionMode){case c.RecognitionMode.Conversation:d=e.parameters.getProperty(n.ForceDictationPropertyName,`false`)===`true`?m+this.dictationRelativeUri:e.recognitionEndpointVersion!==void 0&&parseInt(e.recognitionEndpointVersion,10)>1?`${m}${this.universalUri}${e.recognitionEndpointVersion}`:m+this.conversationRelativeUri;break;case c.RecognitionMode.Dictation:d=m+this.dictationRelativeUri;break;default:d=e.recognitionEndpointVersion!==void 0&&parseInt(e.recognitionEndpointVersion,10)>1?`${m}${this.universalUri}${e.recognitionEndpointVersion}`:m+this.interactiveRelativeUri}let y={};l.token!==void 0&&l.token!==``&&(y[l.headerName]=l.token),y[o.HeaderNames.ConnectionId]=u,y.connectionId=u;let b=e.parameters.getProperty(`SPEECH-EnableWebsocketCompression`,`false`)===`true`,x=new t.WebsocketConnection(d,h,y,new a.WebsocketMessageFormatter,t.ProxyInfo.fromRecognizerConfig(e),b,u),S=x.uri;return e.parameters.setProperty(r.PropertyId.SpeechServiceConnection_Url,S),x}}})),Yn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationTranscriberConnectionFactory=void 0;var t=X(),n=Y(),r=Q(),i=q(),a=Q(),o=A(),s=K();e.ConversationTranscriberConnectionFactory=class extends i.ConnectionFactoryBase{constructor(){super(...arguments),this.universalUri=`/stt/speech/universal/v2`,this.conversationRelativeUriV1=`/speech/recognition/conversation/cognitiveservices/v1`}async create(e,r,c){let l=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Endpoint,void 0),u=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Region,void 0),d=i.ConnectionFactoryBase.getHostSuffix(u),f=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Host,`wss://`+u+`.stt.speech`+d),p={},m=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_EndpointId,void 0),h=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_RecoLanguage,void 0);if(m?(!l||l.search(s.QueryParameterNames.CustomSpeechDeploymentId)===-1)&&(p[s.QueryParameterNames.CustomSpeechDeploymentId]=m):h&&(!l||l.search(s.QueryParameterNames.Language)===-1)&&(p[s.QueryParameterNames.Language]=h),e.autoDetectSourceLanguages!==void 0&&(p[s.QueryParameterNames.EnableLanguageId]=`true`),e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,void 0)===`1`)l=`${f}${this.universalUri}`;else{if(this.setV2UrlParams(e,p,l),l){let e=new URL(l),t=e.pathname;(t===``||t===`/`)&&(e.pathname=this.universalUri,l=await i.ConnectionFactoryBase.getRedirectUrlFromEndpoint(e.toString()))}l||=`${f}${this.conversationRelativeUriV1}`}let g={};r.token!==void 0&&r.token!==``&&(g[r.headerName]=r.token),g[o.HeaderNames.ConnectionId]=c;let _=e.parameters.getProperty(`SPEECH-EnableWebsocketCompression`,`false`)===`true`,v=new t.WebsocketConnection(l,p,g,new a.WebsocketMessageFormatter,t.ProxyInfo.fromRecognizerConfig(e),_,c),y=v.uri;return e.parameters.setProperty(n.PropertyId.SpeechServiceConnection_Url,y),v}setV2UrlParams(e,t,i){new Map([[n.PropertyId.Speech_SegmentationSilenceTimeoutMs,s.QueryParameterNames.SegmentationSilenceTimeoutMs],[n.PropertyId.SpeechServiceConnection_EnableAudioLogging,s.QueryParameterNames.EnableAudioLogging],[n.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs,s.QueryParameterNames.EndSilenceTimeoutMs],[n.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs,s.QueryParameterNames.InitialSilenceTimeoutMs],[n.PropertyId.SpeechServiceResponse_ProfanityOption,s.QueryParameterNames.Profanity],[n.PropertyId.SpeechServiceResponse_StablePartialResultThreshold,s.QueryParameterNames.StableIntermediateThreshold]]).forEach((n,r)=>{this.setUrlParameter(r,n,e,t,i)});let a=JSON.parse(e.parameters.getProperty(r.ServicePropertiesPropertyName,`{}`));Object.keys(a).forEach(e=>{t[e]=a[e]})}}})),Xn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranscriberConnectionFactory=void 0;var t=X(),n=Y(),r=q(),i=Q(),a=A(),o=K();e.TranscriberConnectionFactory=class extends r.ConnectionFactoryBase{constructor(){super(...arguments),this.multiaudioRelativeUri=`/speech/recognition/multiaudio`}create(e,o,s){let c=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Endpoint,void 0),l=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Region,`centralus`),u=r.ConnectionFactoryBase.getHostSuffix(l),d=`wss://transcribe.`+l+`.cts.speech`+u+this.multiaudioRelativeUri,f=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Host,d),p={};this.setQueryParams(p,e,c),c||=f;let m={};o.token!==void 0&&o.token!==``&&(m[o.headerName]=o.token),m[a.HeaderNames.ConnectionId]=s,e.parameters.setProperty(n.PropertyId.SpeechServiceConnection_Url,c);let h=e.parameters.getProperty(`SPEECH-EnableWebsocketCompression`,`false`)===`true`;return Promise.resolve(new t.WebsocketConnection(c,p,m,new i.WebsocketMessageFormatter,t.ProxyInfo.fromRecognizerConfig(e),h,s))}setQueryParams(e,t,r){let a=t.parameters.getProperty(n.PropertyId.SpeechServiceConnection_EndpointId,void 0),s=t.parameters.getProperty(n.PropertyId.SpeechServiceConnection_RecoLanguage,void 0);a&&!(o.QueryParameterNames.CustomSpeechDeploymentId in e)&&(e[o.QueryParameterNames.CustomSpeechDeploymentId]=a),s&&!(o.QueryParameterNames.Language in e)&&(e[o.QueryParameterNames.Language]=s);let c=t.parameters.getProperty(n.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,`false`).toLowerCase()===`true`,l=t.parameters.getProperty(i.OutputFormatPropertyName,n.OutputFormat[n.OutputFormat.Simple])!==n.OutputFormat[n.OutputFormat.Simple];(c||l)&&(e[o.QueryParameterNames.Format]=n.OutputFormat[n.OutputFormat.Detailed].toLowerCase()),this.setCommonUrlParams(t,e,r)}}})),Zn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.StringUtils=void 0,e.StringUtils=class{static formatString(e,t){if(!e)return``;if(!t)return e;let n=``,r=``,i=e=>{n+=e},a=e=>{r+=e},o=i;for(let s=0;s<e.length;s++){let c=e[s],l=s+1<e.length?e[s+1]:``;switch(c){case`{`:l===`{`?(o(`{`),s++):o=a;break;case`}`:l===`}`?(o(`}`),s++):(t.hasOwnProperty(r)&&(n+=t[r]),o=i,r=``);break;default:o(c)}}return n}}})),Qn=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationConnectionFactory=void 0;var t=X(),n=Zn(),r=Y(),i=q(),a=Q(),o=A(),s=K(),c=W();e.TranslationConnectionFactory=class extends i.ConnectionFactoryBase{constructor(){super(...arguments),this.universalUri=`/stt/speech/universal/v2`,this.translationV1Uri=`/speech/translation/cognitiveservices/v1`}async create(e,n,s){let c=this.getEndpointUrl(e),l={};if(this.setQueryParams(l,e,c),c){let e=new URL(c),t=e.pathname;(t===``||t===`/`)&&(e.pathname=this.universalUri,c=await i.ConnectionFactoryBase.getRedirectUrlFromEndpoint(e.toString()))}let u={};n.token!==void 0&&n.token!==``&&(u[n.headerName]=n.token),u[o.HeaderNames.ConnectionId]=s,e.parameters.setProperty(r.PropertyId.SpeechServiceConnection_Url,c);let d=e.parameters.getProperty(`SPEECH-EnableWebsocketCompression`,`false`)===`true`;return new t.WebsocketConnection(c,l,u,new a.WebsocketMessageFormatter,t.ProxyInfo.fromRecognizerConfig(e),d,s)}getEndpointUrl(e,t){let a=e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Region),o=i.ConnectionFactoryBase.getHostSuffix(a),s=e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Endpoint,void 0);return s||=e.parameters.getProperty(`SPEECH-ForceV1Endpoint`,`false`)===`true`?e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Host,`wss://{region}.s2s.speech`+o)+this.translationV1Uri:e.parameters.getProperty(r.PropertyId.SpeechServiceConnection_Host,`wss://{region}.stt.speech`+o)+this.universalUri,t===!0?s:n.StringUtils.formatString(s,{region:a})}setQueryParams(e,t,n){e.from=t.parameters.getProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage),e.to=t.parameters.getProperty(r.PropertyId.SpeechServiceConnection_TranslationToLanguages),e.scenario=t.recognitionMode===c.RecognitionMode.Interactive?`interactive`:t.recognitionMode===c.RecognitionMode.Conversation?`conversation`:``,this.setCommonUrlParams(t,e,n),this.setUrlParameter(r.PropertyId.SpeechServiceResponse_TranslationRequestStablePartialResult,s.QueryParameterNames.StableTranslation,t,e,n);let i=t.parameters.getProperty(r.PropertyId.SpeechServiceConnection_TranslationVoice,void 0);i!==void 0&&(e.voice=i,e.features=`requireVoice`)}}})),$n=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.EnumTranslation=void 0;var t=Y(),n=Q();e.EnumTranslation=class{static implTranslateRecognitionResult(e,r=!1){let i=t.ResultReason.Canceled;switch(e){case n.RecognitionStatus.Success:i=t.ResultReason.RecognizedSpeech;break;case n.RecognitionStatus.EndOfDictation:i=r?t.ResultReason.RecognizedSpeech:t.ResultReason.NoMatch;break;case n.RecognitionStatus.NoMatch:case n.RecognitionStatus.InitialSilenceTimeout:case n.RecognitionStatus.BabbleTimeout:i=t.ResultReason.NoMatch;break;case n.RecognitionStatus.Error:case n.RecognitionStatus.BadRequest:case n.RecognitionStatus.Forbidden:default:i=t.ResultReason.Canceled}return i}static implTranslateCancelResult(e){let r=t.CancellationReason.EndOfStream;switch(e){case n.RecognitionStatus.Success:case n.RecognitionStatus.EndOfDictation:case n.RecognitionStatus.NoMatch:r=t.CancellationReason.EndOfStream;break;case n.RecognitionStatus.InitialSilenceTimeout:case n.RecognitionStatus.BabbleTimeout:case n.RecognitionStatus.Error:case n.RecognitionStatus.BadRequest:case n.RecognitionStatus.Forbidden:default:r=t.CancellationReason.Error}return r}static implTranslateCancelErrorCode(e){let r=t.CancellationErrorCode.NoError;switch(e){case n.RecognitionStatus.Error:r=t.CancellationErrorCode.ServiceError;break;case n.RecognitionStatus.TooManyRequests:r=t.CancellationErrorCode.TooManyRequests;break;case n.RecognitionStatus.BadRequest:r=t.CancellationErrorCode.BadRequestParameters;break;case n.RecognitionStatus.Forbidden:r=t.CancellationErrorCode.Forbidden;break;default:r=t.CancellationErrorCode.NoError}return r}static implTranslateErrorDetails(e){let n=`The speech service encountered an internal error and could not continue.`;switch(e){case t.CancellationErrorCode.Forbidden:n=`The recognizer is using a free subscription that ran out of quota.`;break;case t.CancellationErrorCode.BadRequestParameters:n=`Invalid parameter or unsupported audio format in the request.`;break;case t.CancellationErrorCode.TooManyRequests:n=`The number of parallel requests exceeded the number of allowed concurrent transcriptions.`}return n}}})),er=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RecognitionStatus=e.SynthesisStatus=void 0,(function(e){e[e.Success=0]=`Success`,e[e.SynthesisEnd=1]=`SynthesisEnd`,e[e.Error=2]=`Error`})(e.SynthesisStatus||={}),(function(e){e[e.Success=0]=`Success`,e[e.NoMatch=1]=`NoMatch`,e[e.InitialSilenceTimeout=2]=`InitialSilenceTimeout`,e[e.BabbleTimeout=3]=`BabbleTimeout`,e[e.Error=4]=`Error`,e[e.EndOfDictation=5]=`EndOfDictation`,e[e.TooManyRequests=6]=`TooManyRequests`,e[e.BadRequest=7]=`BadRequest`,e[e.Forbidden=8]=`Forbidden`})(e.RecognitionStatus||={})})),tr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationSynthesisEnd=void 0;var t=Q();e.TranslationSynthesisEnd=class e{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus&&(this.privSynthesisEnd.SynthesisStatus=t.SynthesisStatus[this.privSynthesisEnd.SynthesisStatus]),this.privSynthesisEnd.Status&&(this.privSynthesisEnd.SynthesisStatus=t.SynthesisStatus[this.privSynthesisEnd.Status])}static fromJSON(t){return new e(t)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}})),nr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationHypothesis=void 0;var t=F(),n=O();e.TranslationHypothesis=class e{constructor(e,t){this.privTranslationHypothesis=e,this.privTranslationHypothesis.Offset+=t,this.privTranslationHypothesis.Translation.TranslationStatus=this.mapTranslationStatus(this.privTranslationHypothesis.Translation.TranslationStatus)}static fromJSON(t,n){return new e(JSON.parse(t),n)}static fromTranslationResponse(n,r){t.Contracts.throwIfNullOrUndefined(n,`translationHypothesis`);let i=n.SpeechHypothesis;return n.SpeechHypothesis=void 0,i.Translation=n,new e(i,r)}get Duration(){return this.privTranslationHypothesis.Duration}get Offset(){return this.privTranslationHypothesis.Offset}get Text(){return this.privTranslationHypothesis.Text}get Translation(){return this.privTranslationHypothesis.Translation}get Language(){return this.privTranslationHypothesis.PrimaryLanguage?.Language}asJson(){let e={...this.privTranslationHypothesis};return e.Translation===void 0?JSON.stringify(e):JSON.stringify({...e,TranslationStatus:n.TranslationStatus[e.Translation.TranslationStatus]})}mapTranslationStatus(e){if(typeof e==`string`)return n.TranslationStatus[e];if(typeof e==`number`)return e}}})),rr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationPhrase=void 0;var t=F(),n=Q(),r=O();e.TranslationPhrase=class e{constructor(e,t){this.privTranslationPhrase=e,this.privTranslationPhrase.Offset+=t,this.privTranslationPhrase.RecognitionStatus=this.mapRecognitionStatus(this.privTranslationPhrase.RecognitionStatus),this.privTranslationPhrase.Translation!==void 0&&(this.privTranslationPhrase.Translation.TranslationStatus=this.mapTranslationStatus(this.privTranslationPhrase.Translation.TranslationStatus))}static fromJSON(t,n){return new e(JSON.parse(t),n)}static fromTranslationResponse(n,r){t.Contracts.throwIfNullOrUndefined(n,`translationResponse`);let i=n.SpeechPhrase;return n.SpeechPhrase=void 0,i.Translation=n,i.Text=i.DisplayText,new e(i,r)}get RecognitionStatus(){return this.privTranslationPhrase.RecognitionStatus}get Offset(){return this.privTranslationPhrase.Offset}get Duration(){return this.privTranslationPhrase.Duration}get Text(){return this.privTranslationPhrase.Text}get Language(){return this.privTranslationPhrase.PrimaryLanguage?.Language}get Confidence(){return this.privTranslationPhrase.PrimaryLanguage?.Confidence}get Translation(){return this.privTranslationPhrase.Translation}asJson(){let e={...this.privTranslationPhrase},t={...e,RecognitionStatus:n.RecognitionStatus[e.RecognitionStatus]};return e.Translation&&(t.Translation={...e.Translation,TranslationStatus:r.TranslationStatus[e.Translation.TranslationStatus]}),JSON.stringify(t)}mapRecognitionStatus(e){if(typeof e==`string`)return n.RecognitionStatus[e];if(typeof e==`number`)return e}mapTranslationStatus(e){if(typeof e==`string`)return r.TranslationStatus[e];if(typeof e==`number`)return e}}})),ir=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranslationServiceRecognizer=void 0;var t=k(),n=Y(),r=Q();e.TranslationServiceRecognizer=class extends r.ConversationServiceRecognizer{constructor(e,t,n,r,i){super(e,t,n,r,i),this.privTranslationRecognizer=i,this.connectionEvents.attach(e=>{e.name===`ConnectionEstablishedEvent`&&this.privTranslationRecognizer.onConnection()})}async processTypeSpecificMessages(e){let i=new n.PropertyCollection,a=await this.processSpeechMessages(e);if(a)return!0;let o=async e=>{i.setProperty(n.PropertyId.SpeechServiceResponse_JsonResult,e.asJson());let t=this.privRequestSession.onPhraseRecognized(e.Offset+e.Duration);if(t>0&&i.setProperty(n.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,t.toString()),e.RecognitionStatus===r.RecognitionStatus.Success){let t=this.fireEventForResult(e,i);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,t)}catch{}if(this.privSuccessCallback){try{this.privSuccessCallback(t.result)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}else{let t=r.EnumTranslation.implTranslateRecognitionResult(e.RecognitionStatus),o=new n.TranslationRecognitionResult(void 0,this.privRequestSession.requestId,t,e.Text,e.Duration,e.Offset,e.Language,e.Confidence,void 0,e.asJson(),i);if(t===n.ResultReason.Canceled){let t=r.EnumTranslation.implTranslateCancelResult(e.RecognitionStatus),n=r.EnumTranslation.implTranslateCancelErrorCode(e.RecognitionStatus);await this.cancelRecognitionLocal(t,n,r.EnumTranslation.implTranslateErrorDetails(n))}else if(e.RecognitionStatus!==r.RecognitionStatus.EndOfDictation){let e=new n.TranslationRecognitionEventArgs(o,o.offset,this.privRequestSession.sessionId);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,e)}catch{}if(this.privSuccessCallback){try{this.privSuccessCallback(o)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}a=!0}},s=e=>{i.setProperty(n.PropertyId.SpeechServiceResponse_JsonResult,e.asJson());let t=this.privRequestSession.onHypothesis(e.Offset);t>0&&i.setProperty(n.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,t.toString());let r=this.fireEventForResult(e,i);if(this.privTranslationRecognizer.recognizing)try{this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer,r)}catch{}a=!0};switch(e.messageType===t.MessageType.Text&&i.setProperty(n.PropertyId.SpeechServiceResponse_JsonResult,e.textBody),e.path.toLowerCase()){case`translation.hypothesis`:s(r.TranslationHypothesis.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset));break;case`translation.response`:let t=JSON.parse(e.textBody);if(t.SpeechPhrase)await o(r.TranslationPhrase.fromTranslationResponse(t,this.privRequestSession.currentTurnAudioOffset));else{let t=JSON.parse(e.textBody);t.SpeechHypothesis&&s(r.TranslationHypothesis.fromTranslationResponse(t,this.privRequestSession.currentTurnAudioOffset))}break;case`translation.phrase`:await o(r.TranslationPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset));break;case`translation.synthesis`:case`audio`:this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),a=!0;break;case`audio.end`:case`translation.synthesis.end`:let i=r.TranslationSynthesisEnd.fromJSON(e.textBody);switch(i.SynthesisStatus){case r.SynthesisStatus.Error:if(this.privTranslationRecognizer.synthesizing){let e=new n.TranslationSynthesisResult(n.ResultReason.Canceled,void 0),t=new n.TranslationSynthesisEventArgs(e,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,t)}catch{}}if(this.privTranslationRecognizer.canceled){let e=new n.TranslationRecognitionCanceledEventArgs(this.privRequestSession.sessionId,n.CancellationReason.Error,i.FailureReason,n.CancellationErrorCode.ServiceError,null);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,e)}catch{}}break;case r.SynthesisStatus.Success:this.sendSynthesisAudio(void 0,this.privRequestSession.sessionId)}a=!0}return a}cancelRecognition(e,t,i,a,o){let s=new n.PropertyCollection;if(s.setProperty(r.CancellationErrorCodePropertyName,n.CancellationErrorCode[a]),this.privTranslationRecognizer.canceled){let t=new n.TranslationRecognitionCanceledEventArgs(e,i,o,a,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,t)}catch{}}if(this.privSuccessCallback){let e=new n.TranslationRecognitionResult(void 0,t,n.ResultReason.Canceled,void 0,void 0,void 0,void 0,void 0,o,void 0,s);try{this.privSuccessCallback(e),this.privSuccessCallback=void 0}catch{}}}handleRecognizingCallback(e,t,r){try{let i=new n.TranslationRecognitionEventArgs(n.TranslationRecognitionResult.fromSpeechRecognitionResult(e),t,r);this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer,i)}catch{}}handleRecognizedCallback(e,t,r){try{let i=new n.TranslationRecognitionEventArgs(n.TranslationRecognitionResult.fromSpeechRecognitionResult(e),t,r);this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,i)}catch{}}fireEventForResult(e,i){let a;if(e.Translation.Translations!==void 0){a=new n.Translations;for(let t of e.Translation.Translations)a.set(t.Language,t.Text||t.DisplayText)}let o,s;e instanceof r.TranslationPhrase?(o=e.Translation&&e.Translation.TranslationStatus===t.TranslationStatus.Success?n.ResultReason.TranslatedSpeech:n.ResultReason.RecognizedSpeech,s=e.Confidence):o=n.ResultReason.TranslatingSpeech;let c=e.Language,l=new n.TranslationRecognitionResult(a,this.privRequestSession.requestId,o,e.Text,e.Duration,e.Offset,c,s,e.Translation.FailureReason,e.asJson(),i);return new n.TranslationRecognitionEventArgs(l,e.Offset,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){let r=e===void 0?n.ResultReason.SynthesizingAudioCompleted:n.ResultReason.SynthesizingAudio,i=new n.TranslationSynthesisResult(r,e),a=new n.TranslationSynthesisEventArgs(i,t);if(this.privTranslationRecognizer.synthesizing)try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,a)}catch{}}}})),ar=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechDetected=void 0,e.SpeechDetected=class e{constructor(e,t){this.privSpeechStartDetected=JSON.parse(e),this.privSpeechStartDetected.Offset+=t}static fromJSON(t,n){return new e(t,n)}get Offset(){return this.privSpeechStartDetected.Offset}}})),or=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechHypothesis=void 0,e.SpeechHypothesis=class e{constructor(e,t){this.privSpeechHypothesis=JSON.parse(e),this.updateOffset(t)}static fromJSON(t,n){return new e(t,n)}updateOffset(e){this.privSpeechHypothesis.Offset+=e}asJson(){return JSON.stringify(this.privSpeechHypothesis)}get Text(){return this.privSpeechHypothesis.Text}get Offset(){return this.privSpeechHypothesis.Offset}get Duration(){return this.privSpeechHypothesis.Duration}get Language(){return this.privSpeechHypothesis.PrimaryLanguage===void 0?void 0:this.privSpeechHypothesis.PrimaryLanguage.Language}get LanguageDetectionConfidence(){return this.privSpeechHypothesis.PrimaryLanguage===void 0?void 0:this.privSpeechHypothesis.PrimaryLanguage.Confidence}get SpeakerId(){return this.privSpeechHypothesis.SpeakerId}}})),sr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechKeyword=void 0,e.SpeechKeyword=class e{constructor(e,t){this.privSpeechKeyword=JSON.parse(e),this.privSpeechKeyword.Offset+=t}static fromJSON(t,n){return new e(t,n)}get Status(){return this.privSpeechKeyword.Status}get Text(){return this.privSpeechKeyword.Text}get Offset(){return this.privSpeechKeyword.Offset}get Duration(){return this.privSpeechKeyword.Duration}asJson(){return JSON.stringify(this.privSpeechKeyword)}}})),cr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechServiceRecognizer=void 0;var t=Y(),n=Q();e.SpeechServiceRecognizer=class extends n.ServiceRecognizerBase{constructor(e,t,n,r,i){super(e,t,n,r,i),this.privSpeechRecognizer=i}async processTypeSpecificMessages(e){let r,i=new t.PropertyCollection,a=!1;switch(e.path.toLowerCase()){case`speech.hypothesis`:case`speech.fragment`:let o=n.SpeechHypothesis.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);i.setProperty(t.PropertyId.SpeechServiceResponse_JsonResult,o.asJson());let s=this.privRequestSession.onHypothesis(o.Offset);s>0&&i.setProperty(t.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,s.toString()),r=new t.SpeechRecognitionResult(this.privRequestSession.requestId,t.ResultReason.RecognizingSpeech,o.Text,o.Duration,o.Offset,o.Language,o.LanguageDetectionConfidence,void 0,void 0,o.asJson(),i);let c=new t.SpeechRecognitionEventArgs(r,o.Offset,this.privRequestSession.sessionId);if(this.privSpeechRecognizer.recognizing)try{this.privSpeechRecognizer.recognizing(this.privSpeechRecognizer,c)}catch{}a=!0;break;case`speech.phrase`:let l=n.SimpleSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);i.setProperty(t.PropertyId.SpeechServiceResponse_JsonResult,l.asJson());let u=n.EnumTranslation.implTranslateRecognitionResult(l.RecognitionStatus,this.privExpectContentAssessmentResponse),d=this.privRequestSession.onPhraseRecognized(l.Offset+l.Duration);if(d>0&&i.setProperty(t.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,d.toString()),t.ResultReason.Canceled===u){let e=n.EnumTranslation.implTranslateCancelResult(l.RecognitionStatus),t=n.EnumTranslation.implTranslateCancelErrorCode(l.RecognitionStatus);await this.cancelRecognitionLocal(e,t,n.EnumTranslation.implTranslateErrorDetails(t))}else{if(l.RecognitionStatus===n.RecognitionStatus.EndOfDictation)break;if(this.privRecognizerConfig.parameters.getProperty(n.OutputFormatPropertyName)===t.OutputFormat[t.OutputFormat.Simple])r=new t.SpeechRecognitionResult(this.privRequestSession.requestId,u,l.DisplayText,l.Duration,l.Offset,l.Language,l.LanguageDetectionConfidence,void 0,void 0,l.asJson(),i,l.Channel);else{let a=n.DetailedSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);i.setProperty(t.PropertyId.SpeechServiceResponse_JsonResult,a.asJson()),r=new t.SpeechRecognitionResult(this.privRequestSession.requestId,u,a.RecognitionStatus===n.RecognitionStatus.Success?a.NBest[0].Display:``,a.Duration,a.Offset,a.Language,a.LanguageDetectionConfidence,void 0,void 0,a.asJson(),i,a.Channel)}let a=new t.SpeechRecognitionEventArgs(r,r.offset,this.privRequestSession.sessionId);if(this.privSpeechRecognizer.recognized)try{this.privSpeechRecognizer.recognized(this.privSpeechRecognizer,a)}catch{}if(this.privSuccessCallback){try{this.privSuccessCallback(r)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}a=!0}return a}cancelRecognition(e,r,i,a,o){let s=new t.PropertyCollection;if(s.setProperty(n.CancellationErrorCodePropertyName,t.CancellationErrorCode[a]),this.privSpeechRecognizer.canceled){let n=new t.SpeechRecognitionCanceledEventArgs(i,o,a,void 0,e);try{this.privSpeechRecognizer.canceled(this.privSpeechRecognizer,n)}catch{}}if(this.privSuccessCallback){let e=new t.SpeechRecognitionResult(r,t.ResultReason.Canceled,void 0,void 0,void 0,void 0,void 0,void 0,o,void 0,s);try{this.privSuccessCallback(e),this.privSuccessCallback=void 0}catch{}}}}})),lr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.IdentityProvider=e.SpeakerDiarizationMode=void 0,(function(e){e.None=`None`,e.Identity=`Identity`,e.Anonymous=`Anonymous`})(e.SpeakerDiarizationMode||={}),(function(e){e.CallCenter=`CallCenter`})(e.IdentityProvider||={})})),ur=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationTranscriptionServiceRecognizer=void 0;var t=Y(),n=Q(),r=lr(),i=W();e.ConversationTranscriptionServiceRecognizer=class extends n.ServiceRecognizerBase{constructor(e,t,n,r,i){super(e,t,n,r,i),this.privConversationTranscriber=i,this.setSpeakerDiarizationJson()}setSpeakerDiarizationJson(){if(this.privEnableSpeakerId){let e=this.privSpeechContext.getContext().phraseDetection||{};e.mode=i.RecognitionMode.Conversation;let n={};n.mode=r.SpeakerDiarizationMode.Anonymous,n.audioSessionId=this.privDiarizationSessionId,n.audioOffsetMs=0,n.diarizeIntermediates=this.privRecognizerConfig.parameters.getProperty(t.PropertyId.SpeechServiceResponse_DiarizeIntermediateResults,`false`)===`true`,e.speakerDiarization=n,this.privSpeechContext.getContext().phraseDetection=e}}async processTypeSpecificMessages(e){let r,i=new t.PropertyCollection;i.setProperty(t.PropertyId.SpeechServiceResponse_JsonResult,e.textBody);let a=!1;switch(e.path.toLowerCase()){case`speech.hypothesis`:case`speech.fragment`:let o=n.SpeechHypothesis.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset),s=this.privRequestSession.onHypothesis(o.Offset);s>0&&i.setProperty(t.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,s.toString()),r=new t.ConversationTranscriptionResult(this.privRequestSession.requestId,t.ResultReason.RecognizingSpeech,o.Text,o.Duration,o.Offset,o.Language,o.LanguageDetectionConfidence,o.SpeakerId,void 0,o.asJson(),i);let c=new t.ConversationTranscriptionEventArgs(r,o.Duration,this.privRequestSession.sessionId);if(this.privConversationTranscriber.transcribing)try{this.privConversationTranscriber.transcribing(this.privConversationTranscriber,c)}catch{}a=!0;break;case`speech.phrase`:let l=n.SimpleSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset),u=n.EnumTranslation.implTranslateRecognitionResult(l.RecognitionStatus),d=this.privRequestSession.onPhraseRecognized(l.Offset+l.Duration);if(d>0&&i.setProperty(t.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,d.toString()),t.ResultReason.Canceled===u){let e=n.EnumTranslation.implTranslateCancelResult(l.RecognitionStatus),t=n.EnumTranslation.implTranslateCancelErrorCode(l.RecognitionStatus);await this.cancelRecognitionLocal(e,t,n.EnumTranslation.implTranslateErrorDetails(t))}else if(!(this.privRequestSession.isSpeechEnded&&u===t.ResultReason.NoMatch&&l.RecognitionStatus!==n.RecognitionStatus.InitialSilenceTimeout)){if(this.privRecognizerConfig.parameters.getProperty(n.OutputFormatPropertyName)===t.OutputFormat[t.OutputFormat.Simple])r=new t.ConversationTranscriptionResult(this.privRequestSession.requestId,u,l.DisplayText,l.Duration,l.Offset,l.Language,l.LanguageDetectionConfidence,l.SpeakerId,void 0,l.asJson(),i);else{let a=n.DetailedSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);r=new t.ConversationTranscriptionResult(this.privRequestSession.requestId,u,a.RecognitionStatus===n.RecognitionStatus.Success?a.NBest[0].Display:void 0,a.Duration,a.Offset,a.Language,a.LanguageDetectionConfidence,l.SpeakerId,void 0,a.asJson(),i)}let a=new t.ConversationTranscriptionEventArgs(r,r.offset,this.privRequestSession.sessionId);if(this.privConversationTranscriber.transcribed)try{this.privConversationTranscriber.transcribed(this.privConversationTranscriber,a)}catch{}}a=!0}return a}cancelRecognition(e,r,i,a,o){if(new t.PropertyCollection().setProperty(n.CancellationErrorCodePropertyName,t.CancellationErrorCode[a]),this.privConversationTranscriber.canceled){let n=new t.ConversationTranscriptionCanceledEventArgs(i,o,a,void 0,e);try{this.privConversationTranscriber.canceled(this.privConversationTranscriber,n)}catch{}}}}})),dr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranscriptionServiceRecognizer=void 0;var t=k(),n=Y(),r=Q(),i=Z();e.TranscriptionServiceRecognizer=class extends r.ConversationServiceRecognizer{constructor(e,t,r,i,a){super(e,t,r,i,a),this.privTranscriberRecognizer=a,this.sendPrePayloadJSONOverride=e=>this.sendTranscriptionStartJSON(e),this.privRecognizerConfig.parameters.getProperty(n.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps)===`true`&&this.privSpeechContext.setWordLevelTimings()}async sendMeetingSpeechEventAsync(e,t){if(this.privRequestSession.isRecognizing){let n=await this.fetchConnection();await this.sendSpeechEvent(n,this.createMeetingSpeechEventPayload(e,t))}}processTypeSpecificMessages(e){return this.processSpeechMessages(e)}handleRecognizedCallback(e,t,r){try{let i=new n.SpeechRecognitionEventArgs(e,t,r);if(this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer,i),this.privSuccessCallback){try{this.privSuccessCallback(e)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}catch{}}handleRecognizingCallback(e,t,r){try{let i=new n.SpeechRecognitionEventArgs(e,t,r);this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer,i)}catch{}}cancelRecognition(e,t,i,a,o){let s=new n.PropertyCollection;if(s.setProperty(r.CancellationErrorCodePropertyName,n.CancellationErrorCode[a]),this.privTranscriberRecognizer.canceled){let t=new n.MeetingTranscriptionCanceledEventArgs(i,o,a,void 0,e);try{this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer,t)}catch{}}if(this.privSuccessCallback){let e=new n.SpeechRecognitionResult(t,n.ResultReason.Canceled,void 0,void 0,void 0,void 0,void 0,void 0,o,void 0,s);try{this.privSuccessCallback(e),this.privSuccessCallback=void 0}catch{}}}async sendTranscriptionStartJSON(e){await this.sendSpeechContext(e,!0);let t=this.privTranscriberRecognizer.getMeetingInfo(),n=this.createMeetingSpeechEventPayload(t,`start`);await this.sendSpeechEvent(e,n),await this.sendWaveHeader(e)}sendSpeechEvent(e,n){let r=JSON.stringify(n);if(r)return e.send(new i.SpeechConnectionMessage(t.MessageType.Text,`speech.event`,this.privRequestSession.requestId,`application/json`,r))}createMeetingSpeechEventPayload(e,t){let n={id:`meeting`,name:t,meeting:e.meetingProperties};return n.meeting.id=e.id,n.meeting.attendees=e.participants,n}}})),fr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DetailedSpeechPhrase=void 0;var t=Q();e.DetailedSpeechPhrase=class e{constructor(e,t){this.privDetailedSpeechPhrase=JSON.parse(e),this.privDetailedSpeechPhrase.RecognitionStatus=this.mapRecognitionStatus(this.privDetailedSpeechPhrase.RecognitionStatus),this.updateOffsets(t)}static fromJSON(t,n){return new e(t,n)}updateOffsets(e){if(this.privDetailedSpeechPhrase.Offset+=e,this.privDetailedSpeechPhrase.NBest)for(let t of this.privDetailedSpeechPhrase.NBest){if(t.Words)for(let n of t.Words)n.Offset+=e;if(t.DisplayWords)for(let n of t.DisplayWords)n.Offset+=e}}asJson(){let e={...this.privDetailedSpeechPhrase};return JSON.stringify({...e,RecognitionStatus:t.RecognitionStatus[e.RecognitionStatus]})}get RecognitionStatus(){return this.privDetailedSpeechPhrase.RecognitionStatus}get NBest(){return this.privDetailedSpeechPhrase.NBest}get Duration(){return this.privDetailedSpeechPhrase.Duration}get Offset(){return this.privDetailedSpeechPhrase.Offset}get Language(){return this.privDetailedSpeechPhrase.PrimaryLanguage===void 0?void 0:this.privDetailedSpeechPhrase.PrimaryLanguage.Language}get LanguageDetectionConfidence(){return this.privDetailedSpeechPhrase.PrimaryLanguage===void 0?void 0:this.privDetailedSpeechPhrase.PrimaryLanguage.Confidence}get Text(){return this.privDetailedSpeechPhrase.NBest&&this.privDetailedSpeechPhrase.NBest[0]?this.privDetailedSpeechPhrase.NBest[0].Display||this.privDetailedSpeechPhrase.NBest[0].DisplayText:this.privDetailedSpeechPhrase.DisplayText}get SpeakerId(){return this.privDetailedSpeechPhrase.SpeakerId}get Channel(){return this.privDetailedSpeechPhrase.Channel===void 0?0:this.privDetailedSpeechPhrase.Channel}mapRecognitionStatus(e){if(typeof e==`string`)return t.RecognitionStatus[e];if(typeof e==`number`)return e}}})),pr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SimpleSpeechPhrase=void 0;var t=Q();e.SimpleSpeechPhrase=class e{constructor(e,t=0){this.privSimpleSpeechPhrase=JSON.parse(e),this.privSimpleSpeechPhrase.RecognitionStatus=this.mapRecognitionStatus(this.privSimpleSpeechPhrase.RecognitionStatus),this.updateOffset(t)}static fromJSON(t,n){return new e(t,n)}updateOffset(e){this.privSimpleSpeechPhrase.Offset+=e}asJson(){let e={...this.privSimpleSpeechPhrase};return JSON.stringify({...e,RecognitionStatus:t.RecognitionStatus[e.RecognitionStatus]})}get RecognitionStatus(){return this.privSimpleSpeechPhrase.RecognitionStatus}get DisplayText(){return this.privSimpleSpeechPhrase.DisplayText}get Offset(){return this.privSimpleSpeechPhrase.Offset}get Duration(){return this.privSimpleSpeechPhrase.Duration}get Language(){return this.privSimpleSpeechPhrase.PrimaryLanguage===void 0?void 0:this.privSimpleSpeechPhrase.PrimaryLanguage.Language}get LanguageDetectionConfidence(){return this.privSimpleSpeechPhrase.PrimaryLanguage===void 0?void 0:this.privSimpleSpeechPhrase.PrimaryLanguage.Confidence}get SpeakerId(){return this.privSimpleSpeechPhrase.SpeakerId}get Channel(){return this.privSimpleSpeechPhrase.Channel===void 0?0:this.privSimpleSpeechPhrase.Channel}mapRecognitionStatus(e){if(typeof e==`string`)return t.RecognitionStatus[e];if(typeof e==`number`)return e}}})),mr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ServiceTelemetryListener=void 0;var t=k(),n=N();e.ServiceTelemetryListener=class{constructor(e,t,n){this.privIsDisposed=!1,this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privRequestId=e,this.privAudioSourceId=t,this.privAudioNodeId=n,this.privReceivedMessages={},this.privPhraseLatencies=[],this.privHypothesisLatencies=[]}phraseReceived(e){e>0&&this.privPhraseLatencies.push(Date.now()-e)}hypothesisReceived(e){e>0&&this.privHypothesisLatencies.push(Date.now()-e)}onEvent(e){this.privIsDisposed||(e instanceof n.RecognitionTriggeredEvent&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:`ListeningTrigger`,Start:e.eventTime}),e instanceof t.AudioStreamNodeAttachingEvent&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof t.AudioStreamNodeAttachedEvent&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof t.AudioSourceErrorEvent&&e.audioSourceId===this.privAudioSourceId&&(this.privMicMetric||={End:e.eventTime,Error:e.error,Name:`Microphone`,Start:this.privMicStartTime}),e instanceof t.AudioStreamNodeErrorEvent&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||={End:e.eventTime,Error:e.error,Name:`Microphone`,Start:this.privMicStartTime}),e instanceof t.AudioStreamNodeDetachedEvent&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||={End:e.eventTime,Name:`Microphone`,Start:this.privMicStartTime}),e instanceof n.ConnectingToServiceEvent&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof t.ConnectionStartEvent&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof t.ConnectionEstablishedEvent&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||={End:e.eventTime,Id:this.privConnectionId,Name:`Connection`,Start:this.privConnectionStartTime}),e instanceof t.ConnectionEstablishErrorEvent&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||={End:e.eventTime,Error:this.getConnectionError(e.statusCode),Id:this.privConnectionId,Name:`Connection`,Start:this.privConnectionStartTime}),e instanceof t.ConnectionMessageReceivedEvent&&e.connectionId===this.privConnectionId&&e.message&&e.message.headers&&e.message.headers.path&&(this.privReceivedMessages[e.message.headers.path]||(this.privReceivedMessages[e.message.headers.path]=[]),this.privReceivedMessages[e.message.headers.path].length<50&&this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime)))}getTelemetry(){let e=[];this.privListeningTriggerMetric&&e.push(this.privListeningTriggerMetric),this.privMicMetric&&e.push(this.privMicMetric),this.privConnectionEstablishMetric&&e.push(this.privConnectionEstablishMetric),this.privPhraseLatencies.length>0&&e.push({PhraseLatencyMs:this.privPhraseLatencies}),this.privHypothesisLatencies.length>0&&e.push({FirstHypothesisLatencyMs:this.privHypothesisLatencies});let t={Metrics:e,ReceivedMessages:this.privReceivedMessages},n=JSON.stringify(t);return this.privReceivedMessages={},this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privPhraseLatencies=[],this.privHypothesisLatencies=[],n}get hasTelemetry(){return Object.keys(this.privReceivedMessages).length!==0||this.privListeningTriggerMetric!==null||this.privMicMetric!==null||this.privConnectionEstablishMetric!==null||this.privPhraseLatencies.length!==0||this.privHypothesisLatencies.length!==0}dispose(){this.privIsDisposed=!0}getConnectionError(e){switch(e){case 400:case 1002:case 1003:case 1005:case 1007:case 1008:case 1009:return`BadRequest`;case 401:return`Unauthorized`;case 403:return`Forbidden`;case 503:case 1001:return`ServerUnavailable`;case 500:case 1011:return`ServerError`;case 408:case 504:return`Timeout`;default:return`statuscode:`+e.toString()}}}})),hr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RequestSession=void 0;var t=k(),n=N(),r=mr();e.RequestSession=class{constructor(e){this.privIsDisposed=!1,this.privDetachables=[],this.privIsAudioNodeDetached=!1,this.privIsRecognizing=!1,this.privIsSpeechEnded=!1,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privHypothesisReceived=!1,this.privBytesSent=0,this.privRecognitionBytesSent=0,this.privRecogNumber=0,this.privInTurn=!1,this.privConnectionAttempts=0,this.privAudioSourceId=e,this.privRequestId=(0,t.createNoDashGuid)(),this.privAudioNodeId=(0,t.createNoDashGuid)(),this.privTurnDeferral=new t.Deferred,this.privTurnDeferral.resolve()}get sessionId(){return this.privSessionId}get requestId(){return this.privRequestId}get audioNodeId(){return this.privAudioNodeId}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSpeechEnded(){return this.privIsSpeechEnded}get isRecognizing(){return this.privIsRecognizing}get currentTurnAudioOffset(){return this.privTurnStartAudioOffset}get recogNumber(){return this.privRecogNumber}get numConnectionAttempts(){return this.privConnectionAttempts}get bytesSent(){return this.privBytesSent}get recognitionBytesSent(){return this.privRecognitionBytesSent}listenForServiceTelemetry(e){this.privServiceTelemetryListener&&this.privDetachables.push(e.attachListener(this.privServiceTelemetryListener))}startNewRecognition(){this.privRecognitionBytesSent=0,this.privIsSpeechEnded=!1,this.privIsRecognizing=!0,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privRecogNumber++,this.privServiceTelemetryListener=new r.ServiceTelemetryListener(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new n.RecognitionTriggeredEvent(this.requestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}async onAudioSourceAttachCompleted(e,t){this.privAudioNode=e,this.privIsAudioNodeDetached=!1,t?await this.onComplete():this.onEvent(new n.ListeningStartedEvent(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new n.ConnectingToServiceEvent(this.privRequestId,this.privAuthFetchEventId,this.privSessionId))}async onAuthCompleted(e){e&&await this.onComplete()}async onConnectionEstablishCompleted(e,t){if(e===200){this.onEvent(new n.RecognitionStartedEvent(this.requestId,this.privAudioSourceId,this.privAudioNodeId,this.privAuthFetchEventId,this.privSessionId)),this.privAudioNode&&this.privAudioNode.replay(),this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privBytesSent=0;return}e===403&&await this.onComplete()}async onServiceTurnEndResponse(e){this.privTurnDeferral.resolve(),!e||this.isSpeechEnded?(await this.onComplete(),this.privInTurn=!1):(this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privAudioNode.replay())}onSpeechContext(){this.privRequestId=(0,t.createNoDashGuid)()}onServiceTurnStartResponse(){this.privTurnDeferral&&this.privInTurn&&(this.privTurnDeferral.reject(`Another turn started before current completed.`),this.privTurnDeferral.promise.then().catch(()=>{})),this.privInTurn=!0,this.privTurnDeferral=new t.Deferred}onHypothesis(e){let t=this.privAudioNode.findTimeAtOffset(e);return this.privHypothesisReceived||(this.privHypothesisReceived=!0,this.privServiceTelemetryListener.hypothesisReceived(t)),t>0?Date.now()-t:0}onPhraseRecognized(e){let t=this.privAudioNode.findTimeAtOffset(e);return this.privServiceTelemetryListener.phraseReceived(t),this.onServiceRecognized(e),t>0?Date.now()-t:0}onServiceRecognized(e){this.privLastRecoOffset=e,this.privHypothesisReceived=!1,this.privAudioNode.shrinkBuffers(e),this.privConnectionAttempts=0}onServiceAcknowledgedAudio(e){this.privAudioNode&&this.privAudioNode.shrinkBuffers(e)}onAudioSent(e){this.privBytesSent+=e,this.privRecognitionBytesSent+=e}onRetryConnection(){this.privConnectionAttempts++}async dispose(){if(!this.privIsDisposed){this.privIsDisposed=!0;for(let e of this.privDetachables)await e.detach();this.privServiceTelemetryListener&&this.privServiceTelemetryListener.dispose(),this.privIsRecognizing=!1}}getTelemetry(){return this.privServiceTelemetryListener.hasTelemetry?this.privServiceTelemetryListener.getTelemetry():null}async onStopRecognizing(){await this.onComplete()}onSpeechEnded(){this.privIsSpeechEnded=!0}onEvent(e){this.privServiceTelemetryListener&&this.privServiceTelemetryListener.onEvent(e),t.Events.instance.onEvent(e)}async onComplete(){this.privIsRecognizing&&(this.privIsRecognizing=!1,await this.detachAudioNode())}async detachAudioNode(){this.privIsAudioNodeDetached||(this.privIsAudioNodeDetached=!0,this.privAudioNode&&await this.privAudioNode.detach())}}})),gr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TentativePhraseResultsOption=e.OutputFormat=e.PhraseExtension=e.PhraseOption=void 0,(function(e){e.WordTimings=`WordTimings`,e.SNR=`SNR`,e.Pronunciation=`Pronunciation`,e.WordPronunciation=`WordPronunciation`,e.WordConfidence=`WordConfidence`,e.Words=`Words`,e.Sentiment=`Sentiment`,e.PronunciationAssessment=`PronunciationAssessment`,e.ContentAssessment=`ContentAssessment`,e.PhraseAMScore=`PhraseAMScore`,e.PhraseLMScore=`PhraseLMScore`,e.WordAMScore=`WordAMScore`,e.WordLMScore=`WordLMScore`,e.RuleTree=`RuleTree`,e.NBestTimings=`NBestTimings`,e.DecoderDiagnostics=`DecoderDiagnostics`,e.DisplayWordTimings=`DisplayWordTimings`,e.DisplayWords=`DisplayWords`})(e.PhraseOption||={}),(function(e){e.Graph=`Graph`,e.Corrections=`Corrections`,e.Sentiment=`Sentiment`})(e.PhraseExtension||={}),(function(e){e.Simple=`Simple`,e.Detailed=`Detailed`})(e.OutputFormat||={}),(function(e){e.None=`None`,e.Always=`Always`})(e.TentativePhraseResultsOption||={})})),_r=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechContext=void 0;var t=W(),n=gr();e.SpeechContext=class{constructor(e){this.privContext={},this.privDynamicGrammar=e}getContext(){return this.privContext}setPronunciationAssessmentParams(e,r=!1){this.privContext.phraseDetection===void 0&&(this.privContext.phraseDetection={enrichment:{pronunciationAssessment:{}}}),this.privContext.phraseDetection.enrichment===void 0&&(this.privContext.phraseDetection.enrichment={pronunciationAssessment:{}}),this.privContext.phraseDetection.enrichment.pronunciationAssessment=JSON.parse(e)||{},r&&(this.privContext.phraseDetection.mode=t.RecognitionMode.Conversation),this.setWordLevelTimings(),this.privContext.phraseOutput.detailed.options.push(n.PhraseOption.PronunciationAssessment),this.privContext.phraseOutput.detailed.options.indexOf(n.PhraseOption.SNR)===-1&&this.privContext.phraseOutput.detailed.options.push(n.PhraseOption.SNR)}setDetailedOutputFormat(){this.privContext.phraseOutput===void 0&&(this.privContext.phraseOutput={detailed:{options:[]}}),this.privContext.phraseOutput.detailed===void 0&&(this.privContext.phraseOutput.detailed={options:[]}),this.privContext.phraseOutput.format=n.OutputFormat.Detailed}setWordLevelTimings(){this.privContext.phraseOutput===void 0&&(this.privContext.phraseOutput={detailed:{options:[]}}),this.privContext.phraseOutput.detailed===void 0&&(this.privContext.phraseOutput.detailed={options:[]}),this.privContext.phraseOutput.format=n.OutputFormat.Detailed,this.privContext.phraseOutput.detailed.options.indexOf(n.PhraseOption.WordTimings)===-1&&this.privContext.phraseOutput.detailed.options.push(n.PhraseOption.WordTimings)}setSpeakerDiarizationAudioOffsetMs(e){this.privContext.phraseDetection.speakerDiarization.audioOffsetMs=e}toJSON(){let e=this.privDynamicGrammar.generateGrammarObject();return this.privContext.dgi=e,JSON.stringify(this.privContext)}}})),vr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReconnectContinuationState=void 0;var t=A();e.ReconnectContinuationState=class{constructor(e=`1`){this.privDefaultStreamId=e}get defaultStreamId(){return this.privDefaultStreamId}get streamOffset(){return this.privStreamOffset}get hasPendingContinuation(){return this.privToken!==void 0||this.privServiceTag!==void 0||this.privStreamOffset!==void 0}reset(){this.privToken=void 0,this.privServiceTag=void 0,this.privStreamOffset=void 0}onTurnStart(e){this.privServiceTag=e??``}updateFromHeaders(e,n=0){if(!e)return;let r=t.HeaderNames.ContinuationToken.toLowerCase(),i=t.HeaderNames.ContinuationAudioStreamOffset.toLowerCase();for(let t in e){if(!t)continue;let a=t.toLowerCase(),o=e[t];if(a===r)this.privToken=o;else if(a===i){let e=parseInt(o,10);if(!isNaN(e)){let t=n+e;(this.privStreamOffset===void 0||t>this.privStreamOffset)&&(this.privStreamOffset=t)}}}}buildAudioStreamsMetadata(){let e={};return e[this.privDefaultStreamId]=null,{streams:e}}buildContinuationContext(){if(!this.hasPendingContinuation)return;let e={previousServiceTag:this.privServiceTag??``,token:this.privToken??``};return this.privStreamOffset!==void 0&&(e.audio={streams:{[this.privDefaultStreamId]:{offset:this.privStreamOffset}}}),e}}})),yr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SubstringMatchType=e.GroupType=void 0,(function(e){e.IntentText=`IntentText`,e.IntentEntity=`IntentEntity`,e.Generic=`Generic`,e.People=`People`,e.Place=`Place`,e.DynamicEntity=`DynamicEntity`})(e.GroupType||={}),(function(e){e.None=`None`,e.LeftRooted=`LeftRooted`,e.PartialName=`PartialName`,e.MiddleOfSentence=`MiddleOfSentence`})(e.SubstringMatchType||={})})),br=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DynamicGrammarBuilder=void 0;var t=yr();e.DynamicGrammarBuilder=class{constructor(){this.privWeight=1}addPhrase(e){this.privPhrases||=[],e instanceof Array?this.privPhrases=this.privPhrases.concat(e):this.privPhrases.push(e)}clearPhrases(){this.privPhrases=void 0}addReferenceGrammar(e){this.privGrammars||=[],e instanceof Array?this.privGrammars=this.privGrammars.concat(e):this.privGrammars.push(e)}clearGrammars(){this.privGrammars=void 0}setWeight(e){this.privWeight=e}generateGrammarObject(){if(this.privGrammars===void 0&&this.privPhrases===void 0)return;let e={};if(e.referenceGrammars=this.privGrammars,this.privPhrases!==void 0&&this.privPhrases.length!==0){let n=[];this.privPhrases.forEach(e=>{n.push({text:e})}),e.groups=[{type:t.GroupType.Generic,items:n}],e.bias=this.privWeight}return e}}})),xr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MessageDataStreamType=e.ActivityPayloadResponse=void 0,e.ActivityPayloadResponse=class e{constructor(e){this.privActivityResponse=JSON.parse(e)}static fromJSON(t){return new e(t)}get conversationId(){return this.privActivityResponse.conversationId}get messageDataStreamType(){return this.privActivityResponse.messageDataStreamType}get messagePayload(){return this.privActivityResponse.messagePayload}get version(){return this.privActivityResponse.version}},(function(e){e[e.None=0]=`None`,e[e.TextToSpeechAudio=1]=`TextToSpeechAudio`})(e.MessageDataStreamType||={})})),Sr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DialogServiceTurnState=void 0;var t=B(),n=V(),r=xr();e.DialogServiceTurnState=class{constructor(e,t){this.privRequestId=t,this.privIsCompleted=!1,this.privAudioStream=null,this.privTurnManager=e,this.resetTurnEndTimeout()}get audioStream(){return this.resetTurnEndTimeout(),this.privAudioStream}processActivityPayload(e,i){return e.messageDataStreamType===r.MessageDataStreamType.TextToSpeechAudio&&(this.privAudioStream=n.AudioOutputStream.createPullStream(),this.privAudioStream.format=i===void 0?t.AudioOutputFormatImpl.getDefaultOutputFormat():i),this.privAudioStream}endAudioStream(){this.privAudioStream!==null&&!this.privAudioStream.isClosed&&this.privAudioStream.close()}complete(){this.privTimeoutToken!==void 0&&clearTimeout(this.privTimeoutToken),this.endAudioStream()}resetTurnEndTimeout(){this.privTimeoutToken!==void 0&&clearTimeout(this.privTimeoutToken),this.privTimeoutToken=setTimeout(()=>{this.privTurnManager.CompleteTurn(this.privRequestId)},2e3)}}})),Cr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DialogServiceTurnStateManager=void 0;var t=T(),n=Sr();e.DialogServiceTurnStateManager=class{constructor(){this.privTurnMap=new Map}StartTurn(e){if(this.privTurnMap.has(e))throw new t.InvalidOperationError(`Service error: There is already a turn with id:`+e);let r=new n.DialogServiceTurnState(this,e);return this.privTurnMap.set(e,r),this.privTurnMap.get(e)}GetTurn(e){return this.privTurnMap.get(e)}CompleteTurn(e){if(!this.privTurnMap.has(e))throw new t.InvalidOperationError(`Service error: Received turn end for an unknown turn id:`+e);let n=this.privTurnMap.get(e);return n.complete(),this.privTurnMap.delete(e),n}}})),wr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.InvocationSource=void 0,(function(e){e.None=`None`,e.VoiceActivationWithKeyword=`VoiceActivationWithKeyword`})(e.InvocationSource||={})})),Tr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OnRejectAction=e.KeywordDetectionType=void 0,(function(e){e.StartTrigger=`StartTrigger`})(e.KeywordDetectionType||={}),(function(e){e.EndOfTurn=`EndOfTurn`,e.Continue=`Continue`})(e.OnRejectAction||={})})),Er=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DialogServiceAdapter=void 0;var t=X(),n=fe(),r=k(),i=B(),a=Y(),o=Cr(),s=Q(),c=xr(),l=wr(),u=Tr(),d=Z();e.DialogServiceAdapter=class extends s.ServiceRecognizerBase{constructor(e,t,n,i,a){super(e,t,n,i,a),this.privEvents=new r.EventSource,this.privDialogServiceConnector=a,this.receiveMessageOverride=()=>this.receiveDialogMessageOverride(),this.privTurnStateManager=new o.DialogServiceTurnStateManager,this.recognizeOverride=(e,t,n)=>this.listenOnce(e,t,n),this.postConnectImplOverride=e=>this.dialogConnectImpl(e),this.configConnectionOverride=e=>this.configConnection(e),this.disconnectOverride=()=>this.privDisconnect(),this.privDialogAudioSource=n,this.agentConfigSent=!1,this.privLastResult=null,this.connectionEvents.attach(e=>{e.name===`ConnectionClosedEvent`&&(this.terminateMessageLoop=!0)})}async sendMessage(e){let t=(0,r.createGuid)(),n=(0,r.createNoDashGuid)(),i={context:{interactionId:t},messagePayload:JSON.parse(e),version:.5},a=JSON.stringify(i);await(await this.fetchConnection()).send(new d.SpeechConnectionMessage(r.MessageType.Text,`agent`,n,`application/json`,a))}async privDisconnect(){await this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,a.CancellationReason.Error,a.CancellationErrorCode.NoError,`Disconnecting`),this.terminateMessageLoop=!0,this.agentConfigSent=!1}processTypeSpecificMessages(e){let t=new a.PropertyCollection;e.messageType===r.MessageType.Text&&t.setProperty(a.PropertyId.SpeechServiceResponse_JsonResult,e.textBody);let n,i;switch(e.path.toLowerCase()){case`speech.phrase`:let r=s.SimpleSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);if(this.privRequestSession.onPhraseRecognized(r.Offset+r.Duration),r.RecognitionStatus!==s.RecognitionStatus.TooManyRequests&&r.RecognitionStatus!==s.RecognitionStatus.Error){let e=this.fireEventForResult(r,t);if(this.privLastResult=e.result,this.privDialogServiceConnector.recognized)try{this.privDialogServiceConnector.recognized(this.privDialogServiceConnector,e)}catch{}}i=!0;break;case`speech.hypothesis`:let o=s.SpeechHypothesis.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);n=new a.SpeechRecognitionResult(this.privRequestSession.requestId,a.ResultReason.RecognizingSpeech,o.Text,o.Duration,o.Offset,o.Language,o.LanguageDetectionConfidence,void 0,void 0,o.asJson(),t),this.privRequestSession.onHypothesis(o.Offset);let c=new a.SpeechRecognitionEventArgs(n,o.Offset,this.privRequestSession.sessionId);if(this.privDialogServiceConnector.recognizing)try{this.privDialogServiceConnector.recognizing(this.privDialogServiceConnector,c)}catch{}i=!0;break;case`speech.keyword`:let l=s.SpeechKeyword.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);n=new a.SpeechRecognitionResult(this.privRequestSession.requestId,l.Status===`Accepted`?a.ResultReason.RecognizedKeyword:a.ResultReason.NoMatch,l.Text,l.Duration,l.Offset,void 0,void 0,void 0,void 0,l.asJson(),t),l.Status!==`Accepted`&&(this.privLastResult=n);let u=new a.SpeechRecognitionEventArgs(n,n.duration,n.resultId);if(this.privDialogServiceConnector.recognized)try{this.privDialogServiceConnector.recognized(this.privDialogServiceConnector,u)}catch{}i=!0;break;case`audio`:{let t=e.requestId.toUpperCase(),n=this.privTurnStateManager.GetTurn(t);try{e.binaryBody?n.audioStream.write(e.binaryBody):n.endAudioStream()}catch{}}i=!0;break;case`response`:this.handleResponseMessage(e),i=!0}let o=new r.Deferred;return o.resolve(i),o.promise}async cancelRecognition(e,t,n,r,i){if(this.terminateMessageLoop=!0,this.privRequestSession.isRecognizing&&await this.privRequestSession.onStopRecognizing(),this.privDialogServiceConnector.canceled){let t=new a.PropertyCollection;t.setProperty(s.CancellationErrorCodePropertyName,a.CancellationErrorCode[r]);let o=new a.SpeechRecognitionCanceledEventArgs(n,i,r,void 0,e);try{this.privDialogServiceConnector.canceled(this.privDialogServiceConnector,o)}catch{}if(this.privSuccessCallback){let e=new a.SpeechRecognitionResult(void 0,a.ResultReason.Canceled,void 0,void 0,void 0,void 0,void 0,void 0,i,void 0,t);try{this.privSuccessCallback(e),this.privSuccessCallback=void 0}catch{}}}}async listenOnce(e,n,r){this.privRecognizerConfig.recognitionMode=e,this.privSuccessCallback=n,this.privErrorCallback=r,this.privRequestSession.startNewRecognition(),this.privRequestSession.listenForServiceTelemetry(this.privDialogAudioSource.events),this.privRecognizerConfig.parameters.setProperty(a.PropertyId.Speech_SessionId,this.privRequestSession.sessionId);let i=this.connectImpl(),o=this.sendPreAudioMessages(),s=await this.privDialogAudioSource.attach(this.privRequestSession.audioNodeId),c=await this.privDialogAudioSource.format,l=await this.privDialogAudioSource.deviceInfo,u=new t.ReplayableAudioNode(s,c.avgBytesPerSec);await this.privRequestSession.onAudioSourceAttachCompleted(u,!1),this.privRecognizerConfig.SpeechServiceConfig.Context.audio={source:l};try{await i,await o}catch(e){return await this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,a.CancellationReason.Error,a.CancellationErrorCode.ConnectionFailure,e),Promise.resolve()}let d=new a.SessionEventArgs(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,d),this.sendAudio(u).then(()=>{},async e=>{await this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,a.CancellationReason.Error,a.CancellationErrorCode.RuntimeError,e)})}dialogConnectImpl(e){return this.privConnectionLoop=this.startMessageLoop(),e}receiveDialogMessageOverride(){let e=new r.Deferred,t=async()=>{try{let n=this.isDisposed(),i=!this.isDisposed()&&this.terminateMessageLoop;if(n||i){e.resolve(void 0);return}let o=await(await this.fetchConnection()).read();if(!o)return t();let c=d.SpeechConnectionMessage.fromConnectionMessage(o);switch(c.path.toLowerCase()){case`turn.start`:{let e=c.requestId.toUpperCase();e===this.privRequestSession.requestId.toUpperCase()?this.privRequestSession.onServiceTurnStartResponse():this.privTurnStateManager.StartTurn(e)}break;case`speech.startdetected`:let e=s.SpeechDetected.fromJSON(c.textBody,this.privRequestSession.currentTurnAudioOffset),t=new a.RecognitionEventArgs(e.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechStartDetected&&this.privRecognizer.speechStartDetected(this.privRecognizer,t);break;case`speech.enddetected`:let n;n=c.textBody.length>0?c.textBody:`{ Offset: 0 }`;let i=s.SpeechDetected.fromJSON(n,this.privRequestSession.currentTurnAudioOffset);this.privRequestSession.onServiceRecognized(i.Offset);let o=new a.RecognitionEventArgs(i.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechEndDetected&&this.privRecognizer.speechEndDetected(this.privRecognizer,o);break;case`turn.end`:{let e=c.requestId.toUpperCase();if(e!==this.privRequestSession.requestId.toUpperCase())this.privTurnStateManager.CompleteTurn(e);else{let e=new a.SessionEventArgs(this.privRequestSession.sessionId);if(await this.privRequestSession.onServiceTurnEndResponse(!1),(!this.privRecognizerConfig.isContinuousRecognition||this.privRequestSession.isSpeechEnded||!this.privRequestSession.isRecognizing)&&this.privRecognizer.sessionStopped&&this.privRecognizer.sessionStopped(this.privRecognizer,e),this.privSuccessCallback&&this.privLastResult){try{this.privSuccessCallback(this.privLastResult),this.privLastResult=null}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}}break;default:try{await this.processTypeSpecificMessages(c)||this.serviceEvents&&this.serviceEvents.onEvent(new r.ServiceEvent(c.path.toLowerCase(),c.textBody))}catch{}}return t()}catch{this.terminateMessageLoop=!0,e.resolve()}};return t().catch(e=>{r.Events.instance.onEvent(new r.BackgroundEvent(e))}),e.promise}async startMessageLoop(){this.terminateMessageLoop=!1;try{await this.receiveDialogMessageOverride()}catch(e){await this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,a.CancellationReason.Error,a.CancellationErrorCode.RuntimeError,e)}return Promise.resolve()}async configConnection(e){return this.terminateMessageLoop?(this.terminateMessageLoop=!1,Promise.reject(`Connection to service terminated.`)):(await this.sendSpeechServiceConfig(e,this.privRequestSession,this.privRecognizerConfig.SpeechServiceConfig.serialize()),await this.sendAgentConfig(e),e)}async sendPreAudioMessages(){let e=await this.fetchConnection();this.addKeywordContextData(),await this.sendSpeechContext(e,!0),await this.sendAgentContext(e),await this.sendWaveHeader(e)}sendAgentConfig(e){if(this.agentConfig&&!this.agentConfigSent){if(this.privRecognizerConfig.parameters.getProperty(a.PropertyId.Conversation_DialogType)===a.DialogServiceConfig.DialogTypes.CustomCommands){let e=this.agentConfig.get();e.botInfo.commandsCulture=this.privRecognizerConfig.parameters.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage,`en-us`),this.agentConfig.set(e)}this.onEvent(new n.SendingAgentContextMessageEvent(this.agentConfig));let t=this.agentConfig.toJsonString();return this.agentConfigSent=!0,e.send(new d.SpeechConnectionMessage(r.MessageType.Text,`agent.config`,this.privRequestSession.requestId,`application/json`,t))}}sendAgentContext(e){let t=(0,r.createGuid)(),n=this.privDialogServiceConnector.properties.getProperty(a.PropertyId.Conversation_Speech_Activity_Template),i=JSON.stringify({channelData:``,context:{interactionId:t},messagePayload:n,version:.5});return e.send(new d.SpeechConnectionMessage(r.MessageType.Text,`speech.agent.context`,this.privRequestSession.requestId,`application/json`,i))}fireEventForResult(e,t){let n=s.EnumTranslation.implTranslateRecognitionResult(e.RecognitionStatus),r=new a.SpeechRecognitionResult(this.privRequestSession.requestId,n,e.DisplayText,e.Duration,e.Offset,e.Language,e.LanguageDetectionConfidence,void 0,void 0,e.asJson(),t);return new a.SpeechRecognitionEventArgs(r,e.Offset,this.privRequestSession.sessionId)}handleResponseMessage(e){let t=JSON.parse(e.textBody);switch(t.messageType.toLowerCase()){case`message`:let n=e.requestId.toUpperCase(),o=c.ActivityPayloadResponse.fromJSON(e.textBody),s=this.privTurnStateManager.GetTurn(n);if(o.conversationId){let e=this.agentConfig.get();e.botInfo.conversationId=o.conversationId,this.agentConfig.set(e)}let l=s.processActivityPayload(o,i.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(this.privDialogServiceConnector.properties.getProperty(a.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0))),u=new a.ActivityReceivedEventArgs(o.messagePayload,l);if(this.privDialogServiceConnector.activityReceived)try{this.privDialogServiceConnector.activityReceived(this.privDialogServiceConnector,u)}catch{}break;case`messagestatus`:if(this.privDialogServiceConnector.turnStatusReceived)try{this.privDialogServiceConnector.turnStatusReceived(this.privDialogServiceConnector,new a.TurnStatusReceivedEventArgs(e.textBody))}catch{}break;default:r.Events.instance.onEvent(new r.BackgroundEvent(`Unexpected response of type ${t.messageType}. Ignoring.`))}}onEvent(e){this.privEvents.onEvent(e),r.Events.instance.onEvent(e)}addKeywordContextData(){let e=this.privRecognizerConfig.parameters.getProperty(`SPEECH-KeywordsToDetect`);if(e===void 0)return;let t=this.privRecognizerConfig.parameters.getProperty(`SPEECH-KeywordsToDetect-Offsets`),n=this.privRecognizerConfig.parameters.getProperty(`SPEECH-KeywordsToDetect-Durations`),r=e.split(`;`),i=t===void 0?[]:t.split(`;`),a=n===void 0?[]:n.split(`;`),o=[];for(let e=0;e<r.length;e++){let t={text:r[e]};e<i.length&&(t.startOffset=Number(i[e])),e<a.length&&(t.duration=Number(a[e])),o.push(t)}this.speechContext.getContext().invocationSource=l.InvocationSource.VoiceActivationWithKeyword,this.speechContext.getContext().keywordDetection=[{clientDetectedKeywords:o,onReject:{action:u.OnRejectAction.EndOfTurn},type:u.KeywordDetectionType.StartTrigger}]}}})),Dr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AgentConfig=void 0,e.AgentConfig=class{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}})),Or=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ConversationConnectionConfig=void 0;var t=kn(),n=class e extends t.RestConfigBase{static get defaultLanguageCode(){return e.privDefaultLanguageCode}static get transcriptionEventKeys(){return e.privTranscriptionEventKeys}};e.ConversationConnectionConfig=n,n.privDefaultLanguageCode=`en-US`,n.privTranscriptionEventKeys=[`iCalUid`,`callId`,`organizer`,`FLAC`,`MTUri`,`DifferentiateGuestSpeakers`,`audiorecording`,`Threadid`,`OrganizerMri`,`OrganizerTenantId`,`UserToken`]})),kr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TranscriberRecognizer=void 0;var t=k(),n=F(),r=Y(),i=Q(),a=W();e.TranscriberRecognizer=class extends r.Recognizer{constructor(e,t){let a=e;n.Contracts.throwIfNull(a,`speechTranslationConfig`);let o=t;n.Contracts.throwIfNull(o,`audioConfigImpl`),n.Contracts.throwIfNullOrWhitespace(a.speechRecognitionLanguage,r.PropertyId[r.PropertyId.SpeechServiceConnection_RecoLanguage]),super(t,a.properties,new i.TranscriberConnectionFactory),this.privDisposedRecognizer=!1}get speechRecognitionLanguage(){return n.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(r.PropertyId.SpeechServiceConnection_RecoLanguage)}get properties(){return this.privProperties}get authorizationToken(){return this.properties.getProperty(r.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){n.Contracts.throwIfNullOrWhitespace(e,`token`),this.properties.setProperty(r.PropertyId.SpeechServiceAuthorization_Token,e)}set meeting(e){n.Contracts.throwIfNullOrUndefined(e,`Meeting`),this.privMeeting=e}getMeetingInfo(){return n.Contracts.throwIfNullOrUndefined(this.privMeeting,`Meeting`),this.privMeeting.meetingInfo}startContinuousRecognitionAsync(e,n){(0,t.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(a.RecognitionMode.Conversation),e,n)}stopContinuousRecognitionAsync(e,n){(0,t.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(),e,n)}async close(){this.privDisposedRecognizer||await this.dispose(!0)}async pushMeetingEvent(e,t){let r=this.privReco;n.Contracts.throwIfNullOrUndefined(r,`serviceRecognizer`),await r.sendMeetingSpeechEventAsync(e,t)}async enforceAudioGating(){let e=(await this.audioConfig.format).channels;if(e===1){if(this.properties.getProperty(`f0f5debc-f8c9-4892-ac4b-90a7ab359fd2`,`false`).toLowerCase()!==`true`)throw Error(`Single channel audio configuration for MeetingTranscriber is currently under private preview, please contact diarizationrequest@microsoft.com for more details`)}else if(e!==8)throw Error(`Unsupported audio configuration: Detected ${e}-channel audio`)}connectMeetingCallbacks(e){this.canceled=(t,n)=>{e.canceled&&e.canceled(e,n)},this.recognizing=(t,n)=>{e.transcribing&&e.transcribing(e,n)},this.recognized=(t,n)=>{e.transcribed&&e.transcribed(e,n)},this.sessionStarted=(t,n)=>{e.sessionStarted&&e.sessionStarted(e,n)},this.sessionStopped=(t,n)=>{e.sessionStopped&&e.sessionStopped(e,n)}}disconnectCallbacks(){this.canceled=void 0,this.recognizing=void 0,this.recognized=void 0,this.sessionStarted=void 0,this.sessionStopped=void 0}async dispose(e){this.privDisposedRecognizer||(e&&(this.privDisposedRecognizer=!0,await this.implRecognizerStop()),await super.dispose(e))}createRecognizerConfig(e){return new i.RecognizerConfig(e,this.properties)}createServiceRecognizer(e,t,n,r){let a=n;return new i.TranscriptionServiceRecognizer(e,t,a,r,this)}}})),Ar=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.InternalParticipants=void 0,e.InternalParticipants=class{constructor(e=[]){this.participants=e}addOrUpdateParticipant(e){if(e===void 0)return;let t=this.getParticipantIndex(e.id);return t>-1?this.participants.splice(t,1,e):this.participants.push(e),this.getParticipant(e.id)}getParticipantIndex(e){return this.participants.findIndex(t=>t.id===e)}getParticipant(e){return this.participants.find(t=>t.id===e)}deleteParticipant(e){this.participants=this.participants.filter(t=>t.id!==e)}}})),jr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.InternalParticipants=e.TranscriberRecognizer=e.ConversationConnectionConfig=void 0;var t=Or();Object.defineProperty(e,"ConversationConnectionConfig",{enumerable:!0,get:function(){return t.ConversationConnectionConfig}});var n=kr();Object.defineProperty(e,"TranscriberRecognizer",{enumerable:!0,get:function(){return n.TranscriberRecognizer}});var r=Ar();Object.defineProperty(e,"InternalParticipants",{enumerable:!0,get:function(){return r.InternalParticipants}})})),Mr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesisAudioMetadata=e.MetadataType=void 0,(function(e){e.WordBoundary=`WordBoundary`,e.Bookmark=`Bookmark`,e.Viseme=`Viseme`,e.SentenceBoundary=`SentenceBoundary`,e.SessionEnd=`SessionEnd`,e.AvatarSignal=`TalkingAvatarSignal`})(e.MetadataType||={}),e.SynthesisAudioMetadata=class e{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(t){return new e(t)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}})),Nr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesisStartedEvent=e.ConnectingToSynthesisServiceEvent=e.SynthesisTriggeredEvent=e.SpeechSynthesisEvent=void 0;var t=k(),n=class extends t.PlatformEvent{constructor(e,n,r=t.EventType.Info){super(e,r),this.privRequestId=n}get requestId(){return this.privRequestId}};e.SpeechSynthesisEvent=n,e.SynthesisTriggeredEvent=class extends n{constructor(e,t,n){super(`SynthesisTriggeredEvent`,e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=n}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}},e.ConnectingToSynthesisServiceEvent=class extends n{constructor(e,t){super(`ConnectingToSynthesisServiceEvent`,e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}},e.SynthesisStartedEvent=class extends n{constructor(e,t){super(`SynthesisStartedEvent`,e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}})),Pr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesisTurn=void 0;var t=k(),n=V(),r=Y(),i=Mr(),a=Nr();e.SynthesisTurn=class e{constructor(){this.privIsDisposed=!1,this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!1,this.privBytesReceived=0,this.privInTurn=!1,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privSynthesisStartTime=0,this.privConnectionLatency=-1,this.privNetworkLatency=-1,this.privFirstByteLatency=-1,this.privServiceLatency=-1,this.privRequestId=(0,t.createNoDashGuid)(),this.privTurnDeferral=new t.Deferred,this.privTurnDeferral.resolve()}get requestId(){return this.privRequestId}get streamId(){return this.privStreamId}set streamId(e){this.privStreamId=e}get audioOutputFormat(){return this.privAudioOutputFormat}set audioOutputFormat(e){this.privAudioOutputFormat=e}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSynthesisEnded(){return this.privIsSynthesisEnded}get isSynthesizing(){return this.privIsSynthesizing}get currentTextOffset(){return this.privTextOffset}get currentSentenceOffset(){return this.privSentenceOffset}get bytesReceived(){return this.privBytesReceived}get audioDuration(){return this.privAudioDuration}get extraProperties(){if(this.privWebRTCSDP){let e=new r.PropertyCollection;return e.setProperty(r.PropertyId.TalkingAvatarService_WebRTC_SDP,this.privWebRTCSDP),e}}async getAllReceivedAudio(){return this.privReceivedAudio?Promise.resolve(this.privReceivedAudio):this.privIsSynthesisEnded?(await this.readAllAudioFromStream(),Promise.resolve(this.privReceivedAudio)):null}async getAllReceivedAudioWithHeader(){if(this.privReceivedAudioWithHeader)return this.privReceivedAudioWithHeader;if(!this.privIsSynthesisEnded)return null;if(this.audioOutputFormat.hasHeader){let e=await this.getAllReceivedAudio();return this.privReceivedAudioWithHeader=this.audioOutputFormat.addHeader(e),this.privReceivedAudioWithHeader}return this.getAllReceivedAudio()}startNewSynthesis(e,t,r,i){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=r,this.privAudioOutputStream=new n.PullAudioOutputStreamImpl,this.privAudioOutputStream.format=this.privAudioOutputFormat,this.privReceivedAudio=null,this.privReceivedAudioWithHeader=null,this.privBytesReceived=0,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privPartialVisemeAnimation=``,this.privWebRTCSDP=``,this.privSynthesisStartTime=Date.now(),this.privConnectionLatency=-1,this.privNetworkLatency=-1,this.privFirstByteLatency=-1,this.privServiceLatency=-1,i!==void 0&&(this.privTurnAudioDestination=i,this.privTurnAudioDestination.format=this.privAudioOutputFormat),this.onEvent(new a.SynthesisTriggeredEvent(this.requestId,void 0,i===void 0?void 0:i.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new a.ConnectingToSynthesisServiceEvent(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.privConnectionLatency=Date.now()-this.privSynthesisStartTime,this.onEvent(new a.SynthesisStartedEvent(this.requestId,this.privAuthFetchEventId)),this.privBytesReceived=0;return}e===403&&this.onComplete()}onServiceResponseMessage(e){let t=JSON.parse(e);this.streamId=t.audio.streamId}onServiceTurnEndResponse(){this.privInTurn=!1,this.privTurnDeferral.resolve(),this.onComplete()}onServiceTurnStartResponse(e){this.privTurnDeferral&&this.privInTurn&&(this.privTurnDeferral.reject(`Another turn started before current completed.`),this.privTurnDeferral.promise.then().catch(()=>{})),this.privInTurn=!0,this.privTurnDeferral=new t.Deferred,this.privConnectionLatency<0&&(this.privConnectionLatency=0),this.privNetworkLatency=Date.now()-this.privSynthesisStartTime-this.privConnectionLatency;let n=JSON.parse(e);n.webrtc&&(this.privWebRTCSDP=n.webrtc.connectionString)}onAudioChunkReceived(e){this.isSynthesizing&&(this.privFirstByteLatency<0&&(this.privFirstByteLatency=Date.now()-this.privSynthesisStartTime,this.privNetworkLatency>=0&&(this.privServiceLatency=this.privFirstByteLatency-this.privConnectionLatency-this.privNetworkLatency)),this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength,this.privTurnAudioDestination!==void 0&&this.privTurnAudioDestination.write(e))}onTextBoundaryEvent(e){this.updateTextOffset(e.Data.text.Text,e.Type)}onVisemeMetadataReceived(e){e.Data.AnimationChunk!==void 0&&(this.privPartialVisemeAnimation+=e.Data.AnimationChunk)}onSessionEnd(e){this.privAudioDuration=e.Data.Offset}async constructSynthesisResult(){let e=Date.now()-this.privSynthesisStartTime,t=await this.getAllReceivedAudioWithHeader(),n=new r.PropertyCollection;return this.privWebRTCSDP&&n.setProperty(r.PropertyId.TalkingAvatarService_WebRTC_SDP,this.privWebRTCSDP),n.setProperty(r.PropertyId.SpeechServiceResponse_SynthesisFirstByteLatencyMs,String(Math.max(0,this.privFirstByteLatency))),n.setProperty(r.PropertyId.SpeechServiceResponse_SynthesisFinishLatencyMs,String(e)),n.setProperty(r.PropertyId.SpeechServiceResponse_SynthesisConnectionLatencyMs,String(Math.max(0,this.privConnectionLatency))),n.setProperty(r.PropertyId.SpeechServiceResponse_SynthesisNetworkLatencyMs,String(Math.max(0,this.privNetworkLatency))),n.setProperty(r.PropertyId.SpeechServiceResponse_SynthesisServiceLatencyMs,String(Math.max(0,this.privServiceLatency))),new r.SpeechSynthesisResult(this.requestId,r.ResultReason.SynthesizingAudioCompleted,t,void 0,n,this.audioDuration)}dispose(){this.privIsDisposed||=!0}onStopSynthesizing(){this.onComplete()}getAndClearVisemeAnimation(){let e=this.privPartialVisemeAnimation;return this.privPartialVisemeAnimation=``,e}onEvent(e){t.Events.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]===`<`&&e[e.length-1]===`>`}updateTextOffset(t,n){n===i.MetadataType.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(t,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+t.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!e.isXmlTag(t)&&this.updateTextOffset(t,n))):(this.privSentenceOffset=this.privRawText.indexOf(t,this.privNextSearchSentenceIndex),this.privSentenceOffset>=0&&(this.privNextSearchSentenceIndex=this.privSentenceOffset+t.length,this.privIsSSML&&this.withinXmlTag(this.privSentenceOffset)&&!e.isXmlTag(t)&&this.updateTextOffset(t,n)))}onComplete(){this.privIsSynthesizing&&(this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!0,this.privAudioOutputStream.close(),this.privInTurn=!1,this.privTurnAudioDestination!==void 0&&(this.privTurnAudioDestination.close(),this.privTurnAudioDestination=void 0))}async readAllAudioFromStream(){if(this.privIsSynthesisEnded){this.privReceivedAudio=new ArrayBuffer(this.bytesReceived);try{await this.privAudioOutputStream.read(this.privReceivedAudio)}catch{this.privReceivedAudio=new ArrayBuffer(0)}}}withinXmlTag(e){return this.privRawText.indexOf(`<`,e+1)>this.privRawText.indexOf(`>`,e+1)}}})),Fr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesisAdapterBase=void 0;var t=k(),n=Y(),r=Q(),i=Z(),a=class{constructor(e,i,a,o){if(this.speakOverride=void 0,this.receiveMessageOverride=void 0,this.connectImplOverride=void 0,this.configConnectionOverride=void 0,this.privConnectionConfigurationPromise=void 0,!e)throw new t.ArgumentNullError(`authentication`);if(!i)throw new t.ArgumentNullError(`connectionFactory`);if(!a)throw new t.ArgumentNullError(`synthesizerConfig`);this.privAuthentication=e,this.privConnectionFactory=i,this.privSynthesizerConfig=a,this.privIsDisposed=!1,this.privSessionAudioDestination=o,this.privSynthesisTurn=new r.SynthesisTurn,this.privConnectionEvents=new t.EventSource,this.privServiceEvents=new t.EventSource,this.privSynthesisContext=new r.SynthesisContext,this.privAgentConfig=new r.AgentConfig,this.connectionEvents.attach(e=>{if(e.name===`ConnectionClosedEvent`){let t=e;t.statusCode!==1e3&&this.cancelSynthesisLocal(n.CancellationReason.Error,t.statusCode===1007?n.CancellationErrorCode.BadRequestParameters:n.CancellationErrorCode.ConnectionFailure,`${t.reason} websocket error code: ${t.statusCode}`)}})}get synthesizerConfig(){return this.privSynthesizerConfig}get synthesisContext(){return this.privSynthesisContext}get agentConfig(){return this.privAgentConfig}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}set audioOutputFormat(e){this.privAudioOutputFormat=e,this.privSynthesisTurn.audioOutputFormat=e,this.privSessionAudioDestination!==void 0&&(this.privSessionAudioDestination.format=e),this.synthesisContext!==void 0&&(this.synthesisContext.audioOutputFormat=e)}isDisposed(){return this.privIsDisposed}async dispose(e){if(this.privIsDisposed=!0,this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.close(),this.privConnectionConfigurationPromise!==void 0)try{await(await this.privConnectionConfigurationPromise).dispose(e)}catch{}}async connect(){await this.connectImpl()}async sendNetworkMessage(e,n){let r=typeof n==`string`?t.MessageType.Text:t.MessageType.Binary,a=typeof n==`string`?`application/json`:``;return(await this.fetchConnection()).send(new i.SpeechConnectionMessage(r,e,this.privSynthesisTurn.requestId,a,n))}async Speak(e,t,r,i,a,o){let s;if(s=t?e:this.privSynthesizer.buildSsml(e),this.speakOverride!==void 0)return this.speakOverride(s,r,i,a);this.privSuccessCallback=i,this.privErrorCallback=a,this.privSynthesisTurn.startNewSynthesis(r,e,t,o);try{let e=await this.fetchConnection();await this.sendSynthesisContext(e),await this.sendSsmlMessage(e,s,r),this.onSynthesisStarted(r),this.receiveMessage()}catch(e){return this.cancelSynthesisLocal(n.CancellationReason.Error,n.CancellationErrorCode.ConnectionFailure,e),Promise.reject(e)}}async stopSpeaking(){return(await this.fetchConnection()).send(new i.SpeechConnectionMessage(t.MessageType.Text,`synthesis.control`,this.privSynthesisTurn.requestId,`application/json`,JSON.stringify({action:`stop`})))}async SpeakStream(e,t,r,i,a){this.privSuccessCallback=r,this.privErrorCallback=i,this.privSynthesisTurn.startNewSynthesis(t,``,!1,a);try{let r=await this.fetchConnection();await this.sendStreamingSynthesisContext(r,e,t),this.onSynthesisStarted(t),e.onTextPiece=e=>{this.sendTextPiece(r,e,t).catch(e=>{this.cancelSynthesisLocal(n.CancellationReason.Error,n.CancellationErrorCode.ConnectionFailure,e)})},e.onClose=()=>{this.sendTextStreamEnd(r,t).catch(e=>{this.cancelSynthesisLocal(n.CancellationReason.Error,n.CancellationErrorCode.ConnectionFailure,e)})},this.receiveMessage()}catch(e){return this.cancelSynthesisLocal(n.CancellationReason.Error,n.CancellationErrorCode.ConnectionFailure,e),Promise.reject(e)}}cancelSynthesis(e,t,i,a){let o=new n.PropertyCollection;o.setProperty(r.CancellationErrorCodePropertyName,n.CancellationErrorCode[i]);let s=new n.SpeechSynthesisResult(e,n.ResultReason.Canceled,void 0,a,o);if(this.onSynthesisCancelled(s),this.privSuccessCallback)try{this.privSuccessCallback(s)}catch{}}cancelSynthesisLocal(e,t,n){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,n))}processTypeSpecificMessages(e){return!0}async receiveMessage(){try{let e=await(await this.fetchConnection()).read();if(this.receiveMessageOverride!==void 0)return this.receiveMessageOverride();if(this.privIsDisposed)return;if(!e)return this.privSynthesisTurn.isSynthesizing?this.receiveMessage():void 0;let a=i.SpeechConnectionMessage.fromConnectionMessage(e);if(a.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(a.path.toLowerCase()){case`turn.start`:this.privSynthesisTurn.onServiceTurnStartResponse(a.textBody);break;case`response`:this.privSynthesisTurn.onServiceResponseMessage(a.textBody);break;case`audio`:this.privSynthesisTurn.streamId.toLowerCase()===a.streamId.toLowerCase()&&a.binaryBody&&(this.privSynthesisTurn.onAudioChunkReceived(a.binaryBody),this.onSynthesizing(a.binaryBody),this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(a.binaryBody));break;case`audio.metadata`:let e=r.SynthesisAudioMetadata.fromJSON(a.textBody).Metadata;for(let t of e)switch(t.Type){case r.MetadataType.WordBoundary:case r.MetadataType.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(t);let e=new n.SpeechSynthesisWordBoundaryEventArgs(t.Data.Offset,t.Data.Duration,t.Data.text.Text,t.Data.text.Length,t.Type===r.MetadataType.WordBoundary?this.privSynthesisTurn.currentTextOffset:this.privSynthesisTurn.currentSentenceOffset,t.Data.text.BoundaryType);this.onWordBoundary(e);break;case r.MetadataType.Bookmark:let i=new n.SpeechSynthesisBookmarkEventArgs(t.Data.Offset,t.Data.Bookmark);this.onBookmarkReached(i);break;case r.MetadataType.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(t),t.Data.IsLastAnimation){let e=new n.SpeechSynthesisVisemeEventArgs(t.Data.Offset,t.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());this.onVisemeReceived(e)}break;case r.MetadataType.AvatarSignal:this.onAvatarEvent(t);break;case r.MetadataType.SessionEnd:this.privSynthesisTurn.onSessionEnd(t)}break;case`turn.end`:this.privSynthesisTurn.onServiceTurnEndResponse();let i;try{i=await this.privSynthesisTurn.constructSynthesisResult(),this.onSynthesisCompleted(i),this.privSuccessCallback&&this.privSuccessCallback(i)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}break;default:this.processTypeSpecificMessages(a)||this.privServiceEvents&&this.serviceEvents.onEvent(new t.ServiceEvent(a.path.toLowerCase(),a.textBody))}return this.receiveMessage()}catch{}}sendSynthesisContext(e){this.setSynthesisContextSynthesisSection();let n=this.synthesisContext.toJSON();if(n)return e.send(new i.SpeechConnectionMessage(t.MessageType.Text,`synthesis.context`,this.privSynthesisTurn.requestId,`application/json`,n))}setSpeechConfigSynthesisSection(){}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(e=>e.state()===t.ConnectionState.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()));this.privAuthFetchEventId=(0,t.createNoDashGuid)(),this.privConnectionId=(0,t.createNoDashGuid)(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);let r=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=r.then(async t=>{this.privSynthesisTurn.onAuthCompleted(!1);let r=await this.privConnectionFactory.create(this.privSynthesizerConfig,t,this.privConnectionId);r.events.attach(e=>{this.connectionEvents.onEvent(e)});let i=await r.open();return i.statusCode===200?(this.privSynthesisTurn.onConnectionEstablishCompleted(i.statusCode),Promise.resolve(r)):i.statusCode===403&&!e?this.connectImpl(!0):(this.privSynthesisTurn.onConnectionEstablishCompleted(i.statusCode),Promise.reject(`Unable to contact server. StatusCode: ${i.statusCode},
|
|
22
|
+
${this.privSynthesizerConfig.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Url)} Reason: ${i.reason}`))},e=>{throw this.privSynthesisTurn.onAuthCompleted(!0),Error(e)}),this.privConnectionPromise.catch(()=>{}),this.privConnectionPromise}sendSpeechServiceConfig(e,n){if(n)return e.send(new i.SpeechConnectionMessage(t.MessageType.Text,`speech.config`,this.privSynthesisTurn.requestId,`application/json`,n))}sendSsmlMessage(e,n,r){return e.send(new i.SpeechConnectionMessage(t.MessageType.Text,`ssml`,r,`application/ssml+xml`,n))}async sendStreamingSynthesisContext(e,r,a){this.setSynthesisContextSynthesisSection();let o={bidirectionalStreamingMode:!0},s=this.privSynthesizerConfig.parameters.getProperty(n.PropertyId.SpeechServiceConnection_SynthVoice,``),c=this.privSynthesizerConfig.parameters.getProperty(n.PropertyId.SpeechServiceConnection_SynthLanguage,`en-US`);s&&(o.voiceName=s),o.language=c;let l=r.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Pitch,void 0),u=r.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Rate,void 0),d=r.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Volume,void 0),f=r.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Style,void 0),p=r.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Temperature,void 0),m=r.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_CustomLexiconUrl,void 0),h=r.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_PreferLocales,void 0);l!==void 0&&(o.pitch=l),u!==void 0&&(o.rate=u),d!==void 0&&(o.volume=d),f!==void 0&&(o.style=f),p!==void 0&&(o.temperature=p),m!==void 0&&(o.customLexiconUrl=m),h!==void 0&&(o.preferLocales=h);let g=this.privSynthesisContext.getSection(`synthesis`)??{};this.privSynthesisContext.setSection(`synthesis`,{...g,input:o});let _=this.privSynthesisContext.toJSON();if(_)return e.send(new i.SpeechConnectionMessage(t.MessageType.Text,`synthesis.context`,a,`application/json`,_))}async sendTextPiece(e,n,r){return e.send(new i.SpeechConnectionMessage(t.MessageType.Text,`text.piece`,r,`text/plain`,n))}async sendTextStreamEnd(e,n){return e.send(new i.SpeechConnectionMessage(t.MessageType.Text,`text.end`,n,`text/plain`,``))}async fetchConnection(){return this.privConnectionConfigurationPromise===void 0?(this.privConnectionConfigurationPromise=this.configureConnection(),await this.privConnectionConfigurationPromise):this.privConnectionConfigurationPromise.then(e=>e.state()===t.ConnectionState.Disconnected?(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.fetchConnection()):this.privConnectionConfigurationPromise,()=>(this.privConnectionId=null,this.privConnectionConfigurationPromise=void 0,this.fetchConnection()))}async configureConnection(){let e=await this.connectImpl();return this.configConnectionOverride===void 0?(this.setSpeechConfigSynthesisSection(),await this.sendSpeechServiceConfig(e,this.privSynthesizerConfig.SpeechServiceConfig.serialize()),e):this.configConnectionOverride(e)}onAvatarEvent(e){}onSynthesisStarted(e){}onSynthesizing(e){}onSynthesisCancelled(e){}onSynthesisCompleted(e){}onWordBoundary(e){}onVisemeReceived(e){}onBookmarkReached(e){}};e.SynthesisAdapterBase=a,a.telemetryDataEnabled=!0})),Ir=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AvatarSynthesisAdapter=void 0;var t=Y(),n=Q();e.AvatarSynthesisAdapter=class extends n.SynthesisAdapterBase{constructor(e,t,n,r,i){super(e,t,n,void 0),this.privAvatarSynthesizer=r,this.privSynthesizer=r,this.privAvatarConfig=i}setSynthesisContextSynthesisSection(){this.privSynthesisContext.setSynthesisSection(void 0)}setSpeechConfigSynthesisSection(){let e={background:{color:this.privAvatarConfig.backgroundColor,image:{url:this.privAvatarConfig.backgroundImage?.toString()}},character:this.privAvatarConfig.character,customized:this.privAvatarConfig.customized,photoAvatarBaseModel:this.privAvatarConfig.photoAvatarBaseModel,style:this.privAvatarConfig.style,useBuiltInVoice:this.privAvatarConfig.useBuiltInVoice};this.privAvatarConfig.scene&&(e.scene={amplitude:this.privAvatarConfig.scene.amplitude,positionX:this.privAvatarConfig.scene.positionX,positionY:this.privAvatarConfig.scene.positionY,rotationX:this.privAvatarConfig.scene.rotationX,rotationY:this.privAvatarConfig.scene.rotationY,rotationZ:this.privAvatarConfig.scene.rotationZ,zoom:this.privAvatarConfig.scene.zoom}),this.privSynthesizerConfig.synthesisVideoSection={format:{bitrate:this.privAvatarConfig.videoFormat?.bitrate,codec:this.privAvatarConfig.videoFormat?.codec,crop:{bottomRight:{x:this.privAvatarConfig.videoFormat?.cropRange?.bottomRight?.x,y:this.privAvatarConfig.videoFormat?.cropRange?.bottomRight?.y},topLeft:{x:this.privAvatarConfig.videoFormat?.cropRange?.topLeft?.x,y:this.privAvatarConfig.videoFormat?.cropRange?.topLeft?.y}},resolution:{height:this.privAvatarConfig.videoFormat?.height,width:this.privAvatarConfig.videoFormat?.width}},protocol:{name:`WebRTC`,webrtcConfig:{clientDescription:btoa(this.privSynthesizerConfig.parameters.getProperty(t.PropertyId.TalkingAvatarService_WebRTC_SDP)),iceServers:this.privAvatarConfig.remoteIceServers??this.privAvatarSynthesizer.iceServers}},talkingAvatar:e}}onAvatarEvent(e){if(this.privAvatarSynthesizer.avatarEventReceived){let n=new t.AvatarEventArgs(e.Data.Offset,e.Data.Name);try{this.privAvatarSynthesizer.avatarEventReceived(this.privAvatarSynthesizer,n)}catch{}}}}})),Lr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpeechSynthesisAdapter=void 0;var t=Y(),n=Q();e.SpeechSynthesisAdapter=class extends n.SynthesisAdapterBase{constructor(e,t,n,r,i){super(e,t,n,i),this.privSpeechSynthesizer=r,this.privSynthesizer=r}setSynthesisContextSynthesisSection(){this.privSynthesisContext.setSynthesisSection(this.privSpeechSynthesizer)}onSynthesisStarted(e){let n=new t.SpeechSynthesisEventArgs(new t.SpeechSynthesisResult(e,t.ResultReason.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,n)}onSynthesizing(e){if(this.privSpeechSynthesizer.synthesizing)try{let n=this.privSynthesisTurn.audioOutputFormat.addHeader(e),r=new t.SpeechSynthesisEventArgs(new t.SpeechSynthesisResult(this.privSynthesisTurn.requestId,t.ResultReason.SynthesizingAudio,n));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,r)}catch{}}onSynthesisCancelled(e){if(this.privSpeechSynthesizer.SynthesisCanceled){let n=new t.SpeechSynthesisEventArgs(e);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,n)}catch{}}}onSynthesisCompleted(e){if(this.privSpeechSynthesizer.synthesisCompleted)try{this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer,new t.SpeechSynthesisEventArgs(e))}catch{}}onWordBoundary(e){if(this.privSpeechSynthesizer.wordBoundary)try{this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer,e)}catch{}}onVisemeReceived(e){if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,e)}catch{}}onBookmarkReached(e){if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,e)}catch{}}}})),Rr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesisRestAdapter=void 0;var t=X(),n=Y(),r=q(),i=A();e.SynthesisRestAdapter=class{constructor(e,i){let a=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Endpoint,void 0);if(this.privIsCustomEndpoint=!!a,!a){let t=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Region,`westus`),i=r.ConnectionFactoryBase.getHostSuffix(t);a=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Host,`https://${t}.tts.speech${i}`)}this.privEndpoint=a;let o=t.RestConfigBase.requestOptions;this.privRestAdapter=new t.RestMessageAdapter(o),this.privAuthentication=i}async getVoicesList(e){let n=await this.getVoicesListUri();this.privRestAdapter.setHeaders(i.HeaderNames.ConnectionId,e);let r=await this.privAuthentication.fetch(e);return this.privRestAdapter.setHeaders(r.headerName,r.token),this.privRestAdapter.request(t.RestRequestType.Get,n)}async getVoicesListUri(){if(this.privUri!==void 0)return this.privUri;let e=`/cognitiveservices/voices/list`,t=new URL(this.privEndpoint),n=t.pathname,i=n===``||n===`/`;if(this.privIsCustomEndpoint&&i){t.pathname=`/tts/cognitiveservices/websocket/v1`;let n=await r.ConnectionFactoryBase.getRedirectUrlFromEndpoint(t.toString(),!1),i=new URL(n);i.pathname=e,i.searchParams.delete(`GenerateRedirectResponse`),this.privUri=i.toString()}else i?(t.pathname=e,this.privUri=t.toString()):this.privUri=`${this.privEndpoint}${e}`;return this.privUri}}})),zr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesizerConfig=e.SynthesisServiceType=void 0;var t=Q(),n;(function(e){e[e.Standard=0]=`Standard`,e[e.Custom=1]=`Custom`})(n=e.SynthesisServiceType||={}),e.SynthesizerConfig=class{constructor(e,r){this.privSynthesisServiceType=n.Standard,this.avatarEnabled=!1,this.privSpeechServiceConfig=e||new t.SpeechServiceConfig(new t.Context(null)),this.privParameters=r}get parameters(){return this.privParameters}get synthesisServiceType(){return this.privSynthesisServiceType}set synthesisServiceType(e){this.privSynthesisServiceType=e}set synthesisVideoSection(e){this.privSpeechServiceConfig.Context.synthesis={video:e}}get SpeechServiceConfig(){return this.privSpeechServiceConfig}setContextFromJson(e){let t=JSON.parse(e);t.system&&(this.privSpeechServiceConfig.Context.system=t.system),t.os&&(this.privSpeechServiceConfig.Context.os=t.os),t.audio&&(this.privSpeechServiceConfig.Context.audio=t.audio),t.synthesis&&(this.privSpeechServiceConfig.Context.synthesis=t.synthesis)}}})),Br=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SynthesisContext=void 0;var t=Y();e.SynthesisContext=class{constructor(){this.privContext={}}setSection(e,t){this.privContext[e]=t}set audioOutputFormat(e){this.privAudioOutputFormat=e}toJSON(){return JSON.stringify(this.privContext)}getSection(e){return this.privContext[e]}setSynthesisSection(e){let t=this.buildSynthesisContext(e);this.setSection(`synthesis`,t)}buildSynthesisContext(e){return{audio:{metadataOptions:{bookmarkEnabled:!!e?.bookmarkReached,punctuationBoundaryEnabled:e?.properties.getProperty(t.PropertyId.SpeechServiceResponse_RequestPunctuationBoundary,!!e?.wordBoundary),sentenceBoundaryEnabled:e?.properties.getProperty(t.PropertyId.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!e?.visemeReceived,wordBoundaryEnabled:e?.properties.getProperty(t.PropertyId.SpeechServiceResponse_RequestWordBoundary,!!e?.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:e?.autoDetectSourceLanguage}}}}})),Vr=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.type=e.connectivity=e.Device=e.OS=e.System=e.Context=e.SpeechServiceConfig=void 0,e.SpeechServiceConfig=class{constructor(e){this.context=e}serialize(){return JSON.stringify(this,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let r=n===`SeparateChannelProcessing`?n:n&&n.charAt(0).toLowerCase()+n.substring(1);e[r]=t[n]}return e}return t})}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}},e.Context=class{constructor(e){this.system=new t,this.os=e}};var t=class{constructor(){this.name=`SpeechSDK`,this.version=`1.51.0`,this.build=`JavaScript`,this.lang=`JavaScript`}};e.System=t,e.OS=class{constructor(e,t,n){this.platform=e,this.name=t,this.version=n}},e.Device=class{constructor(e,t,n){this.manufacturer=e,this.model=t,this.version=n}},(function(e){e.Bluetooth=`Bluetooth`,e.Wired=`Wired`,e.WiFi=`WiFi`,e.Cellular=`Cellular`,e.InBuilt=`InBuilt`,e.Unknown=`Unknown`})(e.connectivity||={}),(function(e){e.Phone=`Phone`,e.Speaker=`Speaker`,e.Car=`Car`,e.Headset=`Headset`,e.Thermostat=`Thermostat`,e.Microphones=`Microphones`,e.Deskphone=`Deskphone`,e.RemoteControl=`RemoteControl`,e.Unknown=`Unknown`,e.File=`File`,e.Stream=`Stream`})(e.type||={})})),Q=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.AutoDetectSourceLanguagesOpenRangeOptionName=e.ForceDictationPropertyName=e.ServicePropertiesPropertyName=e.CancellationErrorCodePropertyName=e.OutputFormatPropertyName=e.SpeechSynthesisAdapter=e.AvatarSynthesisAdapter=void 0,n(M(),e),n(Fe(),e),n(j(),e),n(Ie(),e),n(Le(),e),n(N(),e),n(Un(),e),n(Wn(),e),n(Gn(),e),n(Kn(),e),n(qn(),e),n(Jn(),e),n(Yn(),e),n(Xn(),e),n(Qn(),e),n(bn(),e),n($n(),e),n(er(),e),n(tr(),e),n(nr(),e),n(rr(),e),n(ir(),e),n(ar(),e),n(or(),e),n(sr(),e),n(cr(),e),n(ur(),e),n(dr(),e),n(fr(),e),n(pr(),e),n(hr(),e),n(_r(),e),n(vr(),e),n(br(),e),n(Er(),e),n(Dr(),e),n(jr(),e),n(Mr(),e),n(Pr(),e),n(Fr(),e);var r=Ir();Object.defineProperty(e,"AvatarSynthesisAdapter",{enumerable:!0,get:function(){return r.AvatarSynthesisAdapter}});var i=Lr();Object.defineProperty(e,"SpeechSynthesisAdapter",{enumerable:!0,get:function(){return i.SpeechSynthesisAdapter}}),n(Rr(),e),n(zr(),e),n(Br(),e),n(Vr(),e),e.OutputFormatPropertyName=`OutputFormat`,e.CancellationErrorCodePropertyName=`CancellationErrorCode`,e.ServicePropertiesPropertyName=`ServiceProperties`,e.ForceDictationPropertyName=`ForceDictation`,e.AutoDetectSourceLanguagesOpenRangeOptionName=`UND`})),$=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),new(Q()).AgentConfig,n(Y(),e)}))(),Hr=class{region=``;sourceLanguage;targetLanguage;recognizer;authorizationManager;authorizationRefreshIntervalMs;authorizationRefreshTimer;stopPromise;constructor(e){if(!e||typeof e.sourceLanguage!=`string`||e.sourceLanguage.trim()===``)throw Error(`A sourceLanguage is required.`);this.authorizationManager=new l(e),this.authorizationRefreshIntervalMs=e.tokenLifetimeMs&&e.tokenLifetimeMs>0?e.tokenLifetimeMs:n,this.sourceLanguage=e.sourceLanguage,this.targetLanguage=e.targetLanguage??e.sourceLanguage}async start(){await this.registerBindings(document)}async registerBindings(e){let t=e.childNodes;for(let e=0;e<t.length;e++){if(!t[e])continue;let n=t[e];n.attributes&&(n.attributes.getNamedItem(`co-stt.start`)?await this.handleStartModifier(n,n.attributes.getNamedItem(`co-stt.start`)):n.attributes.getNamedItem(`co-stt.stop`)&&await this.handleStopModifier(n,n.attributes.getNamedItem(`co-stt.stop`))),n.childNodes.length>0&&await this.registerBindings(n)}}async createSpeechTranslationConfig(){let e=await this.authorizationManager.getAuthorization(),t=$.SpeechTranslationConfig.fromAuthorizationToken(e.token,e.region);return t.speechRecognitionLanguage=this.sourceLanguage,t.addTargetLanguage(this.targetLanguage),this.region=e.region,t}async handleStartModifier(e,t){e.addEventListener(`click`,async e=>{try{await this.stop();let e=await this.createSpeechTranslationConfig(),n=$.AudioConfig.fromDefaultMicrophoneInput();this.recognizer=new $.TranslationRecognizer(e,n),document.dispatchEvent(new CustomEvent(`COAzureSTTStartedRecording`,{}));let r={};this.recognizer.recognizing=(e,n)=>{let i=n.result;if(i&&i.reason===$.ResultReason.TranslatingSpeech){let e=i.translations.get(this.targetLanguage);r[`result_`+i.privOffset.toString()]=e;let n=Object.values(r).join(`. `),a=document.getElementById(t.value);a!==null&&(a instanceof HTMLInputElement?a.value=`${n} `:a.innerHTML=`${n} `)}},this.recognizer.startContinuousRecognitionAsync(()=>{this.scheduleAuthorizationRefresh()},e=>{c(e)&&this.authorizationManager.clearAuthorization(),this.dispatchError(e,`RECOGNITION_ERROR`),this.stop()})}catch(e){this.clearAuthorizationRefreshTimer(),c(e)&&this.authorizationManager.clearAuthorization(),this.dispatchError(e),await this.stop()}})}async handleStopModifier(e,t){e.addEventListener(`click`,async e=>{await this.stop()})}async stop(){if(this.stopPromise)return this.stopPromise;this.clearAuthorizationRefreshTimer();let e=this.recognizer;if(e)return this.recognizer=void 0,this.stopPromise=this.stopRecognizer(e).finally(()=>{this.stopPromise=void 0,document.dispatchEvent(new CustomEvent(`COAzureSTTStoppedRecording`,{}))}),this.stopPromise}scheduleAuthorizationRefresh(){this.clearAuthorizationRefreshTimer(),this.authorizationRefreshTimer=setTimeout(async()=>{if(this.recognizer)try{let e=await this.authorizationManager.refreshAuthorization();if(!this.recognizer)return;this.recognizer.authorizationToken=e.token,this.region=e.region,this.scheduleAuthorizationRefresh()}catch(e){this.dispatchError(e,`TOKEN_REFRESH_ERROR`),await this.stop()}},this.authorizationRefreshIntervalMs)}clearAuthorizationRefreshTimer(){this.authorizationRefreshTimer&&=(clearTimeout(this.authorizationRefreshTimer),void 0)}stopRecognizer(e){return new Promise(t=>{let n=!1,r=()=>{if(n){t();return}n=!0;try{e.close()}catch{}finally{t()}};try{e.stopContinuousRecognitionAsync(()=>{r()},()=>{r()})}catch{r()}})}dispatchError(e,t){let n=o(e);t&&!n.code&&(n.code=t),document.dispatchEvent(new CustomEvent(`COAzureSTTError`,{detail:{error:n}}))}},Ur=[`.`,`,`,`!`,`?`,`*`,`(`,`)`,`&`,`\\`,`/`,`^`,`[`,`]`,`<`,`>`,`:`],Wr=class{region=``;voice;rate;pitch;textToRead=``;wordBoundryList=[];clickedNode;highlightDiv;speechConfig;audioConfig;player;synthesizer;previousWordBoundary;originalHighlightDivInnerHTML=``;currentWord=``;currentOffset=0;wordBoundaryOffset=0;playbackTextOffsetBase;prevTextOffset=0;url=``;prefetchedAudio=new Map;prefetchPromises=new Map;activePrefetchedAudioUrl=``;playbackSegments=[];authorizationManager;stopPromise;playbackSessionId=0;highlightInterval;constructor(e){if(!e||typeof e.voice!=`string`||e.voice.trim()===``)throw Error(`A voice is required.`);this.authorizationManager=new l(e),this.voice=e.voice,this.rate=e.rate??0,this.pitch=e.pitch??0,this.url=e.url??``}async start(){await this.registerBindings(document)}setVoice(e){return this.voice=e,this.clearPrefetchedAudio(),this}setRate(e){return this.rate=e,this.clearPrefetchedAudio(),this}setPitch(e){return this.pitch=e,this.clearPrefetchedAudio(),this}async registerBindings(e){let t=e.childNodes;for(let e=0;e<t.length;e++){if(!t[e])continue;let n=t[e];n.attributes&&(n.attributes.getNamedItem(`co-tts.id`)?await this.handleIdModifier(n,n.attributes.getNamedItem(`co-tts.id`)):n.attributes.getNamedItem(`co-tts.ajax`)?await this.handleAjaxModifier(n,n.attributes.getNamedItem(`co-tts.ajax`)):n.attributes.getNamedItem(`co-tts`)?await this.handleDefault(n,n.attributes.getNamedItem(`co-tts`)):n.attributes.getNamedItem(`co-tts.stop`)?await this.handleStopModifier(n,n.attributes.getNamedItem(`co-tts.stop`)):n.attributes.getNamedItem(`co-tts.resume`)?await this.handleResumeModifier(n,n.attributes.getNamedItem(`co-tts.resume`)):n.attributes.getNamedItem(`co-tts.pause`)&&await this.handlePauseModifier(n,n.attributes.getNamedItem(`co-tts.pause`))),n.childNodes.length>0&&await this.registerBindings(n)}}async handleIdModifier(e,t){e.addEventListener(`click`,async n=>{await this.stopPlayer();let r=document.getElementById(t.value);this.clickedNode=r,r&&(this.textToRead=r.hasAttribute(`co-tts.text`)&&r.getAttribute(`co-tts.text`)!==``?r.getAttribute(`co-tts.text`)??``:r.innerText??r.textContent??``,this.setHighlightTargetFromNode(r),await this.startSynthesizer(e,t))})}async handleAjaxModifier(e,t){e.addEventListener(`click`,async n=>{await this.stopPlayer(),this.clickedNode=e;let r=await fetch(t.value,{method:`GET`});this.textToRead=await r.text(),this.setHighlightTargetFromNode(e),await this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener(`click`,async n=>{await this.stopPlayer(),this.clickedNode=e,this.setHighlightTargetFromNode(e),this.textToRead=t.value===``?e.innerText??e.textContent??``:t.value,await this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){await this.stopPlayer(),this.clickedNode=e,this.setHighlightTargetFromNode(e),this.textToRead=t.value===``?e.innerText??e.textContent??``:t.value,await this.startSynthesizer(e,t)}async handleStopModifier(e,t){e.addEventListener(`click`,async e=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent(`COAzureTTSStoppedPlaying`,{}))})}async handlePauseModifier(e,t){e.addEventListener(`click`,async e=>{this.player&&typeof this.player.pause==`function`&&(this.stopHighlightingInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent(`COAzureTTSPausedPlaying`,{})))})}async handleResumeModifier(e,t){e.addEventListener(`click`,async e=>{if(this.player){if(this.shouldHighlight()&&this.startHighlightingInterval(this.playbackSessionId),typeof this.player.resume==`function`)await this.player.resume();else if(typeof this.player.play==`function`)await this.player.play();else return;document.dispatchEvent(new CustomEvent(`COAzureTTSResumedPlaying`,{}))}})}async stopPlayer(){return this.stopPromise||=this.performStopPlayer().finally(()=>{this.stopPromise=void 0}),this.stopPromise}async performStopPlayer(){this.invalidatePlaybackSession(),this.stopHighlightingInterval(),this.highlightDiv&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML),this.resetPlaybackSegments();let e=this.player,t=this.activePrefetchedAudioUrl,n=this.synthesizer;if(this.textToRead=``,this.currentWord=``,this.currentOffset=0,this.wordBoundaryOffset=0,this.originalHighlightDivInnerHTML=``,this.wordBoundryList=[],this.playbackSegments=[],this.previousWordBoundary=void 0,this.highlightDiv=void 0,this.prevTextOffset=0,this.playbackTextOffsetBase=void 0,this.audioConfig=void 0,this.speechConfig=void 0,this.player===e&&(this.player=void 0),this.activePrefetchedAudioUrl===t&&(this.activePrefetchedAudioUrl=``),this.synthesizer===n&&(this.synthesizer=void 0),e!==void 0&&typeof e.pause==`function`)try{e.pause()}catch{}t!==``&&URL.revokeObjectURL(t),this.closeResource(n)}async createSpeechConfig(){let e=await this.authorizationManager.getAuthorization(),t=$.SpeechConfig.fromAuthorizationToken(e.token,e.region);return t.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,t.speechSynthesisOutputFormat=$.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3,this.region=e.region,t}async startSynthesizer(e,t){try{this.speechConfig=await this.createSpeechConfig();let e=this.createPlaybackSession();this.resetHighlightState();let t=new $.SpeakerAudioDestination,n=$.AudioConfig.fromSpeakerOutput(t),r=new $.SpeechSynthesizer(this.speechConfig,n);this.player=t,this.audioConfig=n,this.synthesizer=r,r.wordBoundary=(t,n)=>{this.isActivePlaybackSession(e)&&this.wordBoundryList.push(n)};let i=this.collectPlaybackChain(this.clickedNode),a=i.length>1;a?this.preparePlaybackChain(i):this.playbackSegments=[],t.onAudioEnd=async()=>{if(!this.isActivePlaybackSession(e))return;let t=this.clickedNode,n=this.playbackSegments.length>0,r=t?.hasAttribute?.(`co-tts.next`)?t.getAttribute(`co-tts.next`):null;if(await this.stopPlayer(),n){document.dispatchEvent(new CustomEvent(`COAzureTTSFinishedPlaying`,{}));return}if(r){let e=document.getElementById(r);if(e&&await this.playPrefetchedNode(e))return;let t=e?.attributes.getNamedItem(`co-tts.text`);e&&t?await this.handleWithoutClick(e,t):e&&e.dispatchEvent(new Event(`click`))}else document.dispatchEvent(new CustomEvent(`COAzureTTSFinishedPlaying`,{}))},t.onAudioStart=async()=>{this.isActivePlaybackSession(e)&&document.dispatchEvent(new CustomEvent(`COAzureTTSStartedPlaying`,{}))},this.shouldHighlight()&&this.startHighlightingInterval(e),a||this.prefetchNextNode(this.clickedNode);let o=this.buildSSML(this.textToRead);r.speakSsmlAsync(o,()=>{this.closeResource(r),this.isActivePlaybackSession(e)&&this.synthesizer===r&&(this.synthesizer=void 0)},t=>{this.closeResource(r),this.isActivePlaybackSession(e)&&(this.synthesizer===r&&(this.synthesizer=void 0),c(t)&&this.authorizationManager.clearAuthorization(),this.dispatchError(t,`SYNTHESIS_ERROR`),this.stopPlayer())})}catch(e){c(e)&&this.authorizationManager.clearAuthorization(),this.dispatchError(e),await this.stopPlayer()}}collectPlaybackChain(e){let t=[],n=new Set,r=e,i=0;for(;r&&!n.has(r.id);){n.add(r.id);let e=r.attributes.getNamedItem(`co-tts.text`)??r.attributes.getNamedItem(`co-tts`),a=this.getNodeText(r,e);if(a===``)break;let o=this.getHighlightDivForNode(r);if(t.push({node:r,text:a,start:i,end:i+a.length,highlightDiv:o,originalHighlightDivInnerHTML:o?.innerHTML??``}),i+=a.length+1,!r.hasAttribute(`co-tts.next`))break;r=document.getElementById(r.getAttribute(`co-tts.next`))}return t}preparePlaybackChain(e){this.playbackSegments=e,this.textToRead=e.map(e=>e.text).join(` `),this.highlightDiv=void 0,this.originalHighlightDivInnerHTML=``,this.resetHighlightState()}getHighlightDivForNode(e){if(!e?.hasAttribute?.(`co-tts.highlight`))return;let t=e.attributes.getNamedItem(`co-tts.highlight`)?.value??``;return t===``?e:document.getElementById(t)??void 0}resetPlaybackSegments(){this.playbackSegments.forEach(e=>{e.highlightDiv&&(e.highlightDiv.innerHTML=e.originalHighlightDivInnerHTML)})}updateChainedHighlight(e){if(~Ur.indexOf(e.text)&&(e=this.previousWordBoundary??void 0),!e){this.resetPlaybackSegments();return}this.ensurePlaybackTextOffsetBase();let t=Math.max(0,e.textOffset-(this.playbackTextOffsetBase??0)),n=this.playbackSegments.find(e=>t>=e.start&&t<e.end);if(this.resetPlaybackSegments(),!n?.highlightDiv){this.previousWordBoundary=e;return}let r=t-n.start;this.highlightTextRange(n.highlightDiv,n.originalHighlightDivInnerHTML,r,e.wordLength,n.text),this.previousWordBoundary=e}getNodeText(e,t){return t&&t.value!==``?t.value:e.hasAttribute(`co-tts.text`)&&e.getAttribute(`co-tts.text`)!==``?e.getAttribute(`co-tts.text`)??``:e.innerText??e.textContent??``}getPrefetchKey(e,t){return[e.id,t,this.voice,this.rate,this.pitch,this.url].join(`|`)}clearPrefetchedAudio(){this.prefetchedAudio.forEach(e=>{e.url&&URL.revokeObjectURL(e.url)}),this.prefetchedAudio.clear(),this.prefetchPromises.clear()}async prefetchNextNode(e){if(!e||!e.hasAttribute(`co-tts.next`))return;let t=document.getElementById(e.getAttribute(`co-tts.next`));if(!t)return;let n=t.attributes.getNamedItem(`co-tts.text`)??t.attributes.getNamedItem(`co-tts`),r=this.getNodeText(t,n);if(r===``)return;let i=this.getPrefetchKey(t,r);if(this.prefetchedAudio.has(i)||this.prefetchPromises.has(i))return;let a,o=(async()=>{try{let e=await this.createSpeechConfig();a=new $.SpeechSynthesizer(e,void 0);let n=[];return a.wordBoundary=(e,t)=>{n.push(t)},await new Promise(e=>{a?.speakSsmlAsync(this.buildSSML(r),o=>{if(this.closeResource(a),a=void 0,!o?.audioData){e(null);return}let s=new Blob([o.audioData],{type:`audio/mpeg`}),c=URL.createObjectURL(s),l={key:i,nodeId:t.id,text:r,url:c,wordBoundryList:n};this.prefetchedAudio.set(i,l),e(l)},t=>{this.closeResource(a),a=void 0,c(t)&&this.authorizationManager.clearAuthorization(),this.dispatchError(t,`PREFETCH_ERROR`),e(null)})})}catch(e){return this.closeResource(a),a=void 0,c(e)&&this.authorizationManager.clearAuthorization(),this.dispatchError(e),null}})().finally(()=>{this.prefetchPromises.delete(i)});this.prefetchPromises.set(i,o)}async playPrefetchedNode(e){let t=e.attributes.getNamedItem(`co-tts.text`)??e.attributes.getNamedItem(`co-tts`),n=this.getNodeText(e,t),r=this.getPrefetchKey(e,n),i=this.prefetchedAudio.get(r)??await this.prefetchPromises.get(r);if(!i)return!1;this.prefetchedAudio.delete(r);let a=this.createPlaybackSession();this.resetHighlightState(),this.clickedNode=e,this.textToRead=i.text,this.wordBoundryList=i.wordBoundryList,this.playbackSegments=[],this.setHighlightTargetFromNode(e);try{let t=new Audio(i.url);return this.activePrefetchedAudioUrl=i.url,this.player=t,t.addEventListener(`play`,()=>{this.isActivePlaybackSession(a)&&document.dispatchEvent(new CustomEvent(`COAzureTTSStartedPlaying`,{}))},{once:!0}),t.addEventListener(`ended`,async()=>{if(!this.isActivePlaybackSession(a))return;let e=this.clickedNode,t=e?.hasAttribute?.(`co-tts.next`)?e.getAttribute(`co-tts.next`):null;if(await this.stopPlayer(),t){let e=document.getElementById(t);if(e&&await this.playPrefetchedNode(e))return;let n=e?.attributes.getNamedItem(`co-tts.text`);e&&n?await this.handleWithoutClick(e,n):e&&e.dispatchEvent(new Event(`click`))}else document.dispatchEvent(new CustomEvent(`COAzureTTSFinishedPlaying`,{}))},{once:!0}),t.addEventListener(`error`,()=>{this.isActivePlaybackSession(a)&&(this.dispatchError(Error(`Prefetched audio resource closed unexpectedly.`),`AUDIO_RESOURCE_ERROR`),this.stopPlayer())},{once:!0}),this.shouldHighlight()&&this.startHighlightingInterval(a),this.prefetchNextNode(e),await t.play(),!0}catch(e){return this.stopHighlightingInterval(),this.dispatchError(e,`AUDIO_RESOURCE_ERROR`),await this.stopPlayer(),!1}}createPlaybackSession(){return this.playbackSessionId+=1,this.playbackSessionId}isActivePlaybackSession(e){return e===this.playbackSessionId}invalidatePlaybackSession(){this.playbackSessionId+=1}stopHighlightingInterval(){this.highlightInterval&&=(clearInterval(this.highlightInterval),void 0)}startHighlightingInterval(e){this.stopHighlightingInterval(),this.highlightInterval=setInterval(()=>{if(!this.isActivePlaybackSession(e)){this.stopHighlightingInterval();return}this.updateHighlightForCurrentTime(e)},50)}updateHighlightForCurrentTime(e){if(!this.isActivePlaybackSession(e)||this.player===void 0||!this.shouldHighlight())return;let t=this.player.currentTime,n;for(let e of this.wordBoundryList)if(t*1e3>e.audioOffset/1e4)n=e;else break;if(n===void 0){this.resetCurrentHighlight();return}if(this.playbackSegments.length>0){this.updateChainedHighlight(n);return}if(~Ur.indexOf(n.text)&&(n=this.previousWordBoundary??void 0),n===void 0||this.prevTextOffset>n.textOffset){this.resetCurrentHighlight();return}this.prevTextOffset=n.textOffset,this.ensurePlaybackTextOffsetBase();let r=Math.max(0,n.textOffset-(this.playbackTextOffsetBase??0));this.highlightTextRange(this.highlightDiv,this.originalHighlightDivInnerHTML,r,n.wordLength,this.textToRead),this.previousWordBoundary=n,this.currentWord=n.text,this.wordBoundaryOffset=n.textOffset}highlightTextRange(e,t,n,r,i){if(!e||r<=0||n<0)return;e.innerHTML=t;let a=n+this.getSpokenTextDomOffset(e,i),o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),s=0,c,l,u=0,d=0,f=a+r;for(;o.nextNode();){let e=o.currentNode,t=e.data.length,n=s,r=s+t;if(!c&&a>=n&&a<r&&(c=e,u=a-n),f>n&&f<=r){l=e,d=f-n;break}s=r}if(!c||!l)return;let p=document.createRange();try{if(p.setStart(c,u),p.setEnd(l,d),!this.isRangeVisuallyVisible(p,e))return;let t=document.createElement(`mark`);t.className=`co-tts-highlight`,t.appendChild(p.extractContents()),p.insertNode(t)}catch{e.innerHTML=t}}getSpokenTextDomOffset(e,t){if(!t)return 0;let n=e.textContent??``;if(n===``||n===t)return 0;let r=n.indexOf(t);return r>=0?r:0}isRangeVisuallyVisible(e,t){if(typeof e.getClientRects!=`function`)return!0;let n;try{n=Array.from(e.getClientRects()).filter(e=>e.width>0&&e.height>0)}catch{return!0}if(n.length===0)return!0;let r=this.getClippingRect(t);return n.some(e=>this.rectsOverlap(e,r))}getClippingRect(e){let t=e;for(;t;){if(this.isClippingElement(t))return t.getBoundingClientRect();t=t.parentElement}return e.getBoundingClientRect()}isClippingElement(e){let t=globalThis.getComputedStyle?.(e);if(!t)return!1;let n=t.overflowX||t.overflow,r=t.overflowY||t.overflow;if(this.isClippingOverflowValue(n)||this.isClippingOverflowValue(r))return!0;let i=t.getPropertyValue(`-webkit-line-clamp`).trim();return i!==``&&i!==`none`}isClippingOverflowValue(e){return e===`hidden`||e===`auto`||e===`scroll`||e===`clip`}rectsOverlap(e,t){return e.right>t.left&&e.left<t.right&&e.bottom>t.top&&e.top<t.bottom}setHighlightTargetFromNode(e){let t=this.getHighlightDivForNode(e);this.highlightDiv=t,this.originalHighlightDivInnerHTML=t?.innerHTML??``}shouldHighlight(){return this.highlightDiv?!0:this.playbackSegments.some(e=>!!e.highlightDiv)}resetHighlightState(){this.prevTextOffset=0,this.previousWordBoundary=void 0,this.currentWord=``,this.currentOffset=0,this.wordBoundaryOffset=0,this.playbackTextOffsetBase=void 0}ensurePlaybackTextOffsetBase(){this.playbackTextOffsetBase===void 0&&this.wordBoundryList.length!==0&&(this.playbackTextOffsetBase=this.wordBoundryList.reduce((e,t)=>Math.min(e,t.textOffset),this.wordBoundryList[0].textOffset))}resetCurrentHighlight(){if(this.playbackSegments.length>0){this.resetPlaybackSegments();return}this.highlightDiv&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML)}buildSSML(e){let t=`<speak xmlns="http://www.w3.org/2001/10/synthesis"
|
|
21
23
|
xmlns:mstts="http://www.w3.org/2001/mstts"
|
|
22
24
|
xmlns:emo="http://www.w3.org/2009/10/emotionml"
|
|
23
25
|
version="1.0"
|
|
24
26
|
xml:lang="en-US">
|
|
25
|
-
<voice name="${this.voice}">`;return this.url
|
|
27
|
+
<voice name="${this.voice}">`;return this.url!==``&&(t+=`<lexicon uri="${this.url}"/>`),t+=`<prosody rate="${this.rate}%" pitch="${this.pitch}%">
|
|
26
28
|
${this.convertHtmlEntities(e)}
|
|
27
|
-
</prosody></voice></speak>`,t}convertHtmlEntities(e){
|
|
29
|
+
</prosody></voice></speak>`,t}convertHtmlEntities(e){let t=document.createElement(`p`);return t.textContent=e,t.innerHTML}closeResource(e){if(e&&typeof e.close==`function`)try{e.close()}catch{}}dispatchError(e,t){let n=o(e);t&&!n.code&&(n.code=t),document.dispatchEvent(new CustomEvent(`COAzureTTSError`,{detail:{error:n}}))}};e.DEFAULT_TOKEN_LIFETIME_MS=n,e.SpeechAuthorizationManager=l,e.SpeechToText=Hr,e.TextToSpeech=Wr,e.createSpeechAuthorizationProvider=r,e.isLikelyAuthorizationError=c,e.sanitizeErrorText=s,e.toSafeErrorDetail=o,e.validateSpeechAuthorization=i});
|