@creativeorange/azure-text-to-speech 1.1.5 → 1.1.6
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/co-azure-tts.es.js +21 -4
- package/dist/co-azure-tts.umd.js +16 -6
- package/package.json +1 -1
- package/src/main.ts +21 -3
package/dist/co-azure-tts.es.js
CHANGED
@@ -5842,10 +5842,12 @@ class RestMessageAdapter {
|
|
5842
5842
|
}
|
5843
5843
|
}
|
5844
5844
|
class TextToSpeech {
|
5845
|
-
constructor(key, region, voice) {
|
5845
|
+
constructor(key, region, voice, rate = 0, pitch = 0) {
|
5846
5846
|
__publicField(this, "key");
|
5847
5847
|
__publicField(this, "region");
|
5848
5848
|
__publicField(this, "voice");
|
5849
|
+
__publicField(this, "rate");
|
5850
|
+
__publicField(this, "pitch");
|
5849
5851
|
__publicField(this, "textToRead", "");
|
5850
5852
|
__publicField(this, "wordBoundryList", []);
|
5851
5853
|
__publicField(this, "clickedNode");
|
@@ -5864,6 +5866,8 @@ class TextToSpeech {
|
|
5864
5866
|
this.key = key;
|
5865
5867
|
this.region = region;
|
5866
5868
|
this.voice = voice;
|
5869
|
+
this.rate = rate;
|
5870
|
+
this.pitch = pitch;
|
5867
5871
|
}
|
5868
5872
|
async start() {
|
5869
5873
|
await this.registerBindings(document);
|
@@ -5965,7 +5969,6 @@ class TextToSpeech {
|
|
5965
5969
|
await this.createInterval();
|
5966
5970
|
this.clickedNode = node;
|
5967
5971
|
if (node.hasAttribute("co-tts.highlight")) {
|
5968
|
-
console.log(node.attributes.getNamedItem("co-tts.highlight"));
|
5969
5972
|
if (((_a = node.attributes.getNamedItem("co-tts.highlight")) == null ? void 0 : _a.value) !== "") {
|
5970
5973
|
const newReferenceDiv = document.getElementById(node.attributes.getNamedItem("co-tts.highlight").value);
|
5971
5974
|
this.highlightDiv = newReferenceDiv;
|
@@ -6044,8 +6047,9 @@ class TextToSpeech {
|
|
6044
6047
|
this.player.onAudioStart = async () => {
|
6045
6048
|
document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying", {}));
|
6046
6049
|
};
|
6047
|
-
this.
|
6048
|
-
|
6050
|
+
console.log(this.buildSSML(this.textToRead));
|
6051
|
+
this.synthesizer.speakSsmlAsync(
|
6052
|
+
this.buildSSML(this.textToRead),
|
6049
6053
|
() => {
|
6050
6054
|
this.synthesizer.close();
|
6051
6055
|
this.synthesizer = void 0;
|
@@ -6115,5 +6119,18 @@ class TextToSpeech {
|
|
6115
6119
|
const offset = string.slice(lastOffset).search(regex);
|
6116
6120
|
return (offset <= 0 ? offset : offset + 1) + lastOffset;
|
6117
6121
|
}
|
6122
|
+
buildSSML(text) {
|
6123
|
+
return `<speak xmlns="http://www.w3.org/2001/10/synthesis"
|
6124
|
+
xmlns:mstts="http://www.w3.org/2001/mstts"
|
6125
|
+
xmlns:emo="http://www.w3.org/2009/10/emotionml"
|
6126
|
+
version="1.0"
|
6127
|
+
xml:lang="en-US">
|
6128
|
+
<voice name="${this.voice}">
|
6129
|
+
<prosody rate="${this.rate}%" pitch="${this.pitch}%">
|
6130
|
+
${text}
|
6131
|
+
</prosody>
|
6132
|
+
</voice>
|
6133
|
+
</speak>`;
|
6134
|
+
}
|
6118
6135
|
}
|
6119
6136
|
export { TextToSpeech as default };
|
package/dist/co-azure-tts.umd.js
CHANGED
@@ -1,8 +1,8 @@
|
|
1
|
-
(function(z,T){typeof exports=="object"&&typeof module!="undefined"?module.exports=T():typeof define=="function"&&define.amd?define(T):(z=typeof globalThis!="undefined"?globalThis:z||self,z.CreativeOrangeAzureTextToSpeech=T())})(this,function(){"use strict";var Oi=Object.defineProperty;var _i=(z,T,q)=>T in z?Oi(z,T,{enumerable:!0,configurable:!0,writable:!0,value:q}):z[T]=q;var E=(z,T,q)=>(_i(z,typeof T!="symbol"?T+"":T,q),q);var z={},T,q=new Uint8Array(16);function Tt(){if(!T&&(T=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!T))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return T(q)}var Rt=/^(?:[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 Dt(i){return typeof i=="string"&&Rt.test(i)}for(var P=[],ke=0;ke<256;++ke)P.push((ke+256).toString(16).substr(1));function kt(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(P[i[e+0]]+P[i[e+1]]+P[i[e+2]]+P[i[e+3]]+"-"+P[i[e+4]]+P[i[e+5]]+"-"+P[i[e+6]]+P[i[e+7]]+"-"+P[i[e+8]]+P[i[e+9]]+"-"+P[i[e+10]]+P[i[e+11]]+P[i[e+12]]+P[i[e+13]]+P[i[e+14]]+P[i[e+15]]).toLowerCase();if(!Dt(t))throw TypeError("Stringified UUID is invalid");return t}function It(i,e,t){i=i||{};var r=i.random||(i.rng||Tt)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(var n=0;n<16;++n)e[t+n]=r[n];return e}return kt(r)}const zt=()=>It(),A=()=>zt().replace(new RegExp("-","g"),"").toUpperCase();var S;(function(i){i[i.Debug=0]="Debug",i[i.Info=1]="Info",i[i.Warning=2]="Warning",i[i.Error=3]="Error",i[i.None=4]="None"})(S||(S={}));class F{constructor(e,t){this.privName=e,this.privEventId=A(),this.privEventTime=new Date().toISOString(),this.privEventType=t,this.privMetadata={}}get name(){return this.privName}get eventId(){return this.privEventId}get eventTime(){return this.privEventTime}get eventType(){return this.privEventType}get metadata(){return this.privMetadata}}class se extends F{constructor(e,t,r=S.Info){super(e,r),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class le extends se{constructor(e){super("AudioSourceInitializingEvent",e)}}class oe extends se{constructor(e){super("AudioSourceReadyEvent",e)}}class Ye extends se{constructor(e){super("AudioSourceOffEvent",e)}}class Ie extends se{constructor(e,t){super("AudioSourceErrorEvent",e,S.Error),this.privError=t}get error(){return this.privError}}class fe extends se{constructor(e,t,r){super(e,t),this.privAudioNodeId=r}get audioNodeId(){return this.privAudioNodeId}}class me extends fe{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class Se extends fe{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class K extends fe{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class et extends fe{constructor(e,t,r){super("AudioStreamNodeErrorEvent",e,t),this.privError=r}get error(){return this.privError}}class xt extends F{constructor(e,t,r=S.Info){super(e,r),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class J extends F{constructor(e,t,r=S.Info){super(e,r),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class Bt extends J{constructor(e,t,r){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=r}get uri(){return this.privUri}get headers(){return this.privHeaders}}class Nt extends J{constructor(e){super("ConnectionEstablishedEvent",e)}}class Lt extends J{constructor(e,t,r){super("ConnectionClosedEvent",e,S.Debug),this.privReason=r,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class Ot extends J{constructor(e,t,r){super("ConnectionErrorEvent",e,S.Debug),this.privMessage=t,this.privType=r}get message(){return this.privMessage}get type(){return this.privType}}class tt extends J{constructor(e,t,r){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=r}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class _t extends J{constructor(e,t,r){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=r}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class k extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class B extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class ze extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var g;(function(i){i[i.Text=0]="Text",i[i.Binary=1]="Binary"})(g||(g={}));class xe{constructor(e,t,r,n){if(this.privBody=null,e===g.Text&&t&&typeof t!="string")throw new B("Payload must be a string");if(e===g.Binary&&t&&!(t instanceof ArrayBuffer))throw new B("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=r||{},this.privId=n||A(),this.messageType){case g.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case g.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===g.Binary)throw new B("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===g.Text)throw new B("Not supported for text message");return this.privBody}get id(){return this.privId}}class Be{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}class H{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new ze("EventSource");if(this.metadata)for(const t in this.metadata)t&&e.metadata&&(e.metadata[t]||(e.metadata[t]=this.metadata[t]));for(const t in this.privEventListeners)t&&this.privEventListeners[t]&&this.privEventListeners[t](e)}attach(e){const t=A();return this.privEventListeners[t]=e,{detach:()=>(delete this.privEventListeners[t],Promise.resolve())}}attachListener(e){return this.attach(t=>e.onEvent(t))}attachConsoleListener(e){return this.privConsoleListener&&this.privConsoleListener.detach(),this.privConsoleListener=this.attach(t=>e.onEvent(t)),this.privConsoleListener}isDisposed(){return this.privIsDisposed}dispose(){this.privEventListeners=null,this.privIsDisposed=!0}get metadata(){return this.privMetadata}}class R{static setEventSource(e){if(!e)throw new k("eventSource");R.privInstance=e}static get instance(){return R.privInstance}}R.privInstance=new H;var M;(function(i){i[i.None=0]="None",i[i.Connected=1]="Connected",i[i.Connecting=2]="Connecting",i[i.Disconnected=3]="Disconnected"})(M||(M={}));class L{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 r=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),r}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 r=0;r<this.privList.length;r++)t.push(e(this.privList[r],r));return new L(t)}where(e){this.throwIfDisposed();const t=new L;for(let r=0;r<this.privList.length;r++)e(this.privList[r],r)&&t.add(this.privList[r]);return t}orderBy(e){this.throwIfDisposed();const r=this.toArray().sort(e);return new L(r)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,r)=>e(r,t))}clone(){return this.throwIfDisposed(),new L(this.toArray())}concat(e){return this.throwIfDisposed(),new L(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new L(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 ze("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var it;(function(i){i[i.None=0]="None",i[i.Resolved=1]="Resolved",i[i.Rejected=2]="Rejected"})(it||(it={}));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 Kt(i,e,t){i.then(r=>{try{e&&e(r)}catch(n){if(t)try{if(n instanceof Error){const s=n;t(s.name+": "+s.message)}else t(n)}catch{}}},r=>{if(t)try{if(r instanceof Error){const n=r;t(n.name+": "+n.message)}else t(r)}catch{}})}var rt=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})},ae;(function(i){i[i.Dequeue=0]="Dequeue",i[i.Peek=1]="Peek"})(ae||(ae={}));class he{constructor(e){this.privPromiseStore=new L,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new L,this.privDetachables=[],this.privSubscribers=new L,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:ae.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new D;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:ae.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return rt(this,void 0,void 0,function*(){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;const r=this.privSubscribers;if(r){for(;r.length()>0;)r.removeFirst().deferral.resolve(void 0);this.privSubscribers===r&&(this.privSubscribers=r)}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 rt(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 r=e.removeFirst();if(r.type===ae.Peek)r.deferral.resolve(t.first());else{const n=t.removeFirst();r.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 B(this.privDisposeReason):new ze("Queue");if(this.privIsDisposing)throw new B("Queue disposing")}}class ge{constructor(e,t,r){if(this.privPayload=null,!t)throw new k("payload");if(e===g.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new B("Payload must be ArrayBuffer");if(e===g.Text&&typeof t!="string")throw new B("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=r||A()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===g.Binary)throw new B("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===g.Text)throw new B("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Ht{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 r=t.length*2,n=new ArrayBuffer(r),s=new DataView(n);return this.floatTo16BitPCM(s,0,t),n}setString(e,t,r){for(let n=0;n<r.length;n++)e.setUint8(t+n,r.charCodeAt(n))}floatTo16BitPCM(e,t,r){for(let n=0;n<r.length;n++,t+=2){const s=Math.max(-1,Math.min(1,r[n]));e.setInt16(t,s<0?s*32768:s*32767,!0)}}downSampleAudioFrame(e,t,r){if(!e)return null;if(r===t||r>t)return e;const n=t/r,s=Math.round(e.length/n),o=new Float32Array(s);let a=0,u=0;for(;u<s;){const c=Math.round((u+1)*n);let h=0,p=0;for(;a<c&&a<e.length;)h+=e[a++],p++;o[u++]=h/p}return o}}var Ut=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class nt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||A(),this.privReaderQueue=new he}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 B("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>Ut(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 he)}throwIfClosed(){if(this.privIsWriteEnded)throw new B("Stream closed")}}class Ne extends nt{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 r=Math.min(e.buffer.byteLength-t,this.privTargetChunkSize-this.privNextBufferReadyBytes),n=new Uint8Array(this.privNextBufferToWrite),s=new Uint8Array(e.buffer.slice(t,r+t));n.set(s,this.privNextBufferReadyBytes),this.privNextBufferReadyBytes+=r,t+=r,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 I extends F{constructor(e,t,r){super(e,t),this.privSignature=r}}class Wt extends I{constructor(e){super("OCSPMemoryCacheHitEvent",S.Debug,e)}}class Vt extends I{constructor(e){super("OCSPCacheMissEvent",S.Debug,e)}}class qt extends I{constructor(e){super("OCSPDiskCacheHitEvent",S.Debug,e)}}class jt extends I{constructor(e){super("OCSPCacheUpdateNeededEvent",S.Debug,e)}}class $t extends I{constructor(e){super("OCSPMemoryCacheStoreEvent",S.Debug,e)}}class Gt extends I{constructor(e){super("OCSPDiskCacheStoreEvent",S.Debug,e)}}class Ft extends I{constructor(e){super("OCSPCacheUpdateCompleteEvent",S.Debug,e)}}class Jt extends I{constructor(){super("OCSPStapleReceivedEvent",S.Debug,"")}}class Qt extends I{constructor(e,t){super("OCSPCacheEntryExpiredEvent",S.Debug,e),this.privExpireTime=t}}class Xt extends I{constructor(e,t,r){super("OCSPCacheEntryNeedsRefreshEvent",S.Debug,e),this.privExpireTime=r,this.privStartTime=t}}class Zt extends I{constructor(e,t,r){super("OCSPCacheHitEvent",S.Debug,e),this.privExpireTime=r,this.privExpireTimeString=new Date(r).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class Yt extends I{constructor(e,t){super("OCSPVerificationFailedEvent",S.Debug,e),this.privError=t}}class st extends I{constructor(e,t){super("OCSPCacheFetchErrorEvent",S.Debug,e),this.privError=t}}class ei extends I{constructor(e){super("OCSPResponseRetrievedEvent",S.Debug,e)}}class ti extends I{constructor(e,t){super("OCSPCacheUpdateErrorEvent",S.Debug,e),this.privError=t}}class ce extends F{constructor(e){super("BackgroundEvent",S.Error),this.privError=e}get error(){return this.privError}}class C{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(C.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(C.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const r of e)C.throwIfNullOrWhitespace(r,t)}static throwIfFileDoesNotExist(e,t){C.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class y{}y.AuthKey="Ocp-Apim-Subscription-Key",y.ConnectionId="X-ConnectionId",y.ContentType="Content-Type",y.CustomCommandsAppId="X-CommandsAppId",y.Path="Path",y.RequestId="X-RequestId",y.RequestStreamId="X-StreamId",y.RequestTimestamp="X-Timestamp";class Le{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class ii{constructor(e){if(!e)throw new k("subscriptionKey");this.privAuthInfo=new Le(y.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 k("fetchCallback");if(!t)throw new k("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new Le(ot,ue.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new Le(ot,ue.privTokenPrefix+t))}}ue.privTokenPrefix="bearer ";class at{constructor(e){C.throwIfNullOrUndefined(void 0,`
|
2
|
-
File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){C.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){C.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(i){i[i.PCM=1]="PCM",i[i.MuLaw=2]="MuLaw",i[i.Siren=3]="Siren",i[i.MP3=4]="MP3",i[i.SILKSkype=5]="SILKSkype",i[i.OGG_OPUS=6]="OGG_OPUS",i[i.WEBM_OPUS=7]="WEBM_OPUS",i[i.ALaw=8]="ALaw",i[i.FLAC=9]="FLAC",i[i.OPUS=10]="OPUS"})(v||(v={}));class we{static getDefaultInputFormat(){return U.getDefaultInputFormat()}static getWaveFormat(e,t,r,n){return new U(e,t,r,n)}static getWaveFormatPCM(e,t,r){return new U(e,t,r)}}class U extends we{constructor(e=16e3,t=16,r=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=r,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 U}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,r){for(let n=0;n<r.length;n++)e.setUint8(t+n,r.charCodeAt(n))}}var Oe=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class _e{constructor(){}static createPushStream(e){return ht.create(e)}static createPullStream(e,t){return ct.create(e,t)}}class ht extends _e{static create(e){return new ri(e)}}class ri extends ht{constructor(e){super(),e===void 0?this.privFormat=U.getDefaultInputFormat():this.privFormat=e,this.privEvents=new H,this.privId=A(),this.privStream=new Ne(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 r=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(r)):(typeof Blob!="undefined"?t.push(s.buffer):r=Buffer.concat([r,this.toBuffer(s.buffer)]),n()));return n()})}turnOn(){this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}attach(e){return Oe(this,void 0,void 0,function*(){this.onEvent(new me(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new Se(this.privId,e)),{detach:()=>Oe(this,void 0,void 0,function*(){return this.onEvent(new K(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new K(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:re.Stream})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}toBuffer(e){const t=Buffer.alloc(e.byteLength),r=new Uint8Array(e);for(let n=0;n<t.length;++n)t[n]=r[n];return t}}class ct extends _e{constructor(){super()}static create(e,t){return new ut(e,t)}}class ut extends ct{constructor(e,t){super(),t===void 0?this.privFormat=we.getDefaultInputFormat():this.privFormat=t,this.privEvents=new H,this.privId=A(),this.privCallback=e,this.privIsClosed=!1,this.privBufferSize=this.privFormat.avgBytesPerSec/10}get format(){return Promise.resolve(this.privFormat)}close(){this.privIsClosed=!0,this.privCallback.close()}id(){return this.privId}get blob(){return Promise.reject("Not implemented")}turnOn(){this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}attach(e){return Oe(this,void 0,void 0,function*(){return this.onEvent(new me(this.privId,e)),yield this.turnOn(),this.onEvent(new Se(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new K(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let t=0,r;for(;t<this.privBufferSize;){const n=new ArrayBuffer(this.privBufferSize-t),s=this.privCallback.read(n);if(r===void 0?r=n:new Int8Array(r).set(new Int8Array(n),t),s===0)break;t+=s}return Promise.resolve({buffer:r.slice(0,t),isEnd:this.privIsClosed||t===0,timeReceived:Date.now()})}}})}detach(e){this.onEvent(new K(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:re.Stream})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}}var f;(function(i){i[i.Raw8Khz8BitMonoMULaw=0]="Raw8Khz8BitMonoMULaw",i[i.Riff16Khz16KbpsMonoSiren=1]="Riff16Khz16KbpsMonoSiren",i[i.Audio16Khz16KbpsMonoSiren=2]="Audio16Khz16KbpsMonoSiren",i[i.Audio16Khz32KBitRateMonoMp3=3]="Audio16Khz32KBitRateMonoMp3",i[i.Audio16Khz128KBitRateMonoMp3=4]="Audio16Khz128KBitRateMonoMp3",i[i.Audio16Khz64KBitRateMonoMp3=5]="Audio16Khz64KBitRateMonoMp3",i[i.Audio24Khz48KBitRateMonoMp3=6]="Audio24Khz48KBitRateMonoMp3",i[i.Audio24Khz96KBitRateMonoMp3=7]="Audio24Khz96KBitRateMonoMp3",i[i.Audio24Khz160KBitRateMonoMp3=8]="Audio24Khz160KBitRateMonoMp3",i[i.Raw16Khz16BitMonoTrueSilk=9]="Raw16Khz16BitMonoTrueSilk",i[i.Riff16Khz16BitMonoPcm=10]="Riff16Khz16BitMonoPcm",i[i.Riff8Khz16BitMonoPcm=11]="Riff8Khz16BitMonoPcm",i[i.Riff24Khz16BitMonoPcm=12]="Riff24Khz16BitMonoPcm",i[i.Riff8Khz8BitMonoMULaw=13]="Riff8Khz8BitMonoMULaw",i[i.Raw16Khz16BitMonoPcm=14]="Raw16Khz16BitMonoPcm",i[i.Raw24Khz16BitMonoPcm=15]="Raw24Khz16BitMonoPcm",i[i.Raw8Khz16BitMonoPcm=16]="Raw8Khz16BitMonoPcm",i[i.Ogg16Khz16BitMonoOpus=17]="Ogg16Khz16BitMonoOpus",i[i.Ogg24Khz16BitMonoOpus=18]="Ogg24Khz16BitMonoOpus",i[i.Raw48Khz16BitMonoPcm=19]="Raw48Khz16BitMonoPcm",i[i.Riff48Khz16BitMonoPcm=20]="Riff48Khz16BitMonoPcm",i[i.Audio48Khz96KBitRateMonoMp3=21]="Audio48Khz96KBitRateMonoMp3",i[i.Audio48Khz192KBitRateMonoMp3=22]="Audio48Khz192KBitRateMonoMp3",i[i.Ogg48Khz16BitMonoOpus=23]="Ogg48Khz16BitMonoOpus",i[i.Webm16Khz16BitMonoOpus=24]="Webm16Khz16BitMonoOpus",i[i.Webm24Khz16BitMonoOpus=25]="Webm24Khz16BitMonoOpus",i[i.Raw24Khz16BitMonoTrueSilk=26]="Raw24Khz16BitMonoTrueSilk",i[i.Raw8Khz8BitMonoALaw=27]="Raw8Khz8BitMonoALaw",i[i.Riff8Khz8BitMonoALaw=28]="Riff8Khz8BitMonoALaw",i[i.Webm24Khz16Bit24KbpsMonoOpus=29]="Webm24Khz16Bit24KbpsMonoOpus",i[i.Audio16Khz16Bit32KbpsMonoOpus=30]="Audio16Khz16Bit32KbpsMonoOpus",i[i.Audio24Khz16Bit48KbpsMonoOpus=31]="Audio24Khz16Bit48KbpsMonoOpus",i[i.Audio24Khz16Bit24KbpsMonoOpus=32]="Audio24Khz16Bit24KbpsMonoOpus",i[i.Raw22050Hz16BitMonoPcm=33]="Raw22050Hz16BitMonoPcm",i[i.Riff22050Hz16BitMonoPcm=34]="Riff22050Hz16BitMonoPcm",i[i.Raw44100Hz16BitMonoPcm=35]="Raw44100Hz16BitMonoPcm",i[i.Riff44100Hz16BitMonoPcm=36]="Riff44100Hz16BitMonoPcm"})(f||(f={}));class l extends U{constructor(e,t,r,n,s,o,a,u,c){super(r,o,t,e),this.formatTag=e,this.avgBytesPerSec=n,this.blockAlign=s,this.priAudioFormatString=a,this.priRequestAudioFormatString=u,this.priHasHeader=c}static fromSpeechSynthesisOutputFormat(e){return e===void 0?l.getDefaultOutputFormat():l.fromSpeechSynthesisOutputFormatString(l.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new l(v.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new l(v.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new l(v.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new l(v.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new l(v.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new l(v.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new l(v.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new l(v.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new l(v.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new l(v.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new l(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new l(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new l(v.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new l(v.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new l(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new l(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new l(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new l(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new l(v.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new l(v.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new l(v.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new l(v.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new l(v.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new l(v.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new l(v.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new l(v.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new l(v.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new l(v.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new l(v.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new l(v.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new l(v.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new l(v.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new l(v.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new l(v.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new l(v.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new l(v.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return l.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}}l.SpeechSynthesisOutputFormatToString={[f.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[f.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[f.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[f.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[f.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[f.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[f.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[f.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[f.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[f.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[f.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[f.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[f.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[f.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[f.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[f.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[f.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[f.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[f.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[f.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[f.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[f.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[f.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[f.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[f.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[f.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[f.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[f.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[f.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[f.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[f.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[f.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[f.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[f.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[f.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[f.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[f.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var ni=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class pt{constructor(){}static createPullStream(){return Ce.create()}}class Ce extends pt{static create(){return new Ke}}class Ke extends Ce{constructor(){super(),this.privId=A(),this.privStream=new nt}set format(e){e==null&&(this.privFormat=l.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return ni(this,void 0,void 0,function*(){const t=new Int8Array(e);let r=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),r=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;r<e.byteLength&&!this.privStream.isReadEnded;){const n=yield this.privStream.read();if(n!==void 0&&!n.isEnd){let s;n.buffer.byteLength>e.byteLength-r?(s=n.buffer.slice(0,e.byteLength-r),this.privLastChunkView=new Int8Array(n.buffer.slice(e.byteLength-r))):s=n.buffer,t.set(new Int8Array(s),r),r+=s.byteLength}else this.privStream.readEnded()}return r})}write(e){C.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class dt extends pt{constructor(){super()}static create(e){return new He(e)}}class He extends dt{constructor(e){super(),this.privId=A(),this.privCallback=e}set format(e){}write(e){this.privCallback.write&&this.privCallback.write(e)}close(){this.privCallback.close&&this.privCallback.close()}id(){return this.privId}}class Q{static fromDefaultMicrophoneInput(){const e=new Qe(!0);return new X(new N(e))}static fromMicrophoneInput(e){const t=new Qe(!0);return new X(new N(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new X(new Ti(e,t))}static fromStreamInput(e){if(e instanceof si)return new X(new ut(e));if(e instanceof _e)return new X(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new Qe(!1);return new X(new N(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new Z(new Ve)}static fromSpeakerOutput(e){if(e===void 0)return Q.fromDefaultSpeakerOutput();if(e instanceof Ve)return new Z(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new Z(new at(e))}static fromStreamOutput(e){if(e instanceof vt)return new Z(new He(e));if(e instanceof dt)return new Z(e);if(e instanceof Ce)return new Z(e);throw new Error("Not Supported Type")}}class X extends Q{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then(()=>{e&&e()},r=>{t&&t(r)})}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(C.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 Z extends Q{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 ye;(function(i){i[i.Error=0]="Error",i[i.EndOfStream=1]="EndOfStream"})(ye||(ye={}));class si{}class vt{}var pe;(function(i){i[i.Simple=0]="Simple",i[i.Detailed=1]="Detailed"})(pe||(pe={}));var W;(function(i){i[i.NoMatch=0]="NoMatch",i[i.Canceled=1]="Canceled",i[i.RecognizingSpeech=2]="RecognizingSpeech",i[i.RecognizedSpeech=3]="RecognizedSpeech",i[i.RecognizedKeyword=4]="RecognizedKeyword",i[i.RecognizingIntent=5]="RecognizingIntent",i[i.RecognizedIntent=6]="RecognizedIntent",i[i.TranslatingSpeech=7]="TranslatingSpeech",i[i.TranslatedSpeech=8]="TranslatedSpeech",i[i.SynthesizingAudio=9]="SynthesizingAudio",i[i.SynthesizingAudioCompleted=10]="SynthesizingAudioCompleted",i[i.SynthesizingAudioStarted=11]="SynthesizingAudioStarted",i[i.EnrollingVoiceProfile=12]="EnrollingVoiceProfile",i[i.EnrolledVoiceProfile=13]="EnrolledVoiceProfile",i[i.RecognizedSpeakers=14]="RecognizedSpeakers",i[i.RecognizedSpeaker=15]="RecognizedSpeaker",i[i.ResetVoiceProfile=16]="ResetVoiceProfile",i[i.DeletedVoiceProfile=17]="DeletedVoiceProfile",i[i.VoicesListRetrieved=18]="VoicesListRetrieved"})(W||(W={}));class lt{constructor(){}static fromSubscription(e,t){C.throwIfNullOrWhitespace(e,"subscriptionKey"),C.throwIfNullOrWhitespace(t,"region");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Region,t),r.setProperty(d.SpeechServiceConnection_IntentRegion,t),r.setProperty(d.SpeechServiceConnection_Key,e),r}static fromEndpoint(e,t){C.throwIfNull(e,"endpoint");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&r.setProperty(d.SpeechServiceConnection_Key,t),r}static fromHost(e,t){C.throwIfNull(e,"hostName");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&r.setProperty(d.SpeechServiceConnection_Key,t),r}static fromAuthorizationToken(e,t){C.throwIfNull(e,"authorizationToken"),C.throwIfNullOrWhitespace(t,"region");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Region,t),r.setProperty(d.SpeechServiceConnection_IntentRegion,t),r.authorizationToken=e,r}close(){}}class Y extends lt{constructor(){super(),this.privProperties=new ee,this.speechRecognitionLanguage="en-US",this.outputFormat=pe.Simple}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(d.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(d.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(d.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(d.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(d.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(d.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(d.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return pe[this.privProperties.getProperty(At,void 0)]}set outputFormat(e){this.privProperties.setProperty(At,pe[e])}get endpointId(){return this.privProperties.getProperty(d.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(d.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){C.throwIfNull(t,"value"),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,r,n){this.setProperty(d[d.SpeechServiceConnection_ProxyHostName],e),this.setProperty(d[d.SpeechServiceConnection_ProxyPort],t),this.setProperty(d[d.SpeechServiceConnection_ProxyUserName],r),this.setProperty(d[d.SpeechServiceConnection_ProxyPassword],n)}setServiceProperty(e,t){const r=JSON.parse(this.privProperties.getProperty(Fe,"{}"));r[e]=t,this.privProperties.setProperty(Fe,JSON.stringify(r))}setProfanity(e){this.privProperties.setProperty(d.SpeechServiceResponse_ProfanityOption,Ue[e])}enableAudioLogging(){this.privProperties.setProperty(d.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(d.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(Ai,"true")}clone(){const e=new Y;return e.privProperties=this.privProperties.clone(),e}get speechSynthesisLanguage(){return this.privProperties.getProperty(d.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(d.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return f[this.privProperties.getProperty(d.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthOutputFormat,f[e])}}class ee{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,t){let r;typeof e=="string"?r=e:r=d[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===r)return this.privValues[n];if(t!==void 0)return String(t)}setProperty(e,t){let r;typeof e=="string"?r=e:r=d[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===r){this.privValues[n]=t;return}this.privKeys.push(r),this.privValues.push(t)}clone(){const e=new ee;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 r=this.getProperty(t);e.setProperty(t,r)}})}get keys(){return this.privKeys}}var d;(function(i){i[i.SpeechServiceConnection_Key=0]="SpeechServiceConnection_Key",i[i.SpeechServiceConnection_Endpoint=1]="SpeechServiceConnection_Endpoint",i[i.SpeechServiceConnection_Region=2]="SpeechServiceConnection_Region",i[i.SpeechServiceAuthorization_Token=3]="SpeechServiceAuthorization_Token",i[i.SpeechServiceAuthorization_Type=4]="SpeechServiceAuthorization_Type",i[i.SpeechServiceConnection_EndpointId=5]="SpeechServiceConnection_EndpointId",i[i.SpeechServiceConnection_TranslationToLanguages=6]="SpeechServiceConnection_TranslationToLanguages",i[i.SpeechServiceConnection_TranslationVoice=7]="SpeechServiceConnection_TranslationVoice",i[i.SpeechServiceConnection_TranslationFeatures=8]="SpeechServiceConnection_TranslationFeatures",i[i.SpeechServiceConnection_IntentRegion=9]="SpeechServiceConnection_IntentRegion",i[i.SpeechServiceConnection_ProxyHostName=10]="SpeechServiceConnection_ProxyHostName",i[i.SpeechServiceConnection_ProxyPort=11]="SpeechServiceConnection_ProxyPort",i[i.SpeechServiceConnection_ProxyUserName=12]="SpeechServiceConnection_ProxyUserName",i[i.SpeechServiceConnection_ProxyPassword=13]="SpeechServiceConnection_ProxyPassword",i[i.SpeechServiceConnection_RecoMode=14]="SpeechServiceConnection_RecoMode",i[i.SpeechServiceConnection_RecoLanguage=15]="SpeechServiceConnection_RecoLanguage",i[i.Speech_SessionId=16]="Speech_SessionId",i[i.SpeechServiceConnection_SynthLanguage=17]="SpeechServiceConnection_SynthLanguage",i[i.SpeechServiceConnection_SynthVoice=18]="SpeechServiceConnection_SynthVoice",i[i.SpeechServiceConnection_SynthOutputFormat=19]="SpeechServiceConnection_SynthOutputFormat",i[i.SpeechServiceConnection_AutoDetectSourceLanguages=20]="SpeechServiceConnection_AutoDetectSourceLanguages",i[i.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]="SpeechServiceResponse_RequestDetailedResultTrueFalse",i[i.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]="SpeechServiceResponse_RequestProfanityFilterTrueFalse",i[i.SpeechServiceResponse_JsonResult=23]="SpeechServiceResponse_JsonResult",i[i.SpeechServiceResponse_JsonErrorDetails=24]="SpeechServiceResponse_JsonErrorDetails",i[i.CancellationDetails_Reason=25]="CancellationDetails_Reason",i[i.CancellationDetails_ReasonText=26]="CancellationDetails_ReasonText",i[i.CancellationDetails_ReasonDetailedText=27]="CancellationDetails_ReasonDetailedText",i[i.LanguageUnderstandingServiceResponse_JsonResult=28]="LanguageUnderstandingServiceResponse_JsonResult",i[i.SpeechServiceConnection_Url=29]="SpeechServiceConnection_Url",i[i.SpeechServiceConnection_InitialSilenceTimeoutMs=30]="SpeechServiceConnection_InitialSilenceTimeoutMs",i[i.SpeechServiceConnection_EndSilenceTimeoutMs=31]="SpeechServiceConnection_EndSilenceTimeoutMs",i[i.Speech_SegmentationSilenceTimeoutMs=32]="Speech_SegmentationSilenceTimeoutMs",i[i.SpeechServiceConnection_EnableAudioLogging=33]="SpeechServiceConnection_EnableAudioLogging",i[i.SpeechServiceConnection_AtStartLanguageIdPriority=34]="SpeechServiceConnection_AtStartLanguageIdPriority",i[i.SpeechServiceConnection_ContinuousLanguageIdPriority=35]="SpeechServiceConnection_ContinuousLanguageIdPriority",i[i.SpeechServiceConnection_RecognitionEndpointVersion=36]="SpeechServiceConnection_RecognitionEndpointVersion",i[i.SpeechServiceResponse_ProfanityOption=37]="SpeechServiceResponse_ProfanityOption",i[i.SpeechServiceResponse_PostProcessingOption=38]="SpeechServiceResponse_PostProcessingOption",i[i.SpeechServiceResponse_RequestWordLevelTimestamps=39]="SpeechServiceResponse_RequestWordLevelTimestamps",i[i.SpeechServiceResponse_StablePartialResultThreshold=40]="SpeechServiceResponse_StablePartialResultThreshold",i[i.SpeechServiceResponse_OutputFormatOption=41]="SpeechServiceResponse_OutputFormatOption",i[i.SpeechServiceResponse_TranslationRequestStablePartialResult=42]="SpeechServiceResponse_TranslationRequestStablePartialResult",i[i.SpeechServiceResponse_RequestWordBoundary=43]="SpeechServiceResponse_RequestWordBoundary",i[i.SpeechServiceResponse_RequestPunctuationBoundary=44]="SpeechServiceResponse_RequestPunctuationBoundary",i[i.SpeechServiceResponse_RequestSentenceBoundary=45]="SpeechServiceResponse_RequestSentenceBoundary",i[i.Conversation_ApplicationId=46]="Conversation_ApplicationId",i[i.Conversation_DialogType=47]="Conversation_DialogType",i[i.Conversation_Initial_Silence_Timeout=48]="Conversation_Initial_Silence_Timeout",i[i.Conversation_From_Id=49]="Conversation_From_Id",i[i.Conversation_Conversation_Id=50]="Conversation_Conversation_Id",i[i.Conversation_Custom_Voice_Deployment_Ids=51]="Conversation_Custom_Voice_Deployment_Ids",i[i.Conversation_Speech_Activity_Template=52]="Conversation_Speech_Activity_Template",i[i.Conversation_Request_Bot_Status_Messages=53]="Conversation_Request_Bot_Status_Messages",i[i.Conversation_Agent_Connection_Id=54]="Conversation_Agent_Connection_Id",i[i.SpeechServiceConnection_Host=55]="SpeechServiceConnection_Host",i[i.ConversationTranslator_Host=56]="ConversationTranslator_Host",i[i.ConversationTranslator_Name=57]="ConversationTranslator_Name",i[i.ConversationTranslator_CorrelationId=58]="ConversationTranslator_CorrelationId",i[i.ConversationTranslator_Token=59]="ConversationTranslator_Token",i[i.PronunciationAssessment_ReferenceText=60]="PronunciationAssessment_ReferenceText",i[i.PronunciationAssessment_GradingSystem=61]="PronunciationAssessment_GradingSystem",i[i.PronunciationAssessment_Granularity=62]="PronunciationAssessment_Granularity",i[i.PronunciationAssessment_EnableMiscue=63]="PronunciationAssessment_EnableMiscue",i[i.PronunciationAssessment_Json=64]="PronunciationAssessment_Json",i[i.PronunciationAssessment_Params=65]="PronunciationAssessment_Params",i[i.SpeakerRecognition_Api_Version=66]="SpeakerRecognition_Api_Version"})(d||(d={}));var te;(function(i){i[i.NoError=0]="NoError",i[i.AuthenticationFailure=1]="AuthenticationFailure",i[i.BadRequestParameters=2]="BadRequestParameters",i[i.TooManyRequests=3]="TooManyRequests",i[i.ConnectionFailure=4]="ConnectionFailure",i[i.ServiceTimeout=5]="ServiceTimeout",i[i.ServiceError=6]="ServiceError",i[i.RuntimeError=7]="RuntimeError",i[i.Forbidden=8]="Forbidden"})(te||(te={}));class m{}m.BotId="botid",m.CustomSpeechDeploymentId="cid",m.CustomVoiceDeploymentId="deploymentId",m.EnableAudioLogging="storeAudio",m.EnableLanguageId="lidEnabled",m.EnableWordLevelTimestamps="wordLevelTimestamps",m.EndSilenceTimeoutMs="endSilenceTimeoutMs",m.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",m.Format="format",m.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",m.Language="language",m.Profanity="profanity",m.RequestBotStatusMessages="enableBotMessageStatus",m.StableIntermediateThreshold="stableIntermediateThreshold",m.StableTranslation="stableTranslation",m.TestHooks="testhooks",m.Postprocessing="postprocessing";class ft{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,r){new Map([[d.Speech_SegmentationSilenceTimeoutMs,m.SegmentationSilenceTimeoutMs],[d.SpeechServiceConnection_EnableAudioLogging,m.EnableAudioLogging],[d.SpeechServiceConnection_EndSilenceTimeoutMs,m.EndSilenceTimeoutMs],[d.SpeechServiceConnection_InitialSilenceTimeoutMs,m.InitialSilenceTimeoutMs],[d.SpeechServiceResponse_PostProcessingOption,m.Postprocessing],[d.SpeechServiceResponse_ProfanityOption,m.Profanity],[d.SpeechServiceResponse_RequestWordLevelTimestamps,m.EnableWordLevelTimestamps],[d.SpeechServiceResponse_StablePartialResultThreshold,m.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,r)});const s=JSON.parse(e.parameters.getProperty(Fe,"{}"));Object.keys(s).forEach(o=>{t[o]=s[o]})}setUrlParameter(e,t,r,n,s){const o=r.parameters.getProperty(e,void 0);o&&(!s||s.search(t)===-1)&&(n[t]=o.toLocaleLowerCase())}}var Ue;(function(i){i[i.Masked=0]="Masked",i[i.Removed=1]="Removed",i[i.Raw=2]="Raw"})(Ue||(Ue={}));var be=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Ee{constructor(e,t){const r=e;C.throwIfNull(r,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:Q.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=r.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new fi,this.synthesisRequestQueue=new he,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(d.SpeechServiceAuthorization_Token)}set authorizationToken(e){C.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(d.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages)===Pi}static FromConfig(e,t,r){const n=e;return t.properties.mergeTo(n.properties),new Ee(e,r)}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 r=this.properties.getProperty(d.SpeechServiceConnection_SynthLanguage,"en-US"),n=this.properties.getProperty(d.SpeechServiceConnection_SynthVoice,""),s=Ee.XMLEncode(e);return this.autoDetectSourceLanguage?r="en-US":n=n||t[r],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='${r}'>${s}</speak>`,s}speakTextAsync(e,t,r,n){this.speakImpl(e,!1,t,r,n)}speakSsmlAsync(e,t,r,n){this.speakImpl(e,!0,t,r,n)}getVoicesAsync(e=""){return be(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){C.throwIfDisposed(this.privDisposed),Kt(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return be(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new yi(e,this.privProperties)}createSynthesisAdapter(e,t,r,n){return new ne(e,t,n,this,this.audioConfig)}implCommonSynthesizeSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",r="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,r=navigator.appVersion);const n=this.createSynthesizerConfig(new yt(new bt(new vi(e,t,r)))),s=this.privProperties.getProperty(d.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new ii(s):new ue(()=>{const a=this.privProperties.getProperty(d.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)},()=>{const a=this.privProperties.getProperty(d.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)});this.privAdapter=this.createSynthesisAdapter(o,this.privConnectionFactory,this.audioConfig,n),this.privAdapter.audioOutputFormat=l.fromSpeechSynthesisOutputFormat(f[this.properties.getProperty(d.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new Ci(n)}speakImpl(e,t,r,n,s){try{C.throwIfDisposed(this.privDisposed);const o=A();let a;s instanceof vt?a=new He(s):s instanceof Ce?a=s:s!==void 0?a=new at(s):a=void 0,this.synthesisRequestQueue.enqueue(new oi(o,e,t,u=>{if(this.privSynthesizing=!1,r)try{r(u)}catch(c){n&&n(c)}r=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 be(this,void 0,void 0,function*(){const t=A(),r=yield this.privRestAdapter.getVoicesList(t);if(r.ok&&Array.isArray(r.json)){let n=r.json;return!!e&&e.length>0&&(n=n.filter(s=>!!s.Locale&&s.Locale.toLowerCase()===e.toLowerCase())),new St(t,n,void 0)}else return new St(t,void 0,`Error: ${r.status}: ${r.statusText}`)})}adapterSpeak(){return be(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 oi{constructor(e,t,r,n,s,o){this.requestId=e,this.text=t,this.isSSML=r,this.cb=n,this.err=s,this.dataStream=o}}class mt{constructor(e,t,r,n){this.privResultId=e,this.privReason=t,this.privErrorDetails=r,this.privProperties=n}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}class Ae extends mt{constructor(e,t,r,n,s,o){super(e,t,n,s),this.privAudioData=r,this.privAudioDuration=o}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}class Pe{constructor(e){this.privResult=e}get result(){return this.privResult}}class ai{constructor(e,t,r,n,s,o){this.privAudioOffset=e,this.privDuration=t,this.privText=r,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 hi{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class ci{constructor(e,t,r){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=r}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}class St extends mt{constructor(e,t,r){if(Array.isArray(t)){super(e,W.VoicesListRetrieved,void 0,new ee),this.privVoices=[];for(const n of t)this.privVoices.push(new ui(n))}else super(e,W.Canceled,r||"Error information unavailable",new ee)}get voices(){return this.privVoices}}var de;(function(i){i[i.Unknown=0]="Unknown",i[i.Female=1]="Female",i[i.Male=2]="Male"})(de||(de={}));var Me;(function(i){i[i.OnlineNeural=1]="OnlineNeural",i[i.OnlineStandard=2]="OnlineStandard",i[i.OfflineNeural=3]="OfflineNeural",i[i.OfflineStandard=4]="OfflineStandard"})(Me||(Me={}));class ui{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")?Me.OnlineStandard:Me.OnlineNeural,this.privGender=e.Gender==="Male"?de.Male:e.Gender==="Female"?de.Female:de.Unknown,!!e.StyleList&&Array.isArray(e.StyleList)))for(const t of e.StyleList)this.privStyleList.push(t)}get name(){return this.privName}get locale(){return this.privLocale}get shortName(){return this.privShortName}get localName(){return this.privLocalName}get gender(){return this.privGender}get voiceType(){return this.privVoiceType}get styleList(){return this.privStyleList}get voicePath(){return this.privVoicePath}}var We=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};const pi=60*30,gt={[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 Ve{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||A(),this.privIsPaused=!1,this.privIsClosed=!1}id(){return this.privId}write(e,t,r){this.privAudioBuffer!==void 0?(this.privAudioBuffer.push(e),this.updateSourceBuffer().then(()=>{t&&t()},n=>{r&&r(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()},r=>{t&&t(r)});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 r=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(r).then(()=>{r=ne.addHeader(r,this.privFormat);const n=new Blob([r],{type:gt[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=gt[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=pi,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(r=>{R.instance.onEvent(new ce(r))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(r=>{R.instance.onEvent(new ce(r))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(r=>{R.instance.onEvent(new ce(r))})):(console.warn(`Format ${v[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new Ke,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()},r=>{t&&t(r)}),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}updateSourceBuffer(){return We(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 We(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return We(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 j extends xe{constructor(e,t,r,n,s,o,a,u){if(!t)throw new k("path");if(!r)throw new k("requestId");const c={};if(c[y.Path]=t,c[y.RequestId]=r,c[y.RequestTimestamp]=new Date().toISOString(),n&&(c[y.ContentType]=n),o&&(c[y.RequestStreamId]=o),a)for(const h in a)h&&(c[h]=a[h]);u?super(e,s,c,u):super(e,s,c),this.privPath=t,this.privRequestId=r,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,r=null,n=null,s=null;const o={};if(e.headers)for(const a in e.headers)a&&(a.toLowerCase()===y.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===y.RequestId.toLowerCase()?r=e.headers[a]:a.toLowerCase()===y.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===y.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new j(e.messageType,t,r,n,e.body,s,o,e.id)}}var wt;(function(i){i[i.Interactive=0]="Interactive",i[i.Conversation=1]="Conversation",i[i.Dictation=2]="Dictation"})(wt||(wt={}));var Ct;(function(i){i[i.Simple=0]="Simple",i[i.Detailed=1]="Detailed"})(Ct||(Ct={}));class yt{constructor(e){this.context=e}serialize(){return JSON.stringify(this,(e,t)=>{if(t&&typeof t=="object"){const r={};for(const n in t)Object.hasOwnProperty.call(t,n)&&(r[n&&n.charAt(0).toLowerCase()+n.substring(1)]=t[n]);return r}return t})}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}}class bt{constructor(e){this.system=new di,this.os=e}}class di{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class vi{constructor(e,t,r){this.platform=e,this.name=t,this.version=r}}var ie;(function(i){i.Bluetooth="Bluetooth",i.Wired="Wired",i.WiFi="WiFi",i.Cellular="Cellular",i.InBuilt="InBuilt",i.Unknown="Unknown"})(ie||(ie={}));var re;(function(i){i.Phone="Phone",i.Speaker="Speaker",i.Car="Car",i.Headset="Headset",i.Thermostat="Thermostat",i.Microphones="Microphones",i.Deskphone="Deskphone",i.RemoteControl="RemoteControl",i.Unknown="Unknown",i.File="File",i.Stream="Stream"})(re||(re={}));const Et=`\r
|
3
|
-
`;class li{toConnectionMessage(e){const t=new
|
1
|
+
(function(z,T){typeof exports=="object"&&typeof module!="undefined"?module.exports=T():typeof define=="function"&&define.amd?define(T):(z=typeof globalThis!="undefined"?globalThis:z||self,z.CreativeOrangeAzureTextToSpeech=T())})(this,function(){"use strict";var Oi=Object.defineProperty;var _i=(z,T,q)=>T in z?Oi(z,T,{enumerable:!0,configurable:!0,writable:!0,value:q}):z[T]=q;var E=(z,T,q)=>(_i(z,typeof T!="symbol"?T+"":T,q),q);var z={},T,q=new Uint8Array(16);function Tt(){if(!T&&(T=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!T))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return T(q)}var Rt=/^(?:[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 kt(i){return typeof i=="string"&&Rt.test(i)}for(var P=[],De=0;De<256;++De)P.push((De+256).toString(16).substr(1));function Dt(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(P[i[e+0]]+P[i[e+1]]+P[i[e+2]]+P[i[e+3]]+"-"+P[i[e+4]]+P[i[e+5]]+"-"+P[i[e+6]]+P[i[e+7]]+"-"+P[i[e+8]]+P[i[e+9]]+"-"+P[i[e+10]]+P[i[e+11]]+P[i[e+12]]+P[i[e+13]]+P[i[e+14]]+P[i[e+15]]).toLowerCase();if(!kt(t))throw TypeError("Stringified UUID is invalid");return t}function It(i,e,t){i=i||{};var r=i.random||(i.rng||Tt)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(var n=0;n<16;++n)e[t+n]=r[n];return e}return Dt(r)}const zt=()=>It(),A=()=>zt().replace(new RegExp("-","g"),"").toUpperCase();var S;(function(i){i[i.Debug=0]="Debug",i[i.Info=1]="Info",i[i.Warning=2]="Warning",i[i.Error=3]="Error",i[i.None=4]="None"})(S||(S={}));class F{constructor(e,t){this.privName=e,this.privEventId=A(),this.privEventTime=new Date().toISOString(),this.privEventType=t,this.privMetadata={}}get name(){return this.privName}get eventId(){return this.privEventId}get eventTime(){return this.privEventTime}get eventType(){return this.privEventType}get metadata(){return this.privMetadata}}class se extends F{constructor(e,t,r=S.Info){super(e,r),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}class le extends se{constructor(e){super("AudioSourceInitializingEvent",e)}}class oe extends se{constructor(e){super("AudioSourceReadyEvent",e)}}class Ye extends se{constructor(e){super("AudioSourceOffEvent",e)}}class Ie extends se{constructor(e,t){super("AudioSourceErrorEvent",e,S.Error),this.privError=t}get error(){return this.privError}}class fe extends se{constructor(e,t,r){super(e,t),this.privAudioNodeId=r}get audioNodeId(){return this.privAudioNodeId}}class me extends fe{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}}class Se extends fe{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}}class K extends fe{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}}class et extends fe{constructor(e,t,r){super("AudioStreamNodeErrorEvent",e,t),this.privError=r}get error(){return this.privError}}class xt extends F{constructor(e,t,r=S.Info){super(e,r),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}class J extends F{constructor(e,t,r=S.Info){super(e,r),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}class Bt extends J{constructor(e,t,r){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=r}get uri(){return this.privUri}get headers(){return this.privHeaders}}class Nt extends J{constructor(e){super("ConnectionEstablishedEvent",e)}}class Lt extends J{constructor(e,t,r){super("ConnectionClosedEvent",e,S.Debug),this.privReason=r,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}}class Ot extends J{constructor(e,t,r){super("ConnectionErrorEvent",e,S.Debug),this.privMessage=t,this.privType=r}get message(){return this.privMessage}get type(){return this.privType}}class tt extends J{constructor(e,t,r){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=r}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}}class _t extends J{constructor(e,t,r){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=r}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}}class D extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}class B extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}class ze extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}var g;(function(i){i[i.Text=0]="Text",i[i.Binary=1]="Binary"})(g||(g={}));class xe{constructor(e,t,r,n){if(this.privBody=null,e===g.Text&&t&&typeof t!="string")throw new B("Payload must be a string");if(e===g.Binary&&t&&!(t instanceof ArrayBuffer))throw new B("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=r||{},this.privId=n||A(),this.messageType){case g.Binary:this.privSize=this.binaryBody!==null?this.binaryBody.byteLength:0;break;case g.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===g.Binary)throw new B("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===g.Text)throw new B("Not supported for text message");return this.privBody}get id(){return this.privId}}class Be{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}class H{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new ze("EventSource");if(this.metadata)for(const t in this.metadata)t&&e.metadata&&(e.metadata[t]||(e.metadata[t]=this.metadata[t]));for(const t in this.privEventListeners)t&&this.privEventListeners[t]&&this.privEventListeners[t](e)}attach(e){const t=A();return this.privEventListeners[t]=e,{detach:()=>(delete this.privEventListeners[t],Promise.resolve())}}attachListener(e){return this.attach(t=>e.onEvent(t))}attachConsoleListener(e){return this.privConsoleListener&&this.privConsoleListener.detach(),this.privConsoleListener=this.attach(t=>e.onEvent(t)),this.privConsoleListener}isDisposed(){return this.privIsDisposed}dispose(){this.privEventListeners=null,this.privIsDisposed=!0}get metadata(){return this.privMetadata}}class R{static setEventSource(e){if(!e)throw new D("eventSource");R.privInstance=e}static get instance(){return R.privInstance}}R.privInstance=new H;var M;(function(i){i[i.None=0]="None",i[i.Connected=1]="Connected",i[i.Connecting=2]="Connecting",i[i.Disconnected=3]="Disconnected"})(M||(M={}));class L{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 r=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),r}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 r=0;r<this.privList.length;r++)t.push(e(this.privList[r],r));return new L(t)}where(e){this.throwIfDisposed();const t=new L;for(let r=0;r<this.privList.length;r++)e(this.privList[r],r)&&t.add(this.privList[r]);return t}orderBy(e){this.throwIfDisposed();const r=this.toArray().sort(e);return new L(r)}orderByDesc(e){return this.throwIfDisposed(),this.orderBy((t,r)=>e(r,t))}clone(){return this.throwIfDisposed(),new L(this.toArray())}concat(e){return this.throwIfDisposed(),new L(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new L(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 ze("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}var it;(function(i){i[i.None=0]="None",i[i.Resolved=1]="Resolved",i[i.Rejected=2]="Rejected"})(it||(it={}));class k{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 Kt(i,e,t){i.then(r=>{try{e&&e(r)}catch(n){if(t)try{if(n instanceof Error){const s=n;t(s.name+": "+s.message)}else t(n)}catch{}}},r=>{if(t)try{if(r instanceof Error){const n=r;t(n.name+": "+n.message)}else t(r)}catch{}})}var rt=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})},ae;(function(i){i[i.Dequeue=0]="Dequeue",i[i.Peek=1]="Peek"})(ae||(ae={}));class he{constructor(e){this.privPromiseStore=new L,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new L,this.privDetachables=[],this.privSubscribers=new L,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 k;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:ae.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new k;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:ae.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return this.privSubscribers==null}drainAndDispose(e,t){return rt(this,void 0,void 0,function*(){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;const r=this.privSubscribers;if(r){for(;r.length()>0;)r.removeFirst().deferral.resolve(void 0);this.privSubscribers===r&&(this.privSubscribers=r)}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 rt(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 r=e.removeFirst();if(r.type===ae.Peek)r.deferral.resolve(t.first());else{const n=t.removeFirst();r.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 B(this.privDisposeReason):new ze("Queue");if(this.privIsDisposing)throw new B("Queue disposing")}}class ge{constructor(e,t,r){if(this.privPayload=null,!t)throw new D("payload");if(e===g.Binary&&t.__proto__.constructor.name!=="ArrayBuffer")throw new B("Payload must be ArrayBuffer");if(e===g.Text&&typeof t!="string")throw new B("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=r||A()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===g.Binary)throw new B("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===g.Text)throw new B("Not supported for text message");return this.privPayload}get id(){return this.privId}}class Ht{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 r=t.length*2,n=new ArrayBuffer(r),s=new DataView(n);return this.floatTo16BitPCM(s,0,t),n}setString(e,t,r){for(let n=0;n<r.length;n++)e.setUint8(t+n,r.charCodeAt(n))}floatTo16BitPCM(e,t,r){for(let n=0;n<r.length;n++,t+=2){const s=Math.max(-1,Math.min(1,r[n]));e.setInt16(t,s<0?s*32768:s*32767,!0)}}downSampleAudioFrame(e,t,r){if(!e)return null;if(r===t||r>t)return e;const n=t/r,s=Math.round(e.length/n),o=new Float32Array(s);let a=0,u=0;for(;u<s;){const c=Math.round((u+1)*n);let h=0,p=0;for(;a<c&&a<e.length;)h+=e[a++],p++;o[u++]=h/p}return o}}var Ut=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class nt{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||A(),this.privReaderQueue=new he}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 B("Stream read has already finished");return this.privReaderQueue.dequeue().then(e=>Ut(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 he)}throwIfClosed(){if(this.privIsWriteEnded)throw new B("Stream closed")}}class Ne extends nt{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 r=Math.min(e.buffer.byteLength-t,this.privTargetChunkSize-this.privNextBufferReadyBytes),n=new Uint8Array(this.privNextBufferToWrite),s=new Uint8Array(e.buffer.slice(t,r+t));n.set(s,this.privNextBufferReadyBytes),this.privNextBufferReadyBytes+=r,t+=r,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 I extends F{constructor(e,t,r){super(e,t),this.privSignature=r}}class Wt extends I{constructor(e){super("OCSPMemoryCacheHitEvent",S.Debug,e)}}class Vt extends I{constructor(e){super("OCSPCacheMissEvent",S.Debug,e)}}class qt extends I{constructor(e){super("OCSPDiskCacheHitEvent",S.Debug,e)}}class $t extends I{constructor(e){super("OCSPCacheUpdateNeededEvent",S.Debug,e)}}class jt extends I{constructor(e){super("OCSPMemoryCacheStoreEvent",S.Debug,e)}}class Gt extends I{constructor(e){super("OCSPDiskCacheStoreEvent",S.Debug,e)}}class Ft extends I{constructor(e){super("OCSPCacheUpdateCompleteEvent",S.Debug,e)}}class Jt extends I{constructor(){super("OCSPStapleReceivedEvent",S.Debug,"")}}class Qt extends I{constructor(e,t){super("OCSPCacheEntryExpiredEvent",S.Debug,e),this.privExpireTime=t}}class Xt extends I{constructor(e,t,r){super("OCSPCacheEntryNeedsRefreshEvent",S.Debug,e),this.privExpireTime=r,this.privStartTime=t}}class Zt extends I{constructor(e,t,r){super("OCSPCacheHitEvent",S.Debug,e),this.privExpireTime=r,this.privExpireTimeString=new Date(r).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}}class Yt extends I{constructor(e,t){super("OCSPVerificationFailedEvent",S.Debug,e),this.privError=t}}class st extends I{constructor(e,t){super("OCSPCacheFetchErrorEvent",S.Debug,e),this.privError=t}}class ei extends I{constructor(e){super("OCSPResponseRetrievedEvent",S.Debug,e)}}class ti extends I{constructor(e,t){super("OCSPCacheUpdateErrorEvent",S.Debug,e),this.privError=t}}class ce extends F{constructor(e){super("BackgroundEvent",S.Error),this.privError=e}get error(){return this.privError}}class C{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(C.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(C.throwIfNullOrUndefined(e,t),e.length===0)throw new Error("throwIfArrayEmptyOrWhitespace:"+t);for(const r of e)C.throwIfNullOrWhitespace(r,t)}static throwIfFileDoesNotExist(e,t){C.throwIfNullOrWhitespace(e,t)}static throwIfNotUndefined(e,t){if(e!==void 0)throw new Error("throwIfNotUndefined:"+t)}}class y{}y.AuthKey="Ocp-Apim-Subscription-Key",y.ConnectionId="X-ConnectionId",y.ContentType="Content-Type",y.CustomCommandsAppId="X-CommandsAppId",y.Path="Path",y.RequestId="X-RequestId",y.RequestStreamId="X-StreamId",y.RequestTimestamp="X-Timestamp";class Le{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}class ii{constructor(e){if(!e)throw new D("subscriptionKey");this.privAuthInfo=new Le(y.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 D("fetchCallback");if(!t)throw new D("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then(t=>new Le(ot,ue.privTokenPrefix+t))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then(t=>new Le(ot,ue.privTokenPrefix+t))}}ue.privTokenPrefix="bearer ";class at{constructor(e){C.throwIfNullOrUndefined(void 0,`
|
2
|
+
File System access not available, please use Push or PullAudioOutputStream`),this.privFd=(void 0)(e,"w")}set format(e){C.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){C.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(i){i[i.PCM=1]="PCM",i[i.MuLaw=2]="MuLaw",i[i.Siren=3]="Siren",i[i.MP3=4]="MP3",i[i.SILKSkype=5]="SILKSkype",i[i.OGG_OPUS=6]="OGG_OPUS",i[i.WEBM_OPUS=7]="WEBM_OPUS",i[i.ALaw=8]="ALaw",i[i.FLAC=9]="FLAC",i[i.OPUS=10]="OPUS"})(v||(v={}));class we{static getDefaultInputFormat(){return U.getDefaultInputFormat()}static getWaveFormat(e,t,r,n){return new U(e,t,r,n)}static getWaveFormatPCM(e,t,r){return new U(e,t,r)}}class U extends we{constructor(e=16e3,t=16,r=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=r,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 U}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,r){for(let n=0;n<r.length;n++)e.setUint8(t+n,r.charCodeAt(n))}}var Oe=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class _e{constructor(){}static createPushStream(e){return ht.create(e)}static createPullStream(e,t){return ct.create(e,t)}}class ht extends _e{static create(e){return new ri(e)}}class ri extends ht{constructor(e){super(),e===void 0?this.privFormat=U.getDefaultInputFormat():this.privFormat=e,this.privEvents=new H,this.privId=A(),this.privStream=new Ne(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 r=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(r)):(typeof Blob!="undefined"?t.push(s.buffer):r=Buffer.concat([r,this.toBuffer(s.buffer)]),n()));return n()})}turnOn(){this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}attach(e){return Oe(this,void 0,void 0,function*(){this.onEvent(new me(this.privId,e)),yield this.turnOn();const t=this.privStream;return this.onEvent(new Se(this.privId,e)),{detach:()=>Oe(this,void 0,void 0,function*(){return this.onEvent(new K(this.privId,e)),this.turnOff()}),id:()=>e,read:()=>t.read()}})}detach(e){this.onEvent(new K(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:re.Stream})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}toBuffer(e){const t=Buffer.alloc(e.byteLength),r=new Uint8Array(e);for(let n=0;n<t.length;++n)t[n]=r[n];return t}}class ct extends _e{constructor(){super()}static create(e,t){return new ut(e,t)}}class ut extends ct{constructor(e,t){super(),t===void 0?this.privFormat=we.getDefaultInputFormat():this.privFormat=t,this.privEvents=new H,this.privId=A(),this.privCallback=e,this.privIsClosed=!1,this.privBufferSize=this.privFormat.avgBytesPerSec/10}get format(){return Promise.resolve(this.privFormat)}close(){this.privIsClosed=!0,this.privCallback.close()}id(){return this.privId}get blob(){return Promise.reject("Not implemented")}turnOn(){this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}attach(e){return Oe(this,void 0,void 0,function*(){return this.onEvent(new me(this.privId,e)),yield this.turnOn(),this.onEvent(new Se(this.privId,e)),{detach:()=>(this.privCallback.close(),this.onEvent(new K(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let t=0,r;for(;t<this.privBufferSize;){const n=new ArrayBuffer(this.privBufferSize-t),s=this.privCallback.read(n);if(r===void 0?r=n:new Int8Array(r).set(new Int8Array(n),t),s===0)break;t+=s}return Promise.resolve({buffer:r.slice(0,t),isEnd:this.privIsClosed||t===0,timeReceived:Date.now()})}}})}detach(e){this.onEvent(new K(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:"PullStream",samplerate:this.privFormat.samplesPerSec,type:re.Stream})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}}var f;(function(i){i[i.Raw8Khz8BitMonoMULaw=0]="Raw8Khz8BitMonoMULaw",i[i.Riff16Khz16KbpsMonoSiren=1]="Riff16Khz16KbpsMonoSiren",i[i.Audio16Khz16KbpsMonoSiren=2]="Audio16Khz16KbpsMonoSiren",i[i.Audio16Khz32KBitRateMonoMp3=3]="Audio16Khz32KBitRateMonoMp3",i[i.Audio16Khz128KBitRateMonoMp3=4]="Audio16Khz128KBitRateMonoMp3",i[i.Audio16Khz64KBitRateMonoMp3=5]="Audio16Khz64KBitRateMonoMp3",i[i.Audio24Khz48KBitRateMonoMp3=6]="Audio24Khz48KBitRateMonoMp3",i[i.Audio24Khz96KBitRateMonoMp3=7]="Audio24Khz96KBitRateMonoMp3",i[i.Audio24Khz160KBitRateMonoMp3=8]="Audio24Khz160KBitRateMonoMp3",i[i.Raw16Khz16BitMonoTrueSilk=9]="Raw16Khz16BitMonoTrueSilk",i[i.Riff16Khz16BitMonoPcm=10]="Riff16Khz16BitMonoPcm",i[i.Riff8Khz16BitMonoPcm=11]="Riff8Khz16BitMonoPcm",i[i.Riff24Khz16BitMonoPcm=12]="Riff24Khz16BitMonoPcm",i[i.Riff8Khz8BitMonoMULaw=13]="Riff8Khz8BitMonoMULaw",i[i.Raw16Khz16BitMonoPcm=14]="Raw16Khz16BitMonoPcm",i[i.Raw24Khz16BitMonoPcm=15]="Raw24Khz16BitMonoPcm",i[i.Raw8Khz16BitMonoPcm=16]="Raw8Khz16BitMonoPcm",i[i.Ogg16Khz16BitMonoOpus=17]="Ogg16Khz16BitMonoOpus",i[i.Ogg24Khz16BitMonoOpus=18]="Ogg24Khz16BitMonoOpus",i[i.Raw48Khz16BitMonoPcm=19]="Raw48Khz16BitMonoPcm",i[i.Riff48Khz16BitMonoPcm=20]="Riff48Khz16BitMonoPcm",i[i.Audio48Khz96KBitRateMonoMp3=21]="Audio48Khz96KBitRateMonoMp3",i[i.Audio48Khz192KBitRateMonoMp3=22]="Audio48Khz192KBitRateMonoMp3",i[i.Ogg48Khz16BitMonoOpus=23]="Ogg48Khz16BitMonoOpus",i[i.Webm16Khz16BitMonoOpus=24]="Webm16Khz16BitMonoOpus",i[i.Webm24Khz16BitMonoOpus=25]="Webm24Khz16BitMonoOpus",i[i.Raw24Khz16BitMonoTrueSilk=26]="Raw24Khz16BitMonoTrueSilk",i[i.Raw8Khz8BitMonoALaw=27]="Raw8Khz8BitMonoALaw",i[i.Riff8Khz8BitMonoALaw=28]="Riff8Khz8BitMonoALaw",i[i.Webm24Khz16Bit24KbpsMonoOpus=29]="Webm24Khz16Bit24KbpsMonoOpus",i[i.Audio16Khz16Bit32KbpsMonoOpus=30]="Audio16Khz16Bit32KbpsMonoOpus",i[i.Audio24Khz16Bit48KbpsMonoOpus=31]="Audio24Khz16Bit48KbpsMonoOpus",i[i.Audio24Khz16Bit24KbpsMonoOpus=32]="Audio24Khz16Bit24KbpsMonoOpus",i[i.Raw22050Hz16BitMonoPcm=33]="Raw22050Hz16BitMonoPcm",i[i.Riff22050Hz16BitMonoPcm=34]="Riff22050Hz16BitMonoPcm",i[i.Raw44100Hz16BitMonoPcm=35]="Raw44100Hz16BitMonoPcm",i[i.Riff44100Hz16BitMonoPcm=36]="Riff44100Hz16BitMonoPcm"})(f||(f={}));class l extends U{constructor(e,t,r,n,s,o,a,u,c){super(r,o,t,e),this.formatTag=e,this.avgBytesPerSec=n,this.blockAlign=s,this.priAudioFormatString=a,this.priRequestAudioFormatString=u,this.priHasHeader=c}static fromSpeechSynthesisOutputFormat(e){return e===void 0?l.getDefaultOutputFormat():l.fromSpeechSynthesisOutputFormatString(l.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new l(v.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new l(v.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new l(v.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new l(v.MP3,1,16e3,32<<7,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new l(v.MP3,1,16e3,128<<7,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new l(v.MP3,1,16e3,64<<7,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new l(v.MP3,1,24e3,48<<7,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new l(v.MP3,1,24e3,96<<7,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new l(v.MP3,1,24e3,160<<7,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new l(v.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new l(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new l(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new l(v.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new l(v.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new l(v.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new l(v.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new l(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new l(v.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new l(v.MP3,1,48e3,96<<7,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new l(v.MP3,1,48e3,192<<7,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new l(v.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new l(v.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new l(v.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new l(v.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new l(v.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new l(v.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new l(v.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new l(v.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new l(v.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new l(v.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new l(v.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new l(v.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new l(v.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new l(v.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new l(v.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new l(v.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"riff-16khz-16bit-mono-pcm":default:return new l(v.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return l.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}}l.SpeechSynthesisOutputFormatToString={[f.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[f.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[f.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[f.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[f.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[f.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[f.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[f.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[f.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[f.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[f.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[f.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[f.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[f.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[f.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[f.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[f.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[f.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[f.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[f.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[f.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[f.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[f.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[f.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[f.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[f.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[f.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[f.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[f.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[f.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[f.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[f.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[f.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[f.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[f.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[f.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[f.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm"};var ni=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class pt{constructor(){}static createPullStream(){return Ce.create()}}class Ce extends pt{static create(){return new Ke}}class Ke extends Ce{constructor(){super(),this.privId=A(),this.privStream=new nt}set format(e){e==null&&(this.privFormat=l.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}read(e){return ni(this,void 0,void 0,function*(){const t=new Int8Array(e);let r=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),r=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;r<e.byteLength&&!this.privStream.isReadEnded;){const n=yield this.privStream.read();if(n!==void 0&&!n.isEnd){let s;n.buffer.byteLength>e.byteLength-r?(s=n.buffer.slice(0,e.byteLength-r),this.privLastChunkView=new Int8Array(n.buffer.slice(e.byteLength-r))):s=n.buffer,t.set(new Int8Array(s),r),r+=s.byteLength}else this.privStream.readEnded()}return r})}write(e){C.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}class dt extends pt{constructor(){super()}static create(e){return new He(e)}}class He extends dt{constructor(e){super(),this.privId=A(),this.privCallback=e}set format(e){}write(e){this.privCallback.write&&this.privCallback.write(e)}close(){this.privCallback.close&&this.privCallback.close()}id(){return this.privId}}class Q{static fromDefaultMicrophoneInput(){const e=new Qe(!0);return new X(new N(e))}static fromMicrophoneInput(e){const t=new Qe(!0);return new X(new N(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new X(new Ti(e,t))}static fromStreamInput(e){if(e instanceof si)return new X(new ut(e));if(e instanceof _e)return new X(e);if(typeof MediaStream!="undefined"&&e instanceof MediaStream){const t=new Qe(!1);return new X(new N(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new Z(new Ve)}static fromSpeakerOutput(e){if(e===void 0)return Q.fromDefaultSpeakerOutput();if(e instanceof Ve)return new Z(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new Z(new at(e))}static fromStreamOutput(e){if(e instanceof vt)return new Z(new He(e));if(e instanceof dt)return new Z(e);if(e instanceof Ce)return new Z(e);throw new Error("Not Supported Type")}}class X extends Q{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then(()=>{e&&e()},r=>{t&&t(r)})}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(C.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 Z extends Q{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 ye;(function(i){i[i.Error=0]="Error",i[i.EndOfStream=1]="EndOfStream"})(ye||(ye={}));class si{}class vt{}var pe;(function(i){i[i.Simple=0]="Simple",i[i.Detailed=1]="Detailed"})(pe||(pe={}));var W;(function(i){i[i.NoMatch=0]="NoMatch",i[i.Canceled=1]="Canceled",i[i.RecognizingSpeech=2]="RecognizingSpeech",i[i.RecognizedSpeech=3]="RecognizedSpeech",i[i.RecognizedKeyword=4]="RecognizedKeyword",i[i.RecognizingIntent=5]="RecognizingIntent",i[i.RecognizedIntent=6]="RecognizedIntent",i[i.TranslatingSpeech=7]="TranslatingSpeech",i[i.TranslatedSpeech=8]="TranslatedSpeech",i[i.SynthesizingAudio=9]="SynthesizingAudio",i[i.SynthesizingAudioCompleted=10]="SynthesizingAudioCompleted",i[i.SynthesizingAudioStarted=11]="SynthesizingAudioStarted",i[i.EnrollingVoiceProfile=12]="EnrollingVoiceProfile",i[i.EnrolledVoiceProfile=13]="EnrolledVoiceProfile",i[i.RecognizedSpeakers=14]="RecognizedSpeakers",i[i.RecognizedSpeaker=15]="RecognizedSpeaker",i[i.ResetVoiceProfile=16]="ResetVoiceProfile",i[i.DeletedVoiceProfile=17]="DeletedVoiceProfile",i[i.VoicesListRetrieved=18]="VoicesListRetrieved"})(W||(W={}));class lt{constructor(){}static fromSubscription(e,t){C.throwIfNullOrWhitespace(e,"subscriptionKey"),C.throwIfNullOrWhitespace(t,"region");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Region,t),r.setProperty(d.SpeechServiceConnection_IntentRegion,t),r.setProperty(d.SpeechServiceConnection_Key,e),r}static fromEndpoint(e,t){C.throwIfNull(e,"endpoint");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Endpoint,e.href),t!==void 0&&r.setProperty(d.SpeechServiceConnection_Key,t),r}static fromHost(e,t){C.throwIfNull(e,"hostName");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(e.port===""?"":":"+e.port)),t!==void 0&&r.setProperty(d.SpeechServiceConnection_Key,t),r}static fromAuthorizationToken(e,t){C.throwIfNull(e,"authorizationToken"),C.throwIfNullOrWhitespace(t,"region");const r=new Y;return r.setProperty(d.SpeechServiceConnection_Region,t),r.setProperty(d.SpeechServiceConnection_IntentRegion,t),r.authorizationToken=e,r}close(){}}class Y extends lt{constructor(){super(),this.privProperties=new ee,this.speechRecognitionLanguage="en-US",this.outputFormat=pe.Simple}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(d.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(d.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(d.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(d.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(d.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(d.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(d.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return pe[this.privProperties.getProperty(At,void 0)]}set outputFormat(e){this.privProperties.setProperty(At,pe[e])}get endpointId(){return this.privProperties.getProperty(d.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(d.SpeechServiceConnection_EndpointId,e)}setProperty(e,t){C.throwIfNull(t,"value"),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,r,n){this.setProperty(d[d.SpeechServiceConnection_ProxyHostName],e),this.setProperty(d[d.SpeechServiceConnection_ProxyPort],t),this.setProperty(d[d.SpeechServiceConnection_ProxyUserName],r),this.setProperty(d[d.SpeechServiceConnection_ProxyPassword],n)}setServiceProperty(e,t){const r=JSON.parse(this.privProperties.getProperty(Fe,"{}"));r[e]=t,this.privProperties.setProperty(Fe,JSON.stringify(r))}setProfanity(e){this.privProperties.setProperty(d.SpeechServiceResponse_ProfanityOption,Ue[e])}enableAudioLogging(){this.privProperties.setProperty(d.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(d.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privProperties.setProperty(Ai,"true")}clone(){const e=new Y;return e.privProperties=this.privProperties.clone(),e}get speechSynthesisLanguage(){return this.privProperties.getProperty(d.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(d.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return f[this.privProperties.getProperty(d.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(d.SpeechServiceConnection_SynthOutputFormat,f[e])}}class ee{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,t){let r;typeof e=="string"?r=e:r=d[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===r)return this.privValues[n];if(t!==void 0)return String(t)}setProperty(e,t){let r;typeof e=="string"?r=e:r=d[e];for(let n=0;n<this.privKeys.length;n++)if(this.privKeys[n]===r){this.privValues[n]=t;return}this.privKeys.push(r),this.privValues.push(t)}clone(){const e=new ee;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 r=this.getProperty(t);e.setProperty(t,r)}})}get keys(){return this.privKeys}}var d;(function(i){i[i.SpeechServiceConnection_Key=0]="SpeechServiceConnection_Key",i[i.SpeechServiceConnection_Endpoint=1]="SpeechServiceConnection_Endpoint",i[i.SpeechServiceConnection_Region=2]="SpeechServiceConnection_Region",i[i.SpeechServiceAuthorization_Token=3]="SpeechServiceAuthorization_Token",i[i.SpeechServiceAuthorization_Type=4]="SpeechServiceAuthorization_Type",i[i.SpeechServiceConnection_EndpointId=5]="SpeechServiceConnection_EndpointId",i[i.SpeechServiceConnection_TranslationToLanguages=6]="SpeechServiceConnection_TranslationToLanguages",i[i.SpeechServiceConnection_TranslationVoice=7]="SpeechServiceConnection_TranslationVoice",i[i.SpeechServiceConnection_TranslationFeatures=8]="SpeechServiceConnection_TranslationFeatures",i[i.SpeechServiceConnection_IntentRegion=9]="SpeechServiceConnection_IntentRegion",i[i.SpeechServiceConnection_ProxyHostName=10]="SpeechServiceConnection_ProxyHostName",i[i.SpeechServiceConnection_ProxyPort=11]="SpeechServiceConnection_ProxyPort",i[i.SpeechServiceConnection_ProxyUserName=12]="SpeechServiceConnection_ProxyUserName",i[i.SpeechServiceConnection_ProxyPassword=13]="SpeechServiceConnection_ProxyPassword",i[i.SpeechServiceConnection_RecoMode=14]="SpeechServiceConnection_RecoMode",i[i.SpeechServiceConnection_RecoLanguage=15]="SpeechServiceConnection_RecoLanguage",i[i.Speech_SessionId=16]="Speech_SessionId",i[i.SpeechServiceConnection_SynthLanguage=17]="SpeechServiceConnection_SynthLanguage",i[i.SpeechServiceConnection_SynthVoice=18]="SpeechServiceConnection_SynthVoice",i[i.SpeechServiceConnection_SynthOutputFormat=19]="SpeechServiceConnection_SynthOutputFormat",i[i.SpeechServiceConnection_AutoDetectSourceLanguages=20]="SpeechServiceConnection_AutoDetectSourceLanguages",i[i.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]="SpeechServiceResponse_RequestDetailedResultTrueFalse",i[i.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]="SpeechServiceResponse_RequestProfanityFilterTrueFalse",i[i.SpeechServiceResponse_JsonResult=23]="SpeechServiceResponse_JsonResult",i[i.SpeechServiceResponse_JsonErrorDetails=24]="SpeechServiceResponse_JsonErrorDetails",i[i.CancellationDetails_Reason=25]="CancellationDetails_Reason",i[i.CancellationDetails_ReasonText=26]="CancellationDetails_ReasonText",i[i.CancellationDetails_ReasonDetailedText=27]="CancellationDetails_ReasonDetailedText",i[i.LanguageUnderstandingServiceResponse_JsonResult=28]="LanguageUnderstandingServiceResponse_JsonResult",i[i.SpeechServiceConnection_Url=29]="SpeechServiceConnection_Url",i[i.SpeechServiceConnection_InitialSilenceTimeoutMs=30]="SpeechServiceConnection_InitialSilenceTimeoutMs",i[i.SpeechServiceConnection_EndSilenceTimeoutMs=31]="SpeechServiceConnection_EndSilenceTimeoutMs",i[i.Speech_SegmentationSilenceTimeoutMs=32]="Speech_SegmentationSilenceTimeoutMs",i[i.SpeechServiceConnection_EnableAudioLogging=33]="SpeechServiceConnection_EnableAudioLogging",i[i.SpeechServiceConnection_AtStartLanguageIdPriority=34]="SpeechServiceConnection_AtStartLanguageIdPriority",i[i.SpeechServiceConnection_ContinuousLanguageIdPriority=35]="SpeechServiceConnection_ContinuousLanguageIdPriority",i[i.SpeechServiceConnection_RecognitionEndpointVersion=36]="SpeechServiceConnection_RecognitionEndpointVersion",i[i.SpeechServiceResponse_ProfanityOption=37]="SpeechServiceResponse_ProfanityOption",i[i.SpeechServiceResponse_PostProcessingOption=38]="SpeechServiceResponse_PostProcessingOption",i[i.SpeechServiceResponse_RequestWordLevelTimestamps=39]="SpeechServiceResponse_RequestWordLevelTimestamps",i[i.SpeechServiceResponse_StablePartialResultThreshold=40]="SpeechServiceResponse_StablePartialResultThreshold",i[i.SpeechServiceResponse_OutputFormatOption=41]="SpeechServiceResponse_OutputFormatOption",i[i.SpeechServiceResponse_TranslationRequestStablePartialResult=42]="SpeechServiceResponse_TranslationRequestStablePartialResult",i[i.SpeechServiceResponse_RequestWordBoundary=43]="SpeechServiceResponse_RequestWordBoundary",i[i.SpeechServiceResponse_RequestPunctuationBoundary=44]="SpeechServiceResponse_RequestPunctuationBoundary",i[i.SpeechServiceResponse_RequestSentenceBoundary=45]="SpeechServiceResponse_RequestSentenceBoundary",i[i.Conversation_ApplicationId=46]="Conversation_ApplicationId",i[i.Conversation_DialogType=47]="Conversation_DialogType",i[i.Conversation_Initial_Silence_Timeout=48]="Conversation_Initial_Silence_Timeout",i[i.Conversation_From_Id=49]="Conversation_From_Id",i[i.Conversation_Conversation_Id=50]="Conversation_Conversation_Id",i[i.Conversation_Custom_Voice_Deployment_Ids=51]="Conversation_Custom_Voice_Deployment_Ids",i[i.Conversation_Speech_Activity_Template=52]="Conversation_Speech_Activity_Template",i[i.Conversation_Request_Bot_Status_Messages=53]="Conversation_Request_Bot_Status_Messages",i[i.Conversation_Agent_Connection_Id=54]="Conversation_Agent_Connection_Id",i[i.SpeechServiceConnection_Host=55]="SpeechServiceConnection_Host",i[i.ConversationTranslator_Host=56]="ConversationTranslator_Host",i[i.ConversationTranslator_Name=57]="ConversationTranslator_Name",i[i.ConversationTranslator_CorrelationId=58]="ConversationTranslator_CorrelationId",i[i.ConversationTranslator_Token=59]="ConversationTranslator_Token",i[i.PronunciationAssessment_ReferenceText=60]="PronunciationAssessment_ReferenceText",i[i.PronunciationAssessment_GradingSystem=61]="PronunciationAssessment_GradingSystem",i[i.PronunciationAssessment_Granularity=62]="PronunciationAssessment_Granularity",i[i.PronunciationAssessment_EnableMiscue=63]="PronunciationAssessment_EnableMiscue",i[i.PronunciationAssessment_Json=64]="PronunciationAssessment_Json",i[i.PronunciationAssessment_Params=65]="PronunciationAssessment_Params",i[i.SpeakerRecognition_Api_Version=66]="SpeakerRecognition_Api_Version"})(d||(d={}));var te;(function(i){i[i.NoError=0]="NoError",i[i.AuthenticationFailure=1]="AuthenticationFailure",i[i.BadRequestParameters=2]="BadRequestParameters",i[i.TooManyRequests=3]="TooManyRequests",i[i.ConnectionFailure=4]="ConnectionFailure",i[i.ServiceTimeout=5]="ServiceTimeout",i[i.ServiceError=6]="ServiceError",i[i.RuntimeError=7]="RuntimeError",i[i.Forbidden=8]="Forbidden"})(te||(te={}));class m{}m.BotId="botid",m.CustomSpeechDeploymentId="cid",m.CustomVoiceDeploymentId="deploymentId",m.EnableAudioLogging="storeAudio",m.EnableLanguageId="lidEnabled",m.EnableWordLevelTimestamps="wordLevelTimestamps",m.EndSilenceTimeoutMs="endSilenceTimeoutMs",m.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",m.Format="format",m.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",m.Language="language",m.Profanity="profanity",m.RequestBotStatusMessages="enableBotMessageStatus",m.StableIntermediateThreshold="stableIntermediateThreshold",m.StableTranslation="stableTranslation",m.TestHooks="testhooks",m.Postprocessing="postprocessing";class ft{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,r){new Map([[d.Speech_SegmentationSilenceTimeoutMs,m.SegmentationSilenceTimeoutMs],[d.SpeechServiceConnection_EnableAudioLogging,m.EnableAudioLogging],[d.SpeechServiceConnection_EndSilenceTimeoutMs,m.EndSilenceTimeoutMs],[d.SpeechServiceConnection_InitialSilenceTimeoutMs,m.InitialSilenceTimeoutMs],[d.SpeechServiceResponse_PostProcessingOption,m.Postprocessing],[d.SpeechServiceResponse_ProfanityOption,m.Profanity],[d.SpeechServiceResponse_RequestWordLevelTimestamps,m.EnableWordLevelTimestamps],[d.SpeechServiceResponse_StablePartialResultThreshold,m.StableIntermediateThreshold]]).forEach((o,a)=>{this.setUrlParameter(a,o,e,t,r)});const s=JSON.parse(e.parameters.getProperty(Fe,"{}"));Object.keys(s).forEach(o=>{t[o]=s[o]})}setUrlParameter(e,t,r,n,s){const o=r.parameters.getProperty(e,void 0);o&&(!s||s.search(t)===-1)&&(n[t]=o.toLocaleLowerCase())}}var Ue;(function(i){i[i.Masked=0]="Masked",i[i.Removed=1]="Removed",i[i.Raw=2]="Raw"})(Ue||(Ue={}));var be=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Ee{constructor(e,t){const r=e;C.throwIfNull(r,"speechConfig"),t!==null&&(t===void 0?this.audioConfig=typeof window=="undefined"?void 0:Q.fromDefaultSpeakerOutput():this.audioConfig=t),this.privProperties=r.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.privConnectionFactory=new fi,this.synthesisRequestQueue=new he,this.implCommonSynthesizeSetup()}get authorizationToken(){return this.properties.getProperty(d.SpeechServiceAuthorization_Token)}set authorizationToken(e){C.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(d.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(d.SpeechServiceConnection_AutoDetectSourceLanguages)===Pi}static FromConfig(e,t,r){const n=e;return t.properties.mergeTo(n.properties),new Ee(e,r)}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 r=this.properties.getProperty(d.SpeechServiceConnection_SynthLanguage,"en-US"),n=this.properties.getProperty(d.SpeechServiceConnection_SynthVoice,""),s=Ee.XMLEncode(e);return this.autoDetectSourceLanguage?r="en-US":n=n||t[r],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='${r}'>${s}</speak>`,s}speakTextAsync(e,t,r,n){this.speakImpl(e,!1,t,r,n)}speakSsmlAsync(e,t,r,n){this.speakImpl(e,!0,t,r,n)}getVoicesAsync(e=""){return be(this,void 0,void 0,function*(){return this.getVoices(e)})}close(e,t){C.throwIfDisposed(this.privDisposed),Kt(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}dispose(e){return be(this,void 0,void 0,function*(){this.privDisposed||(e&&this.privAdapter&&(yield this.privAdapter.dispose()),this.privDisposed=!0)})}createSynthesizerConfig(e){return new yi(e,this.privProperties)}createSynthesisAdapter(e,t,r,n){return new ne(e,t,n,this,this.audioConfig)}implCommonSynthesizeSetup(){let e=typeof window!="undefined"?"Browser":"Node",t="unknown",r="unknown";typeof navigator!="undefined"&&(e=e+"/"+navigator.platform,t=navigator.userAgent,r=navigator.appVersion);const n=this.createSynthesizerConfig(new yt(new bt(new vi(e,t,r)))),s=this.privProperties.getProperty(d.SpeechServiceConnection_Key,void 0),o=s&&s!==""?new ii(s):new ue(()=>{const a=this.privProperties.getProperty(d.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)},()=>{const a=this.privProperties.getProperty(d.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(a)});this.privAdapter=this.createSynthesisAdapter(o,this.privConnectionFactory,this.audioConfig,n),this.privAdapter.audioOutputFormat=l.fromSpeechSynthesisOutputFormat(f[this.properties.getProperty(d.SpeechServiceConnection_SynthOutputFormat,void 0)]),this.privRestAdapter=new Ci(n)}speakImpl(e,t,r,n,s){try{C.throwIfDisposed(this.privDisposed);const o=A();let a;s instanceof vt?a=new He(s):s instanceof Ce?a=s:s!==void 0?a=new at(s):a=void 0,this.synthesisRequestQueue.enqueue(new oi(o,e,t,u=>{if(this.privSynthesizing=!1,r)try{r(u)}catch(c){n&&n(c)}r=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 be(this,void 0,void 0,function*(){const t=A(),r=yield this.privRestAdapter.getVoicesList(t);if(r.ok&&Array.isArray(r.json)){let n=r.json;return!!e&&e.length>0&&(n=n.filter(s=>!!s.Locale&&s.Locale.toLowerCase()===e.toLowerCase())),new St(t,n,void 0)}else return new St(t,void 0,`Error: ${r.status}: ${r.statusText}`)})}adapterSpeak(){return be(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 oi{constructor(e,t,r,n,s,o){this.requestId=e,this.text=t,this.isSSML=r,this.cb=n,this.err=s,this.dataStream=o}}class mt{constructor(e,t,r,n){this.privResultId=e,this.privReason=t,this.privErrorDetails=r,this.privProperties=n}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}class Ae extends mt{constructor(e,t,r,n,s,o){super(e,t,n,s),this.privAudioData=r,this.privAudioDuration=o}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}class Pe{constructor(e){this.privResult=e}get result(){return this.privResult}}class ai{constructor(e,t,r,n,s,o){this.privAudioOffset=e,this.privDuration=t,this.privText=r,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 hi{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}class ci{constructor(e,t,r){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=r}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}class St extends mt{constructor(e,t,r){if(Array.isArray(t)){super(e,W.VoicesListRetrieved,void 0,new ee),this.privVoices=[];for(const n of t)this.privVoices.push(new ui(n))}else super(e,W.Canceled,r||"Error information unavailable",new ee)}get voices(){return this.privVoices}}var de;(function(i){i[i.Unknown=0]="Unknown",i[i.Female=1]="Female",i[i.Male=2]="Male"})(de||(de={}));var Me;(function(i){i[i.OnlineNeural=1]="OnlineNeural",i[i.OnlineStandard=2]="OnlineStandard",i[i.OfflineNeural=3]="OfflineNeural",i[i.OfflineStandard=4]="OfflineStandard"})(Me||(Me={}));class ui{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")?Me.OnlineStandard:Me.OnlineNeural,this.privGender=e.Gender==="Male"?de.Male:e.Gender==="Female"?de.Female:de.Unknown,!!e.StyleList&&Array.isArray(e.StyleList)))for(const t of e.StyleList)this.privStyleList.push(t)}get name(){return this.privName}get locale(){return this.privLocale}get shortName(){return this.privShortName}get localName(){return this.privLocalName}get gender(){return this.privGender}get voiceType(){return this.privVoiceType}get styleList(){return this.privStyleList}get voicePath(){return this.privVoicePath}}var We=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};const pi=60*30,gt={[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 Ve{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||A(),this.privIsPaused=!1,this.privIsClosed=!1}id(){return this.privId}write(e,t,r){this.privAudioBuffer!==void 0?(this.privAudioBuffer.push(e),this.updateSourceBuffer().then(()=>{t&&t()},n=>{r&&r(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()},r=>{t&&t(r)});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 r=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(r).then(()=>{r=ne.addHeader(r,this.privFormat);const n=new Blob([r],{type:gt[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=gt[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=pi,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch(r=>{R.instance.onEvent(new ce(r))})},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch(r=>{R.instance.onEvent(new ce(r))})},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch(r=>{R.instance.onEvent(new ce(r))})):(console.warn(`Format ${v[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new Ke,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()},r=>{t&&t(r)}),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}updateSourceBuffer(){return We(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 We(this,void 0,void 0,function*(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),yield this.notifyPlayback())})}notifyPlayback(){return We(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 $ extends xe{constructor(e,t,r,n,s,o,a,u){if(!t)throw new D("path");if(!r)throw new D("requestId");const c={};if(c[y.Path]=t,c[y.RequestId]=r,c[y.RequestTimestamp]=new Date().toISOString(),n&&(c[y.ContentType]=n),o&&(c[y.RequestStreamId]=o),a)for(const h in a)h&&(c[h]=a[h]);u?super(e,s,c,u):super(e,s,c),this.privPath=t,this.privRequestId=r,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,r=null,n=null,s=null;const o={};if(e.headers)for(const a in e.headers)a&&(a.toLowerCase()===y.Path.toLowerCase()?t=e.headers[a]:a.toLowerCase()===y.RequestId.toLowerCase()?r=e.headers[a]:a.toLowerCase()===y.ContentType.toLowerCase()?n=e.headers[a]:a.toLowerCase()===y.RequestStreamId.toLowerCase()?s=e.headers[a]:o[a]=e.headers[a]);return new $(e.messageType,t,r,n,e.body,s,o,e.id)}}var wt;(function(i){i[i.Interactive=0]="Interactive",i[i.Conversation=1]="Conversation",i[i.Dictation=2]="Dictation"})(wt||(wt={}));var Ct;(function(i){i[i.Simple=0]="Simple",i[i.Detailed=1]="Detailed"})(Ct||(Ct={}));class yt{constructor(e){this.context=e}serialize(){return JSON.stringify(this,(e,t)=>{if(t&&typeof t=="object"){const r={};for(const n in t)Object.hasOwnProperty.call(t,n)&&(r[n&&n.charAt(0).toLowerCase()+n.substring(1)]=t[n]);return r}return t})}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}}class bt{constructor(e){this.system=new di,this.os=e}}class di{constructor(){const e="1.22.0";this.name="SpeechSDK",this.version=e,this.build="JavaScript",this.lang="JavaScript"}}class vi{constructor(e,t,r){this.platform=e,this.name=t,this.version=r}}var ie;(function(i){i.Bluetooth="Bluetooth",i.Wired="Wired",i.WiFi="WiFi",i.Cellular="Cellular",i.InBuilt="InBuilt",i.Unknown="Unknown"})(ie||(ie={}));var re;(function(i){i.Phone="Phone",i.Speaker="Speaker",i.Car="Car",i.Headset="Headset",i.Thermostat="Thermostat",i.Microphones="Microphones",i.Deskphone="Deskphone",i.RemoteControl="RemoteControl",i.Unknown="Unknown",i.File="File",i.Stream="Stream"})(re||(re={}));const Et=`\r
|
3
|
+
`;class li{toConnectionMessage(e){const t=new k;try{if(e.messageType===g.Text){const r=e.textContent;let n={},s=null;if(r){const o=r.split(`\r
|
4
4
|
\r
|
5
|
-
`);o&&o.length>0&&(n=this.parseHeaders(o[0]),o.length>1&&(s=o[1]))}t.resolve(new xe(e.messageType,s,n,e.id))}else if(e.messageType===g.Binary){const r=e.binaryContent;let n={},s=null;if(!r||r.byteLength<2)throw new Error("Invalid binary message format. Header length missing.");const o=new DataView(r),a=o.getInt16(0);if(r.byteLength<a+2)throw new Error("Invalid binary message format. Header content missing.");let u="";for(let c=0;c<a;c++)u+=String.fromCharCode(o.getInt8(c+2));n=this.parseHeaders(u),r.byteLength>a+2&&(s=r.slice(2+a)),t.resolve(new xe(e.messageType,s,n,e.id))}}catch(r){t.reject(`Error formatting the message. Error: ${r}`)}return t.promise}fromConnectionMessage(e){const t=new D;try{if(e.messageType===g.Text){const r=`${this.makeHeaders(e)}${Et}${e.textBody?e.textBody:""}`;t.resolve(new ge(g.Text,r,e.id))}else if(e.messageType===g.Binary){const r=this.makeHeaders(e),n=e.binaryBody,s=this.stringToArrayBuffer(r),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 h=new Int8Array(n);u.set(h,2+a)}const c=u.buffer;t.resolve(new ge(g.Binary,c,e.id))}}catch(r){t.reject(`Error formatting the message. ${r}`)}return t.promise}makeHeaders(e){let t="";if(e.headers)for(const r in e.headers)r&&(t+=`${r}: ${e.headers[r]}${Et}`);return t}parseHeaders(e){const t={};if(e){const r=e.match(/[^\r\n]+/g);if(t){for(const n of r)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),r=new DataView(t);for(let n=0;n<e.length;n++)r.setUint8(n,e.charCodeAt(n));return t}}class fi{constructor(){this.synthesisUri="/cognitiveservices/websocket/v1"}create(e,t,r){let n=e.parameters.getProperty(d.SpeechServiceConnection_Endpoint,void 0);const s=e.parameters.getProperty(d.SpeechServiceConnection_Region,void 0),o=ft.getHostSuffix(s),a=e.parameters.getProperty(d.SpeechServiceConnection_EndpointId,void 0),u=a===void 0?"tts":"voice",c=e.parameters.getProperty(d.SpeechServiceConnection_Host,"wss://"+s+"."+u+".speech"+o),h={};n||(n=c+this.synthesisUri);const p={};t.token!==void 0&&t.token!==""&&(p[t.headerName]=t.token),p[y.ConnectionId]=r,a!==void 0&&(p[m.CustomVoiceDeploymentId]=a),e.parameters.setProperty(d.SpeechServiceConnection_Url,n);const w=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new Di(n,h,p,new li,Xe.fromParameters(e.parameters),w,r)}}class mi{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class O{static get requestOptions(){return O.privDefaultRequestOptions}static get configParams(){return O.privDefaultParams}static get restErrors(){return O.privRestErrors}}O.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},O.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."},O.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 _;(function(i){i.WordBoundary="WordBoundary",i.Bookmark="Bookmark",i.Viseme="Viseme",i.SentenceBoundary="SentenceBoundary",i.SessionEnd="SessionEnd"})(_||(_={}));class qe{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new qe(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var V=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ne{constructor(e,t,r,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 k("authentication");if(!t)throw new k("connectionFactory");if(!r)throw new k("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=r,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new Te,this.privConnectionEvents=new H,this.privServiceEvents=new H,this.privSynthesisContext=new bi(this.privSpeechSynthesizer),this.privAgentConfig=new mi,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(ye.Error,a.statusCode===1007?te.BadRequestParameters:te.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 r=new Uint8Array(e.byteLength+t.header.byteLength);return r.set(new Uint8Array(t.header),0),r.set(new Uint8Array(e),t.header.byteLength),r.buffer}isDisposed(){return this.privIsDisposed}dispose(e){return V(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 V(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return V(this,void 0,void 0,function*(){const r=typeof t=="string"?g.Text:g.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new j(r,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,r,n,s,o){return V(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,r,n,s);this.privSuccessCallback=n,this.privErrorCallback=s,this.privSynthesisTurn.startNewSynthesis(r,e,t,o);try{yield this.connectImpl();const u=yield this.fetchConnection();yield this.sendSynthesisContext(u),yield this.sendSsmlMessage(u,a,r);const c=new Pe(new Ae(r,W.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,c),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(ye.Error,te.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,r,n){const s=new ee;s.setProperty(Ei,te[r]);const o=new Ae(e,W.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new Pe(o);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,a)}catch{}}if(this.privSuccessCallback)try{this.privSuccessCallback(o)}catch{}}cancelSynthesisLocal(e,t,r){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,r))}processTypeSpecificMessages(e){return!0}receiveMessage(){return V(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 r=j.fromConnectionMessage(t);if(r.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(r.path.toLowerCase()){case"turn.start":this.privSynthesisTurn.onServiceTurnStartResponse();break;case"response":this.privSynthesisTurn.onServiceResponseMessage(r.textBody);break;case"audio":if(this.privSynthesisTurn.streamId.toLowerCase()===r.streamId.toLowerCase()&&!!r.binaryBody){if(this.privSynthesisTurn.onAudioChunkReceived(r.binaryBody),this.privSpeechSynthesizer.synthesizing)try{const o=ne.addHeader(r.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new Pe(new Ae(this.privSynthesisTurn.requestId,W.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(r.binaryBody)}break;case"audio.metadata":const n=qe.fromJSON(r.textBody).Metadata;for(const o of n)switch(o.Type){case _.WordBoundary:case _.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new ai(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===_.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 _.Bookmark:const u=new hi(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case _.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const c=new ci(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,c)}catch{}}break;case _.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Ae(this.privSynthesisTurn.requestId,W.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 Pe(s))}catch{}break;default:this.processTypeSpecificMessages(r)||this.privServiceEvents&&this.serviceEvents.onEvent(new xt(r.path.toLowerCase(),r.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new j(g.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(r=>r.state()===M.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()));this.privAuthFetchEventId=A(),this.privConnectionId=A(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=t.then(r=>V(this,void 0,void 0,function*(){this.privSynthesisTurn.onAuthCompleted(!1);const n=this.privConnectionFactory.create(this.privSynthesizerConfig,r,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(d.SpeechServiceConnection_Endpoint)} Reason: ${s.reason}`))}),r=>{throw this.privSynthesisTurn.onAuthCompleted(!0),new Error(r)}),this.privConnectionPromise.catch(()=>{}),this.privConnectionPromise}sendSpeechServiceConfig(e,t){if(t)return e.send(new j(g.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,r){return e.send(new j(g.Text,"ssml",r,"application/ssml+xml",t))}fetchConnection(){return V(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 V(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)})}}ne.telemetryDataEnabled=!0;class je extends F{constructor(e,t,r=S.Info){super(e,r),this.privRequestId=t}get requestId(){return this.privRequestId}}class Si extends je{constructor(e,t,r){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=r}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class gi extends je{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class wi extends je{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var $e=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Te{constructor(){this.privIsDisposed=!1,this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!1,this.privBytesReceived=0,this.privInTurn=!1,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privRequestId=A(),this.privTurnDeferral=new 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 $e(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 $e(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=ne.addHeader(e,this.audioOutputFormat),this.privReceivedAudioWithHeader}else return this.getAllReceivedAudio()})}startNewSynthesis(e,t,r,n){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=r,this.privAudioOutputStream=new Ke,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 Si(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new gi(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new wi(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){R.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===_.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!Te.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)&&!Te.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 $e(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 Ci{constructor(e){let t=e.parameters.getProperty(d.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(d.SpeechServiceConnection_Region,"westus"),s=ft.getHostSuffix(n);t=e.parameters.getProperty(d.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const r=O.requestOptions;r.headers[O.configParams.subscriptionKey]=e.parameters.getProperty(d.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new Ni(r)}getVoicesList(e){return this.privRestAdapter.setHeaders(y.ConnectionId,e),this.privRestAdapter.request($.Get,this.privUri)}}var Ge;(function(i){i[i.Standard=0]="Standard",i[i.Custom=1]="Custom"})(Ge||(Ge={}));class yi{constructor(e,t){this.privSynthesisServiceType=Ge.Standard,this.privSpeechServiceConfig=e||new yt(new bt(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 bi{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(d.SpeechServiceResponse_RequestPunctuationBoundary,!!this.privSpeechSynthesizer.wordBoundary),sentenceBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(d.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!this.privSpeechSynthesizer.visemeReceived,wordBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(d.SpeechServiceResponse_RequestWordBoundary,!!this.privSpeechSynthesizer.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:this.privSpeechSynthesizer.autoDetectSourceLanguage}}}}const At="OutputFormat",Ei="CancellationErrorCode",Fe="ServiceProperties",Ai="ForceDictation",Pi="OpenRange";var Re=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};const Mi="MICROPHONE-WorkletSourceUrl";class N{constructor(e,t,r,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=N.AUDIOFORMAT.avgBytesPerSec/10,this.privId=r||A(),this.privEvents=new H,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(N.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(r){if(r instanceof Error){const n=r;this.privInitializeDeferral.reject(n.name+": "+n.message)}else this.privInitializeDeferral.reject(r);return this.privInitializeDeferral.promise}const e=window.navigator;let t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(r,n,s)=>{e.mediaDevices.getUserMedia(r).then(n).catch(s)}),t){const r=()=>{this.onEvent(new le(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new oe(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new oe(this.privId)),this.privInitializeDeferral.resolve()},n=>{const s=`Error occurred during microphone initialization: ${n}`;this.privInitializeDeferral.reject(s),this.onEvent(new Ie(this.privId,s))})};this.privContext.state==="suspended"?this.privContext.resume().then(r).catch(n=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${n}`)}):r()}else{const r="Browser does not support getUserMedia.";this.privInitializeDeferral.reject(r),this.onEvent(new Ie(r,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new me(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new Se(this.privId,e)),{detach:()=>Re(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new K(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 K(this.privId,e)))}turnOff(){return Re(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 Ye(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:N.AUDIOFORMAT.bitsPerSample,channelcount:N.AUDIOFORMAT.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:e,samplerate:N.AUDIOFORMAT.samplesPerSec,type:re.Microphones}))}setProperty(e,t){if(e===Mi)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 r=new D;return navigator.mediaDevices.enumerateDevices().then(n=>{for(const s of n)if(s.deviceId===t){this.privMicrophoneLabel=s.label;break}r.resolve(this.privMicrophoneLabel)},()=>r.resolve(this.privMicrophoneLabel)),r.promise}listen(e){return Re(this,void 0,void 0,function*(){yield this.turnOn();const t=new Ne(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new et(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=U.getAudioContext(N.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return Re(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())})}}N.AUDIOFORMAT=we.getDefaultInputFormat();var Je=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Ti{constructor(e,t,r){this.privStreams={},this.privHeaderEnd=44,this.privId=r||A(),this.privEvents=new H,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 Ie(e,"")),Promise.reject(e)}this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}id(){return this.privId}attach(e){return Je(this,void 0,void 0,function*(){this.onEvent(new me(this.privId,e));const t=yield this.upload(e);return this.onEvent(new Se(this.privId,e)),Promise.resolve({detach:()=>Je(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new K(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 K(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 Ye(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:ie.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:re.File}))}readHeader(){const t=this.privSource.slice(0,512),r=new D,n=s=>{const o=new DataView(s),a=x=>String.fromCharCode(o.getUint8(x),o.getUint8(x+1),o.getUint8(x+2),o.getUint8(x+3));if(a(0)!=="RIFF"){r.reject("Invalid WAV header in file, RIFF was not found");return}if(a(8)!=="WAVE"||a(12)!=="fmt "){r.reject("Invalid WAV header in file, WAVEfmt was not found");return}const u=o.getInt32(16,!0),c=o.getUint16(22,!0),h=o.getUint32(24,!0),p=o.getUint16(34,!0);let w=36+Math.max(u-16,0);for(;a(w)!=="data";w+=2)if(w>512-8){r.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=w+8,r.resolve(we.getWaveFormatPCM(h,p,c))};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 r.promise}upload(e){return Je(this,void 0,void 0,function*(){const t=r=>{const n=`Error occurred while processing '${this.privFilename}'. ${r}`;throw this.onEvent(new et(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const r=yield this.privAudioFormatPromise,n=new Ne(r.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 c=u.target.result;o(c)},a.readAsArrayBuffer(s)}else{const a=s;o(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength))}return n}catch(r){t(r)}})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}}class Qe{constructor(e){this.privStopInputOnRelease=e}record(e,t,r){const s=new Ht(e.sampleRate,16e3),o=e.createMediaStreamSource(t);if(!this.privSpeechProcessorScript){const u=`class SP extends AudioWorkletProcessor {
|
5
|
+
`);o&&o.length>0&&(n=this.parseHeaders(o[0]),o.length>1&&(s=o[1]))}t.resolve(new xe(e.messageType,s,n,e.id))}else if(e.messageType===g.Binary){const r=e.binaryContent;let n={},s=null;if(!r||r.byteLength<2)throw new Error("Invalid binary message format. Header length missing.");const o=new DataView(r),a=o.getInt16(0);if(r.byteLength<a+2)throw new Error("Invalid binary message format. Header content missing.");let u="";for(let c=0;c<a;c++)u+=String.fromCharCode(o.getInt8(c+2));n=this.parseHeaders(u),r.byteLength>a+2&&(s=r.slice(2+a)),t.resolve(new xe(e.messageType,s,n,e.id))}}catch(r){t.reject(`Error formatting the message. Error: ${r}`)}return t.promise}fromConnectionMessage(e){const t=new k;try{if(e.messageType===g.Text){const r=`${this.makeHeaders(e)}${Et}${e.textBody?e.textBody:""}`;t.resolve(new ge(g.Text,r,e.id))}else if(e.messageType===g.Binary){const r=this.makeHeaders(e),n=e.binaryBody,s=this.stringToArrayBuffer(r),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 h=new Int8Array(n);u.set(h,2+a)}const c=u.buffer;t.resolve(new ge(g.Binary,c,e.id))}}catch(r){t.reject(`Error formatting the message. ${r}`)}return t.promise}makeHeaders(e){let t="";if(e.headers)for(const r in e.headers)r&&(t+=`${r}: ${e.headers[r]}${Et}`);return t}parseHeaders(e){const t={};if(e){const r=e.match(/[^\r\n]+/g);if(t){for(const n of r)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),r=new DataView(t);for(let n=0;n<e.length;n++)r.setUint8(n,e.charCodeAt(n));return t}}class fi{constructor(){this.synthesisUri="/cognitiveservices/websocket/v1"}create(e,t,r){let n=e.parameters.getProperty(d.SpeechServiceConnection_Endpoint,void 0);const s=e.parameters.getProperty(d.SpeechServiceConnection_Region,void 0),o=ft.getHostSuffix(s),a=e.parameters.getProperty(d.SpeechServiceConnection_EndpointId,void 0),u=a===void 0?"tts":"voice",c=e.parameters.getProperty(d.SpeechServiceConnection_Host,"wss://"+s+"."+u+".speech"+o),h={};n||(n=c+this.synthesisUri);const p={};t.token!==void 0&&t.token!==""&&(p[t.headerName]=t.token),p[y.ConnectionId]=r,a!==void 0&&(p[m.CustomVoiceDeploymentId]=a),e.parameters.setProperty(d.SpeechServiceConnection_Url,n);const w=e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false")==="true";return new ki(n,h,p,new li,Xe.fromParameters(e.parameters),w,r)}}class mi{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}class O{static get requestOptions(){return O.privDefaultRequestOptions}static get configParams(){return O.privDefaultParams}static get restErrors(){return O.privRestErrors}}O.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},O.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."},O.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 _;(function(i){i.WordBoundary="WordBoundary",i.Bookmark="Bookmark",i.Viseme="Viseme",i.SentenceBoundary="SentenceBoundary",i.SessionEnd="SessionEnd"})(_||(_={}));class qe{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new qe(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}var V=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ne{constructor(e,t,r,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 D("authentication");if(!t)throw new D("connectionFactory");if(!r)throw new D("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=r,this.privIsDisposed=!1,this.privSpeechSynthesizer=n,this.privSessionAudioDestination=s,this.privSynthesisTurn=new Te,this.privConnectionEvents=new H,this.privServiceEvents=new H,this.privSynthesisContext=new bi(this.privSpeechSynthesizer),this.privAgentConfig=new mi,this.connectionEvents.attach(o=>{if(o.name==="ConnectionClosedEvent"){const a=o;a.statusCode!==1e3&&this.cancelSynthesisLocal(ye.Error,a.statusCode===1007?te.BadRequestParameters:te.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 r=new Uint8Array(e.byteLength+t.header.byteLength);return r.set(new Uint8Array(t.header),0),r.set(new Uint8Array(e),t.header.byteLength),r.buffer}isDisposed(){return this.privIsDisposed}dispose(e){return V(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 V(this,void 0,void 0,function*(){yield this.connectImpl()})}sendNetworkMessage(e,t){return V(this,void 0,void 0,function*(){const r=typeof t=="string"?g.Text:g.Binary,n=typeof t=="string"?"application/json":"";return(yield this.fetchConnection()).send(new $(r,e,this.privSynthesisTurn.requestId,n,t))})}Speak(e,t,r,n,s,o){return V(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,r,n,s);this.privSuccessCallback=n,this.privErrorCallback=s,this.privSynthesisTurn.startNewSynthesis(r,e,t,o);try{yield this.connectImpl();const u=yield this.fetchConnection();yield this.sendSynthesisContext(u),yield this.sendSsmlMessage(u,a,r);const c=new Pe(new Ae(r,W.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,c),this.receiveMessage()}catch(u){return this.cancelSynthesisLocal(ye.Error,te.ConnectionFailure,u),Promise.reject(u)}})}cancelSynthesis(e,t,r,n){const s=new ee;s.setProperty(Ei,te[r]);const o=new Ae(e,W.Canceled,void 0,n,s);if(this.privSpeechSynthesizer.SynthesisCanceled){const a=new Pe(o);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,a)}catch{}}if(this.privSuccessCallback)try{this.privSuccessCallback(o)}catch{}}cancelSynthesisLocal(e,t,r){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,r))}processTypeSpecificMessages(e){return!0}receiveMessage(){return V(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 r=$.fromConnectionMessage(t);if(r.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(r.path.toLowerCase()){case"turn.start":this.privSynthesisTurn.onServiceTurnStartResponse();break;case"response":this.privSynthesisTurn.onServiceResponseMessage(r.textBody);break;case"audio":if(this.privSynthesisTurn.streamId.toLowerCase()===r.streamId.toLowerCase()&&!!r.binaryBody){if(this.privSynthesisTurn.onAudioChunkReceived(r.binaryBody),this.privSpeechSynthesizer.synthesizing)try{const o=ne.addHeader(r.binaryBody,this.privSynthesisTurn.audioOutputFormat),a=new Pe(new Ae(this.privSynthesisTurn.requestId,W.SynthesizingAudio,o));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,a)}catch{}this.privSessionAudioDestination!==void 0&&this.privSessionAudioDestination.write(r.binaryBody)}break;case"audio.metadata":const n=qe.fromJSON(r.textBody).Metadata;for(const o of n)switch(o.Type){case _.WordBoundary:case _.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(o);const a=new ai(o.Data.Offset,o.Data.Duration,o.Data.text.Text,o.Data.text.Length,o.Type===_.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 _.Bookmark:const u=new hi(o.Data.Offset,o.Data.Bookmark);if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,u)}catch{}break;case _.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(o),o.Data.IsLastAnimation){const c=new ci(o.Data.Offset,o.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,c)}catch{}}break;case _.SessionEnd:this.privSynthesisTurn.onSessionEnd(o);break}break;case"turn.end":this.privSynthesisTurn.onServiceTurnEndResponse();let s;try{const o=yield this.privSynthesisTurn.getAllReceivedAudioWithHeader();s=new Ae(this.privSynthesisTurn.requestId,W.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 Pe(s))}catch{}break;default:this.processTypeSpecificMessages(r)||this.privServiceEvents&&this.serviceEvents.onEvent(new xt(r.path.toLowerCase(),r.textBody))}return this.receiveMessage()}catch{}})}sendSynthesisContext(e){const t=this.synthesisContext.toJSON();if(t)return e.send(new $(g.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}connectImpl(e=!1){if(this.privConnectionPromise!=null)return this.privConnectionPromise.then(r=>r.state()===M.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise,()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()));this.privAuthFetchEventId=A(),this.privConnectionId=A(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=t.then(r=>V(this,void 0,void 0,function*(){this.privSynthesisTurn.onAuthCompleted(!1);const n=this.privConnectionFactory.create(this.privSynthesizerConfig,r,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(d.SpeechServiceConnection_Endpoint)} Reason: ${s.reason}`))}),r=>{throw this.privSynthesisTurn.onAuthCompleted(!0),new Error(r)}),this.privConnectionPromise.catch(()=>{}),this.privConnectionPromise}sendSpeechServiceConfig(e,t){if(t)return e.send(new $(g.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,r){return e.send(new $(g.Text,"ssml",r,"application/ssml+xml",t))}fetchConnection(){return V(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 V(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)})}}ne.telemetryDataEnabled=!0;class $e extends F{constructor(e,t,r=S.Info){super(e,r),this.privRequestId=t}get requestId(){return this.privRequestId}}class Si extends $e{constructor(e,t,r){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=r}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}}class gi extends $e{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}class wi extends $e{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}var je=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Te{constructor(){this.privIsDisposed=!1,this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!1,this.privBytesReceived=0,this.privInTurn=!1,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privRequestId=A(),this.privTurnDeferral=new k,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 je(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 je(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=ne.addHeader(e,this.audioOutputFormat),this.privReceivedAudioWithHeader}else return this.getAllReceivedAudio()})}startNewSynthesis(e,t,r,n){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=r,this.privAudioOutputStream=new Ke,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 Si(this.requestId,void 0,n===void 0?void 0:n.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new gi(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(e===200){this.onEvent(new wi(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 k}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){R.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&e[0]==="<"&&e[e.length-1]===">"}updateTextOffset(e,t){t===_.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!Te.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)&&!Te.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 je(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 Ci{constructor(e){let t=e.parameters.getProperty(d.SpeechServiceConnection_Endpoint,void 0);if(!t){const n=e.parameters.getProperty(d.SpeechServiceConnection_Region,"westus"),s=ft.getHostSuffix(n);t=e.parameters.getProperty(d.SpeechServiceConnection_Host,`https://${n}.tts.speech${s}`)}this.privUri=`${t}/cognitiveservices/voices/list`;const r=O.requestOptions;r.headers[O.configParams.subscriptionKey]=e.parameters.getProperty(d.SpeechServiceConnection_Key,void 0),this.privRestAdapter=new Ni(r)}getVoicesList(e){return this.privRestAdapter.setHeaders(y.ConnectionId,e),this.privRestAdapter.request(j.Get,this.privUri)}}var Ge;(function(i){i[i.Standard=0]="Standard",i[i.Custom=1]="Custom"})(Ge||(Ge={}));class yi{constructor(e,t){this.privSynthesisServiceType=Ge.Standard,this.privSpeechServiceConfig=e||new yt(new bt(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 bi{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(d.SpeechServiceResponse_RequestPunctuationBoundary,!!this.privSpeechSynthesizer.wordBoundary),sentenceBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(d.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!this.privSpeechSynthesizer.visemeReceived,wordBoundaryEnabled:this.privSpeechSynthesizer.properties.getProperty(d.SpeechServiceResponse_RequestWordBoundary,!!this.privSpeechSynthesizer.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:this.privSpeechSynthesizer.autoDetectSourceLanguage}}}}const At="OutputFormat",Ei="CancellationErrorCode",Fe="ServiceProperties",Ai="ForceDictation",Pi="OpenRange";var Re=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};const Mi="MICROPHONE-WorkletSourceUrl";class N{constructor(e,t,r,n){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=N.AUDIOFORMAT.avgBytesPerSec/10,this.privId=r||A(),this.privEvents=new H,this.privMediaStream=n||null,this.privIsClosing=!1}get format(){return Promise.resolve(N.AUDIOFORMAT)}get blob(){return Promise.reject("Not implemented for Mic input")}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new k;try{this.createAudioContext()}catch(r){if(r instanceof Error){const n=r;this.privInitializeDeferral.reject(n.name+": "+n.message)}else this.privInitializeDeferral.reject(r);return this.privInitializeDeferral.promise}const e=window.navigator;let t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(r,n,s)=>{e.mediaDevices.getUserMedia(r).then(n).catch(s)}),t){const r=()=>{this.onEvent(new le(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new oe(this.privId)),this.privInitializeDeferral.resolve()):t({audio:this.deviceId?{deviceId:this.deviceId}:!0,video:!1},n=>{this.privMediaStream=n,this.onEvent(new oe(this.privId)),this.privInitializeDeferral.resolve()},n=>{const s=`Error occurred during microphone initialization: ${n}`;this.privInitializeDeferral.reject(s),this.onEvent(new Ie(this.privId,s))})};this.privContext.state==="suspended"?this.privContext.resume().then(r).catch(n=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${n}`)}):r()}else{const r="Browser does not support getUserMedia.";this.privInitializeDeferral.reject(r),this.onEvent(new Ie(r,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new me(this.privId,e)),this.listen(e).then(t=>(this.onEvent(new Se(this.privId,e)),{detach:()=>Re(this,void 0,void 0,function*(){return t.readEnded(),delete this.privStreams[e],this.onEvent(new K(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 K(this.privId,e)))}turnOff(){return Re(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 Ye(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:N.AUDIOFORMAT.bitsPerSample,channelcount:N.AUDIOFORMAT.channels,connectivity:ie.Unknown,manufacturer:"Speech SDK",model:e,samplerate:N.AUDIOFORMAT.samplesPerSec,type:re.Microphones}))}setProperty(e,t){if(e===Mi)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 r=new k;return navigator.mediaDevices.enumerateDevices().then(n=>{for(const s of n)if(s.deviceId===t){this.privMicrophoneLabel=s.label;break}r.resolve(this.privMicrophoneLabel)},()=>r.resolve(this.privMicrophoneLabel)),r.promise}listen(e){return Re(this,void 0,void 0,function*(){yield this.turnOn();const t=new Ne(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(n){throw this.onEvent(new et(this.privId,e,n)),n}return t})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=U.getAudioContext(N.AUDIOFORMAT.samplesPerSec))}destroyAudioContext(){return Re(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())})}}N.AUDIOFORMAT=we.getDefaultInputFormat();var Je=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Ti{constructor(e,t,r){this.privStreams={},this.privHeaderEnd=44,this.privId=r||A(),this.privEvents=new H,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 Ie(e,"")),Promise.reject(e)}this.onEvent(new le(this.privId)),this.onEvent(new oe(this.privId))}id(){return this.privId}attach(e){return Je(this,void 0,void 0,function*(){this.onEvent(new me(this.privId,e));const t=yield this.upload(e);return this.onEvent(new Se(this.privId,e)),Promise.resolve({detach:()=>Je(this,void 0,void 0,function*(){t.readEnded(),delete this.privStreams[e],this.onEvent(new K(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 K(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 Ye(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:ie.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:re.File}))}readHeader(){const t=this.privSource.slice(0,512),r=new k,n=s=>{const o=new DataView(s),a=x=>String.fromCharCode(o.getUint8(x),o.getUint8(x+1),o.getUint8(x+2),o.getUint8(x+3));if(a(0)!=="RIFF"){r.reject("Invalid WAV header in file, RIFF was not found");return}if(a(8)!=="WAVE"||a(12)!=="fmt "){r.reject("Invalid WAV header in file, WAVEfmt was not found");return}const u=o.getInt32(16,!0),c=o.getUint16(22,!0),h=o.getUint32(24,!0),p=o.getUint16(34,!0);let w=36+Math.max(u-16,0);for(;a(w)!=="data";w+=2)if(w>512-8){r.reject("Invalid WAV header in file, data block was not found");return}this.privHeaderEnd=w+8,r.resolve(we.getWaveFormatPCM(h,p,c))};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 r.promise}upload(e){return Je(this,void 0,void 0,function*(){const t=r=>{const n=`Error occurred while processing '${this.privFilename}'. ${r}`;throw this.onEvent(new et(this.privId,e,n)),new Error(n)};try{yield this.turnOn();const r=yield this.privAudioFormatPromise,n=new Ne(r.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 c=u.target.result;o(c)},a.readAsArrayBuffer(s)}else{const a=s;o(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength))}return n}catch(r){t(r)}})}onEvent(e){this.privEvents.onEvent(e),R.instance.onEvent(e)}}class Qe{constructor(e){this.privStopInputOnRelease=e}record(e,t,r){const s=new Ht(e.sampleRate,16e3),o=e.createMediaStreamSource(t);if(!this.privSpeechProcessorScript){const u=`class SP extends AudioWorkletProcessor {
|
6
6
|
constructor(options) {
|
7
7
|
super(options);
|
8
8
|
}
|
@@ -16,6 +16,16 @@ File System access not available, please use Push or PullAudioOutputStream`),thi
|
|
16
16
|
return true;
|
17
17
|
}
|
18
18
|
}
|
19
|
-
registerProcessor('speech-processor', SP);`,c=new Blob([u],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(c)}const a=()=>{const u=(()=>{let c=0;try{return e.createScriptProcessor(c,1,1)}catch{c=2048;let p=e.sampleRate;for(;c<16384&&p>=32e3;)c<<=1,p>>=1;return e.createScriptProcessor(c,1,1)}})();u.onaudioprocess=c=>{const h=c.inputBuffer.getChannelData(0);if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,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=c=>{const h=c.data;if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,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 ve=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class b{constructor(e){e&&(this.privProxyInfo=e),b.privDiskCache||(b.privDiskCache=new z("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){b.privDiskCache=void 0,b.privMemCache={}}GetAgent(e){const t=new z.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const r="privProxyInfo";t[r]=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 z(t)}static OCSPCheck(e,t){return ve(this,void 0,void 0,function*(){let r,n,s=!1;const o=yield e;o.cork();const a=o;return new Promise((u,c)=>{o.on("OCSPResponse",h=>{h&&(this.onEvent(new Jt),n=h)}),o.on("error",h=>{s||(s=!0,o.destroy(),c(h))}),a.on("secure",()=>ve(this,void 0,void 0,function*(){const h=a.getPeerCertificate(!0);try{const p=yield this.GetIssuer(h);r=(void 0)(h.raw,p.raw);const w=r.id.toString("hex");n||(n=yield b.GetResponseFromCache(w,r,t)),yield this.VerifyOCSPResponse(n,r,t),o.uncork(),s=!0,u(o)}catch(p){o.destroy(),s=!0,c(p)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,r)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){r(s);return}t(o)})})}static GetResponseFromCache(e,t,r){return ve(this,void 0,void 0,function*(){let n=b.privMemCache[e];if(n&&this.onEvent(new Wt(e)),!n)try{const s=yield b.privDiskCache.get(e);s.isCached&&(b.onEvent(new qt(e)),b.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 st(e,"Not enough data in cached response"));return}const u=a.responses[0].thisUpdate,c=a.responses[0].nextUpdate;if(c<Date.now()+this.testTimeOffset-6e4)this.onEvent(new Qt(e,c)),n=null;else{const h=Math.min(864e5,(c-u)/2);c-(Date.now()+this.testTimeOffset)<h?(this.onEvent(new Xt(e,u,c)),this.UpdateCache(t,r).catch(p=>{this.onEvent(new ti(e,p.toString()))})):this.onEvent(new Zt(e,u,c))}}catch(s){this.onEvent(new st(e,s)),n=null}return n||this.onEvent(new Vt(e)),n})}static VerifyOCSPResponse(e,t,r){return ve(this,void 0,void 0,function*(){let n=e;return n||(n=yield b.GetOCSPResponse(t,r)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(b.onEvent(new Yt(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,r).then(()=>{s()},u=>{o(u)}):o(a)):(e||b.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return ve(this,void 0,void 0,function*(){const r=e.id.toString("hex");this.onEvent(new jt(r));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(r,n),this.onEvent(new Ft(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 $t(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Gt(e))})}static GetOCSPResponse(e,t){const r="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=b.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,r,(a,u)=>{if(a){o(a);return}const c=new URL(u);n=Object.assign(Object.assign({},n),{host:c.host,protocol:c.protocol,port:c.port,path:c.pathname,hostname:c.host}),(void 0)(n,e.data,(h,p)=>{if(h){o(h);return}const w=e.certID;this.onEvent(new ei(w.toString("hex"))),s(p)})})})}static onEvent(e){R.instance.onEvent(e)}CreateConnection(e,t){const r=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:!b.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=b.GetProxyAgent(this.privProxyInfo);n=new Promise((a,u)=>{o.callback(e,t,(c,h)=>{c?u(c):a(h)})})}else t.secureEndpoint,n=Promise.resolve((void 0)(t));return r?b.OCSPCheck(n,this.privProxyInfo):n}}b.testTimeOffset=0,b.forceDisableOCSPStapling=!1,b.privMemCache={};var Pt=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class De{constructor(e,t,r,n,s,o){if(!e)throw new k("uri");if(!r)throw new k("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new H,this.privConnectionId=t,this.privMessageFormatter=r,this.privConnectionState=M.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[y.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"&&!De.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 b(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 z(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new he,this.privDisconnectDeferral=new D,this.privSendMessageQueue=new he,this.processSendQueue().catch(e=>{R.instance.onEvent(new ce(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new Be(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Bt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=M.Connected,this.onEvent(new Nt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new Be(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ot(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 Be(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=M.Disconnected,this.privWebsocketClient=null,this.onEvent(new Lt(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{R.instance.onEvent(new ce(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const r=new D;if(this.privReceivingMessageQueue.enqueueFromPromise(r.promise),e.data instanceof ArrayBuffer){const n=new ge(g.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new ge(g.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.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,r=new D;return this.privSendMessageQueue.enqueueFromPromise(r.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{r.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{r.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 _t(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 Pt(this,void 0,void 0,function*(){const r=`Connection closed. ${e}: ${t}`;this.privConnectionState=M.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},r),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(r)},r)})}processSendQueue(){return Pt(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(r){t.sendStatusDeferral.reject(r)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),R.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}De.forceNpmWebSocket=!1;var Ri=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class Di{constructor(e,t,r,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new k("uri");if(!n)throw new k("messageFormatter");this.privMessageFormatter=n;let u="",c=0;if(t){for(const h in t)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(t[h]);u+=`${h}=${p}`,c++}}if(r){for(const h in r)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(r[h]);u+=`${h}=${p}`,c++}}this.privUri=e+u,this.privId=a||A(),this.privConnectionMessageAdapter=new De(this.privUri,this.id,this.privMessageFormatter,s,r,o)}dispose(){return Ri(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 Xe{constructor(e,t,r,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=r,this.privProxyPassword=n}static fromParameters(e){return new Xe(e.getProperty(d.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(d.SpeechServiceConnection_ProxyPort),10),e.getProperty(d.SpeechServiceConnection_ProxyUserName),e.getProperty(d.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 ki=new Set(["json","buffer","string"]);var Ii=i=>(...e)=>{const t=new Set;let r,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(r){const u=`Can't set method to ${a}, already set to ${r}.`;throw new Error(u)}else r=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(ki.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}`)}),r||(r="GET"),t.size===0&&t.add(200),i(t,r,n,s,o)};const zi=Ii;class Ze extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Ze),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 r;Object.defineProperty(this,"responseBody",{get:()=>(r||(r=this.arrayBuffer()),r)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var xi=zi((i,e,t,r,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(r||(r={}),u.username&&(r.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),r["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...r||{},...a});const c=await fetch(u,{method:e,headers:a,body:o});if(c.statusCode=c.status,!i.has(c.status))throw new Ze(c);return t==="json"?c.json():t==="buffer"?c.arrayBuffer():t==="string"?c.text():c}),Bi=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})},$;(function(i){i.Get="GET",i.Post="POST",i.Delete="DELETE",i.File="file"})($||($={}));class Ni{constructor(e){if(!e)throw new k("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let r="";try{const n=t.trim().split(/[\r\n]+/),s={};n.forEach(o=>{const a=o.split(": "),u=a.shift().toLowerCase(),c=a.join(": ");s[u]=c}),r=s[e.toLowerCase()]}catch{}return r}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,r={},n=null,s=null){const o=new D,a=e===$.File?"POST":e,u=(p,w={})=>{const x=p;return{data:JSON.stringify(w),headers:JSON.stringify(p.headers),json:w,ok:p.statusCode>=200&&p.statusCode<300,status:p.statusCode,statusText:w.error?w.error.message:x.statusText?x.statusText:x.statusMessage}},c=p=>{const w=new FileReader;return w.readAsArrayBuffer(p),new Promise(x=>{w.onloadend=()=>{x(w.result)}})},h=p=>{const w=xi(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),x=this.queryParams(r)===""?"":`?${this.queryParams(r)}`;w(x,p).then(G=>Bi(this,void 0,void 0,function*(){if(e===$.Delete||G.statusCode===204)o.resolve(u(G));else try{const Mt=yield G.json();o.resolve(u(G,Mt))}catch{o.resolve(u(G))}})).catch(G=>{o.reject(G)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===$.File&&s){const p="multipart/form-data";this.privHeaders["content-type"]=p,this.privHeaders["Content-Type"]=p,typeof Blob!="undefined"&&s instanceof Blob?c(s).then(w=>{h(w)}).catch(w=>{o.reject(w)}):h(s)}else e===$.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),h(n);return o.promise}withQuery(e,t={}){const r=this.queryParams(t);return r?e+(e.indexOf("?")===-1?"?":"&")+r:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class Li{constructor(e,t,r){E(this,"key");E(this,"region");E(this,"voice");E(this,"textToRead","");E(this,"wordBoundryList",[]);E(this,"clickedNode");E(this,"highlightDiv");E(this,"speechConfig");E(this,"audioConfig");E(this,"player");E(this,"synthesizer");E(this,"previousWordBoundary");E(this,"interval");E(this,"wordEncounters",[]);E(this,"originalHighlightDivInnerHTML","");E(this,"currentWord","");E(this,"currentOffset",0);E(this,"wordBoundaryOffset",0);this.key=e,this.region=t,this.voice=r}async start(){await this.registerBindings(document)}async registerBindings(e){const t=e.childNodes;for(let r=0;r<t.length;r++){if(!t[r])continue;const n=t[r];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 r=>{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 r=>{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 r=>{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 r;if(this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(console.log(e.attributes.getNamedItem("co-tts.highlight")),((r=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:r.value)!==""){const n=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=n,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 r=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying",{}))})}async handlePauseModifier(e,t){e.addEventListener("click",async r=>{await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{}))})}async handleResumeModifier(e,t){e.addEventListener("click",async r=>{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}async startSynthesizer(e,t){this.speechConfig=lt.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=f.Audio24Khz160KBitRateMonoMp3,this.player=new Ve,this.audioConfig=Q.fromSpeakerOutput(this.player),this.synthesizer=new Ee(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(r,n)=>{this.wordBoundryList.push(n)},this.player.onAudioEnd=async()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const r=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));r&&r.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(r,r.attributes.getNamedItem("co-tts.text")):r&&r.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},this.synthesizer.speakTextAsync(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 r;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)r=n;else break;if(r!==void 0)if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(r.text)&&(r=(e=this.previousWordBoundary)!=null?e:void 0),r===void 0)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else if(this.wordEncounters[r.text]||(this.wordEncounters[r.text]=0),(this.currentWord!==r.text||this.wordBoundaryOffset!==r.textOffset)&&(this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,r.text,this.wordEncounters[r.text]),this.wordEncounters[r.text]=this.currentOffset+r.wordLength,this.currentWord=r.text,this.wordBoundaryOffset=r.textOffset),this.currentOffset<=-1)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else{this.previousWordBoundary=r;const n=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset),s=this.currentOffset+r.wordLength,o=this.originalHighlightDivInnerHTML.substring(s);this.highlightDiv.innerHTML=`
|
19
|
+
registerProcessor('speech-processor', SP);`,c=new Blob([u],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(c)}const a=()=>{const u=(()=>{let c=0;try{return e.createScriptProcessor(c,1,1)}catch{c=2048;let p=e.sampleRate;for(;c<16384&&p>=32e3;)c<<=1,p>>=1;return e.createScriptProcessor(c,1,1)}})();u.onaudioprocess=c=>{const h=c.inputBuffer.getChannelData(0);if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,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=c=>{const h=c.data;if(r&&!r.isClosed){const p=s.encode(h);p&&r.writeStreamChunk({buffer:p,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 ve=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class b{constructor(e){e&&(this.privProxyInfo=e),b.privDiskCache||(b.privDiskCache=new z("microsoft-cognitiveservices-speech-sdk-cache",{supportBuffer:!0,location:typeof process!="undefined"&&!!{}.SPEECH_OCSP_CACHE_ROOT?{}.SPEECH_OCSP_CACHE_ROOT:void 0}))}static forceReinitDiskCache(){b.privDiskCache=void 0,b.privMemCache={}}GetAgent(e){const t=new z.Agent(this.CreateConnection);if(this.privProxyInfo!==void 0&&this.privProxyInfo.HostName!==void 0&&this.privProxyInfo.Port>0){const r="privProxyInfo";t[r]=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 z(t)}static OCSPCheck(e,t){return ve(this,void 0,void 0,function*(){let r,n,s=!1;const o=yield e;o.cork();const a=o;return new Promise((u,c)=>{o.on("OCSPResponse",h=>{h&&(this.onEvent(new Jt),n=h)}),o.on("error",h=>{s||(s=!0,o.destroy(),c(h))}),a.on("secure",()=>ve(this,void 0,void 0,function*(){const h=a.getPeerCertificate(!0);try{const p=yield this.GetIssuer(h);r=(void 0)(h.raw,p.raw);const w=r.id.toString("hex");n||(n=yield b.GetResponseFromCache(w,r,t)),yield this.VerifyOCSPResponse(n,r,t),o.uncork(),s=!0,u(o)}catch(p){o.destroy(),s=!0,c(p)}}))})})}static GetIssuer(e){return e.issuerCertificate?Promise.resolve(e.issuerCertificate):new Promise((t,r)=>{new(void 0)({}).fetchIssuer(e,null,(s,o)=>{if(s){r(s);return}t(o)})})}static GetResponseFromCache(e,t,r){return ve(this,void 0,void 0,function*(){let n=b.privMemCache[e];if(n&&this.onEvent(new Wt(e)),!n)try{const s=yield b.privDiskCache.get(e);s.isCached&&(b.onEvent(new qt(e)),b.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 st(e,"Not enough data in cached response"));return}const u=a.responses[0].thisUpdate,c=a.responses[0].nextUpdate;if(c<Date.now()+this.testTimeOffset-6e4)this.onEvent(new Qt(e,c)),n=null;else{const h=Math.min(864e5,(c-u)/2);c-(Date.now()+this.testTimeOffset)<h?(this.onEvent(new Xt(e,u,c)),this.UpdateCache(t,r).catch(p=>{this.onEvent(new ti(e,p.toString()))})):this.onEvent(new Zt(e,u,c))}}catch(s){this.onEvent(new st(e,s)),n=null}return n||this.onEvent(new Vt(e)),n})}static VerifyOCSPResponse(e,t,r){return ve(this,void 0,void 0,function*(){let n=e;return n||(n=yield b.GetOCSPResponse(t,r)),new Promise((s,o)=>{(void 0)({request:t,response:n},a=>{a?(b.onEvent(new Yt(t.id.toString("hex"),a)),e?this.VerifyOCSPResponse(null,t,r).then(()=>{s()},u=>{o(u)}):o(a)):(e||b.StoreCacheEntry(t.id.toString("hex"),n),s())})})})}static UpdateCache(e,t){return ve(this,void 0,void 0,function*(){const r=e.id.toString("hex");this.onEvent(new $t(r));const n=yield this.GetOCSPResponse(e,t);this.StoreCacheEntry(r,n),this.onEvent(new Ft(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 jt(e))}static StoreDiskCacheEntry(e,t){this.privDiskCache.set(e,t).then(()=>{this.onEvent(new Gt(e))})}static GetOCSPResponse(e,t){const r="1.3.6.1.5.5.7.48.1";let n={};if(t){const s=b.GetProxyAgent(t);n.agent=s}return new Promise((s,o)=>{(void 0)(e.cert,r,(a,u)=>{if(a){o(a);return}const c=new URL(u);n=Object.assign(Object.assign({},n),{host:c.host,protocol:c.protocol,port:c.port,path:c.pathname,hostname:c.host}),(void 0)(n,e.data,(h,p)=>{if(h){o(h);return}const w=e.certID;this.onEvent(new ei(w.toString("hex"))),s(p)})})})}static onEvent(e){R.instance.onEvent(e)}CreateConnection(e,t){const r=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:!b.forceDisableOCSPStapling,servername:t.host}),this.privProxyInfo){const o=b.GetProxyAgent(this.privProxyInfo);n=new Promise((a,u)=>{o.callback(e,t,(c,h)=>{c?u(c):a(h)})})}else t.secureEndpoint,n=Promise.resolve((void 0)(t));return r?b.OCSPCheck(n,this.privProxyInfo):n}}b.testTimeOffset=0,b.forceDisableOCSPStapling=!1,b.privMemCache={};var Pt=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ke{constructor(e,t,r,n,s,o){if(!e)throw new D("uri");if(!r)throw new D("messageFormatter");this.proxyInfo=n,this.privConnectionEvents=new H,this.privConnectionId=t,this.privMessageFormatter=r,this.privConnectionState=M.None,this.privUri=e,this.privHeaders=s,this.privEnableCompression=o,this.privHeaders[y.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 k,this.privCertificateValidatedDeferral=new k,this.privConnectionState=M.Connecting;try{if(typeof WebSocket!="undefined"&&!ke.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 b(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 z(this.privUri,e)}this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new he,this.privDisconnectDeferral=new k,this.privSendMessageQueue=new he,this.processSendQueue().catch(e=>{R.instance.onEvent(new ce(e))})}catch(e){return this.privConnectionEstablishDeferral.resolve(new Be(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new Bt(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then(()=>{this.privConnectionState=M.Connected,this.onEvent(new Nt(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new Be(200,""))},e=>{this.privConnectionEstablishDeferral.reject(e)})},this.privWebsocketClient.onerror=e=>{this.onEvent(new Ot(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 Be(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=M.Disconnected,this.privWebsocketClient=null,this.onEvent(new Lt(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch(t=>{R.instance.onEvent(new ce(t))})},this.privWebsocketClient.onmessage=e=>{const t=new Date().toISOString();if(this.privConnectionState===M.Connected){const r=new k;if(this.privReceivingMessageQueue.enqueueFromPromise(r.promise),e.data instanceof ArrayBuffer){const n=new ge(g.Binary,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.reject(`Invalid binary message format. Error: ${s}`)})}else{const n=new ge(g.Text,e.data);this.privMessageFormatter.toConnectionMessage(n).then(s=>{this.onEvent(new tt(this.privConnectionId,t,s)),r.resolve(s)},s=>{r.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 k,r=new k;return this.privSendMessageQueue.enqueueFromPromise(r.promise),this.privMessageFormatter.fromConnectionMessage(e).then(n=>{r.resolve({Message:e,RawWebsocketMessage:n,sendStatusDeferral:t})},n=>{r.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 _t(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 Pt(this,void 0,void 0,function*(){const r=`Connection closed. ${e}: ${t}`;this.privConnectionState=M.Disconnected,this.privDisconnectDeferral.resolve(),yield this.privReceivingMessageQueue.drainAndDispose(()=>{},r),yield this.privSendMessageQueue.drainAndDispose(n=>{n.sendStatusDeferral.reject(r)},r)})}processSendQueue(){return Pt(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(r){t.sendStatusDeferral.reject(r)}}})}onEvent(e){this.privConnectionEvents.onEvent(e),R.instance.onEvent(e)}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}ke.forceNpmWebSocket=!1;var Ri=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})};class ki{constructor(e,t,r,n,s,o=!1,a){if(this.privIsDisposed=!1,!e)throw new D("uri");if(!n)throw new D("messageFormatter");this.privMessageFormatter=n;let u="",c=0;if(t){for(const h in t)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(t[h]);u+=`${h}=${p}`,c++}}if(r){for(const h in r)if(h){u+=c===0&&e.indexOf("?")===-1?"?":"&";const p=encodeURIComponent(r[h]);u+=`${h}=${p}`,c++}}this.privUri=e+u,this.privId=a||A(),this.privConnectionMessageAdapter=new ke(this.privUri,this.id,this.privMessageFormatter,s,r,o)}dispose(){return Ri(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 Xe{constructor(e,t,r,n){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=r,this.privProxyPassword=n}static fromParameters(e){return new Xe(e.getProperty(d.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(d.SpeechServiceConnection_ProxyPort),10),e.getProperty(d.SpeechServiceConnection_ProxyUserName),e.getProperty(d.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 Di=new Set(["json","buffer","string"]);var Ii=i=>(...e)=>{const t=new Set;let r,n,s,o="";return e.forEach(a=>{if(typeof a=="string")if(a.toUpperCase()===a)if(r){const u=`Can't set method to ${a}, already set to ${r}.`;throw new Error(u)}else r=a;else if(a.startsWith("http:")||a.startsWith("https:"))o=a;else if(Di.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}`)}),r||(r="GET"),t.size===0&&t.add(200),i(t,r,n,s,o)};const zi=Ii;class Ze extends Error{constructor(e,...t){super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,Ze),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 r;Object.defineProperty(this,"responseBody",{get:()=>(r||(r=this.arrayBuffer()),r)}),this.headers={};for(const[s,o]of e.headers.entries())this.headers[s.toLowerCase()]=o}}var xi=zi((i,e,t,r,n)=>async(s,o,a={})=>{s=n+(s||"");let u=new URL(s);if(r||(r={}),u.username&&(r.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),r["Content-Type"]="application/json";else throw new Error("Unknown body type.");a=new Headers({...r||{},...a});const c=await fetch(u,{method:e,headers:a,body:o});if(c.statusCode=c.status,!i.has(c.status))throw new Ze(c);return t==="json"?c.json():t==="buffer"?c.arrayBuffer():t==="string"?c.text():c}),Bi=globalThis&&globalThis.__awaiter||function(i,e,t,r){function n(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(h){try{c(r.next(h))}catch(p){o(p)}}function u(h){try{c(r.throw(h))}catch(p){o(p)}}function c(h){h.done?s(h.value):n(h.value).then(a,u)}c((r=r.apply(i,e||[])).next())})},j;(function(i){i.Get="GET",i.Post="POST",i.Delete="DELETE",i.File="file"})(j||(j={}));class Ni{constructor(e){if(!e)throw new D("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let r="";try{const n=t.trim().split(/[\r\n]+/),s={};n.forEach(o=>{const a=o.split(": "),u=a.shift().toLowerCase(),c=a.join(": ");s[u]=c}),r=s[e.toLowerCase()]}catch{}return r}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,r={},n=null,s=null){const o=new k,a=e===j.File?"POST":e,u=(p,w={})=>{const x=p;return{data:JSON.stringify(w),headers:JSON.stringify(p.headers),json:w,ok:p.statusCode>=200&&p.statusCode<300,status:p.statusCode,statusText:w.error?w.error.message:x.statusText?x.statusText:x.statusMessage}},c=p=>{const w=new FileReader;return w.readAsArrayBuffer(p),new Promise(x=>{w.onloadend=()=>{x(w.result)}})},h=p=>{const w=xi(t,a,this.privHeaders,200,201,202,204,400,401,402,403,404),x=this.queryParams(r)===""?"":`?${this.queryParams(r)}`;w(x,p).then(G=>Bi(this,void 0,void 0,function*(){if(e===j.Delete||G.statusCode===204)o.resolve(u(G));else try{const Mt=yield G.json();o.resolve(u(G,Mt))}catch{o.resolve(u(G))}})).catch(G=>{o.reject(G)})};if(this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===j.File&&s){const p="multipart/form-data";this.privHeaders["content-type"]=p,this.privHeaders["Content-Type"]=p,typeof Blob!="undefined"&&s instanceof Blob?c(s).then(w=>{h(w)}).catch(w=>{o.reject(w)}):h(s)}else e===j.Post&&n&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),h(n);return o.promise}withQuery(e,t={}){const r=this.queryParams(t);return r?e+(e.indexOf("?")===-1?"?":"&")+r:e}queryParams(e={}){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}}class Li{constructor(e,t,r,n=0,s=0){E(this,"key");E(this,"region");E(this,"voice");E(this,"rate");E(this,"pitch");E(this,"textToRead","");E(this,"wordBoundryList",[]);E(this,"clickedNode");E(this,"highlightDiv");E(this,"speechConfig");E(this,"audioConfig");E(this,"player");E(this,"synthesizer");E(this,"previousWordBoundary");E(this,"interval");E(this,"wordEncounters",[]);E(this,"originalHighlightDivInnerHTML","");E(this,"currentWord","");E(this,"currentOffset",0);E(this,"wordBoundaryOffset",0);this.key=e,this.region=t,this.voice=r,this.rate=n,this.pitch=s}async start(){await this.registerBindings(document)}async registerBindings(e){const t=e.childNodes;for(let r=0;r<t.length;r++){if(!t[r])continue;const n=t[r];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 r=>{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 r=>{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 r=>{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 r;if(this.stopPlayer(),await this.createInterval(),this.clickedNode=e,e.hasAttribute("co-tts.highlight"))if(((r=e.attributes.getNamedItem("co-tts.highlight"))==null?void 0:r.value)!==""){const n=document.getElementById(e.attributes.getNamedItem("co-tts.highlight").value);this.highlightDiv=n,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 r=>{await this.stopPlayer(),document.dispatchEvent(new CustomEvent("COAzureTTSStoppedPlaying",{}))})}async handlePauseModifier(e,t){e.addEventListener("click",async r=>{await this.clearInterval(),await this.player.pause(),document.dispatchEvent(new CustomEvent("COAzureTTSPausedPlaying",{}))})}async handleResumeModifier(e,t){e.addEventListener("click",async r=>{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}async startSynthesizer(e,t){this.speechConfig=lt.fromSubscription(this.key,this.region),this.speechConfig.speechSynthesisVoiceName=`Microsoft Server Speech Text to Speech Voice (${this.voice})`,this.speechConfig.speechSynthesisOutputFormat=f.Audio24Khz160KBitRateMonoMp3,this.player=new Ve,this.audioConfig=Q.fromSpeakerOutput(this.player),this.synthesizer=new Ee(this.speechConfig,this.audioConfig),this.synthesizer.wordBoundary=(r,n)=>{this.wordBoundryList.push(n)},this.player.onAudioEnd=async()=>{if(this.stopPlayer(),this.clickedNode.hasAttribute("co-tts.next")){const r=document.getElementById(this.clickedNode.getAttribute("co-tts.next"));r&&r.attributes.getNamedItem("co-tts.text")?this.handleWithoutClick(r,r.attributes.getNamedItem("co-tts.text")):r&&r.dispatchEvent(new Event("click"))}else document.dispatchEvent(new CustomEvent("COAzureTTSFinishedPlaying",{}))},this.player.onAudioStart=async()=>{document.dispatchEvent(new CustomEvent("COAzureTTSStartedPlaying",{}))},console.log(this.buildSSML(this.textToRead)),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 r;for(const n of this.wordBoundryList)if(t*1e3>n.audioOffset/1e4)r=n;else break;if(r!==void 0)if(~[".",",","!","?","*","(",")","&","\\","/","^","[","]","<",">",":"].indexOf(r.text)&&(r=(e=this.previousWordBoundary)!=null?e:void 0),r===void 0)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else if(this.wordEncounters[r.text]||(this.wordEncounters[r.text]=0),(this.currentWord!==r.text||this.wordBoundaryOffset!==r.textOffset)&&(this.currentOffset=this.getPosition(this.originalHighlightDivInnerHTML,r.text,this.wordEncounters[r.text]),this.wordEncounters[r.text]=this.currentOffset+r.wordLength,this.currentWord=r.text,this.wordBoundaryOffset=r.textOffset),this.currentOffset<=-1)this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML;else{this.previousWordBoundary=r;const n=this.originalHighlightDivInnerHTML.substring(0,this.currentOffset),s=this.currentOffset+r.wordLength,o=this.originalHighlightDivInnerHTML.substring(s);this.highlightDiv.innerHTML=`
|
20
20
|
${n}<mark class='co-tts-highlight'>${r.text}</mark>${o}
|
21
|
-
`}else this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML}},50)}getPosition(e,t,r){const n=new RegExp(`(?:^|[^-\\w])(${t})\\b`,"g"),s=e.slice(r).search(n);return(s<=0?s:s+1)+r}
|
21
|
+
`}else this.highlightDiv.innerHTML=this.originalHighlightDivInnerHTML}},50)}getPosition(e,t,r){const n=new RegExp(`(?:^|[^-\\w])(${t})\\b`,"g"),s=e.slice(r).search(n);return(s<=0?s:s+1)+r}buildSSML(e){return`<speak xmlns="http://www.w3.org/2001/10/synthesis"
|
22
|
+
xmlns:mstts="http://www.w3.org/2001/mstts"
|
23
|
+
xmlns:emo="http://www.w3.org/2009/10/emotionml"
|
24
|
+
version="1.0"
|
25
|
+
xml:lang="en-US">
|
26
|
+
<voice name="${this.voice}">
|
27
|
+
<prosody rate="${this.rate}%" pitch="${this.pitch}%">
|
28
|
+
${e}
|
29
|
+
</prosody>
|
30
|
+
</voice>
|
31
|
+
</speak>`}}return Li});
|
package/package.json
CHANGED
package/src/main.ts
CHANGED
@@ -10,6 +10,8 @@ export default class TextToSpeech {
|
|
10
10
|
key: string;
|
11
11
|
region: string;
|
12
12
|
voice: string;
|
13
|
+
rate: number;
|
14
|
+
pitch: number;
|
13
15
|
|
14
16
|
textToRead: string = '';
|
15
17
|
|
@@ -34,10 +36,12 @@ export default class TextToSpeech {
|
|
34
36
|
wordBoundaryOffset: number = 0;
|
35
37
|
|
36
38
|
|
37
|
-
constructor(key: string, region: string, voice: string) {
|
39
|
+
constructor(key: string, region: string, voice: string, rate: number = 0, pitch: number = 0) {
|
38
40
|
this.key = key;
|
39
41
|
this.region = region;
|
40
42
|
this.voice = voice;
|
43
|
+
this.rate = rate;
|
44
|
+
this.pitch = pitch;
|
41
45
|
}
|
42
46
|
|
43
47
|
async start() {
|
@@ -155,7 +159,6 @@ export default class TextToSpeech {
|
|
155
159
|
await this.createInterval();
|
156
160
|
this.clickedNode = node;
|
157
161
|
if (node.hasAttribute('co-tts.highlight')) {
|
158
|
-
console.log(node.attributes.getNamedItem('co-tts.highlight'));
|
159
162
|
if (node.attributes.getNamedItem('co-tts.highlight')?.value !== '') {
|
160
163
|
const newReferenceDiv = document.getElementById(node.attributes.getNamedItem('co-tts.highlight').value);
|
161
164
|
|
@@ -250,7 +253,8 @@ export default class TextToSpeech {
|
|
250
253
|
document.dispatchEvent(new CustomEvent('COAzureTTSStartedPlaying', {}));
|
251
254
|
};
|
252
255
|
|
253
|
-
this.
|
256
|
+
console.log(this.buildSSML(this.textToRead));
|
257
|
+
this.synthesizer.speakSsmlAsync(this.buildSSML(this.textToRead),
|
254
258
|
() => {
|
255
259
|
this.synthesizer.close();
|
256
260
|
this.synthesizer = undefined;
|
@@ -326,4 +330,18 @@ export default class TextToSpeech {
|
|
326
330
|
const offset = string.slice(lastOffset).search(regex);
|
327
331
|
return (offset <= 0 ? offset : offset + 1) + lastOffset;
|
328
332
|
}
|
333
|
+
|
334
|
+
buildSSML(text: string) {
|
335
|
+
return `<speak xmlns="http://www.w3.org/2001/10/synthesis"
|
336
|
+
xmlns:mstts="http://www.w3.org/2001/mstts"
|
337
|
+
xmlns:emo="http://www.w3.org/2009/10/emotionml"
|
338
|
+
version="1.0"
|
339
|
+
xml:lang="en-US">
|
340
|
+
<voice name="${this.voice}">
|
341
|
+
<prosody rate="${this.rate}%" pitch="${this.pitch}%">
|
342
|
+
${text}
|
343
|
+
</prosody>
|
344
|
+
</voice>
|
345
|
+
</speak>`;
|
346
|
+
}
|
329
347
|
}
|