@creativeorange/azure-text-to-speech 1.2.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/co-azure-tts.es.js +14 -12
- package/dist/co-azure-tts.umd.js +6 -11
- package/package.json +1 -1
- package/src/TextToSpeech.ts +16 -13
- package/.idea/azure-text-to-speech.iml +0 -8
- package/.idea/codeStyles/Project.xml +0 -376
- package/.idea/codeStyles/codeStyleConfig.xml +0 -5
- package/.idea/inspectionProfiles/Project_Default.xml +0 -6
- package/.idea/modules.xml +0 -8
- package/.idea/vcs.xml +0 -6
package/dist/co-azure-tts.umd.js
CHANGED
@@ -1,9 +1,9 @@
|
|
1
|
-
(function(_,L){typeof exports=="object"&&typeof module!="undefined"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(_=typeof globalThis!="undefined"?globalThis:_||self,L(_.CreativeOrangeAzureTextToSpeech={}))})(this,function(_){"use strict";var L={},V,Si=new Uint8Array(16);function mi(){if(!V&&(V=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!V))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return V(Si)}var yi=/^(?:[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 wi(r){return typeof r=="string"&&yi.test(r)}for(var z=[],tt=0;tt<256;++tt)z.push((tt+256).toString(16).substr(1));function Ci(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(z[r[e+0]]+z[r[e+1]]+z[r[e+2]]+z[r[e+3]]+"-"+z[r[e+4]]+z[r[e+5]]+"-"+z[r[e+6]]+z[r[e+7]]+"-"+z[r[e+8]]+z[r[e+9]]+"-"+z[r[e+10]]+z[r[e+11]]+z[r[e+12]]+z[r[e+13]]+z[r[e+14]]+z[r[e+15]]).toLowerCase();if(!wi(t))throw TypeError("Stringified UUID is invalid");return t}function Ti(r,e,t){r=r||{};var i=r.random||(r.rng||mi)();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 Ci(i)}const Ei=()=>Ti(),b=()=>Ei().replace(new RegExp("-","g"),"").toUpperCase();var m;(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"})(m||(m={}));class ne{constructor(e,t){this.privName=e,this.privEventId=b(),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 Se extends ne{constructor(e,t,i=m.Info){super(e,i),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class De extends Se{constructor(e){super("AudioSourceInitializingEvent",e)}}class me extends Se{constructor(e){super("AudioSourceReadyEvent",e)}}class It extends Se{constructor(e){super("AudioSourceOffEvent",e)}}class ke extends Se{constructor(e,t){super("AudioSourceErrorEvent",e,m.Error),this.privError=t}get error(){return this.privError}}class ze extends Se{constructor(e,t,i){super(e,t),this.privAudioNodeId=i}get audioNodeId(){return this.privAudioNodeId}}class ye extends ze{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class we extends ze{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class $ extends ze{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class it extends ze{constructor(e,t,i){super("AudioStreamNodeErrorEvent",e,t),this.privError=i}get error(){return this.privError}}class Mt extends ne{constructor(e,t,i=m.Info){super(e,i),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class se extends ne{constructor(e,t,i=m.Info){super(e,i),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class Dt extends se{constructor(e,t,i){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=i}get uri(){return this.privUri}get headers(){return this.privHeaders}}class kt extends se{constructor(e){super("ConnectionEstablishedEvent",e)}}class bi extends se{constructor(e,t,i){super("ConnectionClosedEvent",e,m.Debug),this.privReason=i,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class Ri extends se{constructor(e,t,i){super("ConnectionErrorEvent",e,m.Debug),this.privMessage=t,this.privType=i}get message(){return this.privMessage}get type(){return this.privType}}class Ai extends se{constructor(e,t,i){super("ConnectionEstablishErrorEvent",e,m.Error),this.privStatusCode=t,this.privReason=i}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class rt extends se{constructor(e,t,i){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=i}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class Pi extends se{constructor(e,t,i){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=i}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class I extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class K extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class nt extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var S;(function(r){r[r.Text=0]="Text",r[r.Binary=1]="Binary"})(S||(S={}));class st{constructor(e,t,i,n){if(this.privBody=null,e===S.Text&&t&&typeof t!="string")throw new K("Payload must be a string");if(e===S.Binary&&t&&!(t instanceof ArrayBuffer))throw new K("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=i||{},this.privId=n||b(),this.messageType){case S.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case S.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===S.Binary)throw new K("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===S.Text)throw new K("Not supported for text message");return this.privBody}get id(){return this.privId}}class ot{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 nt("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=b();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 N{static setEventSource(e){if(!e)throw new I("eventSource");N.privInstance=e}static get instance(){return N.privInstance}}N.privInstance=new j;var M;(function(r){r[r.None=0]="None",r[r.Connected=1]="Connected",r[r.Connecting=2]="Connecting",r[r.Disconnected=3]="Disconnected"})(M||(M={}));class F{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 F(t)}where(e){this.throwIfDisposed();const t=new F;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 F(i)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,i)=>e(i,t))}clone(){return this.throwIfDisposed(),new F(this.toArray())}concat(e){return this.throwIfDisposed(),new F(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new F(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 nt("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var zt;(function(r){r[r.None=0]="None",r[r.Resolved=1]="Resolved",r[r.Rejected=2]="Rejected"})(zt||(zt={}));class D{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 J(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 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())})},Ce;(function(r){r[r.Dequeue=0]="Dequeue",r[r.Peek=1]="Peek"})(Ce||(Ce={}));class Te{constructor(e){this.privPromiseStore=new F,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new F,this.privDetachables=[],this.privSubscribers=new F,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 D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ce.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ce.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return Nt(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 Nt(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===Ce.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 K(this.privDisposeReason):new nt("Queue");if(this.privIsDisposing)throw new K("Queue disposing")}}class Ne{constructor(e,t,i){if(this.privPayload=null,!t)throw new I("payload");if(e===S.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new K("Payload must be ArrayBuffer");if(e===S.Text&&typeof t!="string")throw new K("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=i||b()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===S.Binary)throw new K("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===S.Text)throw new K("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Ii{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 Mi=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 xt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||b(),this.privReaderQueue=new Te}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 K("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>Mi(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 Te)}throwIfClosed(){if(this.privIsWriteEnded)throw new K("Stream closed")}}var Ee;(function(r){r[r.Success=0]="Success",r[r.Error=1]="Error"})(Ee||(Ee={}));class at extends xt{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 x{static load(e){const t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(e);return n.addEventListener("message",({data:a})=>{if(x.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(x.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 Lr=Object.defineProperty;var Br=(_,L,V)=>L in _?Lr(_,L,{enumerable:!0,configurable:!0,writable:!0,value:V}):_[L]=V;var w=(_,L,V)=>(Br(_,typeof L!="symbol"?L+"":L,V),V);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(x.workerTimers!==null)return x.workerTimers;const t=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(t);return x.workerTimers=x.load(i),x.workerTimers.setTimeout(()=>URL.revokeObjectURL(i),0),x.workerTimers}}static isCallNotification(e){return e.method!==void 0&&e.method==="call"}static isClearResponse(e){return e.error===null&&typeof e.id=="number"}}x.workerTimers=null,x.clearTimeout=r=>x.timers().clearTimeout(r),x.setTimeout=(r,e)=>x.timers().setTimeout(r,e),x.timers=x.loadWorkerTimers();class B extends ne{constructor(e,t,i){super(e,t),this.privSignature=i}}class Di extends B{constructor(e){super("OCSPMemoryCacheHitEvent",m.Debug,e)}}class ki extends B{constructor(e){super("OCSPCacheMissEvent",m.Debug,e)}}class zi extends B{constructor(e){super("OCSPDiskCacheHitEvent",m.Debug,e)}}class Ni extends B{constructor(e){super("OCSPCacheUpdateNeededEvent",m.Debug,e)}}class xi extends B{constructor(e){super("OCSPMemoryCacheStoreEvent",m.Debug,e)}}class Li extends B{constructor(e){super("OCSPDiskCacheStoreEvent",m.Debug,e)}}class Bi extends B{constructor(e){super("OCSPCacheUpdateCompleteEvent",m.Debug,e)}}class Oi extends B{constructor(){super("OCSPStapleReceivedEvent",m.Debug,"")}}class _i extends B{constructor(e,t){super("OCSPCacheEntryExpiredEvent",m.Debug,e),this.privExpireTime=t}}class Hi extends B{constructor(e,t,i){super("OCSPCacheEntryNeedsRefreshEvent",m.Debug,e),this.privExpireTime=i,this.privStartTime=t}}class qi extends B{constructor(e,t,i){super("OCSPCacheHitEvent",m.Debug,e),this.privExpireTime=i,this.privExpireTimeString=new Date(i).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class Ki extends B{constructor(e,t){super("OCSPVerificationFailedEvent",m.Debug,e),this.privError=t}}class Lt extends B{constructor(e,t){super("OCSPCacheFetchErrorEvent",m.Debug,e),this.privError=t}}class Ui extends B{constructor(e){super("OCSPResponseRetrievedEvent",m.Debug,e)}}class Wi extends B{constructor(e,t){super("OCSPCacheUpdateErrorEvent",m.Debug,e),this.privError=t}}class be extends ne{constructor(e){super("BackgroundEvent",m.Error),this.privError=e}get error(){return this.privError}}class l{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(l.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(l.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const i of e)l.throwIfNullOrWhitespace(i,t)}static throwIfFileDoesNotExist(e,t){l.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class E{}E.AuthKey="Ocp-Apim-Subscription-Key",E.ConnectionId="X-ConnectionId",E.ContentType="Content-Type",E.CustomCommandsAppId="X-CommandsAppId",E.Path="Path",E.RequestId="X-RequestId",E.RequestStreamId="X-StreamId",E.RequestTimestamp="X-Timestamp";class ct{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class Bt{constructor(e){if(!e)throw new I("subscriptionKey");this.privAuthInfo=new ct(E.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}const Ot="Authorization";class ue{constructor(e,t){if(!e)throw new I("fetchCallback");if(!t)throw new I("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new ct(Ot,ue.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new ct(Ot,ue.privTokenPrefix+t))}}ue.privTokenPrefix="bearer ";class _t{constructor(e){l.throwIfNullOrUndefined(void 0,`
|
2
|
-
File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){l.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){l.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 v;(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"})(v||(v={}));class xe{static getDefaultInputFormat(){return Z.getDefaultInputFormat()}static getWaveFormat(e,t,i,n){return new Z(e,t,i,n)}static getWaveFormatPCM(e,t,i){return new Z(e,t,i)}}class Z extends xe{constructor(e=16e3,t=16,i=1,n=v.PCM){super();let s=!0;switch(n){case v.PCM:this.formatTag=1;break;case v.ALaw:this.formatTag=6;break;case v.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 Z}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 ht=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 ut{constructor(){}static createPushStream(e){return Ht.create(e)}static createPullStream(e,t){return qt.create(e,t)}}class Ht extends ut{static create(e){return new Vi(e)}}class Vi extends Ht{constructor(e){super(),e===void 0?this.privFormat=Z.getDefaultInputFormat():this.privFormat=e,this.privEvents=new j,this.privId=b(),this.privStream=new at(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 De(this.privId)),this.onEvent(new me(this.privId))}attach(e){return ht(this,void 0,void 0,function*(){this.onEvent(new ye(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new we(this.privId,e)),{detach:()=>ht(this,void 0,void 0,function*(){return this.onEvent(new $(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new $(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:ae.Stream})}onEvent(e){this.privEvents.onEvent(e),N.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 ut{constructor(){super()}static create(e,t){return new Kt(e,t)}}class Kt extends qt{constructor(e,t){super(),t===void 0?this.privFormat=xe.getDefaultInputFormat():this.privFormat=t,this.privEvents=new j,this.privId=b(),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 De(this.privId)),this.onEvent(new me(this.privId))}attach(e){return ht(this,void 0,void 0,function*(){return this.onEvent(new ye(this.privId,e)),yield this.turnOn(),this.onEvent(new we(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new $(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 $(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:ae.Stream})}onEvent(e){this.privEvents.onEvent(e),N.instance.onEvent(e)}}var g;(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"})(g||(g={}));class f extends Z{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?f.getDefaultOutputFormat():f.fromSpeechSynthesisOutputFormatString(f.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new f(v.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new f(v.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new f(v.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new f(v.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new f(v.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new f(v.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new f(v.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new f(v.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new f(v.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new f(v.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new f(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new f(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new f(v.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new f(v.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new f(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new f(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new f(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new f(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new f(v.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new f(v.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new f(v.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new f(v.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new f(v.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new f(v.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new f(v.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new f(v.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new f(v.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new f(v.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new f(v.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new f(v.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new f(v.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new f(v.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new f(v.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new f(v.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new f(v.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new f(v.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return f.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}}f.SpeechSynthesisOutputFormatToString={[g.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[g.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[g.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[g.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[g.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[g.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[g.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[g.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[g.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[g.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[g.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[g.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[g.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[g.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[g.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[g.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[g.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[g.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[g.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[g.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[g.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[g.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[g.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[g.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[g.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[g.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[g.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[g.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[g.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[g.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[g.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[g.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[g.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[g.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[g.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[g.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[g.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var ji=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 Ut{constructor(){}static createPullStream(){return Le.create()}}class Le extends Ut{static create(){return new pt}}class pt extends Le{constructor(){super(),this.privId=b(),this.privStream=new xt}set format(e){e==null&&(this.privFormat=f.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return ji(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){l.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class Wt extends Ut{constructor(){super()}static create(e){return new dt(e)}}class dt extends Wt{constructor(e){super(),this.privId=b(),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 Y{static fromDefaultMicrophoneInput(){const e=new At(!0);return new pe(new W(e))}static fromMicrophoneInput(e){const t=new At(!0);return new pe(new W(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new pe(new Er(e,t))}static fromStreamInput(e){if(e instanceof Fi)return new pe(new Kt(e));if(e instanceof ut)return new pe(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new At(!1);return new pe(new W(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new de(new mt)}static fromSpeakerOutput(e){if(e===void 0)return Y.fromDefaultSpeakerOutput();if(e instanceof mt)return new de(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new de(new _t(e))}static fromStreamOutput(e){if(e instanceof Vt)return new de(new dt(e));if(e instanceof Wt)return new de(e);if(e instanceof Le)return new de(e);throw new Error("Not Supported Type")}}class pe extends Y{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(l.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 de extends Y{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 H;(function(r){r[r.Error=0]="Error",r[r.EndOfStream=1]="EndOfStream"})(H||(H={}));class Fi{}class Vt{}class ve{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}class vt extends ve{constructor(e,t){super(t),this.privOffset=e}get offset(){return this.privOffset}}var ee;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(ee||(ee={}));class Gi{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 $i extends Gi{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 jt extends vt{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}class Ft extends ve{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}class lt extends $i{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 Gt{constructor(e,t){this.privReason=e,this.privAudio=t}get audio(){return this.privAudio}get reason(){return this.privReason}}var A;(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"})(A||(A={}));class ft{constructor(){}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new le;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.setProperty(p.SpeechServiceConnection_Key,e),i}static fromEndpoint(e,t){l.throwIfNull(e,"endpoint");const i=new le;return i.setProperty(p.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromHost(e,t){l.throwIfNull(e,"hostName");const i=new le;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){l.throwIfNull(e,"authorizationToken"),l.throwIfNullOrWhitespace(t,"region");const i=new le;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.authorizationToken=e,i}close(){}}class le extends ft{constructor(){super(),this.privProperties=new U,this.speechRecognitionLanguage="en-US",this.outputFormat=ee.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 ee[this.privProperties.getProperty(Xe,void 0)]}set outputFormat(e){this.privProperties.setProperty(Xe,ee[e])}get endpointId(){return this.privProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){l.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(Ie,"{}"));i[e]=t,this.privProperties.setProperty(Ie,JSON.stringify(i))}setProfanity(e){this.privProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,He[e])}enableAudioLogging(){this.privProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(vi,"true")}clone(){const e=new le;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 g[this.privProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,g[e])}}class $t extends ft{constructor(){super()}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new Be;return i.properties.setProperty(p.SpeechServiceConnection_Key,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromAuthorizationToken(e,t){l.throwIfNullOrWhitespace(e,"authorizationToken"),l.throwIfNullOrWhitespace(t,"region");const i=new Be;return i.properties.setProperty(p.SpeechServiceAuthorization_Token,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromHost(e,t){l.throwIfNull(e,"hostName");const i=new Be;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){l.throwIfNull(e,"endpoint"),l.throwIfNull(t,"subscriptionKey");const i=new Be;return i.properties.setProperty(p.SpeechServiceConnection_Endpoint,e.href),i.properties.setProperty(p.SpeechServiceConnection_Key,t),i}}class Be extends $t{constructor(){super(),this.privSpeechProperties=new U,this.outputFormat=ee.Simple}set authorizationToken(e){l.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceAuthorization_Token,e)}set speechRecognitionLanguage(e){l.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 ee[this.privSpeechProperties.getProperty(Xe,void 0)]}set outputFormat(e){this.privSpeechProperties.setProperty(Xe,ee[e])}get endpointId(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}addTargetLanguage(e){l.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){l.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(Ie,"{}"));i[e]=t,this.privSpeechProperties.setProperty(Ie,JSON.stringify(i))}setProfanity(e){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,He[e])}enableAudioLogging(){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privSpeechProperties.setProperty(vi,"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 g[this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,g[e])}}class U{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 U;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 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 gt{constructor(e,t,i){this.audioConfig=e!==void 0?e:Y.fromDefaultMicrophoneInput(),this.privDisposed=!1,this.privProperties=t.clone(),this.privConnectionFactory=i,this.implCommonRecognizerSetup()}close(e,t){l.throwIfDisposed(this.privDisposed),J(this.dispose(!0),e,t)}get internalData(){return this.privReco}dispose(e){return Re(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 G.telemetryDataEnabled}static enableTelemetry(e){G.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 Fe(new Ge(new ai(e,t,i))));this.privReco=this.createServiceRecognizer(gt.getAuthFromProperties(this.privProperties),this.privConnectionFactory,this.audioConfig,n)}recognizeOnceAsyncImpl(e){return Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed);const t=new D;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 Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop(),yield this.privReco.recognize(e,void 0,void 0)})}stopContinuousRecognitionAsyncImpl(){return Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop()})}implRecognizerStop(){return Re(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 Bt(t):new ue(()=>{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 Jt{constructor(e){this.privConnectionMessage=e,this.privProperties=new U,this.privConnectionMessage.headers[E.ConnectionId]&&this.privProperties.setProperty(p.Speech_SessionId,this.privConnectionMessage.headers[E.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===S.Text}get isBinaryMessage(){return this.privConnectionMessage.messageType===S.Binary}get TextMessage(){return this.privConnectionMessage.textBody}get binaryMessage(){return this.privConnectionMessage.binaryBody}get properties(){return this.privProperties}toString(){return""}}class Oe{static fromRecognizer(e){const t=e.internalData,i=new Oe;return i.privInternalData=t,i.setupEvents(),i}static fromSynthesizer(e){const t=e.internalData,i=new Oe;return i.privInternalData=t,i.setupEvents(),i}openConnection(e,t){J(this.privInternalData.connect(),e,t)}closeConnection(e,t){if(this.privInternalData instanceof re)throw new Error("Disconnecting a synthesizer's connection is currently not supported");J(this.privInternalData.disconnect(),e,t)}setMessageProperty(e,t,i){if(l.throwIfNullOrWhitespace(t,"propertyName"),this.privInternalData instanceof G){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 re){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){J(this.privInternalData.sendNetworkMessage(e,t),i,n)}close(){}setupEvents(){this.privEventListener=this.privInternalData.connectionEvents.attach(e=>{e.name==="ConnectionEstablishedEvent"?this.connected&&this.connected(new Zt(e.connectionId)):e.name==="ConnectionClosedEvent"?this.disconnected&&this.disconnected(new Zt(e.connectionId)):e.name==="ConnectionMessageSentEvent"?this.messageSent&&this.messageSent(new Yt(new Jt(e.message))):e.name==="ConnectionMessageReceivedEvent"&&this.messageReceived&&this.messageReceived(new Yt(new Jt(e.message)))}),this.privServiceEventListener=this.privInternalData.serviceEvents.attach(e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new Xi(e.jsonString,e.name))})}}var Qt=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 Ji extends gt{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),super(t,i.properties,new cr),this.privDisposedTranslationRecognizer=!1,this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice),p[p.SpeechServiceConnection_TranslationVoice]),l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages),p[p.SpeechServiceConnection_TranslationToLanguages]),l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage),p[p.SpeechServiceConnection_RecoLanguage])}get speechRecognitionLanguage(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage)}get targetLanguages(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(",")}get voiceName(){return l.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){l.throwIfDisposed(this.privDisposedTranslationRecognizer),J(this.recognizeOnceAsyncImpl(oe.Conversation),e,t)}startContinuousRecognitionAsync(e,t){J(this.startContinuousRecognitionAsyncImpl(oe.Conversation),e,t)}stopContinuousRecognitionAsync(e,t){J(this.stopContinuousRecognitionAsyncImpl(),e,t)}removeTargetLanguage(e){if(l.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){l.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){l.throwIfDisposed(this.privDisposedTranslationRecognizer),J(this.dispose(!0),e,t)}onConnection(){}onDisconnection(){return Qt(this,void 0,void 0,function*(){})}dispose(e){const t=Object.create(null,{dispose:{get:()=>super.dispose}});return Qt(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 or(e,this.properties)}createServiceRecognizer(e,t,i,n){const s=i;return new ur(e,t,s,n,this)}updateLanguages(e){const t=Oe.fromRecognizer(this);t&&(t.setMessageProperty("speech.context","translationcontext",{to:e}),t.sendMessageAsync("event",JSON.stringify({id:"translation",name:"updateLanguage",to:e})))}}class Qi{constructor(){this.privMap=new U}get languages(){return this.privMap.keys}get(e,t){return this.privMap.getProperty(e,t)}set(e,t){this.privMap.setProperty(e,t)}}class Xt{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 R;(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"})(R||(R={}));class Zt extends ve{}class Xi extends ve{constructor(e,t,i){super(i),this.privJsonResult=e,this.privEventName=t}get jsonString(){return this.privJsonResult}get eventName(){return this.privEventName}}class y{}y.BotId="botid",y.CustomSpeechDeploymentId="cid",y.CustomVoiceDeploymentId="deploymentId",y.EnableAudioLogging="storeAudio",y.EnableLanguageId="lidEnabled",y.EnableWordLevelTimestamps="wordLevelTimestamps",y.EndSilenceTimeoutMs="endSilenceTimeoutMs",y.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",y.Format="format",y.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",y.Language="language",y.Profanity="profanity",y.RequestBotStatusMessages="enableBotMessageStatus",y.StableIntermediateThreshold="stableIntermediateThreshold",y.StableTranslation="stableTranslation",y.TestHooks="testhooks",y.Postprocessing="postprocessing";class _e{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,y.SegmentationSilenceTimeoutMs],[p.SpeechServiceConnection_EnableAudioLogging,y.EnableAudioLogging],[p.SpeechServiceConnection_EndSilenceTimeoutMs,y.EndSilenceTimeoutMs],[p.SpeechServiceConnection_InitialSilenceTimeoutMs,y.InitialSilenceTimeoutMs],[p.SpeechServiceResponse_PostProcessingOption,y.Postprocessing],[p.SpeechServiceResponse_ProfanityOption,y.Profanity],[p.SpeechServiceResponse_RequestWordLevelTimestamps,y.EnableWordLevelTimestamps],[p.SpeechServiceResponse_StablePartialResultThreshold,y.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,i)});const s=JSON.parse(e.parameters.getProperty(Ie,"{}"));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 He;(function(r){r[r.Masked=0]="Masked",r[r.Removed=1]="Removed",r[r.Raw=2]="Raw"})(He||(He={}));class Yt{constructor(e){this.privConnectionMessage=e}get message(){return this.privConnectionMessage}toString(){return"Message: "+this.privConnectionMessage.toString()}}var qe=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 Ke{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:Y.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=i.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new hr,this.synthesisRequestQueue=new Te,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){l.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(p.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages)===Cr}static FromConfig(e,t,i){const n=e;return t.properties.mergeTo(n.properties),new Ke(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=Ke.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 qe(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){l.throwIfDisposed(this.privDisposed),J(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return qe(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new yr(e,this.privProperties)}createSynthesisAdapter(e,t,i,n){return new re(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 Fe(new Ge(new ai(e,t,i)))),s=this.privProperties.getProperty(p.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new Bt(s):new ue(()=>{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=f.fromSpeechSynthesisOutputFormat(g[this.properties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new mr(n)}speakImpl(e,t,i,n,s){try{l.throwIfDisposed(this.privDisposed);const o=b();let a;s instanceof Vt?a=new dt(s):s instanceof Le?a=s:s!==void 0?a=new _t(s):a=void 0,this.synthesisRequestQueue.enqueue(new Zi(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 qe(this,void 0,void 0,function*(){const t=b(),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 ti(t,n,void 0)}else return new ti(t,void 0,`Error: ${i.status}: ${i.statusText}`)})}adapterSpeak(){return qe(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 Zi{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 ei{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 Ue extends ei{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 We{constructor(e){this.privResult=e}get result(){return this.privResult}}class Yi{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 er{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class tr{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 ti extends ei{constructor(e,t,i){if(Array.isArray(t)){super(e,A.VoicesListRetrieved,void 0,new U),this.privVoices=[];for(const n of t)this.privVoices.push(new ir(n))}else super(e,A.Canceled,i||"Error information unavailable",new U)}get voices(){return this.privVoices}}var Ae;(function(r){r[r.Unknown=0]="Unknown",r[r.Female=1]="Female",r[r.Male=2]="Male"})(Ae||(Ae={}));var Ve;(function(r){r[r.OnlineNeural=1]="OnlineNeural",r[r.OnlineStandard=2]="OnlineStandard",r[r.OfflineNeural=3]="OfflineNeural",r[r.OfflineStandard=4]="OfflineStandard"})(Ve||(Ve={}));class ir{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")?Ve.OnlineStandard:Ve.OnlineNeural,this.privGender=e.Gender==="Male"?Ae.Male:e.Gender==="Female"?Ae.Female:Ae.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 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 rr=60*30,ii={[v.PCM]:"audio/wav",[v.MuLaw]:"audio/x-wav",[v.MP3]:"audio/mpeg",[v.OGG_OPUS]:"audio/ogg",[v.WEBM_OPUS]:"audio/webm; codecs=opus",[v.ALaw]:"audio/x-wav",[v.FLAC]:"audio/flac"};class mt{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||b(),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===v.PCM||this.privFormat.formatTag===v.MuLaw||this.privFormat.formatTag===v.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=re.addHeader(i,this.privFormat);const n=new Blob([i],{type:ii[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=ii[this.privFormat.formatTag];t===void 0?console.warn(`Unknown mimeType for format ${v[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=rr,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(i=>{N.instance.onEvent(new be(i))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(i=>{N.instance.onEvent(new be(i))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(i=>{N.instance.onEvent(new be(i))})):(console.warn(`Format ${v[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new pt,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 St(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 St(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return St(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 je extends ne{constructor(e,t,i,n=m.Info){super(e,n),this.privRequestId=t,this.privSessionId=i}get requestId(){return this.privRequestId}get sessionId(){return this.privSessionId}}class ri extends je{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 nr extends je{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 ni extends je{constructor(e,t,i){super("ConnectingToServiceEvent",e,i),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}}class sr extends je{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 O extends st{constructor(e,t,i,n,s,o,a,u){if(!t)throw new I("path");if(!i)throw new I("requestId");const h={};if(h[E.Path]=t,h[E.RequestId]=i,h[E.RequestTimestamp]=new Date().toISOString(),n&&(h[E.ContentType]=n),o&&(h[E.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()===E.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===E.RequestId.toLowerCase()?i=e.headers[a]:a.toLowerCase()===E.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===E.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new O(e.messageType,t,i,n,e.body,s,o,e.id)}}var k=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 G{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 I("authentication");if(!t)throw new I("connectionFactory");if(!i)throw new I("audioSource");if(!n)throw new I("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 dr(this.privAudioSource.id()),this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privDynamicGrammar=new lr,this.privSpeechContext=new vr(this.privDynamicGrammar),this.privAgentConfig=new pi,typeof Blob!="undefined"&&typeof Worker!="undefined"&&(this.privSetTimeout=x.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(H.Error,a.statusCode===1007?R.BadRequestParameters:R.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 k(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 k(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===ae.Microphones,s=new Rr(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(H.Error,R.ConnectionFailure,u);return}const o=new ve(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,o),this.receiveMessage(),this.sendAudio(s).catch(u=>k(this,void 0,void 0,function*(){yield this.cancelRecognitionLocal(H.Error,R.RuntimeError,u)}))})}stopRecognizing(){return k(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 k(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 k(this,void 0,void 0,function*(){if(yield this.cancelRecognitionLocal(H.Error,R.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 k(this,void 0,void 0,function*(){const i=typeof t=="string"?S.Text:S.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new O(i,e,this.privRequestSession.requestId,n,t))})}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}sendTelemetryData(){return k(this,void 0,void 0,function*(){const e=this.privRequestSession.getTelemetry();if(G.telemetryDataEnabled!==!0||this.privIsDisposed||e===null)return;if(G.telemetryData)try{G.telemetryData(e)}catch{}yield(yield this.fetchConnection()).send(new O(S.Text,"telemetry",this.privRequestSession.requestId,"application/json",e))})}cancelRecognitionLocal(e,t,i){return k(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 k(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=O.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=Je.fromJSON(i.textBody),s=new vt(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=Je.fromJSON(o);this.privRecognizerConfig.isContinuousRecognition&&this.privRequestSession.onServiceRecognized(a.Offset+this.privRequestSession.currentTurnAudioOffset);const u=new vt(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(H.EndOfStream,R.NoError,void 0));const h=new ve(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 Mt(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 O(S.Text,"speech.context",this.privRequestSession.requestId,"application/json",i))}sendPrePayloadJSON(e,t=!0){return k(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 k(this,void 0,void 0,function*(){const t=yield this.audioSource.format;return e.send(new O(S.Binary,"audio",this.privRequestSession.requestId,"audio/x-wav",t.header))})}connectImpl(){return this.privConnectionPromise!==void 0?this.privConnectionPromise.then(e=>e.state()===M.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(),G.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 O(S.Text,"speech.config",t.requestId,"application/json",i))}fetchConnection(){return k(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===M.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 k(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=()=>k(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 O(S.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 k(this,void 0,void 0,function*(){let e=!1;this.privAuthFetchEventId=b();const t=this.privRequestSession.sessionId;this.privConnectionId=t!==void 0?t:b(),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
|
1
|
+
(function(_,L){typeof exports=="object"&&typeof module!="undefined"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(_=typeof globalThis!="undefined"?globalThis:_||self,L(_.CreativeOrangeAzureTextToSpeech={}))})(this,function(_){"use strict";var L={},V,Si=new Uint8Array(16);function mi(){if(!V&&(V=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!V))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return V(Si)}var yi=/^(?:[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 wi(r){return typeof r=="string"&&yi.test(r)}for(var z=[],tt=0;tt<256;++tt)z.push((tt+256).toString(16).substr(1));function Ci(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(z[r[e+0]]+z[r[e+1]]+z[r[e+2]]+z[r[e+3]]+"-"+z[r[e+4]]+z[r[e+5]]+"-"+z[r[e+6]]+z[r[e+7]]+"-"+z[r[e+8]]+z[r[e+9]]+"-"+z[r[e+10]]+z[r[e+11]]+z[r[e+12]]+z[r[e+13]]+z[r[e+14]]+z[r[e+15]]).toLowerCase();if(!wi(t))throw TypeError("Stringified UUID is invalid");return t}function Ti(r,e,t){r=r||{};var i=r.random||(r.rng||mi)();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 Ci(i)}const Ei=()=>Ti(),b=()=>Ei().replace(new RegExp("-","g"),"").toUpperCase();var y;(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"})(y||(y={}));class ne{constructor(e,t){this.privName=e,this.privEventId=b(),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 Se extends ne{constructor(e,t,i=y.Info){super(e,i),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class De extends Se{constructor(e){super("AudioSourceInitializingEvent",e)}}class me extends Se{constructor(e){super("AudioSourceReadyEvent",e)}}class It extends Se{constructor(e){super("AudioSourceOffEvent",e)}}class ke extends Se{constructor(e,t){super("AudioSourceErrorEvent",e,y.Error),this.privError=t}get error(){return this.privError}}class ze extends Se{constructor(e,t,i){super(e,t),this.privAudioNodeId=i}get audioNodeId(){return this.privAudioNodeId}}class ye extends ze{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class we extends ze{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class $ extends ze{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class it extends ze{constructor(e,t,i){super("AudioStreamNodeErrorEvent",e,t),this.privError=i}get error(){return this.privError}}class Mt extends ne{constructor(e,t,i=y.Info){super(e,i),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class se extends ne{constructor(e,t,i=y.Info){super(e,i),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class Dt extends se{constructor(e,t,i){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=i}get uri(){return this.privUri}get headers(){return this.privHeaders}}class kt extends se{constructor(e){super("ConnectionEstablishedEvent",e)}}class bi extends se{constructor(e,t,i){super("ConnectionClosedEvent",e,y.Debug),this.privReason=i,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class Ri extends se{constructor(e,t,i){super("ConnectionErrorEvent",e,y.Debug),this.privMessage=t,this.privType=i}get message(){return this.privMessage}get type(){return this.privType}}class Ai extends se{constructor(e,t,i){super("ConnectionEstablishErrorEvent",e,y.Error),this.privStatusCode=t,this.privReason=i}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class rt extends se{constructor(e,t,i){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=i}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class Pi extends se{constructor(e,t,i){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=i}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class I extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class K extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class nt extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var S;(function(r){r[r.Text=0]="Text",r[r.Binary=1]="Binary"})(S||(S={}));class st{constructor(e,t,i,n){if(this.privBody=null,e===S.Text&&t&&typeof t!="string")throw new K("Payload must be a string");if(e===S.Binary&&t&&!(t instanceof ArrayBuffer))throw new K("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=i||{},this.privId=n||b(),this.messageType){case S.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case S.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===S.Binary)throw new K("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===S.Text)throw new K("Not supported for text message");return this.privBody}get id(){return this.privId}}class ot{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 nt("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=b();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 N{static setEventSource(e){if(!e)throw new I("eventSource");N.privInstance=e}static get instance(){return N.privInstance}}N.privInstance=new j;var M;(function(r){r[r.None=0]="None",r[r.Connected=1]="Connected",r[r.Connecting=2]="Connecting",r[r.Disconnected=3]="Disconnected"})(M||(M={}));class F{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 F(t)}where(e){this.throwIfDisposed();const t=new F;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 F(i)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,i)=>e(i,t))}clone(){return this.throwIfDisposed(),new F(this.toArray())}concat(e){return this.throwIfDisposed(),new F(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new F(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 nt("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var zt;(function(r){r[r.None=0]="None",r[r.Resolved=1]="Resolved",r[r.Rejected=2]="Rejected"})(zt||(zt={}));class D{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 J(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 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())})},Ce;(function(r){r[r.Dequeue=0]="Dequeue",r[r.Peek=1]="Peek"})(Ce||(Ce={}));class Te{constructor(e){this.privPromiseStore=new F,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new F,this.privDetachables=[],this.privSubscribers=new F,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 D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ce.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:Ce.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return Nt(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 Nt(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===Ce.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 K(this.privDisposeReason):new nt("Queue");if(this.privIsDisposing)throw new K("Queue disposing")}}class Ne{constructor(e,t,i){if(this.privPayload=null,!t)throw new I("payload");if(e===S.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new K("Payload must be ArrayBuffer");if(e===S.Text&&typeof t!="string")throw new K("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=i||b()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===S.Binary)throw new K("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===S.Text)throw new K("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Ii{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 Mi=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 xt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||b(),this.privReaderQueue=new Te}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 K("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>Mi(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 Te)}throwIfClosed(){if(this.privIsWriteEnded)throw new K("Stream closed")}}var Ee;(function(r){r[r.Success=0]="Success",r[r.Error=1]="Error"})(Ee||(Ee={}));class at extends xt{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 x{static load(e){const t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(e);return n.addEventListener("message",({data:a})=>{if(x.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(x.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 Lr=Object.defineProperty;var Br=(_,L,V)=>L in _?Lr(_,L,{enumerable:!0,configurable:!0,writable:!0,value:V}):_[L]=V;var m=(_,L,V)=>(Br(_,typeof L!="symbol"?L+"":L,V),V);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(x.workerTimers!==null)return x.workerTimers;const t=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(t);return x.workerTimers=x.load(i),x.workerTimers.setTimeout(()=>URL.revokeObjectURL(i),0),x.workerTimers}}static isCallNotification(e){return e.method!==void 0&&e.method==="call"}static isClearResponse(e){return e.error===null&&typeof e.id=="number"}}x.workerTimers=null,x.clearTimeout=r=>x.timers().clearTimeout(r),x.setTimeout=(r,e)=>x.timers().setTimeout(r,e),x.timers=x.loadWorkerTimers();class B extends ne{constructor(e,t,i){super(e,t),this.privSignature=i}}class Di extends B{constructor(e){super("OCSPMemoryCacheHitEvent",y.Debug,e)}}class ki extends B{constructor(e){super("OCSPCacheMissEvent",y.Debug,e)}}class zi extends B{constructor(e){super("OCSPDiskCacheHitEvent",y.Debug,e)}}class Ni extends B{constructor(e){super("OCSPCacheUpdateNeededEvent",y.Debug,e)}}class xi extends B{constructor(e){super("OCSPMemoryCacheStoreEvent",y.Debug,e)}}class Li extends B{constructor(e){super("OCSPDiskCacheStoreEvent",y.Debug,e)}}class Bi extends B{constructor(e){super("OCSPCacheUpdateCompleteEvent",y.Debug,e)}}class Oi extends B{constructor(){super("OCSPStapleReceivedEvent",y.Debug,"")}}class _i extends B{constructor(e,t){super("OCSPCacheEntryExpiredEvent",y.Debug,e),this.privExpireTime=t}}class Hi extends B{constructor(e,t,i){super("OCSPCacheEntryNeedsRefreshEvent",y.Debug,e),this.privExpireTime=i,this.privStartTime=t}}class qi extends B{constructor(e,t,i){super("OCSPCacheHitEvent",y.Debug,e),this.privExpireTime=i,this.privExpireTimeString=new Date(i).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class Ki extends B{constructor(e,t){super("OCSPVerificationFailedEvent",y.Debug,e),this.privError=t}}class Lt extends B{constructor(e,t){super("OCSPCacheFetchErrorEvent",y.Debug,e),this.privError=t}}class Ui extends B{constructor(e){super("OCSPResponseRetrievedEvent",y.Debug,e)}}class Wi extends B{constructor(e,t){super("OCSPCacheUpdateErrorEvent",y.Debug,e),this.privError=t}}class be extends ne{constructor(e){super("BackgroundEvent",y.Error),this.privError=e}get error(){return this.privError}}class l{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(l.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(l.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const i of e)l.throwIfNullOrWhitespace(i,t)}static throwIfFileDoesNotExist(e,t){l.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class E{}E.AuthKey="Ocp-Apim-Subscription-Key",E.ConnectionId="X-ConnectionId",E.ContentType="Content-Type",E.CustomCommandsAppId="X-CommandsAppId",E.Path="Path",E.RequestId="X-RequestId",E.RequestStreamId="X-StreamId",E.RequestTimestamp="X-Timestamp";class ct{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class Bt{constructor(e){if(!e)throw new I("subscriptionKey");this.privAuthInfo=new ct(E.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}const Ot="Authorization";class ue{constructor(e,t){if(!e)throw new I("fetchCallback");if(!t)throw new I("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new ct(Ot,ue.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new ct(Ot,ue.privTokenPrefix+t))}}ue.privTokenPrefix="bearer ";class _t{constructor(e){l.throwIfNullOrUndefined(void 0,`
|
2
|
+
File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){l.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){l.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 v;(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"})(v||(v={}));class xe{static getDefaultInputFormat(){return Z.getDefaultInputFormat()}static getWaveFormat(e,t,i,n){return new Z(e,t,i,n)}static getWaveFormatPCM(e,t,i){return new Z(e,t,i)}}class Z extends xe{constructor(e=16e3,t=16,i=1,n=v.PCM){super();let s=!0;switch(n){case v.PCM:this.formatTag=1;break;case v.ALaw:this.formatTag=6;break;case v.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 Z}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 ht=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 ut{constructor(){}static createPushStream(e){return Ht.create(e)}static createPullStream(e,t){return qt.create(e,t)}}class Ht extends ut{static create(e){return new Vi(e)}}class Vi extends Ht{constructor(e){super(),e===void 0?this.privFormat=Z.getDefaultInputFormat():this.privFormat=e,this.privEvents=new j,this.privId=b(),this.privStream=new at(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 De(this.privId)),this.onEvent(new me(this.privId))}attach(e){return ht(this,void 0,void 0,function*(){this.onEvent(new ye(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new we(this.privId,e)),{detach:()=>ht(this,void 0,void 0,function*(){return this.onEvent(new $(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new $(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:ae.Stream})}onEvent(e){this.privEvents.onEvent(e),N.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 ut{constructor(){super()}static create(e,t){return new Kt(e,t)}}class Kt extends qt{constructor(e,t){super(),t===void 0?this.privFormat=xe.getDefaultInputFormat():this.privFormat=t,this.privEvents=new j,this.privId=b(),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 De(this.privId)),this.onEvent(new me(this.privId))}attach(e){return ht(this,void 0,void 0,function*(){return this.onEvent(new ye(this.privId,e)),yield this.turnOn(),this.onEvent(new we(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new $(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 $(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:ae.Stream})}onEvent(e){this.privEvents.onEvent(e),N.instance.onEvent(e)}}var g;(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"})(g||(g={}));class f extends Z{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?f.getDefaultOutputFormat():f.fromSpeechSynthesisOutputFormatString(f.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new f(v.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new f(v.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new f(v.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new f(v.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new f(v.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new f(v.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new f(v.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new f(v.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new f(v.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new f(v.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new f(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new f(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new f(v.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new f(v.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new f(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new f(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new f(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new f(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new f(v.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new f(v.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new f(v.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new f(v.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new f(v.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new f(v.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new f(v.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new f(v.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new f(v.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new f(v.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new f(v.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new f(v.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new f(v.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new f(v.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new f(v.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new f(v.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new f(v.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new f(v.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new f(v.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return f.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}}f.SpeechSynthesisOutputFormatToString={[g.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[g.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[g.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[g.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[g.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[g.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[g.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[g.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[g.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[g.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[g.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[g.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[g.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[g.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[g.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[g.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[g.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[g.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[g.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[g.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[g.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[g.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[g.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[g.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[g.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[g.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[g.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[g.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[g.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[g.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[g.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[g.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[g.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[g.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[g.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[g.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[g.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var ji=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 Ut{constructor(){}static createPullStream(){return Le.create()}}class Le extends Ut{static create(){return new pt}}class pt extends Le{constructor(){super(),this.privId=b(),this.privStream=new xt}set format(e){e==null&&(this.privFormat=f.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return ji(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){l.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class Wt extends Ut{constructor(){super()}static create(e){return new dt(e)}}class dt extends Wt{constructor(e){super(),this.privId=b(),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 Y{static fromDefaultMicrophoneInput(){const e=new At(!0);return new pe(new W(e))}static fromMicrophoneInput(e){const t=new At(!0);return new pe(new W(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new pe(new Er(e,t))}static fromStreamInput(e){if(e instanceof Fi)return new pe(new Kt(e));if(e instanceof ut)return new pe(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new At(!1);return new pe(new W(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new de(new mt)}static fromSpeakerOutput(e){if(e===void 0)return Y.fromDefaultSpeakerOutput();if(e instanceof mt)return new de(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new de(new _t(e))}static fromStreamOutput(e){if(e instanceof Vt)return new de(new dt(e));if(e instanceof Wt)return new de(e);if(e instanceof Le)return new de(e);throw new Error("Not Supported Type")}}class pe extends Y{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(l.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 de extends Y{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 H;(function(r){r[r.Error=0]="Error",r[r.EndOfStream=1]="EndOfStream"})(H||(H={}));class Fi{}class Vt{}class ve{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}class vt extends ve{constructor(e,t){super(t),this.privOffset=e}get offset(){return this.privOffset}}var ee;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(ee||(ee={}));class Gi{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 $i extends Gi{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 jt extends vt{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}class Ft extends ve{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}class lt extends $i{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 Gt{constructor(e,t){this.privReason=e,this.privAudio=t}get audio(){return this.privAudio}get reason(){return this.privReason}}var A;(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"})(A||(A={}));class ft{constructor(){}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new le;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.setProperty(p.SpeechServiceConnection_Key,e),i}static fromEndpoint(e,t){l.throwIfNull(e,"endpoint");const i=new le;return i.setProperty(p.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&i.setProperty(p.SpeechServiceConnection_Key,t),i}static fromHost(e,t){l.throwIfNull(e,"hostName");const i=new le;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){l.throwIfNull(e,"authorizationToken"),l.throwIfNullOrWhitespace(t,"region");const i=new le;return i.setProperty(p.SpeechServiceConnection_Region,t),i.setProperty(p.SpeechServiceConnection_IntentRegion,t),i.authorizationToken=e,i}close(){}}class le extends ft{constructor(){super(),this.privProperties=new U,this.speechRecognitionLanguage="en-US",this.outputFormat=ee.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 ee[this.privProperties.getProperty(Xe,void 0)]}set outputFormat(e){this.privProperties.setProperty(Xe,ee[e])}get endpointId(){return this.privProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){l.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(Ie,"{}"));i[e]=t,this.privProperties.setProperty(Ie,JSON.stringify(i))}setProfanity(e){this.privProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,He[e])}enableAudioLogging(){this.privProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(vi,"true")}clone(){const e=new le;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 g[this.privProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,g[e])}}class $t extends ft{constructor(){super()}static fromSubscription(e,t){l.throwIfNullOrWhitespace(e,"subscriptionKey"),l.throwIfNullOrWhitespace(t,"region");const i=new Be;return i.properties.setProperty(p.SpeechServiceConnection_Key,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromAuthorizationToken(e,t){l.throwIfNullOrWhitespace(e,"authorizationToken"),l.throwIfNullOrWhitespace(t,"region");const i=new Be;return i.properties.setProperty(p.SpeechServiceAuthorization_Token,e),i.properties.setProperty(p.SpeechServiceConnection_Region,t),i}static fromHost(e,t){l.throwIfNull(e,"hostName");const i=new Be;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){l.throwIfNull(e,"endpoint"),l.throwIfNull(t,"subscriptionKey");const i=new Be;return i.properties.setProperty(p.SpeechServiceConnection_Endpoint,e.href),i.properties.setProperty(p.SpeechServiceConnection_Key,t),i}}class Be extends $t{constructor(){super(),this.privSpeechProperties=new U,this.outputFormat=ee.Simple}set authorizationToken(e){l.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(p.SpeechServiceAuthorization_Token,e)}set speechRecognitionLanguage(e){l.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 ee[this.privSpeechProperties.getProperty(Xe,void 0)]}set outputFormat(e){this.privSpeechProperties.setProperty(Xe,ee[e])}get endpointId(){return this.privSpeechProperties.getProperty(p.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EndpointId,e)}addTargetLanguage(e){l.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){l.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(Ie,"{}"));i[e]=t,this.privSpeechProperties.setProperty(Ie,JSON.stringify(i))}setProfanity(e){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_ProfanityOption,He[e])}enableAudioLogging(){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privSpeechProperties.setProperty(p.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privSpeechProperties.setProperty(vi,"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 g[this.privSpeechProperties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privSpeechProperties.setProperty(p.SpeechServiceConnection_SynthOutputFormat,g[e])}}class U{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 U;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 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 gt{constructor(e,t,i){this.audioConfig=e!==void 0?e:Y.fromDefaultMicrophoneInput(),this.privDisposed=!1,this.privProperties=t.clone(),this.privConnectionFactory=i,this.implCommonRecognizerSetup()}close(e,t){l.throwIfDisposed(this.privDisposed),J(this.dispose(!0),e,t)}get internalData(){return this.privReco}dispose(e){return Re(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 G.telemetryDataEnabled}static enableTelemetry(e){G.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 Fe(new Ge(new ai(e,t,i))));this.privReco=this.createServiceRecognizer(gt.getAuthFromProperties(this.privProperties),this.privConnectionFactory,this.audioConfig,n)}recognizeOnceAsyncImpl(e){return Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed);const t=new D;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 Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop(),yield this.privReco.recognize(e,void 0,void 0)})}stopContinuousRecognitionAsyncImpl(){return Re(this,void 0,void 0,function*(){l.throwIfDisposed(this.privDisposed),yield this.implRecognizerStop()})}implRecognizerStop(){return Re(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 Bt(t):new ue(()=>{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 Jt{constructor(e){this.privConnectionMessage=e,this.privProperties=new U,this.privConnectionMessage.headers[E.ConnectionId]&&this.privProperties.setProperty(p.Speech_SessionId,this.privConnectionMessage.headers[E.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===S.Text}get isBinaryMessage(){return this.privConnectionMessage.messageType===S.Binary}get TextMessage(){return this.privConnectionMessage.textBody}get binaryMessage(){return this.privConnectionMessage.binaryBody}get properties(){return this.privProperties}toString(){return""}}class Oe{static fromRecognizer(e){const t=e.internalData,i=new Oe;return i.privInternalData=t,i.setupEvents(),i}static fromSynthesizer(e){const t=e.internalData,i=new Oe;return i.privInternalData=t,i.setupEvents(),i}openConnection(e,t){J(this.privInternalData.connect(),e,t)}closeConnection(e,t){if(this.privInternalData instanceof re)throw new Error("Disconnecting a synthesizer's connection is currently not supported");J(this.privInternalData.disconnect(),e,t)}setMessageProperty(e,t,i){if(l.throwIfNullOrWhitespace(t,"propertyName"),this.privInternalData instanceof G){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 re){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){J(this.privInternalData.sendNetworkMessage(e,t),i,n)}close(){}setupEvents(){this.privEventListener=this.privInternalData.connectionEvents.attach(e=>{e.name==="ConnectionEstablishedEvent"?this.connected&&this.connected(new Zt(e.connectionId)):e.name==="ConnectionClosedEvent"?this.disconnected&&this.disconnected(new Zt(e.connectionId)):e.name==="ConnectionMessageSentEvent"?this.messageSent&&this.messageSent(new Yt(new Jt(e.message))):e.name==="ConnectionMessageReceivedEvent"&&this.messageReceived&&this.messageReceived(new Yt(new Jt(e.message)))}),this.privServiceEventListener=this.privInternalData.serviceEvents.attach(e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new Xi(e.jsonString,e.name))})}}var Qt=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 Ji extends gt{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),super(t,i.properties,new cr),this.privDisposedTranslationRecognizer=!1,this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice,void 0)!==void 0&&l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationVoice),p[p.SpeechServiceConnection_TranslationVoice]),l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages),p[p.SpeechServiceConnection_TranslationToLanguages]),l.throwIfNullOrWhitespace(this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage),p[p.SpeechServiceConnection_RecoLanguage])}get speechRecognitionLanguage(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_RecoLanguage)}get targetLanguages(){return l.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(p.SpeechServiceConnection_TranslationToLanguages).split(",")}get voiceName(){return l.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){l.throwIfDisposed(this.privDisposedTranslationRecognizer),J(this.recognizeOnceAsyncImpl(oe.Conversation),e,t)}startContinuousRecognitionAsync(e,t){J(this.startContinuousRecognitionAsyncImpl(oe.Conversation),e,t)}stopContinuousRecognitionAsync(e,t){J(this.stopContinuousRecognitionAsyncImpl(),e,t)}removeTargetLanguage(e){if(l.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){l.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){l.throwIfDisposed(this.privDisposedTranslationRecognizer),J(this.dispose(!0),e,t)}onConnection(){}onDisconnection(){return Qt(this,void 0,void 0,function*(){})}dispose(e){const t=Object.create(null,{dispose:{get:()=>super.dispose}});return Qt(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 or(e,this.properties)}createServiceRecognizer(e,t,i,n){const s=i;return new ur(e,t,s,n,this)}updateLanguages(e){const t=Oe.fromRecognizer(this);t&&(t.setMessageProperty("speech.context","translationcontext",{to:e}),t.sendMessageAsync("event",JSON.stringify({id:"translation",name:"updateLanguage",to:e})))}}class Qi{constructor(){this.privMap=new U}get languages(){return this.privMap.keys}get(e,t){return this.privMap.getProperty(e,t)}set(e,t){this.privMap.setProperty(e,t)}}class Xt{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 R;(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"})(R||(R={}));class Zt extends ve{}class Xi extends ve{constructor(e,t,i){super(i),this.privJsonResult=e,this.privEventName=t}get jsonString(){return this.privJsonResult}get eventName(){return this.privEventName}}class w{}w.BotId="botid",w.CustomSpeechDeploymentId="cid",w.CustomVoiceDeploymentId="deploymentId",w.EnableAudioLogging="storeAudio",w.EnableLanguageId="lidEnabled",w.EnableWordLevelTimestamps="wordLevelTimestamps",w.EndSilenceTimeoutMs="endSilenceTimeoutMs",w.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",w.Format="format",w.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",w.Language="language",w.Profanity="profanity",w.RequestBotStatusMessages="enableBotMessageStatus",w.StableIntermediateThreshold="stableIntermediateThreshold",w.StableTranslation="stableTranslation",w.TestHooks="testhooks",w.Postprocessing="postprocessing";class _e{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,w.SegmentationSilenceTimeoutMs],[p.SpeechServiceConnection_EnableAudioLogging,w.EnableAudioLogging],[p.SpeechServiceConnection_EndSilenceTimeoutMs,w.EndSilenceTimeoutMs],[p.SpeechServiceConnection_InitialSilenceTimeoutMs,w.InitialSilenceTimeoutMs],[p.SpeechServiceResponse_PostProcessingOption,w.Postprocessing],[p.SpeechServiceResponse_ProfanityOption,w.Profanity],[p.SpeechServiceResponse_RequestWordLevelTimestamps,w.EnableWordLevelTimestamps],[p.SpeechServiceResponse_StablePartialResultThreshold,w.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,i)});const s=JSON.parse(e.parameters.getProperty(Ie,"{}"));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 He;(function(r){r[r.Masked=0]="Masked",r[r.Removed=1]="Removed",r[r.Raw=2]="Raw"})(He||(He={}));class Yt{constructor(e){this.privConnectionMessage=e}get message(){return this.privConnectionMessage}toString(){return"Message: "+this.privConnectionMessage.toString()}}var qe=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 Ke{constructor(e,t){const i=e;l.throwIfNull(i,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:Y.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=i.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new hr,this.synthesisRequestQueue=new Te,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(p.SpeechServiceAuthorization_Token)}set authorizationToken(e){l.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(p.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(p.SpeechServiceConnection_AutoDetectSourceLanguages)===Cr}static FromConfig(e,t,i){const n=e;return t.properties.mergeTo(n.properties),new Ke(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=Ke.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 qe(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){l.throwIfDisposed(this.privDisposed),J(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return qe(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new yr(e,this.privProperties)}createSynthesisAdapter(e,t,i,n){return new re(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 Fe(new Ge(new ai(e,t,i)))),s=this.privProperties.getProperty(p.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new Bt(s):new ue(()=>{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=f.fromSpeechSynthesisOutputFormat(g[this.properties.getProperty(p.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new mr(n)}speakImpl(e,t,i,n,s){try{l.throwIfDisposed(this.privDisposed);const o=b();let a;s instanceof Vt?a=new dt(s):s instanceof Le?a=s:s!==void 0?a=new _t(s):a=void 0,this.synthesisRequestQueue.enqueue(new Zi(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 qe(this,void 0,void 0,function*(){const t=b(),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 ti(t,n,void 0)}else return new ti(t,void 0,`Error: ${i.status}: ${i.statusText}`)})}adapterSpeak(){return qe(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 Zi{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 ei{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 Ue extends ei{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 We{constructor(e){this.privResult=e}get result(){return this.privResult}}class Yi{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 er{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class tr{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 ti extends ei{constructor(e,t,i){if(Array.isArray(t)){super(e,A.VoicesListRetrieved,void 0,new U),this.privVoices=[];for(const n of t)this.privVoices.push(new ir(n))}else super(e,A.Canceled,i||"Error information unavailable",new U)}get voices(){return this.privVoices}}var Ae;(function(r){r[r.Unknown=0]="Unknown",r[r.Female=1]="Female",r[r.Male=2]="Male"})(Ae||(Ae={}));var Ve;(function(r){r[r.OnlineNeural=1]="OnlineNeural",r[r.OnlineStandard=2]="OnlineStandard",r[r.OfflineNeural=3]="OfflineNeural",r[r.OfflineStandard=4]="OfflineStandard"})(Ve||(Ve={}));class ir{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")?Ve.OnlineStandard:Ve.OnlineNeural,this.privGender=e.Gender==="Male"?Ae.Male:e.Gender==="Female"?Ae.Female:Ae.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 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 rr=60*30,ii={[v.PCM]:"audio/wav",[v.MuLaw]:"audio/x-wav",[v.MP3]:"audio/mpeg",[v.OGG_OPUS]:"audio/ogg",[v.WEBM_OPUS]:"audio/webm; codecs=opus",[v.ALaw]:"audio/x-wav",[v.FLAC]:"audio/flac"};class mt{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||b(),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===v.PCM||this.privFormat.formatTag===v.MuLaw||this.privFormat.formatTag===v.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=re.addHeader(i,this.privFormat);const n=new Blob([i],{type:ii[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=ii[this.privFormat.formatTag];t===void 0?console.warn(`Unknown mimeType for format ${v[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=rr,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(i=>{N.instance.onEvent(new be(i))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(i=>{N.instance.onEvent(new be(i))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(i=>{N.instance.onEvent(new be(i))})):(console.warn(`Format ${v[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new pt,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 St(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 St(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return St(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 je extends ne{constructor(e,t,i,n=y.Info){super(e,n),this.privRequestId=t,this.privSessionId=i}get requestId(){return this.privRequestId}get sessionId(){return this.privSessionId}}class ri extends je{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 nr extends je{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 ni extends je{constructor(e,t,i){super("ConnectingToServiceEvent",e,i),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}}class sr extends je{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 O extends st{constructor(e,t,i,n,s,o,a,u){if(!t)throw new I("path");if(!i)throw new I("requestId");const h={};if(h[E.Path]=t,h[E.RequestId]=i,h[E.RequestTimestamp]=new Date().toISOString(),n&&(h[E.ContentType]=n),o&&(h[E.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()===E.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===E.RequestId.toLowerCase()?i=e.headers[a]:a.toLowerCase()===E.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===E.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new O(e.messageType,t,i,n,e.body,s,o,e.id)}}var k=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 G{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 I("authentication");if(!t)throw new I("connectionFactory");if(!i)throw new I("audioSource");if(!n)throw new I("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 dr(this.privAudioSource.id()),this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privDynamicGrammar=new lr,this.privSpeechContext=new vr(this.privDynamicGrammar),this.privAgentConfig=new pi,typeof Blob!="undefined"&&typeof Worker!="undefined"&&(this.privSetTimeout=x.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(H.Error,a.statusCode===1007?R.BadRequestParameters:R.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 k(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 k(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===ae.Microphones,s=new Rr(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(H.Error,R.ConnectionFailure,u);return}const o=new ve(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,o),this.receiveMessage(),this.sendAudio(s).catch(u=>k(this,void 0,void 0,function*(){yield this.cancelRecognitionLocal(H.Error,R.RuntimeError,u)}))})}stopRecognizing(){return k(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 k(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 k(this,void 0,void 0,function*(){if(yield this.cancelRecognitionLocal(H.Error,R.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 k(this,void 0,void 0,function*(){const i=typeof t=="string"?S.Text:S.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new O(i,e,this.privRequestSession.requestId,n,t))})}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}sendTelemetryData(){return k(this,void 0,void 0,function*(){const e=this.privRequestSession.getTelemetry();if(G.telemetryDataEnabled!==!0||this.privIsDisposed||e===null)return;if(G.telemetryData)try{G.telemetryData(e)}catch{}yield(yield this.fetchConnection()).send(new O(S.Text,"telemetry",this.privRequestSession.requestId,"application/json",e))})}cancelRecognitionLocal(e,t,i){return k(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 k(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=O.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=Je.fromJSON(i.textBody),s=new vt(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=Je.fromJSON(o);this.privRecognizerConfig.isContinuousRecognition&&this.privRequestSession.onServiceRecognized(a.Offset+this.privRequestSession.currentTurnAudioOffset);const u=new vt(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(H.EndOfStream,R.NoError,void 0));const h=new ve(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 Mt(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 O(S.Text,"speech.context",this.privRequestSession.requestId,"application/json",i))}sendPrePayloadJSON(e,t=!0){return k(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 k(this,void 0,void 0,function*(){const t=yield this.audioSource.format;return e.send(new O(S.Binary,"audio",this.privRequestSession.requestId,"audio/x-wav",t.header))})}connectImpl(){return this.privConnectionPromise!==void 0?this.privConnectionPromise.then(e=>e.state()===M.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(),G.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 O(S.Text,"speech.config",t.requestId,"application/json",i))}fetchConnection(){return k(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===M.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 k(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=()=>k(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 O(S.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 k(this,void 0,void 0,function*(){let e=!1;this.privAuthFetchEventId=b();const t=this.privRequestSession.sessionId;this.privConnectionId=t!==void 0?t:b(),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
3
|
`;for(let n=0;n<e.byteLength;n++)t+=i[n].toString(16).padStart(2,"0")+" "}console.info(t)}sendFinalAudio(){return k(this,void 0,void 0,function*(){yield(yield this.fetchConnection()).send(new O(S.Binary,"audio",this.privRequestSession.requestId,null,null))})}configureConnection(){return k(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)})}}G.telemetryDataEnabled=!0;var oe;(function(r){r[r.Interactive=0]="Interactive",r[r.Conversation=1]="Conversation",r[r.Dictation=2]="Dictation"})(oe||(oe={}));var oi;(function(r){r[r.Simple=0]="Simple",r[r.Detailed=1]="Detailed"})(oi||(oi={}));class or{constructor(e,t){this.privSpeechServiceConfig=e||new Fe(new Ge(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===oe.Interactive?8e3:25e3,this.privSpeechServiceConfig.Recognition=oe[e]}get SpeechServiceConfig(){return this.privSpeechServiceConfig}get recognitionActivityTimeout(){return this.privRecognitionActivityTimeout}get isContinuousRecognition(){return this.privRecognitionMode!==oe.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 Fe{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 Ge{constructor(e){this.system=new ar,this.os=e}}class ar{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class ai{constructor(e,t,i){this.platform=e,this.name=t,this.version=i}}var fe;(function(r){r.Bluetooth="Bluetooth",r.Wired="Wired",r.WiFi="WiFi",r.Cellular="Cellular",r.InBuilt="InBuilt",r.Unknown="Unknown"})(fe||(fe={}));var ae;(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"})(ae||(ae={}));const ci=`\r
|
4
4
|
`;class hi{toConnectionMessage(e){const t=new D;try{if(e.messageType===S.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 st(e.messageType,s,n,e.id))}else if(e.messageType===S.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 st(e.messageType,s,n,e.id))}}catch(i){t.reject(`Error formatting the message. Error: ${i}`)}return t.promise}fromConnectionMessage(e){const t=new D;try{if(e.messageType===S.Text){const i=`${this.makeHeaders(e)}${ci}${e.textBody?e.textBody:""}`;t.resolve(new Ne(S.Text,i,e.id))}else if(e.messageType===S.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 Ne(S.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]}${ci}`);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 cr extends _e{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=_e.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,y.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[E.ConnectionId]=i,e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const h=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new fi(n,s,u,new hi,et.fromRecognizerConfig(e),h,i)}}class hr{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=_e.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[E.ConnectionId]=i,a!==void 0&&(d[y.CustomVoiceDeploymentId]=a),e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const C=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new fi(n,c,d,new hi,et.fromParameters(e.parameters),C,i)}}class $e{static implTranslateRecognitionResult(e){let t=A.Canceled;switch(e){case T.Success:t=A.RecognizedSpeech;break;case T.NoMatch:case T.InitialSilenceTimeout:case T.BabbleTimeout:case T.EndOfDictation:t=A.NoMatch;break;case T.Error:case T.BadRequest:case T.Forbidden:default:t=A.Canceled;break}return t}static implTranslateCancelResult(e){let t=H.EndOfStream;switch(e){case T.Success:case T.EndOfDictation:case T.NoMatch:t=H.EndOfStream;break;case T.InitialSilenceTimeout:case T.BabbleTimeout:case T.Error:case T.BadRequest:case T.Forbidden:default:t=H.Error;break}return t}static implTranslateCancelErrorCode(e){let t=R.NoError;switch(e){case T.Error:t=R.ServiceError;break;case T.TooManyRequests:t=R.TooManyRequests;break;case T.BadRequest:t=R.BadRequestParameters;break;case T.Forbidden:t=R.Forbidden;break;default:t=R.NoError;break}return t}static implTranslateErrorDetails(e){let t="The speech service encountered an internal error and could not continue.";switch(e){case R.Forbidden:t="The recognizer is using a free subscription that ran out of quota.";break;case R.BadRequestParameters:t="Invalid parameter or unsupported audio format in the request.";break;case R.TooManyRequests:t="The number of parallel requests exceeded the number of allowed concurrent transcriptions.";break}return t}}var Pe;(function(r){r[r.Success=0]="Success",r[r.SynthesisEnd=1]="SynthesisEnd",r[r.Error=2]="Error"})(Pe||(Pe={}));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 yt{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus=Pe[this.privSynthesisEnd.SynthesisStatus]}static fromJSON(e){return new yt(e)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}class wt{constructor(e){this.privTranslationHypothesis=JSON.parse(e),this.privTranslationHypothesis.Translation.TranslationStatus=Ee[this.privTranslationHypothesis.Translation.TranslationStatus]}static fromJSON(e){return new wt(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 ge{constructor(e){this.privTranslationPhrase=e,this.privTranslationPhrase.RecognitionStatus=T[this.privTranslationPhrase.RecognitionStatus],this.privTranslationPhrase.Translation!==void 0&&(this.privTranslationPhrase.Translation.TranslationStatus=Ee[this.privTranslationPhrase.Translation.TranslationStatus])}static fromJSON(e){return new ge(JSON.parse(e))}static fromTranslationResponse(e){l.throwIfNullOrUndefined(e,"translationResponse");const t=e.SpeechPhrase;return e.SpeechPhrase=void 0,t.Translation=e,t.Text=t.DisplayText,new ge(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 ui=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 ur extends G{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 ui(this,void 0,void 0,function*(){const t=new U;let i=!1;const n=s=>ui(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=$e.implTranslateRecognitionResult(s.RecognitionStatus),a=new lt(void 0,this.privRequestSession.requestId,o,s.Text,s.Duration,this.privRequestSession.currentTurnAudioOffset+s.Offset,void 0,e.textBody,t);if(o===A.Canceled){const u=$e.implTranslateCancelResult(s.RecognitionStatus),h=$e.implTranslateCancelErrorCode(s.RecognitionStatus);yield this.cancelRecognitionLocal(u,h,$e.implTranslateErrorDetails(h))}else{if(!(this.privRequestSession.isSpeechEnded&&o===A.NoMatch&&s.RecognitionStatus!==T.InitialSilenceTimeout)){const u=new jt(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===S.Text&&t.setProperty(p.SpeechServiceResponse_JsonResult,e.textBody),e.path.toLowerCase()){case"translation.hypothesis":const s=this.fireEventForResult(wt.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(ge.fromTranslationResponse(o)));break;case"translation.phrase":yield n(ge.fromJSON(e.textBody));break;case"translation.synthesis":this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),i=!0;break;case"translation.synthesis.end":const a=yt.fromJSON(e.textBody);switch(a.SynthesisStatus){case Pe.Error:if(this.privTranslationRecognizer.synthesizing){const u=new Gt(A.Canceled,void 0),h=new Ft(u,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,h)}catch{}}if(this.privTranslationRecognizer.canceled){const u=new Xt(this.privRequestSession.sessionId,H.Error,a.FailureReason,R.ServiceError,null);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,u)}catch{}}break;case Pe.Success:this.sendSynthesisAudio(void 0,this.privRequestSession.sessionId);break}i=!0;break}return i})}cancelRecognition(e,t,i,n,s){const o=new U;if(o.setProperty(di,R[n]),this.privTranslationRecognizer.canceled){const a=new Xt(e,i,s,n,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,a)}catch{}}if(this.privSuccessCallback){const a=new lt(void 0,t,A.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 Qi;for(const u of e.Translation.Translations)i.set(u.Language,u.Text||u.DisplayText)}let n;e instanceof ge?e.Translation.TranslationStatus===Ee.Success?n=A.TranslatedSpeech:n=A.RecognizedSpeech:n=A.TranslatingSpeech;const s=e.Offset+this.privRequestSession.currentTurnAudioOffset,o=new lt(i,this.privRequestSession.requestId,n,e.Text,e.Duration,s,e.Translation.FailureReason,JSON.stringify(e),t);return new jt(o,s,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){const i=e===void 0?A.SynthesizingAudioCompleted:A.SynthesizingAudio,n=new Gt(i,e),s=new Ft(n,t);if(this.privTranslationRecognizer.synthesizing)try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,s)}catch{}}}class Je{constructor(e){this.privSpeechStartDetected=JSON.parse(e)}static fromJSON(e){return new Je(e)}get Offset(){return this.privSpeechStartDetected.Offset}}class pr{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 ri&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:"ListeningTrigger",Start:e.eventTime}),e instanceof ye&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof we&&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 it&&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 $&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Name:"Microphone",Start:this.privMicStartTime})),e instanceof ni&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof Dt&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof kt&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof Ai&&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 rt&&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 te=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 dr{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=b(),this.privAudioNodeId=b(),this.privTurnDeferral=new D,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 pr(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new ri(this.requestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}onAudioSourceAttachCompleted(e,t){return te(this,void 0,void 0,function*(){this.privAudioNode=e,this.privIsAudioNodeDetached=!1,t?yield this.onComplete():this.onEvent(new nr(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))})}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new ni(this.privRequestId,this.privAuthFetchEventId,this.privSessionId))}onAuthCompleted(e){return te(this,void 0,void 0,function*(){e&&(yield this.onComplete())})}onConnectionEstablishCompleted(e,t){return te(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 te(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=b()}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 D}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 te(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 te(this,void 0,void 0,function*(){yield this.onComplete()})}onSpeechEnded(){this.privIsSpeechEnded=!0}onEvent(e){this.privServiceTelemetryListener&&this.privServiceTelemetryListener.onEvent(e),N.instance.onEvent(e)}onComplete(){return te(this,void 0,void 0,function*(){this.privIsRecognizing&&(this.privIsRecognizing=!1,yield this.detachAudioNode())})}detachAudioNode(){return te(this,void 0,void 0,function*(){this.privIsAudioNodeDetached||(this.privIsAudioNodeDetached=!0,this.privAudioNode&&(yield this.privAudioNode.detach()))})}}class vr{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 lr{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 pi{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class Q{static get requestOptions(){return Q.privDefaultRequestOptions}static get configParams(){return Q.privDefaultParams}static get restErrors(){return Q.privRestErrors}}Q.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},Q.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."},Q.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 X;(function(r){r.WordBoundary="WordBoundary",r.Bookmark="Bookmark",r.Viseme="Viseme",r.SentenceBoundary="SentenceBoundary",r.SessionEnd="SessionEnd"})(X||(X={}));class Ct{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new Ct(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var ie=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 re{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 I("authentication");if(!t)throw new I("connectionFactory");if(!i)throw new I("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=i,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new Qe,this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privSynthesisContext=new wr(this.privSpeechSynthesizer),this.privAgentConfig=new pi,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(H.Error,a.statusCode===1007?R.BadRequestParameters:R.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 ie(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 ie(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return ie(this,void 0,void 0,function*(){const i=typeof t=="string"?S.Text:S.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new O(i,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,i,n,s,o){return ie(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 We(new Ue(i,A.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,h),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(H.Error,R.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,i,n){const s=new U;s.setProperty(di,R[i]);const o=new Ue(e,A.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new We(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 ie(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=O.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=re.addHeader(i.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new We(new Ue(this.privSynthesisTurn.requestId,A.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(i.binaryBody)}break;case"audio.metadata":const n=Ct.fromJSON(i.textBody).Metadata;for(const o of n)switch(o.Type){case X.WordBoundary:case X.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new Yi(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===X.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 X.Bookmark:const u=new er(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case X.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const h=new tr(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,h)}catch{}}break;case X.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Ue(this.privSynthesisTurn.requestId,A.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 We(s))}catch{}break;default:this.processTypeSpecificMessages(i)||this.privServiceEvents&&this.serviceEvents.onEvent(new Mt(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new O(S.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(i=>i.state()===M.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()));this.privAuthFetchEventId=b(),this.privConnectionId=b(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=t.then(i=>ie(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 O(S.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,i){return e.send(new O(S.Text,"ssml",i,"application/ssml+xml",t))}fetchConnection(){return ie(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===M.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 ie(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)})}}re.telemetryDataEnabled=!0;class Tt extends ne{constructor(e,t,i=m.Info){super(e,i),this.privRequestId=t}get requestId(){return this.privRequestId}}class fr extends Tt{constructor(e,t,i){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=i}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class gr extends Tt{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class Sr extends Tt{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var Et=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 Qe{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=b(),this.privTurnDeferral=new D,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 Et(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 Et(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=re.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 pt,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 fr(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new gr(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new Sr(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 D}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){N.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===X.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!Qe.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)&&!Qe.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 Et(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 mr{constructor(e){let t=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(p.SpeechServiceConnection_Region,"westus"),s=_e.getHostSuffix(n);t=e.parameters.getProperty(p.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const i=Q.requestOptions;i.headers[Q.configParams.subscriptionKey]=e.parameters.getProperty(p.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new zr(i)}getVoicesList(e){return this.privRestAdapter.setHeaders(E.ConnectionId,e),this.privRestAdapter.request(ce.Get,this.privUri)}}var bt;(function(r){r[r.Standard=0]="Standard",r[r.Custom=1]="Custom"})(bt||(bt={}));class yr{constructor(e,t){this.privSynthesisServiceType=bt.Standard,this.privSpeechServiceConfig=e||new Fe(new Ge(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 wr{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 Xe="OutputFormat",di="CancellationErrorCode",Ie="ServiceProperties",vi="ForceDictation",Cr="OpenRange";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())})};const Tr="MICROPHONE-WorkletSourceUrl";class W{constructor(e,t,i,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=W.AUDIOFORMAT.avgBytesPerSec/10,this.privId=i||b(),this.privEvents=new j,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(W.AUDIOFORMAT)}get blob(){return Promise.reject("Not implemented for Mic input")}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new D;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 De(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new me(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new me(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 ye(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new we(this.privId,e)),{detach:()=>Ze(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new $(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 $(this.privId,e)))}turnOff(){return Ze(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 It(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:W.AUDIOFORMAT.bitsPerSample,channelcount:W.AUDIOFORMAT.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:e,samplerate:W.AUDIOFORMAT.samplesPerSec,type:ae.Microphones}))}setProperty(e,t){if(e===Tr)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 D;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 Ze(this,void 0,void 0,function*(){yield this.turnOn();const t=new at(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new it(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),N.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=Z.getAudioContext(W.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return Ze(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())})}}W.AUDIOFORMAT=xe.getDefaultInputFormat();var Rt=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,t,i){this.privStreams={},this.privHeaderEnd=44,this.privId=i||b(),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 De(this.privId)),this.onEvent(new me(this.privId))}id(){return this.privId}attach(e){return Rt(this,void 0,void 0,function*(){this.onEvent(new ye(this.privId,e));const t=yield this.upload(e);return this.onEvent(new we(this.privId,e)),Promise.resolve({detach:()=>Rt(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new $(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 $(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 It(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:fe.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:ae.File}))}readHeader(){const t=this.privSource.slice(0,512),i=new D,n=s=>{const o=new DataView(s),a=q=>String.fromCharCode(o.getUint8(q),o.getUint8(q+1),o.getUint8(q+2),o.getUint8(q+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 C=36+Math.max(u-16,0);for(;a(C)!=="data";C+=2)if(C>512-8){i.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=C+8,i.resolve(xe.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 Rt(this,void 0,void 0,function*(){const t=i=>{const n=`Error occurred while processing '${this.privFilename}'. ${i}`;throw this.onEvent(new it(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const i=yield this.privAudioFormatPromise,n=new at(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),N.instance.onEvent(e)}}class At{constructor(e){this.privStopInputOnRelease=e}record(e,t,i){const s=new Ii(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 st(e.messageType,s,n,e.id))}else if(e.messageType===S.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 st(e.messageType,s,n,e.id))}}catch(i){t.reject(`Error formatting the message. Error: ${i}`)}return t.promise}fromConnectionMessage(e){const t=new D;try{if(e.messageType===S.Text){const i=`${this.makeHeaders(e)}${ci}${e.textBody?e.textBody:""}`;t.resolve(new Ne(S.Text,i,e.id))}else if(e.messageType===S.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 Ne(S.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]}${ci}`);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 cr extends _e{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=_e.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,w.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[E.ConnectionId]=i,e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const h=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new fi(n,s,u,new hi,et.fromRecognizerConfig(e),h,i)}}class hr{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=_e.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[E.ConnectionId]=i,a!==void 0&&(d[w.CustomVoiceDeploymentId]=a),e.parameters.setProperty(p.SpeechServiceConnection_Url,n);const C=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new fi(n,c,d,new hi,et.fromParameters(e.parameters),C,i)}}class $e{static implTranslateRecognitionResult(e){let t=A.Canceled;switch(e){case T.Success:t=A.RecognizedSpeech;break;case T.NoMatch:case T.InitialSilenceTimeout:case T.BabbleTimeout:case T.EndOfDictation:t=A.NoMatch;break;case T.Error:case T.BadRequest:case T.Forbidden:default:t=A.Canceled;break}return t}static implTranslateCancelResult(e){let t=H.EndOfStream;switch(e){case T.Success:case T.EndOfDictation:case T.NoMatch:t=H.EndOfStream;break;case T.InitialSilenceTimeout:case T.BabbleTimeout:case T.Error:case T.BadRequest:case T.Forbidden:default:t=H.Error;break}return t}static implTranslateCancelErrorCode(e){let t=R.NoError;switch(e){case T.Error:t=R.ServiceError;break;case T.TooManyRequests:t=R.TooManyRequests;break;case T.BadRequest:t=R.BadRequestParameters;break;case T.Forbidden:t=R.Forbidden;break;default:t=R.NoError;break}return t}static implTranslateErrorDetails(e){let t="The speech service encountered an internal error and could not continue.";switch(e){case R.Forbidden:t="The recognizer is using a free subscription that ran out of quota.";break;case R.BadRequestParameters:t="Invalid parameter or unsupported audio format in the request.";break;case R.TooManyRequests:t="The number of parallel requests exceeded the number of allowed concurrent transcriptions.";break}return t}}var Pe;(function(r){r[r.Success=0]="Success",r[r.SynthesisEnd=1]="SynthesisEnd",r[r.Error=2]="Error"})(Pe||(Pe={}));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 yt{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus=Pe[this.privSynthesisEnd.SynthesisStatus]}static fromJSON(e){return new yt(e)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}class wt{constructor(e){this.privTranslationHypothesis=JSON.parse(e),this.privTranslationHypothesis.Translation.TranslationStatus=Ee[this.privTranslationHypothesis.Translation.TranslationStatus]}static fromJSON(e){return new wt(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 ge{constructor(e){this.privTranslationPhrase=e,this.privTranslationPhrase.RecognitionStatus=T[this.privTranslationPhrase.RecognitionStatus],this.privTranslationPhrase.Translation!==void 0&&(this.privTranslationPhrase.Translation.TranslationStatus=Ee[this.privTranslationPhrase.Translation.TranslationStatus])}static fromJSON(e){return new ge(JSON.parse(e))}static fromTranslationResponse(e){l.throwIfNullOrUndefined(e,"translationResponse");const t=e.SpeechPhrase;return e.SpeechPhrase=void 0,t.Translation=e,t.Text=t.DisplayText,new ge(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 ui=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 ur extends G{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 ui(this,void 0,void 0,function*(){const t=new U;let i=!1;const n=s=>ui(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=$e.implTranslateRecognitionResult(s.RecognitionStatus),a=new lt(void 0,this.privRequestSession.requestId,o,s.Text,s.Duration,this.privRequestSession.currentTurnAudioOffset+s.Offset,void 0,e.textBody,t);if(o===A.Canceled){const u=$e.implTranslateCancelResult(s.RecognitionStatus),h=$e.implTranslateCancelErrorCode(s.RecognitionStatus);yield this.cancelRecognitionLocal(u,h,$e.implTranslateErrorDetails(h))}else{if(!(this.privRequestSession.isSpeechEnded&&o===A.NoMatch&&s.RecognitionStatus!==T.InitialSilenceTimeout)){const u=new jt(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===S.Text&&t.setProperty(p.SpeechServiceResponse_JsonResult,e.textBody),e.path.toLowerCase()){case"translation.hypothesis":const s=this.fireEventForResult(wt.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(ge.fromTranslationResponse(o)));break;case"translation.phrase":yield n(ge.fromJSON(e.textBody));break;case"translation.synthesis":this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),i=!0;break;case"translation.synthesis.end":const a=yt.fromJSON(e.textBody);switch(a.SynthesisStatus){case Pe.Error:if(this.privTranslationRecognizer.synthesizing){const u=new Gt(A.Canceled,void 0),h=new Ft(u,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,h)}catch{}}if(this.privTranslationRecognizer.canceled){const u=new Xt(this.privRequestSession.sessionId,H.Error,a.FailureReason,R.ServiceError,null);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,u)}catch{}}break;case Pe.Success:this.sendSynthesisAudio(void 0,this.privRequestSession.sessionId);break}i=!0;break}return i})}cancelRecognition(e,t,i,n,s){const o=new U;if(o.setProperty(di,R[n]),this.privTranslationRecognizer.canceled){const a=new Xt(e,i,s,n,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,a)}catch{}}if(this.privSuccessCallback){const a=new lt(void 0,t,A.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 Qi;for(const u of e.Translation.Translations)i.set(u.Language,u.Text||u.DisplayText)}let n;e instanceof ge?e.Translation.TranslationStatus===Ee.Success?n=A.TranslatedSpeech:n=A.RecognizedSpeech:n=A.TranslatingSpeech;const s=e.Offset+this.privRequestSession.currentTurnAudioOffset,o=new lt(i,this.privRequestSession.requestId,n,e.Text,e.Duration,s,e.Translation.FailureReason,JSON.stringify(e),t);return new jt(o,s,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){const i=e===void 0?A.SynthesizingAudioCompleted:A.SynthesizingAudio,n=new Gt(i,e),s=new Ft(n,t);if(this.privTranslationRecognizer.synthesizing)try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,s)}catch{}}}class Je{constructor(e){this.privSpeechStartDetected=JSON.parse(e)}static fromJSON(e){return new Je(e)}get Offset(){return this.privSpeechStartDetected.Offset}}class pr{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 ri&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:"ListeningTrigger",Start:e.eventTime}),e instanceof ye&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof we&&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 it&&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 $&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Name:"Microphone",Start:this.privMicStartTime})),e instanceof ni&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof Dt&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof kt&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof Ai&&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 rt&&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 te=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 dr{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=b(),this.privAudioNodeId=b(),this.privTurnDeferral=new D,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 pr(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new ri(this.requestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}onAudioSourceAttachCompleted(e,t){return te(this,void 0,void 0,function*(){this.privAudioNode=e,this.privIsAudioNodeDetached=!1,t?yield this.onComplete():this.onEvent(new nr(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))})}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new ni(this.privRequestId,this.privAuthFetchEventId,this.privSessionId))}onAuthCompleted(e){return te(this,void 0,void 0,function*(){e&&(yield this.onComplete())})}onConnectionEstablishCompleted(e,t){return te(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 te(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=b()}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 D}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 te(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 te(this,void 0,void 0,function*(){yield this.onComplete()})}onSpeechEnded(){this.privIsSpeechEnded=!0}onEvent(e){this.privServiceTelemetryListener&&this.privServiceTelemetryListener.onEvent(e),N.instance.onEvent(e)}onComplete(){return te(this,void 0,void 0,function*(){this.privIsRecognizing&&(this.privIsRecognizing=!1,yield this.detachAudioNode())})}detachAudioNode(){return te(this,void 0,void 0,function*(){this.privIsAudioNodeDetached||(this.privIsAudioNodeDetached=!0,this.privAudioNode&&(yield this.privAudioNode.detach()))})}}class vr{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 lr{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 pi{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class Q{static get requestOptions(){return Q.privDefaultRequestOptions}static get configParams(){return Q.privDefaultParams}static get restErrors(){return Q.privRestErrors}}Q.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},Q.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."},Q.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 X;(function(r){r.WordBoundary="WordBoundary",r.Bookmark="Bookmark",r.Viseme="Viseme",r.SentenceBoundary="SentenceBoundary",r.SessionEnd="SessionEnd"})(X||(X={}));class Ct{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new Ct(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var ie=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 re{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 I("authentication");if(!t)throw new I("connectionFactory");if(!i)throw new I("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=i,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new Qe,this.privConnectionEvents=new j,this.privServiceEvents=new j,this.privSynthesisContext=new wr(this.privSpeechSynthesizer),this.privAgentConfig=new pi,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(H.Error,a.statusCode===1007?R.BadRequestParameters:R.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 ie(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 ie(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return ie(this,void 0,void 0,function*(){const i=typeof t=="string"?S.Text:S.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new O(i,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,i,n,s,o){return ie(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 We(new Ue(i,A.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,h),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(H.Error,R.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,i,n){const s=new U;s.setProperty(di,R[i]);const o=new Ue(e,A.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new We(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 ie(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=O.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=re.addHeader(i.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new We(new Ue(this.privSynthesisTurn.requestId,A.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(i.binaryBody)}break;case"audio.metadata":const n=Ct.fromJSON(i.textBody).Metadata;for(const o of n)switch(o.Type){case X.WordBoundary:case X.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new Yi(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===X.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 X.Bookmark:const u=new er(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case X.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const h=new tr(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,h)}catch{}}break;case X.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Ue(this.privSynthesisTurn.requestId,A.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 We(s))}catch{}break;default:this.processTypeSpecificMessages(i)||this.privServiceEvents&&this.serviceEvents.onEvent(new Mt(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new O(S.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(i=>i.state()===M.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()));this.privAuthFetchEventId=b(),this.privConnectionId=b(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=t.then(i=>ie(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 O(S.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,i){return e.send(new O(S.Text,"ssml",i,"application/ssml+xml",t))}fetchConnection(){return ie(this,void 0,void 0,function*(){return this.privConnectionConfigurationPromise!==void 0?this.privConnectionConfigurationPromise.then(e=>e.state()===M.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 ie(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)})}}re.telemetryDataEnabled=!0;class Tt extends ne{constructor(e,t,i=y.Info){super(e,i),this.privRequestId=t}get requestId(){return this.privRequestId}}class fr extends Tt{constructor(e,t,i){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=i}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class gr extends Tt{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class Sr extends Tt{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var Et=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 Qe{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=b(),this.privTurnDeferral=new D,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 Et(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 Et(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=re.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 pt,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 fr(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new gr(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new Sr(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 D}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){N.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===X.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!Qe.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)&&!Qe.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 Et(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 mr{constructor(e){let t=e.parameters.getProperty(p.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(p.SpeechServiceConnection_Region,"westus"),s=_e.getHostSuffix(n);t=e.parameters.getProperty(p.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const i=Q.requestOptions;i.headers[Q.configParams.subscriptionKey]=e.parameters.getProperty(p.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new zr(i)}getVoicesList(e){return this.privRestAdapter.setHeaders(E.ConnectionId,e),this.privRestAdapter.request(ce.Get,this.privUri)}}var bt;(function(r){r[r.Standard=0]="Standard",r[r.Custom=1]="Custom"})(bt||(bt={}));class yr{constructor(e,t){this.privSynthesisServiceType=bt.Standard,this.privSpeechServiceConfig=e||new Fe(new Ge(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 wr{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 Xe="OutputFormat",di="CancellationErrorCode",Ie="ServiceProperties",vi="ForceDictation",Cr="OpenRange";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())})};const Tr="MICROPHONE-WorkletSourceUrl";class W{constructor(e,t,i,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=W.AUDIOFORMAT.avgBytesPerSec/10,this.privId=i||b(),this.privEvents=new j,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(W.AUDIOFORMAT)}get blob(){return Promise.reject("Not implemented for Mic input")}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new D;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 De(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new me(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new me(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 ye(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new we(this.privId,e)),{detach:()=>Ze(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new $(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 $(this.privId,e)))}turnOff(){return Ze(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 It(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:W.AUDIOFORMAT.bitsPerSample,channelcount:W.AUDIOFORMAT.channels,connectivity:fe.Unknown,manufacturer:"Speech SDK",model:e,samplerate:W.AUDIOFORMAT.samplesPerSec,type:ae.Microphones}))}setProperty(e,t){if(e===Tr)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 D;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 Ze(this,void 0,void 0,function*(){yield this.turnOn();const t=new at(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new it(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),N.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=Z.getAudioContext(W.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return Ze(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())})}}W.AUDIOFORMAT=xe.getDefaultInputFormat();var Rt=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,t,i){this.privStreams={},this.privHeaderEnd=44,this.privId=i||b(),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 De(this.privId)),this.onEvent(new me(this.privId))}id(){return this.privId}attach(e){return Rt(this,void 0,void 0,function*(){this.onEvent(new ye(this.privId,e));const t=yield this.upload(e);return this.onEvent(new we(this.privId,e)),Promise.resolve({detach:()=>Rt(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new $(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 $(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 It(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:fe.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:ae.File}))}readHeader(){const t=this.privSource.slice(0,512),i=new D,n=s=>{const o=new DataView(s),a=q=>String.fromCharCode(o.getUint8(q),o.getUint8(q+1),o.getUint8(q+2),o.getUint8(q+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 C=36+Math.max(u-16,0);for(;a(C)!=="data";C+=2)if(C>512-8){i.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=C+8,i.resolve(xe.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 Rt(this,void 0,void 0,function*(){const t=i=>{const n=`Error occurred while processing '${this.privFilename}'. ${i}`;throw this.onEvent(new it(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const i=yield this.privAudioFormatPromise,n=new at(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),N.instance.onEvent(e)}}class At{constructor(e){this.privStopInputOnRelease=e}record(e,t,i){const s=new Ii(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,16 +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 Me=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 P{constructor(e){e&&(this.privProxyInfo=e),P.privDiskCache||(P.privDiskCache=new L("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){P.privDiskCache=void 0,P.privMemCache={}}GetAgent(e){const t=new L.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 L(t)}static OCSPCheck(e,t){return Me(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 Oi),n=c)}),o.on("error",c=>{s||(s=!0,o.destroy(),h(c))}),a.on("secure",()=>Me(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 C=i.id.toString("hex");n||(n=yield P.GetResponseFromCache(C,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 Me(this,void 0,void 0,function*(){let n=P.privMemCache[e];if(n&&this.onEvent(new Di(e)),!n)try{const s=yield P.privDiskCache.get(e);s.isCached&&(P.onEvent(new zi(e)),P.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 Lt(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 Hi(e,u,h)),this.UpdateCache(t,i).catch(d=>{this.onEvent(new Wi(e,d.toString()))})):this.onEvent(new qi(e,u,h))}}catch(s){this.onEvent(new Lt(e,s)),n=null}return n||this.onEvent(new ki(e)),n})}static VerifyOCSPResponse(e,t,i){return Me(this,void 0,void 0,function*(){let n=e;return n||(n=yield P.GetOCSPResponse(t,i)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(P.onEvent(new Ki(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,i).then(()=>{s()},u=>{o(u)}):o(a)):(e||P.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return Me(this,void 0,void 0,function*(){const i=e.id.toString("hex");this.onEvent(new Ni(i));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(i,n),this.onEvent(new Bi(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 xi(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Li(e))})}static GetOCSPResponse(e,t){const i="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=P.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 C=e.certID;this.onEvent(new Ui(C.toString("hex"))),s(d)})})})}static onEvent(e){N.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:!P.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=P.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?P.OCSPCheck(n,this.privProxyInfo):n}}P.testTimeOffset=0,P.forceDisableOCSPStapling=!1,P.privMemCache={};var li=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 Ye{constructor(e,t,i,n,s,o){if(!e)throw new I("uri");if(!i)throw new I("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new j,this.privConnectionId=t,this.privMessageFormatter=i,this.privConnectionState=M.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[E.ConnectionId]=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===M.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new D,this.privCertificateValidatedDeferral=new D,this.privConnectionState=M.Connecting;try{if(typeof WebSocket!="undefined"&&!Ye.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 P(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 L(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new Te,this.privDisconnectDeferral=new D,this.privSendMessageQueue=new Te,this.processSendQueue().catch(e=>{N.instance.onEvent(new be(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new ot(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Dt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=M.Connected,this.onEvent(new kt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new ot(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ri(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===M.Connecting?(this.privConnectionState=M.Disconnected,this.privConnectionEstablishDeferral.resolve(new ot(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=M.Disconnected,this.privWebsocketClient=null,this.onEvent(new bi(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{N.instance.onEvent(new be(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const i=new D;if(this.privReceivingMessageQueue.enqueueFromPromise(i.promise),e.data instanceof ArrayBuffer){const n=new Ne(S.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new rt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new Ne(S.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new rt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid text message format. Error: ${s}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==M.Connected)return Promise.reject(`Cannot send on connection that is in ${M[this.privConnectionState]} state`);const t=new D,i=new D;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!==M.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){if(this.privWebsocketClient)this.privConnectionState!==M.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 Pi(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 li(this,void 0,void 0,function*(){const i=`Connection closed. ${e}: ${t}`;this.privConnectionState=M.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},i),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(i)},i)})}processSendQueue(){return li(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),N.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}Ye.forceNpmWebSocket=!1;var br=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 fi{constructor(e,t,i,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new I("uri");if(!n)throw new I("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||b(),this.privConnectionMessageAdapter=new Ye(this.privUri,this.id,this.privMessageFormatter,s,i,o)}dispose(){return br(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 Rr{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 Ar(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 Ar{constructor(e,t,i){this.chunk=e,this.serial=t,this.byteOffset=i}}class et{constructor(e,t,i,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=i,this.privProxyPassword=n}static fromParameters(e){return new et(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 Pr=new Set(["json","buffer","string"]);var Ir=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(Pr.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 Mr=Ir;class Pt extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Pt),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 Dr=Mr((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 Pt(h);return t==="json"?h.json():t==="buffer"?h.arrayBuffer():t==="string"?h.text():h}),kr=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())})},ce;(function(r){r.Get="GET",r.Post="POST",r.Delete="DELETE",r.File="file"})(ce||(ce={}));class zr{constructor(e){if(!e)throw new I("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 D,a=e===ce.File?"POST":e,u=(d,C={})=>{const q=d;return{data:JSON.stringify(C),headers:JSON.stringify(d.headers),json:C,ok:d.statusCode>=200&&d.statusCode<300,status:d.statusCode,statusText:C.error?C.error.message:q.statusText?q.statusText:q.statusMessage}},h=d=>{const C=new FileReader;return C.readAsArrayBuffer(d),new Promise(q=>{C.onloadend=()=>{q(C.result)}})},c=d=>{const C=Dr(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),q=this.queryParams(i)===""?"":`?${this.queryParams(i)}`;C(q,d).then(he=>kr(this,void 0,void 0,function*(){if(e===ce.Delete||he.statusCode===204)o.resolve(u(he));else try{const gi=yield he.json();o.resolve(u(he,gi))}catch{o.resolve(u(he))}})).catch(he=>{o.reject(he)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===ce.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(C=>{c(C)}).catch(C=>{o.reject(C)}):c(s)}else e===ce.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 Nr{constructor(e,t,i,n=null){w(this,"key");w(this,"region");w(this,"sourceLanguage");w(this,"targetLanguage");w(this,"recognizer");this.key=e,this.region=t,this.sourceLanguage=i,this.targetLanguage=n!==null?n:i}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 handleStartModifier(e,t){e.addEventListener("click",async i=>{const n=$t.fromSubscription(this.key,this.region);n.speechRecognitionLanguage=this.sourceLanguage,n.addTargetLanguage(this.targetLanguage);const s=Y.fromDefaultMicrophoneInput();this.recognizer=new Ji(n,s),document.dispatchEvent(new CustomEvent("COAzureSTTStartedRecording",{})),this.recognizer.recognizeOnceAsync(o=>{if(o.reason===A.TranslatedSpeech){const a=o.translations.get(this.targetLanguage),u=document.getElementById(t.value);u!==null&&(u instanceof HTMLInputElement?u.value+=`${a} `:u.innerHTML+=`${a} `)}this.stop()},o=>{console.log(o),this.stop()})})}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stop()})}async stop(){this.recognizer!==void 0&&(this.recognizer.close(),this.recognizer=void 0),document.dispatchEvent(new CustomEvent("COAzureSTTStoppedRecording",{}))}}class xr{constructor(e,t,i,n=0,s=0){w(this,"key");w(this,"region");w(this,"voice");w(this,"rate");w(this,"pitch");w(this,"textToRead","");w(this,"wordBoundryList",[]);w(this,"clickedNode");w(this,"highlightDiv");w(this,"speechConfig");w(this,"audioConfig");w(this,"player");w(this,"synthesizer");w(this,"previousWordBoundary");w(this,"interval");w(this,"wordEncounters",[]);w(this,"originalHighlightDivInnerHTML","");w(this,"currentWord","");w(this,"currentOffset",0);w(this,"wordBoundaryOffset",0);w(this,"privTextOffset",0);this.key=e,this.region=t,this.voice=i,this.rate=n,this.pitch=s}async start(){await this.registerBindings(document)}setVoice(e){return this.voice=e,this}setRate(e){return this.rate=e,this}setPitch(e){return this.pitch=e,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;this.stopPlayer(),await this.createInterval();const n=document.getElementById(t.value);if(this.clickedNode=n,!!n){if(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=n.innerText,n.hasAttribute("co-tts.highlight"))if(((o=n.attributes.getNamedItem("co-tts.highlight"))==null?void 0:o.value)!==""){const a=document.getElementById(n.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=a,this.originalHighlightDivInnerHTML=a.innerHTML}else this.highlightDiv=n,this.originalHighlightDivInnerHTML=n.innerHTML;this.startSynthesizer(e,t)}})}async handleAjaxModifier(e,t){e.addEventListener("click",async i=>{this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=await fetch(t.value,{method:"GET"});this.textToRead=await n.text(),this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener("click",async i=>{var n;if(this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(((n=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:n.value)!==""){const s=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=s,this.originalHighlightDivInnerHTML=s.innerHTML}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;t.value===""?this.textToRead=e.innerText:this.textToRead=t.value,this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){var i;if(this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(((i=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:i.value)!==""){const n=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=n,n!==null&&(this.originalHighlightDivInnerHTML=n.innerHTML)}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;t.value===""?this.textToRead=e.innerText:this.textToRead=t.value,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=>{await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{}))})}async handleResumeModifier(e,t){e.addEventListener("click",async i=>{await this.createInterval(),await this.player.resume(),document.dispatchEvent(new CustomEvent("COAzureTTSResumedPlaying",{}))})}async stopPlayer(){await this.clearInterval(),this.highlightDiv!==void 0&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML),this.textToRead="",this.currentWord="",this.originalHighlightDivInnerHTML="",this.wordBoundryList=[],this.wordEncounters=[],this.player!==void 0&&this.player.pause(),this.player=void 0,this.highlightDiv=void 0,this.privTextOffset=0}async startSynthesizer(e,t){this.speechConfig=ft.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=g.Audio24Khz160KBitRateMonoMp3,this.player=new mt,this.audioConfig=Y.fromSpeakerOutput(this.player),this.synthesizer=new Ke(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(i,n)=>{this.wordBoundryList.push(n)},this.player.onAudioEnd=async()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const i=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));i&&i.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(i,i.attributes.getNamedItem("co-tts.text")):i&&i.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},this.synthesizer.speakSsmlAsync(this.buildSSML(this.textToRead),()=>{this.synthesizer.close(),this.synthesizer=void 0},()=>{this.synthesizer.close(),this.synthesizer=void 0})}async clearInterval(){clearInterval(this.interval)}async createInterval(){this.interval=setInterval(()=>{var e;if(this.player!==void 0&&this.highlightDiv){const t=this.player.currentTime;let i;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)i=n;else break;if(i!==void 0)if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(i.text)&&(i=(e=this.previousWordBoundary)!=null?e:void 0),i===void 0||this.privTextOffset>i.privTextOffset)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else if(this.wordEncounters[i.text]||(this.wordEncounters[i.text]=0),this.privTextOffset=i.privTextOffset,(this.currentWord!==i.text||this.wordBoundaryOffset!==i.textOffset)&&(this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,i.text,this.wordEncounters[i.text]),this.wordEncounters[i.text]=this.currentOffset+i.wordLength,this.currentWord=i.text,this.wordBoundaryOffset=i.textOffset),this.currentOffset===Number.MAX_SAFE_INTEGER)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else{this.previousWordBoundary=i;const n=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset),s=this.currentOffset+i.wordLength,o=this.originalHighlightDivInnerHTML.substring(s);this.highlightDiv.innerHTML=`
|
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 Me=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 P{constructor(e){e&&(this.privProxyInfo=e),P.privDiskCache||(P.privDiskCache=new L("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){P.privDiskCache=void 0,P.privMemCache={}}GetAgent(e){const t=new L.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 L(t)}static OCSPCheck(e,t){return Me(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 Oi),n=c)}),o.on("error",c=>{s||(s=!0,o.destroy(),h(c))}),a.on("secure",()=>Me(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 C=i.id.toString("hex");n||(n=yield P.GetResponseFromCache(C,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 Me(this,void 0,void 0,function*(){let n=P.privMemCache[e];if(n&&this.onEvent(new Di(e)),!n)try{const s=yield P.privDiskCache.get(e);s.isCached&&(P.onEvent(new zi(e)),P.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 Lt(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 Hi(e,u,h)),this.UpdateCache(t,i).catch(d=>{this.onEvent(new Wi(e,d.toString()))})):this.onEvent(new qi(e,u,h))}}catch(s){this.onEvent(new Lt(e,s)),n=null}return n||this.onEvent(new ki(e)),n})}static VerifyOCSPResponse(e,t,i){return Me(this,void 0,void 0,function*(){let n=e;return n||(n=yield P.GetOCSPResponse(t,i)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(P.onEvent(new Ki(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,i).then(()=>{s()},u=>{o(u)}):o(a)):(e||P.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return Me(this,void 0,void 0,function*(){const i=e.id.toString("hex");this.onEvent(new Ni(i));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(i,n),this.onEvent(new Bi(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 xi(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Li(e))})}static GetOCSPResponse(e,t){const i="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=P.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 C=e.certID;this.onEvent(new Ui(C.toString("hex"))),s(d)})})})}static onEvent(e){N.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:!P.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=P.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?P.OCSPCheck(n,this.privProxyInfo):n}}P.testTimeOffset=0,P.forceDisableOCSPStapling=!1,P.privMemCache={};var li=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 Ye{constructor(e,t,i,n,s,o){if(!e)throw new I("uri");if(!i)throw new I("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new j,this.privConnectionId=t,this.privMessageFormatter=i,this.privConnectionState=M.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[E.ConnectionId]=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===M.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new D,this.privCertificateValidatedDeferral=new D,this.privConnectionState=M.Connecting;try{if(typeof WebSocket!="undefined"&&!Ye.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 P(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 L(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new Te,this.privDisconnectDeferral=new D,this.privSendMessageQueue=new Te,this.processSendQueue().catch(e=>{N.instance.onEvent(new be(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new ot(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Dt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=M.Connected,this.onEvent(new kt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new ot(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ri(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===M.Connecting?(this.privConnectionState=M.Disconnected,this.privConnectionEstablishDeferral.resolve(new ot(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=M.Disconnected,this.privWebsocketClient=null,this.onEvent(new bi(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{N.instance.onEvent(new be(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const i=new D;if(this.privReceivingMessageQueue.enqueueFromPromise(i.promise),e.data instanceof ArrayBuffer){const n=new Ne(S.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new rt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new Ne(S.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new rt(this.privConnectionId,t,s)),i.resolve(s)},s=>{i.reject(`Invalid text message format. Error: ${s}`)})}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==M.Connected)return Promise.reject(`Cannot send on connection that is in ${M[this.privConnectionState]} state`);const t=new D,i=new D;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!==M.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){if(this.privWebsocketClient)this.privConnectionState!==M.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 Pi(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 li(this,void 0,void 0,function*(){const i=`Connection closed. ${e}: ${t}`;this.privConnectionState=M.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},i),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(i)},i)})}processSendQueue(){return li(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),N.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}Ye.forceNpmWebSocket=!1;var br=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 fi{constructor(e,t,i,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new I("uri");if(!n)throw new I("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||b(),this.privConnectionMessageAdapter=new Ye(this.privUri,this.id,this.privMessageFormatter,s,i,o)}dispose(){return br(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 Rr{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 Ar(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 Ar{constructor(e,t,i){this.chunk=e,this.serial=t,this.byteOffset=i}}class et{constructor(e,t,i,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=i,this.privProxyPassword=n}static fromParameters(e){return new et(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 Pr=new Set(["json","buffer","string"]);var Ir=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(Pr.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 Mr=Ir;class Pt extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Pt),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 Dr=Mr((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 Pt(h);return t==="json"?h.json():t==="buffer"?h.arrayBuffer():t==="string"?h.text():h}),kr=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())})},ce;(function(r){r.Get="GET",r.Post="POST",r.Delete="DELETE",r.File="file"})(ce||(ce={}));class zr{constructor(e){if(!e)throw new I("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 D,a=e===ce.File?"POST":e,u=(d,C={})=>{const q=d;return{data:JSON.stringify(C),headers:JSON.stringify(d.headers),json:C,ok:d.statusCode>=200&&d.statusCode<300,status:d.statusCode,statusText:C.error?C.error.message:q.statusText?q.statusText:q.statusMessage}},h=d=>{const C=new FileReader;return C.readAsArrayBuffer(d),new Promise(q=>{C.onloadend=()=>{q(C.result)}})},c=d=>{const C=Dr(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),q=this.queryParams(i)===""?"":`?${this.queryParams(i)}`;C(q,d).then(he=>kr(this,void 0,void 0,function*(){if(e===ce.Delete||he.statusCode===204)o.resolve(u(he));else try{const gi=yield he.json();o.resolve(u(he,gi))}catch{o.resolve(u(he))}})).catch(he=>{o.reject(he)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===ce.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(C=>{c(C)}).catch(C=>{o.reject(C)}):c(s)}else e===ce.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 Nr{constructor(e,t,i,n=null){m(this,"key");m(this,"region");m(this,"sourceLanguage");m(this,"targetLanguage");m(this,"recognizer");this.key=e,this.region=t,this.sourceLanguage=i,this.targetLanguage=n!==null?n:i}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 handleStartModifier(e,t){e.addEventListener("click",async i=>{const n=$t.fromSubscription(this.key,this.region);n.speechRecognitionLanguage=this.sourceLanguage,n.addTargetLanguage(this.targetLanguage);const s=Y.fromDefaultMicrophoneInput();this.recognizer=new Ji(n,s),document.dispatchEvent(new CustomEvent("COAzureSTTStartedRecording",{})),this.recognizer.recognizeOnceAsync(o=>{if(o.reason===A.TranslatedSpeech){const a=o.translations.get(this.targetLanguage),u=document.getElementById(t.value);u!==null&&(u instanceof HTMLInputElement?u.value+=`${a} `:u.innerHTML+=`${a} `)}this.stop()},o=>{console.log(o),this.stop()})})}async handleStopModifier(e,t){e.addEventListener("click",async i=>{await this.stop()})}async stop(){this.recognizer!==void 0&&(this.recognizer.close(),this.recognizer=void 0),document.dispatchEvent(new CustomEvent("COAzureSTTStoppedRecording",{}))}}class xr{constructor(e,t,i,n=0,s=0,o=""){m(this,"key");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,"interval");m(this,"wordEncounters",[]);m(this,"originalHighlightDivInnerHTML","");m(this,"currentWord","");m(this,"currentOffset",0);m(this,"wordBoundaryOffset",0);m(this,"prevTextOffset",0);m(this,"url","");this.key=e,this.region=t,this.voice=i,this.rate=n,this.pitch=s,this.url=o}async start(){await this.registerBindings(document)}setVoice(e){return this.voice=e,this}setRate(e){return this.rate=e,this}setPitch(e){return this.pitch=e,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;this.stopPlayer(),await this.createInterval();const n=document.getElementById(t.value);if(this.clickedNode=n,!!n){if(n.hasAttribute("co-tts.text")&&n.getAttribute("co-tts.text")!==""?this.textToRead=(s=n.getAttribute("co-tts.text"))!=null?s:"":this.textToRead=n.innerText,n.hasAttribute("co-tts.highlight"))if(((o=n.attributes.getNamedItem("co-tts.highlight"))==null?void 0:o.value)!==""){const a=document.getElementById(n.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=a,this.originalHighlightDivInnerHTML=a.innerHTML}else this.highlightDiv=n,this.originalHighlightDivInnerHTML=n.innerHTML;this.startSynthesizer(e,t)}})}async handleAjaxModifier(e,t){e.addEventListener("click",async i=>{this.stopPlayer(),await this.createInterval(),this.clickedNode=e;const n=await fetch(t.value,{method:"GET"});this.textToRead=await n.text(),this.startSynthesizer(e,t)})}async handleDefault(e,t){e.addEventListener("click",async i=>{var n;if(this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(((n=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:n.value)!==""){const s=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=s,this.originalHighlightDivInnerHTML=s.innerHTML}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;t.value===""?this.textToRead=e.innerText:this.textToRead=t.value,this.startSynthesizer(e,t)})}async handleWithoutClick(e,t){var i;if(this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(((i=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:i.value)!==""){const n=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=n,n!==null&&(this.originalHighlightDivInnerHTML=n.innerHTML)}else this.highlightDiv=e,this.originalHighlightDivInnerHTML=e.innerHTML;t.value===""?this.textToRead=e.innerText:this.textToRead=t.value,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=>{await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{}))})}async handleResumeModifier(e,t){e.addEventListener("click",async i=>{await this.createInterval(),await this.player.resume(),document.dispatchEvent(new CustomEvent("COAzureTTSResumedPlaying",{}))})}async stopPlayer(){await this.clearInterval(),this.highlightDiv!==void 0&&(this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML),this.textToRead="",this.currentWord="",this.originalHighlightDivInnerHTML="",this.wordBoundryList=[],this.wordEncounters=[],this.player!==void 0&&this.player.pause(),this.player=void 0,this.highlightDiv=void 0,this.prevTextOffset=0}async startSynthesizer(e,t){this.speechConfig=ft.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=g.Audio24Khz160KBitRateMonoMp3,this.player=new mt,this.audioConfig=Y.fromSpeakerOutput(this.player),this.synthesizer=new Ke(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(i,n)=>{this.wordBoundryList.push(n)},this.player.onAudioEnd=async()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const i=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));i&&i.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(i,i.attributes.getNamedItem("co-tts.text")):i&&i.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},this.synthesizer.speakSsmlAsync(this.buildSSML(this.textToRead),()=>{this.synthesizer.close(),this.synthesizer=void 0},()=>{this.synthesizer.close(),this.synthesizer=void 0})}async clearInterval(){clearInterval(this.interval)}async createInterval(){this.interval=setInterval(()=>{var e;if(this.player!==void 0&&this.highlightDiv){const t=this.player.currentTime;let i;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)i=n;else break;if(i!==void 0)if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(i.text)&&(i=(e=this.previousWordBoundary)!=null?e:void 0),i===void 0||this.prevTextOffset>i.prevTextOffset)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else if(this.wordEncounters[i.text]||(this.wordEncounters[i.text]=0),this.prevTextOffset=i.prevTextOffset,(this.currentWord!==i.text||this.wordBoundaryOffset!==i.textOffset)&&(this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,i.text,this.wordEncounters[i.text]),this.wordEncounters[i.text]=this.currentOffset+i.wordLength,this.currentWord=i.text,this.wordBoundaryOffset=i.textOffset),this.currentOffset===Number.MAX_SAFE_INTEGER)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else{this.previousWordBoundary=i;const n=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset),s=this.currentOffset+i.wordLength,o=this.originalHighlightDivInnerHTML.substring(s);this.highlightDiv.innerHTML=`
|
21
21
|
${n}<mark class='co-tts-highlight'>${i.text}</mark>${o}
|
22
|
-
`}else this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML}},50)}getPosition(e,t,i){const n=new RegExp(`(?:^|[^-\\w])(${t})\\b`,"g"),s=e.slice(i).search(n);let o=s<=0?Number.MAX_SAFE_INTEGER:s+1;return o!==Number.MAX_SAFE_INTEGER&&(o+=i),o}buildSSML(e){
|
22
|
+
`}else this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML}},50)}getPosition(e,t,i){const n=new RegExp(`(?:^|[^-\\w])(${t})\\b`,"g"),s=e.slice(i).search(n);let o=s<=0?Number.MAX_SAFE_INTEGER:s+1;return o!==Number.MAX_SAFE_INTEGER&&(o+=i),o}buildSSML(e){let t=`<speak xmlns="http://www.w3.org/2001/10/synthesis"
|
23
23
|
xmlns:mstts="http://www.w3.org/2001/mstts"
|
24
24
|
xmlns:emo="http://www.w3.org/2009/10/emotionml"
|
25
25
|
version="1.0"
|
26
26
|
xml:lang="en-US">
|
27
|
-
<voice name="${this.voice}"
|
28
|
-
<prosody rate="${this.rate}%" pitch="${this.pitch}%">
|
29
|
-
${e}
|
30
|
-
</prosody>
|
31
|
-
</voice>
|
32
|
-
</speak>`}}_.SpeechToText=Nr,_.TextToSpeech=xr,Object.defineProperties(_,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
27
|
+
<voice name="${this.voice}">`;return this.url!==""&&(t+=`<lexicon uri="${this.url}"/>`),t+=`<prosody rate="${this.rate}%" pitch="${this.pitch}%">${e}</prosody></voice></speak>`,t}}_.SpeechToText=Nr,_.TextToSpeech=xr,Object.defineProperties(_,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|