@creativeorange/azure-text-to-speech 3.0.2 → 3.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/co-azure-tts.umd.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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 ct(a)}}function ct(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(Ce(r));return t.message=Ce(r),e&&(t.code=e),t}function we(r){if(typeof r=="string")return{message:r.trim()!==""?Ce(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!==""?Ce(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 Ce(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=we(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 ht{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 ct(e)}catch(e){this.clearAuthorization();const t=we(e);throw oe(t.message,t.code)}}}var Oe={},Be,Pi=new Uint8Array(16);function Ii(){if(!Be&&(Be=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Be))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Be(Pi)}var Mi=/^(?:[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 ki(r){return typeof r=="string"&&Mi.test(r)}for(var L=[],ut=0;ut<256;++ut)L.push((ut+256).toString(16).substr(1));function zi(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(!ki(t))throw TypeError("Stringified UUID is invalid");return t}function Di(r,e,t){r=r||{};var i=r.random||(r.rng||Ii)();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 zi(i)}const Ni=()=>Di(),A=()=>Ni().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 Ee extends ce{constructor(e,t,i=C.Info){super(e,i),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class _e extends Ee{constructor(e){super("AudioSourceInitializingEvent",e)}}class Te extends Ee{constructor(e){super("AudioSourceReadyEvent",e)}}class _t extends Ee{constructor(e){super("AudioSourceOffEvent",e)}}class He extends Ee{constructor(e,t){super("AudioSourceErrorEvent",e,C.Error),this.privError=t}get error(){return this.privError}}class Ke extends Ee{constructor(e,t,i){super(e,t),this.privAudioNodeId=i}get audioNodeId(){return this.privAudioNodeId}}class be extends Ke{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class Re extends Ke{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class J extends Ke{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class pt extends Ke{constructor(e,t,i){super("AudioStreamNodeErrorEvent",e,t),this.privError=i}get error(){return this.privError}}class Ht 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 Kt 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 qt extends he{constructor(e){super("ConnectionEstablishedEvent",e)}}class xi 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 Li 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 Oi 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 dt 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 Bi 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 lt 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 vt{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 ft{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 lt("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 lt("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var Ut;(function(r){r[r.None=0]="None",r[r.Resolved=1]="Resolved",r[r.Rejected=2]="Rejected"})(Ut||(Ut={}));class N{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 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())})},Ae;(function(r){r[r.Dequeue=0]="Dequeue",r[r.Peek=1]="Peek"})(Ae||(Ae={}));class Pe{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 N;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ae.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new N;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ae.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return Wt(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 Wt(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===Ae.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 lt("Queue");if(this.privIsDisposing)throw new W("Queue disposing")}}class qe{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 _i{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 Hi=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 Vt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||A(),this.privReaderQueue=new Pe}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=>Hi(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 Pe)}throwIfClosed(){if(this.privIsWriteEnded)throw new W("Stream closed")}}var Ie;(function(r){r[r.Success=0]="Success",r[r.Error=1]="Error"})(Ie||(Ie={}));class gt extends Vt{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 Fr=Object.defineProperty;var jr=(k,U,Y)=>U in k?Fr(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 Ki extends _{constructor(e){super("OCSPMemoryCacheHitEvent",C.Debug,e)}}class qi extends _{constructor(e){super("OCSPCacheMissEvent",C.Debug,e)}}class Ui extends _{constructor(e){super("OCSPDiskCacheHitEvent",C.Debug,e)}}class Wi extends _{constructor(e){super("OCSPCacheUpdateNeededEvent",C.Debug,e)}}class Vi extends _{constructor(e){super("OCSPMemoryCacheStoreEvent",C.Debug,e)}}class Fi extends _{constructor(e){super("OCSPDiskCacheStoreEvent",C.Debug,e)}}class ji extends _{constructor(e){super("OCSPCacheUpdateCompleteEvent",C.Debug,e)}}class Gi extends _{constructor(){super("OCSPStapleReceivedEvent",C.Debug,"")}}class $i extends _{constructor(e,t){super("OCSPCacheEntryExpiredEvent",C.Debug,e),this.privExpireTime=t}}class Ji extends _{constructor(e,t,i){super("OCSPCacheEntryNeedsRefreshEvent",C.Debug,e),this.privExpireTime=i,this.privStartTime=t}}class Qi 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 Xi extends _{constructor(e,t){super("OCSPVerificationFailedEvent",C.Debug,e),this.privError=t}}class Ft extends _{constructor(e,t){super("OCSPCacheFetchErrorEvent",C.Debug,e),this.privError=t}}class Zi extends _{constructor(e){super("OCSPResponseRetrievedEvent",C.Debug,e)}}class Yi extends _{constructor(e,t){super("OCSPCacheUpdateErrorEvent",C.Debug,e),this.privError=t}}class Me 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 b{}b.AuthKey="Ocp-Apim-Subscription-Key",b.ConnectionId="X-ConnectionId",b.ContentType="Content-Type",b.CustomCommandsAppId="X-CommandsAppId",b.Path="Path",b.RequestId="X-RequestId",b.RequestStreamId="X-StreamId",b.RequestTimestamp="X-Timestamp";class St{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class jt{constructor(e){if(!e)throw new z("subscriptionKey");this.privAuthInfo=new St(b.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}const Gt="Authorization";class le{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 St(Gt,le.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new St(Gt,le.privTokenPrefix+t))}}le.privTokenPrefix="bearer ";class $t{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 Ue{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 Ue{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 mt=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 yt{constructor(){}static createPushStream(e){return Jt.create(e)}static createPullStream(e,t){return Qt.create(e,t)}}class Jt extends yt{static create(e){return new er(e)}}class er extends Jt{constructor(e){super(),e===void 0?this.privFormat=ee.getDefaultInputFormat():this.privFormat=e,this.privEvents=new j,this.privId=A(),this.privStream=new gt(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 _e(this.privId)),this.onEvent(new Te(this.privId))}attach(e){return mt(this,void 0,void 0,function*(){this.onEvent(new be(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new Re(this.privId,e)),{detach:()=>mt(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:me.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 Qt extends yt{constructor(){super()}static create(e,t){return new Xt(e,t)}}class Xt extends Qt{constructor(e,t){super(),t===void 0?this.privFormat=Ue.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 _e(this.privId)),this.onEvent(new Te(this.privId))}attach(e){return mt(this,void 0,void 0,function*(){return this.onEvent(new be(this.privId,e)),yield this.turnOn(),this.onEvent(new Re(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:me.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 tr=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 Zt{constructor(){}static createPullStream(){return We.create()}}class We extends Zt{static create(){return new wt}}class wt extends We{constructor(){super(),this.privId=A(),this.privStream=new Vt}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 tr(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 Yt extends Zt{constructor(){super()}static create(e){return new Ct(e)}}class Ct extends Yt{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 Lt(!0);return new ve(new F(e))}static fromMicrophoneInput(e){const t=new Lt(!0);return new ve(new F(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new ve(new Nr(e,t))}static fromStreamInput(e){if(e instanceof ir)return new ve(new Xt(e));if(e instanceof yt)return new ve(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new Lt(!1);return new ve(new F(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new fe(new Pt)}static fromSpeakerOutput(e){if(e===void 0)return te.fromDefaultSpeakerOutput();if(e instanceof Pt)return new fe(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new fe(new $t(e))}static fromStreamOutput(e){if(e instanceof ei)return new fe(new Ct(e));if(e instanceof Yt)return new fe(e);if(e instanceof We)return new fe(e);throw new Error("Not Supported Type")}}class ve 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 fe 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 K;(function(r){r[r.Error=0]="Error",r[r.EndOfStream=1]="EndOfStream"})(K||(K={}));class ir{}class ei{}class ge{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}class Et extends ge{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 rr{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 nr extends rr{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 ti extends Et{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}class ii extends ge{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}class Tt extends nr{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 ri{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 bt{constructor(){}static fromSubscription(e,t){f.throwIfNullOrWhitespace(e,"subscriptionKey"),f.throwIfNullOrWhitespace(t,"region");const i=new Se;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 Se;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 Se;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 Se;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.authorizationToken=e,i}close(){}}class Se extends bt{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(nt,void 0)]}set outputFormat(e){this.privProperties.setProperty(nt,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(xe,"{}"));i[e]=t,this.privProperties.setProperty(xe,JSON.stringify(i))}setProfanity(e){this.privProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,Ge[e])}enableAudioLogging(){this.privProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(Ti,"true")}clone(){const e=new Se;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 ni extends bt{constructor(){super()}static fromSubscription(e,t){f.throwIfNullOrWhitespace(e,"subscriptionKey"),f.throwIfNullOrWhitespace(t,"region");const i=new Ve;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 Ve;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 Ve;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 Ve;return i.properties.setProperty(p.SpeechServiceConnection_Endpoint,e.href),i.properties.setProperty(p.SpeechServiceConnection_Key,t),i}}class Ve extends ni{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(nt,void 0)]}set outputFormat(e){this.privSpeechProperties.setProperty(nt,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(xe,"{}"));i[e]=t,this.privSpeechProperties.setProperty(xe,JSON.stringify(i))}setProfanity(e){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,Ge[e])}enableAudioLogging(){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privSpeechProperties.setProperty(Ti,"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 ke=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 Rt{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 ke(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 Ye(new et(new Si(e,t,i))));this.privReco=this.createServiceRecognizer(Rt.getAuthFromProperties(this.privProperties),this.privConnectionFactory,this.audioConfig,n)}recognizeOnceAsyncImpl(e){return ke(this,void 0,void 0,function*(){f.throwIfDisposed(this.privDisposed);const t=new N;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 ke(this,void 0,void 0,function*(){f.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop(),yield this.privReco.recognize(e,void 0,void 0)})}stopContinuousRecognitionAsyncImpl(){return ke(this,void 0,void 0,function*(){f.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop()})}implRecognizerStop(){return ke(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 jt(t):new le(()=>{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 si{constructor(e){this.privConnectionMessage=e,this.privProperties=new V,this.privConnectionMessage.headers[b.ConnectionId]&&this.privProperties.setProperty(p.Speech_SessionId,this.privConnectionMessage.headers[b.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 Fe{static fromRecognizer(e){const t=e.internalData,i=new Fe;return i.privInternalData=t,i.setupEvents(),i}static fromSynthesizer(e){const t=e.internalData,i=new Fe;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 ci(e.connectionId)):e.name==="ConnectionClosedEvent"?this.disconnected&&this.disconnected(new ci(e.connectionId)):e.name==="ConnectionMessageSentEvent"?this.messageSent&&this.messageSent(new hi(new si(e.message))):e.name==="ConnectionMessageReceivedEvent"&&this.messageReceived&&this.messageReceived(new hi(new si(e.message)))}),this.privServiceEventListener=this.privInternalData.serviceEvents.attach(e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new ar(e.jsonString,e.name))})}}var oi=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 sr extends Rt{constructor(e,t){const i=e;f.throwIfNull(i,"speechConfig"),super(t,i.properties,new mr),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 oi(this,void 0,void 0,function*(){})}dispose(e){const t=Object.create(null,{dispose:{get:()=>super.dispose}});return oi(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 gr(e,this.properties)}createServiceRecognizer(e,t,i,n){const s=i;return new wr(e,t,s,n,this)}updateLanguages(e){const t=Fe.fromRecognizer(this);t&&(t.setMessageProperty("speech.context","translationcontext",{to:e}),t.sendMessageAsync("event",JSON.stringify({id:"translation",name:"updateLanguage",to:e})))}}class or{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 ai{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 ci extends ge{}class ar extends ge{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 je{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(xe,"{}"));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 Ge;(function(r){r[r.Masked=0]="Masked",r[r.Removed=1]="Removed",r[r.Raw=2]="Raw"})(Ge||(Ge={}));class hi{constructor(e){this.privConnectionMessage=e}get message(){return this.privConnectionMessage}toString(){return"Message: "+this.privConnectionMessage.toString()}}var $e=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 ze{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 yr,this.synthesisRequestQueue=new Pe,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)===zr}static FromConfig(e,t,i){const n=e;return t.properties.mergeTo(n.properties),new ze(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=ze.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 $e(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 $e(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new Mr(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 Ye(new et(new Si(e,t,i)))),s=this.privProperties.getProperty(p.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new jt(s):new le(()=>{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 Ir(n)}speakImpl(e,t,i,n,s){try{f.throwIfDisposed(this.privDisposed);const o=A();let a;s instanceof ei?a=new Ct(s):s instanceof We?a=s:s!==void 0?a=new $t(s):a=void 0,this.synthesisRequestQueue.enqueue(new cr(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 $e(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 pi(t,n,void 0)}else return new pi(t,void 0,`Error: ${i.status}: ${i.statusText}`)})}adapterSpeak(){return $e(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 cr{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 ui{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 Je extends ui{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 Qe{constructor(e){this.privResult=e}get result(){return this.privResult}}class hr{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 ur{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class pr{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 pi extends ui{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 dr(n))}else super(e,I.Canceled,i||"Error information unavailable",new V)}get voices(){return this.privVoices}}var De;(function(r){r[r.Unknown=0]="Unknown",r[r.Female=1]="Female",r[r.Male=2]="Male"})(De||(De={}));var Xe;(function(r){r[r.OnlineNeural=1]="OnlineNeural",r[r.OnlineStandard=2]="OnlineStandard",r[r.OfflineNeural=3]="OfflineNeural",r[r.OfflineStandard=4]="OfflineStandard"})(Xe||(Xe={}));class dr{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")?Xe.OnlineStandard:Xe.OnlineNeural,this.privGender=e.Gender==="Male"?De.Male:e.Gender==="Female"?De.Female:De.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 At=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 lr=60*30,di={[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 Pt{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:di[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=di[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=lr,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(i=>{O.instance.onEvent(new Me(i))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(i=>{O.instance.onEvent(new Me(i))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(i=>{O.instance.onEvent(new Me(i))})):(console.warn(`Format ${l[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new wt,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 At(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 At(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return At(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 Ze 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 li extends Ze{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 vr extends Ze{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 vi extends Ze{constructor(e,t,i){super("ConnectingToServiceEvent",e,i),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}}class fr extends Ze{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 fi;(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"})(fi||(fi={}));class H extends vt{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[b.Path]=t,h[b.RequestId]=i,h[b.RequestTimestamp]=new Date().toISOString(),n&&(h[b.ContentType]=n),o&&(h[b.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()===b.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===b.RequestId.toLowerCase()?i=e.headers[a]:a.toLowerCase()===b.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===b.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 x=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 Er(this.privAudioSource.id()),this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privDynamicGrammar=new br,this.privSpeechContext=new Tr(this.privDynamicGrammar),this.privAgentConfig=new Ci,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(K.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 x(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 x(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 Lr(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(K.Error,P.ConnectionFailure,u);return}const o=new ge(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,o),this.receiveMessage(),this.sendAudio(s).catch(u=>x(this,void 0,void 0,function*(){yield this.cancelRecognitionLocal(K.Error,P.RuntimeError,u)}))})}stopRecognizing(){return x(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 x(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 x(this,void 0,void 0,function*(){if(yield this.cancelRecognitionLocal(K.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 x(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 x(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 x(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 x(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=it.fromJSON(i.textBody),s=new Et(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=it.fromJSON(o);this.privRecognizerConfig.isContinuousRecognition&&this.privRequestSession.onServiceRecognized(a.Offset+this.privRequestSession.currentTurnAudioOffset);const u=new Et(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(K.EndOfStream,P.NoError,void 0));const h=new ge(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 Ht(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 x(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 x(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 x(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 x(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=()=>x(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 x(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
|
|
4
|
-
`;class
|
|
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
|
+
`;class Ci{toConnectionMessage(e){const t=new x;try{if(e.messageType===y.Text){const i=e.textContent;let n={},s=null;if(i){const o=i.split(`\r
|
|
5
5
|
\r
|
|
6
|
-
`);o&&o.length>0&&(n=this.parseHeaders(o[0]),o.length>1&&(s=o[1]))}t.resolve(new vt(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 vt(e.messageType,s,n,e.id))}}catch(i){t.reject(`Error formatting the message. Error: ${i}`)}return t.promise}fromConnectionMessage(e){const t=new N;try{if(e.messageType===y.Text){const i=`${this.makeHeaders(e)}${mi}${e.textBody?e.textBody:""}`;t.resolve(new qe(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 qe(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]}${mi}`);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 mr extends je{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=je.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[b.ConnectionId]=i,e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const h=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new Ri(n,s,u,new yi,at.fromRecognizerConfig(e),h,i)}}class yr{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=je.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[b.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 Ri(n,c,d,new yi,at.fromParameters(e.parameters),v,i)}}class tt{static implTranslateRecognitionResult(e){let t=I.Canceled;switch(e){case T.Success:t=I.RecognizedSpeech;break;case T.NoMatch:case T.InitialSilenceTimeout:case T.BabbleTimeout:case T.EndOfDictation:t=I.NoMatch;break;case T.Error:case T.BadRequest:case T.Forbidden:default:t=I.Canceled;break}return t}static implTranslateCancelResult(e){let t=K.EndOfStream;switch(e){case T.Success:case T.EndOfDictation:case T.NoMatch:t=K.EndOfStream;break;case T.InitialSilenceTimeout:case T.BabbleTimeout:case T.Error:case T.BadRequest:case T.Forbidden:default:t=K.Error;break}return t}static implTranslateCancelErrorCode(e){let t=P.NoError;switch(e){case T.Error:t=P.ServiceError;break;case T.TooManyRequests:t=P.TooManyRequests;break;case T.BadRequest:t=P.BadRequestParameters;break;case T.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 T;(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"})(T||(T={}));class It{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus=Ne[this.privSynthesisEnd.SynthesisStatus]}static fromJSON(e){return new It(e)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}class Mt{constructor(e){this.privTranslationHypothesis=JSON.parse(e),this.privTranslationHypothesis.Translation.TranslationStatus=Ie[this.privTranslationHypothesis.Translation.TranslationStatus]}static fromJSON(e){return new Mt(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 ye{constructor(e){this.privTranslationPhrase=e,this.privTranslationPhrase.RecognitionStatus=T[this.privTranslationPhrase.RecognitionStatus],this.privTranslationPhrase.Translation!==void 0&&(this.privTranslationPhrase.Translation.TranslationStatus=Ie[this.privTranslationPhrase.Translation.TranslationStatus])}static fromJSON(e){return new ye(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 ye(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 wi=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 wr 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 wi(this,void 0,void 0,function*(){const t=new V;let i=!1;const n=s=>wi(this,void 0,void 0,function*(){if(this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset+s.Offset+s.Duration),s.RecognitionStatus===T.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=tt.implTranslateRecognitionResult(s.RecognitionStatus),a=new Tt(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=tt.implTranslateCancelResult(s.RecognitionStatus),h=tt.implTranslateCancelErrorCode(s.RecognitionStatus);yield this.cancelRecognitionLocal(u,h,tt.implTranslateErrorDetails(h))}else{if(!(this.privRequestSession.isSpeechEnded&&o===I.NoMatch&&s.RecognitionStatus!==T.InitialSilenceTimeout)){const u=new ti(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(Mt.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(ye.fromTranslationResponse(o)));break;case"translation.phrase":yield n(ye.fromJSON(e.textBody));break;case"translation.synthesis":this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),i=!0;break;case"translation.synthesis.end":const a=It.fromJSON(e.textBody);switch(a.SynthesisStatus){case Ne.Error:if(this.privTranslationRecognizer.synthesizing){const u=new ri(I.Canceled,void 0),h=new ii(u,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,h)}catch{}}if(this.privTranslationRecognizer.canceled){const u=new ai(this.privRequestSession.sessionId,K.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(Ei,P[n]),this.privTranslationRecognizer.canceled){const a=new ai(e,i,s,n,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,a)}catch{}}if(this.privSuccessCallback){const a=new Tt(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 or;for(const u of e.Translation.Translations)i.set(u.Language,u.Text||u.DisplayText)}let n;e instanceof ye?e.Translation.TranslationStatus===Ie.Success?n=I.TranslatedSpeech:n=I.RecognizedSpeech:n=I.TranslatingSpeech;const s=e.Offset+this.privRequestSession.currentTurnAudioOffset,o=new Tt(i,this.privRequestSession.requestId,n,e.Text,e.Duration,s,e.Translation.FailureReason,JSON.stringify(e),t);return new ti(o,s,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){const i=e===void 0?I.SynthesizingAudioCompleted:I.SynthesizingAudio,n=new ri(i,e),s=new ii(n,t);if(this.privTranslationRecognizer.synthesizing)try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,s)}catch{}}}class it{constructor(e){this.privSpeechStartDetected=JSON.parse(e)}static fromJSON(e){return new it(e)}get Offset(){return this.privSpeechStartDetected.Offset}}class Cr{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 li&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:"ListeningTrigger",Start:e.eventTime}),e instanceof be&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof Re&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof He&&e.audioSourceId===this.privAudioSourceId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof pt&&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 vi&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof Kt&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof qt&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof Oi&&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 dt&&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 Er{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 N,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 Cr(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new li(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 vr(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))})}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new vi(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 fr(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 N}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 Tr{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 br{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 Ci{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 kt{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new kt(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 rt,this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privSynthesisContext=new kr(this.privSpeechSynthesizer),this.privAgentConfig=new Ci,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(K.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 Qe(new Je(i,I.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,h),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(K.Error,P.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,i,n){const s=new V;s.setProperty(Ei,P[i]);const o=new Je(e,I.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new Qe(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 Qe(new Je(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=kt.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 hr(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 ur(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 pr(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 Je(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 Qe(s))}catch{}break;default:this.processTypeSpecificMessages(i)||this.privServiceEvents&&this.serviceEvents.onEvent(new Ht(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 zt extends ce{constructor(e,t,i=C.Info){super(e,i),this.privRequestId=t}get requestId(){return this.privRequestId}}class Rr extends zt{constructor(e,t,i){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=i}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class Ar extends zt{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class Pr extends zt{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var Dt=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 rt{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 N,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 Dt(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 Dt(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 wt,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 Rr(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new Ar(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new Pr(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 N}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)&&!rt.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)&&!rt.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 Dt(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 Ir{constructor(e){let t=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(p.SpeechServiceConnection_Region,"westus"),s=je.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 Ur(i)}getVoicesList(e){return this.privRestAdapter.setHeaders(b.ConnectionId,e),this.privRestAdapter.request(de.Get,this.privUri)}}var Nt;(function(r){r[r.Standard=0]="Standard",r[r.Custom=1]="Custom"})(Nt||(Nt={}));class Mr{constructor(e,t){this.privSynthesisServiceType=Nt.Standard,this.privSpeechServiceConfig=e||new Ye(new et(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 kr{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 nt="OutputFormat",Ei="CancellationErrorCode",xe="ServiceProperties",Ti="ForceDictation",zr="OpenRange";var st=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 Dr="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 N;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 _e(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new Te(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new Te(this.privId)),this.privInitializeDeferral.resolve()},n=>{const s=`Error occurred during microphone initialization: ${n}`;this.privInitializeDeferral.reject(s),this.onEvent(new He(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 He(i,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new be(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new Re(this.privId,e)),{detach:()=>st(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 st(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 _t(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:me.Unknown,manufacturer:"Speech SDK",model:e,samplerate:F.AUDIOFORMAT.samplesPerSec,type:pe.Microphones}))}setProperty(e,t){if(e===Dr)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 N;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 st(this,void 0,void 0,function*(){yield this.turnOn();const t=new gt(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new pt(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 st(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=Ue.getDefaultInputFormat();var xt=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 Nr{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 He(e,"")),Promise.reject(e)}this.onEvent(new _e(this.privId)),this.onEvent(new Te(this.privId))}id(){return this.privId}attach(e){return xt(this,void 0,void 0,function*(){this.onEvent(new be(this.privId,e));const t=yield this.upload(e);return this.onEvent(new Re(this.privId,e)),Promise.resolve({detach:()=>xt(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 _t(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:me.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:pe.File}))}readHeader(){const t=this.privSource.slice(0,512),i=new N,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(Ue.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 xt(this,void 0,void 0,function*(){const t=i=>{const n=`Error occurred while processing '${this.privFilename}'. ${i}`;throw this.onEvent(new pt(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const i=yield this.privAudioFormatPromise,n=new gt(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 Lt{constructor(e){this.privStopInputOnRelease=e}record(e,t,i){const s=new _i(e.sampleRate,16e3),o=e.createMediaStreamSource(t);if(!this.privSpeechProcessorScript){const u=`class SP extends AudioWorkletProcessor {
|
|
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
7
|
constructor(options) {
|
|
8
8
|
super(options);
|
|
9
9
|
}
|
|
@@ -17,11 +17,11 @@ File System access not available, please use Push or PullAudioOutputStream`),thi
|
|
|
17
17
|
return true;
|
|
18
18
|
}
|
|
19
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 Le=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 Oe("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 Oe.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 Oe(t)}static OCSPCheck(e,t){return Le(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 Gi),n=c)}),o.on("error",c=>{s||(s=!0,o.destroy(),h(c))}),a.on("secure",()=>Le(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 Le(this,void 0,void 0,function*(){let n=M.privMemCache[e];if(n&&this.onEvent(new Ki(e)),!n)try{const s=yield M.privDiskCache.get(e);s.isCached&&(M.onEvent(new Ui(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 Ft(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 $i(e,h)),n=null;else{const c=Math.min(864e5,(h-u)/2);h-(Date.now()+this.testTimeOffset)<c?(this.onEvent(new Ji(e,u,h)),this.UpdateCache(t,i).catch(d=>{this.onEvent(new Yi(e,d.toString()))})):this.onEvent(new Qi(e,u,h))}}catch(s){this.onEvent(new Ft(e,s)),n=null}return n||this.onEvent(new qi(e)),n})}static VerifyOCSPResponse(e,t,i){return Le(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 Xi(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 Le(this,void 0,void 0,function*(){const i=e.id.toString("hex");this.onEvent(new Wi(i));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(i,n),this.onEvent(new ji(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 Vi(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Fi(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 Zi(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 bi=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 ot{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[b.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 N,this.privCertificateValidatedDeferral=new N,this.privConnectionState=D.Connecting;try{if(typeof WebSocket!="undefined"&&!ot.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 Oe(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new Pe,this.privDisconnectDeferral=new N,this.privSendMessageQueue=new Pe,this.processSendQueue().catch(e=>{O.instance.onEvent(new Me(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new ft(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Kt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=D.Connected,this.onEvent(new qt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new ft(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Li(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 ft(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=D.Disconnected,this.privWebsocketClient=null,this.onEvent(new xi(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{O.instance.onEvent(new Me(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===D.Connected){const i=new N;if(this.privReceivingMessageQueue.enqueueFromPromise(i.promise),e.data instanceof ArrayBuffer){const n=new qe(y.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new dt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new qe(y.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new dt(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 N,i=new N;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 Bi(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 bi(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 bi(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}}ot.forceNpmWebSocket=!1;var xr=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 Ri{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 ot(this.privUri,this.id,this.privMessageFormatter,s,i,o)}dispose(){return xr(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 Lr{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 Or(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 Or{constructor(e,t,i){this.chunk=e,this.serial=t,this.byteOffset=i}}class at{constructor(e,t,i,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=i,this.privProxyPassword=n}static fromParameters(e){return new at(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 Br=new Set(["json","buffer","string"]);var _r=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(Br.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 Hr=_r;class Ot extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Ot),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 Kr=Hr((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 Ot(h);return t==="json"?h.json():t==="buffer"?h.arrayBuffer():t==="string"?h.text():h}),qr=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 Ur{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 N,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=Kr(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),w=this.queryParams(i)===""?"":`?${this.queryParams(i)}`;v(w,d).then(R=>qr(this,void 0,void 0,function*(){if(e===de.Delete||R.statusCode===204)o.resolve(u(R));else try{const q=yield R.json();o.resolve(u(R,q))}catch{o.resolve(u(R))}})).catch(R=>{o.reject(R)})};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 Wr{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 ht(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=ni.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 sr(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=we(e);t&&!i.code&&(i.code=t),document.dispatchEvent(new CustomEvent("COAzureSTTError",{detail:{error:i}}))}}const Ai=[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"];class Vr{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 ht(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=bt.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 Pt,s=te.fromSpeakerOutput(n),o=new ze(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 R=document.getElementById(v);if(R&&await this.playPrefetchedNode(R))return;const q=R==null?void 0:R.attributes.getNamedItem("co-tts.text");R&&q?await this.handleWithoutClick(R,q):R&&R.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(~Ai.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),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 ze(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"}),R=URL.createObjectURL(w),q={key:s,nodeId:t.id,text:n,url:R,wordBoundryList:c};this.prefetchedAudio.set(s,q),d(q)},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 R=w==null?void 0:w.attributes.getNamedItem("co-tts.text");w&&R?await this.handleWithoutClick(w,R):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(~Ai.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.previousWordBoundary=i,this.currentWord=i.text,this.wordBoundaryOffset=i.textOffset}highlightTextRange(e,t,i,n){if(!e||n<=0)return;e.innerHTML=t;const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let o=0,a,u,h=0,c=0;const d=i+n;for(;s.nextNode();){const w=s.currentNode,R=w.data.length,q=o,Bt=o+R;if(!a&&i>=q&&i<Bt&&(a=w,h=i-q),d>q&&d<=Bt){u=w,c=d-q;break}o=Bt}if(!a||!u)return;const v=document.createRange();try{v.setStart(a,h),v.setEnd(u,c);const w=document.createElement("mark");w.className="co-tts-highlight",w.appendChild(v.extractContents()),v.insertNode(w)}catch{e.innerHTML=t}}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"
|
|
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"
|
|
21
21
|
xmlns:mstts="http://www.w3.org/2001/mstts"
|
|
22
22
|
xmlns:emo="http://www.w3.org/2009/10/emotionml"
|
|
23
23
|
version="1.0"
|
|
24
24
|
xml:lang="en-US">
|
|
25
25
|
<voice name="${this.voice}">`;return this.url!==""&&(t+=`<lexicon uri="${this.url}"/>`),t+=`<prosody rate="${this.rate}%" pitch="${this.pitch}%">
|
|
26
26
|
${this.convertHtmlEntities(e)}
|
|
27
|
-
</prosody></voice></speak>`,t}convertHtmlEntities(e){const 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){const i=
|
|
27
|
+
</prosody></voice></speak>`,t}convertHtmlEntities(e){const 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){const i=Ce(e);t&&!i.code&&(i.code=t),document.dispatchEvent(new CustomEvent("COAzureTTSError",{detail:{error:i}}))}}k.DEFAULT_TOKEN_LIFETIME_MS=48e4,k.SpeechAuthorizationManager=pt,k.SpeechToText=Fr,k.TextToSpeech=jr,k.createSpeechAuthorizationProvider=Y,k.isLikelyAuthorizationError=ae,k.sanitizeErrorText=Ee,k.toSafeErrorDetail=Ce,k.validateSpeechAuthorization=ut,Object.defineProperties(k,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|