diff --git a/src/components/BootstrapBlazor.AzureSpeech/BootstrapBlazor.AzureSpeech.csproj b/src/components/BootstrapBlazor.AzureSpeech/BootstrapBlazor.AzureSpeech.csproj index bdbebba9..3c70ad99 100644 --- a/src/components/BootstrapBlazor.AzureSpeech/BootstrapBlazor.AzureSpeech.csproj +++ b/src/components/BootstrapBlazor.AzureSpeech/BootstrapBlazor.AzureSpeech.csproj @@ -1,4 +1,8 @@ - + + + + 10.0.2 + Bootstrap Blazor Azure WebAssembly wasm Speech Components @@ -6,6 +10,13 @@ BootstrapBlazor.Components + + + + + + + diff --git a/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/microsoft.cognitiveservices.speech.sdk.bundle-min.js b/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/microsoft.cognitiveservices.speech.sdk.bundle-min.js new file mode 100644 index 00000000..b50438eb --- /dev/null +++ b/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/microsoft.cognitiveservices.speech.sdk.bundle-min.js @@ -0,0 +1 @@ +(()=>{var e=[,function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});new(i(2).AgentConfig),n(i(85),t)},function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),t.AutoDetectSourceLanguagesOpenRangeOptionName=t.ForceDictationPropertyName=t.ServicePropertiesPropertyName=t.CancellationErrorCodePropertyName=t.OutputFormatPropertyName=t.SpeechSynthesisAdapter=t.AvatarSynthesisAdapter=void 0,n(i(3),t),n(i(61),t),n(i(60),t),n(i(62),t),n(i(63),t),n(i(64),t),n(i(65),t),n(i(202),t),n(i(203),t),n(i(204),t),n(i(205),t),n(i(206),t),n(i(207),t),n(i(208),t),n(i(209),t),n(i(180),t),n(i(211),t),n(i(212),t),n(i(213),t),n(i(214),t),n(i(215),t),n(i(216),t),n(i(217),t),n(i(218),t),n(i(219),t),n(i(220),t),n(i(221),t),n(i(223),t),n(i(224),t),n(i(225),t),n(i(226),t),n(i(228),t),n(i(230),t),n(i(231),t),n(i(233),t),n(i(239),t),n(i(240),t),n(i(244),t),n(i(245),t),n(i(247),t);var s=i(248);Object.defineProperty(t,"AvatarSynthesisAdapter",{enumerable:!0,get:function(){return s.AvatarSynthesisAdapter}});var o=i(249);Object.defineProperty(t,"SpeechSynthesisAdapter",{enumerable:!0,get:function(){return o.SpeechSynthesisAdapter}}),n(i(250),t),n(i(251),t),n(i(252),t),n(i(253),t),t.OutputFormatPropertyName="OutputFormat",t.CancellationErrorCodePropertyName="CancellationErrorCode",t.ServicePropertiesPropertyName="ServiceProperties",t.ForceDictationPropertyName="ForceDictation",t.AutoDetectSourceLanguagesOpenRangeOptionName="UND"},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CognitiveSubscriptionKeyAuthentication=void 0;const r=i(4),n=i(59),s=i(60);t.CognitiveSubscriptionKeyAuthentication=class{constructor(e){if(!e)throw new r.ArgumentNullError("subscriptionKey");this.privAuthInfo=new s.AuthInfo(n.HeaderNames.AuthKey,e)}fetch(e){return Promise.resolve(this.privAuthInfo)}fetchOnExpiry(e){return Promise.resolve(this.privAuthInfo)}}},function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationStatus=void 0,n(i(5),t),n(i(29),t),n(i(30),t),n(i(32),t),n(i(33),t),n(i(34),t),n(i(31),t),n(i(35),t),n(i(36),t),n(i(7),t),n(i(37),t),n(i(38),t),n(i(39),t),n(i(40),t),n(i(41),t),n(i(42),t),n(i(43),t),n(i(44),t),n(i(45),t),n(i(46),t),n(i(47),t),n(i(6),t),n(i(48),t),n(i(49),t),n(i(50),t),n(i(51),t),n(i(52),t);var s=i(53);Object.defineProperty(t,"TranslationStatus",{enumerable:!0,get:function(){return s.TranslationStatus}}),n(i(54),t),n(i(55),t),n(i(56),t),n(i(57),t),n(i(58),t)},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AudioStreamNodeErrorEvent=t.AudioStreamNodeDetachedEvent=t.AudioStreamNodeAttachedEvent=t.AudioStreamNodeAttachingEvent=t.AudioStreamNodeEvent=t.AudioSourceErrorEvent=t.AudioSourceOffEvent=t.AudioSourceReadyEvent=t.AudioSourceInitializingEvent=t.AudioSourceEvent=void 0;const r=i(6);class n extends r.PlatformEvent{constructor(e,t,i=r.EventType.Info){super(e,i),this.privAudioSourceId=t}get audioSourceId(){return this.privAudioSourceId}}t.AudioSourceEvent=n;t.AudioSourceInitializingEvent=class extends n{constructor(e){super("AudioSourceInitializingEvent",e)}};t.AudioSourceReadyEvent=class extends n{constructor(e){super("AudioSourceReadyEvent",e)}};t.AudioSourceOffEvent=class extends n{constructor(e){super("AudioSourceOffEvent",e)}};t.AudioSourceErrorEvent=class extends n{constructor(e,t){super("AudioSourceErrorEvent",e,r.EventType.Error),this.privError=t}get error(){return this.privError}};class s extends n{constructor(e,t,i){super(e,t),this.privAudioNodeId=i}get audioNodeId(){return this.privAudioNodeId}}t.AudioStreamNodeEvent=s;t.AudioStreamNodeAttachingEvent=class extends s{constructor(e,t){super("AudioStreamNodeAttachingEvent",e,t)}};t.AudioStreamNodeAttachedEvent=class extends s{constructor(e,t){super("AudioStreamNodeAttachedEvent",e,t)}};t.AudioStreamNodeDetachedEvent=class extends s{constructor(e,t){super("AudioStreamNodeDetachedEvent",e,t)}};t.AudioStreamNodeErrorEvent=class extends s{constructor(e,t,i){super("AudioStreamNodeErrorEvent",e,t),this.privError=i}get error(){return this.privError}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PlatformEvent=t.EventType=void 0;const r=i(7);!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error",e[e.None=4]="None"}(t.EventType||(t.EventType={}));t.PlatformEvent=class{constructor(e,t){this.privName=e,this.privEventId=(0,r.createNoDashGuid)(),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}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createNoDashGuid=t.createGuid=void 0;const r=i(8),n=()=>(0,r.v4)();t.createGuid=n;t.createNoDashGuid=()=>n().replace(new RegExp("-","g"),"").toUpperCase()},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.version=t.validate=t.v7=t.v6ToV1=t.v6=t.v5=t.v4=t.v3=t.v1ToV6=t.v1=t.stringify=t.parse=t.NIL=t.MAX=void 0;var r=i(9);Object.defineProperty(t,"MAX",{enumerable:!0,get:function(){return r.default}});var n=i(10);Object.defineProperty(t,"NIL",{enumerable:!0,get:function(){return n.default}});var s=i(11);Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return s.default}});var o=i(14);Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return o.default}});var a=i(15);Object.defineProperty(t,"v1",{enumerable:!0,get:function(){return a.default}});var c=i(17);Object.defineProperty(t,"v1ToV6",{enumerable:!0,get:function(){return c.default}});var p=i(18);Object.defineProperty(t,"v3",{enumerable:!0,get:function(){return p.default}});var u=i(21);Object.defineProperty(t,"v4",{enumerable:!0,get:function(){return u.default}});var h=i(23);Object.defineProperty(t,"v5",{enumerable:!0,get:function(){return h.default}});var d=i(25);Object.defineProperty(t,"v6",{enumerable:!0,get:function(){return d.default}});var v=i(26);Object.defineProperty(t,"v6ToV1",{enumerable:!0,get:function(){return v.default}});var l=i(27);Object.defineProperty(t,"v7",{enumerable:!0,get:function(){return l.default}});var g=i(12);Object.defineProperty(t,"validate",{enumerable:!0,get:function(){return g.default}});var S=i(28);Object.defineProperty(t,"version",{enumerable:!0,get:function(){return S.default}})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default="ffffffff-ffff-ffff-ffff-ffffffffffff"},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default="00000000-0000-0000-0000-000000000000"},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(12);t.default=function(e){if(!(0,r.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(13);t.default=function(e){return"string"==typeof e&&r.default.test(e)}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.unsafeStringify=void 0;const r=i(12),n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));function s(e,t=0){return(n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]).toLowerCase()}t.unsafeStringify=s,t.default=function(e,t=0){const i=s(e,t);if(!(0,r.default)(i))throw TypeError("Stringified UUID is invalid");return i}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateV1State=void 0;const r=i(16),n=i(14),s={};function o(e,t,i){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t= 16");if(s){if(o<0||o+16>s.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`)}else s=new Uint8Array(16),o=0;t??=Date.now(),i??=0,r??=16383&(e[8]<<8|e[9]),n??=e.slice(10,16);const a=(1e4*(268435455&(t+=122192928e5))+i)%4294967296;s[o++]=a>>>24&255,s[o++]=a>>>16&255,s[o++]=a>>>8&255,s[o++]=255&a;const c=t/4294967296*1e4&268435455;s[o++]=c>>>8&255,s[o++]=255&c,s[o++]=c>>>24&15|16,s[o++]=c>>>16&255,s[o++]=r>>>8|128,s[o++]=255&r;for(let e=0;e<6;++e)s[o++]=n[e];return s}t.updateV1State=o,t.default=function(e,t,i){let c;const p=e?._v6??!1;if(e){const t=Object.keys(e);1===t.length&&"_v6"===t[0]&&(e=void 0)}if(e)c=a(e.random??e.rng?.()??(0,r.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,i);else{const e=Date.now(),n=(0,r.default)();o(s,e,n),c=a(n,s.msecs,s.nsecs,p?void 0:s.clockseq,p?void 0:s.node,t,i)}return t??(0,n.unsafeStringify)(c)}},(e,t)=>{"use strict";let i;Object.defineProperty(t,"__esModule",{value:!0});const r=new Uint8Array(16);t.default=function(){if(!i){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");i=crypto.getRandomValues.bind(crypto)}return i(r)}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(11),n=i(14);t.default=function(e){const t=function(e){return Uint8Array.of((15&e[6])<<4|e[7]>>4&15,(15&e[7])<<4|(240&e[4])>>4,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,(15&e[1])<<4|(240&e[2])>>4,96|15&e[2],e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,r.default)(e):e);return"string"==typeof e?(0,n.unsafeStringify)(t):t}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URL=t.DNS=void 0;const r=i(19),n=i(20);var s=i(20);function o(e,t,i,s){return(0,n.default)(48,r.default,e,t,i,s)}Object.defineProperty(t,"DNS",{enumerable:!0,get:function(){return s.DNS}}),Object.defineProperty(t,"URL",{enumerable:!0,get:function(){return s.URL}}),o.DNS=n.DNS,o.URL=n.URL,t.default=o},(e,t)=>{"use strict";function i(e){return 14+(e+64>>>9<<4)+1}function r(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function n(e,t,i,n,s,o){return r((a=r(r(t,e),r(n,o)))<<(c=s)|a>>>32-c,i);var a,c}function s(e,t,i,r,s,o,a){return n(t&i|~t&r,e,t,s,o,a)}function o(e,t,i,r,s,o,a){return n(t&r|i&~r,e,t,s,o,a)}function a(e,t,i,r,s,o,a){return n(t^i^r,e,t,s,o,a)}function c(e,t,i,r,s,o,a){return n(i^(t|~r),e,t,s,o,a)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(e){const t=new Uint8Array(4*e.length);for(let i=0;i<4*e.length;i++)t[i]=e[i>>2]>>>i%4*8&255;return t}(function(e,t){const n=new Uint32Array(i(t)).fill(0);n.set(e),n[t>>5]|=128<>2]|=(255&e[i])<{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URL=t.DNS=t.stringToBytes=void 0;const r=i(11),n=i(14);function s(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let i=0;ia.length)throw new RangeError(`UUID byte range ${c}:${c+15} is out of buffer bounds`);for(let e=0;e<16;++e)a[c+e]=h[e];return a}return(0,n.unsafeStringify)(h)}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(22),n=i(16),s=i(14);t.default=function(e,t,i){if(r.default.randomUUID&&!t&&!e)return r.default.randomUUID();const o=(e=e||{}).random??e.rng?.()??(0,n.default)();if(o.length<16)throw new Error("Random bytes length must be >= 16");if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){if((i=i||0)<0||i+16>t.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[i+e]=o[e];return t}return(0,s.unsafeStringify)(o)}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);t.default={randomUUID:i}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.URL=t.DNS=void 0;const r=i(24),n=i(20);var s=i(20);function o(e,t,i,s){return(0,n.default)(80,r.default,e,t,i,s)}Object.defineProperty(t,"DNS",{enumerable:!0,get:function(){return s.DNS}}),Object.defineProperty(t,"URL",{enumerable:!0,get:function(){return s.URL}}),o.DNS=n.DNS,o.URL=n.URL,t.default=o},(e,t)=>{"use strict";function i(e,t,i,r){switch(e){case 0:return t&i^~t&r;case 1:case 3:return t^i^r;case 2:return t&i^t&r^i&r}}function r(e,t){return e<>>32-t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],s=new Uint8Array(e.length+1);s.set(e),s[e.length]=128;const o=(e=s).length/4+2,a=Math.ceil(o/16),c=new Array(a);for(let t=0;t>>0;h=u,u=p,p=r(a,30)>>>0,a=o,o=c}n[0]=n[0]+o>>>0,n[1]=n[1]+a>>>0,n[2]=n[2]+p>>>0,n[3]=n[3]+u>>>0,n[4]=n[4]+h>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(14),n=i(15),s=i(17);t.default=function(e,t,i){e??={},i??=0;let o=(0,n.default)({...e,_v6:!0},new Uint8Array(16));if(o=(0,s.default)(o),t){if(i<0||i+16>t.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let e=0;e<16;e++)t[i+e]=o[e];return t}return(0,r.unsafeStringify)(o)}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(11),n=i(14);t.default=function(e){const t=function(e){return Uint8Array.of((15&e[3])<<4|e[4]>>4&15,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|15&e[6],e[7],(15&e[1])<<4|(240&e[2])>>4,(15&e[2])<<4|(240&e[3])>>4,16|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,r.default)(e):e);return"string"==typeof e?(0,n.unsafeStringify)(t):t}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateV7State=void 0;const r=i(16),n=i(14),s={};function o(e,t,i){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=i[6]<<23|i[7]<<16|i[8]<<8|i[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++),e}function a(e,t,i,r,n=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(r){if(n<0||n+16>r.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`)}else r=new Uint8Array(16),n=0;return t??=Date.now(),i??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],r[n++]=t/1099511627776&255,r[n++]=t/4294967296&255,r[n++]=t/16777216&255,r[n++]=t/65536&255,r[n++]=t/256&255,r[n++]=255&t,r[n++]=112|i>>>28&15,r[n++]=i>>>20&255,r[n++]=128|i>>>14&63,r[n++]=i>>>6&255,r[n++]=i<<2&255|3&e[10],r[n++]=e[11],r[n++]=e[12],r[n++]=e[13],r[n++]=e[14],r[n++]=e[15],r}t.updateV7State=o,t.default=function(e,t,i){let c;if(e)c=a(e.random??e.rng?.()??(0,r.default)(),e.msecs,e.seq,t,i);else{const e=Date.now(),n=(0,r.default)();o(s,e,n),c=a(n,s.msecs,s.seq,t,i)}return t??(0,n.unsafeStringify)(c)}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=i(12);t.default=function(e){if(!(0,r.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionRedirectEvent=t.ConnectionMessageSentEvent=t.ConnectionMessageReceivedEvent=t.ConnectionEstablishErrorEvent=t.ConnectionErrorEvent=t.ConnectionClosedEvent=t.ConnectionEstablishedEvent=t.ConnectionStartEvent=t.ConnectionEvent=t.ServiceEvent=void 0;const r=i(6);class n extends r.PlatformEvent{constructor(e,t,i=r.EventType.Info){super(e,i),this.privJsonResult=t}get jsonString(){return this.privJsonResult}}t.ServiceEvent=n;class s extends r.PlatformEvent{constructor(e,t,i=r.EventType.Info){super(e,i),this.privConnectionId=t}get connectionId(){return this.privConnectionId}}t.ConnectionEvent=s;t.ConnectionStartEvent=class extends s{constructor(e,t,i){super("ConnectionStartEvent",e),this.privUri=t,this.privHeaders=i}get uri(){return this.privUri}get headers(){return this.privHeaders}};t.ConnectionEstablishedEvent=class extends s{constructor(e){super("ConnectionEstablishedEvent",e)}};t.ConnectionClosedEvent=class extends s{constructor(e,t,i){super("ConnectionClosedEvent",e,r.EventType.Debug),this.privReason=i,this.privStatusCode=t}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}};t.ConnectionErrorEvent=class extends s{constructor(e,t,i){super("ConnectionErrorEvent",e,r.EventType.Debug),this.privMessage=t,this.privType=i}get message(){return this.privMessage}get type(){return this.privType}};t.ConnectionEstablishErrorEvent=class extends s{constructor(e,t,i){super("ConnectionEstablishErrorEvent",e,r.EventType.Error),this.privStatusCode=t,this.privReason=i}get reason(){return this.privReason}get statusCode(){return this.privStatusCode}};t.ConnectionMessageReceivedEvent=class extends s{constructor(e,t,i){super("ConnectionMessageReceivedEvent",e),this.privNetworkReceivedTime=t,this.privMessage=i}get networkReceivedTime(){return this.privNetworkReceivedTime}get message(){return this.privMessage}};t.ConnectionMessageSentEvent=class extends s{constructor(e,t,i){super("ConnectionMessageSentEvent",e),this.privNetworkSentTime=t,this.privMessage=i}get networkSentTime(){return this.privNetworkSentTime}get message(){return this.privMessage}};t.ConnectionRedirectEvent=class extends s{constructor(e,t,i,n){super("ConnectionRedirectEvent",e,r.EventType.Info),this.privRedirectUrl=t,this.privOriginalUrl=i,this.privContext=n}get redirectUrl(){return this.privRedirectUrl}get originalUrl(){return this.privOriginalUrl}get context(){return this.privContext}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionMessage=t.MessageType=void 0;const r=i(31),n=i(7);var s;!function(e){e[e.Text=0]="Text",e[e.Binary=1]="Binary"}(s=t.MessageType||(t.MessageType={}));t.ConnectionMessage=class{constructor(e,t,i,o){if(this.privBody=null,e===s.Text&&t&&"string"!=typeof t)throw new r.InvalidOperationError("Payload must be a string");if(e===s.Binary&&t&&!(t instanceof ArrayBuffer))throw new r.InvalidOperationError("Payload must be ArrayBuffer");switch(this.privMessageType=e,this.privBody=t,this.privHeaders=i||{},this.privId=o||(0,n.createNoDashGuid)(),this.messageType){case s.Binary:this.privSize=null!==this.binaryBody?this.binaryBody.byteLength:0;break;case s.Text:this.privSize=this.textBody.length}}get messageType(){return this.privMessageType}get headers(){return this.privHeaders}get body(){return this.privBody}get textBody(){if(this.privMessageType===s.Binary)throw new r.InvalidOperationError("Not supported for binary message");return this.privBody}get binaryBody(){if(this.privMessageType===s.Text)throw new r.InvalidOperationError("Not supported for text message");return this.privBody}get id(){return this.privId}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectDisposedError=t.InvalidOperationError=t.ArgumentNullError=void 0;class i extends Error{constructor(e){super(e),this.name="ArgumentNull",this.message=e}}t.ArgumentNullError=i;class r extends Error{constructor(e){super(e),this.name="InvalidOperation",this.message=e}}t.InvalidOperationError=r;class n extends Error{constructor(e,t){super(t),this.name=e+"ObjectDisposed",this.message=t}}t.ObjectDisposedError=n},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionOpenResponse=void 0;t.ConnectionOpenResponse=class{constructor(e,t){this.privStatusCode=e,this.privReason=t}get statusCode(){return this.privStatusCode}get reason(){return this.privReason}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DeferralMap=void 0;t.DeferralMap=class{constructor(){this.privMap={}}add(e,t){this.privMap[e]=t}getId(e){return this.privMap[e]}complete(e,t){try{this.privMap[e].resolve(t)}catch(t){this.privMap[e].reject(t)}finally{this.privMap[e]=void 0}}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SendingAgentContextMessageEvent=t.DialogEvent=void 0;const r=i(6);class n extends r.PlatformEvent{constructor(e,t=r.EventType.Info){super(e,t)}}t.DialogEvent=n;t.SendingAgentContextMessageEvent=class extends n{constructor(e){super("SendingAgentContextMessageEvent"),this.privAgentConfig=e}get agentConfig(){return this.privAgentConfig}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Events=void 0;const r=i(31),n=i(36);class s{static setEventSource(e){if(!e)throw new r.ArgumentNullError("eventSource");s.privInstance=e}static get instance(){return s.privInstance}}t.Events=s,s.privInstance=new n.EventSource},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EventSource=void 0;const r=i(31),n=i(7);t.EventSource=class{constructor(e){this.privEventListeners={},this.privIsDisposed=!1,this.privConsoleListener=void 0,this.privMetadata=e}onEvent(e){if(this.isDisposed())throw new r.ObjectDisposedError("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=(0,n.createNoDashGuid)();return this.privEventListeners[t]=e,{detach:()=>(delete this.privEventListeners[t],Promise.resolve())}}attachListener(e){return this.attach((t=>e.onEvent(t)))}attachConsoleListener(e){return this.privConsoleListener&&this.privConsoleListener.detach(),this.privConsoleListener=this.attach((t=>e.onEvent(t))),this.privConsoleListener}isDisposed(){return this.privIsDisposed}dispose(){this.privEventListeners=null,this.privIsDisposed=!0}get metadata(){return this.privMetadata}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionState=void 0,function(e){e[e.None=0]="None",e[e.Connected=1]="Connected",e[e.Connecting=2]="Connecting",e[e.Disconnected=3]="Disconnected"}(t.ConnectionState||(t.ConnectionState={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.List=void 0;const r=i(31);class n{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(),0===e?this.privList.unshift(t):e===this.privList.length?this.privList.push(t):this.privList.splice(e,0,t),this.triggerSubscriptions(this.privAddSubscriptions)}removeFirst(){return this.throwIfDisposed(),this.removeAt(0)}removeLast(){return this.throwIfDisposed(),this.removeAt(this.length()-1)}removeAt(e){return this.throwIfDisposed(),this.remove(e,1)[0]}remove(e,t){this.throwIfDisposed();const i=this.privList.splice(e,t);return this.triggerSubscriptions(this.privRemoveSubscriptions),i}clear(){this.throwIfDisposed(),this.remove(0,this.length())}length(){return this.throwIfDisposed(),this.privList.length}onAdded(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privAddSubscriptions[t]=e,{detach:()=>(delete this.privAddSubscriptions[t],Promise.resolve())}}onRemoved(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privRemoveSubscriptions[t]=e,{detach:()=>(delete this.privRemoveSubscriptions[t],Promise.resolve())}}onDisposed(e){this.throwIfDisposed();const t=this.privSubscriptionIdCounter++;return this.privDisposedSubscriptions[t]=e,{detach:()=>(delete this.privDisposedSubscriptions[t],Promise.resolve())}}join(e){return this.throwIfDisposed(),this.privList.join(e)}toArray(){const e=Array();return this.privList.forEach((t=>{e.push(t)})),e}any(e){return this.throwIfDisposed(),e?this.where(e).length()>0:this.length()>0}all(e){return this.throwIfDisposed(),this.where(e).length()===this.length()}forEach(e){this.throwIfDisposed();for(let t=0;te(i,t)))}clone(){return this.throwIfDisposed(),new n(this.toArray())}concat(e){return this.throwIfDisposed(),new n(this.privList.concat(e.toArray()))}concatArray(e){return this.throwIfDisposed(),new n(this.privList.concat(e))}isDisposed(){return null==this.privList}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 r.ObjectDisposedError("List",this.privDisposeReason)}triggerSubscriptions(e){if(e)for(const t in e)t&&e[t]()}}t.List=n},(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.marshalPromiseToCallbacks=t.Sink=t.Deferred=t.PromiseResultEventSource=t.PromiseResult=t.PromiseState=void 0,function(e){e[e.None=0]="None",e[e.Resolved=1]="Resolved",e[e.Rejected=2]="Rejected"}(i=t.PromiseState||(t.PromiseState={}));class r{constructor(e){this.throwIfError=()=>{if(this.isError)throw this.error},e.on((e=>{this.privIsCompleted||(this.privIsCompleted=!0,this.privIsError=!1,this.privResult=e)}),(e=>{this.privIsCompleted||(this.privIsCompleted=!0,this.privIsError=!0,this.privError=e)}))}get isCompleted(){return this.privIsCompleted}get isError(){return this.privIsError}get error(){return this.privError}get result(){return this.privResult}}t.PromiseResult=r;class n{constructor(){this.setResult=e=>{this.privOnSetResult(e)},this.setError=e=>{this.privOnSetError(e)},this.on=(e,t)=>{this.privOnSetResult=e,this.privOnSetError=t}}}t.PromiseResultEventSource=n;t.Deferred=class{constructor(){this.resolve=e=>(this.privResolve(e),this),this.reject=e=>(this.privReject(e),this),this.privPromise=new Promise(((e,t)=>{this.privResolve=e,this.privReject=t}))}get promise(){return this.privPromise}};t.Sink=class{constructor(){this.privState=i.None,this.privPromiseResult=null,this.privPromiseResultEvents=null,this.privSuccessHandlers=[],this.privErrorHandlers=[],this.privPromiseResultEvents=new n,this.privPromiseResult=new r(this.privPromiseResultEvents)}get state(){return this.privState}get result(){return this.privPromiseResult}resolve(e){if(this.privState!==i.None)throw new Error("'Cannot resolve a completed promise'");this.privState=i.Resolved,this.privPromiseResultEvents.setResult(e);for(let t=0;t{}),this.privState===i.None?(this.privSuccessHandlers.push(e),this.privErrorHandlers.push(t)):(this.privState===i.Resolved?this.executeSuccessCallback(this.privPromiseResult.result,e,t):this.privState===i.Rejected&&this.executeErrorCallback(this.privPromiseResult.error,t),this.detachHandlers())}executeSuccessCallback(e,t,i){try{t(e)}catch(e){this.executeErrorCallback(`'Unhandled callback error: ${e}'`,i)}}executeErrorCallback(e,t){if(!t)throw new Error(`'Unhandled error: ${e}'`);try{t(e)}catch(t){throw new Error(`'Unhandled callback error: ${t}. InnerError: ${e}'`)}}detachHandlers(){this.privErrorHandlers=[],this.privSuccessHandlers=[]}},t.marshalPromiseToCallbacks=function(e,t,i){e.then((e=>{try{t&&t(e)}catch(e){if(i)try{if(e instanceof Error){const t=e;i(t.name+": "+t.message)}else i(e)}catch(e){}}}),(e=>{if(i)try{if(e instanceof Error){const t=e;i(t.name+": "+t.message)}else i(e)}catch(e){}}))}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Queue=void 0;const r=i(31),n=i(47),s=i(48);var o;!function(e){e[e.Dequeue=0]="Dequeue",e[e.Peek=1]="Peek"}(o||(o={}));t.Queue=class{constructor(e){this.privPromiseStore=new n.List,this.privIsDrainInProgress=!1,this.privIsDisposing=!1,this.privDisposeReason=null,this.privList=e||new n.List,this.privDetachables=[],this.privSubscribers=new n.List,this.privDetachables.push(this.privList.onAdded((()=>this.drain())))}enqueue(e){this.throwIfDispose(),this.enqueueFromPromise(new Promise((t=>t(e))))}enqueueFromPromise(e){this.throwIfDispose(),e.then((e=>{this.privList.add(e)}),(()=>{}))}dequeue(){this.throwIfDispose();const e=new s.Deferred;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:o.Dequeue}),this.drain()),e.promise}peek(){this.throwIfDispose();const e=new s.Deferred;return this.privSubscribers&&(this.privSubscribers.add({deferral:e,type:o.Peek}),this.drain()),e.promise}length(){return this.throwIfDispose(),this.privList.length()}isDisposed(){return null==this.privSubscribers}async drainAndDispose(e,t){if(!this.isDisposed()&&!this.privIsDisposing){this.privDisposeReason=t,this.privIsDisposing=!0;const i=this.privSubscribers;if(i){for(;i.length()>0;){i.removeFirst().deferral.resolve(void 0)}this.privSubscribers===i&&(this.privSubscribers=i)}for(const e of this.privDetachables)await e.detach();if(this.privPromiseStore.length()>0&&e){const t=[];return this.privPromiseStore.toArray().forEach((e=>{t.push(e)})),Promise.all(t).finally((()=>{this.privSubscribers=null,this.privList.forEach((t=>{e(t)})),this.privList=null})).then()}this.privSubscribers=null,this.privList=null}}async dispose(e){await this.drainAndDispose(null,e)}drain(){if(!this.privIsDrainInProgress&&!this.privIsDisposing){this.privIsDrainInProgress=!0;const e=this.privSubscribers,t=this.privList;if(e&&t){for(;t.length()>0&&e.length()>0&&!this.privIsDisposing;){const i=e.removeFirst();if(i.type===o.Peek)i.deferral.resolve(t.first());else{const e=t.removeFirst();i.deferral.resolve(e)}}this.privSubscribers===e&&(this.privSubscribers=e),this.privList===t&&(this.privList=t)}this.privIsDrainInProgress=!1}}throwIfDispose(){if(this.isDisposed()){if(this.privDisposeReason)throw new r.InvalidOperationError(this.privDisposeReason);throw new r.ObjectDisposedError("Queue")}if(this.privIsDisposing)throw new r.InvalidOperationError("Queue disposing")}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RawWebsocketMessage=void 0;const r=i(30),n=i(31),s=i(7);t.RawWebsocketMessage=class{constructor(e,t,i){if(this.privPayload=null,!t)throw new n.ArgumentNullError("payload");if(e===r.MessageType.Binary&&"ArrayBuffer"!==Object.getPrototypeOf(t).constructor.name)throw new n.InvalidOperationError("Payload must be ArrayBuffer");if(e===r.MessageType.Text&&"string"!=typeof t)throw new n.InvalidOperationError("Payload must be a string");this.privMessageType=e,this.privPayload=t,this.privId=i||(0,s.createNoDashGuid)()}get messageType(){return this.privMessageType}get payload(){return this.privPayload}get textContent(){if(this.privMessageType===r.MessageType.Binary)throw new n.InvalidOperationError("Not supported for binary message");return this.privPayload}get binaryContent(){if(this.privMessageType===r.MessageType.Text)throw new n.InvalidOperationError("Not supported for text message");return this.privPayload}get id(){return this.privId}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RiffPcmEncoder=void 0;t.RiffPcmEncoder=class{constructor(e,t){this.privActualSampleRate=e,this.privDesiredSampleRate=t}encode(e){const t=this.downSampleAudioFrame(e,this.privActualSampleRate,this.privDesiredSampleRate);if(!t)return null;const i=2*t.length,r=new ArrayBuffer(i),n=new DataView(r);return this.floatTo16BitPCM(n,0,t),r}setString(e,t,i){for(let r=0;rt)return e;const r=t/i,n=Math.round(e.length/r),s=new Float32Array(n);let o=0,a=0;for(;a{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Stream=void 0;const r=i(31),n=i(7),s=i(49);t.Stream=class{constructor(e){this.privIsWriteEnded=!1,this.privIsReadEnded=!1,this.privId=e||(0,n.createNoDashGuid)(),this.privReaderQueue=new s.Queue}get isClosed(){return this.privIsWriteEnded}get isReadEnded(){return this.privIsReadEnded}get id(){return this.privId}close(){this.privIsWriteEnded||(this.writeStreamChunk({buffer:null,isEnd:!0,timeReceived:Date.now()}),this.privIsWriteEnded=!0)}writeStreamChunk(e){if(this.throwIfClosed(),!this.privReaderQueue.isDisposed())try{this.privReaderQueue.enqueue(e)}catch(e){}}read(){if(this.privIsReadEnded)throw new r.InvalidOperationError("Stream read has already finished");return this.privReaderQueue.dequeue().then((async e=>((void 0===e||e.isEnd)&&await this.privReaderQueue.dispose("End of stream reached"),e)))}readEnded(){this.privIsReadEnded||(this.privIsReadEnded=!0,this.privReaderQueue=new s.Queue)}throwIfClosed(){if(this.privIsWriteEnded)throw new r.InvalidOperationError("Stream closed")}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationStatus=void 0,function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(t.TranslationStatus||(t.TranslationStatus={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChunkedArrayBufferStream=void 0;const r=i(4);class n extends r.Stream{constructor(e,t){super(t),this.privTargetChunkSize=Math.round(e),this.privNextBufferReadyBytes=0}writeStreamChunk(e){if(e.isEnd||0===this.privNextBufferReadyBytes&&e.buffer.byteLength===this.privTargetChunkSize)return void super.writeStreamChunk(e);let t=0;for(;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Timeout=void 0;class i{static load(){const e=new Map([[0,()=>{}]]),t=new Map,r="data:text/javascript;base64,"+btoa('!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=14)}([function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return d}));const r=new Map,o=new Map,i=e=>{const t=r.get(e);if(void 0===t)throw new Error(\'There is no interval scheduled with the given id "\'.concat(e,\'".\'));clearTimeout(t),r.delete(e)},u=e=>{const t=o.get(e);if(void 0===t)throw new Error(\'There is no timeout scheduled with the given id "\'.concat(e,\'".\'));clearTimeout(t),o.delete(e)},f=(e,t)=>{let n,r;if("performance"in self){const o=performance.now();n=o,r=e-Math.max(0,o-t)}else n=Date.now(),r=e;return{expected:n+r,remainingDelay:r}},c=(e,t,n,r)=>{const o="performance"in self?performance.now():Date.now();o>n?postMessage({id:null,method:"call",params:{timerId:t}}):e.set(t,setTimeout(c,n-o,e,t,n))},a=(e,t,n)=>{const{expected:o,remainingDelay:i}=f(e,n);r.set(t,setTimeout(c,i,r,t,o))},d=(e,t,n)=>{const{expected:r,remainingDelay:i}=f(e,n);o.set(t,setTimeout(c,i,o,t,r))}},function(e,t,n){"use strict";n.r(t);var r=n(2);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(3);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(4);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o);var f=n(5);for(var o in f)"default"!==o&&function(e){n.d(t,e,(function(){return f[e]}))}(o);var c=n(6);for(var o in c)"default"!==o&&function(e){n.d(t,e,(function(){return c[e]}))}(o);var a=n(7);for(var o in a)"default"!==o&&function(e){n.d(t,e,(function(){return a[e]}))}(o);var d=n(8);for(var o in d)"default"!==o&&function(e){n.d(t,e,(function(){return d[e]}))}(o);var s=n(9);for(var o in s)"default"!==o&&function(e){n.d(t,e,(function(){return s[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(11);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(12);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(13);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(0),o=n(1);for(var i in o)"default"!==i&&function(e){n.d(t,e,(function(){return o[e]}))}(i);var u=n(10);for(var i in u)"default"!==i&&function(e){n.d(t,e,(function(){return u[e]}))}(i);addEventListener("message",({data:e})=>{try{if("clear"===e.method){const{id:t,params:{timerId:n}}=e;Object(r.b)(n),postMessage({error:null,id:t})}else{if("set"!==e.method)throw new Error(\'The given method "\'.concat(e.method,\'" is not supported\'));{const{params:{delay:t,now:n,timerId:o}}=e;Object(r.d)(t,o,n)}}}catch(t){postMessage({error:{message:t.message},id:e.id,result:null})}})}]);'),n=new Worker(r);n.addEventListener("message",(({data:r})=>{if(i.isCallNotification(r)){const{params:{timerId:i}}=r,n=e.get(i);if("number"==typeof n){const e=t.get(n);if(void 0===e||e!==i)throw new Error("The timer is in an undefined state.")}else{if(void 0===n)throw new Error("The timer is in an undefined state.");n(),e.delete(i)}}else{if(!i.isClearResponse(r)){const{error:{message:e}}=r;throw new Error(e)}{const{id:i}=r,n=t.get(i);if(void 0===n)throw new Error("The timer is in an undefined state.");t.delete(i),e.delete(n)}}}));return{clearTimeout:i=>{const r=Math.random();t.set(r,i),e.set(i,r),n.postMessage({id:r,method:"clear",params:{timerId:i}})},setTimeout:(t,i)=>{const r=Math.random();return e.set(r,t),n.postMessage({id:null,method:"set",params:{delay:i,now:performance.now(),timerId:r}}),r}}}static loadWorkerTimers(){return()=>(null!==i.workerTimers||(i.workerTimers=i.load()),i.workerTimers)}static isCallNotification(e){return void 0!==e.method&&"call"===e.method}static isClearResponse(e){return null===e.error&&"number"==typeof e.id}}t.Timeout=i,i.workerTimers=null,i.clearTimeout=e=>i.timers().clearTimeout(e),i.setTimeout=(e,t)=>i.timers().setTimeout(e,t),i.timers=i.loadWorkerTimers()},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OCSPCacheUpdateErrorEvent=t.OCSPResponseRetrievedEvent=t.OCSPCacheFetchErrorEvent=t.OCSPVerificationFailedEvent=t.OCSPCacheHitEvent=t.OCSPCacheEntryNeedsRefreshEvent=t.OCSPCacheEntryExpiredEvent=t.OCSPWSUpgradeStartedEvent=t.OCSPStapleReceivedEvent=t.OCSPCacheUpdateCompleteEvent=t.OCSPDiskCacheStoreEvent=t.OCSPMemoryCacheStoreEvent=t.OCSPCacheUpdateNeededEvent=t.OCSPDiskCacheHitEvent=t.OCSPCacheMissEvent=t.OCSPMemoryCacheHitEvent=t.OCSPEvent=void 0;const r=i(6);class n extends r.PlatformEvent{constructor(e,t,i){super(e,t),this.privSignature=i}}t.OCSPEvent=n;t.OCSPMemoryCacheHitEvent=class extends n{constructor(e){super("OCSPMemoryCacheHitEvent",r.EventType.Debug,e)}};t.OCSPCacheMissEvent=class extends n{constructor(e){super("OCSPCacheMissEvent",r.EventType.Debug,e)}};t.OCSPDiskCacheHitEvent=class extends n{constructor(e){super("OCSPDiskCacheHitEvent",r.EventType.Debug,e)}};t.OCSPCacheUpdateNeededEvent=class extends n{constructor(e){super("OCSPCacheUpdateNeededEvent",r.EventType.Debug,e)}};t.OCSPMemoryCacheStoreEvent=class extends n{constructor(e){super("OCSPMemoryCacheStoreEvent",r.EventType.Debug,e)}};t.OCSPDiskCacheStoreEvent=class extends n{constructor(e){super("OCSPDiskCacheStoreEvent",r.EventType.Debug,e)}};t.OCSPCacheUpdateCompleteEvent=class extends n{constructor(e){super("OCSPCacheUpdateCompleteEvent",r.EventType.Debug,e)}};t.OCSPStapleReceivedEvent=class extends n{constructor(){super("OCSPStapleReceivedEvent",r.EventType.Debug,"")}};t.OCSPWSUpgradeStartedEvent=class extends n{constructor(e){super("OCSPWSUpgradeStartedEvent",r.EventType.Debug,e)}};t.OCSPCacheEntryExpiredEvent=class extends n{constructor(e,t){super("OCSPCacheEntryExpiredEvent",r.EventType.Debug,e),this.privExpireTime=t}};t.OCSPCacheEntryNeedsRefreshEvent=class extends n{constructor(e,t,i){super("OCSPCacheEntryNeedsRefreshEvent",r.EventType.Debug,e),this.privExpireTime=i,this.privStartTime=t}};t.OCSPCacheHitEvent=class extends n{constructor(e,t,i){super("OCSPCacheHitEvent",r.EventType.Debug,e),this.privExpireTime=i,this.privExpireTimeString=new Date(i).toLocaleDateString(),this.privStartTime=t,this.privStartTimeString=new Date(t).toLocaleTimeString()}};t.OCSPVerificationFailedEvent=class extends n{constructor(e,t){super("OCSPVerificationFailedEvent",r.EventType.Debug,e),this.privError=t}};t.OCSPCacheFetchErrorEvent=class extends n{constructor(e,t){super("OCSPCacheFetchErrorEvent",r.EventType.Debug,e),this.privError=t}};t.OCSPResponseRetrievedEvent=class extends n{constructor(e){super("OCSPResponseRetrievedEvent",r.EventType.Debug,e)}};t.OCSPCacheUpdateErrorEvent=class extends n{constructor(e,t){super("OCSPCacheUpdateErrorEvent",r.EventType.Debug,e),this.privError=t}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BackgroundEvent=void 0;const r=i(4);class n extends r.PlatformEvent{constructor(e){super("BackgroundEvent",r.EventType.Error),this.privError=e}get error(){return this.privError}}t.BackgroundEvent=n},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HeaderNames=void 0;class i{}t.HeaderNames=i,i.AuthKey="Ocp-Apim-Subscription-Key",i.Authorization="Authorization",i.SpIDAuthKey="Apim-Subscription-Id",i.ConnectionId="X-ConnectionId",i.ContentType="Content-Type",i.CustomCommandsAppId="X-CommandsAppId",i.Path="Path",i.RequestId="X-RequestId",i.RequestStreamId="X-StreamId",i.RequestTimestamp="X-Timestamp",i.ContinuationToken="X-Continuation-Token",i.ContinuationAudioStreamOffset="X-Continuation-Audio-Streams-1-Offset"},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AuthInfo=void 0;t.AuthInfo=class{constructor(e,t){this.privHeaderName=e,this.privToken=t}get headerName(){return this.privHeaderName}get token(){return this.privToken}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CognitiveTokenAuthentication=void 0;const r=i(4),n=i(60),s=i(59);class o{constructor(e,t){if(!e)throw new r.ArgumentNullError("fetchCallback");if(!t)throw new r.ArgumentNullError("fetchOnExpiryCallback");this.privFetchCallback=e,this.privFetchOnExpiryCallback=t}fetch(e){return this.privFetchCallback(e).then((e=>new n.AuthInfo(s.HeaderNames.Authorization,void 0===e?void 0:o.privTokenPrefix+e)))}fetchOnExpiry(e){return this.privFetchOnExpiryCallback(e).then((e=>new n.AuthInfo(s.HeaderNames.Authorization,void 0===e?void 0:o.privTokenPrefix+e)))}}t.CognitiveTokenAuthentication=o,o.privTokenPrefix="Bearer "},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RecognitionEndedEvent=t.RecognitionCompletionStatus=t.RecognitionStartedEvent=t.ConnectingToServiceEvent=t.ListeningStartedEvent=t.RecognitionTriggeredEvent=t.SpeechRecognitionEvent=void 0;const r=i(4);class n extends r.PlatformEvent{constructor(e,t,i,n=r.EventType.Info){super(e,n),this.privRequestId=t,this.privSessionId=i}get requestId(){return this.privRequestId}get sessionId(){return this.privSessionId}}t.SpeechRecognitionEvent=n;t.RecognitionTriggeredEvent=class extends n{constructor(e,t,i,r){super("RecognitionTriggeredEvent",e,t),this.privAudioSourceId=i,this.privAudioNodeId=r}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}};t.ListeningStartedEvent=class extends n{constructor(e,t,i,r){super("ListeningStartedEvent",e,t),this.privAudioSourceId=i,this.privAudioNodeId=r}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}};t.ConnectingToServiceEvent=class extends n{constructor(e,t,i){super("ConnectingToServiceEvent",e,i),this.privAuthFetchEventid=t}get authFetchEventid(){return this.privAuthFetchEventid}};var s;t.RecognitionStartedEvent=class extends n{constructor(e,t,i,r,n){super("RecognitionStartedEvent",e,n),this.privAudioSourceId=t,this.privAudioNodeId=i,this.privAuthFetchEventId=r}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}get authFetchEventId(){return this.privAuthFetchEventId}},function(e){e[e.Success=0]="Success",e[e.AudioSourceError=1]="AudioSourceError",e[e.AudioSourceTimeout=2]="AudioSourceTimeout",e[e.AuthTokenFetchError=3]="AuthTokenFetchError",e[e.AuthTokenFetchTimeout=4]="AuthTokenFetchTimeout",e[e.UnAuthorized=5]="UnAuthorized",e[e.ConnectTimeout=6]="ConnectTimeout",e[e.ConnectError=7]="ConnectError",e[e.ClientRecognitionActivityTimeout=8]="ClientRecognitionActivityTimeout",e[e.UnknownError=9]="UnknownError"}(s=t.RecognitionCompletionStatus||(t.RecognitionCompletionStatus={}));t.RecognitionEndedEvent=class extends n{constructor(e,t,i,n,o,a,c,p){super("RecognitionEndedEvent",e,o,c===s.Success?r.EventType.Info:r.EventType.Error),this.privAudioSourceId=t,this.privAudioNodeId=i,this.privAuthFetchEventId=n,this.privStatus=c,this.privError=p,this.privServiceTag=a}get audioSourceId(){return this.privAudioSourceId}get audioNodeId(){return this.privAudioNodeId}get authFetchEventId(){return this.privAuthFetchEventId}get serviceTag(){return this.privServiceTag}get status(){return this.privStatus}get error(){return this.privError}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceRecognizerBase=void 0;const r=i(66),n=i(4),s=i(85),o=i(2),a=i(188),c=i(189),p=i(116),u=i(190),h=i(191),d=i(192),v=i(193),l=i(194),g=i(195),S=i(196),f=i(197),y=i(198),m=i(199),C=i(200),P=i(201);class R{constructor(e,t,i,r,a){if(this.privConnectionConfigurationPromise=void 0,this.privConnectionPromise=void 0,this.privSetTimeout=setTimeout,this.privIsLiveAudio=!1,this.privAverageBytesPerMs=0,this.privEnableReliableReconnect=!1,this.privEnableSpeakerId=!1,this.privExpectContentAssessmentResponse=!1,this.recognizeOverride=void 0,this.disconnectOverride=void 0,this.receiveMessageOverride=void 0,this.sendPrePayloadJSONOverride=void 0,this.postConnectImplOverride=void 0,this.configConnectionOverride=void 0,this.handleSpeechPhraseMessage=void 0,this.handleSpeechHypothesisMessage=void 0,!e)throw new n.ArgumentNullError("authentication");if(!t)throw new n.ArgumentNullError("connectionFactory");if(!i)throw new n.ArgumentNullError("audioSource");if(!r)throw new n.ArgumentNullError("recognizerConfig");this.privEnableSpeakerId=r.isSpeakerDiarizationEnabled,this.privMustReportEndOfStream=!1,this.privAuthentication=e,this.privConnectionFactory=t,this.privAudioSource=i,this.privRecognizerConfig=r,this.privIsDisposed=!1,this.privRecognizer=a,this.privRequestSession=new o.RequestSession(this.privAudioSource.id()),this.privConnectionEvents=new n.EventSource,this.privServiceEvents=new n.EventSource,this.privDynamicGrammar=new o.DynamicGrammarBuilder,this.privSpeechContext=new o.SpeechContext(this.privDynamicGrammar),this.privAgentConfig=new o.AgentConfig,this.privEnableReliableReconnect="true"===this.privRecognizerConfig.parameters.getProperty(s.PropertyId.Speech_EnableMultiChannelProcessing,"false").toLowerCase(),this.privContinuationState=new o.ReconnectContinuationState;"on"===this.privRecognizerConfig.parameters.getProperty(s.PropertyId.WebWorkerLoadType,"on").toLowerCase()&&"undefined"!=typeof Blob&&"undefined"!=typeof Worker?this.privSetTimeout=n.Timeout.setTimeout:("undefined"!=typeof window&&(this.privSetTimeout=window.setTimeout.bind(window)),"undefined"!=typeof globalThis&&(this.privSetTimeout=globalThis.setTimeout.bind(globalThis))),this.connectionEvents.attach((e=>{if("ConnectionClosedEvent"===e.name){const t=e;(1003===t.statusCode||1007===t.statusCode||1002===t.statusCode||4e3===t.statusCode||this.privRequestSession.numConnectionAttempts>this.privRecognizerConfig.maxRetryCount)&&this.cancelRecognitionLocal(s.CancellationReason.Error,1007===t.statusCode?s.CancellationErrorCode.BadRequestParameters:s.CancellationErrorCode.ConnectionFailure,`${t.reason} websocket error code: ${t.statusCode}`)}})),this.privEnableSpeakerId&&(this.privDiarizationSessionId=(0,n.createNoDashGuid)())}setTranslationJson(){const e=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0);if(void 0!==e){const t=e.split(","),i=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_TranslationVoice,void 0),r=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_TranslationCategoryId,void 0),n=void 0!==i?u.NextAction.Synthesize:u.NextAction.None;if(this.privSpeechContext.getContext().translation={onPassthrough:{action:n},onSuccess:{action:n},output:{includePassThroughResults:!0,interimResults:{mode:h.Mode.Always}},targetLanguages:t},void 0!==r&&(this.privSpeechContext.getContext().translation.category=r),void 0!==i){const e={};for(const r of t)e[r]=i;this.privSpeechContext.getContext().synthesis={defaultVoices:e}}const o=this.privSpeechContext.getContext().phraseDetection||{};o.onSuccess={action:f.NextAction.Translate},o.onInterim={action:f.NextAction.Translate},this.privSpeechContext.getContext().phraseDetection=o}}setSpeechSegmentationTimeoutJson(){const e=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.Speech_SegmentationSilenceTimeoutMs,void 0),t=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.Speech_SegmentationMaximumTimeMs,void 0),i=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.Speech_SegmentationStrategy,void 0),r={mode:c.SegmentationMode.Normal};let n=!1;if(void 0!==i){n=!0;let e=c.SegmentationMode.Normal;switch(i.toLowerCase()){case"default":break;case"time":e=c.SegmentationMode.Custom;break;case"semantic":e=c.SegmentationMode.Semantic}r.mode=e}if(void 0!==e){n=!0;const t=parseInt(e,10);r.mode=c.SegmentationMode.Custom,r.segmentationSilenceTimeoutMs=t}if(void 0!==t){n=!0;const e=parseInt(t,10);r.mode=c.SegmentationMode.Custom,r.segmentationForcedTimeoutMs=e}if(n){const e=this.privSpeechContext.getContext().phraseDetection||{};switch(e.mode=this.recognitionMode,this.recognitionMode){case p.RecognitionMode.Conversation:e.conversation=e.conversation??{segmentation:{}},e.conversation.segmentation=r;break;case p.RecognitionMode.Interactive:e.interactive=e.interactive??{segmentation:{}},e.interactive.segmentation=r;break;case p.RecognitionMode.Dictation:e.dictation=e.dictation??{},e.dictation.segmentation=r}this.privSpeechContext.getContext().phraseDetection=e}}setLanguageIdJson(){const e=this.privSpeechContext.getContext().phraseDetection||{};if(void 0!==this.privRecognizerConfig.autoDetectSourceLanguages){const t=this.privRecognizerConfig.autoDetectSourceLanguages.split(",");let i;1===t.length&&t[0]===o.AutoDetectSourceLanguagesOpenRangeOptionName&&(t[0]="UND"),i="Continuous"===this.privRecognizerConfig.languageIdMode?d.LanguageIdDetectionMode.DetectContinuous:d.LanguageIdDetectionMode.DetectAtAudioStart,this.privSpeechContext.getContext().languageId={languages:t,mode:i,onSuccess:{action:v.NextAction.Recognize},onUnknown:{action:l.OnUnknownAction.None},priority:d.LanguageIdDetectionPriority.PrioritizeLatency},this.privSpeechContext.getContext().phraseOutput={interimResults:{resultType:g.ResultType.Auto},phraseResults:{resultType:S.PhraseResultOutputType.Always}};const r=this.privRecognizerConfig.sourceLanguageModels;void 0!==r&&(e.customModels=r,e.onInterim={action:f.NextAction.None},e.onSuccess={action:f.NextAction.None})}this.privSpeechContext.getContext().phraseDetection=e}setOutputDetailLevelJson(){if("true"===this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,"false").toLowerCase())this.privSpeechContext.setWordLevelTimings();else{this.privRecognizerConfig.parameters.getProperty(o.OutputFormatPropertyName,s.OutputFormat[s.OutputFormat.Simple]).toLowerCase()===s.OutputFormat[s.OutputFormat.Detailed].toLocaleLowerCase()&&this.privSpeechContext.setDetailedOutputFormat()}}setSpeechStartEventSensitivityJson(){const e=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.Speech_StartEventSensitivity,void 0);if(void 0!==e){let t=!1;switch(e.toLowerCase()){case p.SpeechStartEventSensitivity.Low:case p.SpeechStartEventSensitivity.Medium:case p.SpeechStartEventSensitivity.High:t=!0}if(t){const t=this.privSpeechContext.getContext().phraseDetection||{};t.voiceOnsetSensitivity=e.toLowerCase(),this.privSpeechContext.getContext().phraseDetection=t}}}setPostProcessingOptionJson(){const e=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceResponse_PostProcessingOption,void 0),t=this.privSpeechContext.getContext().phraseDetection||{};t.enrichment=t.enrichment||{};const i=this.recognitionMode===p.RecognitionMode.Conversation?t.enrichment.conversation:this.recognitionMode===p.RecognitionMode.Interactive?t.enrichment.interactive:t.enrichment.dictation;if(i&&(delete i.postprocessingoption,delete i.punctuationMode,delete i.disfluencyMode,delete i.intermediatePunctuationMode,delete i.intermediatedisfluencymode),void 0!==e)if("truetext"===e.toLowerCase())switch(this.recognitionMode){case p.RecognitionMode.Conversation:t.enrichment.conversation=t.enrichment.conversation||{},t.enrichment.conversation.punctuationMode=m.ConversationPunctuationMode.Implicit,t.enrichment.conversation.disfluencyMode=P.DisfluencyMode.Removed,t.enrichment.conversation.intermediatePunctuationMode=m.ConversationPunctuationMode.Implicit,t.enrichment.conversation.intermediatedisfluencymode=P.DisfluencyMode.Removed;break;case p.RecognitionMode.Interactive:t.enrichment.interactive=t.enrichment.interactive||{},t.enrichment.interactive.punctuationMode=y.InteractivePunctuationMode.Implicit,t.enrichment.interactive.disfluencyMode=P.DisfluencyMode.Removed,t.enrichment.interactive.intermediatePunctuationMode=y.InteractivePunctuationMode.Implicit,t.enrichment.interactive.intermediatedisfluencymode=P.DisfluencyMode.Removed;break;case p.RecognitionMode.Dictation:t.enrichment.dictation=t.enrichment.dictation||{},t.enrichment.dictation.punctuationMode=C.DictationPunctuationMode.Implicit,t.enrichment.dictation.disfluencyMode=P.DisfluencyMode.Removed,t.enrichment.dictation.intermediatePunctuationMode=C.DictationPunctuationMode.Implicit,t.enrichment.dictation.intermediatedisfluencymode=P.DisfluencyMode.Removed}else switch(this.recognitionMode){case p.RecognitionMode.Conversation:t.enrichment.conversation=t.enrichment.conversation||{},t.enrichment.conversation.postprocessingoption=e;break;case p.RecognitionMode.Interactive:t.enrichment.interactive=t.enrichment.interactive||{},t.enrichment.interactive.postprocessingoption=e;break;case p.RecognitionMode.Dictation:t.enrichment.dictation=t.enrichment.dictation||{},t.enrichment.dictation.postprocessingoption=e}this.privSpeechContext.getContext().phraseDetection=t}setLanguageJson(){const e=this.privSpeechContext.getContext().phraseDetection||{};if(void 0!==this.privRecognizerConfig.autoDetectSourceLanguages)delete e.language;else{const t=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage,void 0);void 0!==t?e.language=t:delete e.language}this.privSpeechContext.getContext().phraseDetection=e}setInitialSilenceTimeoutJson(){const e=this.privSpeechContext.getContext().phraseDetection||{},t=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs,void 0);void 0!==t?e.initialSilenceTimeout=parseInt(t,10):delete e.initialSilenceTimeout,this.privSpeechContext.getContext().phraseDetection=e}setEndSilenceTimeoutJson(){const e=this.privSpeechContext.getContext().phraseDetection||{},t=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs,void 0);void 0!==t?e.trailingSilenceTimeout=parseInt(t,10):delete e.trailingSilenceTimeout,this.privSpeechContext.getContext().phraseDetection=e}setProfanityOptionJson(){const e=this.privSpeechContext.getContext().phraseDetection||{},t=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceResponse_ProfanityOption,void 0);void 0!==t?(e.enrichment=e.enrichment||{},e.enrichment.profanity=t):e.enrichment&&delete e.enrichment.profanity,this.privSpeechContext.getContext().phraseDetection=e}setStableIntermediateThresholdJson(){const e=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceResponse_StablePartialResultThreshold,void 0),t=this.privSpeechContext.getContext().phraseOutput||{};void 0!==e?(t.interimResults=t.interimResults||{},t.interimResults.stableThreshold=parseInt(e,10)):t.interimResults&&delete t.interimResults.stableThreshold,this.privSpeechContext.getContext().phraseOutput=t}get isSpeakerDiarizationEnabled(){return this.privEnableSpeakerId}get audioSource(){return this.privAudioSource}get speechContext(){return this.privSpeechContext}get dynamicGrammar(){return this.privDynamicGrammar}get agentConfig(){return this.privAgentConfig}set authentication(e){this.privAuthentication=e}isDisposed(){return this.privIsDisposed}async dispose(e){if(this.privIsDisposed=!0,void 0!==this.privConnectionPromise)try{const t=await this.privConnectionPromise;await t.dispose(e)}catch(e){return}}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}get recognitionMode(){return this.privRecognizerConfig.recognitionMode}async recognize(e,t,i){if(void 0!==this.recognizeOverride)return void await this.recognizeOverride(e,t,i);if(this.privConnectionConfigurationPromise=void 0,this.privRecognizerConfig.recognitionMode=e,"2"===this.privRecognizerConfig.recognitionEndpointVersion){const t=this.privSpeechContext.getContext().phraseDetection||{};t.mode=e,this.privSpeechContext.getContext().phraseDetection=t}this.setLanguageIdJson(),this.setTranslationJson(),void 0!==this.privRecognizerConfig.autoDetectSourceLanguages&&void 0!==this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0)&&this.setupTranslationWithLanguageId(),this.setLanguageJson(),this.setInitialSilenceTimeoutJson(),this.setEndSilenceTimeoutJson(),this.setSpeechSegmentationTimeoutJson(),this.setOutputDetailLevelJson(),this.setSpeechStartEventSensitivityJson(),this.setProfanityOptionJson(),this.setPostProcessingOptionJson(),this.setStableIntermediateThresholdJson(),this.privSuccessCallback=t,this.privErrorCallback=i,this.privRequestSession.startNewRecognition(),this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events),this.privEnableReliableReconnect&&this.privContinuationState.reset();const n=this.connectImpl();let a;try{const e=await this.audioSource.attach(this.privRequestSession.audioNodeId),t=await this.audioSource.format,i=await this.audioSource.deviceInfo;this.privIsLiveAudio=i.type&&i.type===o.type.Microphones,this.privEnableReliableReconnect&&(i.SeparateChannelProcessing="true"),a=new r.ReplayableAudioNode(e,t.avgBytesPerSec),await this.privRequestSession.onAudioSourceAttachCompleted(a,!1),this.privRecognizerConfig.SpeechServiceConfig.Context.audio={source:i}}catch(e){throw await this.privRequestSession.onStopRecognizing(),e}try{await n}catch(e){return void await this.cancelRecognitionLocal(s.CancellationReason.Error,s.CancellationErrorCode.ConnectionFailure,e)}const c=new s.SessionEventArgs(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,c),this.receiveMessage();this.sendAudio(a).catch((async e=>{await this.cancelRecognitionLocal(s.CancellationReason.Error,s.CancellationErrorCode.RuntimeError,e)}))}async stopRecognizing(){if(this.privRequestSession.isRecognizing)try{await this.audioSource.turnOff(),await this.sendFinalAudio(),await this.privRequestSession.onStopRecognizing(),await this.privRequestSession.turnCompletionPromise}finally{await this.privRequestSession.dispose()}}async connect(){return await this.connectImpl(),Promise.resolve()}connectAsync(e,t){this.connectImpl().then((()=>{try{e&&e()}catch(e){t&&t(e)}}),(e=>{try{t&&t(e)}catch(e){}}))}async disconnect(){if(await this.cancelRecognitionLocal(s.CancellationReason.Error,s.CancellationErrorCode.NoError,"Disconnecting"),void 0!==this.disconnectOverride&&await this.disconnectOverride(),void 0!==this.privConnectionPromise)try{await(await this.privConnectionPromise).dispose()}catch(e){}this.privConnectionPromise=void 0}sendMessage(e){}async sendNetworkMessage(e,t){const i="string"==typeof t?n.MessageType.Text:n.MessageType.Binary,r="string"==typeof t?"application/json":"";return(await this.fetchConnection()).send(new a.SpeechConnectionMessage(i,e,this.privRequestSession.requestId,r,t))}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}set expectContentAssessmentResponse(e){this.privExpectContentAssessmentResponse=e}async sendTelemetryData(){const e=this.privRequestSession.getTelemetry();if(!0!==R.telemetryDataEnabled||this.privIsDisposed||null===e)return;if(R.telemetryData)try{R.telemetryData(e)}catch{}const t=await this.fetchConnection();await t.send(new a.SpeechConnectionMessage(n.MessageType.Text,"telemetry",this.privRequestSession.requestId,"application/json",e))}async cancelRecognitionLocal(e,t,i){this.privRequestSession.isRecognizing&&(await this.privRequestSession.onStopRecognizing(),this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,e,t,i))}async receiveMessage(){try{if(this.privIsDisposed)return;let e=await this.fetchConnection();const t=await e.read();if(void 0!==this.receiveMessageOverride)return this.receiveMessageOverride();if(!t)return this.receiveMessage();this.privServiceHasSentMessage=!0;const i=a.SpeechConnectionMessage.fromConnectionMessage(t);if(i.requestId.toLowerCase()===this.privRequestSession.requestId.toLowerCase()){if(this.privEnableReliableReconnect){this.privContinuationState.updateFromHeaders(i.additionalHeaders,this.privRequestSession.currentTurnAudioOffset);const e=this.privContinuationState.streamOffset;void 0!==e&&this.privRequestSession.onServiceAcknowledgedAudio(e)}switch(i.path.toLowerCase()){case"turn.start":if(this.privMustReportEndOfStream=!0,this.privRequestSession.onServiceTurnStartResponse(),this.privEnableReliableReconnect){let e;try{if(i.textBody&&i.textBody.length>0){const t=JSON.parse(i.textBody);e=t?.context?.serviceTag}}catch{e=void 0}this.privContinuationState.onTurnStart(e)}break;case"speech.startdetected":const t=o.SpeechDetected.fromJSON(i.textBody,this.privRequestSession.currentTurnAudioOffset),r=new s.RecognitionEventArgs(t.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechStartDetected&&this.privRecognizer.speechStartDetected(this.privRecognizer,r);break;case"speech.enddetected":let a;a=i.textBody.length>0?i.textBody:"{ Offset: 0 }";const c=o.SpeechDetected.fromJSON(a,this.privRequestSession.currentTurnAudioOffset),p=new s.RecognitionEventArgs(c.Offset+this.privRequestSession.currentTurnAudioOffset,this.privRequestSession.sessionId);this.privRecognizer.speechEndDetected&&this.privRecognizer.speechEndDetected(this.privRecognizer,p);break;case"turn.end":await this.sendTelemetryData(),this.privRequestSession.isSpeechEnded&&this.privMustReportEndOfStream&&(this.privMustReportEndOfStream=!1,await this.cancelRecognitionLocal(s.CancellationReason.EndOfStream,s.CancellationErrorCode.NoError,void 0));const u=new s.SessionEventArgs(this.privRequestSession.sessionId);if(await this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition),!this.privRecognizerConfig.isContinuousRecognition||this.privRequestSession.isSpeechEnded||!this.privRequestSession.isRecognizing)return void(this.privRecognizer.sessionStopped&&this.privRecognizer.sessionStopped(this.privRecognizer,u));e=await this.fetchConnection(),await this.sendPrePayloadJSON(e);break;default:await this.processTypeSpecificMessages(i)||this.privServiceEvents&&this.serviceEvents.onEvent(new n.ServiceEvent(i.path.toLowerCase(),i.textBody))}}return this.receiveMessage()}catch(e){return null}}updateSpeakerDiarizationAudioOffset(){const e=this.privRequestSession.recognitionBytesSent,t=0!==this.privAverageBytesPerMs?e/this.privAverageBytesPerMs:0;this.privSpeechContext.setSpeakerDiarizationAudioOffsetMs(t)}get audioStreamId(){return this.privEnableReliableReconnect?this.privContinuationState.defaultStreamId:void 0}applyReconnectContinuation(){const e=this.privSpeechContext.getContext();e.audio=this.privContinuationState.buildAudioStreamsMetadata();const t=this.privContinuationState.buildContinuationContext();void 0!==t?e.continuation=t:delete e.continuation}sendSpeechContext(e,t){this.privEnableSpeakerId&&this.updateSpeakerDiarizationAudioOffset(),this.privEnableReliableReconnect&&this.applyReconnectContinuation();const i=this.speechContext.toJSON();if(t&&this.privRequestSession.onSpeechContext(),i)return e.send(new a.SpeechConnectionMessage(n.MessageType.Text,"speech.context",this.privRequestSession.requestId,"application/json",i))}setupTranslationWithLanguageId(){const e=this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0),t=void 0!==this.privRecognizerConfig.autoDetectSourceLanguages;if(void 0!==e&&t){this.privSpeechContext.getContext().phraseOutput={interimResults:{resultType:g.ResultType.None},phraseResults:{resultType:S.PhraseResultOutputType.None}};const e=this.privSpeechContext.getContext().translation;if(e){const t=this.privRecognizerConfig.sourceLanguageModels;if(void 0!==t&&t.length>0){const e=this.privSpeechContext.getContext().phraseDetection||{};e.customModels=t,this.privSpeechContext.getContext().phraseDetection=e}void 0!==this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_TranslationVoice,void 0)&&(e.onSuccess={action:u.NextAction.Synthesize},e.onPassthrough={action:u.NextAction.Synthesize})}}}noOp(){}async sendPrePayloadJSON(e,t=!0){if(void 0!==this.sendPrePayloadJSONOverride)return this.sendPrePayloadJSONOverride(e);await this.sendSpeechContext(e,t),await this.sendWaveHeader(e)}async sendWaveHeader(e){const t=await this.audioSource.format;return e.send(new a.SpeechConnectionMessage(n.MessageType.Binary,"audio",this.privRequestSession.requestId,"audio/x-wav",t.header,this.audioStreamId))}reconnect(){return void 0===this.privConnectionPromise||this.privServiceHasSentMessage?(this.privConnectionId=null,this.privConnectionPromise=void 0,this.privServiceHasSentMessage=!1,this.connectImpl()):this.privConnectionPromise}connectImpl(){return void 0!==this.privConnectionPromise?this.privConnectionPromise.then((e=>e.state()===n.ConnectionState.Disconnected?this.reconnect():this.privConnectionPromise),(()=>this.reconnect())):(this.privConnectionPromise=this.retryableConnect(),this.privConnectionPromise.catch((()=>{})),void 0!==this.postConnectImplOverride?this.postConnectImplOverride(this.privConnectionPromise):this.privConnectionPromise)}sendSpeechServiceConfig(e,t,i){if(t.onSpeechContext(),!0!==R.telemetryDataEnabled){const e={context:{system:JSON.parse(i).context.system}};i=JSON.stringify(e)}if("true"===this.privRecognizerConfig.parameters.getProperty("f0f5debc-f8c9-4892-ac4b-90a7ab359fd2","false").toLowerCase()){const e=JSON.parse(i);e.context.DisableReferenceChannel="True",e.context.MicSpec="1_0_0",i=JSON.stringify(e)}if(i)return e.send(new a.SpeechConnectionMessage(n.MessageType.Text,"speech.config",t.requestId,"application/json",i))}async fetchConnection(){return void 0!==this.privConnectionConfigurationPromise?this.privConnectionConfigurationPromise.then((e=>e.state()===n.ConnectionState.Disconnected?(this.privConnectionConfigurationPromise=void 0,this.fetchConnection()):this.privConnectionConfigurationPromise),(()=>(this.privConnectionConfigurationPromise=void 0,this.fetchConnection()))):(this.privConnectionConfigurationPromise=this.configureConnection(),await this.privConnectionConfigurationPromise)}async sendAudio(e){const t=await this.audioSource.format;this.privAverageBytesPerMs=t.avgBytesPerSec/1e3;let i=Date.now();const r=this.privRecognizerConfig.parameters.getProperty("SPEECH-TransmitLengthBeforThrottleMs","5000"),s=t.avgBytesPerSec/1e3*parseInt(r,10),o=this.privRequestSession.recogNumber,c=async()=>{if(!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===o){const r=await this.fetchConnection(),p=await e.read();if(this.privRequestSession.isSpeechEnded)return;let u,h;if(!p||p.isEnd?(u=null,h=0):(u=p.buffer,this.privRequestSession.onAudioSent(u.byteLength),h=s>=this.privRequestSession.bytesSent?0:Math.max(0,i-Date.now())),0!==h&&await this.delay(h),null!==u&&(i=Date.now()+1e3*u.byteLength/(2*t.avgBytesPerSec)),!this.privIsDisposed&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing&&this.privRequestSession.recogNumber===o){if(r.send(new a.SpeechConnectionMessage(n.MessageType.Binary,"audio",this.privRequestSession.requestId,null,u,this.audioStreamId)).catch((()=>{this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch((()=>{}))})),!p?.isEnd)return c();this.privIsLiveAudio||this.privRequestSession.onSpeechEnded()}}};return c()}async retryableConnect(){let e=!1;this.privAuthFetchEventId=(0,n.createNoDashGuid)();const t=this.privRequestSession.sessionId;this.privConnectionId=void 0!==t?t:(0,n.createNoDashGuid)(),this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId,this.privConnectionId);let i=0,r="";for(;this.privRequestSession.numConnectionAttempts<=this.privRecognizerConfig.maxRetryCount;){this.privRequestSession.onRetryConnection();const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId),n=await t;await this.privRequestSession.onAuthCompleted(!1);const s=await this.privConnectionFactory.create(this.privRecognizerConfig,n,this.privConnectionId);this.privRequestSession.listenForServiceTelemetry(s.events),s.events.attach((e=>{this.connectionEvents.onEvent(e)}));const o=await s.open();if(200===o.statusCode)return await this.privRequestSession.onConnectionEstablishCompleted(o.statusCode),Promise.resolve(s);1006===o.statusCode&&(e=!0),i=o.statusCode,r=o.reason}return await this.privRequestSession.onConnectionEstablishCompleted(i,r),Promise.reject(`Unable to contact server. StatusCode: ${i}, ${this.privRecognizerConfig.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Endpoint)} Reason: ${r}`)}delay(e){return new Promise((t=>this.privSetTimeout(t,e)))}writeBufferToConsole(e){let t="Buffer Size: ";if(null===e)t+="null";else{const i=new Uint8Array(e);t+=`${e.byteLength}\r\n`;for(let r=0;r=this.privLogLevelFilter){const t=this.toString(e);if(this.logCallback&&this.logCallback(t),this.privLogPath&&o.writeFileSync(this.privLogPath,t+"\n",{flag:"a+"}),this.privEnableConsoleOutput)switch(e.eventType){case a.LogLevel.Debug:console.debug(t);break;case a.LogLevel.Info:console.info(t);break;case a.LogLevel.Warning:console.warn(t);break;case a.LogLevel.Error:console.error(t);break;default:console.log(t)}}}toString(e){const t=[`${e.eventTime}`,`${e.name}`],i=e;for(const r in i)if(r&&e.hasOwnProperty(r)&&"eventTime"!==r&&"eventType"!==r&&"eventId"!==r&&"name"!==r&&"constructor"!==r){const e=i[r];let n="";null!=e&&(n="number"==typeof e||"string"==typeof e?e.toString():JSON.stringify(e)),t.push(`${r}: ${n}`)}return t.join(" | ")}}},()=>{},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;const r=i(4);Object.defineProperty(t,"LogLevel",{enumerable:!0,get:function(){return r.EventType}})},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Contracts=void 0;class i{static throwIfNullOrUndefined(e,t){if(null==e)throw new Error("throwIfNullOrUndefined:"+t)}static throwIfNull(e,t){if(null===e)throw new Error("throwIfNull:"+t)}static throwIfNullOrWhitespace(e,t){if(i.throwIfNullOrUndefined(e,t),(""+e).trim().length<1)throw new Error("throwIfNullOrWhitespace:"+t)}static throwIfNullOrTooLong(e,t,r){if(i.throwIfNullOrUndefined(e,t),(""+e).length>r)throw new Error("throwIfNullOrTooLong:"+t+" (more than "+r.toString()+" characters)")}static throwIfNullOrTooShort(e,t,r){if(i.throwIfNullOrUndefined(e,t),(""+e).lengthn)throw new Error("throwIfNumberOutOfRange:"+t+" (must be between "+r.toString()+" and "+n.toString()+")")}}t.Contracts=i},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MicAudioSource=t.AudioWorkletSourceURLPropertyName=void 0;const r=i(2),n=i(4),s=i(73);t.AudioWorkletSourceURLPropertyName="MICROPHONE-WorkletSourceUrl";class o{constructor(e,t,i,r){this.privRecorder=e,this.deviceId=t,this.privStreams={},this.privOutputChunkSize=o.AUDIOFORMAT.avgBytesPerSec/10,this.privId=i||(0,n.createNoDashGuid)(),this.privEvents=new n.EventSource,this.privMediaStream=r||null,this.privIsClosing=!1}get format(){return Promise.resolve(o.AUDIOFORMAT)}turnOn(){if(this.privInitializeDeferral)return this.privInitializeDeferral.promise;this.privInitializeDeferral=new n.Deferred;try{this.createAudioContext()}catch(e){if(e instanceof Error){const t=e;this.privInitializeDeferral.reject(t.name+": "+t.message)}else this.privInitializeDeferral.reject(e);return this.privInitializeDeferral.promise}const e=window.navigator;let t=e.getUserMedia||e.webkitGetUserMedia||e.mozGetUserMedia||e.msGetUserMedia;if(e.mediaDevices&&(t=(t,i,r)=>{e.mediaDevices.getUserMedia(t).then(i).catch(r)}),t){const e=()=>{this.onEvent(new n.AudioSourceInitializingEvent(this.privId)),this.privMediaStream&&this.privMediaStream.active?(this.onEvent(new n.AudioSourceReadyEvent(this.privId)),this.privInitializeDeferral.resolve()):t({audio:!this.deviceId||{deviceId:this.deviceId},video:!1},(e=>{this.privMediaStream=e,this.onEvent(new n.AudioSourceReadyEvent(this.privId)),this.privInitializeDeferral.resolve()}),(e=>{const t=`Error occurred during microphone initialization: ${e}`;this.privInitializeDeferral.reject(t),this.onEvent(new n.AudioSourceErrorEvent(this.privId,t))}))};"suspended"===this.privContext.state?this.privContext.resume().then(e).catch((e=>{this.privInitializeDeferral.reject(`Failed to initialize audio context: ${e}`)})):e()}else{const e="Browser does not support getUserMedia.";this.privInitializeDeferral.reject(e),this.onEvent(new n.AudioSourceErrorEvent(e,""))}return this.privInitializeDeferral.promise}id(){return this.privId}attach(e){return this.onEvent(new n.AudioStreamNodeAttachingEvent(this.privId,e)),this.listen(e).then((t=>(this.onEvent(new n.AudioStreamNodeAttachedEvent(this.privId,e)),{detach:async()=>(t.readEnded(),delete this.privStreams[e],this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)),this.turnOff()),id:()=>e,read:()=>t.read()})))}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)))}async turnOff(){for(const e in this.privStreams)if(e){const t=this.privStreams[e];t&&t.close()}this.onEvent(new n.AudioSourceOffEvent(this.privId)),this.privInitializeDeferral&&(await this.privInitializeDeferral,this.privInitializeDeferral=null),await this.destroyAudioContext()}get events(){return this.privEvents}get deviceInfo(){return this.getMicrophoneLabel().then((e=>({bitspersample:o.AUDIOFORMAT.bitsPerSample,channelcount:o.AUDIOFORMAT.channels,connectivity:r.connectivity.Unknown,manufacturer:"Speech SDK",model:e,samplerate:o.AUDIOFORMAT.samplesPerSec,type:r.type.Microphones})))}setProperty(e,i){if(e!==t.AudioWorkletSourceURLPropertyName)throw new Error("Property '"+e+"' is not supported on Microphone.");this.privRecorder.setWorkletUrl(i)}getMicrophoneLabel(){const e="microphone";if(void 0!==this.privMicrophoneLabel)return Promise.resolve(this.privMicrophoneLabel);if(void 0===this.privMediaStream||!this.privMediaStream.active)return Promise.resolve(e);this.privMicrophoneLabel=e;const t=this.privMediaStream.getTracks()[0].getSettings().deviceId;if(void 0===t)return Promise.resolve(this.privMicrophoneLabel);const i=new n.Deferred;return navigator.mediaDevices.enumerateDevices().then((e=>{for(const i of e)if(i.deviceId===t){this.privMicrophoneLabel=i.label;break}i.resolve(this.privMicrophoneLabel)}),(()=>i.resolve(this.privMicrophoneLabel))),i.promise}async listen(e){await this.turnOn();const t=new n.ChunkedArrayBufferStream(this.privOutputChunkSize,e);this.privStreams[e]=t;try{this.privRecorder.record(this.privContext,this.privMediaStream,t)}catch(t){throw this.onEvent(new n.AudioStreamNodeErrorEvent(this.privId,e,t)),t}return t}onEvent(e){this.privEvents.onEvent(e),n.Events.instance.onEvent(e)}createAudioContext(){this.privContext||(this.privContext=s.AudioStreamFormatImpl.getAudioContext(o.AUDIOFORMAT.samplesPerSec))}async destroyAudioContext(){if(!this.privContext)return;this.privRecorder.releaseMediaResources(this.privContext);let e=!1;"close"in this.privContext&&(e=!0),e?this.privIsClosing||(this.privIsClosing=!0,await this.privContext.close(),this.privContext=null,this.privIsClosing=!1):null!==this.privContext&&"running"===this.privContext.state&&await this.privContext.suspend()}}t.MicAudioSource=o,o.AUDIOFORMAT=s.AudioStreamFormat.getDefaultInputFormat()},(e,t)=>{"use strict";var i;Object.defineProperty(t,"__esModule",{value:!0}),t.AudioStreamFormatImpl=t.AudioStreamFormat=t.AudioFormatTag=void 0,function(e){e[e.PCM=1]="PCM",e[e.MuLaw=2]="MuLaw",e[e.Siren=3]="Siren",e[e.MP3=4]="MP3",e[e.SILKSkype=5]="SILKSkype",e[e.OGG_OPUS=6]="OGG_OPUS",e[e.WEBM_OPUS=7]="WEBM_OPUS",e[e.ALaw=8]="ALaw",e[e.FLAC=9]="FLAC",e[e.OPUS=10]="OPUS",e[e.AMR_WB=11]="AMR_WB",e[e.G722=12]="G722"}(i=t.AudioFormatTag||(t.AudioFormatTag={}));class r{static getDefaultInputFormat(){return n.getDefaultInputFormat()}static getWaveFormat(e,t,i,r){return new n(e,t,i,r)}static getWaveFormatPCM(e,t,i){return new n(e,t,i)}}t.AudioStreamFormat=r;class n extends r{constructor(e=16e3,t=16,r=1,n=i.PCM){super();let s=!0;switch(n){case i.PCM:this.formatTag=1;break;case i.ALaw:this.formatTag=6;break;case i.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 e=new DataView(this.privHeader);this.setString(e,0,"RIFF"),e.setUint32(4,0,!0),this.setString(e,8,"WAVEfmt "),e.setUint32(16,16,!0),e.setUint16(20,this.formatTag,!0),e.setUint16(22,this.channels,!0),e.setUint32(24,this.samplesPerSec,!0),e.setUint32(28,this.avgBytesPerSec,!0),e.setUint16(32,this.channels*(this.bitsPerSample/8),!0),e.setUint16(34,this.bitsPerSample,!0),this.setString(e,36,"data"),e.setUint32(40,0,!0)}}static getDefaultInputFormat(){return new n}static getAudioContext(e){const t=window.AudioContext||window.webkitAudioContext||!1;if(t)return void 0!==e&&navigator.mediaDevices.getSupportedConstraints().sampleRate?new t({sampleRate:e}):new t;throw new Error("Browser does not support Web Audio API (AudioContext is not available).")}close(){}get header(){return this.privHeader}setString(e,t,i){for(let r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileAudioSource=void 0;const r=i(2),n=i(4),s=i(73);t.FileAudioSource=class{constructor(e,t,i){this.privStreams={},this.privHeaderEnd=44,this.privId=i||(0,n.createNoDashGuid)(),this.privEvents=new n.EventSource,this.privSource=e,"undefined"!=typeof window&&"undefined"!=typeof Blob&&this.privSource instanceof Blob?this.privFilename=e.name:this.privFilename=t||"unknown.wav",this.privAudioFormatPromise=this.readHeader()}get format(){return this.privAudioFormatPromise}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 n.AudioSourceErrorEvent(e,"")),Promise.reject(e)}this.onEvent(new n.AudioSourceInitializingEvent(this.privId)),this.onEvent(new n.AudioSourceReadyEvent(this.privId))}id(){return this.privId}async attach(e){this.onEvent(new n.AudioStreamNodeAttachingEvent(this.privId,e));const t=await this.upload(e);return this.onEvent(new n.AudioStreamNodeAttachedEvent(this.privId,e)),Promise.resolve({detach:async()=>{t.readEnded(),delete this.privStreams[e],this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)),await this.turnOff()},id:()=>e,read:()=>t.read()})}detach(e){e&&this.privStreams[e]&&(this.privStreams[e].close(),delete this.privStreams[e],this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)))}turnOff(){for(const e in this.privStreams)if(e){const t=this.privStreams[e];t&&!t.isClosed&&t.close()}return this.onEvent(new n.AudioSourceOffEvent(this.privId)),Promise.resolve()}get events(){return this.privEvents}get deviceInfo(){return this.privAudioFormatPromise.then((e=>Promise.resolve({bitspersample:e.bitsPerSample,channelcount:e.channels,connectivity:r.connectivity.Unknown,manufacturer:"Speech SDK",model:"File",samplerate:e.samplesPerSec,type:r.type.File})))}readHeader(){const e=this.privSource.slice(0,4296),t=new n.Deferred,i=e=>{const i=new DataView(e),r=e=>String.fromCharCode(i.getUint8(e),i.getUint8(e+1),i.getUint8(e+2),i.getUint8(e+3));if("RIFF"!==r(0))return void t.reject("Invalid WAV header in file, RIFF was not found");if("WAVE"!==r(8)||"fmt "!==r(12))return void t.reject("Invalid WAV header in file, WAVEfmt was not found");const n=i.getInt32(16,!0),o=i.getUint16(22,!0),a=i.getUint32(24,!0),c=i.getUint16(34,!0);let p=36+Math.max(n-16,0);for(;"data"!==r(p);p+=2)if(p>4288)return void t.reject("Invalid WAV header in file, data block was not found");this.privHeaderEnd=p+8,t.resolve(s.AudioStreamFormat.getWaveFormatPCM(a,c,o))};if("undefined"!=typeof window&&"undefined"!=typeof Blob&&e instanceof Blob){const t=new FileReader;t.onload=e=>{const t=e.target.result;i(t)},t.readAsArrayBuffer(e)}else{const t=e;i(t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength))}return t.promise}async upload(e){const t=t=>{const i=`Error occurred while processing '${this.privFilename}'. ${t}`;throw this.onEvent(new n.AudioStreamNodeErrorEvent(this.privId,e,i)),new Error(i)};try{await this.turnOn();const i=await this.privAudioFormatPromise,r=new n.ChunkedArrayBufferStream(i.avgBytesPerSec/10,e);this.privStreams[e]=r;const s=this.privSource.slice(this.privHeaderEnd),o=e=>{r.isClosed||(r.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()}),r.close())};if("undefined"!=typeof window&&"undefined"!=typeof Blob&&s instanceof Blob){const e=new FileReader;e.onerror=e=>t(e.toString()),e.onload=e=>{const t=e.target.result;o(t)},e.readAsArrayBuffer(s)}else{const e=s;o(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}return r}catch(e){t(e)}}onEvent(e){this.privEvents.onEvent(e),n.Events.instance.onEvent(e)}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PcmRecorder=void 0;const r=i(4);t.PcmRecorder=class{constructor(e){this.privStopInputOnRelease=e}record(e,t,i){const n=new r.RiffPcmEncoder(e.sampleRate,16e3),s=e.createMediaStreamSource(t),o=()=>{const r=(()=>{let t=0;try{return e.createScriptProcessor(t,1,1)}catch(i){t=2048;let r=e.sampleRate;for(;t<16384&&r>=32e3;)t<<=1,r>>=1;return e.createScriptProcessor(t,1,1)}})();r.onaudioprocess=e=>{const t=e.inputBuffer.getChannelData(0);if(i&&!i.isClosed){const e=n.encode(t);e&&i.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}},s.connect(r),r.connect(e.destination),this.privMediaResources={scriptProcessorNode:r,source:s,stream:t}},a=!!this.privSpeechProcessorScript&&"ignore"===this.privSpeechProcessorScript.toLowerCase();if(e.audioWorklet&&!a){if(!this.privSpeechProcessorScript){const e=new Blob(["class SP extends AudioWorkletProcessor {\n constructor(options) {\n super(options);\n }\n process(inputs, outputs) {\n const input = inputs[0];\n const output = [];\n for (let channel = 0; channel < input.length; channel += 1) {\n output[channel] = input[channel];\n }\n this.port.postMessage(output[0]);\n return true;\n }\n }\n registerProcessor('speech-processor', SP);"],{type:"application/javascript; charset=utf-8"});this.privSpeechProcessorScript=URL.createObjectURL(e)}e.audioWorklet.addModule(this.privSpeechProcessorScript).then((()=>{const r=new AudioWorkletNode(e,"speech-processor");r.port.onmessage=e=>{const t=e.data;if(i&&!i.isClosed){const e=n.encode(t);e&&i.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}},s.connect(r),r.connect(e.destination),this.privMediaResources={scriptProcessorNode:r,source:s,stream:t}})).catch((()=>{o()}))}else try{o()}catch(e){throw new Error(`Unable to start audio worklet node for PCMRecorder: ${e}`)}}releaseMediaResources(e){this.privMediaResources&&(this.privMediaResources.scriptProcessorNode&&(this.privMediaResources.scriptProcessorNode.disconnect(e.destination),this.privMediaResources.scriptProcessorNode=null),this.privMediaResources.source&&(this.privMediaResources.source.disconnect(),this.privStopInputOnRelease&&this.privMediaResources.stream.getTracks().forEach((e=>e.stop())),this.privMediaResources.source=null))}setWorkletUrl(e){this.privSpeechProcessorScript=e}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebsocketConnection=void 0;const r=i(4),n=i(77);t.WebsocketConnection=class{constructor(e,t,i,s,o,a=!1,c){if(this.privIsDisposed=!1,!e)throw new r.ArgumentNullError("uri");if(!s)throw new r.ArgumentNullError("messageFormatter");this.privMessageFormatter=s;let p="",u=0;if(t)for(const i in t)if(i){p+=0===u&&-1===e.indexOf("?")?"?":"&";p+=encodeURIComponent(i);let r=t[i];r&&(r=encodeURIComponent(r),p+=`=${r}`),u++}if(i)for(const t in i)if(t){p+=0===u&&-1===e.indexOf("?")?"?":"&";p+=`${t}=${encodeURIComponent(i[t])}`,u++}this.privUri=e+p,this.privId=c||(0,r.createNoDashGuid)(),this.privConnectionMessageAdapter=new n.WebsocketMessageAdapter(this.privUri,this.id,this.privMessageFormatter,o,i,a)}async dispose(){this.privIsDisposed=!0,this.privConnectionMessageAdapter&&await this.privConnectionMessageAdapter.close()}isDisposed(){return this.privIsDisposed}get id(){return this.privId}get uri(){return this.privUri}state(){return this.privConnectionMessageAdapter.state}open(){return this.privConnectionMessageAdapter.open()}send(e){return this.privConnectionMessageAdapter.send(e)}read(){return this.privConnectionMessageAdapter.read()}get events(){return this.privConnectionMessageAdapter.events}}},function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebsocketMessageAdapter=void 0;const a=s(i(78)),c=s(i(79)),p=o(i(80)),u=o(i(81)),h=o(i(82)),d=i(59),v=i(4);class l{constructor(e,t,i,r,n,s){if(!e)throw new v.ArgumentNullError("uri");if(!i)throw new v.ArgumentNullError("messageFormatter");this.proxyInfo=r,this.privConnectionEvents=new v.EventSource,this.privConnectionId=t,this.privMessageFormatter=i,this.privConnectionState=v.ConnectionState.None,this.privUri=e,this.privHeaders=n,this.privEnableCompression=s,this.privHeaders[d.HeaderNames.ConnectionId]=this.privConnectionId,this.privHeaders.connectionId=this.privConnectionId,this.privLastErrorReceived=""}get state(){return this.privConnectionState}open(){if(this.privConnectionState===v.ConnectionState.Disconnected)return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);if(this.privConnectionEstablishDeferral)return this.privConnectionEstablishDeferral.promise;this.privConnectionEstablishDeferral=new v.Deferred,this.privCertificateValidatedDeferral=new v.Deferred,this.privConnectionState=v.ConnectionState.Connecting;try{const e="undefined"==typeof window&&!!this.proxyInfo?.HostName;if("undefined"==typeof WebSocket||l.forceNpmWebSocket||e){let e=new URL(this.privUri).protocol;"wss:"===e?.toLocaleLowerCase()?e="https:":"ws:"===e?.toLocaleLowerCase()&&(e="http:");const t={headers:this.privHeaders,perMessageDeflate:this.privEnableCompression,followRedirects:"https:"===e.toLocaleLowerCase()};this.privCertificateValidatedDeferral.resolve(),t.agent=this.getAgent(),t.agent.protocol=e,this.privWebsocketClient=new h.default(this.privUri,t),this.privWebsocketClient.on("redirect",(e=>{const t=new v.ConnectionRedirectEvent(this.privConnectionId,e,this.privUri,`Getting redirect URL from endpoint ${this.privUri} with redirect URL '${e}'`);v.Events.instance.onEvent(t)}))}else this.privCertificateValidatedDeferral.resolve(),this.privWebsocketClient=new WebSocket(this.privUri);this.privWebsocketClient.binaryType="arraybuffer",this.privReceivingMessageQueue=new v.Queue,this.privDisconnectDeferral=new v.Deferred,this.privSendMessageQueue=new v.Queue,this.processSendQueue().catch((e=>{v.Events.instance.onEvent(new v.BackgroundEvent(e))}))}catch(e){return this.privConnectionEstablishDeferral.resolve(new v.ConnectionOpenResponse(500,e)),this.privConnectionEstablishDeferral.promise}return this.onEvent(new v.ConnectionStartEvent(this.privConnectionId,this.privUri)),this.privWebsocketClient.onopen=()=>{this.privCertificateValidatedDeferral.promise.then((()=>{this.privConnectionState=v.ConnectionState.Connected,this.onEvent(new v.ConnectionEstablishedEvent(this.privConnectionId)),this.privConnectionEstablishDeferral.resolve(new v.ConnectionOpenResponse(200,""))}),(e=>{this.privConnectionEstablishDeferral.reject(e)}))},this.privWebsocketClient.onerror=e=>{this.onEvent(new v.ConnectionErrorEvent(this.privConnectionId,e.message,e.type)),this.privLastErrorReceived=e.message},this.privWebsocketClient.onclose=e=>{this.privConnectionState===v.ConnectionState.Connecting?(this.privConnectionState=v.ConnectionState.Disconnected,this.privConnectionEstablishDeferral.resolve(new v.ConnectionOpenResponse(e.code,e.reason+" "+this.privLastErrorReceived))):(this.privConnectionState=v.ConnectionState.Disconnected,this.privWebsocketClient=null,this.onEvent(new v.ConnectionClosedEvent(this.privConnectionId,e.code,e.reason))),this.onClose(e.code,e.reason).catch((e=>{v.Events.instance.onEvent(new v.BackgroundEvent(e))}))},this.privWebsocketClient.onmessage=e=>{const t=(new Date).toISOString();if(this.privConnectionState===v.ConnectionState.Connected){const i=new v.Deferred;if(this.privReceivingMessageQueue.enqueueFromPromise(i.promise),e.data instanceof ArrayBuffer){const r=new v.RawWebsocketMessage(v.MessageType.Binary,e.data);this.privMessageFormatter.toConnectionMessage(r).then((e=>{this.onEvent(new v.ConnectionMessageReceivedEvent(this.privConnectionId,t,e)),i.resolve(e)}),(e=>{i.reject(`Invalid binary message format. Error: ${e}`)}))}else{const r=new v.RawWebsocketMessage(v.MessageType.Text,e.data);this.privMessageFormatter.toConnectionMessage(r).then((e=>{this.onEvent(new v.ConnectionMessageReceivedEvent(this.privConnectionId,t,e)),i.resolve(e)}),(e=>{i.reject(`Invalid text message format. Error: ${e}`)}))}}},this.privConnectionEstablishDeferral.promise}send(e){if(this.privConnectionState!==v.ConnectionState.Connected)return Promise.reject(`Cannot send on connection that is in ${v.ConnectionState[this.privConnectionState]} state`);const t=new v.Deferred,i=new v.Deferred;return this.privSendMessageQueue.enqueueFromPromise(i.promise),this.privMessageFormatter.fromConnectionMessage(e).then((r=>{i.resolve({Message:e,RawWebsocketMessage:r,sendStatusDeferral:t})}),(e=>{i.reject(`Error formatting the message. ${e}`)})),t.promise}read(){return this.privConnectionState!==v.ConnectionState.Connected?Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`):this.privReceivingMessageQueue.dequeue()}close(e){return this.privWebsocketClient?(this.privConnectionState!==v.ConnectionState.Disconnected&&this.privWebsocketClient.close(1e3,e||"Normal closure by client"),this.privDisconnectDeferral.promise):Promise.resolve()}get events(){return this.privConnectionEvents}sendRawMessage(e){try{return e?(this.onEvent(new v.ConnectionMessageSentEvent(this.privConnectionId,(new Date).toISOString(),e.Message)),this.isWebsocketOpen?(this.privWebsocketClient.send(e.RawWebsocketMessage.payload),Promise.resolve()):Promise.reject("websocket send error: Websocket not ready "+this.privConnectionId+" "+e.Message.id+" "+(new Error).stack)):Promise.resolve()}catch(e){return Promise.reject(`websocket send error: ${e}`)}}async onClose(e,t){const i=`Connection closed. ${e}: ${t}`;this.privConnectionState=v.ConnectionState.Disconnected,this.privDisconnectDeferral.resolve(),await this.privReceivingMessageQueue.drainAndDispose((()=>{}),i),await this.privSendMessageQueue.drainAndDispose((e=>{e.sendStatusDeferral.reject(i)}),i)}async processSendQueue(){for(;;){const e=this.privSendMessageQueue.dequeue(),t=await e;if(!t)return;try{await this.sendRawMessage(t),t.sendStatusDeferral.resolve()}catch(e){t.sendStatusDeferral.reject(e)}}}onEvent(e){this.privConnectionEvents.onEvent(e),v.Events.instance.onEvent(e)}getAgent(){const e=new p.default.Agent(this.createConnection);return void 0!==this.proxyInfo&&void 0!==this.proxyInfo.HostName&&this.proxyInfo.Port>0&&(e.proxyInfo=this.proxyInfo),e}static GetProxyAgent(e){const t={host:e.HostName,port:e.Port};e.UserName?t.headers={"Proxy-Authentication":"Basic "+Buffer.from(`${e.UserName}:${void 0===e.Password?"":e.Password}`).toString("base64")}:t.headers={},t.headers.requestOCSP="true";return new u.default(t)}createConnection(e,t){let i;if(t={...t,requestOCSP:!0,servername:t.host},this.proxyInfo){const r=l.GetProxyAgent(this.proxyInfo);i=new Promise(((i,n)=>{r.callback(e,t,((e,t)=>{e?n(e):i(t)}))}))}else i=t.secureEndpoint?Promise.resolve(c.connect(t)):Promise.resolve(a.connect(t));return i}get isWebsocketOpen(){return this.privWebsocketClient&&this.privWebsocketClient.readyState===this.privWebsocketClient.OPEN}}t.WebsocketMessageAdapter=l,l.forceNpmWebSocket=!1},()=>{},()=>{},()=>{},()=>{},()=>{},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReplayableAudioNode=void 0;t.ReplayableAudioNode=class{constructor(e,t){this.privBuffers=[],this.privReplayOffset=0,this.privLastShrinkOffset=0,this.privBufferStartOffset=0,this.privBufferSerial=0,this.privBufferedBytes=0,this.privReplay=!1,this.privLastChunkAcquiredTime=0,this.privAudioNode=e,this.privBytesPerSecond=t}id(){return this.privAudioNode.id()}read(){if(this.privReplay&&0!==this.privBuffers.length){const e=this.privReplayOffset-this.privBufferStartOffset;let t=Math.round(e*this.privBytesPerSecond*1e-7);0!=t%2&&t++;let i=0;for(;i=this.privBuffers[i].chunk.buffer.byteLength;)t-=this.privBuffers[i++].chunk.buffer.byteLength;if(i(e&&e.buffer&&this.privBuffers&&(this.privBuffers.push(new i(e,this.privBufferSerial++,this.privBufferedBytes)),this.privBufferedBytes+=e.buffer.byteLength),e)))}detach(){return this.privBuffers=void 0,this.privAudioNode.detach()}replay(){this.privBuffers&&0!==this.privBuffers.length&&(this.privReplay=!0,this.privReplayOffset=this.privLastShrinkOffset)}shrinkBuffers(e){if(void 0===this.privBuffers||0===this.privBuffers.length)return;if(e<=this.privLastShrinkOffset)return;this.privLastShrinkOffset=e;const t=e-this.privBufferStartOffset;let i=Math.round(t*this.privBytesPerSecond*1e-7),r=0;for(;r=this.privBuffers[r].chunk.buffer.byteLength;)i-=this.privBuffers[r++].chunk.buffer.byteLength;this.privBufferStartOffset=Math.round(e-i/this.privBytesPerSecond*1e7),this.privBuffers=this.privBuffers.slice(r)}findTimeAtOffset(e){if(e=i&&e<=r)return t.chunk.timeReceived}return 0}};class i{constructor(e,t,i){this.chunk=e,this.serial=t,this.byteOffset=i}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyInfo=void 0;const r=i(85);class n{constructor(e,t,i,r){this.privProxyHostName=e,this.privProxyPort=t,this.privProxyUserName=i,this.privProxyPassword=r}static fromParameters(e){return new n(e.getProperty(r.PropertyId.SpeechServiceConnection_ProxyHostName),parseInt(e.getProperty(r.PropertyId.SpeechServiceConnection_ProxyPort),10),e.getProperty(r.PropertyId.SpeechServiceConnection_ProxyUserName),e.getProperty(r.PropertyId.SpeechServiceConnection_ProxyPassword))}static fromRecognizerConfig(e){return this.fromParameters(e.parameters)}get HostName(){return this.privProxyHostName}get Port(){return this.privProxyPort}get UserName(){return this.privProxyUserName}get Password(){return this.privProxyPassword}}t.ProxyInfo=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CustomCommandsConfig=t.BotFrameworkConfig=t.DialogServiceConfig=t.PhraseListGrammar=t.Connection=t.ServiceEventArgs=t.ConnectionEventArgs=t.CancellationErrorCode=t.CancellationDetails=t.CancellationDetailsBase=t.TranslationRecognitionCanceledEventArgs=t.NoMatchDetails=t.NoMatchReason=t.Translations=t.TranslationRecognizer=t.SpeechRecognizer=t.Recognizer=t.PropertyId=t.PropertyCollection=t.SpeechTranslationConfigImpl=t.SpeechTranslationConfig=t.SpeechConfigImpl=t.SpeechConfig=t.ResultReason=t.TranslationSynthesisResult=t.TranslationRecognitionResult=t.TranslationSynthesisEventArgs=t.TranslationRecognitionEventArgs=t.SpeechRecognitionCanceledEventArgs=t.MeetingTranscriptionEventArgs=t.ConversationTranscriptionEventArgs=t.SpeechRecognitionEventArgs=t.SpeechRecognitionResult=t.RecognitionResult=t.OutputFormat=t.RecognitionEventArgs=t.SessionEventArgs=t.KeywordRecognitionModel=t.PushAudioOutputStreamCallback=t.PullAudioInputStreamCallback=t.CancellationReason=t.PushAudioOutputStream=t.PullAudioOutputStream=t.AudioOutputStream=t.PushAudioInputStream=t.PullAudioInputStream=t.AudioInputStream=t.AudioFormatTag=t.AudioStreamFormat=t.AudioConfig=void 0,t.Diagnostics=t.AvatarWebRTCConnectionResult=t.Coordinate=t.AvatarVideoFormat=t.AvatarSynthesizer=t.AvatarSceneConfig=t.AvatarEventArgs=t.AvatarConfig=t.LanguageIdMode=t.PronunciationAssessmentResult=t.PronunciationAssessmentConfig=t.PronunciationAssessmentGranularity=t.PronunciationAssessmentGradingSystem=t.MeetingTranscriptionCanceledEventArgs=t.ConversationTranscriptionCanceledEventArgs=t.SpeakerAudioDestination=t.VoiceInfo=t.SynthesisVoiceType=t.SynthesisVoiceGender=t.SynthesisVoicesResult=t.SpeechSynthesisRequestInputType=t.SpeechSynthesisRequestInputStream=t.SpeechSynthesisRequest=t.SpeechSynthesisBoundaryType=t.SpeechSynthesisVisemeEventArgs=t.SpeechSynthesisBookmarkEventArgs=t.SpeechSynthesisWordBoundaryEventArgs=t.SpeechSynthesisEventArgs=t.SpeechSynthesisResult=t.SynthesisResult=t.SpeechSynthesizer=t.SpeechSynthesisOutputFormat=t.Synthesizer=t.User=t.Participant=t.MeetingTranscriber=t.Meeting=t.ConversationTranscriptionResult=t.ConversationTranscriber=t.SourceLanguageConfig=t.AutoDetectSourceLanguageResult=t.AutoDetectSourceLanguageConfig=t.ConnectionMessage=t.ConnectionMessageEventArgs=t.BaseAudioPlayer=t.ProfanityOption=t.ServicePropertyChannel=t.TurnStatusReceivedEventArgs=t.ActivityReceivedEventArgs=t.DialogServiceConnector=void 0,t.LogLevel=void 0;var r=i(86);Object.defineProperty(t,"AudioConfig",{enumerable:!0,get:function(){return r.AudioConfig}});var n=i(73);Object.defineProperty(t,"AudioStreamFormat",{enumerable:!0,get:function(){return n.AudioStreamFormat}}),Object.defineProperty(t,"AudioFormatTag",{enumerable:!0,get:function(){return n.AudioFormatTag}});var s=i(89);Object.defineProperty(t,"AudioInputStream",{enumerable:!0,get:function(){return s.AudioInputStream}}),Object.defineProperty(t,"PullAudioInputStream",{enumerable:!0,get:function(){return s.PullAudioInputStream}}),Object.defineProperty(t,"PushAudioInputStream",{enumerable:!0,get:function(){return s.PushAudioInputStream}});var o=i(90);Object.defineProperty(t,"AudioOutputStream",{enumerable:!0,get:function(){return o.AudioOutputStream}}),Object.defineProperty(t,"PullAudioOutputStream",{enumerable:!0,get:function(){return o.PullAudioOutputStream}}),Object.defineProperty(t,"PushAudioOutputStream",{enumerable:!0,get:function(){return o.PushAudioOutputStream}});var a=i(93);Object.defineProperty(t,"CancellationReason",{enumerable:!0,get:function(){return a.CancellationReason}});var c=i(94);Object.defineProperty(t,"PullAudioInputStreamCallback",{enumerable:!0,get:function(){return c.PullAudioInputStreamCallback}});var p=i(95);Object.defineProperty(t,"PushAudioOutputStreamCallback",{enumerable:!0,get:function(){return p.PushAudioOutputStreamCallback}});var u=i(96);Object.defineProperty(t,"KeywordRecognitionModel",{enumerable:!0,get:function(){return u.KeywordRecognitionModel}});var h=i(97);Object.defineProperty(t,"SessionEventArgs",{enumerable:!0,get:function(){return h.SessionEventArgs}});var d=i(98);Object.defineProperty(t,"RecognitionEventArgs",{enumerable:!0,get:function(){return d.RecognitionEventArgs}});var v=i(99);Object.defineProperty(t,"OutputFormat",{enumerable:!0,get:function(){return v.OutputFormat}});var l=i(100);Object.defineProperty(t,"RecognitionResult",{enumerable:!0,get:function(){return l.RecognitionResult}});var g=i(101);Object.defineProperty(t,"SpeechRecognitionResult",{enumerable:!0,get:function(){return g.SpeechRecognitionResult}});var S=i(102);Object.defineProperty(t,"SpeechRecognitionEventArgs",{enumerable:!0,get:function(){return S.SpeechRecognitionEventArgs}}),Object.defineProperty(t,"ConversationTranscriptionEventArgs",{enumerable:!0,get:function(){return S.ConversationTranscriptionEventArgs}}),Object.defineProperty(t,"MeetingTranscriptionEventArgs",{enumerable:!0,get:function(){return S.MeetingTranscriptionEventArgs}});var f=i(103);Object.defineProperty(t,"SpeechRecognitionCanceledEventArgs",{enumerable:!0,get:function(){return f.SpeechRecognitionCanceledEventArgs}});var y=i(105);Object.defineProperty(t,"TranslationRecognitionEventArgs",{enumerable:!0,get:function(){return y.TranslationRecognitionEventArgs}});var m=i(106);Object.defineProperty(t,"TranslationSynthesisEventArgs",{enumerable:!0,get:function(){return m.TranslationSynthesisEventArgs}});var C=i(107);Object.defineProperty(t,"TranslationRecognitionResult",{enumerable:!0,get:function(){return C.TranslationRecognitionResult}});var P=i(108);Object.defineProperty(t,"TranslationSynthesisResult",{enumerable:!0,get:function(){return P.TranslationSynthesisResult}});var R=i(109);Object.defineProperty(t,"ResultReason",{enumerable:!0,get:function(){return R.ResultReason}});var I=i(110);Object.defineProperty(t,"SpeechConfig",{enumerable:!0,get:function(){return I.SpeechConfig}}),Object.defineProperty(t,"SpeechConfigImpl",{enumerable:!0,get:function(){return I.SpeechConfigImpl}});var w=i(111);Object.defineProperty(t,"SpeechTranslationConfig",{enumerable:!0,get:function(){return w.SpeechTranslationConfig}}),Object.defineProperty(t,"SpeechTranslationConfigImpl",{enumerable:!0,get:function(){return w.SpeechTranslationConfigImpl}});var b=i(112);Object.defineProperty(t,"PropertyCollection",{enumerable:!0,get:function(){return b.PropertyCollection}});var A=i(113);Object.defineProperty(t,"PropertyId",{enumerable:!0,get:function(){return A.PropertyId}});var T=i(114);Object.defineProperty(t,"Recognizer",{enumerable:!0,get:function(){return T.Recognizer}});var E=i(115);Object.defineProperty(t,"SpeechRecognizer",{enumerable:!0,get:function(){return E.SpeechRecognizer}});var O=i(117);Object.defineProperty(t,"TranslationRecognizer",{enumerable:!0,get:function(){return O.TranslationRecognizer}});var M=i(120);Object.defineProperty(t,"Translations",{enumerable:!0,get:function(){return M.Translations}});var D=i(121);Object.defineProperty(t,"NoMatchReason",{enumerable:!0,get:function(){return D.NoMatchReason}});var _=i(122);Object.defineProperty(t,"NoMatchDetails",{enumerable:!0,get:function(){return _.NoMatchDetails}});var N=i(123);Object.defineProperty(t,"TranslationRecognitionCanceledEventArgs",{enumerable:!0,get:function(){return N.TranslationRecognitionCanceledEventArgs}});var k=i(124);Object.defineProperty(t,"CancellationDetailsBase",{enumerable:!0,get:function(){return k.CancellationDetailsBase}});var z=i(125);Object.defineProperty(t,"CancellationDetails",{enumerable:!0,get:function(){return z.CancellationDetails}});var L=i(126);Object.defineProperty(t,"CancellationErrorCode",{enumerable:!0,get:function(){return L.CancellationErrorCode}});var x=i(127);Object.defineProperty(t,"ConnectionEventArgs",{enumerable:!0,get:function(){return x.ConnectionEventArgs}});var B=i(128);Object.defineProperty(t,"ServiceEventArgs",{enumerable:!0,get:function(){return B.ServiceEventArgs}});var F=i(118);Object.defineProperty(t,"Connection",{enumerable:!0,get:function(){return F.Connection}});var j=i(129);Object.defineProperty(t,"PhraseListGrammar",{enumerable:!0,get:function(){return j.PhraseListGrammar}});var q=i(130);Object.defineProperty(t,"DialogServiceConfig",{enumerable:!0,get:function(){return q.DialogServiceConfig}});var U=i(131);Object.defineProperty(t,"BotFrameworkConfig",{enumerable:!0,get:function(){return U.BotFrameworkConfig}});var W=i(132);Object.defineProperty(t,"CustomCommandsConfig",{enumerable:!0,get:function(){return W.CustomCommandsConfig}});var H=i(133);Object.defineProperty(t,"DialogServiceConnector",{enumerable:!0,get:function(){return H.DialogServiceConnector}});var K=i(137);Object.defineProperty(t,"ActivityReceivedEventArgs",{enumerable:!0,get:function(){return K.ActivityReceivedEventArgs}});var V=i(138);Object.defineProperty(t,"TurnStatusReceivedEventArgs",{enumerable:!0,get:function(){return V.TurnStatusReceivedEventArgs}});var J=i(140);Object.defineProperty(t,"ServicePropertyChannel",{enumerable:!0,get:function(){return J.ServicePropertyChannel}});var G=i(141);Object.defineProperty(t,"ProfanityOption",{enumerable:!0,get:function(){return G.ProfanityOption}});var $=i(142);Object.defineProperty(t,"BaseAudioPlayer",{enumerable:!0,get:function(){return $.BaseAudioPlayer}});var Q=i(143);Object.defineProperty(t,"ConnectionMessageEventArgs",{enumerable:!0,get:function(){return Q.ConnectionMessageEventArgs}});var X=i(119);Object.defineProperty(t,"ConnectionMessage",{enumerable:!0,get:function(){return X.ConnectionMessage}});var Z=i(144);Object.defineProperty(t,"AutoDetectSourceLanguageConfig",{enumerable:!0,get:function(){return Z.AutoDetectSourceLanguageConfig}});var Y=i(146);Object.defineProperty(t,"AutoDetectSourceLanguageResult",{enumerable:!0,get:function(){return Y.AutoDetectSourceLanguageResult}});var ee=i(147);Object.defineProperty(t,"SourceLanguageConfig",{enumerable:!0,get:function(){return ee.SourceLanguageConfig}});var te=i(148);Object.defineProperty(t,"ConversationTranscriber",{enumerable:!0,get:function(){return te.ConversationTranscriber}}),Object.defineProperty(t,"ConversationTranscriptionResult",{enumerable:!0,get:function(){return te.ConversationTranscriptionResult}}),Object.defineProperty(t,"Meeting",{enumerable:!0,get:function(){return te.Meeting}}),Object.defineProperty(t,"MeetingTranscriber",{enumerable:!0,get:function(){return te.MeetingTranscriber}}),Object.defineProperty(t,"Participant",{enumerable:!0,get:function(){return te.Participant}}),Object.defineProperty(t,"User",{enumerable:!0,get:function(){return te.User}});var ie=i(155);Object.defineProperty(t,"Synthesizer",{enumerable:!0,get:function(){return ie.Synthesizer}});var re=i(92);Object.defineProperty(t,"SpeechSynthesisOutputFormat",{enumerable:!0,get:function(){return re.SpeechSynthesisOutputFormat}});var ne=i(156);Object.defineProperty(t,"SpeechSynthesizer",{enumerable:!0,get:function(){return ne.SpeechSynthesizer}});var se=i(157);Object.defineProperty(t,"SynthesisResult",{enumerable:!0,get:function(){return se.SynthesisResult}});var oe=i(158);Object.defineProperty(t,"SpeechSynthesisResult",{enumerable:!0,get:function(){return oe.SpeechSynthesisResult}});var ae=i(159);Object.defineProperty(t,"SpeechSynthesisEventArgs",{enumerable:!0,get:function(){return ae.SpeechSynthesisEventArgs}});var ce=i(160);Object.defineProperty(t,"SpeechSynthesisWordBoundaryEventArgs",{enumerable:!0,get:function(){return ce.SpeechSynthesisWordBoundaryEventArgs}});var pe=i(161);Object.defineProperty(t,"SpeechSynthesisBookmarkEventArgs",{enumerable:!0,get:function(){return pe.SpeechSynthesisBookmarkEventArgs}});var ue=i(162);Object.defineProperty(t,"SpeechSynthesisVisemeEventArgs",{enumerable:!0,get:function(){return ue.SpeechSynthesisVisemeEventArgs}});var he=i(163);Object.defineProperty(t,"SpeechSynthesisBoundaryType",{enumerable:!0,get:function(){return he.SpeechSynthesisBoundaryType}});var de=i(164);Object.defineProperty(t,"SpeechSynthesisRequest",{enumerable:!0,get:function(){return de.SpeechSynthesisRequest}}),Object.defineProperty(t,"SpeechSynthesisRequestInputStream",{enumerable:!0,get:function(){return de.SpeechSynthesisRequestInputStream}});var ve=i(165);Object.defineProperty(t,"SpeechSynthesisRequestInputType",{enumerable:!0,get:function(){return ve.SpeechSynthesisRequestInputType}});var le=i(167);Object.defineProperty(t,"SynthesisVoicesResult",{enumerable:!0,get:function(){return le.SynthesisVoicesResult}});var ge=i(168);Object.defineProperty(t,"SynthesisVoiceGender",{enumerable:!0,get:function(){return ge.SynthesisVoiceGender}}),Object.defineProperty(t,"SynthesisVoiceType",{enumerable:!0,get:function(){return ge.SynthesisVoiceType}}),Object.defineProperty(t,"VoiceInfo",{enumerable:!0,get:function(){return ge.VoiceInfo}});var Se=i(169);Object.defineProperty(t,"SpeakerAudioDestination",{enumerable:!0,get:function(){return Se.SpeakerAudioDestination}});var fe=i(170);Object.defineProperty(t,"ConversationTranscriptionCanceledEventArgs",{enumerable:!0,get:function(){return fe.ConversationTranscriptionCanceledEventArgs}});var ye=i(171);Object.defineProperty(t,"MeetingTranscriptionCanceledEventArgs",{enumerable:!0,get:function(){return ye.MeetingTranscriptionCanceledEventArgs}});var me=i(172);Object.defineProperty(t,"PronunciationAssessmentGradingSystem",{enumerable:!0,get:function(){return me.PronunciationAssessmentGradingSystem}});var Ce=i(173);Object.defineProperty(t,"PronunciationAssessmentGranularity",{enumerable:!0,get:function(){return Ce.PronunciationAssessmentGranularity}});var Pe=i(174);Object.defineProperty(t,"PronunciationAssessmentConfig",{enumerable:!0,get:function(){return Pe.PronunciationAssessmentConfig}});var Re=i(175);Object.defineProperty(t,"PronunciationAssessmentResult",{enumerable:!0,get:function(){return Re.PronunciationAssessmentResult}});var Ie=i(145);Object.defineProperty(t,"LanguageIdMode",{enumerable:!0,get:function(){return Ie.LanguageIdMode}});var we=i(176);Object.defineProperty(t,"AvatarConfig",{enumerable:!0,get:function(){return we.AvatarConfig}});var be=i(177);Object.defineProperty(t,"AvatarEventArgs",{enumerable:!0,get:function(){return be.AvatarEventArgs}});var Ae=i(178);Object.defineProperty(t,"AvatarSceneConfig",{enumerable:!0,get:function(){return Ae.AvatarSceneConfig}});var Te=i(179);Object.defineProperty(t,"AvatarSynthesizer",{enumerable:!0,get:function(){return Te.AvatarSynthesizer}});var Ee=i(181);Object.defineProperty(t,"AvatarVideoFormat",{enumerable:!0,get:function(){return Ee.AvatarVideoFormat}}),Object.defineProperty(t,"Coordinate",{enumerable:!0,get:function(){return Ee.Coordinate}});var Oe=i(182);Object.defineProperty(t,"AvatarWebRTCConnectionResult",{enumerable:!0,get:function(){return Oe.AvatarWebRTCConnectionResult}});var Me=i(183);Object.defineProperty(t,"Diagnostics",{enumerable:!0,get:function(){return Me.Diagnostics}});var De=i(69);Object.defineProperty(t,"LogLevel",{enumerable:!0,get:function(){return De.LogLevel}})},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AudioOutputConfigImpl=t.AudioConfigImpl=t.AudioConfig=void 0;const r=i(66),n=i(70),s=i(85),o=i(87),a=i(89),c=i(90);class p{static fromDefaultMicrophoneInput(){const e=new r.PcmRecorder(!0);return new u(new r.MicAudioSource(e))}static fromMicrophoneInput(e){const t=new r.PcmRecorder(!0);return new u(new r.MicAudioSource(t,e))}static fromWavFileInput(e,t="unnamedBuffer.wav"){return new u(new r.FileAudioSource(e,t))}static fromStreamInput(e){if(e instanceof s.PullAudioInputStreamCallback)return new u(new a.PullAudioInputStreamImpl(e));if(e instanceof s.AudioInputStream)return new u(e);if("undefined"!=typeof MediaStream&&e instanceof MediaStream){const t=new r.PcmRecorder(!1);return new u(new r.MicAudioSource(t,null,null,e))}throw new Error("Not Supported Type")}static fromDefaultSpeakerOutput(){return new h(new s.SpeakerAudioDestination)}static fromSpeakerOutput(e){if(void 0===e)return p.fromDefaultSpeakerOutput();if(e instanceof s.SpeakerAudioDestination)return new h(e);throw new Error("Not Supported Type")}static fromAudioFileOutput(e){return new h(new o.AudioFileWriter(e))}static fromStreamOutput(e){if(e instanceof s.PushAudioOutputStreamCallback)return new h(new c.PushAudioOutputStreamImpl(e));if(e instanceof s.PushAudioOutputStream)return new h(e);if(e instanceof s.PullAudioOutputStream)return new h(e);throw new Error("Not Supported Type")}}t.AudioConfig=p;class u extends p{constructor(e){super(),this.privSource=e}get format(){return this.privSource.format}close(e,t){this.privSource.turnOff().then((()=>{e&&e()}),(e=>{t&&t(e)}))}id(){return this.privSource.id()}turnOn(){return this.privSource.turnOn()}attach(e){return this.privSource.attach(e)}detach(e){return this.privSource.detach(e)}turnOff(){return this.privSource.turnOff()}get events(){return this.privSource.events}setProperty(e,t){if(n.Contracts.throwIfNull(t,"value"),void 0===this.privSource.setProperty)throw new Error("This AudioConfig instance does not support setting properties.");this.privSource.setProperty(e,t)}getProperty(e,t){if(void 0!==this.privSource.getProperty)return this.privSource.getProperty(e,t);throw new Error("This AudioConfig instance does not support getting properties.")}get deviceInfo(){return this.privSource.deviceInfo}}t.AudioConfigImpl=u;class h extends p{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.")}}t.AudioOutputConfigImpl=h},function(e,t,i){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return n(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.AudioFileWriter=void 0;const o=s(i(88)),a=i(70);t.AudioFileWriter=class{constructor(e){a.Contracts.throwIfNullOrUndefined(o.openSync,"\nFile System access not available, please use Push or PullAudioOutputStream"),this.privFd=o.openSync(e,"w")}set format(e){a.Contracts.throwIfNotUndefined(this.privAudioFormat,"format is already set"),this.privAudioFormat=e;let t=0;this.privAudioFormat.hasHeader&&(t=this.privAudioFormat.header.byteLength),void 0!==this.privFd&&(this.privWriteStream=o.createWriteStream("",{fd:this.privFd,start:t,autoClose:!1}))}write(e){a.Contracts.throwIfNullOrUndefined(this.privAudioFormat,"must set format before writing."),void 0!==this.privWriteStream&&this.privWriteStream.write(new Uint8Array(e.slice(0)))}close(){void 0!==this.privFd&&(this.privWriteStream.on("finish",(()=>{this.privAudioFormat.hasHeader&&(this.privAudioFormat.updateHeader(this.privWriteStream.bytesWritten),o.writeSync(this.privFd,new Int8Array(this.privAudioFormat.header),0,this.privAudioFormat.header.byteLength,0)),o.closeSync(this.privFd),this.privFd=void 0})),this.privWriteStream.end())}id(){return this.privId}}},()=>{},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullAudioInputStreamImpl=t.PullAudioInputStream=t.PushAudioInputStreamImpl=t.PushAudioInputStream=t.AudioInputStream=void 0;const r=i(2),n=i(4),s=i(7),o=i(85),a=i(73);class c{constructor(){}static createPushStream(e){return p.create(e)}static createPullStream(e,t){return h.create(e,t)}}t.AudioInputStream=c;class p extends c{static create(e){return new u(e)}}t.PushAudioInputStream=p;class u extends p{constructor(e){super(),this.privFormat=void 0===e?a.AudioStreamFormatImpl.getDefaultInputFormat():e,this.privEvents=new n.EventSource,this.privId=(0,s.createNoDashGuid)(),this.privStream=new n.ChunkedArrayBufferStream(this.privFormat.avgBytesPerSec/10)}get format(){return Promise.resolve(this.privFormat)}write(e){this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}id(){return this.privId}turnOn(){this.onEvent(new n.AudioSourceInitializingEvent(this.privId)),this.onEvent(new n.AudioSourceReadyEvent(this.privId))}async attach(e){this.onEvent(new n.AudioStreamNodeAttachingEvent(this.privId,e)),await this.turnOn();const t=this.privStream;return this.onEvent(new n.AudioStreamNodeAttachedEvent(this.privId,e)),{detach:async()=>(this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)),this.turnOff()),id:()=>e,read:()=>t.read()}}detach(e){this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e))}turnOff(){}get events(){return this.privEvents}get deviceInfo(){return Promise.resolve({bitspersample:this.privFormat.bitsPerSample,channelcount:this.privFormat.channels,connectivity:r.connectivity.Unknown,manufacturer:"Speech SDK",model:"PushStream",samplerate:this.privFormat.samplesPerSec,type:r.type.Stream})}onEvent(e){this.privEvents.onEvent(e),n.Events.instance.onEvent(e)}toBuffer(e){const t=Buffer.alloc(e.byteLength),i=new Uint8Array(e);for(let e=0;e(this.privCallback.close(),this.onEvent(new n.AudioStreamNodeDetachedEvent(this.privId,e)),this.turnOff()),id:()=>e,read:()=>{let e,t=0;for(;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushAudioOutputStreamImpl=t.PushAudioOutputStream=t.PullAudioOutputStreamImpl=t.PullAudioOutputStream=t.AudioOutputStream=void 0;const r=i(4),n=i(70),s=i(91);class o{constructor(){}static createPullStream(){return a.create()}}t.AudioOutputStream=o;class a extends o{static create(){return new c}}t.PullAudioOutputStream=a;class c extends a{constructor(){super(),this.privId=(0,r.createNoDashGuid)(),this.privStream=new r.Stream}set format(e){null==e&&(this.privFormat=s.AudioOutputFormatImpl.getDefaultOutputFormat()),this.privFormat=e}get format(){return this.privFormat}get isClosed(){return this.privStream.isClosed}id(){return this.privId}async read(e){const t=new Int8Array(e);let i=0;if(void 0!==this.privLastChunkView){if(this.privLastChunkView.length>e.byteLength)return t.set(this.privLastChunkView.slice(0,e.byteLength)),this.privLastChunkView=this.privLastChunkView.slice(e.byteLength),Promise.resolve(e.byteLength);t.set(this.privLastChunkView),i=this.privLastChunkView.length,this.privLastChunkView=void 0}for(;ie.byteLength-i?(n=r.buffer.slice(0,e.byteLength-i),this.privLastChunkView=new Int8Array(r.buffer.slice(e.byteLength-i))):n=r.buffer,t.set(new Int8Array(n),i),i+=n.byteLength}}return i}write(e){n.Contracts.throwIfNullOrUndefined(this.privStream,"must set format before writing"),this.privStream.writeStreamChunk({buffer:e,isEnd:!1,timeReceived:Date.now()})}close(){this.privStream.close()}}t.PullAudioOutputStreamImpl=c;class p extends o{constructor(){super()}static create(e){return new u(e)}}t.PushAudioOutputStream=p;class u extends p{constructor(e){super(),this.privId=(0,r.createNoDashGuid)(),this.privCallback=e}set format(e){}write(e){this.privCallback.write&&this.privCallback.write(e)}close(){this.privCallback.close&&this.privCallback.close()}id(){return this.privId}}t.PushAudioOutputStreamImpl=u},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AudioOutputFormatImpl=void 0;const r=i(92),n=i(73);class s extends n.AudioStreamFormatImpl{constructor(e,t,i,r,n,s,o,a,c){super(i,s,t,e),this.formatTag=e,this.avgBytesPerSec=r,this.blockAlign=n,this.priAudioFormatString=o,this.priRequestAudioFormatString=a,this.priHasHeader=c}static fromSpeechSynthesisOutputFormat(e){return void 0===e?s.getDefaultOutputFormat():s.fromSpeechSynthesisOutputFormatString(s.SpeechSynthesisOutputFormatToString[e])}static fromSpeechSynthesisOutputFormatString(e){switch(e){case"raw-8khz-8bit-mono-mulaw":return new s(n.AudioFormatTag.MuLaw,1,8e3,8e3,1,8,e,e,!1);case"riff-16khz-16kbps-mono-siren":return new s(n.AudioFormatTag.Siren,1,16e3,2e3,40,0,e,"audio-16khz-16kbps-mono-siren",!0);case"audio-16khz-16kbps-mono-siren":return new s(n.AudioFormatTag.Siren,1,16e3,2e3,40,0,e,e,!1);case"audio-16khz-32kbitrate-mono-mp3":return new s(n.AudioFormatTag.MP3,1,16e3,4096,2,16,e,e,!1);case"audio-16khz-128kbitrate-mono-mp3":return new s(n.AudioFormatTag.MP3,1,16e3,16384,2,16,e,e,!1);case"audio-16khz-64kbitrate-mono-mp3":return new s(n.AudioFormatTag.MP3,1,16e3,8192,2,16,e,e,!1);case"audio-24khz-48kbitrate-mono-mp3":return new s(n.AudioFormatTag.MP3,1,24e3,6144,2,16,e,e,!1);case"audio-24khz-96kbitrate-mono-mp3":return new s(n.AudioFormatTag.MP3,1,24e3,12288,2,16,e,e,!1);case"audio-24khz-160kbitrate-mono-mp3":return new s(n.AudioFormatTag.MP3,1,24e3,20480,2,16,e,e,!1);case"raw-16khz-16bit-mono-truesilk":return new s(n.AudioFormatTag.SILKSkype,1,16e3,32e3,2,16,e,e,!1);case"riff-8khz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!0);case"riff-24khz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!0);case"riff-8khz-8bit-mono-mulaw":return new s(n.AudioFormatTag.MuLaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-mulaw",!0);case"raw-16khz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,16e3,32e3,2,16,e,"raw-16khz-16bit-mono-pcm",!1);case"raw-24khz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,24e3,48e3,2,16,e,"raw-24khz-16bit-mono-pcm",!1);case"raw-8khz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,8e3,16e3,2,16,e,"raw-8khz-16bit-mono-pcm",!1);case"ogg-16khz-16bit-mono-opus":return new s(n.AudioFormatTag.OGG_OPUS,1,16e3,8192,2,16,e,e,!1);case"ogg-24khz-16bit-mono-opus":return new s(n.AudioFormatTag.OGG_OPUS,1,24e3,8192,2,16,e,e,!1);case"raw-48khz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!1);case"riff-48khz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,48e3,96e3,2,16,e,"raw-48khz-16bit-mono-pcm",!0);case"audio-48khz-96kbitrate-mono-mp3":return new s(n.AudioFormatTag.MP3,1,48e3,12288,2,16,e,e,!1);case"audio-48khz-192kbitrate-mono-mp3":return new s(n.AudioFormatTag.MP3,1,48e3,24576,2,16,e,e,!1);case"ogg-48khz-16bit-mono-opus":return new s(n.AudioFormatTag.OGG_OPUS,1,48e3,12e3,2,16,e,e,!1);case"webm-16khz-16bit-mono-opus":return new s(n.AudioFormatTag.WEBM_OPUS,1,16e3,4e3,2,16,e,e,!1);case"webm-24khz-16bit-mono-opus":return new s(n.AudioFormatTag.WEBM_OPUS,1,24e3,6e3,2,16,e,e,!1);case"webm-24khz-16bit-24kbps-mono-opus":return new s(n.AudioFormatTag.WEBM_OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-16khz-16bit-32kbps-mono-opus":return new s(n.AudioFormatTag.OPUS,1,16e3,4e3,2,16,e,e,!1);case"audio-24khz-16bit-48kbps-mono-opus":return new s(n.AudioFormatTag.OPUS,1,24e3,6e3,2,16,e,e,!1);case"audio-24khz-16bit-24kbps-mono-opus":return new s(n.AudioFormatTag.OPUS,1,24e3,3e3,2,16,e,e,!1);case"audio-24khz-16bit-mono-flac":return new s(n.AudioFormatTag.FLAC,1,24e3,24e3,2,16,e,e,!1);case"audio-48khz-16bit-mono-flac":return new s(n.AudioFormatTag.FLAC,1,48e3,3e4,2,16,e,e,!1);case"raw-24khz-16bit-mono-truesilk":return new s(n.AudioFormatTag.SILKSkype,1,24e3,48e3,2,16,e,e,!1);case"raw-8khz-8bit-mono-alaw":return new s(n.AudioFormatTag.ALaw,1,8e3,8e3,1,8,e,e,!1);case"riff-8khz-8bit-mono-alaw":return new s(n.AudioFormatTag.ALaw,1,8e3,8e3,1,8,e,"raw-8khz-8bit-mono-alaw",!0);case"raw-22050hz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,22050,44100,2,16,e,e,!1);case"riff-22050hz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,22050,44100,2,16,e,"raw-22050hz-16bit-mono-pcm",!0);case"raw-44100hz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,44100,88200,2,16,e,e,!1);case"riff-44100hz-16bit-mono-pcm":return new s(n.AudioFormatTag.PCM,1,44100,88200,2,16,e,"raw-44100hz-16bit-mono-pcm",!0);case"amr-wb-16000h":return new s(n.AudioFormatTag.AMR_WB,1,16e3,3052,2,16,e,e,!1);case"g722-16khz-64kbps":return new s(n.AudioFormatTag.G722,1,16e3,8e3,2,16,e,e,!1);default:return new s(n.AudioFormatTag.PCM,1,16e3,32e3,2,16,"riff-16khz-16bit-mono-pcm","raw-16khz-16bit-mono-pcm",!0)}}static getDefaultOutputFormat(){return s.fromSpeechSynthesisOutputFormatString("undefined"!=typeof window?"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}addHeader(e){if(!this.hasHeader)return e;this.updateHeader(e.byteLength);const t=new Uint8Array(e.byteLength+this.header.byteLength);return t.set(new Uint8Array(this.header),0),t.set(new Uint8Array(e),this.header.byteLength),t.buffer}}t.AudioOutputFormatImpl=s,s.SpeechSynthesisOutputFormatToString={[r.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw]:"raw-8khz-8bit-mono-mulaw",[r.SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren]:"riff-16khz-16kbps-mono-siren",[r.SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren]:"audio-16khz-16kbps-mono-siren",[r.SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3]:"audio-16khz-32kbitrate-mono-mp3",[r.SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3]:"audio-16khz-128kbitrate-mono-mp3",[r.SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3]:"audio-16khz-64kbitrate-mono-mp3",[r.SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3]:"audio-24khz-48kbitrate-mono-mp3",[r.SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3]:"audio-24khz-96kbitrate-mono-mp3",[r.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3]:"audio-24khz-160kbitrate-mono-mp3",[r.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk]:"raw-16khz-16bit-mono-truesilk",[r.SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm]:"riff-16khz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm]:"riff-8khz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm]:"riff-24khz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw]:"riff-8khz-8bit-mono-mulaw",[r.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm]:"raw-16khz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm]:"raw-24khz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm]:"raw-8khz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus]:"ogg-16khz-16bit-mono-opus",[r.SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus]:"ogg-24khz-16bit-mono-opus",[r.SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm]:"raw-48khz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm]:"riff-48khz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3]:"audio-48khz-96kbitrate-mono-mp3",[r.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3]:"audio-48khz-192kbitrate-mono-mp3",[r.SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus]:"ogg-48khz-16bit-mono-opus",[r.SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus]:"webm-16khz-16bit-mono-opus",[r.SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus]:"webm-24khz-16bit-mono-opus",[r.SpeechSynthesisOutputFormat.Webm24Khz16Bit24KbpsMonoOpus]:"webm-24khz-16bit-24kbps-mono-opus",[r.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk]:"raw-24khz-16bit-mono-truesilk",[r.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw]:"raw-8khz-8bit-mono-alaw",[r.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw]:"riff-8khz-8bit-mono-alaw",[r.SpeechSynthesisOutputFormat.Audio16Khz16Bit32KbpsMonoOpus]:"audio-16khz-16bit-32kbps-mono-opus",[r.SpeechSynthesisOutputFormat.Audio24Khz16Bit48KbpsMonoOpus]:"audio-24khz-16bit-48kbps-mono-opus",[r.SpeechSynthesisOutputFormat.Audio24Khz16Bit24KbpsMonoOpus]:"audio-24khz-16bit-24kbps-mono-opus",[r.SpeechSynthesisOutputFormat.Raw22050Hz16BitMonoPcm]:"raw-22050hz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Riff22050Hz16BitMonoPcm]:"riff-22050hz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Raw44100Hz16BitMonoPcm]:"raw-44100hz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.Riff44100Hz16BitMonoPcm]:"riff-44100hz-16bit-mono-pcm",[r.SpeechSynthesisOutputFormat.AmrWb16000Hz]:"amr-wb-16000hz",[r.SpeechSynthesisOutputFormat.G72216Khz64Kbps]:"g722-16khz-64kbps"}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisOutputFormat=void 0,function(e){e[e.Raw8Khz8BitMonoMULaw=0]="Raw8Khz8BitMonoMULaw",e[e.Riff16Khz16KbpsMonoSiren=1]="Riff16Khz16KbpsMonoSiren",e[e.Audio16Khz16KbpsMonoSiren=2]="Audio16Khz16KbpsMonoSiren",e[e.Audio16Khz32KBitRateMonoMp3=3]="Audio16Khz32KBitRateMonoMp3",e[e.Audio16Khz128KBitRateMonoMp3=4]="Audio16Khz128KBitRateMonoMp3",e[e.Audio16Khz64KBitRateMonoMp3=5]="Audio16Khz64KBitRateMonoMp3",e[e.Audio24Khz48KBitRateMonoMp3=6]="Audio24Khz48KBitRateMonoMp3",e[e.Audio24Khz96KBitRateMonoMp3=7]="Audio24Khz96KBitRateMonoMp3",e[e.Audio24Khz160KBitRateMonoMp3=8]="Audio24Khz160KBitRateMonoMp3",e[e.Raw16Khz16BitMonoTrueSilk=9]="Raw16Khz16BitMonoTrueSilk",e[e.Riff16Khz16BitMonoPcm=10]="Riff16Khz16BitMonoPcm",e[e.Riff8Khz16BitMonoPcm=11]="Riff8Khz16BitMonoPcm",e[e.Riff24Khz16BitMonoPcm=12]="Riff24Khz16BitMonoPcm",e[e.Riff8Khz8BitMonoMULaw=13]="Riff8Khz8BitMonoMULaw",e[e.Raw16Khz16BitMonoPcm=14]="Raw16Khz16BitMonoPcm",e[e.Raw24Khz16BitMonoPcm=15]="Raw24Khz16BitMonoPcm",e[e.Raw8Khz16BitMonoPcm=16]="Raw8Khz16BitMonoPcm",e[e.Ogg16Khz16BitMonoOpus=17]="Ogg16Khz16BitMonoOpus",e[e.Ogg24Khz16BitMonoOpus=18]="Ogg24Khz16BitMonoOpus",e[e.Raw48Khz16BitMonoPcm=19]="Raw48Khz16BitMonoPcm",e[e.Riff48Khz16BitMonoPcm=20]="Riff48Khz16BitMonoPcm",e[e.Audio48Khz96KBitRateMonoMp3=21]="Audio48Khz96KBitRateMonoMp3",e[e.Audio48Khz192KBitRateMonoMp3=22]="Audio48Khz192KBitRateMonoMp3",e[e.Ogg48Khz16BitMonoOpus=23]="Ogg48Khz16BitMonoOpus",e[e.Webm16Khz16BitMonoOpus=24]="Webm16Khz16BitMonoOpus",e[e.Webm24Khz16BitMonoOpus=25]="Webm24Khz16BitMonoOpus",e[e.Raw24Khz16BitMonoTrueSilk=26]="Raw24Khz16BitMonoTrueSilk",e[e.Raw8Khz8BitMonoALaw=27]="Raw8Khz8BitMonoALaw",e[e.Riff8Khz8BitMonoALaw=28]="Riff8Khz8BitMonoALaw",e[e.Webm24Khz16Bit24KbpsMonoOpus=29]="Webm24Khz16Bit24KbpsMonoOpus",e[e.Audio16Khz16Bit32KbpsMonoOpus=30]="Audio16Khz16Bit32KbpsMonoOpus",e[e.Audio24Khz16Bit48KbpsMonoOpus=31]="Audio24Khz16Bit48KbpsMonoOpus",e[e.Audio24Khz16Bit24KbpsMonoOpus=32]="Audio24Khz16Bit24KbpsMonoOpus",e[e.Raw22050Hz16BitMonoPcm=33]="Raw22050Hz16BitMonoPcm",e[e.Riff22050Hz16BitMonoPcm=34]="Riff22050Hz16BitMonoPcm",e[e.Raw44100Hz16BitMonoPcm=35]="Raw44100Hz16BitMonoPcm",e[e.Riff44100Hz16BitMonoPcm=36]="Riff44100Hz16BitMonoPcm",e[e.AmrWb16000Hz=37]="AmrWb16000Hz",e[e.G72216Khz64Kbps=38]="G72216Khz64Kbps"}(t.SpeechSynthesisOutputFormat||(t.SpeechSynthesisOutputFormat={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationReason=void 0,function(e){e[e.Error=0]="Error",e[e.EndOfStream=1]="EndOfStream"}(t.CancellationReason||(t.CancellationReason={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PullAudioInputStreamCallback=void 0;t.PullAudioInputStreamCallback=class{}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PushAudioOutputStreamCallback=void 0;t.PushAudioOutputStreamCallback=class{}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KeywordRecognitionModel=void 0;const r=i(70);t.KeywordRecognitionModel=class{constructor(){this.privDisposed=!1}static fromFile(e){throw r.Contracts.throwIfFileDoesNotExist(e,"fileName"),new Error("Not yet implemented.")}static fromStream(e){throw r.Contracts.throwIfNull(e,"file"),new Error("Not yet implemented.")}close(){this.privDisposed||(this.privDisposed=!0)}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionEventArgs=void 0;t.SessionEventArgs=class{constructor(e){this.privSessionId=e}get sessionId(){return this.privSessionId}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RecognitionEventArgs=void 0;const r=i(85);class n extends r.SessionEventArgs{constructor(e,t){super(t),this.privOffset=e}get offset(){return this.privOffset}}t.RecognitionEventArgs=n},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OutputFormat=void 0,function(e){e[e.Simple=0]="Simple",e[e.Detailed=1]="Detailed"}(t.OutputFormat||(t.OutputFormat={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RecognitionResult=void 0;t.RecognitionResult=class{constructor(e,t,i,r,n,s,o,a,c,p,u){this.privResultId=e,this.privReason=t,this.privText=i,this.privDuration=r,this.privOffset=n,this.privLanguage=s,this.privLanguageDetectionConfidence=o,this.privErrorDetails=a,this.privJson=c,this.privProperties=p,this.privChannel=void 0===u?0:u}get resultId(){return this.privResultId}get reason(){return this.privReason}get text(){return this.privText}get duration(){return this.privDuration}get offset(){return this.privOffset}get language(){return this.privLanguage}get languageDetectionConfidence(){return this.privLanguageDetectionConfidence}get errorDetails(){return this.privErrorDetails}get json(){return this.privJson}get properties(){return this.privProperties}get channel(){return this.privChannel}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechRecognitionResult=void 0;const r=i(85);class n extends r.RecognitionResult{constructor(e,t,i,r,n,s,o,a,c,p,u,h){super(e,t,i,r,n,s,o,c,p,u,h),this.privSpeakerId=a}get speakerId(){return this.privSpeakerId}}t.SpeechRecognitionResult=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MeetingTranscriptionEventArgs=t.ConversationTranscriptionEventArgs=t.SpeechRecognitionEventArgs=void 0;const r=i(85);class n extends r.RecognitionEventArgs{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}t.SpeechRecognitionEventArgs=n;class s extends r.RecognitionEventArgs{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}t.ConversationTranscriptionEventArgs=s;t.MeetingTranscriptionEventArgs=class extends n{}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechRecognitionCanceledEventArgs=void 0;const r=i(104);class n extends r.CancellationEventArgsBase{}t.SpeechRecognitionCanceledEventArgs=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationEventArgsBase=void 0;const r=i(85);class n extends r.RecognitionEventArgs{constructor(e,t,i,r,n){super(r,n),this.privReason=e,this.privErrorDetails=t,this.privErrorCode=i}get reason(){return this.privReason}get errorCode(){return this.privErrorCode}get errorDetails(){return this.privErrorDetails}}t.CancellationEventArgsBase=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationRecognitionEventArgs=void 0;const r=i(85);class n extends r.RecognitionEventArgs{constructor(e,t,i){super(t,i),this.privResult=e}get result(){return this.privResult}}t.TranslationRecognitionEventArgs=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationSynthesisEventArgs=void 0;const r=i(85);class n extends r.SessionEventArgs{constructor(e,t){super(t),this.privResult=e}get result(){return this.privResult}}t.TranslationSynthesisEventArgs=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationRecognitionResult=void 0;const r=i(85);class n extends r.SpeechRecognitionResult{constructor(e,t,i,r,n,s,o,a,c,p,u){super(t,i,r,n,s,o,a,void 0,c,p,u),this.privTranslations=e}static fromSpeechRecognitionResult(e){return new n(void 0,e.resultId,e.reason,e.text,e.duration,e.offset,e.language,e.languageDetectionConfidence,e.errorDetails,e.json,e.properties)}get translations(){return this.privTranslations}}t.TranslationRecognitionResult=n},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationSynthesisResult=void 0;t.TranslationSynthesisResult=class{constructor(e,t){this.privReason=e,this.privAudio=t}get audio(){return this.privAudio}get reason(){return this.privReason}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ResultReason=void 0,function(e){e[e.NoMatch=0]="NoMatch",e[e.Canceled=1]="Canceled",e[e.RecognizingSpeech=2]="RecognizingSpeech",e[e.RecognizedSpeech=3]="RecognizedSpeech",e[e.RecognizedKeyword=4]="RecognizedKeyword",e[e.TranslatingSpeech=5]="TranslatingSpeech",e[e.TranslatedSpeech=6]="TranslatedSpeech",e[e.SynthesizingAudio=7]="SynthesizingAudio",e[e.SynthesizingAudioCompleted=8]="SynthesizingAudioCompleted",e[e.SynthesizingAudioStarted=9]="SynthesizingAudioStarted",e[e.VoicesListRetrieved=10]="VoicesListRetrieved",e[e.TranslatingParticipantSpeech=11]="TranslatingParticipantSpeech",e[e.TranslatedParticipantSpeech=12]="TranslatedParticipantSpeech",e[e.TranslatedInstantMessage=13]="TranslatedInstantMessage",e[e.TranslatedParticipantInstantMessage=14]="TranslatedParticipantInstantMessage"}(t.ResultReason||(t.ResultReason={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechConfigImpl=t.SpeechConfig=void 0;const r=i(2),n=i(70),s=i(85);class o{constructor(){}static fromSubscription(e,t){n.Contracts.throwIfNullOrWhitespace(e,"subscriptionKey"),n.Contracts.throwIfNullOrWhitespace(t,"region");const i=new a;return i.setProperty(s.PropertyId.SpeechServiceConnection_Region,t),i.setProperty(s.PropertyId.SpeechServiceConnection_Key,e),i}static fromEndpoint(e,t){n.Contracts.throwIfNull(e,"endpoint");const i="string"==typeof t&&t.trim().length>0,r="object"==typeof t&&null!==t&&"function"==typeof t.getToken,o="object"==typeof t&&null!==t&&"string"==typeof t.key;if(void 0!==t&&!i&&!r&&!o)throw new Error("Invalid 'auth' parameter: expected a non-empty API key string, a TokenCredential, or a KeyCredential.");let c;return"string"==typeof t?(c=new a,c.setProperty(s.PropertyId.SpeechServiceConnection_Key,t)):"object"==typeof t&&"function"==typeof t.getToken?c=new a(t):"object"==typeof t&&"string"==typeof t.key?(c=new a,c.setProperty(s.PropertyId.SpeechServiceConnection_Key,t.key)):c=new a,c.setProperty(s.PropertyId.SpeechServiceConnection_Endpoint,e.href),c}static fromHost(e,t){n.Contracts.throwIfNull(e,"hostName");const i=new a;return i.setProperty(s.PropertyId.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(""===e.port?"":":"+e.port)),i.setProperty(s.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,"1"),void 0!==t&&i.setProperty(s.PropertyId.SpeechServiceConnection_Key,t),i}static fromAuthorizationToken(e,t){n.Contracts.throwIfNull(e,"authorizationToken"),n.Contracts.throwIfNullOrWhitespace(t,"region");const i=new a;return i.setProperty(s.PropertyId.SpeechServiceConnection_Region,t),i.authorizationToken=e,i}close(){}}t.SpeechConfig=o;class a extends o{constructor(e){super(),this.privProperties=new s.PropertyCollection,this.speechRecognitionLanguage="en-US",this.outputFormat=s.OutputFormat.Simple,this.privTokenCredential=e}get properties(){return this.privProperties}get endPoint(){return new URL(this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_Endpoint))}get subscriptionKey(){return this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_Key)}get region(){return this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_Region)}get authorizationToken(){return this.privProperties.getProperty(s.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.privProperties.setProperty(s.PropertyId.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage)}set speechRecognitionLanguage(e){this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage,e)}get autoDetectSourceLanguages(){return this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages)}set autoDetectSourceLanguages(e){this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,e)}get outputFormat(){return s.OutputFormat[this.privProperties.getProperty(r.OutputFormatPropertyName,void 0)]}set outputFormat(e){this.privProperties.setProperty(r.OutputFormatPropertyName,s.OutputFormat[e])}get endpointId(){return this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_EndpointId,e)}get tokenCredential(){return this.privTokenCredential}setProperty(e,t){n.Contracts.throwIfNull(t,"value"),this.privProperties.setProperty(e,t)}getProperty(e,t){return this.privProperties.getProperty(e,t)}setProxy(e,t,i,r){this.setProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_ProxyHostName],e),this.setProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_ProxyPort],t),this.setProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_ProxyUserName],i),this.setProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_ProxyPassword],r)}setServiceProperty(e,t){const i=JSON.parse(this.privProperties.getProperty(r.ServicePropertiesPropertyName,"{}"));i[e]=t,this.privProperties.setProperty(r.ServicePropertiesPropertyName,JSON.stringify(i))}setProfanity(e){this.privProperties.setProperty(s.PropertyId.SpeechServiceResponse_ProfanityOption,s.ProfanityOption[e])}enableAudioLogging(){this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privProperties.setProperty(s.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,"true"),this.privProperties.setProperty(r.OutputFormatPropertyName,s.OutputFormat[s.OutputFormat.Detailed])}enableDictation(){this.privProperties.setProperty(r.ForceDictationPropertyName,"true")}clone(){const e=new a(this.tokenCredential);return e.privProperties=this.privProperties.clone(),e}get speechSynthesisLanguage(){return this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return s.SpeechSynthesisOutputFormat[this.privProperties.getProperty(s.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_SynthOutputFormat,s.SpeechSynthesisOutputFormat[e])}}t.SpeechConfigImpl=a},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechTranslationConfigImpl=t.SpeechTranslationConfig=void 0;const r=i(2),n=i(70),s=i(85);class o extends s.SpeechConfig{constructor(){super()}static fromSubscription(e,t){n.Contracts.throwIfNullOrWhitespace(e,"subscriptionKey"),n.Contracts.throwIfNullOrWhitespace(t,"region");const i=new a;return i.properties.setProperty(s.PropertyId.SpeechServiceConnection_Key,e),i.properties.setProperty(s.PropertyId.SpeechServiceConnection_Region,t),i}static fromAuthorizationToken(e,t){n.Contracts.throwIfNullOrWhitespace(e,"authorizationToken"),n.Contracts.throwIfNullOrWhitespace(t,"region");const i=new a;return i.properties.setProperty(s.PropertyId.SpeechServiceAuthorization_Token,e),i.properties.setProperty(s.PropertyId.SpeechServiceConnection_Region,t),i}static fromHost(e,t){n.Contracts.throwIfNull(e,"hostName");const i=new a;return i.setProperty(s.PropertyId.SpeechServiceConnection_Host,e.protocol+"//"+e.hostname+(""===e.port?"":":"+e.port)),void 0!==t&&i.setProperty(s.PropertyId.SpeechServiceConnection_Key,t),i}static fromEndpoint(e,t){n.Contracts.throwIfNull(e,"endpoint");const i="string"==typeof t&&t.trim().length>0,r="object"==typeof t&&null!==t&&"function"==typeof t.getToken,o="object"==typeof t&&null!==t&&"string"==typeof t.key;if(void 0!==t&&!i&&!r&&!o)throw new Error("Invalid 'auth' parameter: expected a non-empty API key string, a TokenCredential, or a KeyCredential.");let c;return"string"==typeof t?(c=new a,c.setProperty(s.PropertyId.SpeechServiceConnection_Key,t)):"object"==typeof t&&"function"==typeof t.getToken?c=new a(t):"object"==typeof t&&"string"==typeof t.key?(c=new a,c.setProperty(s.PropertyId.SpeechServiceConnection_Key,t.key)):c=new a,c.setProperty(s.PropertyId.SpeechServiceConnection_Endpoint,e.href),c}}t.SpeechTranslationConfig=o;class a extends o{constructor(e){super(),this.privSpeechProperties=new s.PropertyCollection,this.outputFormat=s.OutputFormat.Simple,this.privTokenCredential=e}set authorizationToken(e){n.Contracts.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceAuthorization_Token,e)}set speechRecognitionLanguage(e){n.Contracts.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage,e)}get speechRecognitionLanguage(){return this.privSpeechProperties.getProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_RecoLanguage])}get subscriptionKey(){return this.privSpeechProperties.getProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_Key])}get outputFormat(){return s.OutputFormat[this.privSpeechProperties.getProperty(r.OutputFormatPropertyName,void 0)]}set outputFormat(e){this.privSpeechProperties.setProperty(r.OutputFormatPropertyName,s.OutputFormat[e])}get endpointId(){return this.privSpeechProperties.getProperty(s.PropertyId.SpeechServiceConnection_EndpointId)}set endpointId(e){this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceConnection_EndpointId,e)}addTargetLanguage(e){n.Contracts.throwIfNullOrWhitespace(e,"value");const t=this.targetLanguages;t.includes(e)||(t.push(e),this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceConnection_TranslationToLanguages,t.join(",")))}get targetLanguages(){return void 0!==this.privSpeechProperties.getProperty(s.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0)?this.privSpeechProperties.getProperty(s.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","):[]}get voiceName(){return this.getProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_TranslationVoice])}set voiceName(e){n.Contracts.throwIfNullOrWhitespace(e,"value"),this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceConnection_TranslationVoice,e)}get region(){return this.privSpeechProperties.getProperty(s.PropertyId.SpeechServiceConnection_Region)}get tokenCredential(){return this.privTokenCredential}setProxy(e,t,i,r){this.setProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_ProxyHostName],e),this.setProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_ProxyPort],t),this.setProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_ProxyUserName],i),this.setProperty(s.PropertyId[s.PropertyId.SpeechServiceConnection_ProxyPassword],r)}getProperty(e,t){return this.privSpeechProperties.getProperty(e,t)}setProperty(e,t){this.privSpeechProperties.setProperty(e,t)}get properties(){return this.privSpeechProperties}close(){}setServiceProperty(e,t){const i=JSON.parse(this.privSpeechProperties.getProperty(r.ServicePropertiesPropertyName,"{}"));i[e]=t,this.privSpeechProperties.setProperty(r.ServicePropertiesPropertyName,JSON.stringify(i))}setProfanity(e){this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceResponse_ProfanityOption,s.ProfanityOption[e])}enableAudioLogging(){this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceConnection_EnableAudioLogging,"true")}requestWordLevelTimestamps(){this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,"true")}enableDictation(){this.privSpeechProperties.setProperty(r.ForceDictationPropertyName,"true")}get speechSynthesisLanguage(){return this.privSpeechProperties.getProperty(s.PropertyId.SpeechServiceConnection_SynthLanguage)}set speechSynthesisLanguage(e){this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceConnection_SynthLanguage,e)}get speechSynthesisVoiceName(){return this.privSpeechProperties.getProperty(s.PropertyId.SpeechServiceConnection_SynthVoice)}set speechSynthesisVoiceName(e){this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceConnection_SynthVoice,e)}get speechSynthesisOutputFormat(){return s.SpeechSynthesisOutputFormat[this.privSpeechProperties.getProperty(s.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0)]}set speechSynthesisOutputFormat(e){this.privSpeechProperties.setProperty(s.PropertyId.SpeechServiceConnection_SynthOutputFormat,s.SpeechSynthesisOutputFormat[e])}}t.SpeechTranslationConfigImpl=a},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PropertyCollection=void 0;const r=i(85);class n{constructor(){this.privKeys=[],this.privValues=[]}getProperty(e,t){let i;i="string"==typeof e?e:r.PropertyId[e];for(let e=0;e{if(void 0===e.getProperty(t,void 0)){const i=this.getProperty(t);e.setProperty(t,i)}}))}get keys(){return this.privKeys}}t.PropertyCollection=n},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PropertyId=void 0,function(e){e[e.SpeechServiceConnection_Key=0]="SpeechServiceConnection_Key",e[e.SpeechServiceConnection_Endpoint=1]="SpeechServiceConnection_Endpoint",e[e.SpeechServiceConnection_Region=2]="SpeechServiceConnection_Region",e[e.SpeechServiceAuthorization_Token=3]="SpeechServiceAuthorization_Token",e[e.SpeechServiceAuthorization_Type=4]="SpeechServiceAuthorization_Type",e[e.SpeechServiceConnection_EndpointId=5]="SpeechServiceConnection_EndpointId",e[e.SpeechServiceConnection_TranslationToLanguages=6]="SpeechServiceConnection_TranslationToLanguages",e[e.SpeechServiceConnection_TranslationVoice=7]="SpeechServiceConnection_TranslationVoice",e[e.SpeechServiceConnection_TranslationFeatures=8]="SpeechServiceConnection_TranslationFeatures",e[e.SpeechServiceConnection_TranslationCategoryId=9]="SpeechServiceConnection_TranslationCategoryId",e[e.SpeechServiceConnection_ProxyHostName=10]="SpeechServiceConnection_ProxyHostName",e[e.SpeechServiceConnection_ProxyPort=11]="SpeechServiceConnection_ProxyPort",e[e.SpeechServiceConnection_ProxyUserName=12]="SpeechServiceConnection_ProxyUserName",e[e.SpeechServiceConnection_ProxyPassword=13]="SpeechServiceConnection_ProxyPassword",e[e.SpeechServiceConnection_RecoMode=14]="SpeechServiceConnection_RecoMode",e[e.SpeechServiceConnection_RecoLanguage=15]="SpeechServiceConnection_RecoLanguage",e[e.Speech_SessionId=16]="Speech_SessionId",e[e.SpeechServiceConnection_SynthLanguage=17]="SpeechServiceConnection_SynthLanguage",e[e.SpeechServiceConnection_SynthVoice=18]="SpeechServiceConnection_SynthVoice",e[e.SpeechServiceConnection_SynthOutputFormat=19]="SpeechServiceConnection_SynthOutputFormat",e[e.SpeechServiceConnection_AutoDetectSourceLanguages=20]="SpeechServiceConnection_AutoDetectSourceLanguages",e[e.SpeechServiceResponse_RequestDetailedResultTrueFalse=21]="SpeechServiceResponse_RequestDetailedResultTrueFalse",e[e.SpeechServiceResponse_RequestProfanityFilterTrueFalse=22]="SpeechServiceResponse_RequestProfanityFilterTrueFalse",e[e.SpeechServiceResponse_JsonResult=23]="SpeechServiceResponse_JsonResult",e[e.SpeechServiceResponse_JsonErrorDetails=24]="SpeechServiceResponse_JsonErrorDetails",e[e.CancellationDetails_Reason=25]="CancellationDetails_Reason",e[e.CancellationDetails_ReasonText=26]="CancellationDetails_ReasonText",e[e.CancellationDetails_ReasonDetailedText=27]="CancellationDetails_ReasonDetailedText",e[e.SpeechServiceConnection_Url=28]="SpeechServiceConnection_Url",e[e.SpeechServiceConnection_InitialSilenceTimeoutMs=29]="SpeechServiceConnection_InitialSilenceTimeoutMs",e[e.SpeechServiceConnection_EndSilenceTimeoutMs=30]="SpeechServiceConnection_EndSilenceTimeoutMs",e[e.Speech_SegmentationSilenceTimeoutMs=31]="Speech_SegmentationSilenceTimeoutMs",e[e.Speech_SegmentationMaximumTimeMs=32]="Speech_SegmentationMaximumTimeMs",e[e.Speech_SegmentationStrategy=33]="Speech_SegmentationStrategy",e[e.Speech_StartEventSensitivity=34]="Speech_StartEventSensitivity",e[e.Speech_EnableMultiChannelProcessing=35]="Speech_EnableMultiChannelProcessing",e[e.SpeechServiceConnection_EnableAudioLogging=36]="SpeechServiceConnection_EnableAudioLogging",e[e.SpeechServiceConnection_LanguageIdMode=37]="SpeechServiceConnection_LanguageIdMode",e[e.SpeechServiceConnection_RecognitionEndpointVersion=38]="SpeechServiceConnection_RecognitionEndpointVersion",e[e.SpeechServiceResponse_ProfanityOption=39]="SpeechServiceResponse_ProfanityOption",e[e.SpeechServiceResponse_PostProcessingOption=40]="SpeechServiceResponse_PostProcessingOption",e[e.SpeechServiceResponse_RequestWordLevelTimestamps=41]="SpeechServiceResponse_RequestWordLevelTimestamps",e[e.SpeechServiceResponse_StablePartialResultThreshold=42]="SpeechServiceResponse_StablePartialResultThreshold",e[e.SpeechServiceResponse_OutputFormatOption=43]="SpeechServiceResponse_OutputFormatOption",e[e.SpeechServiceResponse_TranslationRequestStablePartialResult=44]="SpeechServiceResponse_TranslationRequestStablePartialResult",e[e.SpeechServiceResponse_RequestWordBoundary=45]="SpeechServiceResponse_RequestWordBoundary",e[e.SpeechServiceResponse_RequestPunctuationBoundary=46]="SpeechServiceResponse_RequestPunctuationBoundary",e[e.SpeechServiceResponse_RequestSentenceBoundary=47]="SpeechServiceResponse_RequestSentenceBoundary",e[e.SpeechServiceResponse_DiarizeIntermediateResults=48]="SpeechServiceResponse_DiarizeIntermediateResults",e[e.Conversation_ApplicationId=49]="Conversation_ApplicationId",e[e.Conversation_DialogType=50]="Conversation_DialogType",e[e.Conversation_Initial_Silence_Timeout=51]="Conversation_Initial_Silence_Timeout",e[e.Conversation_From_Id=52]="Conversation_From_Id",e[e.Conversation_Conversation_Id=53]="Conversation_Conversation_Id",e[e.Conversation_Custom_Voice_Deployment_Ids=54]="Conversation_Custom_Voice_Deployment_Ids",e[e.Conversation_Speech_Activity_Template=55]="Conversation_Speech_Activity_Template",e[e.Conversation_Request_Bot_Status_Messages=56]="Conversation_Request_Bot_Status_Messages",e[e.Conversation_Agent_Connection_Id=57]="Conversation_Agent_Connection_Id",e[e.SpeechServiceConnection_Host=58]="SpeechServiceConnection_Host",e[e.PronunciationAssessment_ReferenceText=59]="PronunciationAssessment_ReferenceText",e[e.PronunciationAssessment_GradingSystem=60]="PronunciationAssessment_GradingSystem",e[e.PronunciationAssessment_Granularity=61]="PronunciationAssessment_Granularity",e[e.PronunciationAssessment_EnableMiscue=62]="PronunciationAssessment_EnableMiscue",e[e.PronunciationAssessment_Json=63]="PronunciationAssessment_Json",e[e.PronunciationAssessment_Params=64]="PronunciationAssessment_Params",e[e.WebWorkerLoadType=65]="WebWorkerLoadType",e[e.TalkingAvatarService_WebRTC_SDP=66]="TalkingAvatarService_WebRTC_SDP",e[e.Recognizer_StopTimeoutMs=67]="Recognizer_StopTimeoutMs",e[e.SpeechServiceResponse_RecognitionLatencyMs=68]="SpeechServiceResponse_RecognitionLatencyMs",e[e.SpeechServiceResponse_SynthesisFirstByteLatencyMs=69]="SpeechServiceResponse_SynthesisFirstByteLatencyMs",e[e.SpeechServiceResponse_SynthesisFinishLatencyMs=70]="SpeechServiceResponse_SynthesisFinishLatencyMs",e[e.SpeechServiceResponse_SynthesisConnectionLatencyMs=71]="SpeechServiceResponse_SynthesisConnectionLatencyMs",e[e.SpeechServiceResponse_SynthesisNetworkLatencyMs=72]="SpeechServiceResponse_SynthesisNetworkLatencyMs",e[e.SpeechServiceResponse_SynthesisServiceLatencyMs=73]="SpeechServiceResponse_SynthesisServiceLatencyMs",e[e.SpeechSynthesisRequest_Pitch=74]="SpeechSynthesisRequest_Pitch",e[e.SpeechSynthesisRequest_Rate=75]="SpeechSynthesisRequest_Rate",e[e.SpeechSynthesisRequest_Volume=76]="SpeechSynthesisRequest_Volume",e[e.SpeechSynthesisRequest_Style=77]="SpeechSynthesisRequest_Style",e[e.SpeechSynthesisRequest_Temperature=78]="SpeechSynthesisRequest_Temperature",e[e.SpeechSynthesisRequest_CustomLexiconUrl=79]="SpeechSynthesisRequest_CustomLexiconUrl",e[e.SpeechSynthesisRequest_PreferLocales=80]="SpeechSynthesisRequest_PreferLocales",e[e.SpeechSynthesis_FrameTimeoutInterval=81]="SpeechSynthesis_FrameTimeoutInterval",e[e.SpeechSynthesis_RtfTimeoutThreshold=82]="SpeechSynthesis_RtfTimeoutThreshold"}(t.PropertyId||(t.PropertyId={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Recognizer=void 0;const r=i(2),n=i(4),s=i(70),o=i(85);class a{constructor(e,t,i,r){this.audioConfig=void 0!==e?e:o.AudioConfig.fromDefaultMicrophoneInput(),this.privDisposed=!1,this.privProperties=t.clone(),this.privConnectionFactory=i,this.tokenCredential=r,this.implCommonRecognizerSetup()}close(e,t){s.Contracts.throwIfDisposed(this.privDisposed),(0,n.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}get internalData(){return this.privReco}async dispose(e){this.privDisposed||(this.privDisposed=!0,e&&this.privReco&&(await this.privReco.audioSource.turnOff(),await this.privReco.dispose()))}static get telemetryEnabled(){return r.ServiceRecognizerBase.telemetryDataEnabled}static enableTelemetry(e){r.ServiceRecognizerBase.telemetryDataEnabled=e}implCommonRecognizerSetup(){let e="undefined"!=typeof window?"Browser":"Node",t="unknown",i="unknown";"undefined"!=typeof navigator&&(e=e+"/"+navigator.platform,t=navigator.userAgent,i=navigator.appVersion);const n=this.createRecognizerConfig(new r.SpeechServiceConfig(new r.Context(new r.OS(e,t,i))));this.privReco=this.createServiceRecognizer(a.getAuth(this.privProperties,this.tokenCredential),this.privConnectionFactory,this.audioConfig,n)}async recognizeOnceAsyncImpl(e){s.Contracts.throwIfDisposed(this.privDisposed);const t=new n.Deferred;await this.implRecognizerStop(),await this.privReco.recognize(e,t.resolve,t.reject);const i=await t.promise;return await this.implRecognizerStop(),i}async startContinuousRecognitionAsyncImpl(e){s.Contracts.throwIfDisposed(this.privDisposed),await this.implRecognizerStop(),await this.privReco.recognize(e,void 0,void 0)}async stopContinuousRecognitionAsyncImpl(){s.Contracts.throwIfDisposed(this.privDisposed),await this.implRecognizerStop()}async implRecognizerStop(){if(this.privReco){const e=this.privProperties.getProperty(o.PropertyId.Recognizer_StopTimeoutMs,void 0);if(void 0!==e&&""!==e){const t=parseInt(e,10);if(t>0){try{await this.withTimeout(this.privReco.stopRecognizing(),t,`Stop operation timed out after ${t}ms waiting for service to complete turn`)}catch(e){throw await this.privReco.disconnect(),e}return}}await this.privReco.stopRecognizing()}}withTimeout(e,t,i){return Promise.race([e,new Promise(((e,r)=>{setTimeout((()=>{r(new Error(i))}),t)}))])}static getAuth(e,t){const i=e.getProperty(o.PropertyId.SpeechServiceConnection_Key,void 0);return i&&""!==i?new r.CognitiveSubscriptionKeyAuthentication(i):t?new r.CognitiveTokenAuthentication((async()=>{try{const e=await t.getToken("https://cognitiveservices.azure.com/.default");return e?.token??""}catch(e){throw e}}),(async()=>{try{const e=await t.getToken("https://cognitiveservices.azure.com/.default");return e?.token??""}catch(e){throw e}})):new r.CognitiveTokenAuthentication((()=>{const t=e.getProperty(o.PropertyId.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(t)}),(()=>{const t=e.getProperty(o.PropertyId.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(t)}))}}t.Recognizer=a},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechRecognizer=void 0;const r=i(2),n=i(116),s=i(4),o=i(70),a=i(85);class c extends a.Recognizer{constructor(e,t){const i=e;o.Contracts.throwIfNull(i,"speechConfig"),o.Contracts.throwIfNullOrWhitespace(i.properties.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage),a.PropertyId[a.PropertyId.SpeechServiceConnection_RecoLanguage]),super(t,i.properties,new r.SpeechConnectionFactory,e.tokenCredential),this.privDisposedRecognizer=!1}static FromConfig(e,t,i){const r=e;t.properties.mergeTo(r.properties);return new c(e,i)}get endpointId(){return o.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(a.PropertyId.SpeechServiceConnection_EndpointId,"00000000-0000-0000-0000-000000000000")}get authorizationToken(){return this.properties.getProperty(a.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){o.Contracts.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(a.PropertyId.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return o.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage)}get outputFormat(){return o.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(r.OutputFormatPropertyName,a.OutputFormat[a.OutputFormat.Simple])===a.OutputFormat[a.OutputFormat.Simple]?a.OutputFormat.Simple:a.OutputFormat.Detailed}get properties(){return this.privProperties}recognizeOnceAsync(e,t){(0,s.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(n.RecognitionMode.Interactive),e,t)}startContinuousRecognitionAsync(e,t){(0,s.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(void 0===this.properties.getProperty(r.ForceDictationPropertyName,void 0)?n.RecognitionMode.Conversation:n.RecognitionMode.Dictation),e,t)}stopContinuousRecognitionAsync(e,t){(0,s.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(),e,t)}startKeywordRecognitionAsync(e,t,i){o.Contracts.throwIfNull(e,"model"),i&&i("Not yet implemented.")}stopKeywordRecognitionAsync(e){e&&e()}close(e,t){o.Contracts.throwIfDisposed(this.privDisposedRecognizer),(0,s.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}async dispose(e){this.privDisposedRecognizer||(e&&(this.privDisposedRecognizer=!0,await this.implRecognizerStop()),await super.dispose(e))}createRecognizerConfig(e){return new r.RecognizerConfig(e,this.privProperties)}createServiceRecognizer(e,t,i,n){const s=i;return new r.SpeechServiceRecognizer(e,t,s,n,this)}}t.SpeechRecognizer=c},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechStartEventSensitivity=t.RecognitionMode=void 0,function(e){e.Interactive="Interactive",e.Dictation="Dictation",e.Conversation="Conversation",e.None="None"}(t.RecognitionMode||(t.RecognitionMode={})),function(e){e.Low="low",e.Medium="medium",e.High="high"}(t.SpeechStartEventSensitivity||(t.SpeechStartEventSensitivity={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationRecognizer=void 0;const r=i(2),n=i(116),s=i(4),o=i(118),a=i(70),c=i(85);class p extends c.Recognizer{constructor(e,t,i){const n=e;a.Contracts.throwIfNull(n,"speechConfig"),super(t,n.properties,i||new r.TranslationConnectionFactory,e.tokenCredential),this.privDisposedTranslationRecognizer=!1,void 0!==this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationVoice,void 0)&&a.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationVoice),c.PropertyId[c.PropertyId.SpeechServiceConnection_TranslationVoice]),a.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages),c.PropertyId[c.PropertyId.SpeechServiceConnection_TranslationToLanguages]),void 0===this.properties.getProperty(c.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)&&a.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(c.PropertyId.SpeechServiceConnection_RecoLanguage),c.PropertyId[c.PropertyId.SpeechServiceConnection_RecoLanguage])}static FromConfig(e,t,i){const n=e;return t.properties.mergeTo(n.properties),t.properties.getProperty(c.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)===r.AutoDetectSourceLanguagesOpenRangeOptionName&&n.properties.setProperty(c.PropertyId.SpeechServiceConnection_RecoLanguage,"en-US"),new p(e,i)}get speechRecognitionLanguage(){return a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(c.PropertyId.SpeechServiceConnection_RecoLanguage)}get targetLanguages(){return a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",")}get voiceName(){return a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationVoice,void 0)}get properties(){return this.privProperties}get authorizationToken(){return this.properties.getProperty(c.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){this.properties.setProperty(c.PropertyId.SpeechServiceAuthorization_Token,e)}recognizeOnceAsync(e,t){a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),(0,s.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(n.RecognitionMode.Interactive),e,t)}startContinuousRecognitionAsync(e,t){(0,s.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(n.RecognitionMode.Conversation),e,t)}stopContinuousRecognitionAsync(e,t){(0,s.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(),e,t)}removeTargetLanguage(e){if(a.Contracts.throwIfNullOrUndefined(e,"language to be removed"),void 0!==this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0)){const t=this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","),i=t.indexOf(e);i>-1&&(t.splice(i,1),this.properties.setProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages,t.join(",")),this.updateLanguages(t))}}addTargetLanguage(e){a.Contracts.throwIfNullOrUndefined(e,"language to be added");let t=[];void 0!==this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages,void 0)?(t=this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","),t.includes(e)||(t.push(e),this.properties.setProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages,t.join(",")))):(this.properties.setProperty(c.PropertyId.SpeechServiceConnection_TranslationToLanguages,e),t=[e]),this.updateLanguages(t)}close(e,t){a.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer),(0,s.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}onConnection(){}async dispose(e){this.privDisposedTranslationRecognizer||(this.privDisposedTranslationRecognizer=!0,e&&(await this.implRecognizerStop(),await super.dispose(e)))}createRecognizerConfig(e){return new r.RecognizerConfig(e,this.privProperties)}createServiceRecognizer(e,t,i,n){const s=i;return new r.TranslationServiceRecognizer(e,t,s,n,this)}updateLanguages(e){const t=o.Connection.fromRecognizer(this);if(t){t.setMessageProperty("speech.context","translationcontext",{to:e});const i=this.properties.getProperty(c.PropertyId.SpeechServiceConnection_TranslationVoice,void 0);let r;if(i){const t={};for(const r of e)t[r]=i;r=JSON.stringify({id:"translation",name:"updateLanguage",synthesis:{defaultVoices:t},to:e})}else r=JSON.stringify({id:"translation",name:"updateLanguage",to:e});t.sendMessageAsync("event",r)}}}t.TranslationRecognizer=p},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Connection=void 0;const r=i(2),n=i(4),s=i(119),o=i(70),a=i(85);class c{static fromRecognizer(e){const t=e.internalData,i=new c;return i.privInternalData=t,i.setupEvents(),i}static fromSynthesizer(e){const t=e.internalData,i=new c;return i.privInternalData=t,i.setupEvents(),i}openConnection(e,t){(0,n.marshalPromiseToCallbacks)(this.privInternalData.connect(),e,t)}closeConnection(e,t){if(this.privInternalData instanceof r.SynthesisAdapterBase)throw new Error("Disconnecting a synthesizer's connection is currently not supported");(0,n.marshalPromiseToCallbacks)(this.privInternalData.disconnect(),e,t)}setMessageProperty(e,t,i){if(o.Contracts.throwIfNullOrWhitespace(t,"propertyName"),this.privInternalData instanceof r.ServiceRecognizerBase){if("speech.context"!==e.toLowerCase())throw new Error("Only speech.context message property sets are currently supported for recognizer");this.privInternalData.speechContext.getContext()[t]=i}else if(this.privInternalData instanceof r.SynthesisAdapterBase){if("speech.config"!==e.toLowerCase()&&"synthesis.context"!==e.toLowerCase())throw new Error("Only speech.config and synthesis.context message paths are currently supported for synthesizer");if("speech.config"===e.toLowerCase()){if("context"!==t.toLowerCase())throw new Error("Only context property is currently supported for speech.config message path for synthesizer");this.privInternalData.synthesizerConfig.setContextFromJson(i)}else this.privInternalData.synthesisContext.setSection(t,i)}}sendMessageAsync(e,t,i,r){(0,n.marshalPromiseToCallbacks)(this.privInternalData.sendNetworkMessage(e,t),i,r)}close(){}setupEvents(){this.privEventListener=this.privInternalData.connectionEvents.attach((e=>{"ConnectionEstablishedEvent"===e.name?this.connected&&this.connected(new a.ConnectionEventArgs(e.connectionId)):"ConnectionClosedEvent"===e.name?this.disconnected&&this.disconnected(new a.ConnectionEventArgs(e.connectionId)):"ConnectionMessageSentEvent"===e.name?this.messageSent&&this.messageSent(new a.ConnectionMessageEventArgs(new s.ConnectionMessageImpl(e.message))):"ConnectionMessageReceivedEvent"===e.name&&this.messageReceived&&this.messageReceived(new a.ConnectionMessageEventArgs(new s.ConnectionMessageImpl(e.message)))})),this.privServiceEventListener=this.privInternalData.serviceEvents.attach((e=>{this.receivedServiceMessage&&this.receivedServiceMessage(new a.ServiceEventArgs(e.jsonString,e.name))}))}}t.Connection=c},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionMessageImpl=t.ConnectionMessage=void 0;const r=i(59),n=i(4),s=i(112),o=i(113);t.ConnectionMessage=class{};t.ConnectionMessageImpl=class{constructor(e){this.privConnectionMessage=e,this.privProperties=new s.PropertyCollection,this.privConnectionMessage.headers[r.HeaderNames.ConnectionId]&&this.privProperties.setProperty(o.PropertyId.Speech_SessionId,this.privConnectionMessage.headers[r.HeaderNames.ConnectionId]),Object.keys(this.privConnectionMessage.headers).forEach((e=>{this.privProperties.setProperty(e,this.privConnectionMessage.headers[e])}))}get path(){return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find((e=>e.toLowerCase()==="path".toLowerCase()))]}get isTextMessage(){return this.privConnectionMessage.messageType===n.MessageType.Text}get isBinaryMessage(){return this.privConnectionMessage.messageType===n.MessageType.Binary}get TextMessage(){return this.privConnectionMessage.textBody}get binaryMessage(){return this.privConnectionMessage.binaryBody}get properties(){return this.privProperties}toString(){return""}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Translations=void 0;const r=i(85);t.Translations=class{constructor(){this.privMap=new r.PropertyCollection}get languages(){return this.privMap.keys}get(e,t){return this.privMap.getProperty(e,t)}set(e,t){this.privMap.setProperty(e,t)}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoMatchReason=void 0,function(e){e[e.NotRecognized=0]="NotRecognized",e[e.InitialSilenceTimeout=1]="InitialSilenceTimeout",e[e.InitialBabbleTimeout=2]="InitialBabbleTimeout"}(t.NoMatchReason||(t.NoMatchReason={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoMatchDetails=void 0;const r=i(2),n=i(85);class s{constructor(e){this.privReason=e}static fromResult(e){const t=r.SimpleSpeechPhrase.fromJSON(e.json,0);let i=n.NoMatchReason.NotRecognized;switch(t.RecognitionStatus){case r.RecognitionStatus.BabbleTimeout:i=n.NoMatchReason.InitialBabbleTimeout;break;case r.RecognitionStatus.InitialSilenceTimeout:i=n.NoMatchReason.InitialSilenceTimeout;break;default:i=n.NoMatchReason.NotRecognized}return new s(i)}get reason(){return this.privReason}}t.NoMatchDetails=s},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationRecognitionCanceledEventArgs=void 0;t.TranslationRecognitionCanceledEventArgs=class{constructor(e,t,i,r,n){this.privCancelReason=t,this.privErrorDetails=i,this.privResult=n,this.privSessionId=e,this.privErrorCode=r}get result(){return this.privResult}get sessionId(){return this.privSessionId}get reason(){return this.privCancelReason}get errorCode(){return this.privErrorCode}get errorDetails(){return this.privErrorDetails}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationDetailsBase=void 0;t.CancellationDetailsBase=class{constructor(e,t,i){this.privReason=e,this.privErrorDetails=t,this.privErrorCode=i}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get ErrorCode(){return this.privErrorCode}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationDetails=void 0;const r=i(2),n=i(124),s=i(85);class o extends n.CancellationDetailsBase{constructor(e,t,i){super(e,t,i)}static fromResult(e){let t=s.CancellationReason.Error,i=s.CancellationErrorCode.NoError;if(e instanceof s.RecognitionResult&&e.json){const i=r.SimpleSpeechPhrase.fromJSON(e.json,0);t=r.EnumTranslation.implTranslateCancelResult(i.RecognitionStatus)}return e.properties&&(i=s.CancellationErrorCode[e.properties.getProperty(r.CancellationErrorCodePropertyName,s.CancellationErrorCode[s.CancellationErrorCode.NoError])]),new o(t,e.errorDetails||r.EnumTranslation.implTranslateErrorDetails(i),i)}}t.CancellationDetails=o},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationErrorCode=void 0,function(e){e[e.NoError=0]="NoError",e[e.AuthenticationFailure=1]="AuthenticationFailure",e[e.BadRequestParameters=2]="BadRequestParameters",e[e.TooManyRequests=3]="TooManyRequests",e[e.ConnectionFailure=4]="ConnectionFailure",e[e.ServiceTimeout=5]="ServiceTimeout",e[e.ServiceError=6]="ServiceError",e[e.RuntimeError=7]="RuntimeError",e[e.Forbidden=8]="Forbidden"}(t.CancellationErrorCode||(t.CancellationErrorCode={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionEventArgs=void 0;const r=i(85);class n extends r.SessionEventArgs{}t.ConnectionEventArgs=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceEventArgs=void 0;const r=i(85);class n extends r.SessionEventArgs{constructor(e,t,i){super(i),this.privJsonResult=e,this.privEventName=t}get jsonString(){return this.privJsonResult}get eventName(){return this.privEventName}}t.ServiceEventArgs=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PhraseListGrammar=void 0;const r=i(70);class n{constructor(e){this.privGrammerBuilder=e.dynamicGrammar}static fromRecognizer(e){const t=e.internalData;return new n(t)}addPhrase(e){this.privGrammerBuilder.addPhrase(e)}addPhrases(e){this.privGrammerBuilder.addPhrase(e)}clear(){this.privGrammerBuilder.clearPhrases()}setWeight(e){r.Contracts.throwIfNumberOutOfRange(e,"weight",0,2),this.privGrammerBuilder.setWeight(e)}}t.PhraseListGrammar=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DialogServiceConfigImpl=t.DialogServiceConfig=void 0;const r=i(70),n=i(85);class s{constructor(){}set applicationId(e){}static get DialogTypes(){return{BotFramework:"bot_framework",CustomCommands:"custom_commands"}}}t.DialogServiceConfig=s;t.DialogServiceConfigImpl=class extends s{constructor(){super(),this.privSpeechConfig=new n.SpeechConfigImpl}get properties(){return this.privSpeechConfig.properties}get speechRecognitionLanguage(){return this.privSpeechConfig.speechRecognitionLanguage}set speechRecognitionLanguage(e){r.Contracts.throwIfNullOrWhitespace(e,"value"),this.privSpeechConfig.speechRecognitionLanguage=e}get outputFormat(){return this.privSpeechConfig.outputFormat}set outputFormat(e){this.privSpeechConfig.outputFormat=e}setProperty(e,t){this.privSpeechConfig.setProperty(e,t)}getProperty(e,t){return this.privSpeechConfig.getProperty(e)}setProxy(e,t,i,r){this.setProperty(n.PropertyId.SpeechServiceConnection_ProxyHostName,e),this.setProperty(n.PropertyId.SpeechServiceConnection_ProxyPort,`${t}`),i&&this.setProperty(n.PropertyId.SpeechServiceConnection_ProxyUserName,i),r&&this.setProperty(n.PropertyId.SpeechServiceConnection_ProxyPassword,r)}setServiceProperty(e,t,i){this.privSpeechConfig.setServiceProperty(e,t)}close(){}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BotFrameworkConfig=void 0;const r=i(70),n=i(130),s=i(85);class o extends n.DialogServiceConfigImpl{constructor(){super()}static fromSubscription(e,t,i){r.Contracts.throwIfNullOrWhitespace(e,"subscription"),r.Contracts.throwIfNullOrWhitespace(t,"region");const o=new n.DialogServiceConfigImpl;return o.setProperty(s.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.BotFramework),o.setProperty(s.PropertyId.SpeechServiceConnection_Key,e),o.setProperty(s.PropertyId.SpeechServiceConnection_Region,t),i&&o.setProperty(s.PropertyId.Conversation_ApplicationId,i),o}static fromAuthorizationToken(e,t,i){r.Contracts.throwIfNullOrWhitespace(e,"authorizationToken"),r.Contracts.throwIfNullOrWhitespace(t,"region");const o=new n.DialogServiceConfigImpl;return o.setProperty(s.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.BotFramework),o.setProperty(s.PropertyId.SpeechServiceAuthorization_Token,e),o.setProperty(s.PropertyId.SpeechServiceConnection_Region,t),i&&o.setProperty(s.PropertyId.Conversation_ApplicationId,i),o}static fromHost(e,t,i){r.Contracts.throwIfNullOrUndefined(e,"host");const o=e instanceof URL?e:new URL(`wss://${e}.convai.speech.azure.us`);r.Contracts.throwIfNullOrUndefined(o,"resolvedHost");const a=new n.DialogServiceConfigImpl;return a.setProperty(s.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.BotFramework),a.setProperty(s.PropertyId.SpeechServiceConnection_Host,o.toString()),void 0!==t&&a.setProperty(s.PropertyId.SpeechServiceConnection_Key,t),a}static fromEndpoint(e,t){r.Contracts.throwIfNull(e,"endpoint");const i=new n.DialogServiceConfigImpl;return i.setProperty(s.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.BotFramework),i.setProperty(s.PropertyId.SpeechServiceConnection_Endpoint,e.toString()),void 0!==t&&i.setProperty(s.PropertyId.SpeechServiceConnection_Key,t),i}}t.BotFrameworkConfig=o},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CustomCommandsConfig=void 0;const r=i(70),n=i(130),s=i(85);class o extends n.DialogServiceConfigImpl{constructor(){super()}static fromSubscription(e,t,i){r.Contracts.throwIfNullOrWhitespace(e,"applicationId"),r.Contracts.throwIfNullOrWhitespace(t,"subscription"),r.Contracts.throwIfNullOrWhitespace(i,"region");const o=new n.DialogServiceConfigImpl;return o.setProperty(s.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.CustomCommands),o.setProperty(s.PropertyId.Conversation_ApplicationId,e),o.setProperty(s.PropertyId.SpeechServiceConnection_Key,t),o.setProperty(s.PropertyId.SpeechServiceConnection_Region,i),o}static fromAuthorizationToken(e,t,i){r.Contracts.throwIfNullOrWhitespace(e,"applicationId"),r.Contracts.throwIfNullOrWhitespace(t,"authorizationToken"),r.Contracts.throwIfNullOrWhitespace(i,"region");const o=new n.DialogServiceConfigImpl;return o.setProperty(s.PropertyId.Conversation_DialogType,n.DialogServiceConfig.DialogTypes.CustomCommands),o.setProperty(s.PropertyId.Conversation_ApplicationId,e),o.setProperty(s.PropertyId.SpeechServiceAuthorization_Token,t),o.setProperty(s.PropertyId.SpeechServiceConnection_Region,i),o}set applicationId(e){r.Contracts.throwIfNullOrWhitespace(e,"value"),this.setProperty(s.PropertyId.Conversation_ApplicationId,e)}get applicationId(){return this.getProperty(s.PropertyId.Conversation_ApplicationId)}}t.CustomCommandsConfig=o},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DialogServiceConnector=void 0;const r=i(134),n=i(2),s=i(116),o=i(4),a=i(70),c=i(85),p=i(113);class u extends c.Recognizer{constructor(e,t){const i=e;a.Contracts.throwIfNull(e,"dialogConfig"),super(t,i.properties,new r.DialogConnectionFactory),this.isTurnComplete=!0,this.privIsDisposed=!1,this.privProperties=i.properties.clone();const n=this.buildAgentConfig();this.privReco.agentConfig.set(n)}connect(e,t){(0,o.marshalPromiseToCallbacks)(this.privReco.connect(),e,t)}disconnect(e,t){(0,o.marshalPromiseToCallbacks)(this.privReco.disconnect(),e,t)}get authorizationToken(){return this.properties.getProperty(p.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){a.Contracts.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(p.PropertyId.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get speechActivityTemplate(){return this.properties.getProperty(p.PropertyId.Conversation_Speech_Activity_Template)}set speechActivityTemplate(e){this.properties.setProperty(p.PropertyId.Conversation_Speech_Activity_Template,e)}listenOnceAsync(e,t){if(this.isTurnComplete){a.Contracts.throwIfDisposed(this.privIsDisposed);const i=(async()=>{await this.privReco.connect(),await this.implRecognizerStop(),this.isTurnComplete=!1;const e=new o.Deferred;await this.privReco.recognize(s.RecognitionMode.Conversation,e.resolve,e.reject);const t=await e.promise;return await this.implRecognizerStop(),t})();i.catch((()=>{this.dispose(!0).catch((()=>{}))})),(0,o.marshalPromiseToCallbacks)(i.finally((()=>{this.isTurnComplete=!0})),e,t)}}sendActivityAsync(e,t,i){(0,o.marshalPromiseToCallbacks)(this.privReco.sendMessage(e),t,i)}close(e,t){a.Contracts.throwIfDisposed(this.privIsDisposed),(0,o.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}async dispose(e){this.privIsDisposed||e&&(this.privIsDisposed=!0,await this.implRecognizerStop(),await super.dispose(e))}createRecognizerConfig(e){return new n.RecognizerConfig(e,this.privProperties)}createServiceRecognizer(e,t,i,r){const s=i;return new n.DialogServiceAdapter(e,t,s,r,this)}buildAgentConfig(){return{botInfo:{commType:this.properties.getProperty("Conversation_Communication_Type","Default"),commandsCulture:void 0,connectionId:this.properties.getProperty(p.PropertyId.Conversation_Agent_Connection_Id),conversationId:this.properties.getProperty(p.PropertyId.Conversation_Conversation_Id,void 0),fromId:this.properties.getProperty(p.PropertyId.Conversation_From_Id,void 0),ttsAudioFormat:this.properties.getProperty(p.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0)},version:.2}}}t.DialogServiceConnector=u},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DialogConnectionFactory=void 0;const r=i(66),n=i(2),s=i(85),o=i(135),a=i(2),c=i(59),p=i(136);class u extends o.ConnectionFactoryBase{create(e,t,i){const h=e.parameters.getProperty(s.PropertyId.Conversation_ApplicationId,""),d=e.parameters.getProperty(s.PropertyId.Conversation_DialogType),v=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Region),l=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage,"en-US"),g=e.parameters.getProperty(s.PropertyId.Conversation_Request_Bot_Status_Messages,"true"),S={};S[c.HeaderNames.ConnectionId]=i,S[p.QueryParameterNames.Format]=e.parameters.getProperty(n.OutputFormatPropertyName,s.OutputFormat[s.OutputFormat.Simple]).toLowerCase(),S[p.QueryParameterNames.Language]=l,S[p.QueryParameterNames.RequestBotStatusMessages]=g,h&&(S[p.QueryParameterNames.BotId]=h,d===s.DialogServiceConfig.DialogTypes.CustomCommands&&(S[c.HeaderNames.CustomCommandsAppId]=h));const f=d===s.DialogServiceConfig.DialogTypes.CustomCommands?"commands/":"",y=d===s.DialogServiceConfig.DialogTypes.CustomCommands?"v1":d===s.DialogServiceConfig.DialogTypes.BotFramework?"v3":"v0",m={};null!=t.token&&""!==t.token&&(m[t.headerName]=t.token);let C=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Endpoint,"");if(!C){const t=o.ConnectionFactoryBase.getHostSuffix(v),i=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Host,`wss://${v}.${u.BaseUrl}${t}`);C=`${i.endsWith("/")?i:i+"/"}${f}${u.ApiKey}/${y}`}this.setCommonUrlParams(e,S,C);const P="true"===e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false");return Promise.resolve(new r.WebsocketConnection(C,S,m,new a.WebsocketMessageFormatter,r.ProxyInfo.fromRecognizerConfig(e),P,i))}}t.DialogConnectionFactory=u,u.ApiKey="api",u.BaseUrl="convai.speech"},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionFactoryBase=void 0;const r=i(2),n=i(4),s=i(85),o=i(136);t.ConnectionFactoryBase=class{static getHostSuffix(e){if(e){if(e.toLowerCase().startsWith("china"))return".azure.cn";if(e.toLowerCase().startsWith("usgov"))return".azure.us"}return".microsoft.com"}setCommonUrlParams(e,t,i){new Map([[s.PropertyId.Speech_SegmentationSilenceTimeoutMs,o.QueryParameterNames.SegmentationSilenceTimeoutMs],[s.PropertyId.SpeechServiceConnection_EnableAudioLogging,o.QueryParameterNames.EnableAudioLogging],[s.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs,o.QueryParameterNames.EndSilenceTimeoutMs],[s.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs,o.QueryParameterNames.InitialSilenceTimeoutMs],[s.PropertyId.SpeechServiceResponse_ProfanityOption,o.QueryParameterNames.Profanity],[s.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,o.QueryParameterNames.EnableWordLevelTimestamps],[s.PropertyId.SpeechServiceResponse_StablePartialResultThreshold,o.QueryParameterNames.StableIntermediateThreshold]]).forEach(((r,n)=>{this.setUrlParameter(n,r,e,t,i)}));const n=JSON.parse(e.parameters.getProperty(r.ServicePropertiesPropertyName,"{}"));Object.keys(n).forEach((e=>{t[e]=n[e]}))}setUrlParameter(e,t,i,r,n){const s=i.parameters.getProperty(e,void 0);!s||n&&-1!==n.search(t)||(r[t]=s.toLocaleLowerCase())}static async getRedirectUrlFromEndpoint(e,t=!0){const i=new URL(e);i.protocol="https:",i.port="443";i.searchParams.append("GenerateRedirectResponse","true");const r=i.toString();n.Events.instance.onEvent(new n.ConnectionRedirectEvent("",r,void 0,"ConnectionFactoryBase: redirectUrl request"));const s=await fetch(r);if(200!==s.status)return e;const o=await s.text();n.Events.instance.onEvent(new n.ConnectionRedirectEvent("",o,e,"ConnectionFactoryBase: redirectUrlString"));try{const e=new URL(o.trim());return t&&("https:"===e.protocol?e.protocol="wss:":"http:"===e.protocol&&(e.protocol="ws:")),e.toString()}catch(t){return e}}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.QueryParameterNames=void 0;class i{}t.QueryParameterNames=i,i.BotId="botid",i.CustomSpeechDeploymentId="cid",i.CustomVoiceDeploymentId="deploymentId",i.EnableAudioLogging="storeAudio",i.EnableLanguageId="lidEnabled",i.EnableWordLevelTimestamps="wordLevelTimestamps",i.EndSilenceTimeoutMs="endSilenceTimeoutMs",i.SegmentationSilenceTimeoutMs="segmentationSilenceTimeoutMs",i.SegmentationMaximumTimeMs="segmentationMaximumTimeMs",i.SegmentationStrategy="segmentationStrategy",i.Format="format",i.InitialSilenceTimeoutMs="initialSilenceTimeoutMs",i.Language="language",i.Profanity="profanity",i.RequestBotStatusMessages="enableBotMessageStatus",i.StableIntermediateThreshold="stableIntermediateThreshold",i.StableTranslation="stableTranslation",i.TestHooks="testhooks",i.Postprocessing="postprocessing",i.CtsMeetingId="meetingId",i.CtsDeviceId="deviceId",i.CtsIsParticipant="isParticipant",i.EnableAvatar="enableTalkingAvatar"},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActivityReceivedEventArgs=void 0;t.ActivityReceivedEventArgs=class{constructor(e,t){this.privActivity=e,this.privAudioStream=t}get activity(){return this.privActivity}get audioStream(){return this.privAudioStream}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TurnStatusReceivedEventArgs=void 0;const r=i(139);t.TurnStatusReceivedEventArgs=class{constructor(e){this.privTurnStatus=r.TurnStatusResponsePayload.fromJSON(e)}get interactionId(){return this.privTurnStatus.interactionId}get conversationId(){return this.privTurnStatus.conversationId}get statusCode(){return this.privTurnStatus.statusCode}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TurnStatusResponsePayload=void 0;class i{constructor(e){this.privMessageStatusResponse=JSON.parse(e)}static fromJSON(e){return new i(e)}get interactionId(){return this.privMessageStatusResponse.interactionId}get conversationId(){return this.privMessageStatusResponse.conversationId}get statusCode(){switch(this.privMessageStatusResponse.statusCode){case"Success":return 200;case"Failed":return 400;case"TimedOut":return 429;default:return this.privMessageStatusResponse.statusCode}}}t.TurnStatusResponsePayload=i},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServicePropertyChannel=void 0,function(e){e[e.UriQueryParameter=0]="UriQueryParameter"}(t.ServicePropertyChannel||(t.ServicePropertyChannel={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProfanityOption=void 0,function(e){e[e.Masked=0]="Masked",e[e.Removed=1]="Removed",e[e.Raw=2]="Raw"}(t.ProfanityOption||(t.ProfanityOption={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseAudioPlayer=void 0;const r=i(31),n=i(85),s=i(73);t.BaseAudioPlayer=class{constructor(e){this.audioContext=null,this.gainNode=null,this.autoUpdateBufferTimer=0,void 0===e&&(e=n.AudioStreamFormat.getDefaultInputFormat()),this.init(e)}playAudioSample(e,t,i){try{this.ensureInitializedContext();const i=this.formatAudioData(e),r=new Float32Array(this.samples.length+i.length);r.set(this.samples,0),r.set(i,this.samples.length),this.samples=r,t&&t()}catch(e){i&&i(e)}}stopAudio(e,t){null!==this.audioContext&&(this.samples=new Float32Array,clearInterval(this.autoUpdateBufferTimer),this.audioContext.close().then((()=>{e&&e()}),(e=>{t&&t(e)})),this.audioContext=null)}init(e){this.audioFormat=e,this.samples=new Float32Array}ensureInitializedContext(){if(null===this.audioContext){this.createAudioContext();const e=200;this.autoUpdateBufferTimer=setInterval((()=>{this.updateAudioBuffer()}),e)}}createAudioContext(){this.audioContext=s.AudioStreamFormatImpl.getAudioContext(),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioContext.destination),this.startTime=this.audioContext.currentTime}formatAudioData(e){switch(this.audioFormat.bitsPerSample){case 8:return this.formatArrayBuffer(new Int8Array(e),128);case 16:return this.formatArrayBuffer(new Int16Array(e),32768);case 32:return this.formatArrayBuffer(new Int32Array(e),2147483648);default:throw new r.InvalidOperationError("Only WAVE_FORMAT_PCM (8/16/32 bps) format supported at this time")}}formatArrayBuffer(e,t){const i=new Float32Array(e.length);for(let r=0;r{t.buffer=e,t.connect(i),t.start(0)}))}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionMessageEventArgs=void 0;t.ConnectionMessageEventArgs=class{constructor(e){this.privConnectionMessage=e}get message(){return this.privConnectionMessage}toString(){return"Message: "+this.privConnectionMessage.toString()}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoDetectSourceLanguageConfig=void 0;const r=i(2),n=i(70),s=i(85),o=i(145);class a{constructor(){this.privProperties=new s.PropertyCollection,this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_LanguageIdMode,"AtStart"),this.privLanguageIdMode=o.LanguageIdMode.AtStart}static fromOpenRange(){const e=new a;return e.properties.setProperty(s.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,r.AutoDetectSourceLanguagesOpenRangeOptionName),e.properties.setProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage,"en-US"),e}static fromLanguages(e){n.Contracts.throwIfArrayEmptyOrWhitespace(e,"languages");const t=new a;return t.properties.setProperty(s.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,e.join()),t}static fromSourceLanguageConfigs(e){if(e.length<1)throw new Error("Expected non-empty SourceLanguageConfig array.");const t=new a,i=[];return e.forEach((e=>{if(i.push(e.language),void 0!==e.endpointId&&""!==e.endpointId){const i=e.language+s.PropertyId.SpeechServiceConnection_EndpointId.toString();t.properties.setProperty(i,e.endpointId)}})),t.properties.setProperty(s.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,i.join()),t}get properties(){return this.privProperties}set mode(e){e===o.LanguageIdMode.Continuous?(this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,"2"),this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_LanguageIdMode,"Continuous")):(this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,"1"),this.privProperties.setProperty(s.PropertyId.SpeechServiceConnection_LanguageIdMode,"AtStart")),this.privLanguageIdMode=e}}t.AutoDetectSourceLanguageConfig=a},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LanguageIdMode=void 0,function(e){e[e.AtStart=0]="AtStart",e[e.Continuous=1]="Continuous"}(t.LanguageIdMode||(t.LanguageIdMode={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoDetectSourceLanguageResult=void 0;const r=i(70);class n{constructor(e,t){r.Contracts.throwIfNullOrUndefined(e,"language"),r.Contracts.throwIfNullOrUndefined(t,"languageDetectionConfidence"),this.privLanguage=e,this.privLanguageDetectionConfidence=t}static fromResult(e){return new n(e.language,e.languageDetectionConfidence)}static fromConversationTranscriptionResult(e){return new n(e.language,e.languageDetectionConfidence)}get language(){return this.privLanguage}get languageDetectionConfidence(){return this.privLanguageDetectionConfidence}}t.AutoDetectSourceLanguageResult=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SourceLanguageConfig=void 0;const r=i(70);class n{constructor(e,t){r.Contracts.throwIfNullOrUndefined(e,"language"),this.privLanguage=e,this.privEndpointId=t}static fromLanguage(e,t){return new n(e,t)}get language(){return this.privLanguage}get endpointId(){return this.privEndpointId}}t.SourceLanguageConfig=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationTranscriptionResult=t.MeetingTranscriber=t.MeetingTranscriptionCanceledEventArgs=t.MeetingImpl=t.Meeting=t.User=t.Participant=t.ConversationTranscriber=void 0;var r=i(149);Object.defineProperty(t,"ConversationTranscriber",{enumerable:!0,get:function(){return r.ConversationTranscriber}});var n=i(150);Object.defineProperty(t,"Participant",{enumerable:!0,get:function(){return n.Participant}}),Object.defineProperty(t,"User",{enumerable:!0,get:function(){return n.User}});var s=i(151);Object.defineProperty(t,"Meeting",{enumerable:!0,get:function(){return s.Meeting}}),Object.defineProperty(t,"MeetingImpl",{enumerable:!0,get:function(){return s.MeetingImpl}});var o=i(152);Object.defineProperty(t,"MeetingTranscriptionCanceledEventArgs",{enumerable:!0,get:function(){return o.MeetingTranscriptionCanceledEventArgs}});var a=i(153);Object.defineProperty(t,"MeetingTranscriber",{enumerable:!0,get:function(){return a.MeetingTranscriber}});var c=i(154);Object.defineProperty(t,"ConversationTranscriptionResult",{enumerable:!0,get:function(){return c.ConversationTranscriptionResult}})},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationTranscriber=void 0;const r=i(2),n=i(116),s=i(4),o=i(70),a=i(85);class c extends a.Recognizer{constructor(e,t){const i=e;o.Contracts.throwIfNull(i,"speechConfig"),o.Contracts.throwIfNullOrWhitespace(i.properties.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage),a.PropertyId[a.PropertyId.SpeechServiceConnection_RecoLanguage]),super(t,i.properties,new r.ConversationTranscriberConnectionFactory,e.tokenCredential),this.privProperties.setProperty(a.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,"2"),this.privDisposedRecognizer=!1}static FromConfig(e,t,i){const r=e;t.properties.mergeTo(r.properties);return new c(e,i)}get endpointId(){return o.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(a.PropertyId.SpeechServiceConnection_EndpointId,"00000000-0000-0000-0000-000000000000")}get authorizationToken(){return this.properties.getProperty(a.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){o.Contracts.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(a.PropertyId.SpeechServiceAuthorization_Token,e)}get speechRecognitionLanguage(){return o.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage)}get outputFormat(){return o.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(r.OutputFormatPropertyName,a.OutputFormat[a.OutputFormat.Simple])===a.OutputFormat[a.OutputFormat.Simple]?a.OutputFormat.Simple:a.OutputFormat.Detailed}get properties(){return this.privProperties}startTranscribingAsync(e,t){(0,s.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(n.RecognitionMode.Conversation),e,t)}stopTranscribingAsync(e,t){(0,s.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(),e,t)}close(e,t){o.Contracts.throwIfDisposed(this.privDisposedRecognizer),(0,s.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}async dispose(e){this.privDisposedRecognizer||(e&&(this.privDisposedRecognizer=!0,await this.implRecognizerStop()),await super.dispose(e))}createRecognizerConfig(e){return new r.RecognizerConfig(e,this.privProperties)}createServiceRecognizer(e,t,i,n){const s=i;return n.isSpeakerDiarizationEnabled=!0,new r.ConversationTranscriptionServiceRecognizer(e,t,s,n,this)}}t.ConversationTranscriber=c},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Participant=t.User=void 0;const r=i(85);t.User=class{constructor(e){this.privUserId=e}get userId(){return this.privUserId}};class n{constructor(e,t,i){this.privId=e,this.privPreferredLanguage=t,this.privVoice=i,this.privProperties=new r.PropertyCollection}get id(){return this.privId}get preferredLanguage(){return this.privPreferredLanguage}get voice(){return this.privVoice}get properties(){return this.privProperties}static From(e,t,i){return new n(e,t,i)}}t.Participant=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MeetingImpl=t.Meeting=void 0;const r=i(2),n=i(4),s=i(70),o=i(85);class a{constructor(){}static createMeetingAsync(e,t,i,a){if(s.Contracts.throwIfNullOrUndefined(e,r.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}","config")),s.Contracts.throwIfNullOrUndefined(e.region,r.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}","SpeechServiceConnection_Region")),s.Contracts.throwIfNull(t,"meetingId"),0===t.length)throw new Error("meetingId cannot be empty");e.subscriptionKey||e.getProperty(o.PropertyId[o.PropertyId.SpeechServiceAuthorization_Token])||s.Contracts.throwIfNullOrUndefined(e.subscriptionKey,r.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}","SpeechServiceConnection_Key"));const p=new c(e,t);return(0,n.marshalPromiseToCallbacks)((async()=>{})(),i,a),p}}t.Meeting=a;class c extends a{constructor(e,t){super(),this.privErrors=r.ConversationConnectionConfig.restErrors,this.privIsDisposed=!1,this.privMeetingId="",this.privProperties=new o.PropertyCollection;e.getProperty(o.PropertyId[o.PropertyId.SpeechServiceConnection_RecoLanguage])||e.setProperty(o.PropertyId[o.PropertyId.SpeechServiceConnection_RecoLanguage],r.ConversationConnectionConfig.defaultLanguageCode),this.privLanguage=e.getProperty(o.PropertyId[o.PropertyId.SpeechServiceConnection_RecoLanguage]),this.privMeetingId=t,this.privConfig=e;const i=e;s.Contracts.throwIfNull(i,"speechConfig"),this.privProperties=i.properties.clone(),this.privParticipants=new r.InternalParticipants}get config(){return this.privConfig}get meetingId(){return this.privMeetingId}get properties(){return this.privProperties}get speechRecognitionLanguage(){return this.privLanguage}get participants(){return this.privParticipants.participants.map((e=>this.toParticipant(e)))}get transcriberRecognizer(){return this.privTranscriberRecognizer}get meetingInfo(){const e=this.meetingId,t=this.participants.map((e=>({id:e.id,preferredLanguage:e.preferredLanguage,voice:e.voice}))),i={};for(const e of r.ConversationConnectionConfig.transcriptionEventKeys){const t=this.properties.getProperty(e,"");""!==t&&(i[e]=t)}return{id:e,participants:t,meetingProperties:i}}get authorizationToken(){return this.privToken}set authorizationToken(e){s.Contracts.throwIfNullOrWhitespace(e,"authorizationToken"),this.privToken=e}addParticipantAsync(e,t,i){s.Contracts.throwIfNullOrUndefined(e,"Participant"),(0,n.marshalPromiseToCallbacks)(this.addParticipantImplAsync(e),t,i)}removeParticipantAsync(e,t,i){s.Contracts.throwIfDisposed(this.privIsDisposed),s.Contracts.throwIfNullOrUndefined(this.privTranscriberRecognizer,"Recognizer"),s.Contracts.throwIfNullOrUndefined(e,this.privErrors.invalidArgs.replace("{arg}","userId")),(0,n.marshalPromiseToCallbacks)(this.removeParticipantImplAsync(e),t,i)}isDisposed(){return this.privIsDisposed}dispose(){this.isDisposed||(this.privIsDisposed=!0,this.config&&this.config.close(),this.privConfig=void 0,this.privLanguage=void 0,this.privProperties=void 0,this.privToken=void 0,this.privParticipants=void 0)}async connectTranscriberRecognizer(e){this.privTranscriberRecognizer&&await this.privTranscriberRecognizer.close(),await e.enforceAudioGating(),this.privTranscriberRecognizer=e,this.privTranscriberRecognizer.meeting=this}addParticipantImplAsync(e){if(void 0!==this.privParticipants.addOrUpdateParticipant(e)&&this.privTranscriberRecognizer){const t=this.meetingInfo;return t.participants=[e],this.privTranscriberRecognizer.pushMeetingEvent(t,"join")}}removeParticipantImplAsync(e){this.privParticipants.deleteParticipant(e.id);const t=this.meetingInfo;return t.participants=[e],this.privTranscriberRecognizer.pushMeetingEvent(t,"leave")}toParticipant(e){return new o.Participant(e.id,e.preferredLanguage,e.voice)}}t.MeetingImpl=c},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MeetingTranscriptionCanceledEventArgs=void 0;const r=i(104);class n extends r.CancellationEventArgsBase{}t.MeetingTranscriptionCanceledEventArgs=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MeetingTranscriber=void 0;const r=i(2),n=i(4),s=i(70),o=i(85),a=i(148);t.MeetingTranscriber=class{constructor(e){this.privAudioConfig=e,this.privProperties=new o.PropertyCollection,this.privRecognizer=void 0,this.privDisposedRecognizer=!1}get speechRecognitionLanguage(){return s.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(o.PropertyId.SpeechServiceConnection_RecoLanguage)}get properties(){return this.privProperties}get internalData(){return this.privRecognizer.internalData}get connection(){return o.Connection.fromRecognizer(this.privRecognizer)}get authorizationToken(){return this.properties.getProperty(o.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){s.Contracts.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(o.PropertyId.SpeechServiceAuthorization_Token,e)}joinMeetingAsync(e,t,i){const o=e;s.Contracts.throwIfNullOrUndefined(a.MeetingImpl,"Meeting"),this.privRecognizer=new r.TranscriberRecognizer(e.config,this.privAudioConfig),s.Contracts.throwIfNullOrUndefined(this.privRecognizer,"Recognizer"),this.privRecognizer.connectMeetingCallbacks(this),(0,n.marshalPromiseToCallbacks)(o.connectTranscriberRecognizer(this.privRecognizer),t,i)}startTranscribingAsync(e,t){this.privRecognizer.startContinuousRecognitionAsync(e,t)}stopTranscribingAsync(e,t){this.privRecognizer.stopContinuousRecognitionAsync(e,t)}leaveMeetingAsync(e,t){this.privRecognizer.disconnectCallbacks(),(0,n.marshalPromiseToCallbacks)((async()=>{})(),e,t)}close(e,t){s.Contracts.throwIfDisposed(this.privDisposedRecognizer),(0,n.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}async dispose(e){this.privDisposedRecognizer||(this.privRecognizer&&(await this.privRecognizer.close(),this.privRecognizer=void 0),e&&(this.privDisposedRecognizer=!0))}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationTranscriptionResult=void 0;const r=i(85);class n extends r.RecognitionResult{constructor(e,t,i,r,n,s,o,a,c,p,u){super(e,t,i,r,n,s,o,c,p,u),this.privSpeakerId=a}get speakerId(){return this.privSpeakerId}}t.ConversationTranscriptionResult=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StreamingSynthesisRequest=t.SynthesisRequest=t.Synthesizer=void 0;const r=i(2),n=i(4),s=i(70),o=i(85);class a{constructor(e){const t=e;s.Contracts.throwIfNull(t,"speechConfig"),this.privProperties=t.properties.clone(),this.privDisposed=!1,this.privSynthesizing=!1,this.synthesisRequestQueue=new n.Queue,this.tokenCredential=e.tokenCredential}get authorizationToken(){return this.properties.getProperty(o.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){s.Contracts.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(o.PropertyId.SpeechServiceAuthorization_Token,e)}get properties(){return this.privProperties}get autoDetectSourceLanguage(){return this.properties.getProperty(o.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages)===r.AutoDetectSourceLanguagesOpenRangeOptionName}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-AvaMultilingualNeural","en-ZA":"en-ZA-LeahNeural","es-AR":"es-AR-ElenaNeural","es-BO":"es-BO-MarceloNeural","es-CL":"es-CL-CatalinaNeural","es-CO":"es-CO-GonzaloNeural","es-CR":"es-CR-JuanNeural","es-CU":"es-CU-BelkysNeural","es-DO":"es-DO-EmilioNeural","es-EC":"es-EC-AndreaNeural","es-ES":"es-ES-AlvaroNeural","es-GQ":"es-GQ-JavierNeural","es-GT":"es-GT-AndresNeural","es-HN":"es-HN-CarlosNeural","es-MX":"es-MX-DaliaNeural","es-NI":"es-NI-FedericoNeural","es-PA":"es-PA-MargaritaNeural","es-PE":"es-PE-AlexNeural","es-PR":"es-PR-KarinaNeural","es-PY":"es-PY-MarioNeural","es-SV":"es-SV-LorenaNeural","es-US":"es-US-AlonsoNeural","es-UY":"es-UY-MateoNeural","es-VE":"es-VE-PaolaNeural","et-EE":"et-EE-AnuNeural","fa-IR":"fa-IR-DilaraNeural","fi-FI":"fi-FI-SelmaNeural","fil-PH":"fil-PH-AngeloNeural","fr-BE":"fr-BE-CharlineNeural","fr-CA":"fr-CA-SylvieNeural","fr-CH":"fr-CH-ArianeNeural","fr-FR":"fr-FR-DeniseNeural","ga-IE":"ga-IE-ColmNeural","gl-ES":"gl-ES-RoiNeural","gu-IN":"gu-IN-DhwaniNeural","he-IL":"he-IL-AvriNeural","hi-IN":"hi-IN-MadhurNeural","hr-HR":"hr-HR-GabrijelaNeural","hu-HU":"hu-HU-NoemiNeural","id-ID":"id-ID-ArdiNeural","is-IS":"is-IS-GudrunNeural","it-IT":"it-IT-IsabellaNeural","ja-JP":"ja-JP-NanamiNeural","jv-ID":"jv-ID-DimasNeural","kk-KZ":"kk-KZ-AigulNeural","km-KH":"km-KH-PisethNeural","kn-IN":"kn-IN-GaganNeural","ko-KR":"ko-KR-SunHiNeural","lo-LA":"lo-LA-ChanthavongNeural","lt-LT":"lt-LT-LeonasNeural","lv-LV":"lv-LV-EveritaNeural","mk-MK":"mk-MK-AleksandarNeural","ml-IN":"ml-IN-MidhunNeural","mr-IN":"mr-IN-AarohiNeural","ms-MY":"ms-MY-OsmanNeural","mt-MT":"mt-MT-GraceNeural","my-MM":"my-MM-NilarNeural","nb-NO":"nb-NO-PernilleNeural","nl-BE":"nl-BE-ArnaudNeural","nl-NL":"nl-NL-ColetteNeural","pl-PL":"pl-PL-AgnieszkaNeural","ps-AF":"ps-AF-GulNawazNeural","pt-BR":"pt-BR-FranciscaNeural","pt-PT":"pt-PT-DuarteNeural","ro-RO":"ro-RO-AlinaNeural","ru-RU":"ru-RU-SvetlanaNeural","si-LK":"si-LK-SameeraNeural","sk-SK":"sk-SK-LukasNeural","sl-SI":"sl-SI-PetraNeural","so-SO":"so-SO-MuuseNeural","sr-RS":"sr-RS-NicholasNeural","su-ID":"su-ID-JajangNeural","sv-SE":"sv-SE-SofieNeural","sw-KE":"sw-KE-RafikiNeural","sw-TZ":"sw-TZ-DaudiNeural","ta-IN":"ta-IN-PallaviNeural","ta-LK":"ta-LK-KumarNeural","ta-SG":"ta-SG-AnbuNeural","te-IN":"te-IN-MohanNeural","th-TH":"th-TH-PremwadeeNeural","tr-TR":"tr-TR-AhmetNeural","uk-UA":"uk-UA-OstapNeural","ur-IN":"ur-IN-GulNeural","ur-PK":"ur-PK-AsadNeural","uz-UZ":"uz-UZ-MadinaNeural","vi-VN":"vi-VN-HoaiMyNeural","zh-CN":"zh-CN-XiaoxiaoNeural","zh-HK":"zh-HK-HiuMaanNeural","zh-TW":"zh-TW-HsiaoChenNeural","zu-ZA":"zu-ZA-ThandoNeural"};let i=this.properties.getProperty(o.PropertyId.SpeechServiceConnection_SynthLanguage,"en-US"),r=this.properties.getProperty(o.PropertyId.SpeechServiceConnection_SynthVoice,""),n=a.XMLEncode(e);return this.autoDetectSourceLanguage?i="en-US":r=r||t[i],r&&(n=`${n}`),n=`${n}`,n}async dispose(e){this.privDisposed||(e&&this.privAdapter&&await this.privAdapter.dispose(),this.privDisposed=!0)}async adapterSpeak(){if(!this.privDisposed&&!this.privSynthesizing){this.privSynthesizing=!0;const e=await this.synthesisRequestQueue.dequeue();return e instanceof c?this.privAdapter.SpeakStream(e.speechSynthesisRequest,e.requestId,e.cb,e.err,e.dataStream):this.privAdapter.Speak(e.text,e.isSSML,e.requestId,e.cb,e.err,e.dataStream)}}createSynthesizerConfig(e){return new r.SynthesizerConfig(e,this.privProperties)}implCommonSynthesizeSetup(){let e="undefined"!=typeof window?"Browser":"Node",t="unknown",i="unknown";"undefined"!=typeof navigator&&(e=e+"/"+navigator.platform,t=navigator.userAgent,i=navigator.appVersion);const n=this.createSynthesizerConfig(new r.SpeechServiceConfig(new r.Context(new r.OS(e,t,i)))),s=this.privProperties.getProperty(o.PropertyId.SpeechServiceConnection_Key,void 0),a=s&&""!==s?new r.CognitiveSubscriptionKeyAuthentication(s):this.tokenCredential?new r.CognitiveTokenAuthentication((async()=>{try{const e=await this.tokenCredential.getToken("https://cognitiveservices.azure.com/.default");return e?.token??""}catch(e){throw e}}),(async()=>{try{const e=await this.tokenCredential.getToken("https://cognitiveservices.azure.com/.default");return e?.token??""}catch(e){throw e}})):new r.CognitiveTokenAuthentication((()=>{const e=this.privProperties.getProperty(o.PropertyId.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(e)}),(()=>{const e=this.privProperties.getProperty(o.PropertyId.SpeechServiceAuthorization_Token,void 0);return Promise.resolve(e)}));this.privAdapter=this.createSynthesisAdapter(a,this.privConnectionFactory,n),this.privRestAdapter=this.createRestSynthesisAdapter(a,n)}static XMLEncode(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}}t.Synthesizer=a;t.SynthesisRequest=class{constructor(e,t,i,r,n,s){this.requestId=e,this.text=t,this.isSSML=i,this.cb=r??(()=>{}),this.err=n??(()=>{}),this.dataStream=s??void 0}};class c{constructor(e,t,i,r,n){this.requestId=e,this.speechSynthesisRequest=t,this.cb=i??(()=>{}),this.err=r??(()=>{}),this.dataStream=n??void 0}}t.StreamingSynthesisRequest=c},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesizer=void 0;const r=i(2),n=i(4),s=i(87),o=i(91),a=i(90),c=i(70),p=i(85),u=i(155);class h extends p.Synthesizer{constructor(e,t){super(e),null!==t&&(this.audioConfig=void 0===t?"undefined"==typeof window?void 0:p.AudioConfig.fromDefaultSpeakerOutput():t),this.privConnectionFactory=new r.SpeechSynthesisConnectionFactory,this.implCommonSynthesizeSetup()}static FromConfig(e,t,i){const r=e;return t.properties.mergeTo(r.properties),new h(e,i)}speakTextAsync(e,t,i,r){this.speakImpl(e,!1,t,i,r)}speakSsmlAsync(e,t,i,r){this.speakImpl(e,!0,t,i,r)}speakAsync(e,t,i,r){try{c.Contracts.throwIfDisposed(this.privDisposed);const s=(0,n.createNoDashGuid)(),o=this.resolveAudioDestination(r),{onSuccess:a,onError:p}=this.createSynthesisCallbacks(t,i,(()=>{this.adapterSpeak().catch((()=>{}))}));this.synthesisRequestQueue.enqueue(new u.StreamingSynthesisRequest(s,e,a,p,o)),this.adapterSpeak().catch((()=>{}))}catch(e){this.handleSpeakError(e,i)}}async getVoicesAsync(e=""){return this.getVoices(e)}close(e,t){c.Contracts.throwIfDisposed(this.privDisposed),(0,n.marshalPromiseToCallbacks)(this.dispose(!0),e,t)}get internalData(){return this.privAdapter}createSynthesisAdapter(e,t,i){return new r.SpeechSynthesisAdapter(e,t,i,this,this.audioConfig)}createRestSynthesisAdapter(e,t){return new r.SynthesisRestAdapter(t,e)}implCommonSynthesizeSetup(){super.implCommonSynthesizeSetup(),this.privAdapter.audioOutputFormat=o.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(p.SpeechSynthesisOutputFormat[this.properties.getProperty(p.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0)])}speakImpl(e,t,i,r,s){try{c.Contracts.throwIfDisposed(this.privDisposed);const o=(0,n.createNoDashGuid)(),a=this.resolveAudioDestination(s),{onSuccess:p,onError:h}=this.createSynthesisCallbacks(i,r,(()=>{this.adapterSpeak().catch((()=>{}))}));this.synthesisRequestQueue.enqueue(new u.SynthesisRequest(o,e,t,p,h,a)),this.adapterSpeak().catch((()=>{}))}catch(e){this.handleSpeakError(e,r)}}resolveAudioDestination(e){return e instanceof p.PushAudioOutputStreamCallback?new a.PushAudioOutputStreamImpl(e):e instanceof p.PullAudioOutputStream?e:void 0!==e?new s.AudioFileWriter(e):void 0}createSynthesisCallbacks(e,t,i){let r=e;return{onError:e=>{this.privSynthesizing=!1,t&&t(e),i&&i()},onSuccess:e=>{if(this.privSynthesizing=!1,r)try{r(e)}catch(e){t&&t(e)}r=void 0,i&&i()}}}handleSpeakError(e,t){if(t)if(e instanceof Error){const i=e;t(i.name+": "+i.message)}else t(e);this.dispose(!0).catch((()=>{}))}async getVoices(e){const t=(0,n.createNoDashGuid)(),i=await this.privRestAdapter.getVoicesList(t);if(i.ok&&Array.isArray(i.json)){let r=i.json;return e&&e.length>0&&(r=r.filter((t=>!!t.Locale&&t.Locale.toLowerCase()===e.toLowerCase()))),new p.SynthesisVoicesResult(t,r,void 0)}return new p.SynthesisVoicesResult(t,void 0,`Error: ${i.status}: ${i.statusText}`)}}t.SpeechSynthesizer=h},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesisResult=void 0;t.SynthesisResult=class{constructor(e,t,i,r){this.privResultId=e,this.privReason=t,this.privErrorDetails=i,this.privProperties=r}get resultId(){return this.privResultId}get reason(){return this.privReason}get errorDetails(){return this.privErrorDetails}get properties(){return this.privProperties}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisResult=void 0;const r=i(85);class n extends r.SynthesisResult{constructor(e,t,i,r,n,s){super(e,t,r,n),this.privAudioData=i,this.privAudioDuration=s}get audioData(){return this.privAudioData}get audioDuration(){return this.privAudioDuration}}t.SpeechSynthesisResult=n},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisEventArgs=void 0;t.SpeechSynthesisEventArgs=class{constructor(e){this.privResult=e}get result(){return this.privResult}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisWordBoundaryEventArgs=void 0;t.SpeechSynthesisWordBoundaryEventArgs=class{constructor(e,t,i,r,n,s){this.privAudioOffset=e,this.privDuration=t,this.privText=i,this.privWordLength=r,this.privTextOffset=n,this.privBoundaryType=s}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}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisBookmarkEventArgs=void 0;t.SpeechSynthesisBookmarkEventArgs=class{constructor(e,t){this.privAudioOffset=e,this.privText=t}get audioOffset(){return this.privAudioOffset}get text(){return this.privText}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisVisemeEventArgs=void 0;t.SpeechSynthesisVisemeEventArgs=class{constructor(e,t,i){this.privAudioOffset=e,this.privVisemeId=t,this.privAnimation=i}get audioOffset(){return this.privAudioOffset}get visemeId(){return this.privVisemeId}get animation(){return this.privAnimation}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisBoundaryType=void 0,function(e){e.Word="WordBoundary",e.Punctuation="PunctuationBoundary",e.Sentence="SentenceBoundary"}(t.SpeechSynthesisBoundaryType||(t.SpeechSynthesisBoundaryType={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisRequest=t.SpeechSynthesisRequestInputStream=void 0;const r=i(85),n=i(165),s=i(166);var o=i(166);Object.defineProperty(t,"SpeechSynthesisRequestInputStream",{enumerable:!0,get:function(){return o.SpeechSynthesisRequestInputStream}});t.SpeechSynthesisRequest=class{constructor(e){if(this.privBufferedTextPieces=[],this.privStreamClosedBeforeReady=!1,e!==n.SpeechSynthesisRequestInputType.TextStream)throw new Error("Only TextStream input type is supported in this version.");this.privInputType=e,this.privInputStream=new s.SpeechSynthesisRequestInputStream(this),this.privProperties=new r.PropertyCollection}get inputType(){return this.privInputType}get inputStream(){return this.privInputStream}get properties(){return this.privProperties}set pitch(e){this.privProperties.setProperty(r.PropertyId.SpeechSynthesisRequest_Pitch,e)}set rate(e){this.privProperties.setProperty(r.PropertyId.SpeechSynthesisRequest_Rate,e)}set volume(e){this.privProperties.setProperty(r.PropertyId.SpeechSynthesisRequest_Volume,e)}set style(e){this.privProperties.setProperty(r.PropertyId.SpeechSynthesisRequest_Style,e)}set temperature(e){this.privProperties.setProperty(r.PropertyId.SpeechSynthesisRequest_Temperature,e.toString())}set customLexiconUrl(e){this.privProperties.setProperty(r.PropertyId.SpeechSynthesisRequest_CustomLexiconUrl,e)}set preferLocales(e){this.privProperties.setProperty(r.PropertyId.SpeechSynthesisRequest_PreferLocales,e)}onTextPieceReceived(e){this.privTextPieceCallback?this.privTextPieceCallback(e):this.privBufferedTextPieces.push(e)}onInputStreamClosed(){this.privStreamCloseCallback?this.privStreamCloseCallback():this.privStreamClosedBeforeReady=!0}set onTextPiece(e){this.privTextPieceCallback=e;for(const t of this.privBufferedTextPieces)e(t);this.privBufferedTextPieces=[]}set onClose(e){this.privStreamCloseCallback=e,this.privStreamClosedBeforeReady&&(this.privStreamClosedBeforeReady=!1,e())}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisRequestInputType=void 0,function(e){e[e.Text=1]="Text",e[e.SSML=2]="SSML",e[e.TextStream=3]="TextStream"}(t.SpeechSynthesisRequestInputType||(t.SpeechSynthesisRequestInputType={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisRequestInputStream=void 0;t.SpeechSynthesisRequestInputStream=class{constructor(e){this.privClosed=!1,this.privParent=e}write(e){if(this.privClosed)throw new Error("Cannot write to a closed input stream.");this.privParent.onTextPieceReceived(e)}close(){this.privClosed||(this.privClosed=!0,this.privParent.onInputStreamClosed())}get isClosed(){return this.privClosed}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesisVoicesResult=void 0;const r=i(85);class n extends r.SynthesisResult{constructor(e,t,i){if(Array.isArray(t)){super(e,r.ResultReason.VoicesListRetrieved,void 0,new r.PropertyCollection),this.privVoices=[];for(const e of t)this.privVoices.push(new r.VoiceInfo(e))}else super(e,r.ResultReason.Canceled,i||"Error information unavailable",new r.PropertyCollection)}get voices(){return this.privVoices}}t.SynthesisVoicesResult=n},(e,t)=>{"use strict";var i,r;Object.defineProperty(t,"__esModule",{value:!0}),t.VoiceInfo=t.SynthesisVoiceType=t.SynthesisVoiceGender=void 0,function(e){e[e.Unknown=0]="Unknown",e[e.Female=1]="Female",e[e.Male=2]="Male",e[e.Neutral=3]="Neutral"}(i=t.SynthesisVoiceGender||(t.SynthesisVoiceGender={})),function(e){e[e.Unknown=0]="Unknown",e[e.OnlineNeural=1]="OnlineNeural",e[e.OnlineStandard=2]="OnlineStandard",e[e.OfflineNeural=3]="OfflineNeural",e[e.OfflineStandard=4]="OfflineStandard",e[e.OnlineNeuralHD=5]="OnlineNeuralHD"}(r=t.SynthesisVoiceType||(t.SynthesisVoiceType={}));const n={[i[i.Neutral]]:i.Neutral,[i[i.Male]]:i.Male,[i[i.Female]]:i.Female},s={Neural:r.OnlineNeural,NeuralHD:r.OnlineNeuralHD};t.VoiceInfo=class{constructor(e){if(this.privStyleList=[],e){if(this.privName=e.Name,this.privLocale=e.Locale,this.privShortName=e.ShortName,this.privLocaleName=e.LocaleName,this.privDisplayName=e.DisplayName,this.privLocalName=e.LocalName,this.privVoiceType=s[e.VoiceType]||r.Unknown,this.privGender=n[e.Gender]||i.Unknown,e.StyleList&&Array.isArray(e.StyleList))for(const t of e.StyleList)this.privStyleList.push(t);this.privSampleRateHertz=e.SampleRateHertz,this.privStatus=e.Status,e.ExtendedPropertyMap&&(this.privExtendedPropertyMap=e.ExtendedPropertyMap),this.privWordsPerMinute=e.WordsPerMinute,Array.isArray(e.SecondaryLocaleList)&&(this.privSecondaryLocaleList=[...e.SecondaryLocaleList]),Array.isArray(e.RolePlayList)&&(this.privRolePlayList=[...e.RolePlayList]),e.VoiceTag&&(this.privVoiceTag=e.VoiceTag)}}get name(){return this.privName}get locale(){return this.privLocale}get shortName(){return this.privShortName}get displayName(){return this.privDisplayName}get localName(){return this.privLocalName}get localeName(){return this.privLocaleName}get gender(){return this.privGender}get voiceType(){return this.privVoiceType}get styleList(){return this.privStyleList}get sampleRateHertz(){return this.privSampleRateHertz}get status(){return this.privStatus}get extendedPropertyMap(){return this.privExtendedPropertyMap}get wordsPerMinute(){return this.privWordsPerMinute}get secondaryLocaleList(){return this.privSecondaryLocaleList}get rolePlayList(){return this.privRolePlayList}get voiceTag(){return this.privVoiceTag}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeakerAudioDestination=void 0;const r=i(4),n=i(90),s=i(73),o={[s.AudioFormatTag.PCM]:"audio/wav",[s.AudioFormatTag.MuLaw]:"audio/x-wav",[s.AudioFormatTag.MP3]:"audio/mpeg",[s.AudioFormatTag.OGG_OPUS]:"audio/ogg",[s.AudioFormatTag.WEBM_OPUS]:"audio/webm; codecs=opus",[s.AudioFormatTag.ALaw]:"audio/x-wav",[s.AudioFormatTag.FLAC]:"audio/flac",[s.AudioFormatTag.AMR_WB]:"audio/amr-wb",[s.AudioFormatTag.G722]:"audio/G722"};t.SpeakerAudioDestination=class{constructor(e){this.privPlaybackStarted=!1,this.privAppendingToBuffer=!1,this.privMediaSourceOpened=!1,this.privBytesReceived=0,this.privId=e||(0,r.createNoDashGuid)(),this.privIsPaused=!1,this.privIsClosed=!1}id(){return this.privId}write(e,t,i){void 0!==this.privAudioBuffer?(this.privAudioBuffer.push(e),this.updateSourceBuffer().then((()=>{t&&t()}),(e=>{i&&i(e)}))):void 0!==this.privAudioOutputStream&&(this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength)}close(e,t){if(this.privIsClosed=!0,void 0!==this.privSourceBuffer)this.handleSourceBufferUpdateEnd().then((()=>{e&&e()}),(e=>{t&&t(e)}));else if(void 0!==this.privAudioOutputStream&&"undefined"!=typeof window)if(this.privFormat.formatTag!==s.AudioFormatTag.PCM&&this.privFormat.formatTag!==s.AudioFormatTag.MuLaw&&this.privFormat.formatTag!==s.AudioFormatTag.ALaw||!1!==this.privFormat.hasHeader){let i=new ArrayBuffer(this.privBytesReceived);this.privAudioOutputStream.read(i).then((()=>{i=this.privFormat.addHeader(i);const r=new Blob([i],{type:o[this.privFormat.formatTag]});this.privAudio.src=window.URL.createObjectURL(r),this.notifyPlayback().then((()=>{e&&e()}),(e=>{t&&t(e)}))}),(e=>{t&&t(e)}))}else console.warn("Play back is not supported for raw PCM, mulaw or alaw format without header."),this.onAudioEnd&&this.onAudioEnd(this);else this.onAudioEnd&&this.onAudioEnd(this)}set format(e){if("undefined"!=typeof AudioContext||"undefined"!=typeof window&&void 0!==window.webkitAudioContext){this.privFormat=e;const t=o[this.privFormat.formatTag];void 0===t?console.warn(`Unknown mimeType for format ${s.AudioFormatTag[this.privFormat.formatTag]}; playback is not supported.`):"undefined"!=typeof MediaSource&&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=1800,this.privSourceBuffer=this.privMediaSource.addSourceBuffer(t),this.privSourceBuffer.onupdate=()=>{this.updateSourceBuffer().catch((e=>{r.Events.instance.onEvent(new r.BackgroundEvent(e))}))},this.privSourceBuffer.onupdateend=()=>{this.handleSourceBufferUpdateEnd().catch((e=>{r.Events.instance.onEvent(new r.BackgroundEvent(e))}))},this.privSourceBuffer.onupdatestart=()=>{this.privAppendingToBuffer=!1}},this.updateSourceBuffer().catch((e=>{r.Events.instance.onEvent(new r.BackgroundEvent(e))}))):(console.warn(`Format ${s.AudioFormatTag[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`),this.privAudioOutputStream=new n.PullAudioOutputStreamImpl,this.privAudioOutputStream.format=this.privFormat,this.privAudio=new Audio)}}get volume(){return this.privAudio?.volume??-1}set volume(e){this.privAudio&&(this.privAudio.volume=e)}mute(){this.privAudio&&(this.privAudio.muted=!0)}unmute(){this.privAudio&&(this.privAudio.muted=!1)}get isClosed(){return this.privIsClosed}get currentTime(){return void 0!==this.privAudio?this.privAudio.currentTime:-1}pause(){this.privIsPaused||void 0===this.privAudio||(this.privAudio.pause(),this.privIsPaused=!0)}resume(e,t){this.privIsPaused&&void 0!==this.privAudio&&(this.privAudio.play().then((()=>{e&&e()}),(e=>{t&&t(e)})),this.privIsPaused=!1)}get internalAudio(){return this.privAudio}async updateSourceBuffer(){if(void 0!==this.privAudioBuffer&&this.privAudioBuffer.length>0&&this.sourceBufferAvailable()){this.privAppendingToBuffer=!0;const e=this.privAudioBuffer.shift();try{this.privSourceBuffer.appendBuffer(e)}catch(t){return this.privAudioBuffer.unshift(e),void console.log("buffer filled, pausing addition of binaries until space is made")}await this.notifyPlayback()}else this.canEndStream()&&await this.handleSourceBufferUpdateEnd()}async handleSourceBufferUpdateEnd(){this.canEndStream()&&this.sourceBufferAvailable()&&(this.privMediaSource.endOfStream(),await this.notifyPlayback())}async notifyPlayback(){this.privPlaybackStarted||void 0===this.privAudio||(this.privPlaybackStarted=!0,this.onAudioStart&&this.onAudioStart(this),this.privAudio.onended=()=>{this.onAudioEnd&&this.onAudioEnd(this)},this.privIsPaused||await this.privAudio.play())}canEndStream(){return this.isClosed&&void 0!==this.privSourceBuffer&&0===this.privAudioBuffer.length&&this.privMediaSourceOpened&&!this.privAppendingToBuffer&&"open"===this.privMediaSource.readyState}sourceBufferAvailable(){return void 0!==this.privSourceBuffer&&!this.privSourceBuffer.updating}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationTranscriptionCanceledEventArgs=void 0;const r=i(104);class n extends r.CancellationEventArgsBase{}t.ConversationTranscriptionCanceledEventArgs=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MeetingTranscriptionCanceledEventArgs=void 0;const r=i(104);class n extends r.CancellationEventArgsBase{}t.MeetingTranscriptionCanceledEventArgs=n},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PronunciationAssessmentGradingSystem=void 0,function(e){e[e.FivePoint=1]="FivePoint",e[e.HundredMark=2]="HundredMark"}(t.PronunciationAssessmentGradingSystem||(t.PronunciationAssessmentGradingSystem={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PronunciationAssessmentGranularity=void 0,function(e){e[e.Phoneme=1]="Phoneme",e[e.Word=2]="Word",e[e.FullText=3]="FullText"}(t.PronunciationAssessmentGranularity||(t.PronunciationAssessmentGranularity={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PronunciationAssessmentConfig=void 0;const r=i(70),n=i(85);class s{constructor(e,t=n.PronunciationAssessmentGradingSystem.FivePoint,i=n.PronunciationAssessmentGranularity.Phoneme,s=!1){r.Contracts.throwIfNullOrUndefined(e,"referenceText"),this.privProperties=new n.PropertyCollection,this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_ReferenceText,e),this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_GradingSystem,n.PronunciationAssessmentGradingSystem[t]),this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_Granularity,n.PronunciationAssessmentGranularity[i]),this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_EnableMiscue,String(s))}static fromJSON(e){r.Contracts.throwIfNullOrUndefined(e,"json");const t=new s("");return t.privProperties=new n.PropertyCollection,t.properties.setProperty(n.PropertyId.PronunciationAssessment_Json,e),t}toJSON(){return this.updateJson(),this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_Params)}applyTo(e){this.updateJson();const t=e.internalData;t.speechContext.setPronunciationAssessmentParams(this.properties.getProperty(n.PropertyId.PronunciationAssessment_Params),t.isSpeakerDiarizationEnabled)}get referenceText(){return this.properties.getProperty(n.PropertyId.PronunciationAssessment_ReferenceText)}set referenceText(e){r.Contracts.throwIfNullOrWhitespace(e,"referenceText"),this.properties.setProperty(n.PropertyId.PronunciationAssessment_ReferenceText,e)}set phonemeAlphabet(e){r.Contracts.throwIfNullOrWhitespace(e,"phonemeAlphabet"),this.privPhonemeAlphabet=e}set enableMiscue(e){const t=e?"true":"false";this.properties.setProperty(n.PropertyId.PronunciationAssessment_EnableMiscue,t)}get enableMiscue(){return"true"===this.properties.getProperty(n.PropertyId.PronunciationAssessment_EnableMiscue,"false").toLowerCase()}set nbestPhonemeCount(e){this.privNBestPhonemeCount=e}set enableProsodyAssessment(e){this.privEnableProsodyAssessment=e}get properties(){return this.privProperties}updateJson(){const e=this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_Json,"{}"),t=JSON.parse(e),i=this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_ReferenceText);i&&(t.referenceText=i);const r=this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_GradingSystem);r&&(t.gradingSystem=r);const s=this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_Granularity);s&&(t.granularity=s),this.privPhonemeAlphabet&&(t.phonemeAlphabet=this.privPhonemeAlphabet),this.privNBestPhonemeCount&&(t.nbestPhonemeCount=this.privNBestPhonemeCount),t.enableProsodyAssessment=this.privEnableProsodyAssessment,t.dimension="Comprehensive";this.privProperties.getProperty(n.PropertyId.PronunciationAssessment_EnableMiscue)&&(t.enableMiscue=this.enableMiscue),this.privProperties.setProperty(n.PropertyId.PronunciationAssessment_Params,JSON.stringify(t))}}t.PronunciationAssessmentConfig=s},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PronunciationAssessmentResult=void 0;const r=i(70),n=i(85);class s{constructor(e){const t=JSON.parse(e);r.Contracts.throwIfNullOrUndefined(t.NBest[0],"NBest"),this.privPronJson=t.NBest[0]}static fromResult(e){r.Contracts.throwIfNullOrUndefined(e,"result");const t=e.properties.getProperty(n.PropertyId.SpeechServiceResponse_JsonResult);return r.Contracts.throwIfNullOrUndefined(t,"json"),new s(t)}get detailResult(){return this.privPronJson}get accuracyScore(){return this.detailResult.PronunciationAssessment?.AccuracyScore}get pronunciationScore(){return this.detailResult.PronunciationAssessment?.PronScore}get completenessScore(){return this.detailResult.PronunciationAssessment?.CompletenessScore}get fluencyScore(){return this.detailResult.PronunciationAssessment?.FluencyScore}get prosodyScore(){return this.detailResult.PronunciationAssessment?.ProsodyScore}}t.PronunciationAssessmentResult=s},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AvatarConfig=void 0;const r=i(70),n=i(85);t.AvatarConfig=class{constructor(e,t,i){this.privCustomized=!1,this.privUseBuiltInVoice=!1,r.Contracts.throwIfNullOrWhitespace(e,"character"),this.character=e,this.style=t,void 0===i&&(i=new n.AvatarVideoFormat),this.videoFormat=i}get customized(){return this.privCustomized}set customized(e){this.privCustomized=e}get useBuiltInVoice(){return this.privUseBuiltInVoice}set useBuiltInVoice(e){this.privUseBuiltInVoice=e}get photoAvatarBaseModel(){return this.privPhotoAvatarBaseModel}set photoAvatarBaseModel(e){this.privPhotoAvatarBaseModel=e}get backgroundColor(){return this.privBackgroundColor}set backgroundColor(e){this.privBackgroundColor=e}get backgroundImage(){return this.privBackgroundImage}set backgroundImage(e){this.privBackgroundImage=e}get remoteIceServers(){return this.privRemoteIceServers}set remoteIceServers(e){this.privRemoteIceServers=e}get scene(){return this.privScene}set scene(e){this.privScene=e}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AvatarEventArgs=t.AvatarEventTypes=void 0,function(e){e.SwitchedToSpeaking="SwitchedToSpeaking",e.SwitchedToIdle="SwitchedToIdle",e.SessionClosed="SessionClosed"}(t.AvatarEventTypes||(t.AvatarEventTypes={}));t.AvatarEventArgs=class{constructor(e,t){this.privOffset=e,this.privDescription=t}get type(){return this.privType}get offset(){return this.privOffset}get description(){return this.privDescription}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AvatarSceneConfig=void 0;t.AvatarSceneConfig=class{constructor(e=1,t=0,i=0,r=0,n=0,s=0,o=1){this.zoom=e,this.positionX=t,this.positionY=i,this.rotationX=r,this.rotationY=n,this.rotationZ=s,this.amplitude=o}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AvatarSynthesizer=void 0;const r=i(180),n=i(2),s=i(4),o=i(91),a=i(85),c=i(70),p=i(155);class u extends a.Synthesizer{constructor(e,t){super(e),c.Contracts.throwIfNullOrUndefined(t,"avatarConfig"),this.privConnectionFactory=new r.SpeechSynthesisConnectionFactory,this.privAvatarConfig=t,this.implCommonSynthesizeSetup()}implCommonSynthesizeSetup(){super.implCommonSynthesizeSetup(),this.privAdapter.audioOutputFormat=o.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(a.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm)}async startAvatarAsync(e){c.Contracts.throwIfNullOrUndefined(e,"peerConnection"),this.privIceServers=e.getConfiguration().iceServers,c.Contracts.throwIfNullOrUndefined(this.privIceServers,"Ice servers must be set.");const t=new s.Deferred;e.onicegatheringstatechange=()=>{s.Events.instance.onEvent(new s.PlatformEvent("peer connection: ice gathering state: "+e.iceGatheringState,s.EventType.Debug)),"complete"===e.iceGatheringState&&(s.Events.instance.onEvent(new s.PlatformEvent("peer connection: ice gathering complete.",s.EventType.Info)),t.resolve())},e.onicecandidate=e=>{e.candidate?s.Events.instance.onEvent(new s.PlatformEvent("peer connection: ice candidate: "+e.candidate.candidate,s.EventType.Debug)):(s.Events.instance.onEvent(new s.PlatformEvent("peer connection: ice candidate: complete",s.EventType.Debug)),t.resolve())},setTimeout((()=>{"complete"!==e.iceGatheringState&&(s.Events.instance.onEvent(new s.PlatformEvent("peer connection: ice gathering timeout.",s.EventType.Warning)),t.resolve())}),2e3);const i=await e.createOffer();await e.setLocalDescription(i),await t.promise,s.Events.instance.onEvent(new s.PlatformEvent("peer connection: got local SDP.",s.EventType.Info)),this.privProperties.setProperty(a.PropertyId.TalkingAvatarService_WebRTC_SDP,JSON.stringify(e.localDescription));const r=await this.speak("",!1);if(r.reason!==a.ResultReason.SynthesizingAudioCompleted)return new a.SynthesisResult(r.resultId,r.reason,r.errorDetails,r.properties);const n=atob(r.properties.getProperty(a.PropertyId.TalkingAvatarService_WebRTC_SDP)),o=new RTCSessionDescription(JSON.parse(n));return await e.setRemoteDescription(o),new a.SynthesisResult(r.resultId,r.reason,void 0,r.properties)}async speakTextAsync(e){const t=await this.speak(e,!1);return new a.SynthesisResult(t.resultId,t.reason,t.errorDetails,t.properties)}async speakSsmlAsync(e){const t=await this.speak(e,!0);return new a.SynthesisResult(t.resultId,t.reason,t.errorDetails,t.properties)}async stopSpeakingAsync(){for(;this.synthesisRequestQueue.length()>0;){(await this.synthesisRequestQueue.dequeue()).err("Synthesis is canceled by user.")}return this.privAdapter.stopSpeaking()}async updateSceneAsync(e){c.Contracts.throwIfDisposed(this.privDisposed),c.Contracts.throwIfNullOrUndefined(e,"sceneConfig");const t={avatarScene:{amplitude:e.amplitude,positionX:e.positionX,positionY:e.positionY,rotationX:e.rotationX,rotationY:e.rotationY,rotationZ:e.rotationZ,zoom:e.zoom}};return this.privAdapter.sendNetworkMessage("synthesis.control",JSON.stringify(t))}async stopAvatarAsync(){return c.Contracts.throwIfDisposed(this.privDisposed),this.dispose(!0)}async close(){if(!this.privDisposed)return this.dispose(!0)}get iceServers(){return this.privIceServers}createSynthesisAdapter(e,t,i){return new n.AvatarSynthesisAdapter(e,t,i,this,this.privAvatarConfig)}createRestSynthesisAdapter(e,t){}createSynthesizerConfig(e){const t=super.createSynthesizerConfig(e);return t.avatarEnabled=!0,t}async speak(e,t){const i=(0,s.createNoDashGuid)(),r=new s.Deferred;return this.synthesisRequestQueue.enqueue(new p.SynthesisRequest(i,e,t,(e=>{r.resolve(e),this.privSynthesizing=!1,this.adapterSpeak()}),(e=>{r.reject(e),this.privSynthesizing=!1}))),this.adapterSpeak(),r.promise}}t.AvatarSynthesizer=u},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisConnectionFactory=void 0;const r=i(66),n=i(85),s=i(135),o=i(2),a=i(59),c=i(136);t.SpeechSynthesisConnectionFactory=class{constructor(){this.synthesisUri="/tts/cognitiveservices/websocket/v1"}async create(e,t,i){let p=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Endpoint,void 0);const u=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Region,void 0),h=s.ConnectionFactoryBase.getHostSuffix(u),d=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_EndpointId,void 0),v=void 0===d?"tts":"voice",l=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Host,"wss://"+u+"."+v+".speech"+h),g={},S={};if(void 0!==t.token&&""!==t.token&&(S[t.headerName]=t.token),S[a.HeaderNames.ConnectionId]=i,void 0!==d&&""!==d&&(p&&-1!==p.search(c.QueryParameterNames.CustomVoiceDeploymentId)||(g[c.QueryParameterNames.CustomVoiceDeploymentId]=d)),e.avatarEnabled&&(p&&-1!==p.search(c.QueryParameterNames.EnableAvatar)||(g[c.QueryParameterNames.EnableAvatar]="true")),p){const e=new URL(p),t=e.pathname;""!==t&&"/"!==t&&t.toLowerCase()!==this.synthesisUri||(e.pathname=this.synthesisUri,p=await s.ConnectionFactoryBase.getRedirectUrlFromEndpoint(e.toString()))}p||(p=l+this.synthesisUri),e.parameters.setProperty(n.PropertyId.SpeechServiceConnection_Url,p);const f="true"===e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false");return new r.WebsocketConnection(p,g,S,new o.WebsocketMessageFormatter,r.ProxyInfo.fromParameters(e.parameters),f,i)}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AvatarVideoFormat=t.Coordinate=void 0;t.Coordinate=class{constructor(e,t){this.x=e,this.y=t}};t.AvatarVideoFormat=class{constructor(e="H264",t=2e6,i=1920,r=1080){this.codec=e,this.bitrate=t,this.width=i,this.height=r}setCropRange(e,t){this.cropRange={bottomRight:t,topLeft:e}}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AvatarWebRTCConnectionResult=void 0;const r=i(85);class n extends r.SynthesisResult{constructor(e,t,i,r,n){super(t,i,r,n),this.privSDPAnswer=e}get SDPAnswer(){return this.privSDPAnswer}}t.AvatarWebRTCConnectionResult=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Diagnostics=void 0;const r=i(66),n=i(4);class s{static SetLoggingLevel(e){this.privListener=new r.ConsoleLoggingListener(e),n.Events.instance.attachConsoleListener(this.privListener)}static StartConsoleOutput(){this.privListener&&(this.privListener.enableConsoleOutput=!0)}static StopConsoleOutput(){this.privListener&&(this.privListener.enableConsoleOutput=!1)}static SetLogOutputPath(e){if("undefined"!=typeof window)throw new Error("File system logging not available in browser.");this.privListener&&(this.privListener.logPath=e)}static set onLogOutput(e){this.privListener&&(this.privListener.logCallback=e)}}t.Diagnostics=s,s.privListener=void 0},function(e,t,i){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RestMessageAdapter=t.RestRequestType=void 0;const n=r(i(185)),s=i(4);var o;!function(e){e.Get="GET",e.Post="POST",e.Delete="DELETE",e.File="file"}(o=t.RestRequestType||(t.RestRequestType={}));t.RestMessageAdapter=class{constructor(e){if(!e)throw new s.ArgumentNullError("configParams");this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}static extractHeaderValue(e,t){let i="";try{const r=t.trim().split(/[\r\n]+/),n={};r.forEach((e=>{const t=e.split(": "),i=t.shift().toLowerCase(),r=t.join(": ");n[i]=r})),i=n[e.toLowerCase()]}catch(e){}return i}set options(e){this.privHeaders=e.headers,this.privIgnoreCache=e.ignoreCache}setHeaders(e,t){this.privHeaders[e]=t}request(e,t,i={},r=null){const a=new s.Deferred,c=e===o.File?"POST":e,p=(e,t={})=>{const i=e;return{data:JSON.stringify(t),headers:JSON.stringify(e.headers),json:t,ok:e.statusCode>=200&&e.statusCode<300,status:e.statusCode,statusText:t.error?t.error.message:i.statusText?i.statusText:i.statusMessage}};return this.privIgnoreCache&&(this.privHeaders["Cache-Control"]="no-cache"),e===o.Post&&r&&(this.privHeaders["content-type"]="application/json",this.privHeaders["Content-Type"]="application/json"),(r=>{(0,n.default)(t,c,this.privHeaders,200,201,202,204,400,401,402,403,404)(""===this.queryParams(i)?"":`?${this.queryParams(i)}`,r).then((async t=>{if(e===o.Delete||204===t.statusCode)a.resolve(p(t));else try{const e=await t.json();a.resolve(p(t,e))}catch{a.resolve(p(t))}})).catch((e=>{a.reject(e)}))})(r),a.promise}queryParams(e={}){return Object.keys(e).map((t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t]))).join("&")}}},(e,t,i)=>{"use strict";const r=i(186);class n extends Error{constructor(e,...t){let i;super(...t),Error.captureStackTrace&&Error.captureStackTrace(this,n),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);Object.defineProperty(this,"responseBody",{get:()=>(i||(i=this.arrayBuffer()),i)}),this.headers={};for(const[t,i]of e.headers.entries())this.headers[t.toLowerCase()]=i}}e.exports=r(((e,t,i,r,s)=>async(o,a,c={})=>{o=s+(o||"");let p=new URL(o);if(r||(r={}),p.username&&(r.Authorization="Basic "+btoa(p.username+":"+p.password),p=new URL(p.protocol+"//"+p.host+p.pathname+p.search)),"https:"!==p.protocol&&"http:"!==p.protocol)throw new Error(`Unknown protocol, ${p.protocol}`);if(a)if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)||"string"==typeof a);else{if("object"!=typeof a)throw new Error("Unknown body type.");a=JSON.stringify(a),r["Content-Type"]="application/json"}c=new Headers({...r||{},...c});const u=await fetch(p,{method:t,headers:c,body:a});if(u.statusCode=u.status,!e.has(u.status))throw new n(u);return"json"===i?u.json():"buffer"===i?u.arrayBuffer():"string"===i?u.text():u}))},e=>{"use strict";const t=new Set(["json","buffer","string"]);e.exports=e=>(...i)=>{const r=new Set;let n,s,o,a="";return i.forEach((e=>{if("string"==typeof e)if(e.toUpperCase()===e){if(n){throw new Error(`Can't set method to ${e}, already set to ${n}.`)}n=e}else if(e.startsWith("http:")||e.startsWith("https:"))a=e;else{if(!t.has(e))throw new Error(`Unknown encoding, ${e}`);s=e}else if("number"==typeof e)r.add(e);else{if("object"!=typeof e)throw new Error("Unknown type: "+typeof e);if(Array.isArray(e)||e instanceof Set)e.forEach((e=>r.add(e)));else{if(o)throw new Error("Cannot set headers twice.");o=e}}})),n||(n="GET"),0===r.size&&r.add(200),e(r,n,s,o,a)}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RestConfigBase=void 0;class i{static get requestOptions(){return i.privDefaultRequestOptions}static get configParams(){return i.privDefaultParams}static get restErrors(){return i.privRestErrors}}t.RestConfigBase=i,i.privDefaultRequestOptions={headers:{Accept:"application/json"},ignoreCache:!1,timeout:1e4},i.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."},i.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"}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechConnectionMessage=void 0;const r=i(4),n=i(59);class s extends r.ConnectionMessage{constructor(e,t,i,s,o,a,c,p){if(!t)throw new r.ArgumentNullError("path");if(!i)throw new r.ArgumentNullError("requestId");const u={};if(u[n.HeaderNames.Path]=t,u[n.HeaderNames.RequestId]=i,u[n.HeaderNames.RequestTimestamp]=(new Date).toISOString(),s&&(u[n.HeaderNames.ContentType]=s),a&&(u[n.HeaderNames.RequestStreamId]=a),c)for(const e in c)e&&(u[e]=c[e]);p?super(e,o,u,p):super(e,o,u),this.privPath=t,this.privRequestId=i,this.privContentType=s,this.privStreamId=a,this.privAdditionalHeaders=c}get path(){return this.privPath}get requestId(){return this.privRequestId}get contentType(){return this.privContentType}get streamId(){return this.privStreamId}get additionalHeaders(){return this.privAdditionalHeaders}static fromConnectionMessage(e){let t=null,i=null,r=null,o=null;const a={};if(e.headers)for(const s in e.headers)s&&(s.toLowerCase()===n.HeaderNames.Path.toLowerCase()?t=e.headers[s]:s.toLowerCase()===n.HeaderNames.RequestId.toLowerCase()?i=e.headers[s]:s.toLowerCase()===n.HeaderNames.ContentType.toLowerCase()?r=e.headers[s]:s.toLowerCase()===n.HeaderNames.RequestStreamId.toLowerCase()?o=e.headers[s]:a[s]=e.headers[s]);return new s(e.messageType,t,i,r,e.body,o,a,e.id)}}t.SpeechConnectionMessage=s},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SegmentationMode=void 0,function(e){e.Normal="Normal",e.Disabled="Disabled",e.Custom="Custom",e.Semantic="Semantic"}(t.SegmentationMode||(t.SegmentationMode={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NextAction=void 0,function(e){e.None="None",e.Synthesize="Synthesize"}(t.NextAction||(t.NextAction={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Mode=void 0,function(e){e.None="None",e.Always="Always"}(t.Mode||(t.Mode={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LanguageIdDetectionPriority=t.LanguageIdDetectionMode=void 0,function(e){e.DetectAtAudioStart="DetectAtAudioStart",e.DetectContinuous="DetectContinuous",e.DetectSegments="DetectSegments"}(t.LanguageIdDetectionMode||(t.LanguageIdDetectionMode={})),function(e){e.Auto="Auto",e.PrioritizeLatency="PrioritizeLatency",e.PrioritizeAccuracy="PrioritizeAccuracy"}(t.LanguageIdDetectionPriority||(t.LanguageIdDetectionPriority={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NextAction=void 0,function(e){e.Recognize="Recognize",e.None="None"}(t.NextAction||(t.NextAction={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OnUnknownAction=void 0,function(e){e.RecognizeWithDefaultLanguage="RecognizeWithDefaultLanguage",e.None="None"}(t.OnUnknownAction||(t.OnUnknownAction={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ResultType=void 0,function(e){e.Auto="Auto",e.StableFragment="StableFragment",e.Hypothesis="Hypothesis",e.None="None"}(t.ResultType||(t.ResultType={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PhraseResultOutputType=void 0,function(e){e.Always="Always",e.None="None"}(t.PhraseResultOutputType||(t.PhraseResultOutputType={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NextAction=void 0,function(e){e.None="None",e.Translate="Translate"}(t.NextAction||(t.NextAction={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InteractivePunctuationMode=void 0,function(e){e.None="None",e.Implicit="Implicit",e.Explicit="Explicit",e.Intelligent="Intelligent"}(t.InteractivePunctuationMode||(t.InteractivePunctuationMode={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationPunctuationMode=void 0,function(e){e.None="None",e.Intelligent="Intelligent",e.Implicit="Implicit",e.Explicit="Explicit"}(t.ConversationPunctuationMode||(t.ConversationPunctuationMode={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DictationPunctuationMode=void 0,function(e){e.None="None",e.Intelligent="Intelligent",e.Implicit="Implicit",e.Explicit="Explicit"}(t.DictationPunctuationMode||(t.DictationPunctuationMode={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DisfluencyMode=void 0,function(e){e.Raw="Raw",e.Removed="Removed",e.Labeled="Labeled"}(t.DisfluencyMode||(t.DisfluencyMode={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationServiceRecognizer=void 0;const r=i(85),n=i(2);class s extends n.ServiceRecognizerBase{constructor(e,t,i,r,n){super(e,t,i,r,n),this.handleSpeechPhraseMessage=async e=>this.handleSpeechPhrase(e),this.handleSpeechHypothesisMessage=e=>this.handleSpeechHypothesis(e)}processTypeSpecificMessages(e){}handleRecognizedCallback(e,t,i){}handleRecognizingCallback(e,t,i){}async processSpeechMessages(e){let t=!1;switch(e.path.toLowerCase()){case"speech.hypothesis":case"speech.fragment":this.handleSpeechHypothesisMessage&&this.handleSpeechHypothesisMessage(e.textBody),t=!0;break;case"speech.phrase":this.handleSpeechPhraseMessage&&await this.handleSpeechPhraseMessage(e.textBody),t=!0}return t}cancelRecognition(e,t,i,r,n){}async handleSpeechPhrase(e){const t=n.SimpleSpeechPhrase.fromJSON(e,this.privRequestSession.currentTurnAudioOffset),i=n.EnumTranslation.implTranslateRecognitionResult(t.RecognitionStatus);let s;const o=new r.PropertyCollection;if(o.setProperty(r.PropertyId.SpeechServiceResponse_JsonResult,e),this.privRequestSession.onPhraseRecognized(t.Offset+t.Duration),r.ResultReason.Canceled===i){const e=n.EnumTranslation.implTranslateCancelResult(t.RecognitionStatus),i=n.EnumTranslation.implTranslateCancelErrorCode(t.RecognitionStatus);await this.cancelRecognitionLocal(e,i,n.EnumTranslation.implTranslateErrorDetails(i))}else if(t.RecognitionStatus!==n.RecognitionStatus.EndOfDictation){if(this.privRecognizerConfig.parameters.getProperty(n.OutputFormatPropertyName)===r.OutputFormat[r.OutputFormat.Simple])s=new r.SpeechRecognitionResult(this.privRequestSession.requestId,i,t.DisplayText,t.Duration,t.Offset,t.Language,t.LanguageDetectionConfidence,t.SpeakerId,void 0,t.asJson(),o);else{const t=n.DetailedSpeechPhrase.fromJSON(e,this.privRequestSession.currentTurnAudioOffset);s=new r.SpeechRecognitionResult(this.privRequestSession.requestId,i,t.Text,t.Duration,t.Offset,t.Language,t.LanguageDetectionConfidence,t.SpeakerId,void 0,t.asJson(),o)}this.handleRecognizedCallback(s,s.offset,this.privRequestSession.sessionId)}}handleSpeechHypothesis(e){const t=n.SpeechHypothesis.fromJSON(e,this.privRequestSession.currentTurnAudioOffset),i=new r.PropertyCollection;i.setProperty(r.PropertyId.SpeechServiceResponse_JsonResult,e);const s=new r.SpeechRecognitionResult(this.privRequestSession.requestId,r.ResultReason.RecognizingSpeech,t.Text,t.Duration,t.Offset,t.Language,t.LanguageDetectionConfidence,t.SpeakerId,void 0,t.asJson(),i);this.privRequestSession.onHypothesis(t.Offset),this.handleRecognizingCallback(s,t.Duration,this.privRequestSession.sessionId)}}t.ConversationServiceRecognizer=s},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RecognizerConfig=t.SpeechResultFormat=void 0;const r=i(85),n=i(2),s=i(116);!function(e){e[e.Simple=0]="Simple",e[e.Detailed=1]="Detailed"}(t.SpeechResultFormat||(t.SpeechResultFormat={}));t.RecognizerConfig=class{constructor(e,t){this.privSpeechServiceConfig=e||new n.SpeechServiceConfig(new n.Context(null)),this.privParameters=t,this.privMaxRetryCount=parseInt(t.getProperty("SPEECH-Error-MaxRetryCount","4"),10),this.privLanguageIdMode=t.getProperty(r.PropertyId.SpeechServiceConnection_LanguageIdMode,void 0),this.privEnableSpeakerId=!1}get parameters(){return this.privParameters}get recognitionMode(){return this.privRecognitionMode}set recognitionMode(e){this.privRecognitionMode=e,this.privRecognitionActivityTimeout=e===s.RecognitionMode.Interactive?8e3:25e3,this.privSpeechServiceConfig.Recognition=s.RecognitionMode[e]}get SpeechServiceConfig(){return this.privSpeechServiceConfig}get recognitionActivityTimeout(){return this.privRecognitionActivityTimeout}get isContinuousRecognition(){return this.privRecognitionMode!==s.RecognitionMode.Interactive}get languageIdMode(){return this.privLanguageIdMode}get autoDetectSourceLanguages(){return this.parameters.getProperty(r.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages,void 0)}get recognitionEndpointVersion(){return this.parameters.getProperty(r.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,"2")}set recognitionEndpointVersion(e){this.parameters.setProperty(r.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,e)}get sourceLanguageModels(){const e=[];let t=!1;if(void 0!==this.autoDetectSourceLanguages)for(const i of this.autoDetectSourceLanguages.split(",")){const n=i+r.PropertyId.SpeechServiceConnection_EndpointId.toString(),s=this.parameters.getProperty(n,void 0);void 0!==s?(e.push({language:i,endpoint:s}),t=!0):e.push({language:i,endpoint:""})}return t?e:void 0}get maxRetryCount(){return this.privMaxRetryCount}get isSpeakerDiarizationEnabled(){return this.privEnableSpeakerId}set isSpeakerDiarizationEnabled(e){this.privEnableSpeakerId=e}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebsocketMessageFormatter=void 0;const r=i(4);t.WebsocketMessageFormatter=class{toConnectionMessage(e){const t=new r.Deferred;try{if(e.messageType===r.MessageType.Text){const i=e.textContent;let n={},s=null;if(i){const e=i.split("\r\n\r\n");e&&e.length>0&&(n=this.parseHeaders(e[0]),e.length>1&&(s=e[1]))}t.resolve(new r.ConnectionMessage(e.messageType,s,n,e.id))}else if(e.messageType===r.MessageType.Binary){const i=e.binaryContent;let n={},s=null;if(!i||i.byteLength<2)throw new Error("Invalid binary message format. Header length missing.");const o=new DataView(i),a=o.getInt16(0);if(i.byteLengtha+2&&(s=i.slice(2+a)),t.resolve(new r.ConnectionMessage(e.messageType,s,n,e.id))}}catch(e){t.reject(`Error formatting the message. Error: ${e}`)}return t.promise}fromConnectionMessage(e){const t=new r.Deferred;try{if(e.messageType===r.MessageType.Text){const i=`${this.makeHeaders(e)}\r\n${e.textBody?e.textBody:""}`;t.resolve(new r.RawWebsocketMessage(r.MessageType.Text,i,e.id))}else if(e.messageType===r.MessageType.Binary){const i=this.makeHeaders(e),n=e.binaryBody,s=this.stringToArrayBuffer(i),o=new Int8Array(s),a=o.byteLength,c=new Int8Array(2+a+(n?n.byteLength:0));if(c[0]=a>>8&255,c[1]=255&a,c.set(o,2),n){const e=new Int8Array(n);c.set(e,2+a)}const p=c.buffer;t.resolve(new r.RawWebsocketMessage(r.MessageType.Binary,p,e.id))}}catch(e){t.reject(`Error formatting the message. ${e}`)}return t.promise}makeHeaders(e){let t="";if(e.headers)for(const i in e.headers)i&&(t+=`${i}: ${e.headers[i]}\r\n`);return t}parseHeaders(e){const t={};if(e){const i=e.match(/[^\r\n]+/g);if(t)for(const e of i)if(e){const i=e.indexOf(":"),r=i>0?e.substr(0,i).trim().toLowerCase():e,n=i>0&&e.length>i+1?e.substr(i+1).trim():"";t[r]=n}}return t}stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),i=new DataView(t);for(let t=0;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechConnectionFactory=void 0;const r=i(66),n=i(2),s=i(85),o=i(135),a=i(2),c=i(59),p=i(136),u=i(116);class h extends o.ConnectionFactoryBase{constructor(){super(...arguments),this.interactiveRelativeUri="/speech/recognition/interactive/cognitiveservices/v1",this.conversationRelativeUri="/speech/recognition/conversation/cognitiveservices/v1",this.dictationRelativeUri="/speech/recognition/dictation/cognitiveservices/v1",this.universalUri="/stt/speech/universal/v"}async create(e,t,i){let h=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Endpoint,void 0);const d=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Region,void 0),v=o.ConnectionFactoryBase.getHostSuffix(d),l=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Host,"wss://"+d+".stt.speech"+v),g={},S=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_EndpointId,void 0),f=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage,void 0),y="true"===e.parameters.getProperty(s.PropertyId.Speech_EnableMultiChannelProcessing,"false").toLowerCase();if(S?h&&-1!==h.search(p.QueryParameterNames.CustomSpeechDeploymentId)||(g[p.QueryParameterNames.CustomSpeechDeploymentId]=S):f&&!y&&(h&&-1!==h.search(p.QueryParameterNames.Language)||(g[p.QueryParameterNames.Language]=f)),y||h&&-1!==h.search(p.QueryParameterNames.Format)||(g[p.QueryParameterNames.Format]=e.parameters.getProperty(n.OutputFormatPropertyName,s.OutputFormat[s.OutputFormat.Simple]).toLowerCase()),void 0!==e.autoDetectSourceLanguages&&(g[p.QueryParameterNames.EnableLanguageId]="true"),this.setCommonUrlParams(e,g,h),h){const t=new URL(h),i=t.pathname;""!==i&&"/"!==i||(t.pathname=this.universalUri+e.recognitionEndpointVersion,h=await o.ConnectionFactoryBase.getRedirectUrlFromEndpoint(t.toString()))}if(!h)switch(e.recognitionMode){case u.RecognitionMode.Conversation:h="true"===e.parameters.getProperty(n.ForceDictationPropertyName,"false")?l+this.dictationRelativeUri:void 0!==e.recognitionEndpointVersion&&parseInt(e.recognitionEndpointVersion,10)>1?`${l}${this.universalUri}${e.recognitionEndpointVersion}`:l+this.conversationRelativeUri;break;case u.RecognitionMode.Dictation:h=l+this.dictationRelativeUri;break;default:h=void 0!==e.recognitionEndpointVersion&&parseInt(e.recognitionEndpointVersion,10)>1?`${l}${this.universalUri}${e.recognitionEndpointVersion}`:l+this.interactiveRelativeUri}const m={};void 0!==t.token&&""!==t.token&&(m[t.headerName]=t.token),m[c.HeaderNames.ConnectionId]=i,m.connectionId=i;const C="true"===e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false"),P=new r.WebsocketConnection(h,g,m,new a.WebsocketMessageFormatter,r.ProxyInfo.fromRecognizerConfig(e),C,i),R=P.uri;return e.parameters.setProperty(s.PropertyId.SpeechServiceConnection_Url,R),P}}t.SpeechConnectionFactory=h},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationTranscriberConnectionFactory=void 0;const r=i(66),n=i(85),s=i(2),o=i(135),a=i(2),c=i(59),p=i(136);class u extends o.ConnectionFactoryBase{constructor(){super(...arguments),this.universalUri="/stt/speech/universal/v2",this.conversationRelativeUriV1="/speech/recognition/conversation/cognitiveservices/v1"}async create(e,t,i){let s=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Endpoint,void 0);const u=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Region,void 0),h=o.ConnectionFactoryBase.getHostSuffix(u),d=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Host,"wss://"+u+".stt.speech"+h),v={},l=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_EndpointId,void 0),g=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_RecoLanguage,void 0);l?s&&-1!==s.search(p.QueryParameterNames.CustomSpeechDeploymentId)||(v[p.QueryParameterNames.CustomSpeechDeploymentId]=l):g&&(s&&-1!==s.search(p.QueryParameterNames.Language)||(v[p.QueryParameterNames.Language]=g)),void 0!==e.autoDetectSourceLanguages&&(v[p.QueryParameterNames.EnableLanguageId]="true");if("1"===e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion,void 0))s=`${d}${this.universalUri}`;else{if(this.setV2UrlParams(e,v,s),s){const e=new URL(s),t=e.pathname;""!==t&&"/"!==t||(e.pathname=this.universalUri,s=await o.ConnectionFactoryBase.getRedirectUrlFromEndpoint(e.toString()))}s||(s=`${d}${this.conversationRelativeUriV1}`)}const S={};void 0!==t.token&&""!==t.token&&(S[t.headerName]=t.token),S[c.HeaderNames.ConnectionId]=i;const f="true"===e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false"),y=new r.WebsocketConnection(s,v,S,new a.WebsocketMessageFormatter,r.ProxyInfo.fromRecognizerConfig(e),f,i),m=y.uri;return e.parameters.setProperty(n.PropertyId.SpeechServiceConnection_Url,m),y}setV2UrlParams(e,t,i){new Map([[n.PropertyId.Speech_SegmentationSilenceTimeoutMs,p.QueryParameterNames.SegmentationSilenceTimeoutMs],[n.PropertyId.SpeechServiceConnection_EnableAudioLogging,p.QueryParameterNames.EnableAudioLogging],[n.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs,p.QueryParameterNames.EndSilenceTimeoutMs],[n.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs,p.QueryParameterNames.InitialSilenceTimeoutMs],[n.PropertyId.SpeechServiceResponse_ProfanityOption,p.QueryParameterNames.Profanity],[n.PropertyId.SpeechServiceResponse_StablePartialResultThreshold,p.QueryParameterNames.StableIntermediateThreshold]]).forEach(((r,n)=>{this.setUrlParameter(n,r,e,t,i)}));const r=JSON.parse(e.parameters.getProperty(s.ServicePropertiesPropertyName,"{}"));Object.keys(r).forEach((e=>{t[e]=r[e]}))}}t.ConversationTranscriberConnectionFactory=u},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranscriberConnectionFactory=void 0;const r=i(66),n=i(85),s=i(135),o=i(2),a=i(59),c=i(136);class p extends s.ConnectionFactoryBase{constructor(){super(...arguments),this.multiaudioRelativeUri="/speech/recognition/multiaudio"}create(e,t,i){let c=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Endpoint,void 0);const p=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Region,"centralus"),u="wss://transcribe."+p+".cts.speech"+s.ConnectionFactoryBase.getHostSuffix(p)+this.multiaudioRelativeUri,h=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Host,u),d={};this.setQueryParams(d,e,c),c||(c=h);const v={};void 0!==t.token&&""!==t.token&&(v[t.headerName]=t.token),v[a.HeaderNames.ConnectionId]=i,e.parameters.setProperty(n.PropertyId.SpeechServiceConnection_Url,c);const l="true"===e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false");return Promise.resolve(new r.WebsocketConnection(c,d,v,new o.WebsocketMessageFormatter,r.ProxyInfo.fromRecognizerConfig(e),l,i))}setQueryParams(e,t,i){const r=t.parameters.getProperty(n.PropertyId.SpeechServiceConnection_EndpointId,void 0),s=t.parameters.getProperty(n.PropertyId.SpeechServiceConnection_RecoLanguage,void 0);r&&!(c.QueryParameterNames.CustomSpeechDeploymentId in e)&&(e[c.QueryParameterNames.CustomSpeechDeploymentId]=r),s&&!(c.QueryParameterNames.Language in e)&&(e[c.QueryParameterNames.Language]=s);const a="true"===t.parameters.getProperty(n.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,"false").toLowerCase(),p=t.parameters.getProperty(o.OutputFormatPropertyName,n.OutputFormat[n.OutputFormat.Simple])!==n.OutputFormat[n.OutputFormat.Simple];(a||p)&&(e[c.QueryParameterNames.Format]=n.OutputFormat[n.OutputFormat.Detailed].toLowerCase()),this.setCommonUrlParams(t,e,i)}}t.TranscriberConnectionFactory=p},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationConnectionFactory=void 0;const r=i(66),n=i(210),s=i(85),o=i(135),a=i(2),c=i(59),p=i(136),u=i(116);class h extends o.ConnectionFactoryBase{constructor(){super(...arguments),this.universalUri="/stt/speech/universal/v2",this.translationV1Uri="/speech/translation/cognitiveservices/v1"}async create(e,t,i){let n=this.getEndpointUrl(e);const p={};if(this.setQueryParams(p,e,n),n){const e=new URL(n),t=e.pathname;""!==t&&"/"!==t||(e.pathname=this.universalUri,n=await o.ConnectionFactoryBase.getRedirectUrlFromEndpoint(e.toString()))}const u={};void 0!==t.token&&""!==t.token&&(u[t.headerName]=t.token),u[c.HeaderNames.ConnectionId]=i,e.parameters.setProperty(s.PropertyId.SpeechServiceConnection_Url,n);const h="true"===e.parameters.getProperty("SPEECH-EnableWebsocketCompression","false");return new r.WebsocketConnection(n,p,u,new a.WebsocketMessageFormatter,r.ProxyInfo.fromRecognizerConfig(e),h,i)}getEndpointUrl(e,t){const i=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Region),r=o.ConnectionFactoryBase.getHostSuffix(i);let a=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Endpoint,void 0);if(a)return!0===t?a:n.StringUtils.formatString(a,{region:i});if("true"===e.parameters.getProperty("SPEECH-ForceV1Endpoint","false")){a=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Host,"wss://{region}.s2s.speech"+r)+this.translationV1Uri}else{a=e.parameters.getProperty(s.PropertyId.SpeechServiceConnection_Host,"wss://{region}.stt.speech"+r)+this.universalUri}return!0===t?a:n.StringUtils.formatString(a,{region:i})}setQueryParams(e,t,i){e.from=t.parameters.getProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage),e.to=t.parameters.getProperty(s.PropertyId.SpeechServiceConnection_TranslationToLanguages),e.scenario=t.recognitionMode===u.RecognitionMode.Interactive?"interactive":t.recognitionMode===u.RecognitionMode.Conversation?"conversation":"",this.setCommonUrlParams(t,e,i),this.setUrlParameter(s.PropertyId.SpeechServiceResponse_TranslationRequestStablePartialResult,p.QueryParameterNames.StableTranslation,t,e,i);const r=t.parameters.getProperty(s.PropertyId.SpeechServiceConnection_TranslationVoice,void 0);void 0!==r&&(e.voice=r,e.features="requireVoice")}}t.TranslationConnectionFactory=h},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringUtils=void 0;t.StringUtils=class{static formatString(e,t){if(!e)return"";if(!t)return e;let i="",r="";const n=e=>{i+=e},s=e=>{r+=e};let o=n;for(let a=0;a{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EnumTranslation=void 0;const r=i(85),n=i(2);t.EnumTranslation=class{static implTranslateRecognitionResult(e,t=!1){let i=r.ResultReason.Canceled;switch(e){case n.RecognitionStatus.Success:i=r.ResultReason.RecognizedSpeech;break;case n.RecognitionStatus.EndOfDictation:i=t?r.ResultReason.RecognizedSpeech:r.ResultReason.NoMatch;break;case n.RecognitionStatus.NoMatch:case n.RecognitionStatus.InitialSilenceTimeout:case n.RecognitionStatus.BabbleTimeout:i=r.ResultReason.NoMatch;break;case n.RecognitionStatus.Error:case n.RecognitionStatus.BadRequest:case n.RecognitionStatus.Forbidden:default:i=r.ResultReason.Canceled}return i}static implTranslateCancelResult(e){let t=r.CancellationReason.EndOfStream;switch(e){case n.RecognitionStatus.Success:case n.RecognitionStatus.EndOfDictation:case n.RecognitionStatus.NoMatch:t=r.CancellationReason.EndOfStream;break;case n.RecognitionStatus.InitialSilenceTimeout:case n.RecognitionStatus.BabbleTimeout:case n.RecognitionStatus.Error:case n.RecognitionStatus.BadRequest:case n.RecognitionStatus.Forbidden:default:t=r.CancellationReason.Error}return t}static implTranslateCancelErrorCode(e){let t=r.CancellationErrorCode.NoError;switch(e){case n.RecognitionStatus.Error:t=r.CancellationErrorCode.ServiceError;break;case n.RecognitionStatus.TooManyRequests:t=r.CancellationErrorCode.TooManyRequests;break;case n.RecognitionStatus.BadRequest:t=r.CancellationErrorCode.BadRequestParameters;break;case n.RecognitionStatus.Forbidden:t=r.CancellationErrorCode.Forbidden;break;default:t=r.CancellationErrorCode.NoError}return t}static implTranslateErrorDetails(e){let t="The speech service encountered an internal error and could not continue.";switch(e){case r.CancellationErrorCode.Forbidden:t="The recognizer is using a free subscription that ran out of quota.";break;case r.CancellationErrorCode.BadRequestParameters:t="Invalid parameter or unsupported audio format in the request.";break;case r.CancellationErrorCode.TooManyRequests:t="The number of parallel requests exceeded the number of allowed concurrent transcriptions."}return t}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RecognitionStatus=t.SynthesisStatus=void 0,function(e){e[e.Success=0]="Success",e[e.SynthesisEnd=1]="SynthesisEnd",e[e.Error=2]="Error"}(t.SynthesisStatus||(t.SynthesisStatus={})),function(e){e[e.Success=0]="Success",e[e.NoMatch=1]="NoMatch",e[e.InitialSilenceTimeout=2]="InitialSilenceTimeout",e[e.BabbleTimeout=3]="BabbleTimeout",e[e.Error=4]="Error",e[e.EndOfDictation=5]="EndOfDictation",e[e.TooManyRequests=6]="TooManyRequests",e[e.BadRequest=7]="BadRequest",e[e.Forbidden=8]="Forbidden"}(t.RecognitionStatus||(t.RecognitionStatus={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationSynthesisEnd=void 0;const r=i(2);class n{constructor(e){this.privSynthesisEnd=JSON.parse(e),this.privSynthesisEnd.SynthesisStatus&&(this.privSynthesisEnd.SynthesisStatus=r.SynthesisStatus[this.privSynthesisEnd.SynthesisStatus]),this.privSynthesisEnd.Status&&(this.privSynthesisEnd.SynthesisStatus=r.SynthesisStatus[this.privSynthesisEnd.Status])}static fromJSON(e){return new n(e)}get SynthesisStatus(){return this.privSynthesisEnd.SynthesisStatus}get FailureReason(){return this.privSynthesisEnd.FailureReason}}t.TranslationSynthesisEnd=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationHypothesis=void 0;const r=i(70),n=i(53);class s{constructor(e,t){this.privTranslationHypothesis=e,this.privTranslationHypothesis.Offset+=t,this.privTranslationHypothesis.Translation.TranslationStatus=this.mapTranslationStatus(this.privTranslationHypothesis.Translation.TranslationStatus)}static fromJSON(e,t){return new s(JSON.parse(e),t)}static fromTranslationResponse(e,t){r.Contracts.throwIfNullOrUndefined(e,"translationHypothesis");const i=e.SpeechHypothesis;return e.SpeechHypothesis=void 0,i.Translation=e,new s(i,t)}get Duration(){return this.privTranslationHypothesis.Duration}get Offset(){return this.privTranslationHypothesis.Offset}get Text(){return this.privTranslationHypothesis.Text}get Translation(){return this.privTranslationHypothesis.Translation}get Language(){return this.privTranslationHypothesis.PrimaryLanguage?.Language}asJson(){const e={...this.privTranslationHypothesis};return void 0!==e.Translation?JSON.stringify({...e,TranslationStatus:n.TranslationStatus[e.Translation.TranslationStatus]}):JSON.stringify(e)}mapTranslationStatus(e){return"string"==typeof e?n.TranslationStatus[e]:"number"==typeof e?e:void 0}}t.TranslationHypothesis=s},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationPhrase=void 0;const r=i(70),n=i(2),s=i(53);class o{constructor(e,t){this.privTranslationPhrase=e,this.privTranslationPhrase.Offset+=t,this.privTranslationPhrase.RecognitionStatus=this.mapRecognitionStatus(this.privTranslationPhrase.RecognitionStatus),void 0!==this.privTranslationPhrase.Translation&&(this.privTranslationPhrase.Translation.TranslationStatus=this.mapTranslationStatus(this.privTranslationPhrase.Translation.TranslationStatus))}static fromJSON(e,t){return new o(JSON.parse(e),t)}static fromTranslationResponse(e,t){r.Contracts.throwIfNullOrUndefined(e,"translationResponse");const i=e.SpeechPhrase;return e.SpeechPhrase=void 0,i.Translation=e,i.Text=i.DisplayText,new o(i,t)}get RecognitionStatus(){return this.privTranslationPhrase.RecognitionStatus}get Offset(){return this.privTranslationPhrase.Offset}get Duration(){return this.privTranslationPhrase.Duration}get Text(){return this.privTranslationPhrase.Text}get Language(){return this.privTranslationPhrase.PrimaryLanguage?.Language}get Confidence(){return this.privTranslationPhrase.PrimaryLanguage?.Confidence}get Translation(){return this.privTranslationPhrase.Translation}asJson(){const e={...this.privTranslationPhrase},t={...e,RecognitionStatus:n.RecognitionStatus[e.RecognitionStatus]};return e.Translation&&(t.Translation={...e.Translation,TranslationStatus:s.TranslationStatus[e.Translation.TranslationStatus]}),JSON.stringify(t)}mapRecognitionStatus(e){return"string"==typeof e?n.RecognitionStatus[e]:"number"==typeof e?e:void 0}mapTranslationStatus(e){return"string"==typeof e?s.TranslationStatus[e]:"number"==typeof e?e:void 0}}t.TranslationPhrase=o},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranslationServiceRecognizer=void 0;const r=i(4),n=i(85),s=i(2);class o extends s.ConversationServiceRecognizer{constructor(e,t,i,r,n){super(e,t,i,r,n),this.privTranslationRecognizer=n,this.connectionEvents.attach((e=>{"ConnectionEstablishedEvent"===e.name&&this.privTranslationRecognizer.onConnection()}))}async processTypeSpecificMessages(e){const t=new n.PropertyCollection;let i=await this.processSpeechMessages(e);if(i)return!0;const o=async e=>{t.setProperty(n.PropertyId.SpeechServiceResponse_JsonResult,e.asJson());const r=this.privRequestSession.onPhraseRecognized(e.Offset+e.Duration);if(r>0&&t.setProperty(n.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,r.toString()),e.RecognitionStatus===s.RecognitionStatus.Success){const i=this.fireEventForResult(e,t);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,i)}catch(e){}if(this.privSuccessCallback){try{this.privSuccessCallback(i.result)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}else{const r=s.EnumTranslation.implTranslateRecognitionResult(e.RecognitionStatus),o=new n.TranslationRecognitionResult(void 0,this.privRequestSession.requestId,r,e.Text,e.Duration,e.Offset,e.Language,e.Confidence,void 0,e.asJson(),t);if(r===n.ResultReason.Canceled){const t=s.EnumTranslation.implTranslateCancelResult(e.RecognitionStatus),i=s.EnumTranslation.implTranslateCancelErrorCode(e.RecognitionStatus);await this.cancelRecognitionLocal(t,i,s.EnumTranslation.implTranslateErrorDetails(i))}else if(e.RecognitionStatus!==s.RecognitionStatus.EndOfDictation){const e=new n.TranslationRecognitionEventArgs(o,o.offset,this.privRequestSession.sessionId);if(this.privTranslationRecognizer.recognized)try{this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,e)}catch(e){}if(this.privSuccessCallback){try{this.privSuccessCallback(o)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}i=!0}},a=e=>{t.setProperty(n.PropertyId.SpeechServiceResponse_JsonResult,e.asJson());const r=this.privRequestSession.onHypothesis(e.Offset);r>0&&t.setProperty(n.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,r.toString());const s=this.fireEventForResult(e,t);if(this.privTranslationRecognizer.recognizing)try{this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer,s)}catch(e){}i=!0};switch(e.messageType===r.MessageType.Text&&t.setProperty(n.PropertyId.SpeechServiceResponse_JsonResult,e.textBody),e.path.toLowerCase()){case"translation.hypothesis":a(s.TranslationHypothesis.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset));break;case"translation.response":const t=JSON.parse(e.textBody);if(t.SpeechPhrase)await o(s.TranslationPhrase.fromTranslationResponse(t,this.privRequestSession.currentTurnAudioOffset));else{const t=JSON.parse(e.textBody);t.SpeechHypothesis&&a(s.TranslationHypothesis.fromTranslationResponse(t,this.privRequestSession.currentTurnAudioOffset))}break;case"translation.phrase":await o(s.TranslationPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset));break;case"translation.synthesis":case"audio":this.sendSynthesisAudio(e.binaryBody,this.privRequestSession.sessionId),i=!0;break;case"audio.end":case"translation.synthesis.end":const r=s.TranslationSynthesisEnd.fromJSON(e.textBody);switch(r.SynthesisStatus){case s.SynthesisStatus.Error:if(this.privTranslationRecognizer.synthesizing){const e=new n.TranslationSynthesisResult(n.ResultReason.Canceled,void 0),t=new n.TranslationSynthesisEventArgs(e,this.privRequestSession.sessionId);try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,t)}catch(e){}}if(this.privTranslationRecognizer.canceled){const e=new n.TranslationRecognitionCanceledEventArgs(this.privRequestSession.sessionId,n.CancellationReason.Error,r.FailureReason,n.CancellationErrorCode.ServiceError,null);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,e)}catch(e){}}break;case s.SynthesisStatus.Success:this.sendSynthesisAudio(void 0,this.privRequestSession.sessionId)}i=!0}return i}cancelRecognition(e,t,i,r,o){const a=new n.PropertyCollection;if(a.setProperty(s.CancellationErrorCodePropertyName,n.CancellationErrorCode[r]),this.privTranslationRecognizer.canceled){const t=new n.TranslationRecognitionCanceledEventArgs(e,i,o,r,void 0);try{this.privTranslationRecognizer.canceled(this.privTranslationRecognizer,t)}catch{}}if(this.privSuccessCallback){const e=new n.TranslationRecognitionResult(void 0,t,n.ResultReason.Canceled,void 0,void 0,void 0,void 0,void 0,o,void 0,a);try{this.privSuccessCallback(e),this.privSuccessCallback=void 0}catch{}}}handleRecognizingCallback(e,t,i){try{const r=new n.TranslationRecognitionEventArgs(n.TranslationRecognitionResult.fromSpeechRecognitionResult(e),t,i);this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer,r)}catch(e){}}handleRecognizedCallback(e,t,i){try{const r=new n.TranslationRecognitionEventArgs(n.TranslationRecognitionResult.fromSpeechRecognitionResult(e),t,i);this.privTranslationRecognizer.recognized(this.privTranslationRecognizer,r)}catch(e){}}fireEventForResult(e,t){let i,o,a;if(void 0!==e.Translation.Translations){i=new n.Translations;for(const t of e.Translation.Translations)i.set(t.Language,t.Text||t.DisplayText)}e instanceof s.TranslationPhrase?(o=e.Translation&&e.Translation.TranslationStatus===r.TranslationStatus.Success?n.ResultReason.TranslatedSpeech:n.ResultReason.RecognizedSpeech,a=e.Confidence):o=n.ResultReason.TranslatingSpeech;const c=e.Language,p=new n.TranslationRecognitionResult(i,this.privRequestSession.requestId,o,e.Text,e.Duration,e.Offset,c,a,e.Translation.FailureReason,e.asJson(),t);return new n.TranslationRecognitionEventArgs(p,e.Offset,this.privRequestSession.sessionId)}sendSynthesisAudio(e,t){const i=void 0===e?n.ResultReason.SynthesizingAudioCompleted:n.ResultReason.SynthesizingAudio,r=new n.TranslationSynthesisResult(i,e),s=new n.TranslationSynthesisEventArgs(r,t);if(this.privTranslationRecognizer.synthesizing)try{this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer,s)}catch(e){}}}t.TranslationServiceRecognizer=o},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechDetected=void 0;class i{constructor(e,t){this.privSpeechStartDetected=JSON.parse(e),this.privSpeechStartDetected.Offset+=t}static fromJSON(e,t){return new i(e,t)}get Offset(){return this.privSpeechStartDetected.Offset}}t.SpeechDetected=i},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechHypothesis=void 0;class i{constructor(e,t){this.privSpeechHypothesis=JSON.parse(e),this.updateOffset(t)}static fromJSON(e,t){return new i(e,t)}updateOffset(e){this.privSpeechHypothesis.Offset+=e}asJson(){return JSON.stringify(this.privSpeechHypothesis)}get Text(){return this.privSpeechHypothesis.Text}get Offset(){return this.privSpeechHypothesis.Offset}get Duration(){return this.privSpeechHypothesis.Duration}get Language(){return void 0===this.privSpeechHypothesis.PrimaryLanguage?void 0:this.privSpeechHypothesis.PrimaryLanguage.Language}get LanguageDetectionConfidence(){return void 0===this.privSpeechHypothesis.PrimaryLanguage?void 0:this.privSpeechHypothesis.PrimaryLanguage.Confidence}get SpeakerId(){return this.privSpeechHypothesis.SpeakerId}}t.SpeechHypothesis=i},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechKeyword=void 0;class i{constructor(e,t){this.privSpeechKeyword=JSON.parse(e),this.privSpeechKeyword.Offset+=t}static fromJSON(e,t){return new i(e,t)}get Status(){return this.privSpeechKeyword.Status}get Text(){return this.privSpeechKeyword.Text}get Offset(){return this.privSpeechKeyword.Offset}get Duration(){return this.privSpeechKeyword.Duration}asJson(){return JSON.stringify(this.privSpeechKeyword)}}t.SpeechKeyword=i},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechServiceRecognizer=void 0;const r=i(85),n=i(2);class s extends n.ServiceRecognizerBase{constructor(e,t,i,r,n){super(e,t,i,r,n),this.privSpeechRecognizer=n}async processTypeSpecificMessages(e){let t;const i=new r.PropertyCollection;let s=!1;switch(e.path.toLowerCase()){case"speech.hypothesis":case"speech.fragment":const o=n.SpeechHypothesis.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);i.setProperty(r.PropertyId.SpeechServiceResponse_JsonResult,o.asJson());const a=this.privRequestSession.onHypothesis(o.Offset);a>0&&i.setProperty(r.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,a.toString()),t=new r.SpeechRecognitionResult(this.privRequestSession.requestId,r.ResultReason.RecognizingSpeech,o.Text,o.Duration,o.Offset,o.Language,o.LanguageDetectionConfidence,void 0,void 0,o.asJson(),i);const c=new r.SpeechRecognitionEventArgs(t,o.Offset,this.privRequestSession.sessionId);if(this.privSpeechRecognizer.recognizing)try{this.privSpeechRecognizer.recognizing(this.privSpeechRecognizer,c)}catch(e){}s=!0;break;case"speech.phrase":const p=n.SimpleSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);i.setProperty(r.PropertyId.SpeechServiceResponse_JsonResult,p.asJson());const u=n.EnumTranslation.implTranslateRecognitionResult(p.RecognitionStatus,this.privExpectContentAssessmentResponse),h=this.privRequestSession.onPhraseRecognized(p.Offset+p.Duration);if(h>0&&i.setProperty(r.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,h.toString()),r.ResultReason.Canceled===u){const e=n.EnumTranslation.implTranslateCancelResult(p.RecognitionStatus),t=n.EnumTranslation.implTranslateCancelErrorCode(p.RecognitionStatus);await this.cancelRecognitionLocal(e,t,n.EnumTranslation.implTranslateErrorDetails(t))}else{if(p.RecognitionStatus===n.RecognitionStatus.EndOfDictation)break;if(this.privRecognizerConfig.parameters.getProperty(n.OutputFormatPropertyName)===r.OutputFormat[r.OutputFormat.Simple])t=new r.SpeechRecognitionResult(this.privRequestSession.requestId,u,p.DisplayText,p.Duration,p.Offset,p.Language,p.LanguageDetectionConfidence,void 0,void 0,p.asJson(),i,p.Channel);else{const s=n.DetailedSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);i.setProperty(r.PropertyId.SpeechServiceResponse_JsonResult,s.asJson()),t=new r.SpeechRecognitionResult(this.privRequestSession.requestId,u,s.RecognitionStatus===n.RecognitionStatus.Success?s.NBest[0].Display:"",s.Duration,s.Offset,s.Language,s.LanguageDetectionConfidence,void 0,void 0,s.asJson(),i,s.Channel)}const s=new r.SpeechRecognitionEventArgs(t,t.offset,this.privRequestSession.sessionId);if(this.privSpeechRecognizer.recognized)try{this.privSpeechRecognizer.recognized(this.privSpeechRecognizer,s)}catch(e){}if(this.privSuccessCallback){try{this.privSuccessCallback(t)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}s=!0}return s}cancelRecognition(e,t,i,s,o){const a=new r.PropertyCollection;if(a.setProperty(n.CancellationErrorCodePropertyName,r.CancellationErrorCode[s]),this.privSpeechRecognizer.canceled){const t=new r.SpeechRecognitionCanceledEventArgs(i,o,s,void 0,e);try{this.privSpeechRecognizer.canceled(this.privSpeechRecognizer,t)}catch{}}if(this.privSuccessCallback){const e=new r.SpeechRecognitionResult(t,r.ResultReason.Canceled,void 0,void 0,void 0,void 0,void 0,void 0,o,void 0,a);try{this.privSuccessCallback(e),this.privSuccessCallback=void 0}catch{}}}}t.SpeechServiceRecognizer=s},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationTranscriptionServiceRecognizer=void 0;const r=i(85),n=i(2),s=i(222),o=i(116);class a extends n.ServiceRecognizerBase{constructor(e,t,i,r,n){super(e,t,i,r,n),this.privConversationTranscriber=n,this.setSpeakerDiarizationJson()}setSpeakerDiarizationJson(){if(this.privEnableSpeakerId){const e=this.privSpeechContext.getContext().phraseDetection||{};e.mode=o.RecognitionMode.Conversation;const t={};t.mode=s.SpeakerDiarizationMode.Anonymous,t.audioSessionId=this.privDiarizationSessionId,t.audioOffsetMs=0,t.diarizeIntermediates="true"===this.privRecognizerConfig.parameters.getProperty(r.PropertyId.SpeechServiceResponse_DiarizeIntermediateResults,"false"),e.speakerDiarization=t,this.privSpeechContext.getContext().phraseDetection=e}}async processTypeSpecificMessages(e){let t;const i=new r.PropertyCollection;i.setProperty(r.PropertyId.SpeechServiceResponse_JsonResult,e.textBody);let s=!1;switch(e.path.toLowerCase()){case"speech.hypothesis":case"speech.fragment":const o=n.SpeechHypothesis.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset),a=this.privRequestSession.onHypothesis(o.Offset);a>0&&i.setProperty(r.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,a.toString()),t=new r.ConversationTranscriptionResult(this.privRequestSession.requestId,r.ResultReason.RecognizingSpeech,o.Text,o.Duration,o.Offset,o.Language,o.LanguageDetectionConfidence,o.SpeakerId,void 0,o.asJson(),i);const c=new r.ConversationTranscriptionEventArgs(t,o.Duration,this.privRequestSession.sessionId);if(this.privConversationTranscriber.transcribing)try{this.privConversationTranscriber.transcribing(this.privConversationTranscriber,c)}catch(e){}s=!0;break;case"speech.phrase":const p=n.SimpleSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset),u=n.EnumTranslation.implTranslateRecognitionResult(p.RecognitionStatus),h=this.privRequestSession.onPhraseRecognized(p.Offset+p.Duration);if(h>0&&i.setProperty(r.PropertyId.SpeechServiceResponse_RecognitionLatencyMs,h.toString()),r.ResultReason.Canceled===u){const e=n.EnumTranslation.implTranslateCancelResult(p.RecognitionStatus),t=n.EnumTranslation.implTranslateCancelErrorCode(p.RecognitionStatus);await this.cancelRecognitionLocal(e,t,n.EnumTranslation.implTranslateErrorDetails(t))}else if(!this.privRequestSession.isSpeechEnded||u!==r.ResultReason.NoMatch||p.RecognitionStatus===n.RecognitionStatus.InitialSilenceTimeout){if(this.privRecognizerConfig.parameters.getProperty(n.OutputFormatPropertyName)===r.OutputFormat[r.OutputFormat.Simple])t=new r.ConversationTranscriptionResult(this.privRequestSession.requestId,u,p.DisplayText,p.Duration,p.Offset,p.Language,p.LanguageDetectionConfidence,p.SpeakerId,void 0,p.asJson(),i);else{const s=n.DetailedSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);t=new r.ConversationTranscriptionResult(this.privRequestSession.requestId,u,s.RecognitionStatus===n.RecognitionStatus.Success?s.NBest[0].Display:void 0,s.Duration,s.Offset,s.Language,s.LanguageDetectionConfidence,p.SpeakerId,void 0,s.asJson(),i)}const s=new r.ConversationTranscriptionEventArgs(t,t.offset,this.privRequestSession.sessionId);if(this.privConversationTranscriber.transcribed)try{this.privConversationTranscriber.transcribed(this.privConversationTranscriber,s)}catch(e){}}s=!0}return s}cancelRecognition(e,t,i,s,o){if((new r.PropertyCollection).setProperty(n.CancellationErrorCodePropertyName,r.CancellationErrorCode[s]),this.privConversationTranscriber.canceled){const t=new r.ConversationTranscriptionCanceledEventArgs(i,o,s,void 0,e);try{this.privConversationTranscriber.canceled(this.privConversationTranscriber,t)}catch{}}}}t.ConversationTranscriptionServiceRecognizer=a},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdentityProvider=t.SpeakerDiarizationMode=void 0,function(e){e.None="None",e.Identity="Identity",e.Anonymous="Anonymous"}(t.SpeakerDiarizationMode||(t.SpeakerDiarizationMode={})),function(e){e.CallCenter="CallCenter"}(t.IdentityProvider||(t.IdentityProvider={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranscriptionServiceRecognizer=void 0;const r=i(4),n=i(85),s=i(2),o=i(188);class a extends s.ConversationServiceRecognizer{constructor(e,t,i,r,s){super(e,t,i,r,s),this.privTranscriberRecognizer=s,this.sendPrePayloadJSONOverride=e=>this.sendTranscriptionStartJSON(e),"true"===this.privRecognizerConfig.parameters.getProperty(n.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps)&&this.privSpeechContext.setWordLevelTimings()}async sendMeetingSpeechEventAsync(e,t){if(this.privRequestSession.isRecognizing){const i=await this.fetchConnection();await this.sendSpeechEvent(i,this.createMeetingSpeechEventPayload(e,t))}}processTypeSpecificMessages(e){return this.processSpeechMessages(e)}handleRecognizedCallback(e,t,i){try{const r=new n.SpeechRecognitionEventArgs(e,t,i);if(this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer,r),this.privSuccessCallback){try{this.privSuccessCallback(e)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}catch(e){}}handleRecognizingCallback(e,t,i){try{const r=new n.SpeechRecognitionEventArgs(e,t,i);this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer,r)}catch(e){}}cancelRecognition(e,t,i,r,o){const a=new n.PropertyCollection;if(a.setProperty(s.CancellationErrorCodePropertyName,n.CancellationErrorCode[r]),this.privTranscriberRecognizer.canceled){const t=new n.MeetingTranscriptionCanceledEventArgs(i,o,r,void 0,e);try{this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer,t)}catch{}}if(this.privSuccessCallback){const e=new n.SpeechRecognitionResult(t,n.ResultReason.Canceled,void 0,void 0,void 0,void 0,void 0,void 0,o,void 0,a);try{this.privSuccessCallback(e),this.privSuccessCallback=void 0}catch{}}}async sendTranscriptionStartJSON(e){await this.sendSpeechContext(e,!0);const t=this.privTranscriberRecognizer.getMeetingInfo(),i=this.createMeetingSpeechEventPayload(t,"start");await this.sendSpeechEvent(e,i),await this.sendWaveHeader(e)}sendSpeechEvent(e,t){const i=JSON.stringify(t);if(i)return e.send(new o.SpeechConnectionMessage(r.MessageType.Text,"speech.event",this.privRequestSession.requestId,"application/json",i))}createMeetingSpeechEventPayload(e,t){const i={id:"meeting",name:t,meeting:e.meetingProperties};return i.meeting.id=e.id,i.meeting.attendees=e.participants,i}}t.TranscriptionServiceRecognizer=a},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DetailedSpeechPhrase=void 0;const r=i(2);class n{constructor(e,t){this.privDetailedSpeechPhrase=JSON.parse(e),this.privDetailedSpeechPhrase.RecognitionStatus=this.mapRecognitionStatus(this.privDetailedSpeechPhrase.RecognitionStatus),this.updateOffsets(t)}static fromJSON(e,t){return new n(e,t)}updateOffsets(e){if(this.privDetailedSpeechPhrase.Offset+=e,this.privDetailedSpeechPhrase.NBest)for(const t of this.privDetailedSpeechPhrase.NBest){if(t.Words)for(const i of t.Words)i.Offset+=e;if(t.DisplayWords)for(const i of t.DisplayWords)i.Offset+=e}}asJson(){const e={...this.privDetailedSpeechPhrase};return JSON.stringify({...e,RecognitionStatus:r.RecognitionStatus[e.RecognitionStatus]})}get RecognitionStatus(){return this.privDetailedSpeechPhrase.RecognitionStatus}get NBest(){return this.privDetailedSpeechPhrase.NBest}get Duration(){return this.privDetailedSpeechPhrase.Duration}get Offset(){return this.privDetailedSpeechPhrase.Offset}get Language(){return void 0===this.privDetailedSpeechPhrase.PrimaryLanguage?void 0:this.privDetailedSpeechPhrase.PrimaryLanguage.Language}get LanguageDetectionConfidence(){return void 0===this.privDetailedSpeechPhrase.PrimaryLanguage?void 0:this.privDetailedSpeechPhrase.PrimaryLanguage.Confidence}get Text(){return this.privDetailedSpeechPhrase.NBest&&this.privDetailedSpeechPhrase.NBest[0]?this.privDetailedSpeechPhrase.NBest[0].Display||this.privDetailedSpeechPhrase.NBest[0].DisplayText:this.privDetailedSpeechPhrase.DisplayText}get SpeakerId(){return this.privDetailedSpeechPhrase.SpeakerId}get Channel(){return void 0===this.privDetailedSpeechPhrase.Channel?0:this.privDetailedSpeechPhrase.Channel}mapRecognitionStatus(e){return"string"==typeof e?r.RecognitionStatus[e]:"number"==typeof e?e:void 0}}t.DetailedSpeechPhrase=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleSpeechPhrase=void 0;const r=i(2);class n{constructor(e,t=0){this.privSimpleSpeechPhrase=JSON.parse(e),this.privSimpleSpeechPhrase.RecognitionStatus=this.mapRecognitionStatus(this.privSimpleSpeechPhrase.RecognitionStatus),this.updateOffset(t)}static fromJSON(e,t){return new n(e,t)}updateOffset(e){this.privSimpleSpeechPhrase.Offset+=e}asJson(){const e={...this.privSimpleSpeechPhrase};return JSON.stringify({...e,RecognitionStatus:r.RecognitionStatus[e.RecognitionStatus]})}get RecognitionStatus(){return this.privSimpleSpeechPhrase.RecognitionStatus}get DisplayText(){return this.privSimpleSpeechPhrase.DisplayText}get Offset(){return this.privSimpleSpeechPhrase.Offset}get Duration(){return this.privSimpleSpeechPhrase.Duration}get Language(){return void 0===this.privSimpleSpeechPhrase.PrimaryLanguage?void 0:this.privSimpleSpeechPhrase.PrimaryLanguage.Language}get LanguageDetectionConfidence(){return void 0===this.privSimpleSpeechPhrase.PrimaryLanguage?void 0:this.privSimpleSpeechPhrase.PrimaryLanguage.Confidence}get SpeakerId(){return this.privSimpleSpeechPhrase.SpeakerId}get Channel(){return void 0===this.privSimpleSpeechPhrase.Channel?0:this.privSimpleSpeechPhrase.Channel}mapRecognitionStatus(e){return"string"==typeof e?r.RecognitionStatus[e]:"number"==typeof e?e:void 0}}t.SimpleSpeechPhrase=n},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RequestSession=void 0;const r=i(4),n=i(64),s=i(227);t.RequestSession=class{constructor(e){this.privIsDisposed=!1,this.privDetachables=new Array,this.privIsAudioNodeDetached=!1,this.privIsRecognizing=!1,this.privIsSpeechEnded=!1,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privHypothesisReceived=!1,this.privBytesSent=0,this.privRecognitionBytesSent=0,this.privRecogNumber=0,this.privInTurn=!1,this.privConnectionAttempts=0,this.privAudioSourceId=e,this.privRequestId=(0,r.createNoDashGuid)(),this.privAudioNodeId=(0,r.createNoDashGuid)(),this.privTurnDeferral=new r.Deferred,this.privTurnDeferral.resolve()}get sessionId(){return this.privSessionId}get requestId(){return this.privRequestId}get audioNodeId(){return this.privAudioNodeId}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSpeechEnded(){return this.privIsSpeechEnded}get isRecognizing(){return this.privIsRecognizing}get currentTurnAudioOffset(){return this.privTurnStartAudioOffset}get recogNumber(){return this.privRecogNumber}get numConnectionAttempts(){return this.privConnectionAttempts}get bytesSent(){return this.privBytesSent}get recognitionBytesSent(){return this.privRecognitionBytesSent}listenForServiceTelemetry(e){this.privServiceTelemetryListener&&this.privDetachables.push(e.attachListener(this.privServiceTelemetryListener))}startNewRecognition(){this.privRecognitionBytesSent=0,this.privIsSpeechEnded=!1,this.privIsRecognizing=!0,this.privTurnStartAudioOffset=0,this.privLastRecoOffset=0,this.privRecogNumber++,this.privServiceTelemetryListener=new s.ServiceTelemetryListener(this.privRequestId,this.privAudioSourceId,this.privAudioNodeId),this.onEvent(new n.RecognitionTriggeredEvent(this.requestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}async onAudioSourceAttachCompleted(e,t){this.privAudioNode=e,this.privIsAudioNodeDetached=!1,t?await this.onComplete():this.onEvent(new n.ListeningStartedEvent(this.privRequestId,this.privSessionId,this.privAudioSourceId,this.privAudioNodeId))}onPreConnectionStart(e,t){this.privAuthFetchEventId=e,this.privSessionId=t,this.onEvent(new n.ConnectingToServiceEvent(this.privRequestId,this.privAuthFetchEventId,this.privSessionId))}async onAuthCompleted(e){e&&await this.onComplete()}async onConnectionEstablishCompleted(e,t){if(200===e)return this.onEvent(new n.RecognitionStartedEvent(this.requestId,this.privAudioSourceId,this.privAudioNodeId,this.privAuthFetchEventId,this.privSessionId)),this.privAudioNode&&this.privAudioNode.replay(),this.privTurnStartAudioOffset=this.privLastRecoOffset,void(this.privBytesSent=0);403===e&&await this.onComplete()}async onServiceTurnEndResponse(e){this.privTurnDeferral.resolve(),!e||this.isSpeechEnded?(await this.onComplete(),this.privInTurn=!1):(this.privTurnStartAudioOffset=this.privLastRecoOffset,this.privAudioNode.replay())}onSpeechContext(){this.privRequestId=(0,r.createNoDashGuid)()}onServiceTurnStartResponse(){this.privTurnDeferral&&this.privInTurn&&(this.privTurnDeferral.reject("Another turn started before current completed."),this.privTurnDeferral.promise.then().catch((()=>{}))),this.privInTurn=!0,this.privTurnDeferral=new r.Deferred}onHypothesis(e){const t=this.privAudioNode.findTimeAtOffset(e);return this.privHypothesisReceived||(this.privHypothesisReceived=!0,this.privServiceTelemetryListener.hypothesisReceived(t)),t>0?Date.now()-t:0}onPhraseRecognized(e){const t=this.privAudioNode.findTimeAtOffset(e);return this.privServiceTelemetryListener.phraseReceived(t),this.onServiceRecognized(e),t>0?Date.now()-t:0}onServiceRecognized(e){this.privLastRecoOffset=e,this.privHypothesisReceived=!1,this.privAudioNode.shrinkBuffers(e),this.privConnectionAttempts=0}onServiceAcknowledgedAudio(e){this.privAudioNode&&this.privAudioNode.shrinkBuffers(e)}onAudioSent(e){this.privBytesSent+=e,this.privRecognitionBytesSent+=e}onRetryConnection(){this.privConnectionAttempts++}async dispose(){if(!this.privIsDisposed){this.privIsDisposed=!0;for(const e of this.privDetachables)await e.detach();this.privServiceTelemetryListener&&this.privServiceTelemetryListener.dispose(),this.privIsRecognizing=!1}}getTelemetry(){return this.privServiceTelemetryListener.hasTelemetry?this.privServiceTelemetryListener.getTelemetry():null}async onStopRecognizing(){await this.onComplete()}onSpeechEnded(){this.privIsSpeechEnded=!0}onEvent(e){this.privServiceTelemetryListener&&this.privServiceTelemetryListener.onEvent(e),r.Events.instance.onEvent(e)}async onComplete(){this.privIsRecognizing&&(this.privIsRecognizing=!1,await this.detachAudioNode())}async detachAudioNode(){this.privIsAudioNodeDetached||(this.privIsAudioNodeDetached=!0,this.privAudioNode&&await this.privAudioNode.detach())}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceTelemetryListener=void 0;const r=i(4),n=i(64);t.ServiceTelemetryListener=class{constructor(e,t,i){this.privIsDisposed=!1,this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privRequestId=e,this.privAudioSourceId=t,this.privAudioNodeId=i,this.privReceivedMessages={},this.privPhraseLatencies=[],this.privHypothesisLatencies=[]}phraseReceived(e){e>0&&this.privPhraseLatencies.push(Date.now()-e)}hypothesisReceived(e){e>0&&this.privHypothesisLatencies.push(Date.now()-e)}onEvent(e){if(!this.privIsDisposed&&(e instanceof n.RecognitionTriggeredEvent&&e.requestId===this.privRequestId&&(this.privListeningTriggerMetric={End:e.eventTime,Name:"ListeningTrigger",Start:e.eventTime}),e instanceof r.AudioStreamNodeAttachingEvent&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof r.AudioStreamNodeAttachedEvent&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicStartTime=e.eventTime),e instanceof r.AudioSourceErrorEvent&&e.audioSourceId===this.privAudioSourceId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof r.AudioStreamNodeErrorEvent&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Error:e.error,Name:"Microphone",Start:this.privMicStartTime})),e instanceof r.AudioStreamNodeDetachedEvent&&e.audioSourceId===this.privAudioSourceId&&e.audioNodeId===this.privAudioNodeId&&(this.privMicMetric||(this.privMicMetric={End:e.eventTime,Name:"Microphone",Start:this.privMicStartTime})),e instanceof n.ConnectingToServiceEvent&&e.requestId===this.privRequestId&&(this.privConnectionId=e.sessionId),e instanceof r.ConnectionStartEvent&&e.connectionId===this.privConnectionId&&(this.privConnectionStartTime=e.eventTime),e instanceof r.ConnectionEstablishedEvent&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof r.ConnectionEstablishErrorEvent&&e.connectionId===this.privConnectionId&&(this.privConnectionEstablishMetric||(this.privConnectionEstablishMetric={End:e.eventTime,Error:this.getConnectionError(e.statusCode),Id:this.privConnectionId,Name:"Connection",Start:this.privConnectionStartTime})),e instanceof r.ConnectionMessageReceivedEvent&&e.connectionId===this.privConnectionId&&e.message&&e.message.headers&&e.message.headers.path)){this.privReceivedMessages[e.message.headers.path]||(this.privReceivedMessages[e.message.headers.path]=new Array);const t=50;this.privReceivedMessages[e.message.headers.path].length0&&e.push({PhraseLatencyMs:this.privPhraseLatencies}),this.privHypothesisLatencies.length>0&&e.push({FirstHypothesisLatencyMs:this.privHypothesisLatencies});const t={Metrics:e,ReceivedMessages:this.privReceivedMessages},i=JSON.stringify(t);return this.privReceivedMessages={},this.privListeningTriggerMetric=null,this.privMicMetric=null,this.privConnectionEstablishMetric=null,this.privPhraseLatencies=[],this.privHypothesisLatencies=[],i}get hasTelemetry(){return 0!==Object.keys(this.privReceivedMessages).length||null!==this.privListeningTriggerMetric||null!==this.privMicMetric||null!==this.privConnectionEstablishMetric||0!==this.privPhraseLatencies.length||0!==this.privHypothesisLatencies.length}dispose(){this.privIsDisposed=!0}getConnectionError(e){switch(e){case 400:case 1002:case 1003:case 1005:case 1007:case 1008:case 1009:return"BadRequest";case 401:return"Unauthorized";case 403:return"Forbidden";case 503:case 1001:return"ServerUnavailable";case 500:case 1011:return"ServerError";case 408:case 504:return"Timeout";default:return"statuscode:"+e.toString()}}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechContext=void 0;const r=i(116),n=i(229);t.SpeechContext=class{constructor(e){this.privContext={},this.privDynamicGrammar=e}getContext(){return this.privContext}setPronunciationAssessmentParams(e,t=!1){void 0===this.privContext.phraseDetection&&(this.privContext.phraseDetection={enrichment:{pronunciationAssessment:{}}}),void 0===this.privContext.phraseDetection.enrichment&&(this.privContext.phraseDetection.enrichment={pronunciationAssessment:{}}),this.privContext.phraseDetection.enrichment.pronunciationAssessment=JSON.parse(e)||{},t&&(this.privContext.phraseDetection.mode=r.RecognitionMode.Conversation),this.setWordLevelTimings(),this.privContext.phraseOutput.detailed.options.push(n.PhraseOption.PronunciationAssessment),-1===this.privContext.phraseOutput.detailed.options.indexOf(n.PhraseOption.SNR)&&this.privContext.phraseOutput.detailed.options.push(n.PhraseOption.SNR)}setDetailedOutputFormat(){void 0===this.privContext.phraseOutput&&(this.privContext.phraseOutput={detailed:{options:[]}}),void 0===this.privContext.phraseOutput.detailed&&(this.privContext.phraseOutput.detailed={options:[]}),this.privContext.phraseOutput.format=n.OutputFormat.Detailed}setWordLevelTimings(){void 0===this.privContext.phraseOutput&&(this.privContext.phraseOutput={detailed:{options:[]}}),void 0===this.privContext.phraseOutput.detailed&&(this.privContext.phraseOutput.detailed={options:[]}),this.privContext.phraseOutput.format=n.OutputFormat.Detailed,-1===this.privContext.phraseOutput.detailed.options.indexOf(n.PhraseOption.WordTimings)&&this.privContext.phraseOutput.detailed.options.push(n.PhraseOption.WordTimings)}setSpeakerDiarizationAudioOffsetMs(e){this.privContext.phraseDetection.speakerDiarization.audioOffsetMs=e}toJSON(){const e=this.privDynamicGrammar.generateGrammarObject();this.privContext.dgi=e;return JSON.stringify(this.privContext)}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TentativePhraseResultsOption=t.OutputFormat=t.PhraseExtension=t.PhraseOption=void 0,function(e){e.WordTimings="WordTimings",e.SNR="SNR",e.Pronunciation="Pronunciation",e.WordPronunciation="WordPronunciation",e.WordConfidence="WordConfidence",e.Words="Words",e.Sentiment="Sentiment",e.PronunciationAssessment="PronunciationAssessment",e.ContentAssessment="ContentAssessment",e.PhraseAMScore="PhraseAMScore",e.PhraseLMScore="PhraseLMScore",e.WordAMScore="WordAMScore",e.WordLMScore="WordLMScore",e.RuleTree="RuleTree",e.NBestTimings="NBestTimings",e.DecoderDiagnostics="DecoderDiagnostics",e.DisplayWordTimings="DisplayWordTimings",e.DisplayWords="DisplayWords"}(t.PhraseOption||(t.PhraseOption={})),function(e){e.Graph="Graph",e.Corrections="Corrections",e.Sentiment="Sentiment"}(t.PhraseExtension||(t.PhraseExtension={})),function(e){e.Simple="Simple",e.Detailed="Detailed"}(t.OutputFormat||(t.OutputFormat={})),function(e){e.None="None",e.Always="Always"}(t.TentativePhraseResultsOption||(t.TentativePhraseResultsOption={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReconnectContinuationState=void 0;const r=i(59);t.ReconnectContinuationState=class{constructor(e="1"){this.privDefaultStreamId=e}get defaultStreamId(){return this.privDefaultStreamId}get streamOffset(){return this.privStreamOffset}get hasPendingContinuation(){return void 0!==this.privToken||void 0!==this.privServiceTag||void 0!==this.privStreamOffset}reset(){this.privToken=void 0,this.privServiceTag=void 0,this.privStreamOffset=void 0}onTurnStart(e){this.privServiceTag=e??""}updateFromHeaders(e,t=0){if(!e)return;const i=r.HeaderNames.ContinuationToken.toLowerCase(),n=r.HeaderNames.ContinuationAudioStreamOffset.toLowerCase();for(const r in e){if(!r)continue;const s=r.toLowerCase(),o=e[r];if(s===i)this.privToken=o;else if(s===n){const e=parseInt(o,10);if(!isNaN(e)){const i=t+e;(void 0===this.privStreamOffset||i>this.privStreamOffset)&&(this.privStreamOffset=i)}}}}buildAudioStreamsMetadata(){const e={};return e[this.privDefaultStreamId]=null,{streams:e}}buildContinuationContext(){if(!this.hasPendingContinuation)return;const e={previousServiceTag:this.privServiceTag??"",token:this.privToken??""};return void 0!==this.privStreamOffset&&(e.audio={streams:{[this.privDefaultStreamId]:{offset:this.privStreamOffset}}}),e}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DynamicGrammarBuilder=void 0;const r=i(232);t.DynamicGrammarBuilder=class{constructor(){this.privWeight=1}addPhrase(e){this.privPhrases||(this.privPhrases=[]),e instanceof Array?this.privPhrases=this.privPhrases.concat(e):this.privPhrases.push(e)}clearPhrases(){this.privPhrases=void 0}addReferenceGrammar(e){this.privGrammars||(this.privGrammars=[]),e instanceof Array?this.privGrammars=this.privGrammars.concat(e):this.privGrammars.push(e)}clearGrammars(){this.privGrammars=void 0}setWeight(e){this.privWeight=e}generateGrammarObject(){if(void 0===this.privGrammars&&void 0===this.privPhrases)return;const e={};if(e.referenceGrammars=this.privGrammars,void 0!==this.privPhrases&&0!==this.privPhrases.length){const t=[];this.privPhrases.forEach((e=>{t.push({text:e})})),e.groups=[{type:r.GroupType.Generic,items:t}],e.bias=this.privWeight}return e}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SubstringMatchType=t.GroupType=void 0,function(e){e.IntentText="IntentText",e.IntentEntity="IntentEntity",e.Generic="Generic",e.People="People",e.Place="Place",e.DynamicEntity="DynamicEntity"}(t.GroupType||(t.GroupType={})),function(e){e.None="None",e.LeftRooted="LeftRooted",e.PartialName="PartialName",e.MiddleOfSentence="MiddleOfSentence"}(t.SubstringMatchType||(t.SubstringMatchType={}))},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DialogServiceAdapter=void 0;const r=i(66),n=i(34),s=i(4),o=i(91),a=i(85),c=i(234),p=i(2),u=i(236),h=i(237),d=i(238),v=i(188);class l extends p.ServiceRecognizerBase{constructor(e,t,i,r,n){super(e,t,i,r,n),this.privEvents=new s.EventSource,this.privDialogServiceConnector=n,this.receiveMessageOverride=()=>this.receiveDialogMessageOverride(),this.privTurnStateManager=new c.DialogServiceTurnStateManager,this.recognizeOverride=(e,t,i)=>this.listenOnce(e,t,i),this.postConnectImplOverride=e=>this.dialogConnectImpl(e),this.configConnectionOverride=e=>this.configConnection(e),this.disconnectOverride=()=>this.privDisconnect(),this.privDialogAudioSource=i,this.agentConfigSent=!1,this.privLastResult=null,this.connectionEvents.attach((e=>{"ConnectionClosedEvent"===e.name&&(this.terminateMessageLoop=!0)}))}async sendMessage(e){const t=(0,s.createGuid)(),i=(0,s.createNoDashGuid)(),r={context:{interactionId:t},messagePayload:JSON.parse(e),version:.5},n=JSON.stringify(r),o=await this.fetchConnection();await o.send(new v.SpeechConnectionMessage(s.MessageType.Text,"agent",i,"application/json",n))}async privDisconnect(){await this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,a.CancellationReason.Error,a.CancellationErrorCode.NoError,"Disconnecting"),this.terminateMessageLoop=!0,this.agentConfigSent=!1}processTypeSpecificMessages(e){const t=new a.PropertyCollection;let i,r;switch(e.messageType===s.MessageType.Text&&t.setProperty(a.PropertyId.SpeechServiceResponse_JsonResult,e.textBody),e.path.toLowerCase()){case"speech.phrase":const n=p.SimpleSpeechPhrase.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);if(this.privRequestSession.onPhraseRecognized(n.Offset+n.Duration),n.RecognitionStatus!==p.RecognitionStatus.TooManyRequests&&n.RecognitionStatus!==p.RecognitionStatus.Error){const e=this.fireEventForResult(n,t);if(this.privLastResult=e.result,this.privDialogServiceConnector.recognized)try{this.privDialogServiceConnector.recognized(this.privDialogServiceConnector,e)}catch(e){}}r=!0;break;case"speech.hypothesis":const s=p.SpeechHypothesis.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);i=new a.SpeechRecognitionResult(this.privRequestSession.requestId,a.ResultReason.RecognizingSpeech,s.Text,s.Duration,s.Offset,s.Language,s.LanguageDetectionConfidence,void 0,void 0,s.asJson(),t),this.privRequestSession.onHypothesis(s.Offset);const o=new a.SpeechRecognitionEventArgs(i,s.Offset,this.privRequestSession.sessionId);if(this.privDialogServiceConnector.recognizing)try{this.privDialogServiceConnector.recognizing(this.privDialogServiceConnector,o)}catch(e){}r=!0;break;case"speech.keyword":const c=p.SpeechKeyword.fromJSON(e.textBody,this.privRequestSession.currentTurnAudioOffset);i=new a.SpeechRecognitionResult(this.privRequestSession.requestId,"Accepted"===c.Status?a.ResultReason.RecognizedKeyword:a.ResultReason.NoMatch,c.Text,c.Duration,c.Offset,void 0,void 0,void 0,void 0,c.asJson(),t),"Accepted"!==c.Status&&(this.privLastResult=i);const u=new a.SpeechRecognitionEventArgs(i,i.duration,i.resultId);if(this.privDialogServiceConnector.recognized)try{this.privDialogServiceConnector.recognized(this.privDialogServiceConnector,u)}catch(e){}r=!0;break;case"audio":{const t=e.requestId.toUpperCase(),i=this.privTurnStateManager.GetTurn(t);try{e.binaryBody?i.audioStream.write(e.binaryBody):i.endAudioStream()}catch(e){}}r=!0;break;case"response":this.handleResponseMessage(e),r=!0}const n=new s.Deferred;return n.resolve(r),n.promise}async cancelRecognition(e,t,i,r,n){if(this.terminateMessageLoop=!0,this.privRequestSession.isRecognizing&&await this.privRequestSession.onStopRecognizing(),this.privDialogServiceConnector.canceled){const t=new a.PropertyCollection;t.setProperty(p.CancellationErrorCodePropertyName,a.CancellationErrorCode[r]);const s=new a.SpeechRecognitionCanceledEventArgs(i,n,r,void 0,e);try{this.privDialogServiceConnector.canceled(this.privDialogServiceConnector,s)}catch{}if(this.privSuccessCallback){const e=new a.SpeechRecognitionResult(void 0,a.ResultReason.Canceled,void 0,void 0,void 0,void 0,void 0,void 0,n,void 0,t);try{this.privSuccessCallback(e),this.privSuccessCallback=void 0}catch{}}}}async listenOnce(e,t,i){this.privRecognizerConfig.recognitionMode=e,this.privSuccessCallback=t,this.privErrorCallback=i,this.privRequestSession.startNewRecognition(),this.privRequestSession.listenForServiceTelemetry(this.privDialogAudioSource.events),this.privRecognizerConfig.parameters.setProperty(a.PropertyId.Speech_SessionId,this.privRequestSession.sessionId);const n=this.connectImpl(),s=this.sendPreAudioMessages(),o=await this.privDialogAudioSource.attach(this.privRequestSession.audioNodeId),c=await this.privDialogAudioSource.format,p=await this.privDialogAudioSource.deviceInfo,u=new r.ReplayableAudioNode(o,c.avgBytesPerSec);await this.privRequestSession.onAudioSourceAttachCompleted(u,!1),this.privRecognizerConfig.SpeechServiceConfig.Context.audio={source:p};try{await n,await s}catch(e){return await this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,a.CancellationReason.Error,a.CancellationErrorCode.ConnectionFailure,e),Promise.resolve()}const h=new a.SessionEventArgs(this.privRequestSession.sessionId);this.privRecognizer.sessionStarted&&this.privRecognizer.sessionStarted(this.privRecognizer,h);this.sendAudio(u).then((()=>{}),(async e=>{await this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,a.CancellationReason.Error,a.CancellationErrorCode.RuntimeError,e)}))}dialogConnectImpl(e){return this.privConnectionLoop=this.startMessageLoop(),e}receiveDialogMessageOverride(){const e=new s.Deferred,t=async()=>{try{const i=this.isDisposed(),r=!this.isDisposed()&&this.terminateMessageLoop;if(i||r)return void e.resolve(void 0);const n=await this.fetchConnection(),o=await n.read();if(!o)return t();const c=v.SpeechConnectionMessage.fromConnectionMessage(o);switch(c.path.toLowerCase()){case"turn.start":{const e=c.requestId.toUpperCase();e!==this.privRequestSession.requestId.toUpperCase()?this.privTurnStateManager.StartTurn(e):this.privRequestSession.onServiceTurnStartResponse()}break;case"speech.startdetected":const e=p.SpeechDetected.fromJSON(c.textBody,this.privRequestSession.currentTurnAudioOffset),t=new a.RecognitionEventArgs(e.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechStartDetected&&this.privRecognizer.speechStartDetected(this.privRecognizer,t);break;case"speech.enddetected":let i;i=c.textBody.length>0?c.textBody:"{ Offset: 0 }";const r=p.SpeechDetected.fromJSON(i,this.privRequestSession.currentTurnAudioOffset);this.privRequestSession.onServiceRecognized(r.Offset);const n=new a.RecognitionEventArgs(r.Offset,this.privRequestSession.sessionId);this.privRecognizer.speechEndDetected&&this.privRecognizer.speechEndDetected(this.privRecognizer,n);break;case"turn.end":{const e=c.requestId.toUpperCase();if(e!==this.privRequestSession.requestId.toUpperCase())this.privTurnStateManager.CompleteTurn(e);else{const e=new a.SessionEventArgs(this.privRequestSession.sessionId);if(await this.privRequestSession.onServiceTurnEndResponse(!1),this.privRecognizerConfig.isContinuousRecognition&&!this.privRequestSession.isSpeechEnded&&this.privRequestSession.isRecognizing||this.privRecognizer.sessionStopped&&this.privRecognizer.sessionStopped(this.privRecognizer,e),this.privSuccessCallback&&this.privLastResult){try{this.privSuccessCallback(this.privLastResult),this.privLastResult=null}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}this.privSuccessCallback=void 0,this.privErrorCallback=void 0}}}break;default:try{await this.processTypeSpecificMessages(c)||this.serviceEvents&&this.serviceEvents.onEvent(new s.ServiceEvent(c.path.toLowerCase(),c.textBody))}catch(e){}}return t()}catch(t){this.terminateMessageLoop=!0,e.resolve()}};return t().catch((e=>{s.Events.instance.onEvent(new s.BackgroundEvent(e))})),e.promise}async startMessageLoop(){this.terminateMessageLoop=!1;try{await this.receiveDialogMessageOverride()}catch(e){await this.cancelRecognition(this.privRequestSession.sessionId,this.privRequestSession.requestId,a.CancellationReason.Error,a.CancellationErrorCode.RuntimeError,e)}return Promise.resolve()}async configConnection(e){return this.terminateMessageLoop?(this.terminateMessageLoop=!1,Promise.reject("Connection to service terminated.")):(await this.sendSpeechServiceConfig(e,this.privRequestSession,this.privRecognizerConfig.SpeechServiceConfig.serialize()),await this.sendAgentConfig(e),e)}async sendPreAudioMessages(){const e=await this.fetchConnection();this.addKeywordContextData(),await this.sendSpeechContext(e,!0),await this.sendAgentContext(e),await this.sendWaveHeader(e)}sendAgentConfig(e){if(this.agentConfig&&!this.agentConfigSent){if(this.privRecognizerConfig.parameters.getProperty(a.PropertyId.Conversation_DialogType)===a.DialogServiceConfig.DialogTypes.CustomCommands){const e=this.agentConfig.get();e.botInfo.commandsCulture=this.privRecognizerConfig.parameters.getProperty(a.PropertyId.SpeechServiceConnection_RecoLanguage,"en-us"),this.agentConfig.set(e)}this.onEvent(new n.SendingAgentContextMessageEvent(this.agentConfig));const t=this.agentConfig.toJsonString();return this.agentConfigSent=!0,e.send(new v.SpeechConnectionMessage(s.MessageType.Text,"agent.config",this.privRequestSession.requestId,"application/json",t))}}sendAgentContext(e){const t=(0,s.createGuid)(),i=this.privDialogServiceConnector.properties.getProperty(a.PropertyId.Conversation_Speech_Activity_Template),r={channelData:"",context:{interactionId:t},messagePayload:void 0===typeof i?void 0:i,version:.5},n=JSON.stringify(r);return e.send(new v.SpeechConnectionMessage(s.MessageType.Text,"speech.agent.context",this.privRequestSession.requestId,"application/json",n))}fireEventForResult(e,t){const i=p.EnumTranslation.implTranslateRecognitionResult(e.RecognitionStatus),r=new a.SpeechRecognitionResult(this.privRequestSession.requestId,i,e.DisplayText,e.Duration,e.Offset,e.Language,e.LanguageDetectionConfidence,void 0,void 0,e.asJson(),t);return new a.SpeechRecognitionEventArgs(r,e.Offset,this.privRequestSession.sessionId)}handleResponseMessage(e){const t=JSON.parse(e.textBody);switch(t.messageType.toLowerCase()){case"message":const i=e.requestId.toUpperCase(),r=u.ActivityPayloadResponse.fromJSON(e.textBody),n=this.privTurnStateManager.GetTurn(i);if(r.conversationId){const e=this.agentConfig.get();e.botInfo.conversationId=r.conversationId,this.agentConfig.set(e)}const c=n.processActivityPayload(r,o.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(this.privDialogServiceConnector.properties.getProperty(a.PropertyId.SpeechServiceConnection_SynthOutputFormat,void 0))),p=new a.ActivityReceivedEventArgs(r.messagePayload,c);if(this.privDialogServiceConnector.activityReceived)try{this.privDialogServiceConnector.activityReceived(this.privDialogServiceConnector,p)}catch(e){}break;case"messagestatus":if(this.privDialogServiceConnector.turnStatusReceived)try{this.privDialogServiceConnector.turnStatusReceived(this.privDialogServiceConnector,new a.TurnStatusReceivedEventArgs(e.textBody))}catch(e){}break;default:s.Events.instance.onEvent(new s.BackgroundEvent(`Unexpected response of type ${t.messageType}. Ignoring.`))}}onEvent(e){this.privEvents.onEvent(e),s.Events.instance.onEvent(e)}addKeywordContextData(){const e=this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect");if(void 0===e)return;const t=this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect-Offsets"),i=this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect-Durations"),r=e.split(";"),n=void 0===t?[]:t.split(";"),s=void 0===i?[]:i.split(";"),o=[];for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DialogServiceTurnStateManager=void 0;const r=i(31),n=i(235);t.DialogServiceTurnStateManager=class{constructor(){this.privTurnMap=new Map}StartTurn(e){if(this.privTurnMap.has(e))throw new r.InvalidOperationError("Service error: There is already a turn with id:"+e);const t=new n.DialogServiceTurnState(this,e);return this.privTurnMap.set(e,t),this.privTurnMap.get(e)}GetTurn(e){return this.privTurnMap.get(e)}CompleteTurn(e){if(!this.privTurnMap.has(e))throw new r.InvalidOperationError("Service error: Received turn end for an unknown turn id:"+e);const t=this.privTurnMap.get(e);return t.complete(),this.privTurnMap.delete(e),t}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DialogServiceTurnState=void 0;const r=i(91),n=i(90),s=i(236);t.DialogServiceTurnState=class{constructor(e,t){this.privRequestId=t,this.privIsCompleted=!1,this.privAudioStream=null,this.privTurnManager=e,this.resetTurnEndTimeout()}get audioStream(){return this.resetTurnEndTimeout(),this.privAudioStream}processActivityPayload(e,t){return e.messageDataStreamType===s.MessageDataStreamType.TextToSpeechAudio&&(this.privAudioStream=n.AudioOutputStream.createPullStream(),this.privAudioStream.format=void 0!==t?t:r.AudioOutputFormatImpl.getDefaultOutputFormat()),this.privAudioStream}endAudioStream(){null===this.privAudioStream||this.privAudioStream.isClosed||this.privAudioStream.close()}complete(){void 0!==this.privTimeoutToken&&clearTimeout(this.privTimeoutToken),this.endAudioStream()}resetTurnEndTimeout(){void 0!==this.privTimeoutToken&&clearTimeout(this.privTimeoutToken),this.privTimeoutToken=setTimeout((()=>{this.privTurnManager.CompleteTurn(this.privRequestId)}),2e3)}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MessageDataStreamType=t.ActivityPayloadResponse=void 0;class i{constructor(e){this.privActivityResponse=JSON.parse(e)}static fromJSON(e){return new i(e)}get conversationId(){return this.privActivityResponse.conversationId}get messageDataStreamType(){return this.privActivityResponse.messageDataStreamType}get messagePayload(){return this.privActivityResponse.messagePayload}get version(){return this.privActivityResponse.version}}t.ActivityPayloadResponse=i,function(e){e[e.None=0]="None",e[e.TextToSpeechAudio=1]="TextToSpeechAudio"}(t.MessageDataStreamType||(t.MessageDataStreamType={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InvocationSource=void 0,function(e){e.None="None",e.VoiceActivationWithKeyword="VoiceActivationWithKeyword"}(t.InvocationSource||(t.InvocationSource={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OnRejectAction=t.KeywordDetectionType=void 0,function(e){e.StartTrigger="StartTrigger"}(t.KeywordDetectionType||(t.KeywordDetectionType={})),function(e){e.EndOfTurn="EndOfTurn",e.Continue="Continue"}(t.OnRejectAction||(t.OnRejectAction={}))},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentConfig=void 0;t.AgentConfig=class{toJsonString(){return JSON.stringify(this.iPrivConfig)}get(){return this.iPrivConfig}set(e){this.iPrivConfig=e}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalParticipants=t.TranscriberRecognizer=t.ConversationConnectionConfig=void 0;var r=i(241);Object.defineProperty(t,"ConversationConnectionConfig",{enumerable:!0,get:function(){return r.ConversationConnectionConfig}});var n=i(242);Object.defineProperty(t,"TranscriberRecognizer",{enumerable:!0,get:function(){return n.TranscriberRecognizer}});var s=i(243);Object.defineProperty(t,"InternalParticipants",{enumerable:!0,get:function(){return s.InternalParticipants}})},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConversationConnectionConfig=void 0;const r=i(187);class n extends r.RestConfigBase{static get defaultLanguageCode(){return n.privDefaultLanguageCode}static get transcriptionEventKeys(){return n.privTranscriptionEventKeys}}t.ConversationConnectionConfig=n,n.privDefaultLanguageCode="en-US",n.privTranscriptionEventKeys=["iCalUid","callId","organizer","FLAC","MTUri","DifferentiateGuestSpeakers","audiorecording","Threadid","OrganizerMri","OrganizerTenantId","UserToken"]},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranscriberRecognizer=void 0;const r=i(4),n=i(70),s=i(85),o=i(2),a=i(116);class c extends s.Recognizer{constructor(e,t){const i=e;n.Contracts.throwIfNull(i,"speechTranslationConfig");const r=t;n.Contracts.throwIfNull(r,"audioConfigImpl"),n.Contracts.throwIfNullOrWhitespace(i.speechRecognitionLanguage,s.PropertyId[s.PropertyId.SpeechServiceConnection_RecoLanguage]),super(t,i.properties,new o.TranscriberConnectionFactory),this.privDisposedRecognizer=!1}get speechRecognitionLanguage(){return n.Contracts.throwIfDisposed(this.privDisposedRecognizer),this.properties.getProperty(s.PropertyId.SpeechServiceConnection_RecoLanguage)}get properties(){return this.privProperties}get authorizationToken(){return this.properties.getProperty(s.PropertyId.SpeechServiceAuthorization_Token)}set authorizationToken(e){n.Contracts.throwIfNullOrWhitespace(e,"token"),this.properties.setProperty(s.PropertyId.SpeechServiceAuthorization_Token,e)}set meeting(e){n.Contracts.throwIfNullOrUndefined(e,"Meeting"),this.privMeeting=e}getMeetingInfo(){return n.Contracts.throwIfNullOrUndefined(this.privMeeting,"Meeting"),this.privMeeting.meetingInfo}startContinuousRecognitionAsync(e,t){(0,r.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(a.RecognitionMode.Conversation),e,t)}stopContinuousRecognitionAsync(e,t){(0,r.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(),e,t)}async close(){this.privDisposedRecognizer||await this.dispose(!0)}async pushMeetingEvent(e,t){const i=this.privReco;n.Contracts.throwIfNullOrUndefined(i,"serviceRecognizer"),await i.sendMeetingSpeechEventAsync(e,t)}async enforceAudioGating(){const e=this.audioConfig,t=(await e.format).channels;if(1===t){if("true"!==this.properties.getProperty("f0f5debc-f8c9-4892-ac4b-90a7ab359fd2","false").toLowerCase())throw new Error("Single channel audio configuration for MeetingTranscriber is currently under private preview, please contact diarizationrequest@microsoft.com for more details")}else if(8!==t)throw new Error(`Unsupported audio configuration: Detected ${t}-channel audio`)}connectMeetingCallbacks(e){this.canceled=(t,i)=>{e.canceled&&e.canceled(e,i)},this.recognizing=(t,i)=>{e.transcribing&&e.transcribing(e,i)},this.recognized=(t,i)=>{e.transcribed&&e.transcribed(e,i)},this.sessionStarted=(t,i)=>{e.sessionStarted&&e.sessionStarted(e,i)},this.sessionStopped=(t,i)=>{e.sessionStopped&&e.sessionStopped(e,i)}}disconnectCallbacks(){this.canceled=void 0,this.recognizing=void 0,this.recognized=void 0,this.sessionStarted=void 0,this.sessionStopped=void 0}async dispose(e){this.privDisposedRecognizer||(e&&(this.privDisposedRecognizer=!0,await this.implRecognizerStop()),await super.dispose(e))}createRecognizerConfig(e){return new o.RecognizerConfig(e,this.properties)}createServiceRecognizer(e,t,i,r){const n=i;return new o.TranscriptionServiceRecognizer(e,t,n,r,this)}}t.TranscriberRecognizer=c},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InternalParticipants=void 0;t.InternalParticipants=class{constructor(e=[]){this.participants=e}addOrUpdateParticipant(e){if(void 0===e)return;const t=this.getParticipantIndex(e.id);return t>-1?this.participants.splice(t,1,e):this.participants.push(e),this.getParticipant(e.id)}getParticipantIndex(e){return this.participants.findIndex((t=>t.id===e))}getParticipant(e){return this.participants.find((t=>t.id===e))}deleteParticipant(e){this.participants=this.participants.filter((t=>t.id!==e))}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesisAudioMetadata=t.MetadataType=void 0,function(e){e.WordBoundary="WordBoundary",e.Bookmark="Bookmark",e.Viseme="Viseme",e.SentenceBoundary="SentenceBoundary",e.SessionEnd="SessionEnd",e.AvatarSignal="TalkingAvatarSignal"}(t.MetadataType||(t.MetadataType={}));class i{constructor(e){this.privSynthesisAudioMetadata=JSON.parse(e)}static fromJSON(e){return new i(e)}get Metadata(){return this.privSynthesisAudioMetadata.Metadata}}t.SynthesisAudioMetadata=i},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesisTurn=void 0;const r=i(4),n=i(90),s=i(85),o=i(244),a=i(246);class c{constructor(){this.privIsDisposed=!1,this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!1,this.privBytesReceived=0,this.privInTurn=!1,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privSynthesisStartTime=0,this.privConnectionLatency=-1,this.privNetworkLatency=-1,this.privFirstByteLatency=-1,this.privServiceLatency=-1,this.privRequestId=(0,r.createNoDashGuid)(),this.privTurnDeferral=new r.Deferred,this.privTurnDeferral.resolve()}get requestId(){return this.privRequestId}get streamId(){return this.privStreamId}set streamId(e){this.privStreamId=e}get audioOutputFormat(){return this.privAudioOutputFormat}set audioOutputFormat(e){this.privAudioOutputFormat=e}get turnCompletionPromise(){return this.privTurnDeferral.promise}get isSynthesisEnded(){return this.privIsSynthesisEnded}get isSynthesizing(){return this.privIsSynthesizing}get currentTextOffset(){return this.privTextOffset}get currentSentenceOffset(){return this.privSentenceOffset}get bytesReceived(){return this.privBytesReceived}get audioDuration(){return this.privAudioDuration}get extraProperties(){if(this.privWebRTCSDP){const e=new s.PropertyCollection;return e.setProperty(s.PropertyId.TalkingAvatarService_WebRTC_SDP,this.privWebRTCSDP),e}}async getAllReceivedAudio(){return this.privReceivedAudio?Promise.resolve(this.privReceivedAudio):this.privIsSynthesisEnded?(await this.readAllAudioFromStream(),Promise.resolve(this.privReceivedAudio)):null}async getAllReceivedAudioWithHeader(){if(this.privReceivedAudioWithHeader)return this.privReceivedAudioWithHeader;if(!this.privIsSynthesisEnded)return null;if(this.audioOutputFormat.hasHeader){const e=await this.getAllReceivedAudio();return this.privReceivedAudioWithHeader=this.audioOutputFormat.addHeader(e),this.privReceivedAudioWithHeader}return this.getAllReceivedAudio()}startNewSynthesis(e,t,i,r){this.privIsSynthesisEnded=!1,this.privIsSynthesizing=!0,this.privRequestId=e,this.privRawText=t,this.privIsSSML=i,this.privAudioOutputStream=new n.PullAudioOutputStreamImpl,this.privAudioOutputStream.format=this.privAudioOutputFormat,this.privReceivedAudio=null,this.privReceivedAudioWithHeader=null,this.privBytesReceived=0,this.privTextOffset=0,this.privNextSearchTextIndex=0,this.privSentenceOffset=0,this.privNextSearchSentenceIndex=0,this.privPartialVisemeAnimation="",this.privWebRTCSDP="",this.privSynthesisStartTime=Date.now(),this.privConnectionLatency=-1,this.privNetworkLatency=-1,this.privFirstByteLatency=-1,this.privServiceLatency=-1,void 0!==r&&(this.privTurnAudioDestination=r,this.privTurnAudioDestination.format=this.privAudioOutputFormat),this.onEvent(new a.SynthesisTriggeredEvent(this.requestId,void 0,void 0===r?void 0:r.id()))}onPreConnectionStart(e){this.privAuthFetchEventId=e,this.onEvent(new a.ConnectingToSynthesisServiceEvent(this.privRequestId,this.privAuthFetchEventId))}onAuthCompleted(e){e&&this.onComplete()}onConnectionEstablishCompleted(e){if(200===e)return this.privConnectionLatency=Date.now()-this.privSynthesisStartTime,this.onEvent(new a.SynthesisStartedEvent(this.requestId,this.privAuthFetchEventId)),void(this.privBytesReceived=0);403===e&&this.onComplete()}onServiceResponseMessage(e){const t=JSON.parse(e);this.streamId=t.audio.streamId}onServiceTurnEndResponse(){this.privInTurn=!1,this.privTurnDeferral.resolve(),this.onComplete()}onServiceTurnStartResponse(e){this.privTurnDeferral&&this.privInTurn&&(this.privTurnDeferral.reject("Another turn started before current completed."),this.privTurnDeferral.promise.then().catch((()=>{}))),this.privInTurn=!0,this.privTurnDeferral=new r.Deferred,this.privConnectionLatency<0&&(this.privConnectionLatency=0),this.privNetworkLatency=Date.now()-this.privSynthesisStartTime-this.privConnectionLatency;const t=JSON.parse(e);t.webrtc&&(this.privWebRTCSDP=t.webrtc.connectionString)}onAudioChunkReceived(e){this.isSynthesizing&&(this.privFirstByteLatency<0&&(this.privFirstByteLatency=Date.now()-this.privSynthesisStartTime,this.privNetworkLatency>=0&&(this.privServiceLatency=this.privFirstByteLatency-this.privConnectionLatency-this.privNetworkLatency)),this.privAudioOutputStream.write(e),this.privBytesReceived+=e.byteLength,void 0!==this.privTurnAudioDestination&&this.privTurnAudioDestination.write(e))}onTextBoundaryEvent(e){this.updateTextOffset(e.Data.text.Text,e.Type)}onVisemeMetadataReceived(e){void 0!==e.Data.AnimationChunk&&(this.privPartialVisemeAnimation+=e.Data.AnimationChunk)}onSessionEnd(e){this.privAudioDuration=e.Data.Offset}async constructSynthesisResult(){const e=Date.now()-this.privSynthesisStartTime,t=await this.getAllReceivedAudioWithHeader(),i=new s.PropertyCollection;return this.privWebRTCSDP&&i.setProperty(s.PropertyId.TalkingAvatarService_WebRTC_SDP,this.privWebRTCSDP),i.setProperty(s.PropertyId.SpeechServiceResponse_SynthesisFirstByteLatencyMs,String(Math.max(0,this.privFirstByteLatency))),i.setProperty(s.PropertyId.SpeechServiceResponse_SynthesisFinishLatencyMs,String(e)),i.setProperty(s.PropertyId.SpeechServiceResponse_SynthesisConnectionLatencyMs,String(Math.max(0,this.privConnectionLatency))),i.setProperty(s.PropertyId.SpeechServiceResponse_SynthesisNetworkLatencyMs,String(Math.max(0,this.privNetworkLatency))),i.setProperty(s.PropertyId.SpeechServiceResponse_SynthesisServiceLatencyMs,String(Math.max(0,this.privServiceLatency))),new s.SpeechSynthesisResult(this.requestId,s.ResultReason.SynthesizingAudioCompleted,t,void 0,i,this.audioDuration)}dispose(){this.privIsDisposed||(this.privIsDisposed=!0)}onStopSynthesizing(){this.onComplete()}getAndClearVisemeAnimation(){const e=this.privPartialVisemeAnimation;return this.privPartialVisemeAnimation="",e}onEvent(e){r.Events.instance.onEvent(e)}static isXmlTag(e){return e.length>=2&&"<"===e[0]&&">"===e[e.length-1]}updateTextOffset(e,t){t===o.MetadataType.WordBoundary?(this.privTextOffset=this.privRawText.indexOf(e,this.privNextSearchTextIndex),this.privTextOffset>=0&&(this.privNextSearchTextIndex=this.privTextOffset+e.length,this.privIsSSML&&this.withinXmlTag(this.privTextOffset)&&!c.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)&&!c.isXmlTag(e)&&this.updateTextOffset(e,t)))}onComplete(){this.privIsSynthesizing&&(this.privIsSynthesizing=!1,this.privIsSynthesisEnded=!0,this.privAudioOutputStream.close(),this.privInTurn=!1,void 0!==this.privTurnAudioDestination&&(this.privTurnAudioDestination.close(),this.privTurnAudioDestination=void 0))}async readAllAudioFromStream(){if(this.privIsSynthesisEnded){this.privReceivedAudio=new ArrayBuffer(this.bytesReceived);try{await this.privAudioOutputStream.read(this.privReceivedAudio)}catch(e){this.privReceivedAudio=new ArrayBuffer(0)}}}withinXmlTag(e){return this.privRawText.indexOf("<",e+1)>this.privRawText.indexOf(">",e+1)}}t.SynthesisTurn=c},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesisStartedEvent=t.ConnectingToSynthesisServiceEvent=t.SynthesisTriggeredEvent=t.SpeechSynthesisEvent=void 0;const r=i(4);class n extends r.PlatformEvent{constructor(e,t,i=r.EventType.Info){super(e,i),this.privRequestId=t}get requestId(){return this.privRequestId}}t.SpeechSynthesisEvent=n;t.SynthesisTriggeredEvent=class extends n{constructor(e,t,i){super("SynthesisTriggeredEvent",e),this.privSessionAudioDestinationId=t,this.privTurnAudioDestinationId=i}get audioSessionDestinationId(){return this.privSessionAudioDestinationId}get audioTurnDestinationId(){return this.privTurnAudioDestinationId}};t.ConnectingToSynthesisServiceEvent=class extends n{constructor(e,t){super("ConnectingToSynthesisServiceEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}};t.SynthesisStartedEvent=class extends n{constructor(e,t){super("SynthesisStartedEvent",e),this.privAuthFetchEventId=t}get authFetchEventId(){return this.privAuthFetchEventId}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesisAdapterBase=void 0;const r=i(4),n=i(85),s=i(2),o=i(188);class a{constructor(e,t,i,o){if(this.speakOverride=void 0,this.receiveMessageOverride=void 0,this.connectImplOverride=void 0,this.configConnectionOverride=void 0,this.privConnectionConfigurationPromise=void 0,!e)throw new r.ArgumentNullError("authentication");if(!t)throw new r.ArgumentNullError("connectionFactory");if(!i)throw new r.ArgumentNullError("synthesizerConfig");this.privAuthentication=e,this.privConnectionFactory=t,this.privSynthesizerConfig=i,this.privIsDisposed=!1,this.privSessionAudioDestination=o,this.privSynthesisTurn=new s.SynthesisTurn,this.privConnectionEvents=new r.EventSource,this.privServiceEvents=new r.EventSource,this.privSynthesisContext=new s.SynthesisContext,this.privAgentConfig=new s.AgentConfig,this.connectionEvents.attach((e=>{if("ConnectionClosedEvent"===e.name){const t=e;1e3!==t.statusCode&&this.cancelSynthesisLocal(n.CancellationReason.Error,1007===t.statusCode?n.CancellationErrorCode.BadRequestParameters:n.CancellationErrorCode.ConnectionFailure,`${t.reason} websocket error code: ${t.statusCode}`)}}))}get synthesizerConfig(){return this.privSynthesizerConfig}get synthesisContext(){return this.privSynthesisContext}get agentConfig(){return this.privAgentConfig}get connectionEvents(){return this.privConnectionEvents}get serviceEvents(){return this.privServiceEvents}set activityTemplate(e){this.privActivityTemplate=e}get activityTemplate(){return this.privActivityTemplate}set audioOutputFormat(e){this.privAudioOutputFormat=e,this.privSynthesisTurn.audioOutputFormat=e,void 0!==this.privSessionAudioDestination&&(this.privSessionAudioDestination.format=e),void 0!==this.synthesisContext&&(this.synthesisContext.audioOutputFormat=e)}isDisposed(){return this.privIsDisposed}async dispose(e){if(this.privIsDisposed=!0,void 0!==this.privSessionAudioDestination&&this.privSessionAudioDestination.close(),void 0!==this.privConnectionConfigurationPromise)try{const t=await this.privConnectionConfigurationPromise;await t.dispose(e)}catch{}}async connect(){await this.connectImpl()}async sendNetworkMessage(e,t){const i="string"==typeof t?r.MessageType.Text:r.MessageType.Binary,n="string"==typeof t?"application/json":"";return(await this.fetchConnection()).send(new o.SpeechConnectionMessage(i,e,this.privSynthesisTurn.requestId,n,t))}async Speak(e,t,i,r,s,o){let a;if(a=t?e:this.privSynthesizer.buildSsml(e),void 0!==this.speakOverride)return this.speakOverride(a,i,r,s);this.privSuccessCallback=r,this.privErrorCallback=s,this.privSynthesisTurn.startNewSynthesis(i,e,t,o);try{const e=await this.fetchConnection();await this.sendSynthesisContext(e),await this.sendSsmlMessage(e,a,i),this.onSynthesisStarted(i),this.receiveMessage()}catch(e){return this.cancelSynthesisLocal(n.CancellationReason.Error,n.CancellationErrorCode.ConnectionFailure,e),Promise.reject(e)}}async stopSpeaking(){return(await this.fetchConnection()).send(new o.SpeechConnectionMessage(r.MessageType.Text,"synthesis.control",this.privSynthesisTurn.requestId,"application/json",JSON.stringify({action:"stop"})))}async SpeakStream(e,t,i,r,s){this.privSuccessCallback=i,this.privErrorCallback=r,this.privSynthesisTurn.startNewSynthesis(t,"",!1,s);try{const i=await this.fetchConnection();await this.sendStreamingSynthesisContext(i,e,t),this.onSynthesisStarted(t),e.onTextPiece=e=>{this.sendTextPiece(i,e,t).catch((e=>{this.cancelSynthesisLocal(n.CancellationReason.Error,n.CancellationErrorCode.ConnectionFailure,e)}))},e.onClose=()=>{this.sendTextStreamEnd(i,t).catch((e=>{this.cancelSynthesisLocal(n.CancellationReason.Error,n.CancellationErrorCode.ConnectionFailure,e)}))},this.receiveMessage()}catch(e){return this.cancelSynthesisLocal(n.CancellationReason.Error,n.CancellationErrorCode.ConnectionFailure,e),Promise.reject(e)}}cancelSynthesis(e,t,i,r){const o=new n.PropertyCollection;o.setProperty(s.CancellationErrorCodePropertyName,n.CancellationErrorCode[i]);const a=new n.SpeechSynthesisResult(e,n.ResultReason.Canceled,void 0,r,o);if(this.onSynthesisCancelled(a),this.privSuccessCallback)try{this.privSuccessCallback(a)}catch{}}cancelSynthesisLocal(e,t,i){this.privSynthesisTurn.isSynthesizing&&(this.privSynthesisTurn.onStopSynthesizing(),this.cancelSynthesis(this.privSynthesisTurn.requestId,e,t,i))}processTypeSpecificMessages(e){return!0}async receiveMessage(){try{const e=await this.fetchConnection(),t=await e.read();if(void 0!==this.receiveMessageOverride)return this.receiveMessageOverride();if(this.privIsDisposed)return;if(!t)return this.privSynthesisTurn.isSynthesizing?this.receiveMessage():void 0;const i=o.SpeechConnectionMessage.fromConnectionMessage(t);if(i.requestId.toLowerCase()===this.privSynthesisTurn.requestId.toLowerCase())switch(i.path.toLowerCase()){case"turn.start":this.privSynthesisTurn.onServiceTurnStartResponse(i.textBody);break;case"response":this.privSynthesisTurn.onServiceResponseMessage(i.textBody);break;case"audio":this.privSynthesisTurn.streamId.toLowerCase()===i.streamId.toLowerCase()&&i.binaryBody&&(this.privSynthesisTurn.onAudioChunkReceived(i.binaryBody),this.onSynthesizing(i.binaryBody),void 0!==this.privSessionAudioDestination&&this.privSessionAudioDestination.write(i.binaryBody));break;case"audio.metadata":const e=s.SynthesisAudioMetadata.fromJSON(i.textBody).Metadata;for(const t of e)switch(t.Type){case s.MetadataType.WordBoundary:case s.MetadataType.SentenceBoundary:this.privSynthesisTurn.onTextBoundaryEvent(t);const e=new n.SpeechSynthesisWordBoundaryEventArgs(t.Data.Offset,t.Data.Duration,t.Data.text.Text,t.Data.text.Length,t.Type===s.MetadataType.WordBoundary?this.privSynthesisTurn.currentTextOffset:this.privSynthesisTurn.currentSentenceOffset,t.Data.text.BoundaryType);this.onWordBoundary(e);break;case s.MetadataType.Bookmark:const i=new n.SpeechSynthesisBookmarkEventArgs(t.Data.Offset,t.Data.Bookmark);this.onBookmarkReached(i);break;case s.MetadataType.Viseme:if(this.privSynthesisTurn.onVisemeMetadataReceived(t),t.Data.IsLastAnimation){const e=new n.SpeechSynthesisVisemeEventArgs(t.Data.Offset,t.Data.VisemeId,this.privSynthesisTurn.getAndClearVisemeAnimation());this.onVisemeReceived(e)}break;case s.MetadataType.AvatarSignal:this.onAvatarEvent(t);break;case s.MetadataType.SessionEnd:this.privSynthesisTurn.onSessionEnd(t)}break;case"turn.end":let t;this.privSynthesisTurn.onServiceTurnEndResponse();try{t=await this.privSynthesisTurn.constructSynthesisResult(),this.onSynthesisCompleted(t),this.privSuccessCallback&&this.privSuccessCallback(t)}catch(e){this.privErrorCallback&&this.privErrorCallback(e)}break;default:this.processTypeSpecificMessages(i)||this.privServiceEvents&&this.serviceEvents.onEvent(new r.ServiceEvent(i.path.toLowerCase(),i.textBody))}return this.receiveMessage()}catch(e){}}sendSynthesisContext(e){this.setSynthesisContextSynthesisSection();const t=this.synthesisContext.toJSON();if(t)return e.send(new o.SpeechConnectionMessage(r.MessageType.Text,"synthesis.context",this.privSynthesisTurn.requestId,"application/json",t))}setSpeechConfigSynthesisSection(){}connectImpl(e=!1){if(null!=this.privConnectionPromise)return this.privConnectionPromise.then((e=>e.state()===r.ConnectionState.Disconnected?(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl()):this.privConnectionPromise),(()=>(this.privConnectionId=null,this.privConnectionPromise=null,this.connectImpl())));this.privAuthFetchEventId=(0,r.createNoDashGuid)(),this.privConnectionId=(0,r.createNoDashGuid)(),this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);const t=e?this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId):this.privAuthentication.fetch(this.privAuthFetchEventId);return this.privConnectionPromise=t.then((async t=>{this.privSynthesisTurn.onAuthCompleted(!1);const i=await this.privConnectionFactory.create(this.privSynthesizerConfig,t,this.privConnectionId);i.events.attach((e=>{this.connectionEvents.onEvent(e)}));const r=await i.open();return 200===r.statusCode?(this.privSynthesisTurn.onConnectionEstablishCompleted(r.statusCode),Promise.resolve(i)):403!==r.statusCode||e?(this.privSynthesisTurn.onConnectionEstablishCompleted(r.statusCode),Promise.reject(`Unable to contact server. StatusCode: ${r.statusCode},\n ${this.privSynthesizerConfig.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Url)} Reason: ${r.reason}`)):this.connectImpl(!0)}),(e=>{throw this.privSynthesisTurn.onAuthCompleted(!0),new Error(e)})),this.privConnectionPromise.catch((()=>{})),this.privConnectionPromise}sendSpeechServiceConfig(e,t){if(t)return e.send(new o.SpeechConnectionMessage(r.MessageType.Text,"speech.config",this.privSynthesisTurn.requestId,"application/json",t))}sendSsmlMessage(e,t,i){return e.send(new o.SpeechConnectionMessage(r.MessageType.Text,"ssml",i,"application/ssml+xml",t))}async sendStreamingSynthesisContext(e,t,i){this.setSynthesisContextSynthesisSection();const s={bidirectionalStreamingMode:!0},a=this.privSynthesizerConfig.parameters.getProperty(n.PropertyId.SpeechServiceConnection_SynthVoice,""),c=this.privSynthesizerConfig.parameters.getProperty(n.PropertyId.SpeechServiceConnection_SynthLanguage,"en-US");a&&(s.voiceName=a),s.language=c;const p=t.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Pitch,void 0),u=t.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Rate,void 0),h=t.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Volume,void 0),d=t.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Style,void 0),v=t.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_Temperature,void 0),l=t.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_CustomLexiconUrl,void 0),g=t.properties.getProperty(n.PropertyId.SpeechSynthesisRequest_PreferLocales,void 0);void 0!==p&&(s.pitch=p),void 0!==u&&(s.rate=u),void 0!==h&&(s.volume=h),void 0!==d&&(s.style=d),void 0!==v&&(s.temperature=v),void 0!==l&&(s.customLexiconUrl=l),void 0!==g&&(s.preferLocales=g);const S=this.privSynthesisContext.getSection("synthesis")??{};this.privSynthesisContext.setSection("synthesis",{...S,input:s});const f=this.privSynthesisContext.toJSON();if(f)return e.send(new o.SpeechConnectionMessage(r.MessageType.Text,"synthesis.context",i,"application/json",f))}async sendTextPiece(e,t,i){return e.send(new o.SpeechConnectionMessage(r.MessageType.Text,"text.piece",i,"text/plain",t))}async sendTextStreamEnd(e,t){return e.send(new o.SpeechConnectionMessage(r.MessageType.Text,"text.end",t,"text/plain",""))}async fetchConnection(){return void 0!==this.privConnectionConfigurationPromise?this.privConnectionConfigurationPromise.then((e=>e.state()===r.ConnectionState.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(),await this.privConnectionConfigurationPromise)}async configureConnection(){const e=await this.connectImpl();return void 0!==this.configConnectionOverride?this.configConnectionOverride(e):(this.setSpeechConfigSynthesisSection(),await this.sendSpeechServiceConfig(e,this.privSynthesizerConfig.SpeechServiceConfig.serialize()),e)}onAvatarEvent(e){}onSynthesisStarted(e){}onSynthesizing(e){}onSynthesisCancelled(e){}onSynthesisCompleted(e){}onWordBoundary(e){}onVisemeReceived(e){}onBookmarkReached(e){}}t.SynthesisAdapterBase=a,a.telemetryDataEnabled=!0},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AvatarSynthesisAdapter=void 0;const r=i(85),n=i(2);class s extends n.SynthesisAdapterBase{constructor(e,t,i,r,n){super(e,t,i,void 0),this.privAvatarSynthesizer=r,this.privSynthesizer=r,this.privAvatarConfig=n}setSynthesisContextSynthesisSection(){this.privSynthesisContext.setSynthesisSection(void 0)}setSpeechConfigSynthesisSection(){const e={background:{color:this.privAvatarConfig.backgroundColor,image:{url:this.privAvatarConfig.backgroundImage?.toString()}},character:this.privAvatarConfig.character,customized:this.privAvatarConfig.customized,photoAvatarBaseModel:this.privAvatarConfig.photoAvatarBaseModel,style:this.privAvatarConfig.style,useBuiltInVoice:this.privAvatarConfig.useBuiltInVoice};this.privAvatarConfig.scene&&(e.scene={amplitude:this.privAvatarConfig.scene.amplitude,positionX:this.privAvatarConfig.scene.positionX,positionY:this.privAvatarConfig.scene.positionY,rotationX:this.privAvatarConfig.scene.rotationX,rotationY:this.privAvatarConfig.scene.rotationY,rotationZ:this.privAvatarConfig.scene.rotationZ,zoom:this.privAvatarConfig.scene.zoom}),this.privSynthesizerConfig.synthesisVideoSection={format:{bitrate:this.privAvatarConfig.videoFormat?.bitrate,codec:this.privAvatarConfig.videoFormat?.codec,crop:{bottomRight:{x:this.privAvatarConfig.videoFormat?.cropRange?.bottomRight?.x,y:this.privAvatarConfig.videoFormat?.cropRange?.bottomRight?.y},topLeft:{x:this.privAvatarConfig.videoFormat?.cropRange?.topLeft?.x,y:this.privAvatarConfig.videoFormat?.cropRange?.topLeft?.y}},resolution:{height:this.privAvatarConfig.videoFormat?.height,width:this.privAvatarConfig.videoFormat?.width}},protocol:{name:"WebRTC",webrtcConfig:{clientDescription:btoa(this.privSynthesizerConfig.parameters.getProperty(r.PropertyId.TalkingAvatarService_WebRTC_SDP)),iceServers:this.privAvatarConfig.remoteIceServers??this.privAvatarSynthesizer.iceServers}},talkingAvatar:e}}onAvatarEvent(e){if(this.privAvatarSynthesizer.avatarEventReceived){const t=new r.AvatarEventArgs(e.Data.Offset,e.Data.Name);try{this.privAvatarSynthesizer.avatarEventReceived(this.privAvatarSynthesizer,t)}catch(e){}}}}t.AvatarSynthesisAdapter=s},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpeechSynthesisAdapter=void 0;const r=i(85),n=i(2);class s extends n.SynthesisAdapterBase{constructor(e,t,i,r,n){super(e,t,i,n),this.privSpeechSynthesizer=r,this.privSynthesizer=r}setSynthesisContextSynthesisSection(){this.privSynthesisContext.setSynthesisSection(this.privSpeechSynthesizer)}onSynthesisStarted(e){const t=new r.SpeechSynthesisEventArgs(new r.SpeechSynthesisResult(e,r.ResultReason.SynthesizingAudioStarted));this.privSpeechSynthesizer.synthesisStarted&&this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer,t)}onSynthesizing(e){if(this.privSpeechSynthesizer.synthesizing)try{const t=this.privSynthesisTurn.audioOutputFormat.addHeader(e),i=new r.SpeechSynthesisEventArgs(new r.SpeechSynthesisResult(this.privSynthesisTurn.requestId,r.ResultReason.SynthesizingAudio,t));this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer,i)}catch(e){}}onSynthesisCancelled(e){if(this.privSpeechSynthesizer.SynthesisCanceled){const t=new r.SpeechSynthesisEventArgs(e);try{this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer,t)}catch{}}}onSynthesisCompleted(e){if(this.privSpeechSynthesizer.synthesisCompleted)try{this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer,new r.SpeechSynthesisEventArgs(e))}catch(e){}}onWordBoundary(e){if(this.privSpeechSynthesizer.wordBoundary)try{this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer,e)}catch(e){}}onVisemeReceived(e){if(this.privSpeechSynthesizer.visemeReceived)try{this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer,e)}catch(e){}}onBookmarkReached(e){if(this.privSpeechSynthesizer.bookmarkReached)try{this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer,e)}catch(e){}}}t.SpeechSynthesisAdapter=s},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesisRestAdapter=void 0;const r=i(66),n=i(85),s=i(135),o=i(59);t.SynthesisRestAdapter=class{constructor(e,t){let i=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Endpoint,void 0);if(this.privIsCustomEndpoint=!!i,!i){const t=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Region,"westus"),r=s.ConnectionFactoryBase.getHostSuffix(t);i=e.parameters.getProperty(n.PropertyId.SpeechServiceConnection_Host,`https://${t}.tts.speech${r}`)}this.privEndpoint=i;const o=r.RestConfigBase.requestOptions;this.privRestAdapter=new r.RestMessageAdapter(o),this.privAuthentication=t}async getVoicesList(e){const t=await this.getVoicesListUri();this.privRestAdapter.setHeaders(o.HeaderNames.ConnectionId,e);const i=await this.privAuthentication.fetch(e);return this.privRestAdapter.setHeaders(i.headerName,i.token),this.privRestAdapter.request(r.RestRequestType.Get,t)}async getVoicesListUri(){if(void 0!==this.privUri)return this.privUri;const e="/cognitiveservices/voices/list",t=new URL(this.privEndpoint),i=t.pathname,r=""===i||"/"===i;if(this.privIsCustomEndpoint&&r){t.pathname="/tts/cognitiveservices/websocket/v1";const i=await s.ConnectionFactoryBase.getRedirectUrlFromEndpoint(t.toString(),!1),r=new URL(i);r.pathname=e,r.searchParams.delete("GenerateRedirectResponse"),this.privUri=r.toString()}else r?(t.pathname=e,this.privUri=t.toString()):this.privUri=`${this.privEndpoint}${e}`;return this.privUri}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesizerConfig=t.SynthesisServiceType=void 0;const r=i(2);var n;!function(e){e[e.Standard=0]="Standard",e[e.Custom=1]="Custom"}(n=t.SynthesisServiceType||(t.SynthesisServiceType={}));t.SynthesizerConfig=class{constructor(e,t){this.privSynthesisServiceType=n.Standard,this.avatarEnabled=!1,this.privSpeechServiceConfig=e||new r.SpeechServiceConfig(new r.Context(null)),this.privParameters=t}get parameters(){return this.privParameters}get synthesisServiceType(){return this.privSynthesisServiceType}set synthesisServiceType(e){this.privSynthesisServiceType=e}set synthesisVideoSection(e){this.privSpeechServiceConfig.Context.synthesis={video:e}}get SpeechServiceConfig(){return this.privSpeechServiceConfig}setContextFromJson(e){const t=JSON.parse(e);t.system&&(this.privSpeechServiceConfig.Context.system=t.system),t.os&&(this.privSpeechServiceConfig.Context.os=t.os),t.audio&&(this.privSpeechServiceConfig.Context.audio=t.audio),t.synthesis&&(this.privSpeechServiceConfig.Context.synthesis=t.synthesis)}}},(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SynthesisContext=void 0;const r=i(85);t.SynthesisContext=class{constructor(){this.privContext={}}setSection(e,t){this.privContext[e]=t}set audioOutputFormat(e){this.privAudioOutputFormat=e}toJSON(){return JSON.stringify(this.privContext)}getSection(e){return this.privContext[e]}setSynthesisSection(e){const t=this.buildSynthesisContext(e);this.setSection("synthesis",t)}buildSynthesisContext(e){return{audio:{metadataOptions:{bookmarkEnabled:!!e?.bookmarkReached,punctuationBoundaryEnabled:e?.properties.getProperty(r.PropertyId.SpeechServiceResponse_RequestPunctuationBoundary,!!e?.wordBoundary),sentenceBoundaryEnabled:e?.properties.getProperty(r.PropertyId.SpeechServiceResponse_RequestSentenceBoundary,!1),sessionEndEnabled:!0,visemeEnabled:!!e?.visemeReceived,wordBoundaryEnabled:e?.properties.getProperty(r.PropertyId.SpeechServiceResponse_RequestWordBoundary,!!e?.wordBoundary)},outputFormat:this.privAudioOutputFormat.requestAudioFormatString},language:{autoDetection:e?.autoDetectSourceLanguage}}}}},(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.type=t.connectivity=t.Device=t.OS=t.System=t.Context=t.SpeechServiceConfig=void 0;t.SpeechServiceConfig=class{constructor(e){this.context=e}serialize(){return JSON.stringify(this,((e,t)=>{if(t&&"object"==typeof t&&!Array.isArray(t)){const e={};for(const i in t)if(Object.hasOwnProperty.call(t,i)){e["SeparateChannelProcessing"===i?i:i&&i.charAt(0).toLowerCase()+i.substring(1)]=t[i]}return e}return t}))}get Context(){return this.context}get Recognition(){return this.recognition}set Recognition(e){this.recognition=e.toLowerCase()}};t.Context=class{constructor(e){this.system=new i,this.os=e}};class i{constructor(){this.name="SpeechSDK",this.version="1.51.0",this.build="JavaScript",this.lang="JavaScript"}}t.System=i;t.OS=class{constructor(e,t,i){this.platform=e,this.name=t,this.version=i}};t.Device=class{constructor(e,t,i){this.manufacturer=e,this.model=t,this.version=i}},function(e){e.Bluetooth="Bluetooth",e.Wired="Wired",e.WiFi="WiFi",e.Cellular="Cellular",e.InBuilt="InBuilt",e.Unknown="Unknown"}(t.connectivity||(t.connectivity={})),function(e){e.Phone="Phone",e.Speaker="Speaker",e.Car="Car",e.Headset="Headset",e.Thermostat="Thermostat",e.Microphones="Microphones",e.Deskphone="Deskphone",e.RemoteControl="RemoteControl",e.Unknown="Unknown",e.File="File",e.Stream="Stream"}(t.type||(t.type={}))}],t={};function i(r){var n=t[r];if(void 0!==n)return n.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,i),s.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};(()=>{"use strict";i.r(r);var e=i(1);window.SpeechSDK=e})()})(); \ No newline at end of file diff --git a/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/microsoft.cognitiveservices.speech.sdk.bundle.js b/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/microsoft.cognitiveservices.speech.sdk.bundle.js index a7965de2..115a34b9 100644 --- a/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/microsoft.cognitiveservices.speech.sdk.bundle.js +++ b/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/microsoft.cognitiveservices.speech.sdk.bundle.js @@ -1,103 +1,8 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -window.SpeechSDK = __webpack_require__(1); - - - -/***/ }), +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ([ +/* 0 */, /* 1 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -109,24 +14,24 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* eslint-disable @typescript-eslint/no-unused-vars */ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(4); -// Common.Storage.SetLocalStorage(new Common.Browser.LocalStorage()); -// Common.Storage.SetSessionStorage(new Common.Browser.SessionStorage()); -Exports_2.Events.instance.attachListener(new Exports_1.ConsoleLoggingListener()); +const Exports_js_1 = __webpack_require__(2); +// Note: this instantiation ensures the above import isn't +// removed on compile. The import being absent causes an error on running +void new Exports_js_1.AgentConfig(); // Speech SDK API -__exportStar(__webpack_require__(61), exports); +__exportStar(__webpack_require__(85), exports); /***/ }), /* 2 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -140,101 +45,126 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AutoDetectSourceLanguagesOpenRangeOptionName = exports.ForceDictationPropertyName = exports.ServicePropertiesPropertyName = exports.CancellationErrorCodePropertyName = exports.OutputFormatPropertyName = exports.SpeechSynthesisAdapter = exports.AvatarSynthesisAdapter = void 0; +// Make sure not to export internal modules. +// __exportStar(__webpack_require__(3), exports); -__exportStar(__webpack_require__(51), exports); -__exportStar(__webpack_require__(52), exports); +__exportStar(__webpack_require__(61), exports); +__exportStar(__webpack_require__(60), exports); +__exportStar(__webpack_require__(62), exports); +__exportStar(__webpack_require__(63), exports); +__exportStar(__webpack_require__(64), exports); +__exportStar(__webpack_require__(65), exports); +__exportStar(__webpack_require__(202), exports); +__exportStar(__webpack_require__(203), exports); +__exportStar(__webpack_require__(204), exports); +__exportStar(__webpack_require__(205), exports); +__exportStar(__webpack_require__(206), exports); +__exportStar(__webpack_require__(207), exports); +__exportStar(__webpack_require__(208), exports); +__exportStar(__webpack_require__(209), exports); +__exportStar(__webpack_require__(180), exports); +__exportStar(__webpack_require__(211), exports); +__exportStar(__webpack_require__(212), exports); +__exportStar(__webpack_require__(213), exports); +__exportStar(__webpack_require__(214), exports); +__exportStar(__webpack_require__(215), exports); +__exportStar(__webpack_require__(216), exports); +__exportStar(__webpack_require__(217), exports); +__exportStar(__webpack_require__(218), exports); +__exportStar(__webpack_require__(219), exports); +__exportStar(__webpack_require__(220), exports); +__exportStar(__webpack_require__(221), exports); +__exportStar(__webpack_require__(223), exports); +__exportStar(__webpack_require__(224), exports); +__exportStar(__webpack_require__(225), exports); +__exportStar(__webpack_require__(226), exports); +__exportStar(__webpack_require__(228), exports); +__exportStar(__webpack_require__(230), exports); +__exportStar(__webpack_require__(231), exports); __exportStar(__webpack_require__(233), exports); -__exportStar(__webpack_require__(234), exports); -__exportStar(__webpack_require__(235), exports); -__exportStar(__webpack_require__(236), exports); -__exportStar(__webpack_require__(249), exports); +__exportStar(__webpack_require__(239), exports); +__exportStar(__webpack_require__(240), exports); +__exportStar(__webpack_require__(244), exports); +__exportStar(__webpack_require__(245), exports); +__exportStar(__webpack_require__(247), exports); +var AvatarSynthesisAdapter_js_1 = __webpack_require__(248); +Object.defineProperty(exports, "AvatarSynthesisAdapter", ({ enumerable: true, get: function () { return AvatarSynthesisAdapter_js_1.AvatarSynthesisAdapter; } })); +var SpeechSynthesisAdapter_js_1 = __webpack_require__(249); +Object.defineProperty(exports, "SpeechSynthesisAdapter", ({ enumerable: true, get: function () { return SpeechSynthesisAdapter_js_1.SpeechSynthesisAdapter; } })); __exportStar(__webpack_require__(250), exports); __exportStar(__webpack_require__(251), exports); -__exportStar(__webpack_require__(210), exports); +__exportStar(__webpack_require__(252), exports); +__exportStar(__webpack_require__(253), exports); +exports.OutputFormatPropertyName = "OutputFormat"; +exports.CancellationErrorCodePropertyName = "CancellationErrorCode"; +exports.ServicePropertiesPropertyName = "ServiceProperties"; +exports.ForceDictationPropertyName = "ForceDictation"; +exports.AutoDetectSourceLanguagesOpenRangeOptionName = "UND"; /***/ }), /* 3 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConsoleLoggingListener = void 0; -var Exports_1 = __webpack_require__(4); -var ConsoleLoggingListener = /** @class */ (function () { - function ConsoleLoggingListener(logLevelFilter) { - var _this = this; - if (logLevelFilter === void 0) { logLevelFilter = Exports_1.EventType.Warning; } - this.onEvent = function (event) { - if (event.eventType >= _this.privLogLevelFilter) { - var log = _this.toString(event); - switch (event.eventType) { - case Exports_1.EventType.Debug: - // tslint:disable-next-line:no-console - console.debug(log); - break; - case Exports_1.EventType.Info: - // tslint:disable-next-line:no-console - console.info(log); - break; - case Exports_1.EventType.Warning: - // tslint:disable-next-line:no-console - console.warn(log); - break; - case Exports_1.EventType.Error: - // tslint:disable-next-line:no-console - console.error(log); - break; - default: - // tslint:disable-next-line:no-console - console.log(log); - break; - } - } - }; - this.toString = function (event) { - var logFragments = [ - "" + event.EventTime, - "" + event.Name, - ]; - for (var prop in event) { - if (prop && event.hasOwnProperty(prop) && - prop !== "eventTime" && prop !== "eventType" && - prop !== "eventId" && prop !== "name" && - prop !== "constructor") { - var value = event[prop]; - var valueToLog = ""; - if (value !== undefined && value !== null) { - if (typeof (value) === "number" || typeof (value) === "string") { - valueToLog = value.toString(); - } - else { - valueToLog = JSON.stringify(value); - } - } - logFragments.push(prop + ": " + valueToLog); - } - } - return logFragments.join(" | "); - }; - this.privLogLevelFilter = logLevelFilter; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CognitiveSubscriptionKeyAuthentication = void 0; +const Exports_js_1 = __webpack_require__(4); +const HeaderNames_js_1 = __webpack_require__(59); +const IAuthentication_js_1 = __webpack_require__(60); +/** + * @class + */ +class CognitiveSubscriptionKeyAuthentication { + /** + * Creates and initializes an instance of the CognitiveSubscriptionKeyAuthentication class. + * @constructor + * @param {string} subscriptionKey - The subscription key + */ + constructor(subscriptionKey) { + if (!subscriptionKey) { + throw new Exports_js_1.ArgumentNullError("subscriptionKey"); + } + this.privAuthInfo = new IAuthentication_js_1.AuthInfo(HeaderNames_js_1.HeaderNames.AuthKey, subscriptionKey); } - return ConsoleLoggingListener; -}()); -exports.ConsoleLoggingListener = ConsoleLoggingListener; + /** + * Fetches the subscription key. + * @member + * @function + * @public + * @param {string} authFetchEventId - The id to fetch. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + fetch(authFetchEventId) { + return Promise.resolve(this.privAuthInfo); + } + /** + * Fetches the subscription key. + * @member + * @function + * @public + * @param {string} authFetchEventId - The id to fetch. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + fetchOnExpiry(authFetchEventId) { + return Promise.resolve(this.privAuthInfo); + } +} +exports.CognitiveSubscriptionKeyAuthentication = CognitiveSubscriptionKeyAuthentication; /***/ }), /* 4 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -248,1293 +178,1163 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranslationStatus = void 0; __exportStar(__webpack_require__(5), exports); -__exportStar(__webpack_require__(23), exports); -__exportStar(__webpack_require__(24), exports); -__exportStar(__webpack_require__(26), exports); -__exportStar(__webpack_require__(27), exports); -__exportStar(__webpack_require__(25), exports); -__exportStar(__webpack_require__(28), exports); __exportStar(__webpack_require__(29), exports); -__exportStar(__webpack_require__(7), exports); __exportStar(__webpack_require__(30), exports); -__exportStar(__webpack_require__(31), exports); __exportStar(__webpack_require__(32), exports); __exportStar(__webpack_require__(33), exports); __exportStar(__webpack_require__(34), exports); +__exportStar(__webpack_require__(31), exports); __exportStar(__webpack_require__(35), exports); __exportStar(__webpack_require__(36), exports); +__exportStar(__webpack_require__(7), exports); __exportStar(__webpack_require__(37), exports); __exportStar(__webpack_require__(38), exports); __exportStar(__webpack_require__(39), exports); -__exportStar(__webpack_require__(6), exports); __exportStar(__webpack_require__(40), exports); __exportStar(__webpack_require__(41), exports); __exportStar(__webpack_require__(42), exports); __exportStar(__webpack_require__(43), exports); __exportStar(__webpack_require__(44), exports); -var TranslationStatus_1 = __webpack_require__(45); -Object.defineProperty(exports, "TranslationStatus", { enumerable: true, get: function () { return TranslationStatus_1.TranslationStatus; } }); +__exportStar(__webpack_require__(45), exports); __exportStar(__webpack_require__(46), exports); __exportStar(__webpack_require__(47), exports); +__exportStar(__webpack_require__(6), exports); __exportStar(__webpack_require__(48), exports); __exportStar(__webpack_require__(49), exports); __exportStar(__webpack_require__(50), exports); +__exportStar(__webpack_require__(51), exports); +__exportStar(__webpack_require__(52), exports); +var TranslationStatus_js_1 = __webpack_require__(53); +Object.defineProperty(exports, "TranslationStatus", ({ enumerable: true, get: function () { return TranslationStatus_js_1.TranslationStatus; } })); +__exportStar(__webpack_require__(54), exports); +__exportStar(__webpack_require__(55), exports); +__exportStar(__webpack_require__(56), exports); +__exportStar(__webpack_require__(57), exports); +__exportStar(__webpack_require__(58), exports); /***/ }), /* 5 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AudioStreamNodeErrorEvent = exports.AudioStreamNodeDetachedEvent = exports.AudioStreamNodeAttachedEvent = exports.AudioStreamNodeAttachingEvent = exports.AudioStreamNodeEvent = exports.AudioSourceErrorEvent = exports.AudioSourceOffEvent = exports.AudioSourceReadyEvent = exports.AudioSourceInitializingEvent = exports.AudioSourceEvent = void 0; -// tslint:disable:max-classes-per-file -var PlatformEvent_1 = __webpack_require__(6); -var AudioSourceEvent = /** @class */ (function (_super) { - __extends(AudioSourceEvent, _super); - function AudioSourceEvent(eventName, audioSourceId, eventType) { - if (eventType === void 0) { eventType = PlatformEvent_1.EventType.Info; } - var _this = _super.call(this, eventName, eventType) || this; - _this.privAudioSourceId = audioSourceId; - return _this; - } - Object.defineProperty(AudioSourceEvent.prototype, "audioSourceId", { - get: function () { - return this.privAudioSourceId; - }, - enumerable: false, - configurable: true - }); - return AudioSourceEvent; -}(PlatformEvent_1.PlatformEvent)); +/* eslint-disable max-classes-per-file */ +const PlatformEvent_js_1 = __webpack_require__(6); +class AudioSourceEvent extends PlatformEvent_js_1.PlatformEvent { + constructor(eventName, audioSourceId, eventType = PlatformEvent_js_1.EventType.Info) { + super(eventName, eventType); + this.privAudioSourceId = audioSourceId; + } + get audioSourceId() { + return this.privAudioSourceId; + } +} exports.AudioSourceEvent = AudioSourceEvent; -var AudioSourceInitializingEvent = /** @class */ (function (_super) { - __extends(AudioSourceInitializingEvent, _super); - function AudioSourceInitializingEvent(audioSourceId) { - return _super.call(this, "AudioSourceInitializingEvent", audioSourceId) || this; +class AudioSourceInitializingEvent extends AudioSourceEvent { + constructor(audioSourceId) { + super("AudioSourceInitializingEvent", audioSourceId); } - return AudioSourceInitializingEvent; -}(AudioSourceEvent)); +} exports.AudioSourceInitializingEvent = AudioSourceInitializingEvent; -var AudioSourceReadyEvent = /** @class */ (function (_super) { - __extends(AudioSourceReadyEvent, _super); - function AudioSourceReadyEvent(audioSourceId) { - return _super.call(this, "AudioSourceReadyEvent", audioSourceId) || this; +class AudioSourceReadyEvent extends AudioSourceEvent { + constructor(audioSourceId) { + super("AudioSourceReadyEvent", audioSourceId); } - return AudioSourceReadyEvent; -}(AudioSourceEvent)); +} exports.AudioSourceReadyEvent = AudioSourceReadyEvent; -var AudioSourceOffEvent = /** @class */ (function (_super) { - __extends(AudioSourceOffEvent, _super); - function AudioSourceOffEvent(audioSourceId) { - return _super.call(this, "AudioSourceOffEvent", audioSourceId) || this; +class AudioSourceOffEvent extends AudioSourceEvent { + constructor(audioSourceId) { + super("AudioSourceOffEvent", audioSourceId); } - return AudioSourceOffEvent; -}(AudioSourceEvent)); +} exports.AudioSourceOffEvent = AudioSourceOffEvent; -var AudioSourceErrorEvent = /** @class */ (function (_super) { - __extends(AudioSourceErrorEvent, _super); - function AudioSourceErrorEvent(audioSourceId, error) { - var _this = _super.call(this, "AudioSourceErrorEvent", audioSourceId, PlatformEvent_1.EventType.Error) || this; - _this.privError = error; - return _this; - } - Object.defineProperty(AudioSourceErrorEvent.prototype, "error", { - get: function () { - return this.privError; - }, - enumerable: false, - configurable: true - }); - return AudioSourceErrorEvent; -}(AudioSourceEvent)); +class AudioSourceErrorEvent extends AudioSourceEvent { + constructor(audioSourceId, error) { + super("AudioSourceErrorEvent", audioSourceId, PlatformEvent_js_1.EventType.Error); + this.privError = error; + } + get error() { + return this.privError; + } +} exports.AudioSourceErrorEvent = AudioSourceErrorEvent; -var AudioStreamNodeEvent = /** @class */ (function (_super) { - __extends(AudioStreamNodeEvent, _super); - function AudioStreamNodeEvent(eventName, audioSourceId, audioNodeId) { - var _this = _super.call(this, eventName, audioSourceId) || this; - _this.privAudioNodeId = audioNodeId; - return _this; - } - Object.defineProperty(AudioStreamNodeEvent.prototype, "audioNodeId", { - get: function () { - return this.privAudioNodeId; - }, - enumerable: false, - configurable: true - }); - return AudioStreamNodeEvent; -}(AudioSourceEvent)); +class AudioStreamNodeEvent extends AudioSourceEvent { + constructor(eventName, audioSourceId, audioNodeId) { + super(eventName, audioSourceId); + this.privAudioNodeId = audioNodeId; + } + get audioNodeId() { + return this.privAudioNodeId; + } +} exports.AudioStreamNodeEvent = AudioStreamNodeEvent; -var AudioStreamNodeAttachingEvent = /** @class */ (function (_super) { - __extends(AudioStreamNodeAttachingEvent, _super); - function AudioStreamNodeAttachingEvent(audioSourceId, audioNodeId) { - return _super.call(this, "AudioStreamNodeAttachingEvent", audioSourceId, audioNodeId) || this; +class AudioStreamNodeAttachingEvent extends AudioStreamNodeEvent { + constructor(audioSourceId, audioNodeId) { + super("AudioStreamNodeAttachingEvent", audioSourceId, audioNodeId); } - return AudioStreamNodeAttachingEvent; -}(AudioStreamNodeEvent)); +} exports.AudioStreamNodeAttachingEvent = AudioStreamNodeAttachingEvent; -var AudioStreamNodeAttachedEvent = /** @class */ (function (_super) { - __extends(AudioStreamNodeAttachedEvent, _super); - function AudioStreamNodeAttachedEvent(audioSourceId, audioNodeId) { - return _super.call(this, "AudioStreamNodeAttachedEvent", audioSourceId, audioNodeId) || this; +class AudioStreamNodeAttachedEvent extends AudioStreamNodeEvent { + constructor(audioSourceId, audioNodeId) { + super("AudioStreamNodeAttachedEvent", audioSourceId, audioNodeId); } - return AudioStreamNodeAttachedEvent; -}(AudioStreamNodeEvent)); +} exports.AudioStreamNodeAttachedEvent = AudioStreamNodeAttachedEvent; -var AudioStreamNodeDetachedEvent = /** @class */ (function (_super) { - __extends(AudioStreamNodeDetachedEvent, _super); - function AudioStreamNodeDetachedEvent(audioSourceId, audioNodeId) { - return _super.call(this, "AudioStreamNodeDetachedEvent", audioSourceId, audioNodeId) || this; +class AudioStreamNodeDetachedEvent extends AudioStreamNodeEvent { + constructor(audioSourceId, audioNodeId) { + super("AudioStreamNodeDetachedEvent", audioSourceId, audioNodeId); } - return AudioStreamNodeDetachedEvent; -}(AudioStreamNodeEvent)); +} exports.AudioStreamNodeDetachedEvent = AudioStreamNodeDetachedEvent; -var AudioStreamNodeErrorEvent = /** @class */ (function (_super) { - __extends(AudioStreamNodeErrorEvent, _super); - function AudioStreamNodeErrorEvent(audioSourceId, audioNodeId, error) { - var _this = _super.call(this, "AudioStreamNodeErrorEvent", audioSourceId, audioNodeId) || this; - _this.privError = error; - return _this; - } - Object.defineProperty(AudioStreamNodeErrorEvent.prototype, "error", { - get: function () { - return this.privError; - }, - enumerable: false, - configurable: true - }); - return AudioStreamNodeErrorEvent; -}(AudioStreamNodeEvent)); +class AudioStreamNodeErrorEvent extends AudioStreamNodeEvent { + constructor(audioSourceId, audioNodeId, error) { + super("AudioStreamNodeErrorEvent", audioSourceId, audioNodeId); + this.privError = error; + } + get error() { + return this.privError; + } +} exports.AudioStreamNodeErrorEvent = AudioStreamNodeErrorEvent; /***/ }), /* 6 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PlatformEvent = exports.EventType = void 0; -var Guid_1 = __webpack_require__(7); +const Guid_js_1 = __webpack_require__(7); var EventType; (function (EventType) { EventType[EventType["Debug"] = 0] = "Debug"; EventType[EventType["Info"] = 1] = "Info"; EventType[EventType["Warning"] = 2] = "Warning"; EventType[EventType["Error"] = 3] = "Error"; + EventType[EventType["None"] = 4] = "None"; })(EventType = exports.EventType || (exports.EventType = {})); -var PlatformEvent = /** @class */ (function () { - function PlatformEvent(eventName, eventType) { +class PlatformEvent { + constructor(eventName, eventType) { this.privName = eventName; - this.privEventId = Guid_1.createNoDashGuid(); + this.privEventId = (0, Guid_js_1.createNoDashGuid)(); this.privEventTime = new Date().toISOString(); this.privEventType = eventType; this.privMetadata = {}; } - Object.defineProperty(PlatformEvent.prototype, "name", { - get: function () { - return this.privName; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PlatformEvent.prototype, "eventId", { - get: function () { - return this.privEventId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PlatformEvent.prototype, "eventTime", { - get: function () { - return this.privEventTime; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PlatformEvent.prototype, "eventType", { - get: function () { - return this.privEventType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PlatformEvent.prototype, "metadata", { - get: function () { - return this.privMetadata; - }, - enumerable: false, - configurable: true - }); - return PlatformEvent; -}()); + 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; + } +} exports.PlatformEvent = PlatformEvent; /***/ }), /* 7 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createNoDashGuid = exports.createGuid = void 0; -var uuid_1 = __webpack_require__(8); -var createGuid = function () { - return uuid_1.v4(); -}; +const uuid_1 = __webpack_require__(8); +const createGuid = () => (0, uuid_1.v4)(); exports.createGuid = createGuid; -var createNoDashGuid = function () { - return createGuid().replace(new RegExp("-", "g"), "").toUpperCase(); -}; +const createNoDashGuid = () => createGuid().replace(new RegExp("-", "g"), "").toUpperCase(); exports.createNoDashGuid = createNoDashGuid; /***/ }), /* 8 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _v1_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v1", function() { return _v1_js__WEBPACK_IMPORTED_MODULE_0__["default"]; }); - -/* harmony import */ var _v3_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v3", function() { return _v3_js__WEBPACK_IMPORTED_MODULE_1__["default"]; }); - -/* harmony import */ var _v4_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v4", function() { return _v4_js__WEBPACK_IMPORTED_MODULE_2__["default"]; }); - -/* harmony import */ var _v5_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v5", function() { return _v5_js__WEBPACK_IMPORTED_MODULE_3__["default"]; }); - -/* harmony import */ var _nil_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(21); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NIL", function() { return _nil_js__WEBPACK_IMPORTED_MODULE_4__["default"]; }); - -/* harmony import */ var _version_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(22); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "version", function() { return _version_js__WEBPACK_IMPORTED_MODULE_5__["default"]; }); - -/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(12); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "validate", function() { return _validate_js__WEBPACK_IMPORTED_MODULE_6__["default"]; }); - -/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(11); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stringify", function() { return _stringify_js__WEBPACK_IMPORTED_MODULE_7__["default"]; }); - -/* harmony import */ var _parse_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(16); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return _parse_js__WEBPACK_IMPORTED_MODULE_8__["default"]; }); - - - - - - - - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = exports.validate = exports.v7 = exports.v6ToV1 = exports.v6 = exports.v5 = exports.v4 = exports.v3 = exports.v1ToV6 = exports.v1 = exports.stringify = exports.parse = exports.NIL = exports.MAX = void 0; +var max_js_1 = __webpack_require__(9); +Object.defineProperty(exports, "MAX", ({ enumerable: true, get: function () { return max_js_1.default; } })); +var nil_js_1 = __webpack_require__(10); +Object.defineProperty(exports, "NIL", ({ enumerable: true, get: function () { return nil_js_1.default; } })); +var parse_js_1 = __webpack_require__(11); +Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { return parse_js_1.default; } })); +var stringify_js_1 = __webpack_require__(14); +Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return stringify_js_1.default; } })); +var v1_js_1 = __webpack_require__(15); +Object.defineProperty(exports, "v1", ({ enumerable: true, get: function () { return v1_js_1.default; } })); +var v1ToV6_js_1 = __webpack_require__(17); +Object.defineProperty(exports, "v1ToV6", ({ enumerable: true, get: function () { return v1ToV6_js_1.default; } })); +var v3_js_1 = __webpack_require__(18); +Object.defineProperty(exports, "v3", ({ enumerable: true, get: function () { return v3_js_1.default; } })); +var v4_js_1 = __webpack_require__(21); +Object.defineProperty(exports, "v4", ({ enumerable: true, get: function () { return v4_js_1.default; } })); +var v5_js_1 = __webpack_require__(23); +Object.defineProperty(exports, "v5", ({ enumerable: true, get: function () { return v5_js_1.default; } })); +var v6_js_1 = __webpack_require__(25); +Object.defineProperty(exports, "v6", ({ enumerable: true, get: function () { return v6_js_1.default; } })); +var v6ToV1_js_1 = __webpack_require__(26); +Object.defineProperty(exports, "v6ToV1", ({ enumerable: true, get: function () { return v6ToV1_js_1.default; } })); +var v7_js_1 = __webpack_require__(27); +Object.defineProperty(exports, "v7", ({ enumerable: true, get: function () { return v7_js_1.default; } })); +var validate_js_1 = __webpack_require__(12); +Object.defineProperty(exports, "validate", ({ enumerable: true, get: function () { return validate_js_1.default; } })); +var version_js_1 = __webpack_require__(28); +Object.defineProperty(exports, "version", ({ enumerable: true, get: function () { return version_js_1.default; } })); /***/ }), /* 9 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _rng_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10); -/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11); - // **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; -var _nodeId; -var _clockseq; // Previous uuid creation time +/***/ }), +/* 10 */ +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -var _lastMSecs = 0; -var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = '00000000-0000-0000-0000-000000000000'; -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || new Array(16); - options = options || {}; - var node = options.node || _nodeId; - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - if (node == null || clockseq == null) { - var seedBytes = options.random || (options.rng || _rng_js__WEBPACK_IMPORTED_MODULE_0__["default"])(); +/***/ }), +/* 11 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } +"use strict"; - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const validate_js_1 = __webpack_require__(12); +function parse(uuid) { + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Invalid UUID'); } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - - - var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) - - var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - - - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested - - - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - - var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` - - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff); +} +exports["default"] = parse; - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - b[i++] = clockseq & 0xff; // `node` +/***/ }), +/* 12 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } +"use strict"; - return buf || Object(_stringify_js__WEBPACK_IMPORTED_MODULE_1__["default"])(b); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const regex_js_1 = __webpack_require__(13); +function validate(uuid) { + return typeof uuid === 'string' && regex_js_1.default.test(uuid); } +exports["default"] = validate; -/* harmony default export */ __webpack_exports__["default"] = (v1); /***/ }), -/* 10 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 13 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return rng; }); -// Unique ID creation requires a high quality random # generator. In the browser we therefore -// require the crypto API and do not support built-in fallback to lower quality random number -// generators (like Math.random()). -var getRandomValues; -var rnds8 = new Uint8Array(16); -function rng() { - // lazy load so that environments that need to polyfill have a chance to do so - if (!getRandomValues) { - // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, - // find the complete implementation of crypto (msCrypto) on IE11. - getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); - if (!getRandomValues) { - throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - return getRandomValues(rnds8); -} /***/ }), -/* 11 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 14 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ - -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.unsafeStringify = void 0; +const validate_js_1 = __webpack_require__(12); +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); } - -function stringify(arr) { - var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!Object(_validate_js__WEBPACK_IMPORTED_MODULE_0__["default"])(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; +function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + + byteToHex[arr[offset + 1]] + + byteToHex[arr[offset + 2]] + + byteToHex[arr[offset + 3]] + + '-' + + byteToHex[arr[offset + 4]] + + byteToHex[arr[offset + 5]] + + '-' + + byteToHex[arr[offset + 6]] + + byteToHex[arr[offset + 7]] + + '-' + + byteToHex[arr[offset + 8]] + + byteToHex[arr[offset + 9]] + + '-' + + byteToHex[arr[offset + 10]] + + byteToHex[arr[offset + 11]] + + byteToHex[arr[offset + 12]] + + byteToHex[arr[offset + 13]] + + byteToHex[arr[offset + 14]] + + byteToHex[arr[offset + 15]]).toLowerCase(); } +exports.unsafeStringify = unsafeStringify; +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +exports["default"] = stringify; -/* harmony default export */ __webpack_exports__["default"] = (stringify); /***/ }), -/* 12 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 15 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _regex_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); - -function validate(uuid) { - return typeof uuid === 'string' && _regex_js__WEBPACK_IMPORTED_MODULE_0__["default"].test(uuid); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.updateV1State = void 0; +const rng_js_1 = __webpack_require__(16); +const stringify_js_1 = __webpack_require__(14); +const _state = {}; +function v1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === '_v6') { + options = undefined; + } + } + if (options) { + bytes = v1Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + } + else { + const now = Date.now(); + const rnds = (0, rng_js_1.default)(); + updateV1State(_state, now, rnds); + bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset); + } + return buf ?? (0, stringify_js_1.unsafeStringify)(bytes); } +function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 10000) { + state.node = undefined; + state.nsecs = 0; + } + } + else if (now > state.msecs) { + state.nsecs = 0; + } + else if (now < state.msecs) { + state.node = undefined; + } + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 0x01; + state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff; + } + state.msecs = now; + return state; +} +exports.updateV1State = updateV1State; +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff; + node ??= rnds.slice(10, 16); + msecs += 12219292800000; + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + buf[offset++] = (tl >>> 24) & 0xff; + buf[offset++] = (tl >>> 16) & 0xff; + buf[offset++] = (tl >>> 8) & 0xff; + buf[offset++] = tl & 0xff; + const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff; + buf[offset++] = (tmh >>> 8) & 0xff; + buf[offset++] = tmh & 0xff; + buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10; + buf[offset++] = (tmh >>> 16) & 0xff; + buf[offset++] = (clockseq >>> 8) | 0x80; + buf[offset++] = clockseq & 0xff; + for (let n = 0; n < 6; ++n) { + buf[offset++] = node[n]; + } + return buf; +} +exports["default"] = v1; -/* harmony default export */ __webpack_exports__["default"] = (validate); /***/ }), -/* 13 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 16 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony default export */ __webpack_exports__["default"] = (/^(?:[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); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +let getRandomValues; +const rnds8 = new Uint8Array(16); +function rng() { + if (!getRandomValues) { + if (typeof crypto === 'undefined' || !crypto.getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + getRandomValues = crypto.getRandomValues.bind(crypto); + } + return getRandomValues(rnds8); +} +exports["default"] = rng; + /***/ }), -/* 14 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 17 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _v35_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15); -/* harmony import */ var _md5_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const parse_js_1 = __webpack_require__(11); +const stringify_js_1 = __webpack_require__(14); +function v1ToV6(uuid) { + const v1Bytes = typeof uuid === 'string' ? (0, parse_js_1.default)(uuid) : uuid; + const v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? (0, stringify_js_1.unsafeStringify)(v6Bytes) : v6Bytes; +} +exports["default"] = v1ToV6; +function _v1ToV6(v1Bytes) { + return Uint8Array.of(((v1Bytes[6] & 0x0f) << 4) | ((v1Bytes[7] >> 4) & 0x0f), ((v1Bytes[7] & 0x0f) << 4) | ((v1Bytes[4] & 0xf0) >> 4), ((v1Bytes[4] & 0x0f) << 4) | ((v1Bytes[5] & 0xf0) >> 4), ((v1Bytes[5] & 0x0f) << 4) | ((v1Bytes[0] & 0xf0) >> 4), ((v1Bytes[0] & 0x0f) << 4) | ((v1Bytes[1] & 0xf0) >> 4), ((v1Bytes[1] & 0x0f) << 4) | ((v1Bytes[2] & 0xf0) >> 4), 0x60 | (v1Bytes[2] & 0x0f), v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} -var v3 = Object(_v35_js__WEBPACK_IMPORTED_MODULE_0__["default"])('v3', 0x30, _md5_js__WEBPACK_IMPORTED_MODULE_1__["default"]); -/* harmony default export */ __webpack_exports__["default"] = (v3); /***/ }), -/* 15 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 18 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DNS", function() { return DNS; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URL", function() { return URL; }); -/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11); -/* harmony import */ var _parse_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.URL = exports.DNS = void 0; +const md5_js_1 = __webpack_require__(19); +const v35_js_1 = __webpack_require__(20); +var v35_js_2 = __webpack_require__(20); +Object.defineProperty(exports, "DNS", ({ enumerable: true, get: function () { return v35_js_2.DNS; } })); +Object.defineProperty(exports, "URL", ({ enumerable: true, get: function () { return v35_js_2.URL; } })); +function v3(value, namespace, buf, offset) { + return (0, v35_js_1.default)(0x30, md5_js_1.default, value, namespace, buf, offset); +} +v3.DNS = v35_js_1.DNS; +v3.URL = v35_js_1.URL; +exports["default"] = v3; -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape +/***/ }), +/* 19 */ +/***/ ((__unused_webpack_module, exports) => { - var bytes = []; +"use strict"; - for (var i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - - return bytes; -} - -var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -/* harmony default export */ __webpack_exports__["default"] = (function (name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } - - if (typeof namespace === 'string') { - namespace = Object(_parse_js__WEBPACK_IMPORTED_MODULE_1__["default"])(namespace); - } - - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - - - var bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - - return buf; - } - - return Object(_stringify_js__WEBPACK_IMPORTED_MODULE_0__["default"])(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -}); - -/***/ }), -/* 16 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); - - -function parse(uuid) { - if (!Object(_validate_js__WEBPACK_IMPORTED_MODULE_0__["default"])(uuid)) { - throw TypeError('Invalid UUID'); - } - - var v; - var arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} - -/* harmony default export */ __webpack_exports__["default"] = (parse); - -/***/ }), -/* 17 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* - * Browser-compatible JavaScript MD5 - * - * Modification of JavaScript MD5 - * https://github.com/blueimp/JavaScript-MD5 - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * https://opensource.org/licenses/MIT - * - * Based on - * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - * Digest Algorithm, as defined in RFC 1321. - * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for more info. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); function md5(bytes) { - if (typeof bytes === 'string') { - var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - - bytes = new Uint8Array(msg.length); - - for (var i = 0; i < msg.length; ++i) { - bytes[i] = msg.charCodeAt(i); - } - } - - return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); + const words = uint8ToUint32(bytes); + const md5Bytes = wordsToMd5(words, bytes.length * 8); + return uint32ToUint8(md5Bytes); } -/* - * Convert an array of little-endian words to an array of bytes - */ - - -function md5ToHexEncodedArray(input) { - var output = []; - var length32 = input.length * 32; - var hexTab = '0123456789abcdef'; - - for (var i = 0; i < length32; i += 8) { - var x = input[i >> 5] >>> i % 32 & 0xff; - var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); - output.push(hex); - } - - return output; +function uint32ToUint8(input) { + const bytes = new Uint8Array(input.length * 4); + for (let i = 0; i < input.length * 4; i++) { + bytes[i] = (input[i >> 2] >>> ((i % 4) * 8)) & 0xff; + } + return bytes; } -/** - * Calculate output length with padding and bit length - */ - - function getOutputLength(inputLength8) { - return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; + return (((inputLength8 + 64) >>> 9) << 4) + 14 + 1; } -/* - * Calculate the MD5 of an array of little-endian words, and a bit length. - */ - - function wordsToMd5(x, len) { - /* append padding */ - x[len >> 5] |= 0x80 << len % 32; - x[getOutputLength(len) - 1] = len; - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for (var i = 0; i < x.length; i += 16) { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - a = md5ff(a, b, c, d, x[i], 7, -680876936); - d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); - c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); - b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); - a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); - d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); - c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); - b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); - a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); - d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); - c = md5ff(c, d, a, b, x[i + 10], 17, -42063); - b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); - a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); - d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); - c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); - b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); - a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); - d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); - c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); - b = md5gg(b, c, d, a, x[i], 20, -373897302); - a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); - d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); - c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); - b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); - a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); - d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); - c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); - b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); - a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); - d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); - c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); - b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); - a = md5hh(a, b, c, d, x[i + 5], 4, -378558); - d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); - c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); - b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); - a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); - d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); - c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); - b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); - a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); - d = md5hh(d, a, b, c, x[i], 11, -358537222); - c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); - b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); - a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); - d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); - c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); - b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); - a = md5ii(a, b, c, d, x[i], 6, -198630844); - d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); - c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); - b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); - a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); - d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); - c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); - b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); - a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); - d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); - c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); - b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); - a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); - d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); - c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); - b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); - a = safeAdd(a, olda); - b = safeAdd(b, oldb); - c = safeAdd(c, oldc); - d = safeAdd(d, oldd); - } - - return [a, b, c, d]; + const xpad = new Uint32Array(getOutputLength(len)).fill(0); + xpad.set(x); + xpad[len >> 5] |= 0x80 << len % 32; + xpad[xpad.length - 1] = len; + x = xpad; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + return Uint32Array.of(a, b, c, d); } -/* - * Convert an array bytes to an array of little-endian words - * Characters >255 have their high-byte silently ignored. - */ - - -function bytesToWords(input) { - if (input.length === 0) { - return []; - } - - var length8 = input.length * 8; - var output = new Uint32Array(getOutputLength(length8)); - - for (var i = 0; i < length8; i += 8) { - output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; - } - - return output; +function uint8ToUint32(input) { + if (input.length === 0) { + return new Uint32Array(); + } + const output = new Uint32Array(getOutputLength(input.length * 8)).fill(0); + for (let i = 0; i < input.length; i++) { + output[i >> 2] |= (input[i] & 0xff) << ((i % 4) * 8); + } + return output; } -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ - - function safeAdd(x, y) { - var lsw = (x & 0xffff) + (y & 0xffff); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return msw << 16 | lsw & 0xffff; + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xffff); } -/* - * Bitwise rotate a 32-bit number to the left. - */ - - function bitRotateLeft(num, cnt) { - return num << cnt | num >>> 32 - cnt; + return (num << cnt) | (num >>> (32 - cnt)); } -/* - * These functions implement the four basic operations the algorithm uses. - */ - - function md5cmn(q, a, b, x, s, t) { - return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } - function md5ff(a, b, c, d, x, s, t) { - return md5cmn(b & c | ~b & d, a, b, x, s, t); + return md5cmn((b & c) | (~b & d), a, b, x, s, t); } - function md5gg(a, b, c, d, x, s, t) { - return md5cmn(b & d | c & ~d, a, b, x, s, t); + return md5cmn((b & d) | (c & ~d), a, b, x, s, t); } - function md5hh(a, b, c, d, x, s, t) { - return md5cmn(b ^ c ^ d, a, b, x, s, t); + return md5cmn(b ^ c ^ d, a, b, x, s, t); } - function md5ii(a, b, c, d, x, s, t) { - return md5cmn(c ^ (b | ~d), a, b, x, s, t); + return md5cmn(c ^ (b | ~d), a, b, x, s, t); } +exports["default"] = md5; -/* harmony default export */ __webpack_exports__["default"] = (md5); /***/ }), -/* 18 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 20 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _rng_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10); -/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11); - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.URL = exports.DNS = exports.stringToBytes = void 0; +const parse_js_1 = __webpack_require__(11); +const stringify_js_1 = __webpack_require__(14); +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} +exports.stringToBytes = stringToBytes; +exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +function v35(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === 'string' ? stringToBytes(value) : value; + const namespaceBytes = typeof namespace === 'string' ? (0, parse_js_1.default)(namespace) : namespace; + if (typeof namespace === 'string') { + namespace = (0, parse_js_1.default)(namespace); + } + if (namespace?.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return (0, stringify_js_1.unsafeStringify)(bytes); +} +exports["default"] = v35; -function v4(options, buf, offset) { - options = options || {}; - var rnds = options.random || (options.rng || _rng_js__WEBPACK_IMPORTED_MODULE_0__["default"])(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided +/***/ }), +/* 21 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (buf) { - offset = offset || 0; +"use strict"; - for (var i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const native_js_1 = __webpack_require__(22); +const rng_js_1 = __webpack_require__(16); +const stringify_js_1 = __webpack_require__(14); +function v4(options, buf, offset) { + if (native_js_1.default.randomUUID && !buf && !options) { + return native_js_1.default.randomUUID(); } - - return buf; - } - - return Object(_stringify_js__WEBPACK_IMPORTED_MODULE_1__["default"])(rnds); + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? (0, rng_js_1.default)(); + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return (0, stringify_js_1.unsafeStringify)(rnds); } +exports["default"] = v4; -/* harmony default export */ __webpack_exports__["default"] = (v4); /***/ }), -/* 19 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 22 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _v35_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15); -/* harmony import */ var _sha1_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +exports["default"] = { randomUUID }; -var v5 = Object(_v35_js__WEBPACK_IMPORTED_MODULE_0__["default"])('v5', 0x50, _sha1_js__WEBPACK_IMPORTED_MODULE_1__["default"]); -/* harmony default export */ __webpack_exports__["default"] = (v5); /***/ }), -/* 20 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 23 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -// Adapted from Chris Veness' SHA1 code at -// http://www.movable-type.co.uk/scripts/sha1.html -function f(s, x, y, z) { - switch (s) { - case 0: - return x & y ^ ~x & z; - case 1: - return x ^ y ^ z; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.URL = exports.DNS = void 0; +const sha1_js_1 = __webpack_require__(24); +const v35_js_1 = __webpack_require__(20); +var v35_js_2 = __webpack_require__(20); +Object.defineProperty(exports, "DNS", ({ enumerable: true, get: function () { return v35_js_2.DNS; } })); +Object.defineProperty(exports, "URL", ({ enumerable: true, get: function () { return v35_js_2.URL; } })); +function v5(value, namespace, buf, offset) { + return (0, v35_js_1.default)(0x50, sha1_js_1.default, value, namespace, buf, offset); +} +v5.DNS = v35_js_1.DNS; +v5.URL = v35_js_1.URL; +exports["default"] = v5; - case 2: - return x & y ^ x & z ^ y & z; - case 3: - return x ^ y ^ z; - } -} +/***/ }), +/* 24 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +function f(s, x, y, z) { + switch (s) { + case 0: + return (x & y) ^ (~x & z); + case 1: + return x ^ y ^ z; + case 2: + return (x & y) ^ (x & z) ^ (y & z); + case 3: + return x ^ y ^ z; + } +} function ROTL(x, n) { - return x << n | x >>> 32 - n; + return (x << n) | (x >>> (32 - n)); } - function sha1(bytes) { - var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; - var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + const newBytes = new Uint8Array(bytes.length + 1); + newBytes.set(bytes); + newBytes[bytes.length] = 0x80; + bytes = newBytes; + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + for (let j = 0; j < 16; ++j) { + arr[j] = + (bytes[i * 64 + j * 4] << 24) | + (bytes[i * 64 + j * 4 + 1] << 16) | + (bytes[i * 64 + j * 4 + 2] << 8) | + bytes[i * 64 + j * 4 + 3]; + } + M[i] = arr; + } + M[N - 1][14] = ((bytes.length - 1) * 8) / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff; + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = (ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t]) >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = (H[0] + a) >>> 0; + H[1] = (H[1] + b) >>> 0; + H[2] = (H[2] + c) >>> 0; + H[3] = (H[3] + d) >>> 0; + H[4] = (H[4] + e) >>> 0; + } + return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]); +} +exports["default"] = sha1; - if (typeof bytes === 'string') { - var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - bytes = []; +/***/ }), +/* 25 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; - for (var i = 0; i < msg.length; ++i) { - bytes.push(msg.charCodeAt(i)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const stringify_js_1 = __webpack_require__(14); +const v1_js_1 = __webpack_require__(15); +const v1ToV6_js_1 = __webpack_require__(17); +function v6(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = (0, v1_js_1.default)({ ...options, _v6: true }, new Uint8Array(16)); + bytes = (0, v1ToV6_js_1.default)(bytes); + if (buf) { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; } - } else if (!Array.isArray(bytes)) { - // Convert Array-like to Array - bytes = Array.prototype.slice.call(bytes); - } + return (0, stringify_js_1.unsafeStringify)(bytes); +} +exports["default"] = v6; - bytes.push(0x80); - var l = bytes.length / 4 + 2; - var N = Math.ceil(l / 16); - var M = new Array(N); - for (var _i = 0; _i < N; ++_i) { - var arr = new Uint32Array(16); +/***/ }), +/* 26 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - for (var j = 0; j < 16; ++j) { - arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; - } +"use strict"; - M[_i] = arr; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const parse_js_1 = __webpack_require__(11); +const stringify_js_1 = __webpack_require__(14); +function v6ToV1(uuid) { + const v6Bytes = typeof uuid === 'string' ? (0, parse_js_1.default)(uuid) : uuid; + const v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? (0, stringify_js_1.unsafeStringify)(v1Bytes) : v1Bytes; +} +exports["default"] = v6ToV1; +function _v6ToV1(v6Bytes) { + return Uint8Array.of(((v6Bytes[3] & 0x0f) << 4) | ((v6Bytes[4] >> 4) & 0x0f), ((v6Bytes[4] & 0x0f) << 4) | ((v6Bytes[5] & 0xf0) >> 4), ((v6Bytes[5] & 0x0f) << 4) | (v6Bytes[6] & 0x0f), v6Bytes[7], ((v6Bytes[1] & 0x0f) << 4) | ((v6Bytes[2] & 0xf0) >> 4), ((v6Bytes[2] & 0x0f) << 4) | ((v6Bytes[3] & 0xf0) >> 4), 0x10 | ((v6Bytes[0] & 0xf0) >> 4), ((v6Bytes[0] & 0x0f) << 4) | ((v6Bytes[1] & 0xf0) >> 4), v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} - M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); - M[N - 1][14] = Math.floor(M[N - 1][14]); - M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; - for (var _i2 = 0; _i2 < N; ++_i2) { - var W = new Uint32Array(80); +/***/ }), +/* 27 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - for (var t = 0; t < 16; ++t) { - W[t] = M[_i2][t]; - } +"use strict"; - for (var _t = 16; _t < 80; ++_t) { - W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.updateV7State = void 0; +const rng_js_1 = __webpack_require__(16); +const stringify_js_1 = __webpack_require__(14); +const _state = {}; +function v7(options, buf, offset) { + let bytes; + if (options) { + bytes = v7Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.seq, buf, offset); + } + else { + const now = Date.now(); + const rnds = (0, rng_js_1.default)(); + updateV7State(_state, now, rnds); + bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + } + return buf ?? (0, stringify_js_1.unsafeStringify)(bytes); +} +function updateV7State(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + state.msecs = now; } - - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - - for (var _t2 = 0; _t2 < 80; ++_t2) { - var s = Math.floor(_t2 / 20); - var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0; - e = d; - d = c; - c = ROTL(b, 30) >>> 0; - b = a; - a = T; + else { + state.seq = (state.seq + 1) | 0; + if (state.seq === 0) { + state.msecs++; + } } - - H[0] = H[0] + a >>> 0; - H[1] = H[1] + b >>> 0; - H[2] = H[2] + c >>> 0; - H[3] = H[3] + d >>> 0; - H[4] = H[4] + e >>> 0; - } - - return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; + return state; } +exports.updateV7State = updateV7State; +function v7Bytes(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + buf[offset++] = (msecs / 0x10000000000) & 0xff; + buf[offset++] = (msecs / 0x100000000) & 0xff; + buf[offset++] = (msecs / 0x1000000) & 0xff; + buf[offset++] = (msecs / 0x10000) & 0xff; + buf[offset++] = (msecs / 0x100) & 0xff; + buf[offset++] = msecs & 0xff; + buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f); + buf[offset++] = (seq >>> 20) & 0xff; + buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f); + buf[offset++] = (seq >>> 6) & 0xff; + buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03); + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +exports["default"] = v7; -/* harmony default export */ __webpack_exports__["default"] = (sha1); - -/***/ }), -/* 21 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony default export */ __webpack_exports__["default"] = ('00000000-0000-0000-0000-000000000000'); /***/ }), -/* 22 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 28 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); - +Object.defineProperty(exports, "__esModule", ({ value: true })); +const validate_js_1 = __webpack_require__(12); function version(uuid) { - if (!Object(_validate_js__WEBPACK_IMPORTED_MODULE_0__["default"])(uuid)) { - throw TypeError('Invalid UUID'); - } - - return parseInt(uuid.substr(14, 1), 16); + if (!(0, validate_js_1.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); } +exports["default"] = version; -/* harmony default export */ __webpack_exports__["default"] = (version); /***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { +/* 29 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionMessageSentEvent = exports.ConnectionMessageReceivedEvent = exports.ConnectionEstablishErrorEvent = exports.ConnectionErrorEvent = exports.ConnectionClosedEvent = exports.ConnectionEstablishedEvent = exports.ConnectionStartEvent = exports.ConnectionEvent = exports.ServiceEvent = void 0; -var PlatformEvent_1 = __webpack_require__(6); -var ServiceEvent = /** @class */ (function (_super) { - __extends(ServiceEvent, _super); - function ServiceEvent(eventName, jsonstring, eventType) { - if (eventType === void 0) { eventType = PlatformEvent_1.EventType.Info; } - var _this = _super.call(this, eventName, eventType) || this; - _this.privJsonResult = jsonstring; - return _this; - } - Object.defineProperty(ServiceEvent.prototype, "jsonString", { - get: function () { - return this.privJsonResult; - }, - enumerable: false, - configurable: true - }); - return ServiceEvent; -}(PlatformEvent_1.PlatformEvent)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConnectionRedirectEvent = exports.ConnectionMessageSentEvent = exports.ConnectionMessageReceivedEvent = exports.ConnectionEstablishErrorEvent = exports.ConnectionErrorEvent = exports.ConnectionClosedEvent = exports.ConnectionEstablishedEvent = exports.ConnectionStartEvent = exports.ConnectionEvent = exports.ServiceEvent = void 0; +const PlatformEvent_js_1 = __webpack_require__(6); +class ServiceEvent extends PlatformEvent_js_1.PlatformEvent { + constructor(eventName, jsonstring, eventType = PlatformEvent_js_1.EventType.Info) { + super(eventName, eventType); + this.privJsonResult = jsonstring; + } + get jsonString() { + return this.privJsonResult; + } +} exports.ServiceEvent = ServiceEvent; -var ConnectionEvent = /** @class */ (function (_super) { - __extends(ConnectionEvent, _super); - function ConnectionEvent(eventName, connectionId, eventType) { - if (eventType === void 0) { eventType = PlatformEvent_1.EventType.Info; } - var _this = _super.call(this, eventName, eventType) || this; - _this.privConnectionId = connectionId; - return _this; - } - Object.defineProperty(ConnectionEvent.prototype, "connectionId", { - get: function () { - return this.privConnectionId; - }, - enumerable: false, - configurable: true - }); - return ConnectionEvent; -}(PlatformEvent_1.PlatformEvent)); +class ConnectionEvent extends PlatformEvent_js_1.PlatformEvent { + constructor(eventName, connectionId, eventType = PlatformEvent_js_1.EventType.Info) { + super(eventName, eventType); + this.privConnectionId = connectionId; + } + get connectionId() { + return this.privConnectionId; + } +} exports.ConnectionEvent = ConnectionEvent; -var ConnectionStartEvent = /** @class */ (function (_super) { - __extends(ConnectionStartEvent, _super); - function ConnectionStartEvent(connectionId, uri, headers) { - var _this = _super.call(this, "ConnectionStartEvent", connectionId) || this; - _this.privUri = uri; - _this.privHeaders = headers; - return _this; - } - Object.defineProperty(ConnectionStartEvent.prototype, "uri", { - get: function () { - return this.privUri; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionStartEvent.prototype, "headers", { - get: function () { - return this.privHeaders; - }, - enumerable: false, - configurable: true - }); - return ConnectionStartEvent; -}(ConnectionEvent)); +class ConnectionStartEvent extends ConnectionEvent { + constructor(connectionId, uri, headers) { + super("ConnectionStartEvent", connectionId); + this.privUri = uri; + this.privHeaders = headers; + } + get uri() { + return this.privUri; + } + get headers() { + return this.privHeaders; + } +} exports.ConnectionStartEvent = ConnectionStartEvent; -var ConnectionEstablishedEvent = /** @class */ (function (_super) { - __extends(ConnectionEstablishedEvent, _super); - function ConnectionEstablishedEvent(connectionId, metadata) { - return _super.call(this, "ConnectionEstablishedEvent", connectionId) || this; +class ConnectionEstablishedEvent extends ConnectionEvent { + constructor(connectionId) { + super("ConnectionEstablishedEvent", connectionId); } - return ConnectionEstablishedEvent; -}(ConnectionEvent)); +} exports.ConnectionEstablishedEvent = ConnectionEstablishedEvent; -var ConnectionClosedEvent = /** @class */ (function (_super) { - __extends(ConnectionClosedEvent, _super); - function ConnectionClosedEvent(connectionId, statusCode, reason) { - var _this = _super.call(this, "ConnectionClosedEvent", connectionId, PlatformEvent_1.EventType.Debug) || this; - _this.privReason = reason; - _this.privStatusCode = statusCode; - return _this; - } - Object.defineProperty(ConnectionClosedEvent.prototype, "reason", { - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionClosedEvent.prototype, "statusCode", { - get: function () { - return this.privStatusCode; - }, - enumerable: false, - configurable: true - }); - return ConnectionClosedEvent; -}(ConnectionEvent)); +class ConnectionClosedEvent extends ConnectionEvent { + constructor(connectionId, statusCode, reason) { + super("ConnectionClosedEvent", connectionId, PlatformEvent_js_1.EventType.Debug); + this.privReason = reason; + this.privStatusCode = statusCode; + } + get reason() { + return this.privReason; + } + get statusCode() { + return this.privStatusCode; + } +} exports.ConnectionClosedEvent = ConnectionClosedEvent; -var ConnectionErrorEvent = /** @class */ (function (_super) { - __extends(ConnectionErrorEvent, _super); - function ConnectionErrorEvent(connectionId, message, type) { - var _this = _super.call(this, "ConnectionErrorEvent", connectionId, PlatformEvent_1.EventType.Debug) || this; - _this.privMessage = message; - _this.privType = type; - return _this; - } - Object.defineProperty(ConnectionErrorEvent.prototype, "message", { - get: function () { - return this.privMessage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionErrorEvent.prototype, "type", { - get: function () { - return this.privType; - }, - enumerable: false, - configurable: true - }); - return ConnectionErrorEvent; -}(ConnectionEvent)); +class ConnectionErrorEvent extends ConnectionEvent { + constructor(connectionId, message, type) { + super("ConnectionErrorEvent", connectionId, PlatformEvent_js_1.EventType.Debug); + this.privMessage = message; + this.privType = type; + } + get message() { + return this.privMessage; + } + get type() { + return this.privType; + } +} exports.ConnectionErrorEvent = ConnectionErrorEvent; -var ConnectionEstablishErrorEvent = /** @class */ (function (_super) { - __extends(ConnectionEstablishErrorEvent, _super); - function ConnectionEstablishErrorEvent(connectionId, statuscode, reason) { - var _this = _super.call(this, "ConnectionEstablishErrorEvent", connectionId, PlatformEvent_1.EventType.Error) || this; - _this.privStatusCode = statuscode; - _this.privReason = reason; - return _this; - } - Object.defineProperty(ConnectionEstablishErrorEvent.prototype, "reason", { - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionEstablishErrorEvent.prototype, "statusCode", { - get: function () { - return this.privStatusCode; - }, - enumerable: false, - configurable: true - }); - return ConnectionEstablishErrorEvent; -}(ConnectionEvent)); +class ConnectionEstablishErrorEvent extends ConnectionEvent { + constructor(connectionId, statuscode, reason) { + super("ConnectionEstablishErrorEvent", connectionId, PlatformEvent_js_1.EventType.Error); + this.privStatusCode = statuscode; + this.privReason = reason; + } + get reason() { + return this.privReason; + } + get statusCode() { + return this.privStatusCode; + } +} exports.ConnectionEstablishErrorEvent = ConnectionEstablishErrorEvent; -var ConnectionMessageReceivedEvent = /** @class */ (function (_super) { - __extends(ConnectionMessageReceivedEvent, _super); - function ConnectionMessageReceivedEvent(connectionId, networkReceivedTimeISO, message) { - var _this = _super.call(this, "ConnectionMessageReceivedEvent", connectionId) || this; - _this.privNetworkReceivedTime = networkReceivedTimeISO; - _this.privMessage = message; - return _this; - } - Object.defineProperty(ConnectionMessageReceivedEvent.prototype, "networkReceivedTime", { - get: function () { - return this.privNetworkReceivedTime; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessageReceivedEvent.prototype, "message", { - get: function () { - return this.privMessage; - }, - enumerable: false, - configurable: true - }); - return ConnectionMessageReceivedEvent; -}(ConnectionEvent)); +class ConnectionMessageReceivedEvent extends ConnectionEvent { + constructor(connectionId, networkReceivedTimeISO, message) { + super("ConnectionMessageReceivedEvent", connectionId); + this.privNetworkReceivedTime = networkReceivedTimeISO; + this.privMessage = message; + } + get networkReceivedTime() { + return this.privNetworkReceivedTime; + } + get message() { + return this.privMessage; + } +} exports.ConnectionMessageReceivedEvent = ConnectionMessageReceivedEvent; -var ConnectionMessageSentEvent = /** @class */ (function (_super) { - __extends(ConnectionMessageSentEvent, _super); - function ConnectionMessageSentEvent(connectionId, networkSentTimeISO, message) { - var _this = _super.call(this, "ConnectionMessageSentEvent", connectionId) || this; - _this.privNetworkSentTime = networkSentTimeISO; - _this.privMessage = message; - return _this; - } - Object.defineProperty(ConnectionMessageSentEvent.prototype, "networkSentTime", { - get: function () { - return this.privNetworkSentTime; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessageSentEvent.prototype, "message", { - get: function () { - return this.privMessage; - }, - enumerable: false, - configurable: true - }); - return ConnectionMessageSentEvent; -}(ConnectionEvent)); +class ConnectionMessageSentEvent extends ConnectionEvent { + constructor(connectionId, networkSentTimeISO, message) { + super("ConnectionMessageSentEvent", connectionId); + this.privNetworkSentTime = networkSentTimeISO; + this.privMessage = message; + } + get networkSentTime() { + return this.privNetworkSentTime; + } + get message() { + return this.privMessage; + } +} exports.ConnectionMessageSentEvent = ConnectionMessageSentEvent; +class ConnectionRedirectEvent extends ConnectionEvent { + constructor(connectionId, redirectUrl, originalUrl, context) { + super("ConnectionRedirectEvent", connectionId, PlatformEvent_js_1.EventType.Info); + this.privRedirectUrl = redirectUrl; + this.privOriginalUrl = originalUrl; + this.privContext = context; + } + get redirectUrl() { + return this.privRedirectUrl; + } + get originalUrl() { + return this.privOriginalUrl; + } + get context() { + return this.privContext; + } +} +exports.ConnectionRedirectEvent = ConnectionRedirectEvent; + + - - /***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { +/* 30 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; +/* eslint-disable @typescript-eslint/no-unsafe-return */ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConnectionMessage = exports.MessageType = void 0; -var Error_1 = __webpack_require__(25); -var Guid_1 = __webpack_require__(7); +const Error_js_1 = __webpack_require__(31); +const Guid_js_1 = __webpack_require__(7); var MessageType; (function (MessageType) { MessageType[MessageType["Text"] = 0] = "Text"; MessageType[MessageType["Binary"] = 1] = "Binary"; })(MessageType = exports.MessageType || (exports.MessageType = {})); -var ConnectionMessage = /** @class */ (function () { - function ConnectionMessage(messageType, body, headers, id) { +class ConnectionMessage { + constructor(messageType, body, headers, id) { this.privBody = null; if (messageType === MessageType.Text && body && !(typeof (body) === "string")) { - throw new Error_1.InvalidOperationError("Payload must be a string"); + throw new Error_js_1.InvalidOperationError("Payload must be a string"); } if (messageType === MessageType.Binary && body && !(body instanceof ArrayBuffer)) { - throw new Error_1.InvalidOperationError("Payload must be ArrayBuffer"); + throw new Error_js_1.InvalidOperationError("Payload must be ArrayBuffer"); } this.privMessageType = messageType; + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment this.privBody = body; this.privHeaders = headers ? headers : {}; - this.privId = id ? id : Guid_1.createNoDashGuid(); + this.privId = id ? id : (0, Guid_js_1.createNoDashGuid)(); switch (this.messageType) { case MessageType.Binary: this.privSize = this.binaryBody !== null ? this.binaryBody.byteLength : 0; @@ -1543,84 +1343,46 @@ var ConnectionMessage = /** @class */ (function () { this.privSize = this.textBody.length; } } - Object.defineProperty(ConnectionMessage.prototype, "messageType", { - get: function () { - return this.privMessageType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessage.prototype, "headers", { - get: function () { - return this.privHeaders; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessage.prototype, "body", { - get: function () { - return this.privBody; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessage.prototype, "textBody", { - get: function () { - if (this.privMessageType === MessageType.Binary) { - throw new Error_1.InvalidOperationError("Not supported for binary message"); - } - return this.privBody; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessage.prototype, "binaryBody", { - get: function () { - if (this.privMessageType === MessageType.Text) { - throw new Error_1.InvalidOperationError("Not supported for text message"); - } - return this.privBody; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessage.prototype, "id", { - get: function () { - return this.privId; - }, - enumerable: false, - configurable: true - }); - return ConnectionMessage; -}()); + get messageType() { + return this.privMessageType; + } + get headers() { + return this.privHeaders; + } + get body() { + return this.privBody; + } + get textBody() { + if (this.privMessageType === MessageType.Binary) { + throw new Error_js_1.InvalidOperationError("Not supported for binary message"); + } + return this.privBody; + } + get binaryBody() { + if (this.privMessageType === MessageType.Text) { + throw new Error_js_1.InvalidOperationError("Not supported for text message"); + } + return this.privBody; + } + get id() { + return this.privId; + } +} exports.ConnectionMessage = ConnectionMessage; /***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { +/* 31 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ObjectDisposedError = exports.InvalidOperationError = exports.ArgumentNullError = void 0; -// tslint:disable:max-classes-per-file +/* eslint-disable max-classes-per-file */ /** * The error that is thrown when an argument passed in is null. * @@ -1628,8 +1390,7 @@ exports.ObjectDisposedError = exports.InvalidOperationError = exports.ArgumentNu * @class ArgumentNullError * @extends {Error} */ -var ArgumentNullError = /** @class */ (function (_super) { - __extends(ArgumentNullError, _super); +class ArgumentNullError extends Error { /** * Creates an instance of ArgumentNullError. * @@ -1637,14 +1398,12 @@ var ArgumentNullError = /** @class */ (function (_super) { * * @memberOf ArgumentNullError */ - function ArgumentNullError(argumentName) { - var _this = _super.call(this, argumentName) || this; - _this.name = "ArgumentNull"; - _this.message = argumentName; - return _this; + constructor(argumentName) { + super(argumentName); + this.name = "ArgumentNull"; + this.message = argumentName; } - return ArgumentNullError; -}(Error)); +} exports.ArgumentNullError = ArgumentNullError; /** * The error that is thrown when an invalid operation is performed in the code. @@ -1653,8 +1412,7 @@ exports.ArgumentNullError = ArgumentNullError; * @class InvalidOperationError * @extends {Error} */ -var InvalidOperationError = /** @class */ (function (_super) { - __extends(InvalidOperationError, _super); +class InvalidOperationError extends Error { /** * Creates an instance of InvalidOperationError. * @@ -1662,14 +1420,12 @@ var InvalidOperationError = /** @class */ (function (_super) { * * @memberOf InvalidOperationError */ - function InvalidOperationError(error) { - var _this = _super.call(this, error) || this; - _this.name = "InvalidOperation"; - _this.message = error; - return _this; + constructor(error) { + super(error); + this.name = "InvalidOperation"; + this.message = error; } - return InvalidOperationError; -}(Error)); +} exports.InvalidOperationError = InvalidOperationError; /** * The error that is thrown when an object is disposed. @@ -1678,9 +1434,7 @@ exports.InvalidOperationError = InvalidOperationError; * @class ObjectDisposedError * @extends {Error} */ -// tslint:disable-next-line:max-classes-per-file -var ObjectDisposedError = /** @class */ (function (_super) { - __extends(ObjectDisposedError, _super); +class ObjectDisposedError extends Error { /** * Creates an instance of ObjectDisposedError. * @@ -1689,235 +1443,238 @@ var ObjectDisposedError = /** @class */ (function (_super) { * * @memberOf ObjectDisposedError */ - function ObjectDisposedError(objectName, error) { - var _this = _super.call(this, error) || this; - _this.name = objectName + "ObjectDisposed"; - _this.message = error; - return _this; + constructor(objectName, error) { + super(error); + this.name = objectName + "ObjectDisposed"; + this.message = error; } - return ObjectDisposedError; -}(Error)); +} exports.ObjectDisposedError = ObjectDisposedError; /***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { +/* 32 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConnectionOpenResponse = void 0; -var ConnectionOpenResponse = /** @class */ (function () { - function ConnectionOpenResponse(statusCode, reason) { +class ConnectionOpenResponse { + constructor(statusCode, reason) { this.privStatusCode = statusCode; this.privReason = reason; } - Object.defineProperty(ConnectionOpenResponse.prototype, "statusCode", { - get: function () { - return this.privStatusCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionOpenResponse.prototype, "reason", { - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - return ConnectionOpenResponse; -}()); + get statusCode() { + return this.privStatusCode; + } + get reason() { + return this.privReason; + } +} exports.ConnectionOpenResponse = ConnectionOpenResponse; /***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { +/* 33 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DeferralMap = void 0; +/** + * The error that is thrown when an argument passed in is null. + * + * @export + * @class DefferalMap + */ +class DeferralMap { + constructor() { + this.privMap = {}; + } + add(id, deferral) { + this.privMap[id] = deferral; + } + getId(id) { + return this.privMap[id]; + } + complete(id, result) { + try { + this.privMap[id].resolve(result); + } + catch (error) { + this.privMap[id].reject(error); + } + finally { + this.privMap[id] = undefined; + } + } +} +exports.DeferralMap = DeferralMap; + + + +/***/ }), +/* 34 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SendingAgentContextMessageEvent = exports.DialogEvent = void 0; -var PlatformEvent_1 = __webpack_require__(6); -var DialogEvent = /** @class */ (function (_super) { - __extends(DialogEvent, _super); - function DialogEvent(eventName, eventType) { - if (eventType === void 0) { eventType = PlatformEvent_1.EventType.Info; } - return _super.call(this, eventName, eventType) || this; - } - return DialogEvent; -}(PlatformEvent_1.PlatformEvent)); +const PlatformEvent_js_1 = __webpack_require__(6); +class DialogEvent extends PlatformEvent_js_1.PlatformEvent { + constructor(eventName, eventType = PlatformEvent_js_1.EventType.Info) { + super(eventName, eventType); + } +} exports.DialogEvent = DialogEvent; -var SendingAgentContextMessageEvent = /** @class */ (function (_super) { - __extends(SendingAgentContextMessageEvent, _super); - function SendingAgentContextMessageEvent(agentConfig) { - var _this = _super.call(this, "SendingAgentContextMessageEvent") || this; - _this.privAgentConfig = agentConfig; - return _this; - } - Object.defineProperty(SendingAgentContextMessageEvent.prototype, "agentConfig", { - get: function () { - return this.privAgentConfig; - }, - enumerable: false, - configurable: true - }); - return SendingAgentContextMessageEvent; -}(DialogEvent)); +class SendingAgentContextMessageEvent extends DialogEvent { + constructor(agentConfig) { + super("SendingAgentContextMessageEvent"); + this.privAgentConfig = agentConfig; + } + get agentConfig() { + return this.privAgentConfig; + } +} exports.SendingAgentContextMessageEvent = SendingAgentContextMessageEvent; /***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { +/* 35 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Events = void 0; -var Error_1 = __webpack_require__(25); -var EventSource_1 = __webpack_require__(29); -var Events = /** @class */ (function () { - function Events() { - } - Object.defineProperty(Events, "instance", { - get: function () { - return Events.privInstance; - }, - enumerable: false, - configurable: true - }); - Events.privInstance = new EventSource_1.EventSource(); - Events.setEventSource = function (eventSource) { +const Error_js_1 = __webpack_require__(31); +const EventSource_js_1 = __webpack_require__(36); +class Events { + static setEventSource(eventSource) { if (!eventSource) { - throw new Error_1.ArgumentNullError("eventSource"); + throw new Error_js_1.ArgumentNullError("eventSource"); } Events.privInstance = eventSource; - }; - return Events; -}()); + } + static get instance() { + return Events.privInstance; + } +} exports.Events = Events; +Events.privInstance = new EventSource_js_1.EventSource(); /***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { +/* 36 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EventSource = void 0; -var Error_1 = __webpack_require__(25); -var Guid_1 = __webpack_require__(7); -var EventSource = /** @class */ (function () { - function EventSource(metadata) { - var _this = this; +const Error_js_1 = __webpack_require__(31); +const Guid_js_1 = __webpack_require__(7); +class EventSource { + constructor(metadata) { this.privEventListeners = {}; this.privIsDisposed = false; - this.onEvent = function (event) { - if (_this.isDisposed()) { - throw (new Error_1.ObjectDisposedError("EventSource")); - } - if (_this.metadata) { - for (var paramName in _this.metadata) { - if (paramName) { - if (event.metadata) { - if (!event.metadata[paramName]) { - event.metadata[paramName] = _this.metadata[paramName]; - } + this.privConsoleListener = undefined; + this.privMetadata = metadata; + } + onEvent(event) { + if (this.isDisposed()) { + throw (new Error_js_1.ObjectDisposedError("EventSource")); + } + if (this.metadata) { + for (const paramName in this.metadata) { + if (paramName) { + if (event.metadata) { + if (!event.metadata[paramName]) { + event.metadata[paramName] = this.metadata[paramName]; } } } } - for (var eventId in _this.privEventListeners) { - if (eventId && _this.privEventListeners[eventId]) { - _this.privEventListeners[eventId](event); - } + } + for (const eventId in this.privEventListeners) { + if (eventId && this.privEventListeners[eventId]) { + this.privEventListeners[eventId](event); } + } + } + attach(onEventCallback) { + const id = (0, Guid_js_1.createNoDashGuid)(); + this.privEventListeners[id] = onEventCallback; + return { + detach: () => { + delete this.privEventListeners[id]; + return Promise.resolve(); + }, }; - this.attach = function (onEventCallback) { - var id = Guid_1.createNoDashGuid(); - _this.privEventListeners[id] = onEventCallback; - return { - detach: function () { - delete _this.privEventListeners[id]; - return Promise.resolve(); - }, - }; - }; - this.attachListener = function (listener) { - return _this.attach(listener.onEvent); - }; - this.isDisposed = function () { - return _this.privIsDisposed; - }; - this.dispose = function () { - _this.privEventListeners = null; - _this.privIsDisposed = true; - }; - this.privMetadata = metadata; } - Object.defineProperty(EventSource.prototype, "metadata", { - get: function () { - return this.privMetadata; - }, - enumerable: false, - configurable: true - }); - return EventSource; -}()); + attachListener(listener) { + return this.attach((e) => listener.onEvent(e)); + } + attachConsoleListener(listener) { + if (!!this.privConsoleListener) { + void this.privConsoleListener.detach(); // Detach implementation for eventListeners is synchronous + } + this.privConsoleListener = this.attach((e) => listener.onEvent(e)); + return this.privConsoleListener; + } + isDisposed() { + return this.privIsDisposed; + } + dispose() { + this.privEventListeners = null; + this.privIsDisposed = true; + } + get metadata() { + return this.privMetadata; + } +} exports.EventSource = EventSource; /***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { +/* 37 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { +/* 38 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConnectionState = void 0; var ConnectionState; (function (ConnectionState) { @@ -1930,511 +1687,487 @@ var ConnectionState; /***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { +/* 39 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { +/* 40 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { +/* 41 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { +/* 42 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { +/* 43 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { +/* 44 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); + + + +/***/ }), +/* 45 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { +/* 46 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { +/* 47 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.List = void 0; -var Error_1 = __webpack_require__(25); -var List = /** @class */ (function () { - function List(list) { - var _this = this; +const Error_js_1 = __webpack_require__(31); +class List { + constructor(list) { this.privSubscriptionIdCounter = 0; this.privAddSubscriptions = {}; this.privRemoveSubscriptions = {}; this.privDisposedSubscriptions = {}; this.privDisposeReason = null; - this.get = function (itemIndex) { - _this.throwIfDisposed(); - return _this.privList[itemIndex]; - }; - this.first = function () { - return _this.get(0); - }; - this.last = function () { - return _this.get(_this.length() - 1); - }; - this.add = function (item) { - _this.throwIfDisposed(); - _this.insertAt(_this.privList.length, item); - }; - this.insertAt = function (index, item) { - _this.throwIfDisposed(); - if (index === 0) { - _this.privList.unshift(item); - } - else if (index === _this.privList.length) { - _this.privList.push(item); - } - else { - _this.privList.splice(index, 0, item); - } - _this.triggerSubscriptions(_this.privAddSubscriptions); - }; - this.removeFirst = function () { - _this.throwIfDisposed(); - return _this.removeAt(0); - }; - this.removeLast = function () { - _this.throwIfDisposed(); - return _this.removeAt(_this.length() - 1); - }; - this.removeAt = function (index) { - _this.throwIfDisposed(); - return _this.remove(index, 1)[0]; - }; - this.remove = function (index, count) { - _this.throwIfDisposed(); - var removedElements = _this.privList.splice(index, count); - _this.triggerSubscriptions(_this.privRemoveSubscriptions); - return removedElements; - }; - this.clear = function () { - _this.throwIfDisposed(); - _this.remove(0, _this.length()); - }; - this.length = function () { - _this.throwIfDisposed(); - return _this.privList.length; - }; - this.onAdded = function (addedCallback) { - _this.throwIfDisposed(); - var subscriptionId = _this.privSubscriptionIdCounter++; - _this.privAddSubscriptions[subscriptionId] = addedCallback; - return { - detach: function () { - delete _this.privAddSubscriptions[subscriptionId]; - return Promise.resolve(); - }, - }; - }; - this.onRemoved = function (removedCallback) { - _this.throwIfDisposed(); - var subscriptionId = _this.privSubscriptionIdCounter++; - _this.privRemoveSubscriptions[subscriptionId] = removedCallback; - return { - detach: function () { - delete _this.privRemoveSubscriptions[subscriptionId]; - return Promise.resolve(); - }, - }; - }; - this.onDisposed = function (disposedCallback) { - _this.throwIfDisposed(); - var subscriptionId = _this.privSubscriptionIdCounter++; - _this.privDisposedSubscriptions[subscriptionId] = disposedCallback; - return { - detach: function () { - delete _this.privDisposedSubscriptions[subscriptionId]; - return Promise.resolve(); - }, - }; - }; - this.join = function (seperator) { - _this.throwIfDisposed(); - return _this.privList.join(seperator); - }; - this.toArray = function () { - var cloneCopy = Array(); - _this.privList.forEach(function (val) { - cloneCopy.push(val); - }); - return cloneCopy; - }; - this.any = function (callback) { - _this.throwIfDisposed(); - if (callback) { - return _this.where(callback).length() > 0; - } - else { - return _this.length() > 0; - } - }; - this.all = function (callback) { - _this.throwIfDisposed(); - return _this.where(callback).length() === _this.length(); - }; - this.forEach = function (callback) { - _this.throwIfDisposed(); - for (var i = 0; i < _this.length(); i++) { - callback(_this.privList[i], i); - } - }; - this.select = function (callback) { - _this.throwIfDisposed(); - var selectList = []; - for (var i = 0; i < _this.privList.length; i++) { - selectList.push(callback(_this.privList[i], i)); - } - return new List(selectList); - }; - this.where = function (callback) { - _this.throwIfDisposed(); - var filteredList = new List(); - for (var i = 0; i < _this.privList.length; i++) { - if (callback(_this.privList[i], i)) { - filteredList.add(_this.privList[i]); - } + this.privList = []; + // copy the list rather than taking as is. + if (list) { + for (const item of list) { + this.privList.push(item); } - return filteredList; - }; - this.orderBy = function (compareFn) { - _this.throwIfDisposed(); - var clonedArray = _this.toArray(); - var orderedArray = clonedArray.sort(compareFn); - return new List(orderedArray); - }; - this.orderByDesc = function (compareFn) { - _this.throwIfDisposed(); - return _this.orderBy(function (a, b) { return compareFn(b, a); }); - }; - this.clone = function () { - _this.throwIfDisposed(); - return new List(_this.toArray()); - }; - this.concat = function (list) { - _this.throwIfDisposed(); - return new List(_this.privList.concat(list.toArray())); - }; - this.concatArray = function (array) { - _this.throwIfDisposed(); - return new List(_this.privList.concat(array)); + } + } + get(itemIndex) { + this.throwIfDisposed(); + return this.privList[itemIndex]; + } + first() { + return this.get(0); + } + last() { + return this.get(this.length() - 1); + } + add(item) { + this.throwIfDisposed(); + this.insertAt(this.privList.length, item); + } + insertAt(index, item) { + this.throwIfDisposed(); + if (index === 0) { + this.privList.unshift(item); + } + else if (index === this.privList.length) { + this.privList.push(item); + } + else { + this.privList.splice(index, 0, item); + } + this.triggerSubscriptions(this.privAddSubscriptions); + } + removeFirst() { + this.throwIfDisposed(); + return this.removeAt(0); + } + removeLast() { + this.throwIfDisposed(); + return this.removeAt(this.length() - 1); + } + removeAt(index) { + this.throwIfDisposed(); + return this.remove(index, 1)[0]; + } + remove(index, count) { + this.throwIfDisposed(); + const removedElements = this.privList.splice(index, count); + this.triggerSubscriptions(this.privRemoveSubscriptions); + return removedElements; + } + clear() { + this.throwIfDisposed(); + this.remove(0, this.length()); + } + length() { + this.throwIfDisposed(); + return this.privList.length; + } + onAdded(addedCallback) { + this.throwIfDisposed(); + const subscriptionId = this.privSubscriptionIdCounter++; + this.privAddSubscriptions[subscriptionId] = addedCallback; + return { + detach: () => { + delete this.privAddSubscriptions[subscriptionId]; + return Promise.resolve(); + }, }; - this.isDisposed = function () { - return _this.privList == null; + } + onRemoved(removedCallback) { + this.throwIfDisposed(); + const subscriptionId = this.privSubscriptionIdCounter++; + this.privRemoveSubscriptions[subscriptionId] = removedCallback; + return { + detach: () => { + delete this.privRemoveSubscriptions[subscriptionId]; + return Promise.resolve(); + }, }; - this.dispose = function (reason) { - if (!_this.isDisposed()) { - _this.privDisposeReason = reason; - _this.privList = null; - _this.privAddSubscriptions = null; - _this.privRemoveSubscriptions = null; - _this.triggerSubscriptions(_this.privDisposedSubscriptions); - } + } + onDisposed(disposedCallback) { + this.throwIfDisposed(); + const subscriptionId = this.privSubscriptionIdCounter++; + this.privDisposedSubscriptions[subscriptionId] = disposedCallback; + return { + detach: () => { + delete this.privDisposedSubscriptions[subscriptionId]; + return Promise.resolve(); + }, }; - this.throwIfDisposed = function () { - if (_this.isDisposed()) { - throw new Error_1.ObjectDisposedError("List", _this.privDisposeReason); + } + join(seperator) { + this.throwIfDisposed(); + return this.privList.join(seperator); + } + toArray() { + const cloneCopy = Array(); + this.privList.forEach((val) => { + cloneCopy.push(val); + }); + return cloneCopy; + } + any(callback) { + this.throwIfDisposed(); + if (callback) { + return this.where(callback).length() > 0; + } + else { + return this.length() > 0; + } + } + all(callback) { + this.throwIfDisposed(); + return this.where(callback).length() === this.length(); + } + forEach(callback) { + this.throwIfDisposed(); + for (let i = 0; i < this.length(); i++) { + callback(this.privList[i], i); + } + } + select(callback) { + this.throwIfDisposed(); + const selectList = []; + for (let i = 0; i < this.privList.length; i++) { + selectList.push(callback(this.privList[i], i)); + } + return new List(selectList); + } + where(callback) { + this.throwIfDisposed(); + const filteredList = new List(); + for (let i = 0; i < this.privList.length; i++) { + if (callback(this.privList[i], i)) { + filteredList.add(this.privList[i]); } - }; - this.triggerSubscriptions = function (subscriptions) { - if (subscriptions) { - for (var subscriptionId in subscriptions) { - if (subscriptionId) { - subscriptions[subscriptionId](); - } + } + return filteredList; + } + orderBy(compareFn) { + this.throwIfDisposed(); + const clonedArray = this.toArray(); + const orderedArray = clonedArray.sort(compareFn); + return new List(orderedArray); + } + orderByDesc(compareFn) { + this.throwIfDisposed(); + return this.orderBy((a, b) => compareFn(b, a)); + } + clone() { + this.throwIfDisposed(); + return new List(this.toArray()); + } + concat(list) { + this.throwIfDisposed(); + return new List(this.privList.concat(list.toArray())); + } + concatArray(array) { + this.throwIfDisposed(); + return new List(this.privList.concat(array)); + } + isDisposed() { + return this.privList == null; + } + dispose(reason) { + if (!this.isDisposed()) { + this.privDisposeReason = reason; + this.privList = null; + this.privAddSubscriptions = null; + this.privRemoveSubscriptions = null; + this.triggerSubscriptions(this.privDisposedSubscriptions); + } + } + throwIfDisposed() { + if (this.isDisposed()) { + throw new Error_js_1.ObjectDisposedError("List", this.privDisposeReason); + } + } + triggerSubscriptions(subscriptions) { + if (subscriptions) { + for (const subscriptionId in subscriptions) { + if (subscriptionId) { + subscriptions[subscriptionId](); } } - }; - this.privList = []; - // copy the list rather than taking as is. - if (list) { - for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { - var item = list_1[_i]; - this.privList.push(item); - } } } - return List; -}()); +} exports.List = List; /***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { +/* 48 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.marshalPromiseToCallbacks = exports.Sink = exports.Deferred = exports.PromiseResultEventSource = exports.PromiseResult = exports.PromiseState = void 0; +/* eslint-disable max-classes-per-file, @typescript-eslint/typedef */ var PromiseState; (function (PromiseState) { PromiseState[PromiseState["None"] = 0] = "None"; PromiseState[PromiseState["Resolved"] = 1] = "Resolved"; PromiseState[PromiseState["Rejected"] = 2] = "Rejected"; })(PromiseState = exports.PromiseState || (exports.PromiseState = {})); -var PromiseResult = /** @class */ (function () { - function PromiseResult(promiseResultEventSource) { - var _this = this; - this.throwIfError = function () { - if (_this.isError) { - throw _this.error; +class PromiseResult { + constructor(promiseResultEventSource) { + this.throwIfError = () => { + if (this.isError) { + throw this.error; } }; - promiseResultEventSource.on(function (result) { - if (!_this.privIsCompleted) { - _this.privIsCompleted = true; - _this.privIsError = false; - _this.privResult = result; - } - }, function (error) { - if (!_this.privIsCompleted) { - _this.privIsCompleted = true; - _this.privIsError = true; - _this.privError = error; + promiseResultEventSource.on((result) => { + if (!this.privIsCompleted) { + this.privIsCompleted = true; + this.privIsError = false; + this.privResult = result; + } + }, (error) => { + if (!this.privIsCompleted) { + this.privIsCompleted = true; + this.privIsError = true; + this.privError = error; } }); } - Object.defineProperty(PromiseResult.prototype, "isCompleted", { - get: function () { - return this.privIsCompleted; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PromiseResult.prototype, "isError", { - get: function () { - return this.privIsError; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PromiseResult.prototype, "error", { - get: function () { - return this.privError; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PromiseResult.prototype, "result", { - get: function () { - return this.privResult; - }, - enumerable: false, - configurable: true - }); - return PromiseResult; -}()); + get isCompleted() { + return this.privIsCompleted; + } + get isError() { + return this.privIsError; + } + get error() { + return this.privError; + } + get result() { + return this.privResult; + } +} exports.PromiseResult = PromiseResult; -var PromiseResultEventSource = /** @class */ (function () { - function PromiseResultEventSource() { - var _this = this; - this.setResult = function (result) { - _this.privOnSetResult(result); +class PromiseResultEventSource { + constructor() { + this.setResult = (result) => { + this.privOnSetResult(result); }; - this.setError = function (error) { - _this.privOnSetError(error); + this.setError = (error) => { + this.privOnSetError(error); }; - this.on = function (onSetResult, onSetError) { - _this.privOnSetResult = onSetResult; - _this.privOnSetError = onSetError; + this.on = (onSetResult, onSetError) => { + this.privOnSetResult = onSetResult; + this.privOnSetError = onSetError; }; } - return PromiseResultEventSource; -}()); +} exports.PromiseResultEventSource = PromiseResultEventSource; -var Deferred = /** @class */ (function () { - function Deferred() { - var _this = this; - this.resolve = function (result) { - _this.privResolve(result); - return _this; +class Deferred { + constructor() { + this.resolve = (result) => { + this.privResolve(result); + return this; }; - this.reject = function (error) { - _this.privReject(error); - return _this; + this.reject = (error) => { + this.privReject(error); + return this; }; - this.privPromise = new Promise(function (resolve, reject) { - _this.privResolve = resolve; - _this.privReject = reject; + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + this.privPromise = new Promise((resolve, reject) => { + this.privResolve = resolve; + this.privReject = reject; }); } - Object.defineProperty(Deferred.prototype, "promise", { - get: function () { - return this.privPromise; - }, - enumerable: false, - configurable: true - }); - return Deferred; -}()); + get promise() { + return this.privPromise; + } +} exports.Deferred = Deferred; -var Sink = /** @class */ (function () { - function Sink() { - var _this = this; +class Sink { + constructor() { this.privState = PromiseState.None; this.privPromiseResult = null; this.privPromiseResultEvents = null; this.privSuccessHandlers = []; this.privErrorHandlers = []; - this.resolve = function (result) { - if (_this.privState !== PromiseState.None) { - throw new Error("'Cannot resolve a completed promise'"); - } - _this.privState = PromiseState.Resolved; - _this.privPromiseResultEvents.setResult(result); - for (var i = 0; i < _this.privSuccessHandlers.length; i++) { - _this.executeSuccessCallback(result, _this.privSuccessHandlers[i], _this.privErrorHandlers[i]); - } - _this.detachHandlers(); - }; - this.reject = function (error) { - if (_this.privState !== PromiseState.None) { - throw new Error("'Cannot reject a completed promise'"); - } - _this.privState = PromiseState.Rejected; - _this.privPromiseResultEvents.setError(error); - for (var _i = 0, _a = _this.privErrorHandlers; _i < _a.length; _i++) { - var errorHandler = _a[_i]; - _this.executeErrorCallback(error, errorHandler); - } - _this.detachHandlers(); - }; - this.on = function (successCallback, errorCallback) { - if (successCallback == null) { - successCallback = function (r) { return; }; - } - if (_this.privState === PromiseState.None) { - _this.privSuccessHandlers.push(successCallback); - _this.privErrorHandlers.push(errorCallback); + this.privPromiseResultEvents = new PromiseResultEventSource(); + this.privPromiseResult = new PromiseResult(this.privPromiseResultEvents); + } + get state() { + return this.privState; + } + get result() { + return this.privPromiseResult; + } + resolve(result) { + if (this.privState !== PromiseState.None) { + throw new Error("'Cannot resolve a completed promise'"); + } + this.privState = PromiseState.Resolved; + this.privPromiseResultEvents.setResult(result); + for (let i = 0; i < this.privSuccessHandlers.length; i++) { + this.executeSuccessCallback(result, this.privSuccessHandlers[i], this.privErrorHandlers[i]); + } + this.detachHandlers(); + } + reject(error) { + if (this.privState !== PromiseState.None) { + throw new Error("'Cannot reject a completed promise'"); + } + this.privState = PromiseState.Rejected; + this.privPromiseResultEvents.setError(error); + for (const errorHandler of this.privErrorHandlers) { + this.executeErrorCallback(error, errorHandler); + } + this.detachHandlers(); + } + on(successCallback, errorCallback) { + if (successCallback == null) { + // eslint-disable-next-line @typescript-eslint/no-empty-function + successCallback = () => { }; + } + if (this.privState === PromiseState.None) { + this.privSuccessHandlers.push(successCallback); + this.privErrorHandlers.push(errorCallback); + } + else { + if (this.privState === PromiseState.Resolved) { + this.executeSuccessCallback(this.privPromiseResult.result, successCallback, errorCallback); } - else { - if (_this.privState === PromiseState.Resolved) { - _this.executeSuccessCallback(_this.privPromiseResult.result, successCallback, errorCallback); - } - else if (_this.privState === PromiseState.Rejected) { - _this.executeErrorCallback(_this.privPromiseResult.error, errorCallback); - } - _this.detachHandlers(); + else if (this.privState === PromiseState.Rejected) { + this.executeErrorCallback(this.privPromiseResult.error, errorCallback); } - }; - this.executeSuccessCallback = function (result, successCallback, errorCallback) { + this.detachHandlers(); + } + } + executeSuccessCallback(result, successCallback, errorCallback) { + try { + successCallback(result); + } + catch (e) { + this.executeErrorCallback(`'Unhandled callback error: ${e}'`, errorCallback); + } + } + executeErrorCallback(error, errorCallback) { + if (errorCallback) { try { - successCallback(result); + errorCallback(error); } catch (e) { - _this.executeErrorCallback("'Unhandled callback error: " + e + "'", errorCallback); - } - }; - this.executeErrorCallback = function (error, errorCallback) { - if (errorCallback) { - try { - errorCallback(error); - } - catch (e) { - throw new Error("'Unhandled callback error: " + e + ". InnerError: " + error + "'"); - } - } - else { - throw new Error("'Unhandled error: " + error + "'"); + throw new Error(`'Unhandled callback error: ${e}. InnerError: ${error}'`); } - }; - this.detachHandlers = function () { - _this.privErrorHandlers = []; - _this.privSuccessHandlers = []; - }; - this.privPromiseResultEvents = new PromiseResultEventSource(); - this.privPromiseResult = new PromiseResult(this.privPromiseResultEvents); + } + else { + throw new Error(`'Unhandled error: ${error}'`); + } } - Object.defineProperty(Sink.prototype, "state", { - get: function () { - return this.privState; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sink.prototype, "result", { - get: function () { - return this.privPromiseResult; - }, - enumerable: false, - configurable: true - }); - return Sink; -}()); + detachHandlers() { + this.privErrorHandlers = []; + this.privSuccessHandlers = []; + } +} exports.Sink = Sink; +// eslint-disable-next-line prefer-arrow/prefer-arrow-functions function marshalPromiseToCallbacks(promise, cb, err) { - promise.then(function (val) { + promise.then((val) => { try { if (!!cb) { cb(val); @@ -2444,28 +2177,28 @@ function marshalPromiseToCallbacks(promise, cb, err) { if (!!err) { try { if (error instanceof Error) { - var typedError = error; + const typedError = error; err(typedError.name + ": " + typedError.message); } else { err(error); } - /* tslint:disable:no-empty */ + // eslint-disable-next-line no-empty } catch (error) { } } } - }, function (error) { + }, (error) => { if (!!err) { try { if (error instanceof Error) { - var typedError = error; + const typedError = error; err(typedError.name + ": " + typedError.message); } else { err(error); } - /* tslint:disable:no-empty */ + // eslint-disable-next-line no-empty } catch (error) { } } @@ -2476,503 +2209,336 @@ exports.marshalPromiseToCallbacks = marshalPromiseToCallbacks; /***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { +/* 49 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Queue = void 0; -var Error_1 = __webpack_require__(25); -var List_1 = __webpack_require__(39); -var Promise_1 = __webpack_require__(40); +const Error_js_1 = __webpack_require__(31); +const List_js_1 = __webpack_require__(47); +const Promise_js_1 = __webpack_require__(48); var SubscriberType; (function (SubscriberType) { SubscriberType[SubscriberType["Dequeue"] = 0] = "Dequeue"; SubscriberType[SubscriberType["Peek"] = 1] = "Peek"; })(SubscriberType || (SubscriberType = {})); -var Queue = /** @class */ (function () { - function Queue(list) { - var _this = this; - this.privPromiseStore = new List_1.List(); +class Queue { + constructor(list) { + this.privPromiseStore = new List_js_1.List(); this.privIsDrainInProgress = false; this.privIsDisposing = false; this.privDisposeReason = null; - this.enqueue = function (item) { - _this.throwIfDispose(); - _this.enqueueFromPromise(new Promise(function (resolve, reject) { resolve(item); })); - }; - this.enqueueFromPromise = function (promise) { - _this.throwIfDispose(); - promise.then(function (val) { - _this.privList.add(val); - /* tslint:disable:no-empty */ - }, function (error) { }); - }; - this.dequeue = function () { - _this.throwIfDispose(); - var deferredSubscriber = new Promise_1.Deferred(); - if (_this.privSubscribers) { - _this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Dequeue }); - _this.drain(); - } - return deferredSubscriber.promise; - }; - this.peek = function () { - _this.throwIfDispose(); - var deferredSubscriber = new Promise_1.Deferred(); - var subs = _this.privSubscribers; + this.privList = list ? list : new List_js_1.List(); + this.privDetachables = []; + this.privSubscribers = new List_js_1.List(); + this.privDetachables.push(this.privList.onAdded(() => this.drain())); + } + enqueue(item) { + this.throwIfDispose(); + this.enqueueFromPromise(new Promise((resolve) => resolve(item))); + } + enqueueFromPromise(promise) { + this.throwIfDispose(); + promise.then((val) => { + this.privList.add(val); + // eslint-disable-next-line @typescript-eslint/no-empty-function + }, () => { }); + } + dequeue() { + this.throwIfDispose(); + const deferredSubscriber = new Promise_js_1.Deferred(); + if (this.privSubscribers) { + this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Dequeue }); + this.drain(); + } + return deferredSubscriber.promise; + } + peek() { + this.throwIfDispose(); + const deferredSubscriber = new Promise_js_1.Deferred(); + const subs = this.privSubscribers; + if (subs) { + this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Peek }); + this.drain(); + } + return deferredSubscriber.promise; + } + length() { + this.throwIfDispose(); + return this.privList.length(); + } + isDisposed() { + return this.privSubscribers == null; + } + async drainAndDispose(pendingItemProcessor, reason) { + if (!this.isDisposed() && !this.privIsDisposing) { + this.privDisposeReason = reason; + this.privIsDisposing = true; + const subs = this.privSubscribers; if (subs) { - _this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Peek }); - _this.drain(); + while (subs.length() > 0) { + const subscriber = subs.removeFirst(); + // TODO: this needs work (Resolve(null) instead?). + subscriber.deferral.resolve(undefined); + // subscriber.deferral.reject("Disposed"); + } + // note: this block assumes cooperative multitasking, i.e., + // between the if-statement and the assignment there are no + // thread switches. + // Reason is that between the initial const = this.; and this + // point there is the derral.resolve() operation that might have + // caused recursive calls to the Queue, especially, calling + // Dispose() on the queue alredy (which would reset the var + // here to null!). + // That should generally hold true for javascript... + if (this.privSubscribers === subs) { + this.privSubscribers = subs; + } + } + for (const detachable of this.privDetachables) { + await detachable.detach(); + } + if (this.privPromiseStore.length() > 0 && pendingItemProcessor) { + const promiseArray = []; + this.privPromiseStore.toArray().forEach((wrapper) => { + promiseArray.push(wrapper); + }); + return Promise.all(promiseArray).finally(() => { + this.privSubscribers = null; + this.privList.forEach((item) => { + pendingItemProcessor(item); + }); + this.privList = null; + return; + }).then(); } - return deferredSubscriber.promise; - }; - this.length = function () { - _this.throwIfDispose(); - return _this.privList.length(); - }; - this.isDisposed = function () { - return _this.privSubscribers == null; - }; - this.drain = function () { - if (!_this.privIsDrainInProgress && !_this.privIsDisposing) { - _this.privIsDrainInProgress = true; - var subs = _this.privSubscribers; - var lists = _this.privList; - if (subs && lists) { - while (lists.length() > 0 && subs.length() > 0 && !_this.privIsDisposing) { - var subscriber = subs.removeFirst(); - if (subscriber.type === SubscriberType.Peek) { - subscriber.deferral.resolve(lists.first()); - } - else { - var dequeuedItem = lists.removeFirst(); - subscriber.deferral.resolve(dequeuedItem); - } - } - // note: this block assumes cooperative multitasking, i.e., - // between the if-statement and the assignment there are no - // thread switches. - // Reason is that between the initial const = this.; and this - // point there is the derral.resolve() operation that might have - // caused recursive calls to the Queue, especially, calling - // Dispose() on the queue alredy (which would reset the var - // here to null!). - // That should generally hold true for javascript... - if (_this.privSubscribers === subs) { - _this.privSubscribers = subs; + else { + this.privSubscribers = null; + this.privList = null; + } + } + } + async dispose(reason) { + await this.drainAndDispose(null, reason); + } + drain() { + if (!this.privIsDrainInProgress && !this.privIsDisposing) { + this.privIsDrainInProgress = true; + const subs = this.privSubscribers; + const lists = this.privList; + if (subs && lists) { + while (lists.length() > 0 && subs.length() > 0 && !this.privIsDisposing) { + const subscriber = subs.removeFirst(); + if (subscriber.type === SubscriberType.Peek) { + subscriber.deferral.resolve(lists.first()); } - // note: this block assumes cooperative multitasking, i.e., - // between the if-statement and the assignment there are no - // thread switches. - // Reason is that between the initial const = this.; and this - // point there is the derral.resolve() operation that might have - // caused recursive calls to the Queue, especially, calling - // Dispose() on the queue alredy (which would reset the var - // here to null!). - // That should generally hold true for javascript... - if (_this.privList === lists) { - _this.privList = lists; + else { + const dequeuedItem = lists.removeFirst(); + subscriber.deferral.resolve(dequeuedItem); } } - _this.privIsDrainInProgress = false; - } - }; - this.throwIfDispose = function () { - if (_this.isDisposed()) { - if (_this.privDisposeReason) { - throw new Error_1.InvalidOperationError(_this.privDisposeReason); - } - throw new Error_1.ObjectDisposedError("Queue"); - } - else if (_this.privIsDisposing) { - throw new Error_1.InvalidOperationError("Queue disposing"); + // note: this block assumes cooperative multitasking, i.e., + // between the if-statement and the assignment there are no + // thread switches. + // Reason is that between the initial const = this.; and this + // point there is the derral.resolve() operation that might have + // caused recursive calls to the Queue, especially, calling + // Dispose() on the queue alredy (which would reset the var + // here to null!). + // That should generally hold true for javascript... + if (this.privSubscribers === subs) { + this.privSubscribers = subs; + } + // note: this block assumes cooperative multitasking, i.e., + // between the if-statement and the assignment there are no + // thread switches. + // Reason is that between the initial const = this.; and this + // point there is the derral.resolve() operation that might have + // caused recursive calls to the Queue, especially, calling + // Dispose() on the queue alredy (which would reset the var + // here to null!). + // That should generally hold true for javascript... + if (this.privList === lists) { + this.privList = lists; + } + } + this.privIsDrainInProgress = false; + } + } + throwIfDispose() { + if (this.isDisposed()) { + if (this.privDisposeReason) { + throw new Error_js_1.InvalidOperationError(this.privDisposeReason); } - }; - this.privList = list ? list : new List_1.List(); - this.privDetachables = []; - this.privSubscribers = new List_1.List(); - this.privDetachables.push(this.privList.onAdded(this.drain)); - } - Queue.prototype.drainAndDispose = function (pendingItemProcessor, reason) { - return __awaiter(this, void 0, void 0, function () { - var subs, subscriber, _i, _a, detachable, promiseArray_1; - var _this = this; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!(!this.isDisposed() && !this.privIsDisposing)) return [3 /*break*/, 5]; - this.privDisposeReason = reason; - this.privIsDisposing = true; - subs = this.privSubscribers; - if (subs) { - while (subs.length() > 0) { - subscriber = subs.removeFirst(); - // TODO: this needs work (Resolve(null) instead?). - subscriber.deferral.resolve(undefined); - // subscriber.deferral.reject("Disposed"); - } - // note: this block assumes cooperative multitasking, i.e., - // between the if-statement and the assignment there are no - // thread switches. - // Reason is that between the initial const = this.; and this - // point there is the derral.resolve() operation that might have - // caused recursive calls to the Queue, especially, calling - // Dispose() on the queue alredy (which would reset the var - // here to null!). - // That should generally hold true for javascript... - if (this.privSubscribers === subs) { - this.privSubscribers = subs; - } - } - _i = 0, _a = this.privDetachables; - _b.label = 1; - case 1: - if (!(_i < _a.length)) return [3 /*break*/, 4]; - detachable = _a[_i]; - return [4 /*yield*/, detachable.detach()]; - case 2: - _b.sent(); - _b.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: - if (this.privPromiseStore.length() > 0 && pendingItemProcessor) { - promiseArray_1 = []; - this.privPromiseStore.toArray().forEach(function (wrapper) { - promiseArray_1.push(wrapper); - }); - return [2 /*return*/, Promise.all(promiseArray_1).finally(function () { - _this.privSubscribers = null; - _this.privList.forEach(function (item, index) { - pendingItemProcessor(item); - }); - _this.privList = null; - return; - }).then()]; - } - else { - this.privSubscribers = null; - this.privList = null; - } - _b.label = 5; - case 5: return [2 /*return*/]; - } - }); - }); - }; - Queue.prototype.dispose = function (reason) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.drainAndDispose(null, reason)]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - return Queue; -}()); + throw new Error_js_1.ObjectDisposedError("Queue"); + } + else if (this.privIsDisposing) { + throw new Error_js_1.InvalidOperationError("Queue disposing"); + } + } +} exports.Queue = Queue; /***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { +/* 50 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RawWebsocketMessage = void 0; -var ConnectionMessage_1 = __webpack_require__(24); -var Error_1 = __webpack_require__(25); -var Guid_1 = __webpack_require__(7); -var RawWebsocketMessage = /** @class */ (function () { - function RawWebsocketMessage(messageType, payload, id) { +const ConnectionMessage_js_1 = __webpack_require__(30); +const Error_js_1 = __webpack_require__(31); +const Guid_js_1 = __webpack_require__(7); +class RawWebsocketMessage { + constructor(messageType, payload, id) { this.privPayload = null; if (!payload) { - throw new Error_1.ArgumentNullError("payload"); + throw new Error_js_1.ArgumentNullError("payload"); } - if (messageType === ConnectionMessage_1.MessageType.Binary && payload.__proto__.constructor.name !== "ArrayBuffer") { - throw new Error_1.InvalidOperationError("Payload must be ArrayBuffer"); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (messageType === ConnectionMessage_js_1.MessageType.Binary && Object.getPrototypeOf(payload).constructor.name !== "ArrayBuffer") { + throw new Error_js_1.InvalidOperationError("Payload must be ArrayBuffer"); } - if (messageType === ConnectionMessage_1.MessageType.Text && !(typeof (payload) === "string")) { - throw new Error_1.InvalidOperationError("Payload must be a string"); + if (messageType === ConnectionMessage_js_1.MessageType.Text && !(typeof (payload) === "string")) { + throw new Error_js_1.InvalidOperationError("Payload must be a string"); } this.privMessageType = messageType; this.privPayload = payload; - this.privId = id ? id : Guid_1.createNoDashGuid(); - } - Object.defineProperty(RawWebsocketMessage.prototype, "messageType", { - get: function () { - return this.privMessageType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RawWebsocketMessage.prototype, "payload", { - get: function () { - return this.privPayload; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RawWebsocketMessage.prototype, "textContent", { - get: function () { - if (this.privMessageType === ConnectionMessage_1.MessageType.Binary) { - throw new Error_1.InvalidOperationError("Not supported for binary message"); - } - return this.privPayload; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RawWebsocketMessage.prototype, "binaryContent", { - get: function () { - if (this.privMessageType === ConnectionMessage_1.MessageType.Text) { - throw new Error_1.InvalidOperationError("Not supported for text message"); - } - return this.privPayload; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RawWebsocketMessage.prototype, "id", { - get: function () { - return this.privId; - }, - enumerable: false, - configurable: true - }); - return RawWebsocketMessage; -}()); + this.privId = id ? id : (0, Guid_js_1.createNoDashGuid)(); + } + get messageType() { + return this.privMessageType; + } + get payload() { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this.privPayload; + } + get textContent() { + if (this.privMessageType === ConnectionMessage_js_1.MessageType.Binary) { + throw new Error_js_1.InvalidOperationError("Not supported for binary message"); + } + return this.privPayload; + } + get binaryContent() { + if (this.privMessageType === ConnectionMessage_js_1.MessageType.Text) { + throw new Error_js_1.InvalidOperationError("Not supported for text message"); + } + return this.privPayload; + } + get id() { + return this.privId; + } +} exports.RawWebsocketMessage = RawWebsocketMessage; /***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { +/* 51 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RiffPcmEncoder = void 0; -var RiffPcmEncoder = /** @class */ (function () { - function RiffPcmEncoder(actualSampleRate, desiredSampleRate) { - var _this = this; - this.encode = function (actualAudioFrame) { - var audioFrame = _this.downSampleAudioFrame(actualAudioFrame, _this.privActualSampleRate, _this.privDesiredSampleRate); - if (!audioFrame) { - return null; - } - var audioLength = audioFrame.length * 2; - var buffer = new ArrayBuffer(audioLength); - var view = new DataView(buffer); - _this.floatTo16BitPCM(view, 0, audioFrame); - return buffer; - }; - this.setString = function (view, offset, str) { - for (var i = 0; i < str.length; i++) { - view.setUint8(offset + i, str.charCodeAt(i)); - } - }; - this.floatTo16BitPCM = function (view, offset, input) { - for (var i = 0; i < input.length; i++, offset += 2) { - var s = Math.max(-1, Math.min(1, input[i])); - view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true); - } - }; - this.downSampleAudioFrame = function (srcFrame, srcRate, dstRate) { - if (!srcFrame) { - return null; - } - if (dstRate === srcRate || dstRate > srcRate) { - return srcFrame; - } - var ratio = srcRate / dstRate; - var dstLength = Math.round(srcFrame.length / ratio); - var dstFrame = new Float32Array(dstLength); - var srcOffset = 0; - var dstOffset = 0; - while (dstOffset < dstLength) { - var nextSrcOffset = Math.round((dstOffset + 1) * ratio); - var accum = 0; - var count = 0; - while (srcOffset < nextSrcOffset && srcOffset < srcFrame.length) { - accum += srcFrame[srcOffset++]; - count++; - } - dstFrame[dstOffset++] = accum / count; - } - return dstFrame; - }; +class RiffPcmEncoder { + constructor(actualSampleRate, desiredSampleRate) { this.privActualSampleRate = actualSampleRate; this.privDesiredSampleRate = desiredSampleRate; } - return RiffPcmEncoder; -}()); + encode(actualAudioFrame) { + const audioFrame = this.downSampleAudioFrame(actualAudioFrame, this.privActualSampleRate, this.privDesiredSampleRate); + if (!audioFrame) { + return null; + } + const audioLength = audioFrame.length * 2; + const buffer = new ArrayBuffer(audioLength); + const view = new DataView(buffer); + this.floatTo16BitPCM(view, 0, audioFrame); + return buffer; + } + setString(view, offset, str) { + for (let i = 0; i < str.length; i++) { + view.setUint8(offset + i, str.charCodeAt(i)); + } + } + floatTo16BitPCM(view, offset, input) { + for (let i = 0; i < input.length; i++, offset += 2) { + const s = Math.max(-1, Math.min(1, input[i])); + view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true); + } + } + downSampleAudioFrame(srcFrame, srcRate, dstRate) { + if (!srcFrame) { + return null; + } + if (dstRate === srcRate || dstRate > srcRate) { + return srcFrame; + } + const ratio = srcRate / dstRate; + const dstLength = Math.round(srcFrame.length / ratio); + const dstFrame = new Float32Array(dstLength); + let srcOffset = 0; + let dstOffset = 0; + while (dstOffset < dstLength) { + const nextSrcOffset = Math.round((dstOffset + 1) * ratio); + let accum = 0; + let count = 0; + while (srcOffset < nextSrcOffset && srcOffset < srcFrame.length) { + accum += srcFrame[srcOffset++]; + count++; + } + dstFrame[dstOffset++] = accum / count; + } + return dstFrame; + } +} exports.RiffPcmEncoder = RiffPcmEncoder; /***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { +/* 52 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Stream = void 0; -var Error_1 = __webpack_require__(25); -var Guid_1 = __webpack_require__(7); -var Queue_1 = __webpack_require__(41); -var Stream = /** @class */ (function () { - function Stream(streamId) { - var _this = this; +const Error_js_1 = __webpack_require__(31); +const Guid_js_1 = __webpack_require__(7); +const Queue_js_1 = __webpack_require__(49); +class Stream { + constructor(streamId) { this.privIsWriteEnded = false; this.privIsReadEnded = false; - this.read = function () { - if (_this.privIsReadEnded) { - throw new Error_1.InvalidOperationError("Stream read has already finished"); - } - return _this.privReaderQueue - .dequeue() - .then(function (streamChunk) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(streamChunk === undefined || streamChunk.isEnd)) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privReaderQueue.dispose("End of stream reached")]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/, streamChunk]; - } - }); - }); }); - }; - this.readEnded = function () { - if (!_this.privIsReadEnded) { - _this.privIsReadEnded = true; - _this.privReaderQueue = new Queue_1.Queue(); - } - }; - this.throwIfClosed = function () { - if (_this.privIsWriteEnded) { - throw new Error_1.InvalidOperationError("Stream closed"); - } - }; - this.privId = streamId ? streamId : Guid_1.createNoDashGuid(); - this.privReaderQueue = new Queue_1.Queue(); - } - Object.defineProperty(Stream.prototype, "isClosed", { - get: function () { - return this.privIsWriteEnded; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Stream.prototype, "isReadEnded", { - get: function () { - return this.privIsReadEnded; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Stream.prototype, "id", { - get: function () { - return this.privId; - }, - enumerable: false, - configurable: true - }); - Stream.prototype.close = function () { + this.privId = streamId ? streamId : (0, Guid_js_1.createNoDashGuid)(); + this.privReaderQueue = new Queue_js_1.Queue(); + } + get isClosed() { + return this.privIsWriteEnded; + } + get isReadEnded() { + return this.privIsReadEnded; + } + get id() { + return this.privId; + } + close() { if (!this.privIsWriteEnded) { this.writeStreamChunk({ buffer: null, @@ -2981,8 +2547,8 @@ var Stream = /** @class */ (function () { }); this.privIsWriteEnded = true; } - }; - Stream.prototype.writeStreamChunk = function (streamChunk) { + } + writeStreamChunk(streamChunk) { this.throwIfClosed(); if (!this.privReaderQueue.isDisposed()) { try { @@ -2992,22 +2558,45 @@ var Stream = /** @class */ (function () { // Do nothing } } - }; - return Stream; -}()); + } + read() { + if (this.privIsReadEnded) { + throw new Error_js_1.InvalidOperationError("Stream read has already finished"); + } + return this.privReaderQueue + .dequeue() + .then(async (streamChunk) => { + if (streamChunk === undefined || streamChunk.isEnd) { + await this.privReaderQueue.dispose("End of stream reached"); + } + return streamChunk; + }); + } + readEnded() { + if (!this.privIsReadEnded) { + this.privIsReadEnded = true; + this.privReaderQueue = new Queue_js_1.Queue(); + } + } + throwIfClosed() { + if (this.privIsWriteEnded) { + throw new Error_js_1.InvalidOperationError("Stream closed"); + } + } +} exports.Stream = Stream; /***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { +/* 53 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TranslationStatus = void 0; /** * Defines translation status. @@ -3028,45 +2617,30 @@ var TranslationStatus; /***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { +/* 54 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ChunkedArrayBufferStream = void 0; -var Exports_1 = __webpack_require__(4); -var ChunkedArrayBufferStream = /** @class */ (function (_super) { - __extends(ChunkedArrayBufferStream, _super); - function ChunkedArrayBufferStream(targetChunkSize, streamId) { - var _this = _super.call(this, streamId) || this; - _this.privTargetChunkSize = targetChunkSize; - _this.privNextBufferReadyBytes = 0; - return _this; - } - ChunkedArrayBufferStream.prototype.writeStreamChunk = function (chunk) { +const Exports_js_1 = __webpack_require__(4); +class ChunkedArrayBufferStream extends Exports_js_1.Stream { + constructor(targetChunkSize, streamId) { + super(streamId); + this.privTargetChunkSize = Math.round(targetChunkSize); + this.privNextBufferReadyBytes = 0; + } + writeStreamChunk(chunk) { // No pending write, and the buffer is the right size so write it. if (chunk.isEnd || (0 === this.privNextBufferReadyBytes && chunk.buffer.byteLength === this.privTargetChunkSize)) { - _super.prototype.writeStreamChunk.call(this, chunk); + super.writeStreamChunk(chunk); return; } - var bytesCopiedFromBuffer = 0; + let bytesCopiedFromBuffer = 0; while (bytesCopiedFromBuffer < chunk.buffer.byteLength) { // Fill the next buffer. if (undefined === this.privNextBufferToWrite) { @@ -3074,15 +2648,15 @@ var ChunkedArrayBufferStream = /** @class */ (function (_super) { this.privNextBufferStartTime = chunk.timeReceived; } // Find out how many bytes we can copy into the read buffer. - var bytesToCopy = Math.min(chunk.buffer.byteLength - bytesCopiedFromBuffer, this.privTargetChunkSize - this.privNextBufferReadyBytes); - var targetView = new Uint8Array(this.privNextBufferToWrite); - var sourceView = new Uint8Array(chunk.buffer.slice(bytesCopiedFromBuffer, bytesToCopy + bytesCopiedFromBuffer)); + const bytesToCopy = Math.min(chunk.buffer.byteLength - bytesCopiedFromBuffer, this.privTargetChunkSize - this.privNextBufferReadyBytes); + const targetView = new Uint8Array(this.privNextBufferToWrite); + const sourceView = new Uint8Array(chunk.buffer.slice(bytesCopiedFromBuffer, bytesToCopy + bytesCopiedFromBuffer)); targetView.set(sourceView, this.privNextBufferReadyBytes); this.privNextBufferReadyBytes += bytesToCopy; bytesCopiedFromBuffer += bytesToCopy; // Are we ready to write? if (this.privNextBufferReadyBytes === this.privTargetChunkSize) { - _super.prototype.writeStreamChunk.call(this, { + super.writeStreamChunk({ buffer: this.privNextBufferToWrite, isEnd: false, timeReceived: this.privNextBufferStartTime, @@ -3091,64 +2665,60 @@ var ChunkedArrayBufferStream = /** @class */ (function (_super) { this.privNextBufferToWrite = undefined; } } - }; - ChunkedArrayBufferStream.prototype.close = function () { + } + close() { // Send whatever is pending, then close the base class. if (0 !== this.privNextBufferReadyBytes && !this.isClosed) { - _super.prototype.writeStreamChunk.call(this, { + super.writeStreamChunk({ buffer: this.privNextBufferToWrite.slice(0, this.privNextBufferReadyBytes), isEnd: false, timeReceived: this.privNextBufferStartTime, }); } - _super.prototype.close.call(this); - }; - return ChunkedArrayBufferStream; -}(Exports_1.Stream)); + super.close(); + } +} exports.ChunkedArrayBufferStream = ChunkedArrayBufferStream; /***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { +/* 55 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { +/* 56 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Timeout = void 0; -var Timeout = /** @class */ (function () { - function Timeout() { - } - Timeout.workerTimers = null; - Timeout.clearTimeout = function (timerId) { return Timeout.timers().clearTimeout(timerId); }; - Timeout.setTimeout = function (func, delay) { return Timeout.timers().setTimeout(func, delay); }; - Timeout.load = function (url) { +class Timeout { + static load() { // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification. - var scheduledTimeoutFunctions = new Map([[0, function () { }]]); // tslint:disable-line no-empty - var unhandledRequests = new Map(); - var worker = new Worker(url); - worker.addEventListener("message", function (_a) { - var data = _a.data; + const scheduledTimeoutFunctions = new Map([[0, () => { }]]); // eslint-disable-line @typescript-eslint/no-empty-function + const unhandledRequests = new Map(); + // eslint-disable-next-line + const workerScript = `!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=14)}([function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return d}));const r=new Map,o=new Map,i=e=>{const t=r.get(e);if(void 0===t)throw new Error('There is no interval scheduled with the given id "'.concat(e,'".'));clearTimeout(t),r.delete(e)},u=e=>{const t=o.get(e);if(void 0===t)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(t),o.delete(e)},f=(e,t)=>{let n,r;if("performance"in self){const o=performance.now();n=o,r=e-Math.max(0,o-t)}else n=Date.now(),r=e;return{expected:n+r,remainingDelay:r}},c=(e,t,n,r)=>{const o="performance"in self?performance.now():Date.now();o>n?postMessage({id:null,method:"call",params:{timerId:t}}):e.set(t,setTimeout(c,n-o,e,t,n))},a=(e,t,n)=>{const{expected:o,remainingDelay:i}=f(e,n);r.set(t,setTimeout(c,i,r,t,o))},d=(e,t,n)=>{const{expected:r,remainingDelay:i}=f(e,n);o.set(t,setTimeout(c,i,o,t,r))}},function(e,t,n){"use strict";n.r(t);var r=n(2);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(3);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(4);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o);var f=n(5);for(var o in f)"default"!==o&&function(e){n.d(t,e,(function(){return f[e]}))}(o);var c=n(6);for(var o in c)"default"!==o&&function(e){n.d(t,e,(function(){return c[e]}))}(o);var a=n(7);for(var o in a)"default"!==o&&function(e){n.d(t,e,(function(){return a[e]}))}(o);var d=n(8);for(var o in d)"default"!==o&&function(e){n.d(t,e,(function(){return d[e]}))}(o);var s=n(9);for(var o in s)"default"!==o&&function(e){n.d(t,e,(function(){return s[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(11);for(var o in r)"default"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(12);for(var o in i)"default"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(13);for(var o in u)"default"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";n.r(t);var r=n(0),o=n(1);for(var i in o)"default"!==i&&function(e){n.d(t,e,(function(){return o[e]}))}(i);var u=n(10);for(var i in u)"default"!==i&&function(e){n.d(t,e,(function(){return u[e]}))}(i);addEventListener("message",({data:e})=>{try{if("clear"===e.method){const{id:t,params:{timerId:n}}=e;Object(r.b)(n),postMessage({error:null,id:t})}else{if("set"!==e.method)throw new Error('The given method "'.concat(e.method,'" is not supported'));{const{params:{delay:t,now:n,timerId:o}}=e;Object(r.d)(t,o,n)}}}catch(t){postMessage({error:{message:t.message},id:e.id,result:null})}})}]);`; + const workerUrl = "data:text/javascript;base64," + btoa(workerScript); + const worker = new Worker(workerUrl); + worker.addEventListener("message", ({ data }) => { if (Timeout.isCallNotification(data)) { - var timerId = data.params.timerId; - var idOrFunc = scheduledTimeoutFunctions.get(timerId); + const { params: { timerId } } = data; + const idOrFunc = scheduledTimeoutFunctions.get(timerId); if (typeof idOrFunc === "number") { - var unhandledTimerId = unhandledRequests.get(idOrFunc); + const unhandledTimerId = unhandledRequests.get(idOrFunc); if (unhandledTimerId === undefined || unhandledTimerId !== timerId) { throw new Error("The timer is in an undefined state."); @@ -3164,8 +2734,8 @@ var Timeout = /** @class */ (function () { } } else if (Timeout.isClearResponse(data)) { - var id = data.id; - var unhandledTimerId = unhandledRequests.get(id); + const { id } = data; + const unhandledTimerId = unhandledRequests.get(id); if (unhandledTimerId === undefined) { throw new Error("The timer is in an undefined state."); } @@ -3173,4601 +2743,4121 @@ var Timeout = /** @class */ (function () { scheduledTimeoutFunctions.delete(unhandledTimerId); } else { - var message = data.error.message; + const { error: { message } } = data; throw new Error(message); } }); - var clearTimeout = function (timerId) { - var id = Math.random(); + const clearTimeout = (timerId) => { + const id = Math.random(); unhandledRequests.set(id, timerId); scheduledTimeoutFunctions.set(timerId, id); worker.postMessage({ - id: id, + id, method: "clear", - params: { timerId: timerId } + params: { timerId } }); }; - var setTimeout = function (func, delay) { - var timerId = Math.random(); + const setTimeout = (func, delay) => { + const timerId = Math.random(); scheduledTimeoutFunctions.set(timerId, func); worker.postMessage({ id: null, method: "set", params: { - delay: delay, + delay, now: performance.now(), - timerId: timerId + timerId } }); return timerId; }; return { - clearTimeout: clearTimeout, - setTimeout: setTimeout + clearTimeout, + setTimeout }; - }; - Timeout.loadWorkerTimers = function () { - var worker = "!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&\"object\"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,\"default\",{enumerable:!0,value:e}),2&t&&\"string\"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,\"a\",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=\"\",n(n.s=14)}([function(e,t,n){\"use strict\";n.d(t,\"a\",(function(){return i})),n.d(t,\"b\",(function(){return u})),n.d(t,\"c\",(function(){return a})),n.d(t,\"d\",(function(){return d}));const r=new Map,o=new Map,i=e=>{const t=r.get(e);if(void 0===t)throw new Error('There is no interval scheduled with the given id \"'.concat(e,'\".'));clearTimeout(t),r.delete(e)},u=e=>{const t=o.get(e);if(void 0===t)throw new Error('There is no timeout scheduled with the given id \"'.concat(e,'\".'));clearTimeout(t),o.delete(e)},f=(e,t)=>{let n,r;if(\"performance\"in self){const o=performance.now();n=o,r=e-Math.max(0,o-t)}else n=Date.now(),r=e;return{expected:n+r,remainingDelay:r}},c=(e,t,n,r)=>{const o=\"performance\"in self?performance.now():Date.now();o>n?postMessage({id:null,method:\"call\",params:{timerId:t}}):e.set(t,setTimeout(c,n-o,e,t,n))},a=(e,t,n)=>{const{expected:o,remainingDelay:i}=f(e,n);r.set(t,setTimeout(c,i,r,t,o))},d=(e,t,n)=>{const{expected:r,remainingDelay:i}=f(e,n);o.set(t,setTimeout(c,i,o,t,r))}},function(e,t,n){\"use strict\";n.r(t);var r=n(2);for(var o in r)\"default\"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(3);for(var o in i)\"default\"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(4);for(var o in u)\"default\"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o);var f=n(5);for(var o in f)\"default\"!==o&&function(e){n.d(t,e,(function(){return f[e]}))}(o);var c=n(6);for(var o in c)\"default\"!==o&&function(e){n.d(t,e,(function(){return c[e]}))}(o);var a=n(7);for(var o in a)\"default\"!==o&&function(e){n.d(t,e,(function(){return a[e]}))}(o);var d=n(8);for(var o in d)\"default\"!==o&&function(e){n.d(t,e,(function(){return d[e]}))}(o);var s=n(9);for(var o in s)\"default\"!==o&&function(e){n.d(t,e,(function(){return s[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){\"use strict\";n.r(t);var r=n(11);for(var o in r)\"default\"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(12);for(var o in i)\"default\"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(13);for(var o in u)\"default\"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){\"use strict\";n.r(t);var r=n(0),o=n(1);for(var i in o)\"default\"!==i&&function(e){n.d(t,e,(function(){return o[e]}))}(i);var u=n(10);for(var i in u)\"default\"!==i&&function(e){n.d(t,e,(function(){return u[e]}))}(i);addEventListener(\"message\",({data:e})=>{try{if(\"clear\"===e.method){const{id:t,params:{timerId:n}}=e;Object(r.b)(n),postMessage({error:null,id:t})}else{if(\"set\"!==e.method)throw new Error('The given method \"'.concat(e.method,'\" is not supported'));{const{params:{delay:t,now:n,timerId:o}}=e;Object(r.d)(t,o,n)}}}catch(t){postMessage({error:{message:t.message},id:e.id,result:null})}})}]);"; // tslint:disable-line:max-line-length - return function () { + } + static loadWorkerTimers() { + return () => { if (Timeout.workerTimers !== null) { return Timeout.workerTimers; } - var blob = new Blob([worker], { type: "application/javascript; charset=utf-8" }); - var url = URL.createObjectURL(blob); - Timeout.workerTimers = Timeout.load(url); - // Edge doesn't like the URL to be revoked directly. - Timeout.workerTimers.setTimeout(function () { return URL.revokeObjectURL(url); }, 0); + Timeout.workerTimers = Timeout.load(); return Timeout.workerTimers; }; - }; - Timeout.timers = Timeout.loadWorkerTimers(); - Timeout.isCallNotification = function (message) { + } + static isCallNotification(message) { return message.method !== undefined && message.method === "call"; - }; - Timeout.isClearResponse = function (message) { + } + static isClearResponse(message) { return message.error === null && typeof message.id === "number"; - }; - return Timeout; -}()); + } +} exports.Timeout = Timeout; +Timeout.workerTimers = null; +Timeout.clearTimeout = (timerId) => Timeout.timers().clearTimeout(timerId); +Timeout.setTimeout = (func, delay) => Timeout.timers().setTimeout(func, delay); +Timeout.timers = Timeout.loadWorkerTimers(); /***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { +/* 57 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OCSPCacheUpdateErrorEvent = exports.OCSPResponseRetrievedEvent = exports.OCSPCacheFetchErrorEvent = exports.OCSPVerificationFailedEvent = exports.OCSPCacheHitEvent = exports.OCSPCacheEntryNeedsRefreshEvent = exports.OCSPCacheEntryExpiredEvent = exports.OCSPWSUpgradeStartedEvent = exports.OCSPStapleReceivedEvent = exports.OCSPCacheUpdateCompleteEvent = exports.OCSPDiskCacheStoreEvent = exports.OCSPMemoryCacheStoreEvent = exports.OCSPCacheUpdateNeededEvent = exports.OCSPDiskCacheHitEvent = exports.OCSPCacheMissEvent = exports.OCSPMemoryCacheHitEvent = exports.OCSPEvent = void 0; -// tslint:disable:max-classes-per-file -var PlatformEvent_1 = __webpack_require__(6); -var OCSPEvent = /** @class */ (function (_super) { - __extends(OCSPEvent, _super); - function OCSPEvent(eventName, eventType, signature) { - var _this = _super.call(this, eventName, eventType) || this; - _this.privSignature = signature; - return _this; - } - return OCSPEvent; -}(PlatformEvent_1.PlatformEvent)); +/* eslint-disable max-classes-per-file */ +const PlatformEvent_js_1 = __webpack_require__(6); +class OCSPEvent extends PlatformEvent_js_1.PlatformEvent { + constructor(eventName, eventType, signature) { + super(eventName, eventType); + this.privSignature = signature; + } +} exports.OCSPEvent = OCSPEvent; -var OCSPMemoryCacheHitEvent = /** @class */ (function (_super) { - __extends(OCSPMemoryCacheHitEvent, _super); - function OCSPMemoryCacheHitEvent(signature) { - return _super.call(this, "OCSPMemoryCacheHitEvent", PlatformEvent_1.EventType.Debug, signature) || this; +class OCSPMemoryCacheHitEvent extends OCSPEvent { + constructor(signature) { + super("OCSPMemoryCacheHitEvent", PlatformEvent_js_1.EventType.Debug, signature); } - return OCSPMemoryCacheHitEvent; -}(OCSPEvent)); +} exports.OCSPMemoryCacheHitEvent = OCSPMemoryCacheHitEvent; -var OCSPCacheMissEvent = /** @class */ (function (_super) { - __extends(OCSPCacheMissEvent, _super); - function OCSPCacheMissEvent(signature) { - return _super.call(this, "OCSPCacheMissEvent", PlatformEvent_1.EventType.Debug, signature) || this; +class OCSPCacheMissEvent extends OCSPEvent { + constructor(signature) { + super("OCSPCacheMissEvent", PlatformEvent_js_1.EventType.Debug, signature); } - return OCSPCacheMissEvent; -}(OCSPEvent)); +} exports.OCSPCacheMissEvent = OCSPCacheMissEvent; -var OCSPDiskCacheHitEvent = /** @class */ (function (_super) { - __extends(OCSPDiskCacheHitEvent, _super); - function OCSPDiskCacheHitEvent(signature) { - return _super.call(this, "OCSPDiskCacheHitEvent", PlatformEvent_1.EventType.Debug, signature) || this; +class OCSPDiskCacheHitEvent extends OCSPEvent { + constructor(signature) { + super("OCSPDiskCacheHitEvent", PlatformEvent_js_1.EventType.Debug, signature); } - return OCSPDiskCacheHitEvent; -}(OCSPEvent)); +} exports.OCSPDiskCacheHitEvent = OCSPDiskCacheHitEvent; -var OCSPCacheUpdateNeededEvent = /** @class */ (function (_super) { - __extends(OCSPCacheUpdateNeededEvent, _super); - function OCSPCacheUpdateNeededEvent(signature) { - return _super.call(this, "OCSPCacheUpdateNeededEvent", PlatformEvent_1.EventType.Debug, signature) || this; +class OCSPCacheUpdateNeededEvent extends OCSPEvent { + constructor(signature) { + super("OCSPCacheUpdateNeededEvent", PlatformEvent_js_1.EventType.Debug, signature); } - return OCSPCacheUpdateNeededEvent; -}(OCSPEvent)); +} exports.OCSPCacheUpdateNeededEvent = OCSPCacheUpdateNeededEvent; -var OCSPMemoryCacheStoreEvent = /** @class */ (function (_super) { - __extends(OCSPMemoryCacheStoreEvent, _super); - function OCSPMemoryCacheStoreEvent(signature) { - return _super.call(this, "OCSPMemoryCacheStoreEvent", PlatformEvent_1.EventType.Debug, signature) || this; +class OCSPMemoryCacheStoreEvent extends OCSPEvent { + constructor(signature) { + super("OCSPMemoryCacheStoreEvent", PlatformEvent_js_1.EventType.Debug, signature); } - return OCSPMemoryCacheStoreEvent; -}(OCSPEvent)); +} exports.OCSPMemoryCacheStoreEvent = OCSPMemoryCacheStoreEvent; -var OCSPDiskCacheStoreEvent = /** @class */ (function (_super) { - __extends(OCSPDiskCacheStoreEvent, _super); - function OCSPDiskCacheStoreEvent(signature) { - return _super.call(this, "OCSPDiskCacheStoreEvent", PlatformEvent_1.EventType.Debug, signature) || this; +class OCSPDiskCacheStoreEvent extends OCSPEvent { + constructor(signature) { + super("OCSPDiskCacheStoreEvent", PlatformEvent_js_1.EventType.Debug, signature); } - return OCSPDiskCacheStoreEvent; -}(OCSPEvent)); +} exports.OCSPDiskCacheStoreEvent = OCSPDiskCacheStoreEvent; -var OCSPCacheUpdateCompleteEvent = /** @class */ (function (_super) { - __extends(OCSPCacheUpdateCompleteEvent, _super); - function OCSPCacheUpdateCompleteEvent(signature) { - return _super.call(this, "OCSPCacheUpdateCompleteEvent", PlatformEvent_1.EventType.Debug, signature) || this; +class OCSPCacheUpdateCompleteEvent extends OCSPEvent { + constructor(signature) { + super("OCSPCacheUpdateCompleteEvent", PlatformEvent_js_1.EventType.Debug, signature); } - return OCSPCacheUpdateCompleteEvent; -}(OCSPEvent)); +} exports.OCSPCacheUpdateCompleteEvent = OCSPCacheUpdateCompleteEvent; -var OCSPStapleReceivedEvent = /** @class */ (function (_super) { - __extends(OCSPStapleReceivedEvent, _super); - function OCSPStapleReceivedEvent() { - return _super.call(this, "OCSPStapleReceivedEvent", PlatformEvent_1.EventType.Debug, "") || this; +class OCSPStapleReceivedEvent extends OCSPEvent { + constructor() { + super("OCSPStapleReceivedEvent", PlatformEvent_js_1.EventType.Debug, ""); } - return OCSPStapleReceivedEvent; -}(OCSPEvent)); +} exports.OCSPStapleReceivedEvent = OCSPStapleReceivedEvent; -var OCSPWSUpgradeStartedEvent = /** @class */ (function (_super) { - __extends(OCSPWSUpgradeStartedEvent, _super); - function OCSPWSUpgradeStartedEvent(serialNumber) { - return _super.call(this, "OCSPWSUpgradeStartedEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this; +class OCSPWSUpgradeStartedEvent extends OCSPEvent { + constructor(serialNumber) { + super("OCSPWSUpgradeStartedEvent", PlatformEvent_js_1.EventType.Debug, serialNumber); } - return OCSPWSUpgradeStartedEvent; -}(OCSPEvent)); +} exports.OCSPWSUpgradeStartedEvent = OCSPWSUpgradeStartedEvent; -var OCSPCacheEntryExpiredEvent = /** @class */ (function (_super) { - __extends(OCSPCacheEntryExpiredEvent, _super); - function OCSPCacheEntryExpiredEvent(serialNumber, expireTime) { - var _this = _super.call(this, "OCSPCacheEntryExpiredEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this; - _this.privExpireTime = expireTime; - return _this; - } - return OCSPCacheEntryExpiredEvent; -}(OCSPEvent)); +class OCSPCacheEntryExpiredEvent extends OCSPEvent { + constructor(serialNumber, expireTime) { + super("OCSPCacheEntryExpiredEvent", PlatformEvent_js_1.EventType.Debug, serialNumber); + this.privExpireTime = expireTime; + } +} exports.OCSPCacheEntryExpiredEvent = OCSPCacheEntryExpiredEvent; -var OCSPCacheEntryNeedsRefreshEvent = /** @class */ (function (_super) { - __extends(OCSPCacheEntryNeedsRefreshEvent, _super); - function OCSPCacheEntryNeedsRefreshEvent(serialNumber, startTime, expireTime) { - var _this = _super.call(this, "OCSPCacheEntryNeedsRefreshEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this; - _this.privExpireTime = expireTime; - _this.privStartTime = startTime; - return _this; - } - return OCSPCacheEntryNeedsRefreshEvent; -}(OCSPEvent)); +class OCSPCacheEntryNeedsRefreshEvent extends OCSPEvent { + constructor(serialNumber, startTime, expireTime) { + super("OCSPCacheEntryNeedsRefreshEvent", PlatformEvent_js_1.EventType.Debug, serialNumber); + this.privExpireTime = expireTime; + this.privStartTime = startTime; + } +} exports.OCSPCacheEntryNeedsRefreshEvent = OCSPCacheEntryNeedsRefreshEvent; -var OCSPCacheHitEvent = /** @class */ (function (_super) { - __extends(OCSPCacheHitEvent, _super); - function OCSPCacheHitEvent(serialNumber, startTime, expireTime) { - var _this = _super.call(this, "OCSPCacheHitEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this; - _this.privExpireTime = expireTime; - _this.privExpireTimeString = new Date(expireTime).toLocaleDateString(); - _this.privStartTime = startTime; - _this.privStartTimeString = new Date(startTime).toLocaleTimeString(); - return _this; - } - return OCSPCacheHitEvent; -}(OCSPEvent)); +class OCSPCacheHitEvent extends OCSPEvent { + constructor(serialNumber, startTime, expireTime) { + super("OCSPCacheHitEvent", PlatformEvent_js_1.EventType.Debug, serialNumber); + this.privExpireTime = expireTime; + this.privExpireTimeString = new Date(expireTime).toLocaleDateString(); + this.privStartTime = startTime; + this.privStartTimeString = new Date(startTime).toLocaleTimeString(); + } +} exports.OCSPCacheHitEvent = OCSPCacheHitEvent; -var OCSPVerificationFailedEvent = /** @class */ (function (_super) { - __extends(OCSPVerificationFailedEvent, _super); - function OCSPVerificationFailedEvent(serialNumber, error) { - var _this = _super.call(this, "OCSPVerificationFailedEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this; - _this.privError = error; - return _this; - } - return OCSPVerificationFailedEvent; -}(OCSPEvent)); +class OCSPVerificationFailedEvent extends OCSPEvent { + constructor(serialNumber, error) { + super("OCSPVerificationFailedEvent", PlatformEvent_js_1.EventType.Debug, serialNumber); + this.privError = error; + } +} exports.OCSPVerificationFailedEvent = OCSPVerificationFailedEvent; -var OCSPCacheFetchErrorEvent = /** @class */ (function (_super) { - __extends(OCSPCacheFetchErrorEvent, _super); - function OCSPCacheFetchErrorEvent(serialNumber, error) { - var _this = _super.call(this, "OCSPCacheFetchErrorEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this; - _this.privError = error; - return _this; - } - return OCSPCacheFetchErrorEvent; -}(OCSPEvent)); +class OCSPCacheFetchErrorEvent extends OCSPEvent { + constructor(serialNumber, error) { + super("OCSPCacheFetchErrorEvent", PlatformEvent_js_1.EventType.Debug, serialNumber); + this.privError = error; + } +} exports.OCSPCacheFetchErrorEvent = OCSPCacheFetchErrorEvent; -var OCSPResponseRetrievedEvent = /** @class */ (function (_super) { - __extends(OCSPResponseRetrievedEvent, _super); - function OCSPResponseRetrievedEvent(serialNumber) { - return _super.call(this, "OCSPResponseRetrievedEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this; +class OCSPResponseRetrievedEvent extends OCSPEvent { + constructor(serialNumber) { + super("OCSPResponseRetrievedEvent", PlatformEvent_js_1.EventType.Debug, serialNumber); } - return OCSPResponseRetrievedEvent; -}(OCSPEvent)); +} exports.OCSPResponseRetrievedEvent = OCSPResponseRetrievedEvent; -var OCSPCacheUpdateErrorEvent = /** @class */ (function (_super) { - __extends(OCSPCacheUpdateErrorEvent, _super); - function OCSPCacheUpdateErrorEvent(serialNumber, error) { - var _this = _super.call(this, "OCSPCacheUpdateErrorEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this; - _this.privError = error; - return _this; - } - return OCSPCacheUpdateErrorEvent; -}(OCSPEvent)); +class OCSPCacheUpdateErrorEvent extends OCSPEvent { + constructor(serialNumber, error) { + super("OCSPCacheUpdateErrorEvent", PlatformEvent_js_1.EventType.Debug, serialNumber); + this.privError = error; + } +} exports.OCSPCacheUpdateErrorEvent = OCSPCacheUpdateErrorEvent; /***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { +/* 58 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BackgroundEvent = void 0; -var Exports_1 = __webpack_require__(4); -var BackgroundEvent = /** @class */ (function (_super) { - __extends(BackgroundEvent, _super); - function BackgroundEvent(error) { - var _this = _super.call(this, "BackgroundEvent", Exports_1.EventType.Error) || this; - _this.privError = error; - return _this; - } - Object.defineProperty(BackgroundEvent.prototype, "error", { - get: function () { - return this.privError; - }, - enumerable: false, - configurable: true - }); - return BackgroundEvent; -}(Exports_1.PlatformEvent)); +const Exports_js_1 = __webpack_require__(4); +class BackgroundEvent extends Exports_js_1.PlatformEvent { + constructor(error) { + super("BackgroundEvent", Exports_js_1.EventType.Error); + this.privError = error; + } + get error() { + return this.privError; + } +} exports.BackgroundEvent = BackgroundEvent; /***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { +/* 59 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HeaderNames = void 0; +class HeaderNames { +} +exports.HeaderNames = HeaderNames; +HeaderNames.AuthKey = "Ocp-Apim-Subscription-Key"; +HeaderNames.Authorization = "Authorization"; +HeaderNames.SpIDAuthKey = "Apim-Subscription-Id"; +HeaderNames.ConnectionId = "X-ConnectionId"; +HeaderNames.ContentType = "Content-Type"; +HeaderNames.CustomCommandsAppId = "X-CommandsAppId"; +HeaderNames.Path = "Path"; +HeaderNames.RequestId = "X-RequestId"; +HeaderNames.RequestStreamId = "X-StreamId"; +HeaderNames.RequestTimestamp = "X-Timestamp"; +// Reliable reconnect protocol (service-originated) headers. The service tag is not a +// header; it arrives in the turn.start body under "$.context.serviceTag". +HeaderNames.ContinuationToken = "X-Continuation-Token"; +// Resume offset for the single audio stream (id "1"); the stream's position otherwise +// rides on X-Continuation-Token, so there is no per-primary-stream offset header. +HeaderNames.ContinuationAudioStreamOffset = "X-Continuation-Audio-Streams-1-Offset"; /***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { +/* 60 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MicAudioSource = exports.AudioWorkletSourceURLPropertyName = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var AudioStreamFormat_1 = __webpack_require__(72); -exports.AudioWorkletSourceURLPropertyName = "MICROPHONE-WorkletSourceUrl"; -var MicAudioSource = /** @class */ (function () { - function MicAudioSource(privRecorder, deviceId, audioSourceId, mediaStream) { - var _this = this; - this.privRecorder = privRecorder; - this.deviceId = deviceId; - this.privStreams = {}; - this.turnOn = function () { - if (_this.privInitializeDeferral) { - return _this.privInitializeDeferral.promise; - } - _this.privInitializeDeferral = new Exports_2.Deferred(); - try { - _this.createAudioContext(); - } - catch (error) { - if (error instanceof Error) { - var typedError = error; - _this.privInitializeDeferral.reject(typedError.name + ": " + typedError.message); - } - else { - _this.privInitializeDeferral.reject(error); - } - return _this.privInitializeDeferral.promise; - } - var nav = window.navigator; - var getUserMedia = (nav.getUserMedia || - nav.webkitGetUserMedia || - nav.mozGetUserMedia || - nav.msGetUserMedia); - if (!!nav.mediaDevices) { - getUserMedia = function (constraints, successCallback, errorCallback) { - nav.mediaDevices - .getUserMedia(constraints) - .then(successCallback) - .catch(errorCallback); - }; - } - if (!getUserMedia) { - var errorMsg = "Browser does not support getUserMedia."; - _this.privInitializeDeferral.reject(errorMsg); - _this.onEvent(new Exports_2.AudioSourceErrorEvent(errorMsg, "")); // mic initialized error - no streamid at this point - } - else { - var next = function () { - _this.onEvent(new Exports_2.AudioSourceInitializingEvent(_this.privId)); // no stream id - if (_this.privMediaStream && _this.privMediaStream.active) { - _this.onEvent(new Exports_2.AudioSourceReadyEvent(_this.privId)); - _this.privInitializeDeferral.resolve(); - } - else { - getUserMedia({ audio: _this.deviceId ? { deviceId: _this.deviceId } : true, video: false }, function (mediaStream) { - _this.privMediaStream = mediaStream; - _this.onEvent(new Exports_2.AudioSourceReadyEvent(_this.privId)); - _this.privInitializeDeferral.resolve(); - }, function (error) { - var errorMsg = "Error occurred during microphone initialization: " + error; - _this.privInitializeDeferral.reject(errorMsg); - _this.onEvent(new Exports_2.AudioSourceErrorEvent(_this.privId, errorMsg)); - }); - } - }; - if (_this.privContext.state === "suspended") { - // NOTE: On iOS, the Web Audio API requires sounds to be triggered from an explicit user action. - // https://github.com/WebAudio/web-audio-api/issues/790 - _this.privContext.resume() - .then(next) - .catch(function (reason) { - _this.privInitializeDeferral.reject("Failed to initialize audio context: " + reason); - }); - } - else { - next(); - } - } - return _this.privInitializeDeferral.promise; - }; - this.id = function () { - return _this.privId; - }; - this.attach = function (audioNodeId) { - _this.onEvent(new Exports_2.AudioStreamNodeAttachingEvent(_this.privId, audioNodeId)); - return _this.listen(audioNodeId).then(function (stream) { - _this.onEvent(new Exports_2.AudioStreamNodeAttachedEvent(_this.privId, audioNodeId)); - return { - detach: function () { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - stream.readEnded(); - delete this.privStreams[audioNodeId]; - this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); - return [2 /*return*/, this.turnOff()]; - }); - }); }, - id: function () { - return audioNodeId; - }, - read: function () { - return stream.read(); - }, - }; - }); - }; - this.detach = function (audioNodeId) { - if (audioNodeId && _this.privStreams[audioNodeId]) { - _this.privStreams[audioNodeId].close(); - delete _this.privStreams[audioNodeId]; - _this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(_this.privId, audioNodeId)); - } - }; - this.listen = function (audioNodeId) { return __awaiter(_this, void 0, void 0, function () { - var stream, result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.turnOn()]; - case 1: - _a.sent(); - stream = new Exports_2.ChunkedArrayBufferStream(this.privOutputChunkSize, audioNodeId); - this.privStreams[audioNodeId] = stream; - try { - this.privRecorder.record(this.privContext, this.privMediaStream, stream); - } - catch (error) { - this.onEvent(new Exports_2.AudioStreamNodeErrorEvent(this.privId, audioNodeId, error)); - throw error; - } - result = stream; - return [2 /*return*/, result]; - } - }); - }); }; - this.onEvent = function (event) { - _this.privEvents.onEvent(event); - Exports_2.Events.instance.onEvent(event); - }; - this.createAudioContext = function () { - if (!!_this.privContext) { - return; - } - _this.privContext = AudioStreamFormat_1.AudioStreamFormatImpl.getAudioContext(MicAudioSource.AUDIOFORMAT.samplesPerSec); - }; - this.privOutputChunkSize = MicAudioSource.AUDIOFORMAT.avgBytesPerSec / 10; - this.privId = audioSourceId ? audioSourceId : Exports_2.createNoDashGuid(); - this.privEvents = new Exports_2.EventSource(); - this.privMediaStream = mediaStream || null; - this.privIsClosing = false; - } - Object.defineProperty(MicAudioSource.prototype, "format", { - get: function () { - return Promise.resolve(MicAudioSource.AUDIOFORMAT); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MicAudioSource.prototype, "blob", { - get: function () { - return Promise.reject("Not implemented for Mic input"); - }, - enumerable: false, - configurable: true - }); - MicAudioSource.prototype.turnOff = function () { - return __awaiter(this, void 0, void 0, function () { - var streamId, stream; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - for (streamId in this.privStreams) { - if (streamId) { - stream = this.privStreams[streamId]; - if (stream) { - stream.close(); - } - } - } - this.onEvent(new Exports_2.AudioSourceOffEvent(this.privId)); // no stream now - if (!this.privInitializeDeferral) return [3 /*break*/, 2]; - // Correctly handle when browser forces mic off before turnOn() completes - return [4 /*yield*/, this.privInitializeDeferral]; - case 1: - // Correctly handle when browser forces mic off before turnOn() completes - _a.sent(); - this.privInitializeDeferral = null; - _a.label = 2; - case 2: return [4 /*yield*/, this.destroyAudioContext()]; - case 3: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - Object.defineProperty(MicAudioSource.prototype, "events", { - get: function () { - return this.privEvents; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MicAudioSource.prototype, "deviceInfo", { - get: function () { - return this.getMicrophoneLabel().then(function (label) { - return { - bitspersample: MicAudioSource.AUDIOFORMAT.bitsPerSample, - channelcount: MicAudioSource.AUDIOFORMAT.channels, - connectivity: Exports_1.connectivity.Unknown, - manufacturer: "Speech SDK", - model: label, - samplerate: MicAudioSource.AUDIOFORMAT.samplesPerSec, - type: Exports_1.type.Microphones, - }; - }); - }, - enumerable: false, - configurable: true - }); - MicAudioSource.prototype.setProperty = function (name, value) { - if (name === exports.AudioWorkletSourceURLPropertyName) { - this.privRecorder.setWorkletUrl(value); - } - else { - throw new Error("Property '" + name + "' is not supported on Microphone."); - } - }; - MicAudioSource.prototype.getMicrophoneLabel = function () { - var _this = this; - var defaultMicrophoneName = "microphone"; - // If we did this already, return the value. - if (this.privMicrophoneLabel !== undefined) { - return Promise.resolve(this.privMicrophoneLabel); - } - // If the stream isn't currently running, we can't query devices because security. - if (this.privMediaStream === undefined || !this.privMediaStream.active) { - return Promise.resolve(defaultMicrophoneName); - } - // Setup a default - this.privMicrophoneLabel = defaultMicrophoneName; - // Get the id of the device running the audio track. - var microphoneDeviceId = this.privMediaStream.getTracks()[0].getSettings().deviceId; - // If the browser doesn't support getting the device ID, set a default and return. - if (undefined === microphoneDeviceId) { - return Promise.resolve(this.privMicrophoneLabel); - } - var deferred = new Exports_2.Deferred(); - // Enumerate the media devices. - navigator.mediaDevices.enumerateDevices().then(function (devices) { - for (var _i = 0, devices_1 = devices; _i < devices_1.length; _i++) { - var device = devices_1[_i]; - if (device.deviceId === microphoneDeviceId) { - // Found the device - _this.privMicrophoneLabel = device.label; - break; - } - } - deferred.resolve(_this.privMicrophoneLabel); - }, function () { return deferred.resolve(_this.privMicrophoneLabel); }); - return deferred.promise; - }; - MicAudioSource.prototype.destroyAudioContext = function () { - return __awaiter(this, void 0, void 0, function () { - var hasClose; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.privContext) { - return [2 /*return*/]; - } - this.privRecorder.releaseMediaResources(this.privContext); - hasClose = false; - if ("close" in this.privContext) { - hasClose = true; - } - if (!hasClose) return [3 /*break*/, 3]; - if (!!this.privIsClosing) return [3 /*break*/, 2]; - // The audio context close may take enough time that the close is called twice - this.privIsClosing = true; - return [4 /*yield*/, this.privContext.close()]; - case 1: - _a.sent(); - this.privContext = null; - this.privIsClosing = false; - _a.label = 2; - case 2: return [3 /*break*/, 5]; - case 3: - if (!(null !== this.privContext && this.privContext.state === "running")) return [3 /*break*/, 5]; - // Suspend actually takes a callback, but analogous to the - // resume method, it'll be only fired if suspend is called - // in a direct response to a user action. The later is not always - // the case, as TurnOff is also called, when we receive an - // end-of-speech message from the service. So, doing a best effort - // fire-and-forget here. - return [4 /*yield*/, this.privContext.suspend()]; - case 4: - // Suspend actually takes a callback, but analogous to the - // resume method, it'll be only fired if suspend is called - // in a direct response to a user action. The later is not always - // the case, as TurnOff is also called, when we receive an - // end-of-speech message from the service. So, doing a best effort - // fire-and-forget here. - _a.sent(); - _a.label = 5; - case 5: return [2 /*return*/]; - } - }); - }); - }; - MicAudioSource.AUDIOFORMAT = AudioStreamFormat_1.AudioStreamFormat.getDefaultInputFormat(); - return MicAudioSource; -}()); -exports.MicAudioSource = MicAudioSource; - - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AutoDetectSourceLanguagesOpenRangeOptionName = exports.ForceDictationPropertyName = exports.ServicePropertiesPropertyName = exports.CancellationErrorCodePropertyName = exports.OutputFormatPropertyName = void 0; -// Make sure not to export internal modules. -// -__exportStar(__webpack_require__(54), exports); -__exportStar(__webpack_require__(57), exports); -__exportStar(__webpack_require__(56), exports); -__exportStar(__webpack_require__(58), exports); -__exportStar(__webpack_require__(59), exports); -__exportStar(__webpack_require__(60), exports); -__exportStar(__webpack_require__(171), exports); -__exportStar(__webpack_require__(172), exports); -__exportStar(__webpack_require__(174), exports); -__exportStar(__webpack_require__(175), exports); -__exportStar(__webpack_require__(176), exports); -__exportStar(__webpack_require__(177), exports); -__exportStar(__webpack_require__(178), exports); -__exportStar(__webpack_require__(179), exports); -__exportStar(__webpack_require__(180), exports); -__exportStar(__webpack_require__(181), exports); -__exportStar(__webpack_require__(182), exports); -__exportStar(__webpack_require__(183), exports); -__exportStar(__webpack_require__(184), exports); -__exportStar(__webpack_require__(185), exports); -__exportStar(__webpack_require__(186), exports); -__exportStar(__webpack_require__(187), exports); -__exportStar(__webpack_require__(188), exports); -__exportStar(__webpack_require__(189), exports); -__exportStar(__webpack_require__(190), exports); -__exportStar(__webpack_require__(191), exports); -__exportStar(__webpack_require__(192), exports); -__exportStar(__webpack_require__(193), exports); -__exportStar(__webpack_require__(194), exports); -__exportStar(__webpack_require__(195), exports); -__exportStar(__webpack_require__(196), exports); -__exportStar(__webpack_require__(197), exports); -__exportStar(__webpack_require__(199), exports); -__exportStar(__webpack_require__(200), exports); -__exportStar(__webpack_require__(201), exports); -__exportStar(__webpack_require__(202), exports); -__exportStar(__webpack_require__(206), exports); -__exportStar(__webpack_require__(207), exports); -__exportStar(__webpack_require__(224), exports); -__exportStar(__webpack_require__(225), exports); -__exportStar(__webpack_require__(226), exports); -__exportStar(__webpack_require__(228), exports); -__exportStar(__webpack_require__(229), exports); -__exportStar(__webpack_require__(230), exports); -__exportStar(__webpack_require__(231), exports); -__exportStar(__webpack_require__(232), exports); -exports.OutputFormatPropertyName = "OutputFormat"; -exports.CancellationErrorCodePropertyName = "CancellationErrorCode"; -exports.ServicePropertiesPropertyName = "ServiceProperties"; -exports.ForceDictationPropertyName = "ForceDictation"; -exports.AutoDetectSourceLanguagesOpenRangeOptionName = "OpenRange"; - - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CognitiveSubscriptionKeyAuthentication = void 0; -var Exports_1 = __webpack_require__(4); -var HeaderNames_1 = __webpack_require__(55); -var IAuthentication_1 = __webpack_require__(56); -/** - * @class - */ -var CognitiveSubscriptionKeyAuthentication = /** @class */ (function () { - /** - * Creates and initializes an instance of the CognitiveSubscriptionKeyAuthentication class. - * @constructor - * @param {string} subscriptionKey - The subscription key - */ - function CognitiveSubscriptionKeyAuthentication(subscriptionKey) { - var _this = this; - /** - * Fetches the subscription key. - * @member - * @function - * @public - * @param {string} authFetchEventId - The id to fetch. - */ - this.fetch = function (authFetchEventId) { - return Promise.resolve(_this.privAuthInfo); - }; - /** - * Fetches the subscription key. - * @member - * @function - * @public - * @param {string} authFetchEventId - The id to fetch. - */ - this.fetchOnExpiry = function (authFetchEventId) { - return Promise.resolve(_this.privAuthInfo); - }; - if (!subscriptionKey) { - throw new Exports_1.ArgumentNullError("subscriptionKey"); - } - this.privAuthInfo = new IAuthentication_1.AuthInfo(HeaderNames_1.HeaderNames.AuthKey, subscriptionKey); - } - return CognitiveSubscriptionKeyAuthentication; -}()); -exports.CognitiveSubscriptionKeyAuthentication = CognitiveSubscriptionKeyAuthentication; - - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.HeaderNames = void 0; -var HeaderNames = /** @class */ (function () { - function HeaderNames() { - } - HeaderNames.AuthKey = "Ocp-Apim-Subscription-Key"; - HeaderNames.ConnectionId = "X-ConnectionId"; - HeaderNames.ContentType = "Content-Type"; - HeaderNames.CustomCommandsAppId = "X-CommandsAppId"; - HeaderNames.Path = "Path"; - HeaderNames.RequestId = "X-RequestId"; - HeaderNames.RequestStreamId = "X-StreamId"; - HeaderNames.RequestTimestamp = "X-Timestamp"; - return HeaderNames; -}()); -exports.HeaderNames = HeaderNames; - - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AuthInfo = void 0; -var AuthInfo = /** @class */ (function () { - function AuthInfo(headerName, token) { +class AuthInfo { + constructor(headerName, token) { this.privHeaderName = headerName; this.privToken = token; } - Object.defineProperty(AuthInfo.prototype, "headerName", { - get: function () { - return this.privHeaderName; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AuthInfo.prototype, "token", { - get: function () { - return this.privToken; - }, - enumerable: false, - configurable: true - }); - return AuthInfo; -}()); + get headerName() { + return this.privHeaderName; + } + get token() { + return this.privToken; + } +} exports.AuthInfo = AuthInfo; /***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { +/* 61 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CognitiveTokenAuthentication = void 0; -var Exports_1 = __webpack_require__(4); -var IAuthentication_1 = __webpack_require__(56); -var AuthHeader = "Authorization"; -var CognitiveTokenAuthentication = /** @class */ (function () { - function CognitiveTokenAuthentication(fetchCallback, fetchOnExpiryCallback) { - var _this = this; - this.fetch = function (authFetchEventId) { - return _this.privFetchCallback(authFetchEventId).then(function (token) { return new IAuthentication_1.AuthInfo(AuthHeader, CognitiveTokenAuthentication.privTokenPrefix + token); }); - }; - this.fetchOnExpiry = function (authFetchEventId) { - return _this.privFetchOnExpiryCallback(authFetchEventId).then(function (token) { return new IAuthentication_1.AuthInfo(AuthHeader, CognitiveTokenAuthentication.privTokenPrefix + token); }); - }; +const Exports_js_1 = __webpack_require__(4); +const IAuthentication_js_1 = __webpack_require__(60); +const HeaderNames_js_1 = __webpack_require__(59); +class CognitiveTokenAuthentication { + constructor(fetchCallback, fetchOnExpiryCallback) { if (!fetchCallback) { - throw new Exports_1.ArgumentNullError("fetchCallback"); + throw new Exports_js_1.ArgumentNullError("fetchCallback"); } if (!fetchOnExpiryCallback) { - throw new Exports_1.ArgumentNullError("fetchOnExpiryCallback"); + throw new Exports_js_1.ArgumentNullError("fetchOnExpiryCallback"); } this.privFetchCallback = fetchCallback; this.privFetchOnExpiryCallback = fetchOnExpiryCallback; } - CognitiveTokenAuthentication.privTokenPrefix = "bearer "; - return CognitiveTokenAuthentication; -}()); + fetch(authFetchEventId) { + return this.privFetchCallback(authFetchEventId).then((token) => new IAuthentication_js_1.AuthInfo(HeaderNames_js_1.HeaderNames.Authorization, token === undefined ? undefined : CognitiveTokenAuthentication.privTokenPrefix + token)); + } + fetchOnExpiry(authFetchEventId) { + return this.privFetchOnExpiryCallback(authFetchEventId).then((token) => new IAuthentication_js_1.AuthInfo(HeaderNames_js_1.HeaderNames.Authorization, token === undefined ? undefined : CognitiveTokenAuthentication.privTokenPrefix + token)); + } +} exports.CognitiveTokenAuthentication = CognitiveTokenAuthentication; +CognitiveTokenAuthentication.privTokenPrefix = "Bearer "; /***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); - - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); - - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { +/* 62 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IntentConnectionFactory = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -var Exports_3 = __webpack_require__(53); -var HeaderNames_1 = __webpack_require__(55); -var IntentConnectionFactory = /** @class */ (function (_super) { - __extends(IntentConnectionFactory, _super); - function IntentConnectionFactory() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.create = function (config, authInfo, connectionId) { - var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint); - if (!endpoint) { - var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_IntentRegion); - var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region); - var host = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".sr.speech" + hostSuffix); - endpoint = host + "/speech/recognition/interactive/cognitiveservices/v1"; - } - var queryParams = { - format: "simple", - language: config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage), - }; - _this.setCommonUrlParams(config, queryParams, endpoint); - var headers = {}; - if (authInfo.token !== undefined && authInfo.token !== "") { - headers[authInfo.headerName] = authInfo.token; - } - headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId; - config.parameters.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Url, endpoint); - var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; - return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_3.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); - }; - return _this; - } - IntentConnectionFactory.prototype.getSpeechRegionFromIntentRegion = function (intentRegion) { - switch (intentRegion) { - case "West US": - case "US West": - case "westus": - return "uswest"; - case "West US 2": - case "US West 2": - case "westus2": - return "uswest2"; - case "South Central US": - case "US South Central": - case "southcentralus": - return "ussouthcentral"; - case "West Central US": - case "US West Central": - case "westcentralus": - return "uswestcentral"; - case "East US": - case "US East": - case "eastus": - return "useast"; - case "East US 2": - case "US East 2": - case "eastus2": - return "useast2"; - case "West Europe": - case "Europe West": - case "westeurope": - return "europewest"; - case "North Europe": - case "Europe North": - case "northeurope": - return "europenorth"; - case "Brazil South": - case "South Brazil": - case "southbrazil": - return "brazilsouth"; - case "Australia East": - case "East Australia": - case "eastaustralia": - return "australiaeast"; - case "Southeast Asia": - case "Asia Southeast": - case "southeastasia": - return "asiasoutheast"; - case "East Asia": - case "Asia East": - case "eastasia": - return "asiaeast"; - default: - return intentRegion; - } - }; - return IntentConnectionFactory; -}(ConnectionFactoryBase_1.ConnectionFactoryBase)); -exports.IntentConnectionFactory = IntentConnectionFactory; +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { +/* 63 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -var AudioConfig_1 = __webpack_require__(62); -Object.defineProperty(exports, "AudioConfig", { enumerable: true, get: function () { return AudioConfig_1.AudioConfig; } }); -var AudioStreamFormat_1 = __webpack_require__(72); -Object.defineProperty(exports, "AudioStreamFormat", { enumerable: true, get: function () { return AudioStreamFormat_1.AudioStreamFormat; } }); -Object.defineProperty(exports, "AudioFormatTag", { enumerable: true, get: function () { return AudioStreamFormat_1.AudioFormatTag; } }); -var AudioInputStream_1 = __webpack_require__(66); -Object.defineProperty(exports, "AudioInputStream", { enumerable: true, get: function () { return AudioInputStream_1.AudioInputStream; } }); -Object.defineProperty(exports, "PullAudioInputStream", { enumerable: true, get: function () { return AudioInputStream_1.PullAudioInputStream; } }); -Object.defineProperty(exports, "PushAudioInputStream", { enumerable: true, get: function () { return AudioInputStream_1.PushAudioInputStream; } }); -var AudioOutputStream_1 = __webpack_require__(73); -Object.defineProperty(exports, "AudioOutputStream", { enumerable: true, get: function () { return AudioOutputStream_1.AudioOutputStream; } }); -Object.defineProperty(exports, "PullAudioOutputStream", { enumerable: true, get: function () { return AudioOutputStream_1.PullAudioOutputStream; } }); -Object.defineProperty(exports, "PushAudioOutputStream", { enumerable: true, get: function () { return AudioOutputStream_1.PushAudioOutputStream; } }); -var CancellationReason_1 = __webpack_require__(76); -Object.defineProperty(exports, "CancellationReason", { enumerable: true, get: function () { return CancellationReason_1.CancellationReason; } }); -var PullAudioInputStreamCallback_1 = __webpack_require__(77); -Object.defineProperty(exports, "PullAudioInputStreamCallback", { enumerable: true, get: function () { return PullAudioInputStreamCallback_1.PullAudioInputStreamCallback; } }); -var PushAudioOutputStreamCallback_1 = __webpack_require__(78); -Object.defineProperty(exports, "PushAudioOutputStreamCallback", { enumerable: true, get: function () { return PushAudioOutputStreamCallback_1.PushAudioOutputStreamCallback; } }); -var KeywordRecognitionModel_1 = __webpack_require__(79); -Object.defineProperty(exports, "KeywordRecognitionModel", { enumerable: true, get: function () { return KeywordRecognitionModel_1.KeywordRecognitionModel; } }); -var SessionEventArgs_1 = __webpack_require__(80); -Object.defineProperty(exports, "SessionEventArgs", { enumerable: true, get: function () { return SessionEventArgs_1.SessionEventArgs; } }); -var RecognitionEventArgs_1 = __webpack_require__(81); -Object.defineProperty(exports, "RecognitionEventArgs", { enumerable: true, get: function () { return RecognitionEventArgs_1.RecognitionEventArgs; } }); -var OutputFormat_1 = __webpack_require__(82); -Object.defineProperty(exports, "OutputFormat", { enumerable: true, get: function () { return OutputFormat_1.OutputFormat; } }); -var IntentRecognitionEventArgs_1 = __webpack_require__(83); -Object.defineProperty(exports, "IntentRecognitionEventArgs", { enumerable: true, get: function () { return IntentRecognitionEventArgs_1.IntentRecognitionEventArgs; } }); -var RecognitionResult_1 = __webpack_require__(84); -Object.defineProperty(exports, "RecognitionResult", { enumerable: true, get: function () { return RecognitionResult_1.RecognitionResult; } }); -var SpeechRecognitionResult_1 = __webpack_require__(85); -Object.defineProperty(exports, "SpeechRecognitionResult", { enumerable: true, get: function () { return SpeechRecognitionResult_1.SpeechRecognitionResult; } }); -var IntentRecognitionResult_1 = __webpack_require__(86); -Object.defineProperty(exports, "IntentRecognitionResult", { enumerable: true, get: function () { return IntentRecognitionResult_1.IntentRecognitionResult; } }); -var LanguageUnderstandingModel_1 = __webpack_require__(87); -Object.defineProperty(exports, "LanguageUnderstandingModel", { enumerable: true, get: function () { return LanguageUnderstandingModel_1.LanguageUnderstandingModel; } }); -var SpeechRecognitionEventArgs_1 = __webpack_require__(88); -Object.defineProperty(exports, "SpeechRecognitionEventArgs", { enumerable: true, get: function () { return SpeechRecognitionEventArgs_1.SpeechRecognitionEventArgs; } }); -Object.defineProperty(exports, "ConversationTranscriptionEventArgs", { enumerable: true, get: function () { return SpeechRecognitionEventArgs_1.ConversationTranscriptionEventArgs; } }); -var SpeechRecognitionCanceledEventArgs_1 = __webpack_require__(89); -Object.defineProperty(exports, "SpeechRecognitionCanceledEventArgs", { enumerable: true, get: function () { return SpeechRecognitionCanceledEventArgs_1.SpeechRecognitionCanceledEventArgs; } }); -var TranslationRecognitionEventArgs_1 = __webpack_require__(91); -Object.defineProperty(exports, "TranslationRecognitionEventArgs", { enumerable: true, get: function () { return TranslationRecognitionEventArgs_1.TranslationRecognitionEventArgs; } }); -var TranslationSynthesisEventArgs_1 = __webpack_require__(92); -Object.defineProperty(exports, "TranslationSynthesisEventArgs", { enumerable: true, get: function () { return TranslationSynthesisEventArgs_1.TranslationSynthesisEventArgs; } }); -var TranslationRecognitionResult_1 = __webpack_require__(93); -Object.defineProperty(exports, "TranslationRecognitionResult", { enumerable: true, get: function () { return TranslationRecognitionResult_1.TranslationRecognitionResult; } }); -var TranslationSynthesisResult_1 = __webpack_require__(94); -Object.defineProperty(exports, "TranslationSynthesisResult", { enumerable: true, get: function () { return TranslationSynthesisResult_1.TranslationSynthesisResult; } }); -var ResultReason_1 = __webpack_require__(95); -Object.defineProperty(exports, "ResultReason", { enumerable: true, get: function () { return ResultReason_1.ResultReason; } }); -var SpeechConfig_1 = __webpack_require__(96); -Object.defineProperty(exports, "SpeechConfig", { enumerable: true, get: function () { return SpeechConfig_1.SpeechConfig; } }); -Object.defineProperty(exports, "SpeechConfigImpl", { enumerable: true, get: function () { return SpeechConfig_1.SpeechConfigImpl; } }); -var SpeechTranslationConfig_1 = __webpack_require__(97); -Object.defineProperty(exports, "SpeechTranslationConfig", { enumerable: true, get: function () { return SpeechTranslationConfig_1.SpeechTranslationConfig; } }); -Object.defineProperty(exports, "SpeechTranslationConfigImpl", { enumerable: true, get: function () { return SpeechTranslationConfig_1.SpeechTranslationConfigImpl; } }); -var PropertyCollection_1 = __webpack_require__(98); -Object.defineProperty(exports, "PropertyCollection", { enumerable: true, get: function () { return PropertyCollection_1.PropertyCollection; } }); -var PropertyId_1 = __webpack_require__(99); -Object.defineProperty(exports, "PropertyId", { enumerable: true, get: function () { return PropertyId_1.PropertyId; } }); -var Recognizer_1 = __webpack_require__(100); -Object.defineProperty(exports, "Recognizer", { enumerable: true, get: function () { return Recognizer_1.Recognizer; } }); -var SpeechRecognizer_1 = __webpack_require__(101); -Object.defineProperty(exports, "SpeechRecognizer", { enumerable: true, get: function () { return SpeechRecognizer_1.SpeechRecognizer; } }); -var IntentRecognizer_1 = __webpack_require__(102); -Object.defineProperty(exports, "IntentRecognizer", { enumerable: true, get: function () { return IntentRecognizer_1.IntentRecognizer; } }); -var VoiceProfileType_1 = __webpack_require__(103); -Object.defineProperty(exports, "VoiceProfileType", { enumerable: true, get: function () { return VoiceProfileType_1.VoiceProfileType; } }); -var TranslationRecognizer_1 = __webpack_require__(104); -Object.defineProperty(exports, "TranslationRecognizer", { enumerable: true, get: function () { return TranslationRecognizer_1.TranslationRecognizer; } }); -var Translations_1 = __webpack_require__(107); -Object.defineProperty(exports, "Translations", { enumerable: true, get: function () { return Translations_1.Translations; } }); -var NoMatchReason_1 = __webpack_require__(108); -Object.defineProperty(exports, "NoMatchReason", { enumerable: true, get: function () { return NoMatchReason_1.NoMatchReason; } }); -var NoMatchDetails_1 = __webpack_require__(109); -Object.defineProperty(exports, "NoMatchDetails", { enumerable: true, get: function () { return NoMatchDetails_1.NoMatchDetails; } }); -var TranslationRecognitionCanceledEventArgs_1 = __webpack_require__(110); -Object.defineProperty(exports, "TranslationRecognitionCanceledEventArgs", { enumerable: true, get: function () { return TranslationRecognitionCanceledEventArgs_1.TranslationRecognitionCanceledEventArgs; } }); -var IntentRecognitionCanceledEventArgs_1 = __webpack_require__(111); -Object.defineProperty(exports, "IntentRecognitionCanceledEventArgs", { enumerable: true, get: function () { return IntentRecognitionCanceledEventArgs_1.IntentRecognitionCanceledEventArgs; } }); -var CancellationDetailsBase_1 = __webpack_require__(112); -Object.defineProperty(exports, "CancellationDetailsBase", { enumerable: true, get: function () { return CancellationDetailsBase_1.CancellationDetailsBase; } }); -var CancellationDetails_1 = __webpack_require__(113); -Object.defineProperty(exports, "CancellationDetails", { enumerable: true, get: function () { return CancellationDetails_1.CancellationDetails; } }); -var CancellationErrorCodes_1 = __webpack_require__(114); -Object.defineProperty(exports, "CancellationErrorCode", { enumerable: true, get: function () { return CancellationErrorCodes_1.CancellationErrorCode; } }); -var ConnectionEventArgs_1 = __webpack_require__(115); -Object.defineProperty(exports, "ConnectionEventArgs", { enumerable: true, get: function () { return ConnectionEventArgs_1.ConnectionEventArgs; } }); -var ServiceEventArgs_1 = __webpack_require__(116); -Object.defineProperty(exports, "ServiceEventArgs", { enumerable: true, get: function () { return ServiceEventArgs_1.ServiceEventArgs; } }); -var Connection_1 = __webpack_require__(105); -Object.defineProperty(exports, "Connection", { enumerable: true, get: function () { return Connection_1.Connection; } }); -var PhraseListGrammar_1 = __webpack_require__(117); -Object.defineProperty(exports, "PhraseListGrammar", { enumerable: true, get: function () { return PhraseListGrammar_1.PhraseListGrammar; } }); -var DialogServiceConfig_1 = __webpack_require__(118); -Object.defineProperty(exports, "DialogServiceConfig", { enumerable: true, get: function () { return DialogServiceConfig_1.DialogServiceConfig; } }); -var BotFrameworkConfig_1 = __webpack_require__(119); -Object.defineProperty(exports, "BotFrameworkConfig", { enumerable: true, get: function () { return BotFrameworkConfig_1.BotFrameworkConfig; } }); -var CustomCommandsConfig_1 = __webpack_require__(120); -Object.defineProperty(exports, "CustomCommandsConfig", { enumerable: true, get: function () { return CustomCommandsConfig_1.CustomCommandsConfig; } }); -var DialogServiceConnector_1 = __webpack_require__(121); -Object.defineProperty(exports, "DialogServiceConnector", { enumerable: true, get: function () { return DialogServiceConnector_1.DialogServiceConnector; } }); -var ActivityReceivedEventArgs_1 = __webpack_require__(125); -Object.defineProperty(exports, "ActivityReceivedEventArgs", { enumerable: true, get: function () { return ActivityReceivedEventArgs_1.ActivityReceivedEventArgs; } }); -var TurnStatusReceivedEventArgs_1 = __webpack_require__(126); -Object.defineProperty(exports, "TurnStatusReceivedEventArgs", { enumerable: true, get: function () { return TurnStatusReceivedEventArgs_1.TurnStatusReceivedEventArgs; } }); -var ServicePropertyChannel_1 = __webpack_require__(128); -Object.defineProperty(exports, "ServicePropertyChannel", { enumerable: true, get: function () { return ServicePropertyChannel_1.ServicePropertyChannel; } }); -var ProfanityOption_1 = __webpack_require__(129); -Object.defineProperty(exports, "ProfanityOption", { enumerable: true, get: function () { return ProfanityOption_1.ProfanityOption; } }); -var BaseAudioPlayer_1 = __webpack_require__(130); -Object.defineProperty(exports, "BaseAudioPlayer", { enumerable: true, get: function () { return BaseAudioPlayer_1.BaseAudioPlayer; } }); -var ConnectionMessageEventArgs_1 = __webpack_require__(131); -Object.defineProperty(exports, "ConnectionMessageEventArgs", { enumerable: true, get: function () { return ConnectionMessageEventArgs_1.ConnectionMessageEventArgs; } }); -var ConnectionMessage_1 = __webpack_require__(106); -Object.defineProperty(exports, "ConnectionMessage", { enumerable: true, get: function () { return ConnectionMessage_1.ConnectionMessage; } }); -var VoiceProfile_1 = __webpack_require__(132); -Object.defineProperty(exports, "VoiceProfile", { enumerable: true, get: function () { return VoiceProfile_1.VoiceProfile; } }); -var VoiceProfileEnrollmentResult_1 = __webpack_require__(133); -Object.defineProperty(exports, "VoiceProfileEnrollmentResult", { enumerable: true, get: function () { return VoiceProfileEnrollmentResult_1.VoiceProfileEnrollmentResult; } }); -Object.defineProperty(exports, "VoiceProfileEnrollmentCancellationDetails", { enumerable: true, get: function () { return VoiceProfileEnrollmentResult_1.VoiceProfileEnrollmentCancellationDetails; } }); -var VoiceProfileResult_1 = __webpack_require__(134); -Object.defineProperty(exports, "VoiceProfileResult", { enumerable: true, get: function () { return VoiceProfileResult_1.VoiceProfileResult; } }); -Object.defineProperty(exports, "VoiceProfileCancellationDetails", { enumerable: true, get: function () { return VoiceProfileResult_1.VoiceProfileCancellationDetails; } }); -var VoiceProfilePhraseResult_1 = __webpack_require__(135); -Object.defineProperty(exports, "VoiceProfilePhraseResult", { enumerable: true, get: function () { return VoiceProfilePhraseResult_1.VoiceProfilePhraseResult; } }); -var VoiceProfileClient_1 = __webpack_require__(136); -Object.defineProperty(exports, "VoiceProfileClient", { enumerable: true, get: function () { return VoiceProfileClient_1.VoiceProfileClient; } }); -var SpeakerRecognizer_1 = __webpack_require__(137); -Object.defineProperty(exports, "SpeakerRecognizer", { enumerable: true, get: function () { return SpeakerRecognizer_1.SpeakerRecognizer; } }); -var SpeakerIdentificationModel_1 = __webpack_require__(138); -Object.defineProperty(exports, "SpeakerIdentificationModel", { enumerable: true, get: function () { return SpeakerIdentificationModel_1.SpeakerIdentificationModel; } }); -var SpeakerVerificationModel_1 = __webpack_require__(139); -Object.defineProperty(exports, "SpeakerVerificationModel", { enumerable: true, get: function () { return SpeakerVerificationModel_1.SpeakerVerificationModel; } }); -var AutoDetectSourceLanguageConfig_1 = __webpack_require__(140); -Object.defineProperty(exports, "AutoDetectSourceLanguageConfig", { enumerable: true, get: function () { return AutoDetectSourceLanguageConfig_1.AutoDetectSourceLanguageConfig; } }); -var AutoDetectSourceLanguageResult_1 = __webpack_require__(141); -Object.defineProperty(exports, "AutoDetectSourceLanguageResult", { enumerable: true, get: function () { return AutoDetectSourceLanguageResult_1.AutoDetectSourceLanguageResult; } }); -var SourceLanguageConfig_1 = __webpack_require__(142); -Object.defineProperty(exports, "SourceLanguageConfig", { enumerable: true, get: function () { return SourceLanguageConfig_1.SourceLanguageConfig; } }); -var SpeakerRecognitionResult_1 = __webpack_require__(143); -Object.defineProperty(exports, "SpeakerRecognitionResult", { enumerable: true, get: function () { return SpeakerRecognitionResult_1.SpeakerRecognitionResult; } }); -Object.defineProperty(exports, "SpeakerRecognitionResultType", { enumerable: true, get: function () { return SpeakerRecognitionResult_1.SpeakerRecognitionResultType; } }); -Object.defineProperty(exports, "SpeakerRecognitionCancellationDetails", { enumerable: true, get: function () { return SpeakerRecognitionResult_1.SpeakerRecognitionCancellationDetails; } }); -var Exports_1 = __webpack_require__(144); -Object.defineProperty(exports, "Conversation", { enumerable: true, get: function () { return Exports_1.Conversation; } }); -Object.defineProperty(exports, "ConversationExpirationEventArgs", { enumerable: true, get: function () { return Exports_1.ConversationExpirationEventArgs; } }); -Object.defineProperty(exports, "ConversationParticipantsChangedEventArgs", { enumerable: true, get: function () { return Exports_1.ConversationParticipantsChangedEventArgs; } }); -Object.defineProperty(exports, "ConversationTranslationCanceledEventArgs", { enumerable: true, get: function () { return Exports_1.ConversationTranslationCanceledEventArgs; } }); -Object.defineProperty(exports, "ConversationTranslationEventArgs", { enumerable: true, get: function () { return Exports_1.ConversationTranslationEventArgs; } }); -Object.defineProperty(exports, "ConversationTranslationResult", { enumerable: true, get: function () { return Exports_1.ConversationTranslationResult; } }); -Object.defineProperty(exports, "ConversationTranslator", { enumerable: true, get: function () { return Exports_1.ConversationTranslator; } }); -Object.defineProperty(exports, "ConversationTranscriber", { enumerable: true, get: function () { return Exports_1.ConversationTranscriber; } }); -Object.defineProperty(exports, "Participant", { enumerable: true, get: function () { return Exports_1.Participant; } }); -Object.defineProperty(exports, "ParticipantChangedReason", { enumerable: true, get: function () { return Exports_1.ParticipantChangedReason; } }); -Object.defineProperty(exports, "User", { enumerable: true, get: function () { return Exports_1.User; } }); -var SpeechSynthesisOutputFormat_1 = __webpack_require__(75); -Object.defineProperty(exports, "SpeechSynthesisOutputFormat", { enumerable: true, get: function () { return SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat; } }); -var SpeechSynthesizer_1 = __webpack_require__(156); -Object.defineProperty(exports, "SpeechSynthesizer", { enumerable: true, get: function () { return SpeechSynthesizer_1.SpeechSynthesizer; } }); -var SynthesisResult_1 = __webpack_require__(157); -Object.defineProperty(exports, "SynthesisResult", { enumerable: true, get: function () { return SynthesisResult_1.SynthesisResult; } }); -var SpeechSynthesisResult_1 = __webpack_require__(158); -Object.defineProperty(exports, "SpeechSynthesisResult", { enumerable: true, get: function () { return SpeechSynthesisResult_1.SpeechSynthesisResult; } }); -var SpeechSynthesisEventArgs_1 = __webpack_require__(159); -Object.defineProperty(exports, "SpeechSynthesisEventArgs", { enumerable: true, get: function () { return SpeechSynthesisEventArgs_1.SpeechSynthesisEventArgs; } }); -var SpeechSynthesisWordBoundaryEventArgs_1 = __webpack_require__(160); -Object.defineProperty(exports, "SpeechSynthesisWordBoundaryEventArgs", { enumerable: true, get: function () { return SpeechSynthesisWordBoundaryEventArgs_1.SpeechSynthesisWordBoundaryEventArgs; } }); -var SpeechSynthesisBookmarkEventArgs_1 = __webpack_require__(161); -Object.defineProperty(exports, "SpeechSynthesisBookmarkEventArgs", { enumerable: true, get: function () { return SpeechSynthesisBookmarkEventArgs_1.SpeechSynthesisBookmarkEventArgs; } }); -var SpeechSynthesisVisemeEventArgs_1 = __webpack_require__(162); -Object.defineProperty(exports, "SpeechSynthesisVisemeEventArgs", { enumerable: true, get: function () { return SpeechSynthesisVisemeEventArgs_1.SpeechSynthesisVisemeEventArgs; } }); -var SynthesisVoicesResult_1 = __webpack_require__(163); -Object.defineProperty(exports, "SynthesisVoicesResult", { enumerable: true, get: function () { return SynthesisVoicesResult_1.SynthesisVoicesResult; } }); -var VoiceInfo_1 = __webpack_require__(164); -Object.defineProperty(exports, "VoiceInfo", { enumerable: true, get: function () { return VoiceInfo_1.VoiceInfo; } }); -var SpeakerAudioDestination_1 = __webpack_require__(165); -Object.defineProperty(exports, "SpeakerAudioDestination", { enumerable: true, get: function () { return SpeakerAudioDestination_1.SpeakerAudioDestination; } }); -var ConversationTranscriptionCanceledEventArgs_1 = __webpack_require__(166); -Object.defineProperty(exports, "ConversationTranscriptionCanceledEventArgs", { enumerable: true, get: function () { return ConversationTranscriptionCanceledEventArgs_1.ConversationTranscriptionCanceledEventArgs; } }); -var PronunciationAssessmentGradingSystem_1 = __webpack_require__(167); -Object.defineProperty(exports, "PronunciationAssessmentGradingSystem", { enumerable: true, get: function () { return PronunciationAssessmentGradingSystem_1.PronunciationAssessmentGradingSystem; } }); -var PronunciationAssessmentGranularity_1 = __webpack_require__(168); -Object.defineProperty(exports, "PronunciationAssessmentGranularity", { enumerable: true, get: function () { return PronunciationAssessmentGranularity_1.PronunciationAssessmentGranularity; } }); -var PronunciationAssessmentConfig_1 = __webpack_require__(169); -Object.defineProperty(exports, "PronunciationAssessmentConfig", { enumerable: true, get: function () { return PronunciationAssessmentConfig_1.PronunciationAssessmentConfig; } }); -var PronunciationAssessmentResult_1 = __webpack_require__(170); -Object.defineProperty(exports, "PronunciationAssessmentResult", { enumerable: true, get: function () { return PronunciationAssessmentResult_1.PronunciationAssessmentResult; } }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { +/* 64 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AudioOutputConfigImpl = exports.AudioConfigImpl = exports.AudioConfig = void 0; -var Exports_1 = __webpack_require__(2); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); -var AudioFileWriter_1 = __webpack_require__(64); -var AudioInputStream_1 = __webpack_require__(66); -var AudioOutputStream_1 = __webpack_require__(73); -/** - * Represents audio input configuration used for specifying what type of input to use (microphone, file, stream). - * @class AudioConfig - * Updated in version 1.11.0 - */ -var AudioConfig = /** @class */ (function () { - function AudioConfig() { +/* eslint-disable max-classes-per-file */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RecognitionEndedEvent = exports.RecognitionCompletionStatus = exports.RecognitionStartedEvent = exports.ConnectingToServiceEvent = exports.ListeningStartedEvent = exports.RecognitionTriggeredEvent = exports.SpeechRecognitionEvent = void 0; +const Exports_js_1 = __webpack_require__(4); +class SpeechRecognitionEvent extends Exports_js_1.PlatformEvent { + constructor(eventName, requestId, sessionId, eventType = Exports_js_1.EventType.Info) { + super(eventName, eventType); + this.privRequestId = requestId; + this.privSessionId = sessionId; } - /** - * Creates an AudioConfig object representing the default microphone on the system. - * @member AudioConfig.fromDefaultMicrophoneInput - * @function - * @public - * @returns {AudioConfig} The audio input configuration being created. - */ - AudioConfig.fromDefaultMicrophoneInput = function () { - var pcmRecorder = new Exports_1.PcmRecorder(true); - return new AudioConfigImpl(new Exports_1.MicAudioSource(pcmRecorder)); - }; - /** - * Creates an AudioConfig object representing a microphone with the specified device ID. - * @member AudioConfig.fromMicrophoneInput - * @function - * @public - * @param {string | undefined} deviceId - Specifies the device ID of the microphone to be used. - * Default microphone is used the value is omitted. - * @returns {AudioConfig} The audio input configuration being created. - */ - AudioConfig.fromMicrophoneInput = function (deviceId) { - var pcmRecorder = new Exports_1.PcmRecorder(true); - return new AudioConfigImpl(new Exports_1.MicAudioSource(pcmRecorder, deviceId)); - }; - /** - * Creates an AudioConfig object representing the specified file. - * @member AudioConfig.fromWavFileInput - * @function - * @public - * @param {File} fileName - Specifies the audio input file. Currently, only WAV / PCM is supported. - * @returns {AudioConfig} The audio input configuration being created. - */ - AudioConfig.fromWavFileInput = function (file, name) { - if (name === void 0) { name = "unnamedBuffer.wav"; } - return new AudioConfigImpl(new Exports_1.FileAudioSource(file, name)); - }; - /** - * Creates an AudioConfig object representing the specified stream. - * @member AudioConfig.fromStreamInput - * @function - * @public - * @param {AudioInputStream | PullAudioInputStreamCallback | MediaStream} audioStream - Specifies the custom audio input - * stream. Currently, only WAV / PCM is supported. - * @returns {AudioConfig} The audio input configuration being created. - */ - AudioConfig.fromStreamInput = function (audioStream) { - if (audioStream instanceof Exports_2.PullAudioInputStreamCallback) { - return new AudioConfigImpl(new AudioInputStream_1.PullAudioInputStreamImpl(audioStream)); + get requestId() { + return this.privRequestId; + } + get sessionId() { + return this.privSessionId; + } +} +exports.SpeechRecognitionEvent = SpeechRecognitionEvent; +class RecognitionTriggeredEvent extends SpeechRecognitionEvent { + constructor(requestId, sessionId, audioSourceId, audioNodeId) { + super("RecognitionTriggeredEvent", requestId, sessionId); + this.privAudioSourceId = audioSourceId; + this.privAudioNodeId = audioNodeId; + } + get audioSourceId() { + return this.privAudioSourceId; + } + get audioNodeId() { + return this.privAudioNodeId; + } +} +exports.RecognitionTriggeredEvent = RecognitionTriggeredEvent; +class ListeningStartedEvent extends SpeechRecognitionEvent { + constructor(requestId, sessionId, audioSourceId, audioNodeId) { + super("ListeningStartedEvent", requestId, sessionId); + this.privAudioSourceId = audioSourceId; + this.privAudioNodeId = audioNodeId; + } + get audioSourceId() { + return this.privAudioSourceId; + } + get audioNodeId() { + return this.privAudioNodeId; + } +} +exports.ListeningStartedEvent = ListeningStartedEvent; +class ConnectingToServiceEvent extends SpeechRecognitionEvent { + constructor(requestId, authFetchEventid, sessionId) { + super("ConnectingToServiceEvent", requestId, sessionId); + this.privAuthFetchEventid = authFetchEventid; + } + get authFetchEventid() { + return this.privAuthFetchEventid; + } +} +exports.ConnectingToServiceEvent = ConnectingToServiceEvent; +class RecognitionStartedEvent extends SpeechRecognitionEvent { + constructor(requestId, audioSourceId, audioNodeId, authFetchEventId, sessionId) { + super("RecognitionStartedEvent", requestId, sessionId); + this.privAudioSourceId = audioSourceId; + this.privAudioNodeId = audioNodeId; + this.privAuthFetchEventId = authFetchEventId; + } + get audioSourceId() { + return this.privAudioSourceId; + } + get audioNodeId() { + return this.privAudioNodeId; + } + get authFetchEventId() { + return this.privAuthFetchEventId; + } +} +exports.RecognitionStartedEvent = RecognitionStartedEvent; +var RecognitionCompletionStatus; +(function (RecognitionCompletionStatus) { + RecognitionCompletionStatus[RecognitionCompletionStatus["Success"] = 0] = "Success"; + RecognitionCompletionStatus[RecognitionCompletionStatus["AudioSourceError"] = 1] = "AudioSourceError"; + RecognitionCompletionStatus[RecognitionCompletionStatus["AudioSourceTimeout"] = 2] = "AudioSourceTimeout"; + RecognitionCompletionStatus[RecognitionCompletionStatus["AuthTokenFetchError"] = 3] = "AuthTokenFetchError"; + RecognitionCompletionStatus[RecognitionCompletionStatus["AuthTokenFetchTimeout"] = 4] = "AuthTokenFetchTimeout"; + RecognitionCompletionStatus[RecognitionCompletionStatus["UnAuthorized"] = 5] = "UnAuthorized"; + RecognitionCompletionStatus[RecognitionCompletionStatus["ConnectTimeout"] = 6] = "ConnectTimeout"; + RecognitionCompletionStatus[RecognitionCompletionStatus["ConnectError"] = 7] = "ConnectError"; + RecognitionCompletionStatus[RecognitionCompletionStatus["ClientRecognitionActivityTimeout"] = 8] = "ClientRecognitionActivityTimeout"; + RecognitionCompletionStatus[RecognitionCompletionStatus["UnknownError"] = 9] = "UnknownError"; +})(RecognitionCompletionStatus = exports.RecognitionCompletionStatus || (exports.RecognitionCompletionStatus = {})); +class RecognitionEndedEvent extends SpeechRecognitionEvent { + constructor(requestId, audioSourceId, audioNodeId, authFetchEventId, sessionId, serviceTag, status, error) { + super("RecognitionEndedEvent", requestId, sessionId, status === RecognitionCompletionStatus.Success ? Exports_js_1.EventType.Info : Exports_js_1.EventType.Error); + this.privAudioSourceId = audioSourceId; + this.privAudioNodeId = audioNodeId; + this.privAuthFetchEventId = authFetchEventId; + this.privStatus = status; + this.privError = error; + this.privServiceTag = serviceTag; + } + get audioSourceId() { + return this.privAudioSourceId; + } + get audioNodeId() { + return this.privAudioNodeId; + } + get authFetchEventId() { + return this.privAuthFetchEventId; + } + get serviceTag() { + return this.privServiceTag; + } + get status() { + return this.privStatus; + } + get error() { + return this.privError; + } +} +exports.RecognitionEndedEvent = RecognitionEndedEvent; + + + +/***/ }), +/* 65 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServiceRecognizerBase = void 0; +const Exports_js_1 = __webpack_require__(66); +const Exports_js_2 = __webpack_require__(4); +const Exports_js_3 = __webpack_require__(85); +const Exports_js_4 = __webpack_require__(2); +const SpeechConnectionMessage_Internal_js_1 = __webpack_require__(188); +const Segmentation_js_1 = __webpack_require__(189); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +const OnSuccess_js_1 = __webpack_require__(190); +const InterimResults_js_1 = __webpack_require__(191); +const LanguageIdContext_js_1 = __webpack_require__(192); +const OnSuccess_js_2 = __webpack_require__(193); +const OnUnknown_js_1 = __webpack_require__(194); +const InterimResults_js_2 = __webpack_require__(195); +const PhraseResults_js_1 = __webpack_require__(196); +const OnSuccess_js_3 = __webpack_require__(197); +const InteractiveEnrichmentOptions_js_1 = __webpack_require__(198); +const ConversationEnrichmentOptions_js_1 = __webpack_require__(199); +const DictationEnrichmentOptions_js_1 = __webpack_require__(200); +const DisfluencyMode_js_1 = __webpack_require__(201); +class ServiceRecognizerBase { + constructor(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) { + // A promise for a configured connection. + // Do not consume directly, call fetchConnection instead. + this.privConnectionConfigurationPromise = undefined; + // A promise for a connection, but one that has not had the speech context sent yet. + // Do not consume directly, call fetchConnection instead. + this.privConnectionPromise = undefined; + this.privSetTimeout = setTimeout; + this.privIsLiveAudio = false; + this.privAverageBytesPerMs = 0; + this.privEnableReliableReconnect = false; + this.privEnableSpeakerId = false; + this.privExpectContentAssessmentResponse = false; + this.recognizeOverride = undefined; + this.disconnectOverride = undefined; + this.receiveMessageOverride = undefined; + this.sendPrePayloadJSONOverride = undefined; + this.postConnectImplOverride = undefined; + this.configConnectionOverride = undefined; + this.handleSpeechPhraseMessage = undefined; + this.handleSpeechHypothesisMessage = undefined; + if (!authentication) { + throw new Exports_js_2.ArgumentNullError("authentication"); } - if (audioStream instanceof Exports_2.AudioInputStream) { - return new AudioConfigImpl(audioStream); + if (!connectionFactory) { + throw new Exports_js_2.ArgumentNullError("connectionFactory"); } - if (typeof MediaStream !== "undefined" && audioStream instanceof MediaStream) { - var pcmRecorder = new Exports_1.PcmRecorder(false); - return new AudioConfigImpl(new Exports_1.MicAudioSource(pcmRecorder, null, null, audioStream)); + if (!audioSource) { + throw new Exports_js_2.ArgumentNullError("audioSource"); } - throw new Error("Not Supported Type"); - }; - /** - * Creates an AudioConfig object representing the default speaker. - * @member AudioConfig.fromDefaultSpeakerOutput - * @function - * @public - * @returns {AudioConfig} The audio output configuration being created. - * Added in version 1.11.0 - */ - AudioConfig.fromDefaultSpeakerOutput = function () { - return new AudioOutputConfigImpl(new Exports_2.SpeakerAudioDestination()); - }; - /** - * Creates an AudioConfig object representing the custom IPlayer object. - * You can use the IPlayer object to control pause, resume, etc. - * @member AudioConfig.fromSpeakerOutput - * @function - * @public - * @param {IPlayer} player - the IPlayer object for playback. - * @returns {AudioConfig} The audio output configuration being created. - * Added in version 1.12.0 - */ - AudioConfig.fromSpeakerOutput = function (player) { - if (player === undefined) { - return AudioConfig.fromDefaultSpeakerOutput(); + if (!recognizerConfig) { + throw new Exports_js_2.ArgumentNullError("recognizerConfig"); } - if (player instanceof Exports_2.SpeakerAudioDestination) { - return new AudioOutputConfigImpl(player); + this.privEnableSpeakerId = recognizerConfig.isSpeakerDiarizationEnabled; + this.privMustReportEndOfStream = false; + this.privAuthentication = authentication; + this.privConnectionFactory = connectionFactory; + this.privAudioSource = audioSource; + this.privRecognizerConfig = recognizerConfig; + this.privIsDisposed = false; + this.privRecognizer = recognizer; + this.privRequestSession = new Exports_js_4.RequestSession(this.privAudioSource.id()); + this.privConnectionEvents = new Exports_js_2.EventSource(); + this.privServiceEvents = new Exports_js_2.EventSource(); + this.privDynamicGrammar = new Exports_js_4.DynamicGrammarBuilder(); + this.privSpeechContext = new Exports_js_4.SpeechContext(this.privDynamicGrammar); + this.privAgentConfig = new Exports_js_4.AgentConfig(); + // Multi-channel always relies on the continuation/resume protocol, so reliable reconnect + // is enabled implicitly whenever multi-channel processing is active. + this.privEnableReliableReconnect = + this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Speech_EnableMultiChannelProcessing, "false").toLowerCase() === "true"; + this.privContinuationState = new Exports_js_4.ReconnectContinuationState(); + const webWorkerLoadType = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.WebWorkerLoadType, "on").toLowerCase(); + if (webWorkerLoadType === "on" && typeof (Blob) !== "undefined" && typeof (Worker) !== "undefined") { + this.privSetTimeout = Exports_js_2.Timeout.setTimeout; } - throw new Error("Not Supported Type"); - }; - /** - * Creates an AudioConfig object representing a specified output audio file - * @member AudioConfig.fromAudioFileOutput - * @function - * @public - * @param {PathLike} filename - the filename of the output audio file - * @returns {AudioConfig} The audio output configuration being created. - * Added in version 1.11.0 - */ - AudioConfig.fromAudioFileOutput = function (filename) { - return new AudioOutputConfigImpl(new AudioFileWriter_1.AudioFileWriter(filename)); - }; - /** - * Creates an AudioConfig object representing a specified audio output stream - * @member AudioConfig.fromStreamOutput - * @function - * @public - * @param {AudioOutputStream | PushAudioOutputStreamCallback} audioStream - Specifies the custom audio output - * stream. - * @returns {AudioConfig} The audio output configuration being created. - * Added in version 1.11.0 - */ - AudioConfig.fromStreamOutput = function (audioStream) { - if (audioStream instanceof Exports_2.PushAudioOutputStreamCallback) { - return new AudioOutputConfigImpl(new AudioOutputStream_1.PushAudioOutputStreamImpl(audioStream)); + else { + if (typeof window !== "undefined") { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.privSetTimeout = window.setTimeout.bind(window); + } + if (typeof globalThis !== "undefined") { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.privSetTimeout = globalThis.setTimeout.bind(globalThis); + } } - if (audioStream instanceof Exports_2.PushAudioOutputStream) { - return new AudioOutputConfigImpl(audioStream); + this.connectionEvents.attach((connectionEvent) => { + if (connectionEvent.name === "ConnectionClosedEvent") { + const connectionClosedEvent = connectionEvent; + if (connectionClosedEvent.statusCode === 1003 || + connectionClosedEvent.statusCode === 1007 || + connectionClosedEvent.statusCode === 1002 || + connectionClosedEvent.statusCode === 4000 || + this.privRequestSession.numConnectionAttempts > this.privRecognizerConfig.maxRetryCount) { + void this.cancelRecognitionLocal(Exports_js_3.CancellationReason.Error, connectionClosedEvent.statusCode === 1007 ? Exports_js_3.CancellationErrorCode.BadRequestParameters : Exports_js_3.CancellationErrorCode.ConnectionFailure, `${connectionClosedEvent.reason} websocket error code: ${connectionClosedEvent.statusCode}`); + } + } + }); + if (this.privEnableSpeakerId) { + this.privDiarizationSessionId = (0, Exports_js_2.createNoDashGuid)(); + } + } + setTranslationJson() { + const targetLanguages = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined); + if (targetLanguages !== undefined) { + const languages = targetLanguages.split(","); + const translationVoice = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined); + const categoryId = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationCategoryId, undefined); + const action = (translationVoice !== undefined) ? OnSuccess_js_1.NextAction.Synthesize : OnSuccess_js_1.NextAction.None; + this.privSpeechContext.getContext().translation = { + onPassthrough: { action }, + onSuccess: { action }, + output: { + includePassThroughResults: true, + interimResults: { mode: InterimResults_js_1.Mode.Always } + }, + targetLanguages: languages, + }; + // Add category if specified + if (categoryId !== undefined) { + this.privSpeechContext.getContext().translation.category = categoryId; + } + if (translationVoice !== undefined) { + const languageToVoiceMap = {}; + for (const lang of languages) { + languageToVoiceMap[lang] = translationVoice; + } + this.privSpeechContext.getContext().synthesis = { + defaultVoices: languageToVoiceMap + }; + } + // Configure phrase detection for translation + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + phraseDetection.onSuccess = { action: OnSuccess_js_3.NextAction.Translate }; + phraseDetection.onInterim = { action: OnSuccess_js_3.NextAction.Translate }; + this.privSpeechContext.getContext().phraseDetection = phraseDetection; } - if (audioStream instanceof Exports_2.PullAudioOutputStream) { - return new AudioOutputConfigImpl(audioStream); + } + setSpeechSegmentationTimeoutJson() { + const speechSegmentationSilenceTimeoutMs = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Speech_SegmentationSilenceTimeoutMs, undefined); + const speechSegmentationMaximumTimeMs = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Speech_SegmentationMaximumTimeMs, undefined); + const speechSegmentationStrategy = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Speech_SegmentationStrategy, undefined); + const segmentation = { + mode: Segmentation_js_1.SegmentationMode.Normal, + }; + let configuredSegment = false; + if (speechSegmentationStrategy !== undefined) { + configuredSegment = true; + let segMode = Segmentation_js_1.SegmentationMode.Normal; + switch (speechSegmentationStrategy.toLowerCase()) { + case "default": + break; + case "time": + segMode = Segmentation_js_1.SegmentationMode.Custom; + break; + case "semantic": + segMode = Segmentation_js_1.SegmentationMode.Semantic; + break; + } + segmentation.mode = segMode; + } + if (speechSegmentationSilenceTimeoutMs !== undefined) { + configuredSegment = true; + const segmentationSilenceTimeoutMs = parseInt(speechSegmentationSilenceTimeoutMs, 10); + segmentation.mode = Segmentation_js_1.SegmentationMode.Custom; + segmentation.segmentationSilenceTimeoutMs = segmentationSilenceTimeoutMs; + } + if (speechSegmentationMaximumTimeMs !== undefined) { + configuredSegment = true; + const segmentationMaximumTimeMs = parseInt(speechSegmentationMaximumTimeMs, 10); + segmentation.mode = Segmentation_js_1.SegmentationMode.Custom; + segmentation.segmentationForcedTimeoutMs = segmentationMaximumTimeMs; + } + if (configuredSegment) { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + phraseDetection.mode = this.recognitionMode; + switch (this.recognitionMode) { + case PhraseDetectionContext_js_1.RecognitionMode.Conversation: + phraseDetection.conversation = phraseDetection.conversation ?? { segmentation: {} }; + phraseDetection.conversation.segmentation = segmentation; + break; + case PhraseDetectionContext_js_1.RecognitionMode.Interactive: + phraseDetection.interactive = phraseDetection.interactive ?? { segmentation: {} }; + phraseDetection.interactive.segmentation = segmentation; + break; + case PhraseDetectionContext_js_1.RecognitionMode.Dictation: + phraseDetection.dictation = phraseDetection.dictation ?? {}; + phraseDetection.dictation.segmentation = segmentation; + break; + } + this.privSpeechContext.getContext().phraseDetection = phraseDetection; } - throw new Error("Not Supported Type"); - }; - return AudioConfig; -}()); -exports.AudioConfig = AudioConfig; -/** - * Represents audio input stream used for custom audio input configurations. - * @private - * @class AudioConfigImpl - */ -var AudioConfigImpl = /** @class */ (function (_super) { - __extends(AudioConfigImpl, _super); - /** - * Creates and initializes an instance of this class. - * @constructor - * @param {IAudioSource} source - An audio source. - */ - function AudioConfigImpl(source) { - var _this = _super.call(this) || this; - _this.privSource = source; - return _this; - } - Object.defineProperty(AudioConfigImpl.prototype, "format", { - /** - * Format information for the audio - */ - get: function () { - return this.privSource.format; - }, - enumerable: false, - configurable: true - }); - /** - * @member AudioConfigImpl.prototype.close - * @function - * @public - */ - AudioConfigImpl.prototype.close = function (cb, err) { - this.privSource.turnOff().then(function () { - if (!!cb) { - cb(); + } + setLanguageIdJson() { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + if (this.privRecognizerConfig.autoDetectSourceLanguages !== undefined) { + const sourceLanguages = this.privRecognizerConfig.autoDetectSourceLanguages.split(","); + if (sourceLanguages.length === 1 && sourceLanguages[0] === Exports_js_4.AutoDetectSourceLanguagesOpenRangeOptionName) { + sourceLanguages[0] = "UND"; } - }, function (error) { - if (!!err) { - err(error); + let speechContextLidMode; + if (this.privRecognizerConfig.languageIdMode === "Continuous") { + speechContextLidMode = LanguageIdContext_js_1.LanguageIdDetectionMode.DetectContinuous; + } + else { // recognizerConfig.languageIdMode === "AtStart" + speechContextLidMode = LanguageIdContext_js_1.LanguageIdDetectionMode.DetectAtAudioStart; + } + this.privSpeechContext.getContext().languageId = { + languages: sourceLanguages, + mode: speechContextLidMode, + onSuccess: { action: OnSuccess_js_2.NextAction.Recognize }, + onUnknown: { action: OnUnknown_js_1.OnUnknownAction.None }, + priority: LanguageIdContext_js_1.LanguageIdDetectionPriority.PrioritizeLatency + }; + this.privSpeechContext.getContext().phraseOutput = { + interimResults: { + resultType: InterimResults_js_2.ResultType.Auto + }, + phraseResults: { + resultType: PhraseResults_js_1.PhraseResultOutputType.Always + } + }; + const customModels = this.privRecognizerConfig.sourceLanguageModels; + if (customModels !== undefined) { + phraseDetection.customModels = customModels; + phraseDetection.onInterim = { action: OnSuccess_js_3.NextAction.None }; + phraseDetection.onSuccess = { action: OnSuccess_js_3.NextAction.None }; + } + } + // No longer setting translation-specific configuration here + // This is now handled in setTranslationJson and setupTranslationWithLanguageId methods + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + setOutputDetailLevelJson() { + const requestWordLevelTimestamps = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "false").toLowerCase(); + if (requestWordLevelTimestamps === "true") { + this.privSpeechContext.setWordLevelTimings(); + } + else { + const outputFormat = this.privRecognizerConfig.parameters.getProperty(Exports_js_4.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]).toLowerCase(); + if (outputFormat === Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Detailed].toLocaleLowerCase()) { + this.privSpeechContext.setDetailedOutputFormat(); + } + } + } + setSpeechStartEventSensitivityJson() { + const sensitivity = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Speech_StartEventSensitivity, undefined); + if (sensitivity !== undefined) { + let configuredSensitivity = false; + switch (sensitivity.toLowerCase()) { + case PhraseDetectionContext_js_1.SpeechStartEventSensitivity.Low: + case PhraseDetectionContext_js_1.SpeechStartEventSensitivity.Medium: + case PhraseDetectionContext_js_1.SpeechStartEventSensitivity.High: + configuredSensitivity = true; + break; + } + if (configuredSensitivity) { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + phraseDetection.voiceOnsetSensitivity = sensitivity.toLowerCase(); + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + } + } + setPostProcessingOptionJson() { + const postProcessingOption = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceResponse_PostProcessingOption, undefined); + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + phraseDetection.enrichment = phraseDetection.enrichment || {}; + // Clear stale postprocessing fields for the current mode before applying new value. + // This prevents leftover fields when switching between truetext/non-truetext/absent across turns. + const modeObj = this.recognitionMode === PhraseDetectionContext_js_1.RecognitionMode.Conversation + ? phraseDetection.enrichment.conversation + : this.recognitionMode === PhraseDetectionContext_js_1.RecognitionMode.Interactive + ? phraseDetection.enrichment.interactive + : phraseDetection.enrichment.dictation; + if (modeObj) { + delete modeObj.postprocessingoption; + delete modeObj.punctuationMode; + delete modeObj.disfluencyMode; + delete modeObj.intermediatePunctuationMode; + delete modeObj.intermediatedisfluencymode; + } + if (postProcessingOption !== undefined) { + if (postProcessingOption.toLowerCase() === "truetext") { + // Client-side expansion for "truetext" - set specific properties + switch (this.recognitionMode) { + case PhraseDetectionContext_js_1.RecognitionMode.Conversation: + phraseDetection.enrichment.conversation = phraseDetection.enrichment.conversation || {}; + phraseDetection.enrichment.conversation.punctuationMode = ConversationEnrichmentOptions_js_1.ConversationPunctuationMode.Implicit; + phraseDetection.enrichment.conversation.disfluencyMode = DisfluencyMode_js_1.DisfluencyMode.Removed; + phraseDetection.enrichment.conversation.intermediatePunctuationMode = ConversationEnrichmentOptions_js_1.ConversationPunctuationMode.Implicit; + phraseDetection.enrichment.conversation.intermediatedisfluencymode = DisfluencyMode_js_1.DisfluencyMode.Removed; + break; + case PhraseDetectionContext_js_1.RecognitionMode.Interactive: + phraseDetection.enrichment.interactive = phraseDetection.enrichment.interactive || {}; + phraseDetection.enrichment.interactive.punctuationMode = InteractiveEnrichmentOptions_js_1.InteractivePunctuationMode.Implicit; + phraseDetection.enrichment.interactive.disfluencyMode = DisfluencyMode_js_1.DisfluencyMode.Removed; + phraseDetection.enrichment.interactive.intermediatePunctuationMode = InteractiveEnrichmentOptions_js_1.InteractivePunctuationMode.Implicit; + phraseDetection.enrichment.interactive.intermediatedisfluencymode = DisfluencyMode_js_1.DisfluencyMode.Removed; + break; + case PhraseDetectionContext_js_1.RecognitionMode.Dictation: + phraseDetection.enrichment.dictation = phraseDetection.enrichment.dictation || {}; + phraseDetection.enrichment.dictation.punctuationMode = DictationEnrichmentOptions_js_1.DictationPunctuationMode.Implicit; + phraseDetection.enrichment.dictation.disfluencyMode = DisfluencyMode_js_1.DisfluencyMode.Removed; + phraseDetection.enrichment.dictation.intermediatePunctuationMode = DictationEnrichmentOptions_js_1.DictationPunctuationMode.Implicit; + phraseDetection.enrichment.dictation.intermediatedisfluencymode = DisfluencyMode_js_1.DisfluencyMode.Removed; + break; + } + } + else { + // Service-side handling for all other strings + switch (this.recognitionMode) { + case PhraseDetectionContext_js_1.RecognitionMode.Conversation: + phraseDetection.enrichment.conversation = phraseDetection.enrichment.conversation || {}; + phraseDetection.enrichment.conversation.postprocessingoption = postProcessingOption; + break; + case PhraseDetectionContext_js_1.RecognitionMode.Interactive: + phraseDetection.enrichment.interactive = phraseDetection.enrichment.interactive || {}; + phraseDetection.enrichment.interactive.postprocessingoption = postProcessingOption; + break; + case PhraseDetectionContext_js_1.RecognitionMode.Dictation: + phraseDetection.enrichment.dictation = phraseDetection.enrichment.dictation || {}; + phraseDetection.enrichment.dictation.postprocessingoption = postProcessingOption; + break; + } + } + } + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + setLanguageJson() { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + if (this.privRecognizerConfig.autoDetectSourceLanguages !== undefined) { + // Auto-detect is configured — language is managed by the language ID subsystem, clear any stale value + delete phraseDetection.language; + } + else { + const language = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, undefined); + if (language !== undefined) { + phraseDetection.language = language; + } + else { + delete phraseDetection.language; } + } + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + setInitialSilenceTimeoutJson() { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + const value = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, undefined); + if (value !== undefined) { + phraseDetection.initialSilenceTimeout = parseInt(value, 10); + } + else { + delete phraseDetection.initialSilenceTimeout; + } + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + setEndSilenceTimeoutJson() { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + const value = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs, undefined); + if (value !== undefined) { + phraseDetection.trailingSilenceTimeout = parseInt(value, 10); + } + else { + delete phraseDetection.trailingSilenceTimeout; + } + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + setProfanityOptionJson() { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + const value = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceResponse_ProfanityOption, undefined); + if (value !== undefined) { + phraseDetection.enrichment = phraseDetection.enrichment || {}; + phraseDetection.enrichment.profanity = value; + } + else { + if (phraseDetection.enrichment) { + delete phraseDetection.enrichment.profanity; + } + } + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + setStableIntermediateThresholdJson() { + const value = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceResponse_StablePartialResultThreshold, undefined); + // Deep-merge into existing phraseOutput — setLanguageIdJson may have already initialized it + const phraseOutput = this.privSpeechContext.getContext().phraseOutput || {}; + if (value !== undefined) { + phraseOutput.interimResults = phraseOutput.interimResults || {}; + phraseOutput.interimResults.stableThreshold = parseInt(value, 10); + } + else { + if (phraseOutput.interimResults) { + delete phraseOutput.interimResults.stableThreshold; + } + } + this.privSpeechContext.getContext().phraseOutput = phraseOutput; + } + get isSpeakerDiarizationEnabled() { + return this.privEnableSpeakerId; + } + get audioSource() { + return this.privAudioSource; + } + get speechContext() { + return this.privSpeechContext; + } + get dynamicGrammar() { + return this.privDynamicGrammar; + } + get agentConfig() { + return this.privAgentConfig; + } + set authentication(auth) { + this.privAuthentication = auth; + } + isDisposed() { + return this.privIsDisposed; + } + async dispose(reason) { + this.privIsDisposed = true; + if (this.privConnectionPromise !== undefined) { + try { + const connection = await this.privConnectionPromise; + await connection.dispose(reason); + } + catch (error) { + // The connection is in a bad state. But we're trying to kill it, so... + return; + } + } + } + get connectionEvents() { + return this.privConnectionEvents; + } + get serviceEvents() { + return this.privServiceEvents; + } + get recognitionMode() { + return this.privRecognizerConfig.recognitionMode; + } + async recognize(recoMode, successCallback, errorCallBack) { + if (this.recognizeOverride !== undefined) { + await this.recognizeOverride(recoMode, successCallback, errorCallBack); + return; + } + // Clear the existing configuration promise to force a re-transmission of config and context. + this.privConnectionConfigurationPromise = undefined; + this.privRecognizerConfig.recognitionMode = recoMode; + if (this.privRecognizerConfig.recognitionEndpointVersion === "2") { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + phraseDetection.mode = recoMode; + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + // Set language ID (if configured) + this.setLanguageIdJson(); + // Then set translation (if configured) + this.setTranslationJson(); + // Configure the integration between language ID and translation (if both are used) + if (this.privRecognizerConfig.autoDetectSourceLanguages !== undefined && + this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) { + this.setupTranslationWithLanguageId(); + } + this.setLanguageJson(); + this.setInitialSilenceTimeoutJson(); + this.setEndSilenceTimeoutJson(); + this.setSpeechSegmentationTimeoutJson(); + this.setOutputDetailLevelJson(); + this.setSpeechStartEventSensitivityJson(); + this.setProfanityOptionJson(); + this.setPostProcessingOptionJson(); + this.setStableIntermediateThresholdJson(); + this.privSuccessCallback = successCallback; + this.privErrorCallback = errorCallBack; + this.privRequestSession.startNewRecognition(); + this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events); + if (this.privEnableReliableReconnect) { + this.privContinuationState.reset(); + } + // Start the connection to the service. The promise this will create is stored and will be used by configureConnection(). + const conPromise = this.connectImpl(); + let audioNode; + try { + const audioStreamNode = await this.audioSource.attach(this.privRequestSession.audioNodeId); + const format = await this.audioSource.format; + const deviceInfo = await this.audioSource.deviceInfo; + this.privIsLiveAudio = deviceInfo.type && deviceInfo.type === Exports_js_4.type.Microphones; + // SeparateChannelProcessing activates per-channel processing and the reliable-reconnect + // contract service-side. + if (this.privEnableReliableReconnect) { + deviceInfo.SeparateChannelProcessing = "true"; + } + audioNode = new Exports_js_1.ReplayableAudioNode(audioStreamNode, format.avgBytesPerSec); + await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false); + this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo }; + } + catch (error) { + await this.privRequestSession.onStopRecognizing(); + throw error; + } + try { + await conPromise; + } + catch (error) { + await this.cancelRecognitionLocal(Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.ConnectionFailure, error); + return; + } + const sessionStartEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId); + if (!!this.privRecognizer.sessionStarted) { + this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs); + } + void this.receiveMessage(); + const audioSendPromise = this.sendAudio(audioNode); + audioSendPromise.catch(async (error) => { + await this.cancelRecognitionLocal(Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.RuntimeError, error); }); - }; - /** - * @member AudioConfigImpl.prototype.id - * @function - * @public - */ - AudioConfigImpl.prototype.id = function () { - return this.privSource.id(); - }; - Object.defineProperty(AudioConfigImpl.prototype, "blob", { - /** - * @member AudioConfigImpl.prototype.blob - * @function - * @public - */ - get: function () { - return this.privSource.blob; - }, - enumerable: false, - configurable: true - }); - /** - * @member AudioConfigImpl.prototype.turnOn - * @function - * @public - * @returns {Promise} A promise. - */ - AudioConfigImpl.prototype.turnOn = function () { - return this.privSource.turnOn(); - }; - /** - * @member AudioConfigImpl.prototype.attach - * @function - * @public - * @param {string} audioNodeId - The audio node id. - * @returns {Promise} A promise. - */ - AudioConfigImpl.prototype.attach = function (audioNodeId) { - return this.privSource.attach(audioNodeId); - }; - /** - * @member AudioConfigImpl.prototype.detach - * @function - * @public - * @param {string} audioNodeId - The audio node id. - */ - AudioConfigImpl.prototype.detach = function (audioNodeId) { - return this.privSource.detach(audioNodeId); - }; - /** - * @member AudioConfigImpl.prototype.turnOff - * @function - * @public - * @returns {Promise} A promise. - */ - AudioConfigImpl.prototype.turnOff = function () { - return this.privSource.turnOff(); - }; - Object.defineProperty(AudioConfigImpl.prototype, "events", { - /** - * @member AudioConfigImpl.prototype.events - * @function - * @public - * @returns {EventSource} An event source for audio events. - */ - get: function () { - return this.privSource.events; - }, - enumerable: false, - configurable: true - }); - AudioConfigImpl.prototype.setProperty = function (name, value) { - Contracts_1.Contracts.throwIfNull(value, "value"); - if (undefined !== this.privSource.setProperty) { - this.privSource.setProperty(name, value); + return; + } + async stopRecognizing() { + if (this.privRequestSession.isRecognizing) { + try { + await this.audioSource.turnOff(); + await this.sendFinalAudio(); + await this.privRequestSession.onStopRecognizing(); + await this.privRequestSession.turnCompletionPromise; + } + finally { + await this.privRequestSession.dispose(); + } + } + return; + } + async connect() { + await this.connectImpl(); + return Promise.resolve(); + } + connectAsync(cb, err) { + this.connectImpl().then(() => { + try { + if (!!cb) { + cb(); + } + } + catch (e) { + if (!!err) { + err(e); + } + } + }, (reason) => { + try { + if (!!err) { + err(reason); + } + /* eslint-disable no-empty */ + } + catch (error) { + } + }); + } + async disconnect() { + await this.cancelRecognitionLocal(Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.NoError, "Disconnecting"); + if (this.disconnectOverride !== undefined) { + await this.disconnectOverride(); + } + if (this.privConnectionPromise !== undefined) { + try { + await (await this.privConnectionPromise).dispose(); + } + catch (error) { + } + } + this.privConnectionPromise = undefined; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + sendMessage(message) { + return; + } + async sendNetworkMessage(path, payload) { + const type = typeof payload === "string" ? Exports_js_2.MessageType.Text : Exports_js_2.MessageType.Binary; + const contentType = typeof payload === "string" ? "application/json" : ""; + const connection = await this.fetchConnection(); + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(type, path, this.privRequestSession.requestId, contentType, payload)); + } + set activityTemplate(messagePayload) { + this.privActivityTemplate = messagePayload; + } + get activityTemplate() { + return this.privActivityTemplate; + } + set expectContentAssessmentResponse(value) { + this.privExpectContentAssessmentResponse = value; + } + async sendTelemetryData() { + const telemetryData = this.privRequestSession.getTelemetry(); + if (ServiceRecognizerBase.telemetryDataEnabled !== true || + this.privIsDisposed || + null === telemetryData) { + return; + } + if (!!ServiceRecognizerBase.telemetryData) { + try { + ServiceRecognizerBase.telemetryData(telemetryData); + /* eslint-disable no-empty */ + } + catch { } + } + const connection = await this.fetchConnection(); + await connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "telemetry", this.privRequestSession.requestId, "application/json", telemetryData)); + } + // Cancels recognition. + async cancelRecognitionLocal(cancellationReason, errorCode, error) { + if (!!this.privRequestSession.isRecognizing) { + await this.privRequestSession.onStopRecognizing(); + this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, cancellationReason, errorCode, error); + } + } + async receiveMessage() { + try { + if (this.privIsDisposed) { + // We're done. + return; + } + let connection = await this.fetchConnection(); + const message = await connection.read(); + if (this.receiveMessageOverride !== undefined) { + return this.receiveMessageOverride(); + } + // indicates we are draining the queue and it came with no message; + if (!message) { + return this.receiveMessage(); + } + this.privServiceHasSentMessage = true; + const connectionMessage = SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage.fromConnectionMessage(message); + if (connectionMessage.requestId.toLowerCase() === this.privRequestSession.requestId.toLowerCase()) { + if (this.privEnableReliableReconnect) { + // Capture the continuation token + per-stream resume offset (the offset header + // is turn-relative and gets rebased onto the session-absolute timeline). + this.privContinuationState.updateFromHeaders(connectionMessage.additionalHeaders, this.privRequestSession.currentTurnAudioOffset); + // Trim the replay buffer to the service-acknowledged offset so a reconnect + // resends only unacknowledged audio. + const acknowledgedOffset = this.privContinuationState.streamOffset; + if (acknowledgedOffset !== undefined) { + this.privRequestSession.onServiceAcknowledgedAudio(acknowledgedOffset); + } + } + switch (connectionMessage.path.toLowerCase()) { + case "turn.start": + this.privMustReportEndOfStream = true; + this.privRequestSession.onServiceTurnStartResponse(); + if (this.privEnableReliableReconnect) { + // The reliable-reconnect service tag is delivered in the + // turn.start body under "$.context.serviceTag" (not a header). + let turnStartServiceTag; + try { + if (connectionMessage.textBody && connectionMessage.textBody.length > 0) { + const turnStartBody = JSON.parse(connectionMessage.textBody); + turnStartServiceTag = turnStartBody?.context?.serviceTag; + } + } + catch { + turnStartServiceTag = undefined; + } + this.privContinuationState.onTurnStart(turnStartServiceTag); + } + break; + case "speech.startdetected": + const speechStartDetected = Exports_js_4.SpeechDetected.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + const speechStartEventArgs = new Exports_js_3.RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId); + if (!!this.privRecognizer.speechStartDetected) { + this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs); + } + break; + case "speech.enddetected": + let json; + if (connectionMessage.textBody.length > 0) { + json = connectionMessage.textBody; + } + else { + // If the request was empty, the JSON returned is empty. + json = "{ Offset: 0 }"; + } + const speechStopDetected = Exports_js_4.SpeechDetected.fromJSON(json, this.privRequestSession.currentTurnAudioOffset); + const speechStopEventArgs = new Exports_js_3.RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId); + if (!!this.privRecognizer.speechEndDetected) { + this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs); + } + break; + case "turn.end": + await this.sendTelemetryData(); + // Reliable reconnect: turn.end does NOT clear the continuation state; the + // token/offset/service tag persist for the session. + if (this.privRequestSession.isSpeechEnded && this.privMustReportEndOfStream) { + this.privMustReportEndOfStream = false; + await this.cancelRecognitionLocal(Exports_js_3.CancellationReason.EndOfStream, Exports_js_3.CancellationErrorCode.NoError, undefined); + } + const sessionStopEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId); + await this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition); + if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) { + if (!!this.privRecognizer.sessionStopped) { + this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs); + } + return; + } + else { + connection = await this.fetchConnection(); + await this.sendPrePayloadJSON(connection); + } + break; + default: + if (!await this.processTypeSpecificMessages(connectionMessage)) { + // here are some messages that the derived class has not processed, dispatch them to connect class + if (!!this.privServiceEvents) { + this.serviceEvents.onEvent(new Exports_js_2.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody)); + } + } + } + } + return this.receiveMessage(); + } + catch (error) { + return null; + } + } + updateSpeakerDiarizationAudioOffset() { + const bytesSent = this.privRequestSession.recognitionBytesSent; + const audioOffsetMs = this.privAverageBytesPerMs !== 0 ? bytesSent / this.privAverageBytesPerMs : 0; + this.privSpeechContext.setSpeakerDiarizationAudioOffsetMs(audioOffsetMs); + } + // The stream id tagged onto outgoing audio messages when reliable reconnect is enabled. + // Undefined disables the X-StreamId header, preserving legacy behavior. + get audioStreamId() { + return this.privEnableReliableReconnect ? this.privContinuationState.defaultStreamId : undefined; + } + // Injects the reliable-reconnect sections into speech.context: the audio.streams marker + // (always present) and the continuation section (only when resuming an interrupted turn). + applyReconnectContinuation() { + const context = this.privSpeechContext.getContext(); + context.audio = this.privContinuationState.buildAudioStreamsMetadata(); + const continuation = this.privContinuationState.buildContinuationContext(); + if (continuation !== undefined) { + context.continuation = continuation; + } + else { + delete context.continuation; + } + } + sendSpeechContext(connection, generateNewRequestId) { + if (this.privEnableSpeakerId) { + this.updateSpeakerDiarizationAudioOffset(); + } + if (this.privEnableReliableReconnect) { + this.applyReconnectContinuation(); + } + const speechContextJson = this.speechContext.toJSON(); + if (generateNewRequestId) { + this.privRequestSession.onSpeechContext(); + } + if (speechContextJson) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speech.context", this.privRequestSession.requestId, "application/json", speechContextJson)); + } + return; + } + setupTranslationWithLanguageId() { + const targetLanguages = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined); + const hasLanguageId = this.privRecognizerConfig.autoDetectSourceLanguages !== undefined; + if (targetLanguages !== undefined && hasLanguageId) { + // Configure phraseOutput for translation + language ID scenario + this.privSpeechContext.getContext().phraseOutput = { + interimResults: { + resultType: InterimResults_js_2.ResultType.None + }, + phraseResults: { + resultType: PhraseResults_js_1.PhraseResultOutputType.None + } + }; + // Handle custom language models and voice mapping + const translationContext = this.privSpeechContext.getContext().translation; + if (translationContext) { + const customModels = this.privRecognizerConfig.sourceLanguageModels; + if (customModels !== undefined && customModels.length > 0) { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + phraseDetection.customModels = customModels; + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + const translationVoice = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined); + if (translationVoice !== undefined) { + // Update translation actions for synthesis + translationContext.onSuccess = { action: OnSuccess_js_1.NextAction.Synthesize }; + translationContext.onPassthrough = { action: OnSuccess_js_1.NextAction.Synthesize }; + } + } + } + } + noOp() { + // operation not supported + return; + } + // Encapsulated for derived service recognizers that need to send additional JSON + async sendPrePayloadJSON(connection, generateNewRequestId = true) { + if (this.sendPrePayloadJSONOverride !== undefined) { + return this.sendPrePayloadJSONOverride(connection); + } + await this.sendSpeechContext(connection, generateNewRequestId); + await this.sendWaveHeader(connection); + return; + } + async sendWaveHeader(connection) { + const format = await this.audioSource.format; + // this.writeBufferToConsole(format.header); + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Binary, "audio", this.privRequestSession.requestId, "audio/x-wav", format.header, this.audioStreamId)); + } + reconnect() { + if (this.privConnectionPromise !== undefined && !this.privServiceHasSentMessage) { + return this.privConnectionPromise; + } + this.privConnectionId = null; + this.privConnectionPromise = undefined; + this.privServiceHasSentMessage = false; + return this.connectImpl(); + } + // Establishes a websocket connection to the end point. + connectImpl() { + if (this.privConnectionPromise !== undefined) { + return this.privConnectionPromise.then((connection) => { + if (connection.state() === Exports_js_2.ConnectionState.Disconnected) { + return this.reconnect(); + } + return this.privConnectionPromise; + }, () => this.reconnect()); + } + this.privConnectionPromise = this.retryableConnect(); + // Attach an empty handler to allow the promise to run in the background while + // other startup events happen. It'll eventually be awaited on. + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.privConnectionPromise.catch(() => { }); + if (this.postConnectImplOverride !== undefined) { + return this.postConnectImplOverride(this.privConnectionPromise); + } + return this.privConnectionPromise; + } + sendSpeechServiceConfig(connection, requestSession, SpeechServiceConfigJson) { + requestSession.onSpeechContext(); + // filter out anything that is not required for the service to work. + if (ServiceRecognizerBase.telemetryDataEnabled !== true) { + const withTelemetry = JSON.parse(SpeechServiceConfigJson); + const replacement = { + context: { + system: withTelemetry.context.system, + }, + }; + SpeechServiceConfigJson = JSON.stringify(replacement); + } + if (this.privRecognizerConfig.parameters.getProperty("f0f5debc-f8c9-4892-ac4b-90a7ab359fd2", "false").toLowerCase() === "true") { + const json = JSON.parse(SpeechServiceConfigJson); + json.context.DisableReferenceChannel = "True"; + json.context.MicSpec = "1_0_0"; + SpeechServiceConfigJson = JSON.stringify(json); + } + if (SpeechServiceConfigJson) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speech.config", requestSession.requestId, "application/json", SpeechServiceConfigJson)); + } + return; + } + async fetchConnection() { + if (this.privConnectionConfigurationPromise !== undefined) { + return this.privConnectionConfigurationPromise.then((connection) => { + if (connection.state() === Exports_js_2.ConnectionState.Disconnected) { + this.privConnectionConfigurationPromise = undefined; + return this.fetchConnection(); + } + return this.privConnectionConfigurationPromise; + }, () => { + this.privConnectionConfigurationPromise = undefined; + return this.fetchConnection(); + }); + } + this.privConnectionConfigurationPromise = this.configureConnection(); + return await this.privConnectionConfigurationPromise; + } + async sendAudio(audioStreamNode) { + const audioFormat = await this.audioSource.format; + this.privAverageBytesPerMs = audioFormat.avgBytesPerSec / 1000; + // The time we last sent data to the service. + let nextSendTime = Date.now(); + // Max amount to send before we start to throttle + const fastLaneSizeMs = this.privRecognizerConfig.parameters.getProperty("SPEECH-TransmitLengthBeforThrottleMs", "5000"); + const maxSendUnthrottledBytes = audioFormat.avgBytesPerSec / 1000 * parseInt(fastLaneSizeMs, 10); + const startRecogNumber = this.privRequestSession.recogNumber; + const readAndUploadCycle = async () => { + // If speech is done, stop sending audio. + if (!this.privIsDisposed && + !this.privRequestSession.isSpeechEnded && + this.privRequestSession.isRecognizing && + this.privRequestSession.recogNumber === startRecogNumber) { + const connection = await this.fetchConnection(); + const audioStreamChunk = await audioStreamNode.read(); + // we have a new audio chunk to upload. + if (this.privRequestSession.isSpeechEnded) { + // If service already recognized audio end then don't send any more audio + return; + } + let payload; + let sendDelay; + if (!audioStreamChunk || audioStreamChunk.isEnd) { + payload = null; + sendDelay = 0; + } + else { + payload = audioStreamChunk.buffer; + this.privRequestSession.onAudioSent(payload.byteLength); + if (maxSendUnthrottledBytes >= this.privRequestSession.bytesSent) { + sendDelay = 0; + } + else { + sendDelay = Math.max(0, nextSendTime - Date.now()); + } + } + if (0 !== sendDelay) { + await this.delay(sendDelay); + } + if (payload !== null) { + nextSendTime = Date.now() + (payload.byteLength * 1000 / (audioFormat.avgBytesPerSec * 2)); + } + // Are we still alive? + if (!this.privIsDisposed && + !this.privRequestSession.isSpeechEnded && + this.privRequestSession.isRecognizing && + this.privRequestSession.recogNumber === startRecogNumber) { + connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Binary, "audio", this.privRequestSession.requestId, null, payload, this.audioStreamId)).catch(() => { + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch(() => { }); + }); + if (!audioStreamChunk?.isEnd) { + // this.writeBufferToConsole(payload); + // Regardless of success or failure, schedule the next upload. + // If the underlying connection was broken, the next cycle will + // get a new connection and re-transmit missing audio automatically. + return readAndUploadCycle(); + } + else { + // the audio stream has been closed, no need to schedule next + // read-upload cycle. + if (!this.privIsLiveAudio) { + this.privRequestSession.onSpeechEnded(); + } + } + } + } + }; + return readAndUploadCycle(); + } + async retryableConnect() { + let isUnAuthorized = false; + this.privAuthFetchEventId = (0, Exports_js_2.createNoDashGuid)(); + const sessionId = this.privRequestSession.sessionId; + this.privConnectionId = (sessionId !== undefined) ? sessionId : (0, Exports_js_2.createNoDashGuid)(); + this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId); + let lastStatusCode = 0; + let lastReason = ""; + while (this.privRequestSession.numConnectionAttempts <= this.privRecognizerConfig.maxRetryCount) { + this.privRequestSession.onRetryConnection(); + // Get the auth information for the connection. This is a bit of overkill for the current API surface, but leaving the plumbing in place to be able to raise a developer-customer + // facing event when a connection fails to let them try and provide new auth information. + const authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId); + const auth = await authPromise; + await this.privRequestSession.onAuthCompleted(false); + // Create the connection + const connection = await this.privConnectionFactory.create(this.privRecognizerConfig, auth, this.privConnectionId); + // Attach the telemetry handlers. + this.privRequestSession.listenForServiceTelemetry(connection.events); + // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away, + // it'll stop sending events. + connection.events.attach((event) => { + this.connectionEvents.onEvent(event); + }); + const response = await connection.open(); + // 200 == everything is fine. + if (response.statusCode === 200) { + await this.privRequestSession.onConnectionEstablishCompleted(response.statusCode); + return Promise.resolve(connection); + } + else if (response.statusCode === 1006) { + isUnAuthorized = true; + } + lastStatusCode = response.statusCode; + lastReason = response.reason; + } + await this.privRequestSession.onConnectionEstablishCompleted(lastStatusCode, lastReason); + return Promise.reject(`Unable to contact server. StatusCode: ${lastStatusCode}, ${this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Endpoint)} Reason: ${lastReason}`); + } + delay(delayMs) { + return new Promise((resolve) => this.privSetTimeout(resolve, delayMs)); + } + writeBufferToConsole(buffer) { + let out = "Buffer Size: "; + if (null === buffer) { + out += "null"; } else { - throw new Error("This AudioConfig instance does not support setting properties."); + const readView = new Uint8Array(buffer); + out += `${buffer.byteLength}\r\n`; + for (let i = 0; i < buffer.byteLength; i++) { + out += readView[i].toString(16).padStart(2, "0") + " "; + if (((i + 1) % 16) === 0) { + // eslint-disable-next-line no-console + console.info(out); + out = ""; + } + } } - }; - AudioConfigImpl.prototype.getProperty = function (name, def) { - if (undefined !== this.privSource.getProperty) { - return this.privSource.getProperty(name, def); + // eslint-disable-next-line no-console + console.info(out); + } + async sendFinalAudio() { + const connection = await this.fetchConnection(); + await connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Binary, "audio", this.privRequestSession.requestId, null, null, this.audioStreamId)); + return; + } + // Takes an established websocket connection to the endpoint and sends speech configuration information. + async configureConnection() { + const connection = await this.connectImpl(); + if (this.configConnectionOverride !== undefined) { + return this.configConnectionOverride(connection); } - else { - throw new Error("This AudioConfig instance does not support getting properties."); + await this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize()); + await this.sendPrePayloadJSON(connection, false); + return connection; + } +} +exports.ServiceRecognizerBase = ServiceRecognizerBase; +ServiceRecognizerBase.telemetryDataEnabled = true; + + + +/***/ }), +/* 66 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__webpack_require__(67), exports); +__exportStar(__webpack_require__(71), exports); +__exportStar(__webpack_require__(72), exports); +__exportStar(__webpack_require__(74), exports); +__exportStar(__webpack_require__(75), exports); +__exportStar(__webpack_require__(76), exports); +__exportStar(__webpack_require__(77), exports); +__exportStar(__webpack_require__(83), exports); +__exportStar(__webpack_require__(84), exports); +__exportStar(__webpack_require__(184), exports); +__exportStar(__webpack_require__(187), exports); + + + +/***/ }), +/* 67 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConsoleLoggingListener = void 0; +const fs = __importStar(__webpack_require__(68)); +const LogLevel_js_1 = __webpack_require__(69); +const Contracts_js_1 = __webpack_require__(70); +class ConsoleLoggingListener { + constructor(logLevelFilter = LogLevel_js_1.LogLevel.None) { + this.privLogPath = undefined; + this.privEnableConsoleOutput = true; + this.privLogLevelFilter = logLevelFilter; + } + set logPath(path) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(fs.openSync, "\nFile System access not available"); + this.privLogPath = path; + } + set enableConsoleOutput(enableOutput) { + this.privEnableConsoleOutput = enableOutput; + } + onEvent(event) { + if (event.eventType >= this.privLogLevelFilter) { + const log = this.toString(event); + if (!!this.logCallback) { + this.logCallback(log); + } + if (!!this.privLogPath) { + fs.writeFileSync(this.privLogPath, log + "\n", { flag: "a+" }); + } + if (this.privEnableConsoleOutput) { + switch (event.eventType) { + case LogLevel_js_1.LogLevel.Debug: + // eslint-disable-next-line no-console + console.debug(log); + break; + case LogLevel_js_1.LogLevel.Info: + // eslint-disable-next-line no-console + console.info(log); + break; + case LogLevel_js_1.LogLevel.Warning: + // eslint-disable-next-line no-console + console.warn(log); + break; + case LogLevel_js_1.LogLevel.Error: + // eslint-disable-next-line no-console + console.error(log); + break; + default: + // eslint-disable-next-line no-console + console.log(log); + break; + } + } } - return def; - }; - Object.defineProperty(AudioConfigImpl.prototype, "deviceInfo", { - get: function () { - return this.privSource.deviceInfo; - }, - enumerable: false, - configurable: true - }); - return AudioConfigImpl; -}(AudioConfig)); -exports.AudioConfigImpl = AudioConfigImpl; -var AudioOutputConfigImpl = /** @class */ (function (_super) { - __extends(AudioOutputConfigImpl, _super); - /** - * Creates and initializes an instance of this class. - * @constructor - * @param {IAudioDestination} destination - An audio destination. - */ - function AudioOutputConfigImpl(destination) { - var _this = _super.call(this) || this; - _this.privDestination = destination; - return _this; - } - Object.defineProperty(AudioOutputConfigImpl.prototype, "format", { - set: function (format) { - this.privDestination.format = format; - }, - enumerable: false, - configurable: true - }); - AudioOutputConfigImpl.prototype.write = function (buffer) { - this.privDestination.write(buffer); - }; - AudioOutputConfigImpl.prototype.close = function () { - this.privDestination.close(); - }; - AudioOutputConfigImpl.prototype.id = function () { - return this.privDestination.id(); - }; - AudioOutputConfigImpl.prototype.setProperty = function (name, value) { - throw new Error("This AudioConfig instance does not support setting properties."); - }; - AudioOutputConfigImpl.prototype.getProperty = function (name, def) { - throw new Error("This AudioConfig instance does not support getting properties."); - }; - return AudioOutputConfigImpl; -}(AudioConfig)); -exports.AudioOutputConfigImpl = AudioOutputConfigImpl; + } + toString(event) { + const logFragments = [ + `${event.eventTime}`, + `${event.name}`, + ]; + const e = event; + for (const prop in e) { + if (prop && event.hasOwnProperty(prop) && + prop !== "eventTime" && prop !== "eventType" && + prop !== "eventId" && prop !== "name" && + prop !== "constructor") { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + const value = e[prop]; + let valueToLog = ""; + if (value !== undefined && value !== null) { + if (typeof (value) === "number" || typeof (value) === "string") { + valueToLog = value.toString(); + } + else { + valueToLog = JSON.stringify(value); + } + } + logFragments.push(`${prop}: ${valueToLog}`); + } + } + return logFragments.join(" | "); + } +} +exports.ConsoleLoggingListener = ConsoleLoggingListener; /***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { +/* 68 */ +/***/ (() => { + +/* (ignored) */ + +/***/ }), +/* 69 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LogLevel = void 0; +const Exports_js_1 = __webpack_require__(4); +Object.defineProperty(exports, "LogLevel", ({ enumerable: true, get: function () { return Exports_js_1.EventType; } })); + + + +/***/ }), +/* 70 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Contracts = void 0; /** * @class Contracts * @private */ -var Contracts = /** @class */ (function () { - function Contracts() { - } - Contracts.throwIfNullOrUndefined = function (param, name) { +class Contracts { + static throwIfNullOrUndefined(param, name) { if (param === undefined || param === null) { throw new Error("throwIfNullOrUndefined:" + name); } - }; - Contracts.throwIfNull = function (param, name) { + } + static throwIfNull(param, name) { if (param === null) { throw new Error("throwIfNull:" + name); } - }; - Contracts.throwIfNullOrWhitespace = function (param, name) { + } + static throwIfNullOrWhitespace(param, name) { Contracts.throwIfNullOrUndefined(param, name); if (("" + param).trim().length < 1) { throw new Error("throwIfNullOrWhitespace:" + name); } - }; - Contracts.throwIfDisposed = function (isDisposed) { + } + static throwIfNullOrTooLong(param, name, maxLength) { + Contracts.throwIfNullOrUndefined(param, name); + if (("" + param).length > maxLength) { + throw new Error("throwIfNullOrTooLong:" + name + " (more than " + maxLength.toString() + " characters)"); + } + } + static throwIfNullOrTooShort(param, name, minLength) { + Contracts.throwIfNullOrUndefined(param, name); + if (("" + param).length < minLength) { + throw new Error("throwIfNullOrTooShort:" + name + " (less than " + minLength.toString() + " characters)"); + } + } + static throwIfDisposed(isDisposed) { if (isDisposed) { throw new Error("the object is already disposed"); } - }; - Contracts.throwIfArrayEmptyOrWhitespace = function (array, name) { + } + static throwIfArrayEmptyOrWhitespace(array, name) { Contracts.throwIfNullOrUndefined(array, name); if (array.length === 0) { throw new Error("throwIfArrayEmptyOrWhitespace:" + name); } - for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { - var item = array_1[_i]; - Contracts.throwIfNullOrWhitespace(item, name); + for (const item of array) { + Contracts.throwIfNullOrWhitespace(item, name); + } + } + static throwIfFileDoesNotExist(param, name) { + Contracts.throwIfNullOrWhitespace(param, name); + // TODO check for file existence. + } + static throwIfNotUndefined(param, name) { + if (param !== undefined) { + throw new Error("throwIfNotUndefined:" + name); + } + } + static throwIfNumberOutOfRange(value, name, rangeStart, rangeEnd) { + Contracts.throwIfNullOrUndefined(value, name); + if (value < rangeStart || value > rangeEnd) { + throw new Error("throwIfNumberOutOfRange:" + name + " (must be between " + rangeStart.toString() + " and " + rangeEnd.toString() + ")"); + } + } +} +exports.Contracts = Contracts; + + + +/***/ }), +/* 71 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); + + + +/***/ }), +/* 72 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MicAudioSource = exports.AudioWorkletSourceURLPropertyName = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const AudioStreamFormat_js_1 = __webpack_require__(73); +exports.AudioWorkletSourceURLPropertyName = "MICROPHONE-WorkletSourceUrl"; +class MicAudioSource { + constructor(privRecorder, deviceId, audioSourceId, mediaStream) { + this.privRecorder = privRecorder; + this.deviceId = deviceId; + this.privStreams = {}; + this.privOutputChunkSize = MicAudioSource.AUDIOFORMAT.avgBytesPerSec / 10; + this.privId = audioSourceId ? audioSourceId : (0, Exports_js_2.createNoDashGuid)(); + this.privEvents = new Exports_js_2.EventSource(); + this.privMediaStream = mediaStream || null; + this.privIsClosing = false; + } + get format() { + return Promise.resolve(MicAudioSource.AUDIOFORMAT); + } + turnOn() { + if (this.privInitializeDeferral) { + return this.privInitializeDeferral.promise; + } + this.privInitializeDeferral = new Exports_js_2.Deferred(); + try { + this.createAudioContext(); + } + catch (error) { + if (error instanceof Error) { + const typedError = error; + this.privInitializeDeferral.reject(typedError.name + ": " + typedError.message); + } + else { + this.privInitializeDeferral.reject(error); + } + return this.privInitializeDeferral.promise; + } + const nav = window.navigator; + let getUserMedia = ( + // eslint-disable-next-line + nav.getUserMedia || + nav.webkitGetUserMedia || + nav.mozGetUserMedia || + nav.msGetUserMedia); + if (!!nav.mediaDevices) { + getUserMedia = (constraints, successCallback, errorCallback) => { + nav.mediaDevices + .getUserMedia(constraints) + .then(successCallback) + .catch(errorCallback); + }; + } + if (!getUserMedia) { + const errorMsg = "Browser does not support getUserMedia."; + this.privInitializeDeferral.reject(errorMsg); + this.onEvent(new Exports_js_2.AudioSourceErrorEvent(errorMsg, "")); // mic initialized error - no streamid at this point + } + else { + const next = () => { + this.onEvent(new Exports_js_2.AudioSourceInitializingEvent(this.privId)); // no stream id + if (this.privMediaStream && this.privMediaStream.active) { + this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId)); + this.privInitializeDeferral.resolve(); + } + else { + getUserMedia({ audio: this.deviceId ? { deviceId: this.deviceId } : true, video: false }, (mediaStream) => { + this.privMediaStream = mediaStream; + this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId)); + this.privInitializeDeferral.resolve(); + }, (error) => { + const errorMsg = `Error occurred during microphone initialization: ${error}`; + this.privInitializeDeferral.reject(errorMsg); + this.onEvent(new Exports_js_2.AudioSourceErrorEvent(this.privId, errorMsg)); + }); + } + }; + if (this.privContext.state === "suspended") { + // NOTE: On iOS, the Web Audio API requires sounds to be triggered from an explicit user action. + // https://github.com/WebAudio/web-audio-api/issues/790 + this.privContext.resume() + .then(next) + .catch((reason) => { + this.privInitializeDeferral.reject(`Failed to initialize audio context: ${reason}`); + }); + } + else { + next(); + } + } + return this.privInitializeDeferral.promise; + } + id() { + return this.privId; + } + attach(audioNodeId) { + this.onEvent(new Exports_js_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId)); + return this.listen(audioNodeId).then((stream) => { + this.onEvent(new Exports_js_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId)); + return { + detach: async () => { + stream.readEnded(); + delete this.privStreams[audioNodeId]; + this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); + return this.turnOff(); + }, + id: () => audioNodeId, + read: () => stream.read(), + }; + }); + } + detach(audioNodeId) { + if (audioNodeId && this.privStreams[audioNodeId]) { + this.privStreams[audioNodeId].close(); + delete this.privStreams[audioNodeId]; + this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); + } + } + async turnOff() { + for (const streamId in this.privStreams) { + if (streamId) { + const stream = this.privStreams[streamId]; + if (stream) { + stream.close(); + } + } + } + this.onEvent(new Exports_js_2.AudioSourceOffEvent(this.privId)); // no stream now + if (this.privInitializeDeferral) { + // Correctly handle when browser forces mic off before turnOn() completes + // eslint-disable-next-line @typescript-eslint/await-thenable + await this.privInitializeDeferral; + this.privInitializeDeferral = null; + } + await this.destroyAudioContext(); + return; + } + get events() { + return this.privEvents; + } + get deviceInfo() { + return this.getMicrophoneLabel().then((label) => ({ + bitspersample: MicAudioSource.AUDIOFORMAT.bitsPerSample, + channelcount: MicAudioSource.AUDIOFORMAT.channels, + connectivity: Exports_js_1.connectivity.Unknown, + manufacturer: "Speech SDK", + model: label, + samplerate: MicAudioSource.AUDIOFORMAT.samplesPerSec, + type: Exports_js_1.type.Microphones, + })); + } + setProperty(name, value) { + if (name === exports.AudioWorkletSourceURLPropertyName) { + this.privRecorder.setWorkletUrl(value); + } + else { + throw new Error("Property '" + name + "' is not supported on Microphone."); + } + } + getMicrophoneLabel() { + const defaultMicrophoneName = "microphone"; + // If we did this already, return the value. + if (this.privMicrophoneLabel !== undefined) { + return Promise.resolve(this.privMicrophoneLabel); + } + // If the stream isn't currently running, we can't query devices because security. + if (this.privMediaStream === undefined || !this.privMediaStream.active) { + return Promise.resolve(defaultMicrophoneName); + } + // Setup a default + this.privMicrophoneLabel = defaultMicrophoneName; + // Get the id of the device running the audio track. + const microphoneDeviceId = this.privMediaStream.getTracks()[0].getSettings().deviceId; + // If the browser doesn't support getting the device ID, set a default and return. + if (undefined === microphoneDeviceId) { + return Promise.resolve(this.privMicrophoneLabel); + } + const deferred = new Exports_js_2.Deferred(); + // Enumerate the media devices. + navigator.mediaDevices.enumerateDevices().then((devices) => { + for (const device of devices) { + if (device.deviceId === microphoneDeviceId) { + // Found the device + this.privMicrophoneLabel = device.label; + break; + } + } + deferred.resolve(this.privMicrophoneLabel); + }, () => deferred.resolve(this.privMicrophoneLabel)); + return deferred.promise; + } + async listen(audioNodeId) { + await this.turnOn(); + const stream = new Exports_js_2.ChunkedArrayBufferStream(this.privOutputChunkSize, audioNodeId); + this.privStreams[audioNodeId] = stream; + try { + this.privRecorder.record(this.privContext, this.privMediaStream, stream); } - }; - Contracts.throwIfFileDoesNotExist = function (param, name) { - Contracts.throwIfNullOrWhitespace(param, name); - // TODO check for file existence. - }; - Contracts.throwIfNotUndefined = function (param, name) { - if (param !== undefined) { - throw new Error("throwIfNotUndefined:" + name); + catch (error) { + this.onEvent(new Exports_js_2.AudioStreamNodeErrorEvent(this.privId, audioNodeId, error)); + throw error; } - }; - return Contracts; -}()); -exports.Contracts = Contracts; - - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AudioFileWriter = void 0; -var fs = __importStar(__webpack_require__(65)); -var Contracts_1 = __webpack_require__(63); -var AudioFileWriter = /** @class */ (function () { - function AudioFileWriter(filename) { - var _this = this; - this.id = function () { - return _this.privId; - }; - Contracts_1.Contracts.throwIfNullOrUndefined(fs.openSync, "\nFile System access not available, please use Push or PullAudioOutputStream"); - this.privFd = fs.openSync(filename, "w"); + const result = stream; + return result; } - Object.defineProperty(AudioFileWriter.prototype, "format", { - set: function (format) { - Contracts_1.Contracts.throwIfNotUndefined(this.privAudioFormat, "format is already set"); - this.privAudioFormat = format; - var headerOffset = 0; - if (this.privAudioFormat.hasHeader) { - headerOffset = this.privAudioFormat.header.byteLength; - } - if (this.privFd !== undefined) { - this.privWriteStream = fs.createWriteStream("", { fd: this.privFd, start: headerOffset, autoClose: false }); - } - }, - enumerable: false, - configurable: true - }); - AudioFileWriter.prototype.write = function (buffer) { - Contracts_1.Contracts.throwIfNullOrUndefined(this.privAudioFormat, "must set format before writing."); - if (this.privWriteStream !== undefined) { - this.privWriteStream.write(new Uint8Array(buffer.slice(0))); + onEvent(event) { + this.privEvents.onEvent(event); + Exports_js_2.Events.instance.onEvent(event); + } + createAudioContext() { + if (!!this.privContext) { + return; } - }; - AudioFileWriter.prototype.close = function () { - var _this = this; - if (this.privFd !== undefined) { - this.privWriteStream.on("finish", function () { - if (_this.privAudioFormat.hasHeader) { - _this.privAudioFormat.updateHeader(_this.privWriteStream.bytesWritten); - fs.writeSync(_this.privFd, new Int8Array(_this.privAudioFormat.header), 0, _this.privAudioFormat.header.byteLength, 0); - } - fs.closeSync(_this.privFd); - _this.privFd = undefined; - }); - this.privWriteStream.end(); + this.privContext = AudioStreamFormat_js_1.AudioStreamFormatImpl.getAudioContext(MicAudioSource.AUDIOFORMAT.samplesPerSec); + } + async destroyAudioContext() { + if (!this.privContext) { + return; } - }; - return AudioFileWriter; -}()); -exports.AudioFileWriter = AudioFileWriter; - - + this.privRecorder.releaseMediaResources(this.privContext); + // This pattern brought to you by a bug in the TypeScript compiler where it + // confuses the ("close" in this.privContext) with this.privContext always being null as the alternate. + // https://github.com/Microsoft/TypeScript/issues/11498 + let hasClose = false; + if ("close" in this.privContext) { + hasClose = true; + } + if (hasClose) { + if (!this.privIsClosing) { + // The audio context close may take enough time that the close is called twice + this.privIsClosing = true; + await this.privContext.close(); + this.privContext = null; + this.privIsClosing = false; + } + } + else if (null !== this.privContext && this.privContext.state === "running") { + // Suspend actually takes a callback, but analogous to the + // resume method, it'll be only fired if suspend is called + // in a direct response to a user action. The later is not always + // the case, as TurnOff is also called, when we receive an + // end-of-speech message from the service. So, doing a best effort + // fire-and-forget here. + await this.privContext.suspend(); + } + } +} +exports.MicAudioSource = MicAudioSource; +MicAudioSource.AUDIOFORMAT = AudioStreamFormat_js_1.AudioStreamFormat.getDefaultInputFormat(); -/***/ }), -/* 65 */ -/***/ (function(module, exports) { -/* (ignored) */ /***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { +/* 73 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { + // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PullAudioInputStreamImpl = exports.PullAudioInputStream = exports.PushAudioInputStreamImpl = exports.PushAudioInputStream = exports.AudioInputStream = void 0; -// tslint:disable:max-classes-per-file -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Guid_1 = __webpack_require__(7); -var Exports_3 = __webpack_require__(61); -var AudioStreamFormat_1 = __webpack_require__(72); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AudioStreamFormatImpl = exports.AudioStreamFormat = exports.AudioFormatTag = void 0; +// eslint-disable-next-line max-classes-per-file +var AudioFormatTag; +(function (AudioFormatTag) { + AudioFormatTag[AudioFormatTag["PCM"] = 1] = "PCM"; + AudioFormatTag[AudioFormatTag["MuLaw"] = 2] = "MuLaw"; + AudioFormatTag[AudioFormatTag["Siren"] = 3] = "Siren"; + AudioFormatTag[AudioFormatTag["MP3"] = 4] = "MP3"; + AudioFormatTag[AudioFormatTag["SILKSkype"] = 5] = "SILKSkype"; + AudioFormatTag[AudioFormatTag["OGG_OPUS"] = 6] = "OGG_OPUS"; + AudioFormatTag[AudioFormatTag["WEBM_OPUS"] = 7] = "WEBM_OPUS"; + AudioFormatTag[AudioFormatTag["ALaw"] = 8] = "ALaw"; + AudioFormatTag[AudioFormatTag["FLAC"] = 9] = "FLAC"; + AudioFormatTag[AudioFormatTag["OPUS"] = 10] = "OPUS"; + AudioFormatTag[AudioFormatTag["AMR_WB"] = 11] = "AMR_WB"; + AudioFormatTag[AudioFormatTag["G722"] = 12] = "G722"; +})(AudioFormatTag = exports.AudioFormatTag || (exports.AudioFormatTag = {})); /** - * Represents audio input stream used for custom audio input configurations. - * @class AudioInputStream + * Represents audio stream format used for custom audio input configurations. + * @class AudioStreamFormat */ -var AudioInputStream = /** @class */ (function () { - /** - * Creates and initializes an instance. - * @constructor - */ - function AudioInputStream() { - } +class AudioStreamFormat { /** - * Creates a memory backed PushAudioInputStream with the specified audio format. - * @member AudioInputStream.createPushStream + * Creates an audio stream format object representing the default audio stream + * format (16KHz 16bit mono PCM). + * @member AudioStreamFormat.getDefaultInputFormat * @function * @public - * @param {AudioStreamFormat} format - The audio data format in which audio will be - * written to the push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM). - * @returns {PushAudioInputStream} The audio input stream being created. + * @returns {AudioStreamFormat} The audio stream format being created. */ - AudioInputStream.createPushStream = function (format) { - return PushAudioInputStream.create(format); - }; + static getDefaultInputFormat() { + return AudioStreamFormatImpl.getDefaultInputFormat(); + } /** - * Creates a PullAudioInputStream that delegates to the specified callback interface for read() - * and close() methods. - * @member AudioInputStream.createPullStream + * Creates an audio stream format object with the specified format characteristics. + * @member AudioStreamFormat.getWaveFormat * @function * @public - * @param {PullAudioInputStreamCallback} callback - The custom audio input object, derived from - * PullAudioInputStreamCallback - * @param {AudioStreamFormat} format - The audio data format in which audio will be returned from - * the callback's read() method (Required if format is not 16 kHz 16bit mono PCM). - * @returns {PullAudioInputStream} The audio input stream being created. + * @param {number} samplesPerSecond - Sample rate, in samples per second (Hertz). + * @param {number} bitsPerSample - Bits per sample, typically 16. + * @param {number} channels - Number of channels in the waveform-audio data. Monaural data + * uses one channel and stereo data uses two channels. + * @param {AudioFormatTag} format - Audio format (PCM, alaw or mulaw). + * @returns {AudioStreamFormat} The audio stream format being created. */ - AudioInputStream.createPullStream = function (callback, format) { - return PullAudioInputStream.create(callback, format); - // throw new Error("Oops"); - }; - return AudioInputStream; -}()); -exports.AudioInputStream = AudioInputStream; -/** - * Represents memory backed push audio input stream used for custom audio input configurations. - * @class PushAudioInputStream - */ -var PushAudioInputStream = /** @class */ (function (_super) { - __extends(PushAudioInputStream, _super); - function PushAudioInputStream() { - return _super !== null && _super.apply(this, arguments) || this; + static getWaveFormat(samplesPerSecond, bitsPerSample, channels, format) { + return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels, format); } /** - * Creates a memory backed PushAudioInputStream with the specified audio format. - * @member PushAudioInputStream.create + * Creates an audio stream format object with the specified pcm waveformat characteristics. + * @member AudioStreamFormat.getWaveFormatPCM * @function * @public - * @param {AudioStreamFormat} format - The audio data format in which audio will be written to the - * push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM). - * @returns {PushAudioInputStream} The push audio input stream being created. + * @param {number} samplesPerSecond - Sample rate, in samples per second (Hertz). + * @param {number} bitsPerSample - Bits per sample, typically 16. + * @param {number} channels - Number of channels in the waveform-audio data. Monaural data + * uses one channel and stereo data uses two channels. + * @returns {AudioStreamFormat} The audio stream format being created. */ - PushAudioInputStream.create = function (format) { - return new PushAudioInputStreamImpl(format); - }; - return PushAudioInputStream; -}(AudioInputStream)); -exports.PushAudioInputStream = PushAudioInputStream; + static getWaveFormatPCM(samplesPerSecond, bitsPerSample, channels) { + return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels); + } +} +exports.AudioStreamFormat = AudioStreamFormat; /** - * Represents memory backed push audio input stream used for custom audio input configurations. * @private - * @class PushAudioInputStreamImpl + * @class AudioStreamFormatImpl */ -var PushAudioInputStreamImpl = /** @class */ (function (_super) { - __extends(PushAudioInputStreamImpl, _super); +class AudioStreamFormatImpl extends AudioStreamFormat { /** - * Creates and initalizes an instance with the given values. + * Creates an instance with the given values. * @constructor - * @param {AudioStreamFormat} format - The audio stream format. + * @param {number} samplesPerSec - Samples per second. + * @param {number} bitsPerSample - Bits per sample. + * @param {number} channels - Number of channels. + * @param {AudioFormatTag} format - Audio format (PCM, alaw or mulaw). */ - function PushAudioInputStreamImpl(format) { - var _this = _super.call(this) || this; - _this.onEvent = function (event) { - _this.privEvents.onEvent(event); - Exports_2.Events.instance.onEvent(event); - }; - if (format === undefined) { - _this.privFormat = AudioStreamFormat_1.AudioStreamFormatImpl.getDefaultInputFormat(); + constructor(samplesPerSec = 16000, bitsPerSample = 16, channels = 1, format = AudioFormatTag.PCM) { + super(); + let isWavFormat = true; + /* 1 for PCM; 6 for alaw; 7 for mulaw */ + switch (format) { + case AudioFormatTag.PCM: + this.formatTag = 1; + break; + case AudioFormatTag.ALaw: + this.formatTag = 6; + break; + case AudioFormatTag.MuLaw: + this.formatTag = 7; + break; + default: + isWavFormat = false; } - else { - _this.privFormat = format; - } - _this.privEvents = new Exports_2.EventSource(); - _this.privId = Guid_1.createNoDashGuid(); - _this.privStream = new Exports_2.ChunkedArrayBufferStream(_this.privFormat.avgBytesPerSec / 10); - return _this; - } - Object.defineProperty(PushAudioInputStreamImpl.prototype, "format", { - /** - * Format information for the audio - */ - get: function () { - return Promise.resolve(this.privFormat); - }, - enumerable: false, - configurable: true - }); - /** - * Writes the audio data specified by making an internal copy of the data. - * @member PushAudioInputStreamImpl.prototype.write - * @function - * @public - * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy. - */ - PushAudioInputStreamImpl.prototype.write = function (dataBuffer) { - this.privStream.writeStreamChunk({ - buffer: dataBuffer, - isEnd: false, - timeReceived: Date.now() - }); - }; - /** - * Closes the stream. - * @member PushAudioInputStreamImpl.prototype.close - * @function - * @public - */ - PushAudioInputStreamImpl.prototype.close = function () { - this.privStream.close(); - }; - PushAudioInputStreamImpl.prototype.id = function () { - return this.privId; - }; - Object.defineProperty(PushAudioInputStreamImpl.prototype, "blob", { - get: function () { - var _this = this; - return this.attach("id").then(function (audioNode) { - var data = []; - var bufferData = Buffer.from(""); - var readCycle = function () { - return audioNode.read().then(function (audioStreamChunk) { - if (!audioStreamChunk || audioStreamChunk.isEnd) { - if (typeof (XMLHttpRequest) !== "undefined" && typeof (Blob) !== "undefined") { - return Promise.resolve(new Blob(data)); - } - else { - return Promise.resolve(Buffer.from(bufferData)); - } - } - else { - if (typeof (Blob) !== "undefined") { - data.push(audioStreamChunk.buffer); - } - else { - bufferData = Buffer.concat([bufferData, _this.toBuffer(audioStreamChunk.buffer)]); - } - return readCycle(); - } - }); - }; - return readCycle(); - }); - }, - enumerable: false, - configurable: true - }); - PushAudioInputStreamImpl.prototype.turnOn = function () { - this.onEvent(new Exports_2.AudioSourceInitializingEvent(this.privId)); // no stream id - this.onEvent(new Exports_2.AudioSourceReadyEvent(this.privId)); - return; - }; - PushAudioInputStreamImpl.prototype.attach = function (audioNodeId) { - return __awaiter(this, void 0, void 0, function () { - var stream; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.onEvent(new Exports_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId)); - return [4 /*yield*/, this.turnOn()]; - case 1: - _a.sent(); - stream = this.privStream; - this.onEvent(new Exports_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId)); - return [2 /*return*/, { - detach: function () { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); - return [2 /*return*/, this.turnOff()]; - }); - }); }, - id: function () { - return audioNodeId; - }, - read: function () { - return stream.read(); - }, - }]; - } - }); - }); - }; - PushAudioInputStreamImpl.prototype.detach = function (audioNodeId) { - this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); - }; - PushAudioInputStreamImpl.prototype.turnOff = function () { - return; - }; - Object.defineProperty(PushAudioInputStreamImpl.prototype, "events", { - get: function () { - return this.privEvents; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PushAudioInputStreamImpl.prototype, "deviceInfo", { - get: function () { - return Promise.resolve({ - bitspersample: this.privFormat.bitsPerSample, - channelcount: this.privFormat.channels, - connectivity: Exports_1.connectivity.Unknown, - manufacturer: "Speech SDK", - model: "PushStream", - samplerate: this.privFormat.samplesPerSec, - type: Exports_1.type.Stream, - }); - }, - enumerable: false, - configurable: true - }); - PushAudioInputStreamImpl.prototype.toBuffer = function (arrayBuffer) { - var buf = Buffer.alloc(arrayBuffer.byteLength); - var view = new Uint8Array(arrayBuffer); - for (var i = 0; i < buf.length; ++i) { - buf[i] = view[i]; + this.bitsPerSample = bitsPerSample; + this.samplesPerSec = samplesPerSec; + this.channels = channels; + this.avgBytesPerSec = this.samplesPerSec * this.channels * (this.bitsPerSample / 8); + this.blockAlign = this.channels * Math.max(this.bitsPerSample, 8); + if (isWavFormat) { + this.privHeader = new ArrayBuffer(44); + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView + const view = new DataView(this.privHeader); + /* RIFF identifier */ + this.setString(view, 0, "RIFF"); + /* file length */ + view.setUint32(4, 0, true); + /* RIFF type & Format */ + this.setString(view, 8, "WAVEfmt "); + /* format chunk length */ + view.setUint32(16, 16, true); + /* audio format */ + view.setUint16(20, this.formatTag, true); + /* channel count */ + view.setUint16(22, this.channels, true); + /* sample rate */ + view.setUint32(24, this.samplesPerSec, true); + /* byte rate (sample rate * block align) */ + view.setUint32(28, this.avgBytesPerSec, true); + /* block align (channel count * bytes per sample) */ + view.setUint16(32, this.channels * (this.bitsPerSample / 8), true); + /* bits per sample */ + view.setUint16(34, this.bitsPerSample, true); + /* data chunk identifier */ + this.setString(view, 36, "data"); + /* data chunk length */ + view.setUint32(40, 0, true); } - return buf; - }; - return PushAudioInputStreamImpl; -}(PushAudioInputStream)); -exports.PushAudioInputStreamImpl = PushAudioInputStreamImpl; -/* - * Represents audio input stream used for custom audio input configurations. - * @class PullAudioInputStream - */ -var PullAudioInputStream = /** @class */ (function (_super) { - __extends(PullAudioInputStream, _super); - /** - * Creates and initializes and instance. - * @constructor - */ - function PullAudioInputStream() { - return _super.call(this) || this; } /** - * Creates a PullAudioInputStream that delegates to the specified callback interface for - * read() and close() methods, using the default format (16 kHz 16bit mono PCM). - * @member PullAudioInputStream.create - * @function - * @public - * @param {PullAudioInputStreamCallback} callback - The custom audio input object, - * derived from PullAudioInputStreamCustomCallback - * @param {AudioStreamFormat} format - The audio data format in which audio will be - * returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM). - * @returns {PullAudioInputStream} The push audio input stream being created. + * Retrieves the default input format. + * @member AudioStreamFormatImpl.getDefaultInputFormat + * @function + * @public + * @returns {AudioStreamFormatImpl} The default input format. */ - PullAudioInputStream.create = function (callback, format) { - return new PullAudioInputStreamImpl(callback, format); - }; - return PullAudioInputStream; -}(AudioInputStream)); -exports.PullAudioInputStream = PullAudioInputStream; -/** - * Represents audio input stream used for custom audio input configurations. - * @private - * @class PullAudioInputStreamImpl - */ -var PullAudioInputStreamImpl = /** @class */ (function (_super) { - __extends(PullAudioInputStreamImpl, _super); + static getDefaultInputFormat() { + return new AudioStreamFormatImpl(); + } /** - * Creates a PullAudioInputStream that delegates to the specified callback interface for - * read() and close() methods, using the default format (16 kHz 16bit mono PCM). - * @constructor - * @param {PullAudioInputStreamCallback} callback - The custom audio input object, - * derived from PullAudioInputStreamCustomCallback - * @param {AudioStreamFormat} format - The audio data format in which audio will be - * returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM). + * Creates an audio context appropriate to current browser + * @member AudioStreamFormatImpl.getAudioContext + * @function + * @public + * @returns {AudioContext} An audio context instance */ - function PullAudioInputStreamImpl(callback, format) { - var _this = _super.call(this) || this; - _this.onEvent = function (event) { - _this.privEvents.onEvent(event); - Exports_2.Events.instance.onEvent(event); - }; - if (undefined === format) { - _this.privFormat = Exports_3.AudioStreamFormat.getDefaultInputFormat(); + /* eslint-disable */ + static getAudioContext(sampleRate) { + // Workaround for Speech SDK bug in Safari. + const AudioContext = window.AudioContext // our preferred impl + || window.webkitAudioContext // fallback, mostly when on Safari + || false; // could not find. + // https://developer.mozilla.org/en-US/docs/Web/API/AudioContext + if (!!AudioContext) { + if (sampleRate !== undefined && navigator.mediaDevices.getSupportedConstraints().sampleRate) { + return new AudioContext({ sampleRate }); + } + else { + return new AudioContext(); + } } else { - _this.privFormat = format; - } - _this.privEvents = new Exports_2.EventSource(); - _this.privId = Guid_1.createNoDashGuid(); - _this.privCallback = callback; - _this.privIsClosed = false; - _this.privBufferSize = _this.privFormat.avgBytesPerSec / 10; - return _this; - } - Object.defineProperty(PullAudioInputStreamImpl.prototype, "format", { - /** - * Format information for the audio - */ - get: function () { - return Promise.resolve(this.privFormat); - }, - enumerable: false, - configurable: true - }); + throw new Error("Browser does not support Web Audio API (AudioContext is not available)."); + } + } + /* eslint-enable */ /** - * Closes the stream. - * @member PullAudioInputStreamImpl.prototype.close + * Closes the configuration object. + * @member AudioStreamFormatImpl.prototype.close * @function * @public */ - PullAudioInputStreamImpl.prototype.close = function () { - this.privIsClosed = true; - this.privCallback.close(); - }; - PullAudioInputStreamImpl.prototype.id = function () { - return this.privId; - }; - Object.defineProperty(PullAudioInputStreamImpl.prototype, "blob", { - get: function () { - return Promise.reject("Not implemented"); - }, - enumerable: false, - configurable: true - }); - PullAudioInputStreamImpl.prototype.turnOn = function () { - this.onEvent(new Exports_2.AudioSourceInitializingEvent(this.privId)); // no stream id - this.onEvent(new Exports_2.AudioSourceReadyEvent(this.privId)); - return; - }; - PullAudioInputStreamImpl.prototype.attach = function (audioNodeId) { - return __awaiter(this, void 0, void 0, function () { - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.onEvent(new Exports_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId)); - return [4 /*yield*/, this.turnOn()]; - case 1: - _a.sent(); - this.onEvent(new Exports_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId)); - return [2 /*return*/, { - detach: function () { - _this.privCallback.close(); - _this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(_this.privId, audioNodeId)); - return _this.turnOff(); - }, - id: function () { - return audioNodeId; - }, - read: function () { - var totalBytes = 0; - var transmitBuff; - // Until we have the minimum number of bytes to send in a transmission, keep asking for more. - while (totalBytes < _this.privBufferSize) { - // Sizing the read buffer to the delta between the perfect size and what's left means we won't ever get too much - // data back. - var readBuff = new ArrayBuffer(_this.privBufferSize - totalBytes); - var pulledBytes = _this.privCallback.read(readBuff); - // If there is no return buffer yet defined, set the return buffer to the that was just populated. - // This was, if we have enough data there's no copy penalty, but if we don't we have a buffer that's the - // preferred size allocated. - if (undefined === transmitBuff) { - transmitBuff = readBuff; - } - else { - // Not the first bite at the apple, so fill the return buffer with the data we got back. - var intView = new Int8Array(transmitBuff); - intView.set(new Int8Array(readBuff), totalBytes); - } - // If there are no bytes to read, just break out and be done. - if (0 === pulledBytes) { - break; - } - totalBytes += pulledBytes; - } - return Promise.resolve({ - buffer: transmitBuff.slice(0, totalBytes), - isEnd: _this.privIsClosed || totalBytes === 0, - timeReceived: Date.now(), - }); - }, - }]; - } - }); - }); - }; - PullAudioInputStreamImpl.prototype.detach = function (audioNodeId) { - this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); - }; - PullAudioInputStreamImpl.prototype.turnOff = function () { + close() { return; - }; - Object.defineProperty(PullAudioInputStreamImpl.prototype, "events", { - get: function () { - return this.privEvents; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PullAudioInputStreamImpl.prototype, "deviceInfo", { - get: function () { - return Promise.resolve({ - bitspersample: this.privFormat.bitsPerSample, - channelcount: this.privFormat.channels, - connectivity: Exports_1.connectivity.Unknown, - manufacturer: "Speech SDK", - model: "PullStream", - samplerate: this.privFormat.samplesPerSec, - type: Exports_1.type.Stream, - }); - }, - enumerable: false, - configurable: true - }); - return PullAudioInputStreamImpl; -}(PullAudioInputStream)); -exports.PullAudioInputStreamImpl = PullAudioInputStreamImpl; + } + get header() { + return this.privHeader; + } + setString(view, offset, str) { + for (let i = 0; i < str.length; i++) { + view.setUint8(offset + i, str.charCodeAt(i)); + } + } +} +exports.AudioStreamFormatImpl = AudioStreamFormatImpl; -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(67).Buffer)) /***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { +/* 74 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - - - -var base64 = __webpack_require__(69) -var ieee754 = __webpack_require__(70) -var isArray = __webpack_require__(71) - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() - -function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -} - -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} - -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileAudioSource = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const AudioStreamFormat_js_1 = __webpack_require__(73); +class FileAudioSource { + constructor(file, filename, audioSourceId) { + this.privStreams = {}; + this.privHeaderEnd = 44; + this.privId = audioSourceId ? audioSourceId : (0, Exports_js_2.createNoDashGuid)(); + this.privEvents = new Exports_js_2.EventSource(); + this.privSource = file; + if (typeof window !== "undefined" && typeof Blob !== "undefined" && this.privSource instanceof Blob) { + this.privFilename = file.name; + } + else { + this.privFilename = filename || "unknown.wav"; + } + // Read the header. + this.privAudioFormatPromise = this.readHeader(); } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) -} - -Buffer.poolSize = 8192 // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr -} - -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} - -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } -} - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} - -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -} - -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 + get format() { + return this.privAudioFormatPromise; } - } - return that -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -} - -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that -} - -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that -} - -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that + turnOn() { + if (this.privFilename.lastIndexOf(".wav") !== this.privFilename.length - 4) { + const errorMsg = this.privFilename + " is not supported. Only WAVE files are allowed at the moment."; + this.onEvent(new Exports_js_2.AudioSourceErrorEvent(errorMsg, "")); + return Promise.reject(errorMsg); + } + this.onEvent(new Exports_js_2.AudioSourceInitializingEvent(this.privId)); // no stream id + this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId)); + return; } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) + id() { + return this.privId; } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) + async attach(audioNodeId) { + this.onEvent(new Exports_js_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId)); + const stream = await this.upload(audioNodeId); + this.onEvent(new Exports_js_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId)); + return Promise.resolve({ + detach: async () => { + stream.readEnded(); + delete this.privStreams[audioNodeId]; + this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); + await this.turnOff(); + }, + id: () => audioNodeId, + read: () => stream.read(), + }); } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} - -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) -} - -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break + detach(audioNodeId) { + if (audioNodeId && this.privStreams[audioNodeId]) { + this.privStreams[audioNodeId].close(); + delete this.privStreams[audioNodeId]; + this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); + } } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length + turnOff() { + for (const streamId in this.privStreams) { + if (streamId) { + const stream = this.privStreams[streamId]; + if (stream && !stream.isClosed) { + stream.close(); + } + } + } + this.onEvent(new Exports_js_2.AudioSourceOffEvent(this.privId)); // no stream now + return Promise.resolve(); } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') + get events() { + return this.privEvents; + } + get deviceInfo() { + return this.privAudioFormatPromise.then((result) => (Promise.resolve({ + bitspersample: result.bitsPerSample, + channelcount: result.channels, + connectivity: Exports_js_1.connectivity.Unknown, + manufacturer: "Speech SDK", + model: "File", + samplerate: result.samplesPerSec, + type: Exports_js_1.type.File, + }))); + } + readHeader() { + // Read the wave header. + const maxHeaderSize = 4296; + const header = this.privSource.slice(0, maxHeaderSize); + const headerResult = new Exports_js_2.Deferred(); + const processHeader = (header) => { + const view = new DataView(header); + const getWord = (index) => String.fromCharCode(view.getUint8(index), view.getUint8(index + 1), view.getUint8(index + 2), view.getUint8(index + 3)); + // RIFF 4 bytes. + if ("RIFF" !== getWord(0)) { + headerResult.reject("Invalid WAV header in file, RIFF was not found"); + return; + } + // length, 4 bytes + // RIFF Type & fmt 8 bytes + if ("WAVE" !== getWord(8) || "fmt " !== getWord(12)) { + headerResult.reject("Invalid WAV header in file, WAVEfmt was not found"); + return; + } + const formatSize = view.getInt32(16, true); + const channelCount = view.getUint16(22, true); + const sampleRate = view.getUint32(24, true); + const bitsPerSample = view.getUint16(34, true); + // Confirm if header is 44 bytes long. + let pos = 36 + Math.max(formatSize - 16, 0); + for (; getWord(pos) !== "data"; pos += 2) { + if (pos > maxHeaderSize - 8) { + headerResult.reject("Invalid WAV header in file, data block was not found"); + return; + } + } + this.privHeaderEnd = pos + 8; + headerResult.resolve(AudioStreamFormat_js_1.AudioStreamFormat.getWaveFormatPCM(sampleRate, bitsPerSample, channelCount)); + }; + if (typeof window !== "undefined" && typeof Blob !== "undefined" && header instanceof Blob) { + const reader = new FileReader(); + reader.onload = (event) => { + const header = event.target.result; + processHeader(header); + }; + reader.readAsArrayBuffer(header); + } + else { + const h = header; + processHeader(h.buffer.slice(h.byteOffset, h.byteOffset + h.byteLength)); + } + return headerResult.promise; + } + async upload(audioNodeId) { + const onerror = (error) => { + const errorMsg = `Error occurred while processing '${this.privFilename}'. ${error}`; + this.onEvent(new Exports_js_2.AudioStreamNodeErrorEvent(this.privId, audioNodeId, errorMsg)); + throw new Error(errorMsg); + }; + try { + await this.turnOn(); + const format = await this.privAudioFormatPromise; + const stream = new Exports_js_2.ChunkedArrayBufferStream(format.avgBytesPerSec / 10, audioNodeId); + this.privStreams[audioNodeId] = stream; + const chunk = this.privSource.slice(this.privHeaderEnd); + const processFile = (buff) => { + if (stream.isClosed) { + return; // output stream was closed (somebody called TurnOff). We're done here. + } + stream.writeStreamChunk({ + buffer: buff, + isEnd: false, + timeReceived: Date.now(), + }); + stream.close(); + }; + if (typeof window !== "undefined" && typeof Blob !== "undefined" && chunk instanceof Blob) { + const reader = new FileReader(); + reader.onerror = (ev) => onerror(ev.toString()); + reader.onload = (event) => { + const fileBuffer = event.target.result; + processFile(fileBuffer); + }; + reader.readAsArrayBuffer(chunk); + } + else { + const c = chunk; + processFile(c.buffer.slice(c.byteOffset, c.byteOffset + c.byteLength)); + } + return stream; + } + catch (e) { + onerror(e); + } } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true + onEvent(event) { + this.privEvents.onEvent(event); + Exports_js_2.Events.instance.onEvent(event); } - } } -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) +exports.FileAudioSource = FileAudioSource; - case 'ascii': - return asciiSlice(this, start, end) - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - case 'base64': - return base64Slice(this, start, end) +/***/ }), +/* 75 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) +"use strict"; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PcmRecorder = void 0; +const Exports_1 = __webpack_require__(4); +class PcmRecorder { + constructor(stopInputOnRelease) { + this.privStopInputOnRelease = stopInputOnRelease; + } + record(context, mediaStream, outputStream) { + const desiredSampleRate = 16000; + const waveStreamEncoder = new Exports_1.RiffPcmEncoder(context.sampleRate, desiredSampleRate); + const micInput = context.createMediaStreamSource(mediaStream); + const attachScriptProcessor = () => { + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + const scriptNode = (() => { + let bufferSize = 0; + try { + return context.createScriptProcessor(bufferSize, 1, 1); + } + catch (error) { + // Webkit (<= version 31) requires a valid bufferSize. + bufferSize = 2048; + let audioSampleRate = context.sampleRate; + while (bufferSize < 16384 && audioSampleRate >= (2 * desiredSampleRate)) { + bufferSize <<= 1; + audioSampleRate >>= 1; + } + return context.createScriptProcessor(bufferSize, 1, 1); + } + })(); + scriptNode.onaudioprocess = (event) => { + const inputFrame = event.inputBuffer.getChannelData(0); + if (outputStream && !outputStream.isClosed) { + const waveFrame = waveStreamEncoder.encode(inputFrame); + if (!!waveFrame) { + outputStream.writeStreamChunk({ + buffer: waveFrame, + isEnd: false, + timeReceived: Date.now(), + }); + } + } + }; + micInput.connect(scriptNode); + scriptNode.connect(context.destination); + this.privMediaResources = { + scriptProcessorNode: scriptNode, + source: micInput, + stream: mediaStream, + }; + }; + // https://webaudio.github.io/web-audio-api/#audioworklet + // Using AudioWorklet to improve audio quality and avoid audio glitches due to blocking the UI thread + const skipAudioWorklet = !!this.privSpeechProcessorScript && this.privSpeechProcessorScript.toLowerCase() === "ignore"; + if (!!context.audioWorklet && !skipAudioWorklet) { + if (!this.privSpeechProcessorScript) { + const workletScript = `class SP extends AudioWorkletProcessor { + constructor(options) { + super(options); + } + process(inputs, outputs) { + const input = inputs[0]; + const output = []; + for (let channel = 0; channel < input.length; channel += 1) { + output[channel] = input[channel]; + } + this.port.postMessage(output[0]); + return true; + } + } + registerProcessor('speech-processor', SP);`; + const blob = new Blob([workletScript], { type: "application/javascript; charset=utf-8" }); + this.privSpeechProcessorScript = URL.createObjectURL(blob); + } + context.audioWorklet + .addModule(this.privSpeechProcessorScript) + .then(() => { + const workletNode = new AudioWorkletNode(context, "speech-processor"); + workletNode.port.onmessage = (ev) => { + const inputFrame = ev.data; + if (outputStream && !outputStream.isClosed) { + const waveFrame = waveStreamEncoder.encode(inputFrame); + if (!!waveFrame) { + outputStream.writeStreamChunk({ + buffer: waveFrame, + isEnd: false, + timeReceived: Date.now(), + }); + } + } + }; + micInput.connect(workletNode); + workletNode.connect(context.destination); + this.privMediaResources = { + scriptProcessorNode: workletNode, + source: micInput, + stream: mediaStream, + }; + }) + .catch(() => { + attachScriptProcessor(); + }); + } + else { + try { + attachScriptProcessor(); + } + catch (err) { + throw new Error(`Unable to start audio worklet node for PCMRecorder: ${err}`); + } + } + } + releaseMediaResources(context) { + if (this.privMediaResources) { + if (this.privMediaResources.scriptProcessorNode) { + this.privMediaResources.scriptProcessorNode.disconnect(context.destination); + this.privMediaResources.scriptProcessorNode = null; + } + if (this.privMediaResources.source) { + this.privMediaResources.source.disconnect(); + if (this.privStopInputOnRelease) { + this.privMediaResources.stream.getTracks().forEach((track) => track.stop()); + } + this.privMediaResources.source = null; + } + } + } + setWorkletUrl(url) { + this.privSpeechProcessorScript = url; } - } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this } +exports.PcmRecorder = PcmRecorder; -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} +/***/ }), +/* 76 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} +"use strict"; -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebsocketConnection = void 0; +const Exports_js_1 = __webpack_require__(4); +const WebsocketMessageAdapter_js_1 = __webpack_require__(77); +class WebsocketConnection { + constructor(uri, queryParameters, headers, messageFormatter, proxyInfo, enableCompression = false, connectionId) { + this.privIsDisposed = false; + if (!uri) { + throw new Exports_js_1.ArgumentNullError("uri"); + } + if (!messageFormatter) { + throw new Exports_js_1.ArgumentNullError("messageFormatter"); + } + this.privMessageFormatter = messageFormatter; + let queryParams = ""; + let i = 0; + if (queryParameters) { + for (const paramName in queryParameters) { + if (paramName) { + queryParams += ((i === 0) && (uri.indexOf("?") === -1)) ? "?" : "&"; + const key = encodeURIComponent(paramName); + queryParams += key; + let val = queryParameters[paramName]; + if (val) { + val = encodeURIComponent(val); + queryParams += `=${val}`; + } + i++; + } + } + } + if (headers) { + for (const headerName in headers) { + if (headerName) { + queryParams += ((i === 0) && (uri.indexOf("?") === -1)) ? "?" : "&"; + const val = encodeURIComponent(headers[headerName]); + queryParams += `${headerName}=${val}`; + i++; + } + } + } + this.privUri = uri + queryParams; + this.privId = connectionId ? connectionId : (0, Exports_js_1.createNoDashGuid)(); + this.privConnectionMessageAdapter = new WebsocketMessageAdapter_js_1.WebsocketMessageAdapter(this.privUri, this.id, this.privMessageFormatter, proxyInfo, headers, enableCompression); + } + async dispose() { + this.privIsDisposed = true; + if (this.privConnectionMessageAdapter) { + await this.privConnectionMessageAdapter.close(); + } + } + isDisposed() { + return this.privIsDisposed; + } + get id() { + return this.privId; + } + get uri() { + return this.privUri; + } + state() { + return this.privConnectionMessageAdapter.state; + } + open() { + return this.privConnectionMessageAdapter.open(); + } + send(message) { + return this.privConnectionMessageAdapter.send(message); + } + read() { + return this.privConnectionMessageAdapter.read(); + } + get events() { + return this.privConnectionMessageAdapter.events; + } } +exports.WebsocketConnection = WebsocketConnection; -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - if (this === target) return 0 - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) +/***/ }), +/* 77 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) +"use strict"; - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebsocketMessageAdapter = void 0; +const net = __importStar(__webpack_require__(78)); +const tls = __importStar(__webpack_require__(79)); +const agent_base_1 = __importDefault(__webpack_require__(80)); +const https_proxy_agent_1 = __importDefault(__webpack_require__(81)); +const ws_1 = __importDefault(__webpack_require__(82)); +const HeaderNames_js_1 = __webpack_require__(59); +const Exports_js_1 = __webpack_require__(4); +class WebsocketMessageAdapter { + constructor(uri, connectionId, messageFormatter, proxyInfo, headers, enableCompression) { + if (!uri) { + throw new Exports_js_1.ArgumentNullError("uri"); + } + if (!messageFormatter) { + throw new Exports_js_1.ArgumentNullError("messageFormatter"); + } + this.proxyInfo = proxyInfo; + this.privConnectionEvents = new Exports_js_1.EventSource(); + this.privConnectionId = connectionId; + this.privMessageFormatter = messageFormatter; + this.privConnectionState = Exports_js_1.ConnectionState.None; + this.privUri = uri; + this.privHeaders = headers; + this.privEnableCompression = enableCompression; + // Add the connection ID to the headers + this.privHeaders[HeaderNames_js_1.HeaderNames.ConnectionId] = this.privConnectionId; + this.privHeaders.connectionId = this.privConnectionId; + this.privLastErrorReceived = ""; } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } + get state() { + return this.privConnectionState; } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 + open() { + if (this.privConnectionState === Exports_js_1.ConnectionState.Disconnected) { + return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`); + } + if (this.privConnectionEstablishDeferral) { + return this.privConnectionEstablishDeferral.promise; + } + this.privConnectionEstablishDeferral = new Exports_js_1.Deferred(); + this.privCertificateValidatedDeferral = new Exports_js_1.Deferred(); + this.privConnectionState = Exports_js_1.ConnectionState.Connecting; + try { + const proxyConfiguredInNode = typeof window === "undefined" && !!this.proxyInfo?.HostName; + if (typeof WebSocket !== "undefined" && !WebsocketMessageAdapter.forceNpmWebSocket && !proxyConfiguredInNode) { + // Browser handles cert checks. + this.privCertificateValidatedDeferral.resolve(); + this.privWebsocketClient = new WebSocket(this.privUri); + } + else { + // Workaround for https://github.com/microsoft/cognitive-services-speech-sdk-js/issues/465 + // Which is root caused by https://github.com/TooTallNate/node-agent-base/issues/61 + const uri = new URL(this.privUri); + let protocol = uri.protocol; + if (protocol?.toLocaleLowerCase() === "wss:") { + protocol = "https:"; + } + else if (protocol?.toLocaleLowerCase() === "ws:") { + protocol = "http:"; + } + const options = { headers: this.privHeaders, perMessageDeflate: this.privEnableCompression, followRedirects: protocol.toLocaleLowerCase() === "https:" }; + // The ocsp library will handle validation for us and fail the connection if needed. + this.privCertificateValidatedDeferral.resolve(); + options.agent = this.getAgent(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + options.agent.protocol = protocol; + this.privWebsocketClient = new ws_1.default(this.privUri, options); + this.privWebsocketClient.on("redirect", (redirectUrl) => { + const event = new Exports_js_1.ConnectionRedirectEvent(this.privConnectionId, redirectUrl, this.privUri, `Getting redirect URL from endpoint ${this.privUri} with redirect URL '${redirectUrl}'`); + Exports_js_1.Events.instance.onEvent(event); + }); + } + this.privWebsocketClient.binaryType = "arraybuffer"; + this.privReceivingMessageQueue = new Exports_js_1.Queue(); + this.privDisconnectDeferral = new Exports_js_1.Deferred(); + this.privSendMessageQueue = new Exports_js_1.Queue(); + this.processSendQueue().catch((reason) => { + Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason)); + }); + } + catch (error) { + this.privConnectionEstablishDeferral.resolve(new Exports_js_1.ConnectionOpenResponse(500, error)); + return this.privConnectionEstablishDeferral.promise; + } + this.onEvent(new Exports_js_1.ConnectionStartEvent(this.privConnectionId, this.privUri)); + this.privWebsocketClient.onopen = () => { + this.privCertificateValidatedDeferral.promise.then(() => { + this.privConnectionState = Exports_js_1.ConnectionState.Connected; + this.onEvent(new Exports_js_1.ConnectionEstablishedEvent(this.privConnectionId)); + this.privConnectionEstablishDeferral.resolve(new Exports_js_1.ConnectionOpenResponse(200, "")); + }, (error) => { + this.privConnectionEstablishDeferral.reject(error); + }); + }; + this.privWebsocketClient.onerror = (e) => { + this.onEvent(new Exports_js_1.ConnectionErrorEvent(this.privConnectionId, e.message, e.type)); + this.privLastErrorReceived = e.message; + }; + this.privWebsocketClient.onclose = (e) => { + if (this.privConnectionState === Exports_js_1.ConnectionState.Connecting) { + this.privConnectionState = Exports_js_1.ConnectionState.Disconnected; + // this.onEvent(new ConnectionEstablishErrorEvent(this.connectionId, e.code, e.reason)); + this.privConnectionEstablishDeferral.resolve(new Exports_js_1.ConnectionOpenResponse(e.code, e.reason + " " + this.privLastErrorReceived)); + } + else { + this.privConnectionState = Exports_js_1.ConnectionState.Disconnected; + this.privWebsocketClient = null; + this.onEvent(new Exports_js_1.ConnectionClosedEvent(this.privConnectionId, e.code, e.reason)); + } + this.onClose(e.code, e.reason).catch((reason) => { + Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason)); + }); + }; + this.privWebsocketClient.onmessage = (e) => { + const networkReceivedTime = new Date().toISOString(); + if (this.privConnectionState === Exports_js_1.ConnectionState.Connected) { + const deferred = new Exports_js_1.Deferred(); + // let id = ++this.idCounter; + this.privReceivingMessageQueue.enqueueFromPromise(deferred.promise); + if (e.data instanceof ArrayBuffer) { + const rawMessage = new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Binary, e.data); + this.privMessageFormatter + .toConnectionMessage(rawMessage) + .then((connectionMessage) => { + this.onEvent(new Exports_js_1.ConnectionMessageReceivedEvent(this.privConnectionId, networkReceivedTime, connectionMessage)); + deferred.resolve(connectionMessage); + }, (error) => { + // TODO: Events for these ? + deferred.reject(`Invalid binary message format. Error: ${error}`); + }); + } + else { + const rawMessage = new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Text, e.data); + this.privMessageFormatter + .toConnectionMessage(rawMessage) + .then((connectionMessage) => { + this.onEvent(new Exports_js_1.ConnectionMessageReceivedEvent(this.privConnectionId, networkReceivedTime, connectionMessage)); + deferred.resolve(connectionMessage); + }, (error) => { + // TODO: Events for these ? + deferred.reject(`Invalid text message format. Error: ${error}`); + }); + } + } + }; + return this.privConnectionEstablishDeferral.promise; + } + send(message) { + if (this.privConnectionState !== Exports_js_1.ConnectionState.Connected) { + return Promise.reject(`Cannot send on connection that is in ${Exports_js_1.ConnectionState[this.privConnectionState]} state`); + } + const messageSendStatusDeferral = new Exports_js_1.Deferred(); + const messageSendDeferral = new Exports_js_1.Deferred(); + this.privSendMessageQueue.enqueueFromPromise(messageSendDeferral.promise); + this.privMessageFormatter + .fromConnectionMessage(message) + .then((rawMessage) => { + messageSendDeferral.resolve({ + Message: message, + RawWebsocketMessage: rawMessage, + sendStatusDeferral: messageSendStatusDeferral, + }); + }, (error) => { + messageSendDeferral.reject(`Error formatting the message. ${error}`); + }); + return messageSendStatusDeferral.promise; + } + read() { + if (this.privConnectionState !== Exports_js_1.ConnectionState.Connected) { + return Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`); + } + return this.privReceivingMessageQueue.dequeue(); + } + close(reason) { + if (this.privWebsocketClient) { + if (this.privConnectionState !== Exports_js_1.ConnectionState.Disconnected) { + this.privWebsocketClient.close(1000, reason ? reason : "Normal closure by client"); + } + } + else { + return Promise.resolve(); + } + return this.privDisconnectDeferral.promise; + } + get events() { + return this.privConnectionEvents; + } + sendRawMessage(sendItem) { + try { + // indicates we are draining the queue and it came with no message; + if (!sendItem) { + return Promise.resolve(); + } + this.onEvent(new Exports_js_1.ConnectionMessageSentEvent(this.privConnectionId, new Date().toISOString(), sendItem.Message)); + // add a check for the ws readystate in order to stop the red console error 'WebSocket is already in CLOSING or CLOSED state' appearing + if (this.isWebsocketOpen) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + this.privWebsocketClient.send(sendItem.RawWebsocketMessage.payload); + } + else { + return Promise.reject("websocket send error: Websocket not ready " + this.privConnectionId + " " + sendItem.Message.id + " " + new Error().stack); + } + return Promise.resolve(); + } + catch (e) { + return Promise.reject(`websocket send error: ${e}`); + } + } + async onClose(code, reason) { + const closeReason = `Connection closed. ${code}: ${reason}`; + this.privConnectionState = Exports_js_1.ConnectionState.Disconnected; + this.privDisconnectDeferral.resolve(); + await this.privReceivingMessageQueue.drainAndDispose(() => { + // TODO: Events for these ? + // Logger.instance.onEvent(new LoggingEvent(LogType.Warning, null, `Failed to process received message. Reason: ${closeReason}, Message: ${JSON.stringify(pendingReceiveItem)}`)); + }, closeReason); + await this.privSendMessageQueue.drainAndDispose((pendingSendItem) => { + pendingSendItem.sendStatusDeferral.reject(closeReason); + }, closeReason); + } + async processSendQueue() { + while (true) { + const itemToSend = this.privSendMessageQueue.dequeue(); + const sendItem = await itemToSend; + // indicates we are draining the queue and it came with no message; + if (!sendItem) { + return; + } + try { + await this.sendRawMessage(sendItem); + sendItem.sendStatusDeferral.resolve(); + } + catch (sendError) { + sendItem.sendStatusDeferral.reject(sendError); + } + } } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) + onEvent(event) { + this.privConnectionEvents.onEvent(event); + Exports_js_1.Events.instance.onEvent(event); } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getAgent() { + // eslint-disable-next-line @typescript-eslint/unbound-method + const agent = new agent_base_1.default.Agent(this.createConnection); + if (this.proxyInfo !== undefined && + this.proxyInfo.HostName !== undefined && + this.proxyInfo.Port > 0) { + agent.proxyInfo = this.proxyInfo; + } + return agent; } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break + static GetProxyAgent(proxyInfo) { + const httpProxyOptions = { + host: proxyInfo.HostName, + port: proxyInfo.Port, + }; + if (!!proxyInfo.UserName) { + httpProxyOptions.headers = { + "Proxy-Authentication": "Basic " + Buffer.from(`${proxyInfo.UserName}:${(proxyInfo.Password === undefined) ? "" : proxyInfo.Password}`).toString("base64"), + }; } - } - if (found) return i + else { + httpProxyOptions.headers = {}; + } + httpProxyOptions.headers.requestOCSP = "true"; + const httpProxyAgent = new https_proxy_agent_1.default(httpProxyOptions); + return httpProxyAgent; } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining + createConnection(request, options) { + let socketPromise; + options = { + ...options, + ...{ + requestOCSP: true, + servername: options.host + } + }; + if (!!this.proxyInfo) { + const httpProxyAgent = WebsocketMessageAdapter.GetProxyAgent(this.proxyInfo); + const baseAgent = httpProxyAgent; + socketPromise = new Promise((resolve, reject) => { + baseAgent.callback(request, options, (error, socket) => { + if (!!error) { + reject(error); + } + else { + resolve(socket); + } + }); + }); + } + else { + if (!!options.secureEndpoint) { + socketPromise = Promise.resolve(tls.connect(options)); + } + else { + socketPromise = Promise.resolve(net.connect(options)); + } + } + return socketPromise; + } + get isWebsocketOpen() { + return this.privWebsocketClient && this.privWebsocketClient.readyState === this.privWebsocketClient.OPEN; } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } +exports.WebsocketMessageAdapter = WebsocketMessageAdapter; +WebsocketMessageAdapter.forceNpmWebSocket = false; -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} +/***/ }), +/* 78 */ +/***/ (() => { -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} +/* (ignored) */ -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } +/***/ }), +/* 79 */ +/***/ (() => { - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining +/* (ignored) */ - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } +/***/ }), +/* 80 */ +/***/ (() => { - if (!encoding) encoding = 'utf8' +/* (ignored) */ - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) +/***/ }), +/* 81 */ +/***/ (() => { - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) +/* (ignored) */ - case 'ascii': - return asciiWrite(this, string, offset, length) +/***/ }), +/* 82 */ +/***/ (() => { - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) +/* (ignored) */ - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) +/***/ }), +/* 83 */ +/***/ ((__unused_webpack_module, exports) => { - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) +"use strict"; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReplayableAudioNode = void 0; +class ReplayableAudioNode { + constructor(audioSource, bytesPerSecond) { + this.privBuffers = []; + this.privReplayOffset = 0; + this.privLastShrinkOffset = 0; + this.privBufferStartOffset = 0; + this.privBufferSerial = 0; + this.privBufferedBytes = 0; + this.privReplay = false; + this.privLastChunkAcquiredTime = 0; + this.privAudioNode = audioSource; + this.privBytesPerSecond = bytesPerSecond; } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } + id() { + return this.privAudioNode.id(); } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF + // Reads and returns the next chunk of audio buffer. + // If replay of existing buffers are needed, read() will first seek and replay + // existing content, and upoin completion it will read new content from the underlying + // audio node, saving that content into the replayable buffers. + read() { + // if there is a replay request to honor. + if (!!this.privReplay && this.privBuffers.length !== 0) { + // Find the start point in the buffers. + // Offsets are in 100ns increments. + // So how many bytes do we need to seek to get the right offset? + const offsetToSeek = this.privReplayOffset - this.privBufferStartOffset; + let bytesToSeek = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7); + if (0 !== (bytesToSeek % 2)) { + bytesToSeek++; + } + let i = 0; + while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) { + bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength; + } + if (i < this.privBuffers.length) { + const retVal = this.privBuffers[i].chunk.buffer.slice(bytesToSeek); + this.privReplayOffset += (retVal.byteLength / this.privBytesPerSecond) * 1e+7; + // If we've reached the end of the buffers, stop replaying. + if (i === this.privBuffers.length - 1) { + this.privReplay = false; + } + return Promise.resolve({ + buffer: retVal, + isEnd: false, + timeReceived: this.privBuffers[i].chunk.timeReceived, + }); + } + } + return this.privAudioNode.read() + .then((result) => { + if (result && result.buffer && this.privBuffers) { + this.privBuffers.push(new BufferEntry(result, this.privBufferSerial++, this.privBufferedBytes)); + this.privBufferedBytes += result.buffer.byteLength; + } + return result; + }); } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] + detach() { + this.privBuffers = undefined; + return this.privAudioNode.detach(); + } + replay() { + if (this.privBuffers && 0 !== this.privBuffers.length) { + this.privReplay = true; + this.privReplayOffset = this.privLastShrinkOffset; + } + } + // Shrinks the existing audio buffers to start at the new offset, or at the + // beginning of the buffer closest to the requested offset. + // A replay request will start from the last shrink point. + shrinkBuffers(offset) { + if (this.privBuffers === undefined || this.privBuffers.length === 0) { + return; + } + // The shrink point must only ever advance; ignore a stale/duplicate offset so the + // resume point never moves backwards. + if (offset <= this.privLastShrinkOffset) { + return; + } + this.privLastShrinkOffset = offset; + // Find the start point in the buffers. + // Offsets are in 100ns increments. + // So how many bytes do we need to seek to get the right offset? + const offsetToSeek = offset - this.privBufferStartOffset; + let bytesToSeek = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7); + let i = 0; + while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) { + bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength; + } + this.privBufferStartOffset = Math.round(offset - ((bytesToSeek / this.privBytesPerSecond) * 1e+7)); + this.privBuffers = this.privBuffers.slice(i); + } + // Finds the time a buffer of audio was first seen by offset. + findTimeAtOffset(offset) { + if (offset < this.privBufferStartOffset || this.privBuffers === undefined) { + return 0; + } + for (const value of this.privBuffers) { + const startOffset = (value.byteOffset / this.privBytesPerSecond) * 1e7; + const endOffset = startOffset + ((value.chunk.buffer.byteLength / this.privBytesPerSecond) * 1e7); + if (offset >= startOffset && offset <= endOffset) { + return value.chunk.timeReceived; + } + } + return 0; } - } - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) } - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) +exports.ReplayableAudioNode = ReplayableAudioNode; +// Primary use of this class is to help debugging problems with the replay +// code. If the memory cost of alloc / dealloc gets too much, drop it and just use +// the ArrayBuffer directly. +class BufferEntry { + constructor(chunk, serial, byteOffset) { + this.chunk = chunk; + this.serial = serial; + this.byteOffset = byteOffset; + } } -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} +/***/ }), +/* 84 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} +"use strict"; -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProxyInfo = void 0; +const Exports_js_1 = __webpack_require__(85); +class ProxyInfo { + constructor(proxyHostName, proxyPort, proxyUserName, proxyPassword) { + this.privProxyHostName = proxyHostName; + this.privProxyPort = proxyPort; + this.privProxyUserName = proxyUserName; + this.privProxyPassword = proxyPassword; + } + static fromParameters(parameters) { + return new ProxyInfo(parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyHostName), parseInt(parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyPort), 10), parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyUserName), parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyPassword)); + } + static fromRecognizerConfig(config) { + return this.fromParameters(config.parameters); + } + get HostName() { + return this.privProxyHostName; + } + get Port() { + return this.privProxyPort; + } + get UserName() { + return this.privProxyUserName; + } + get Password() { + return this.privProxyPassword; + } } +exports.ProxyInfo = ProxyInfo; -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - return offset + byteLength -} -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } +/***/ }), +/* 85 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } +"use strict"; - return offset + byteLength -} +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CustomCommandsConfig = exports.BotFrameworkConfig = exports.DialogServiceConfig = exports.PhraseListGrammar = exports.Connection = exports.ServiceEventArgs = exports.ConnectionEventArgs = exports.CancellationErrorCode = exports.CancellationDetails = exports.CancellationDetailsBase = exports.TranslationRecognitionCanceledEventArgs = exports.NoMatchDetails = exports.NoMatchReason = exports.Translations = exports.TranslationRecognizer = exports.SpeechRecognizer = exports.Recognizer = exports.PropertyId = exports.PropertyCollection = exports.SpeechTranslationConfigImpl = exports.SpeechTranslationConfig = exports.SpeechConfigImpl = exports.SpeechConfig = exports.ResultReason = exports.TranslationSynthesisResult = exports.TranslationRecognitionResult = exports.TranslationSynthesisEventArgs = exports.TranslationRecognitionEventArgs = exports.SpeechRecognitionCanceledEventArgs = exports.MeetingTranscriptionEventArgs = exports.ConversationTranscriptionEventArgs = exports.SpeechRecognitionEventArgs = exports.SpeechRecognitionResult = exports.RecognitionResult = exports.OutputFormat = exports.RecognitionEventArgs = exports.SessionEventArgs = exports.KeywordRecognitionModel = exports.PushAudioOutputStreamCallback = exports.PullAudioInputStreamCallback = exports.CancellationReason = exports.PushAudioOutputStream = exports.PullAudioOutputStream = exports.AudioOutputStream = exports.PushAudioInputStream = exports.PullAudioInputStream = exports.AudioInputStream = exports.AudioFormatTag = exports.AudioStreamFormat = exports.AudioConfig = void 0; +exports.Diagnostics = exports.AvatarWebRTCConnectionResult = exports.Coordinate = exports.AvatarVideoFormat = exports.AvatarSynthesizer = exports.AvatarSceneConfig = exports.AvatarEventArgs = exports.AvatarConfig = exports.LanguageIdMode = exports.PronunciationAssessmentResult = exports.PronunciationAssessmentConfig = exports.PronunciationAssessmentGranularity = exports.PronunciationAssessmentGradingSystem = exports.MeetingTranscriptionCanceledEventArgs = exports.ConversationTranscriptionCanceledEventArgs = exports.SpeakerAudioDestination = exports.VoiceInfo = exports.SynthesisVoiceType = exports.SynthesisVoiceGender = exports.SynthesisVoicesResult = exports.SpeechSynthesisRequestInputType = exports.SpeechSynthesisRequestInputStream = exports.SpeechSynthesisRequest = exports.SpeechSynthesisBoundaryType = exports.SpeechSynthesisVisemeEventArgs = exports.SpeechSynthesisBookmarkEventArgs = exports.SpeechSynthesisWordBoundaryEventArgs = exports.SpeechSynthesisEventArgs = exports.SpeechSynthesisResult = exports.SynthesisResult = exports.SpeechSynthesizer = exports.SpeechSynthesisOutputFormat = exports.Synthesizer = exports.User = exports.Participant = exports.MeetingTranscriber = exports.Meeting = exports.ConversationTranscriptionResult = exports.ConversationTranscriber = exports.SourceLanguageConfig = exports.AutoDetectSourceLanguageResult = exports.AutoDetectSourceLanguageConfig = exports.ConnectionMessage = exports.ConnectionMessageEventArgs = exports.BaseAudioPlayer = exports.ProfanityOption = exports.ServicePropertyChannel = exports.TurnStatusReceivedEventArgs = exports.ActivityReceivedEventArgs = exports.DialogServiceConnector = void 0; +exports.LogLevel = void 0; +var AudioConfig_js_1 = __webpack_require__(86); +Object.defineProperty(exports, "AudioConfig", ({ enumerable: true, get: function () { return AudioConfig_js_1.AudioConfig; } })); +var AudioStreamFormat_js_1 = __webpack_require__(73); +Object.defineProperty(exports, "AudioStreamFormat", ({ enumerable: true, get: function () { return AudioStreamFormat_js_1.AudioStreamFormat; } })); +Object.defineProperty(exports, "AudioFormatTag", ({ enumerable: true, get: function () { return AudioStreamFormat_js_1.AudioFormatTag; } })); +var AudioInputStream_js_1 = __webpack_require__(89); +Object.defineProperty(exports, "AudioInputStream", ({ enumerable: true, get: function () { return AudioInputStream_js_1.AudioInputStream; } })); +Object.defineProperty(exports, "PullAudioInputStream", ({ enumerable: true, get: function () { return AudioInputStream_js_1.PullAudioInputStream; } })); +Object.defineProperty(exports, "PushAudioInputStream", ({ enumerable: true, get: function () { return AudioInputStream_js_1.PushAudioInputStream; } })); +var AudioOutputStream_js_1 = __webpack_require__(90); +Object.defineProperty(exports, "AudioOutputStream", ({ enumerable: true, get: function () { return AudioOutputStream_js_1.AudioOutputStream; } })); +Object.defineProperty(exports, "PullAudioOutputStream", ({ enumerable: true, get: function () { return AudioOutputStream_js_1.PullAudioOutputStream; } })); +Object.defineProperty(exports, "PushAudioOutputStream", ({ enumerable: true, get: function () { return AudioOutputStream_js_1.PushAudioOutputStream; } })); +var CancellationReason_js_1 = __webpack_require__(93); +Object.defineProperty(exports, "CancellationReason", ({ enumerable: true, get: function () { return CancellationReason_js_1.CancellationReason; } })); +var PullAudioInputStreamCallback_js_1 = __webpack_require__(94); +Object.defineProperty(exports, "PullAudioInputStreamCallback", ({ enumerable: true, get: function () { return PullAudioInputStreamCallback_js_1.PullAudioInputStreamCallback; } })); +var PushAudioOutputStreamCallback_js_1 = __webpack_require__(95); +Object.defineProperty(exports, "PushAudioOutputStreamCallback", ({ enumerable: true, get: function () { return PushAudioOutputStreamCallback_js_1.PushAudioOutputStreamCallback; } })); +var KeywordRecognitionModel_js_1 = __webpack_require__(96); +Object.defineProperty(exports, "KeywordRecognitionModel", ({ enumerable: true, get: function () { return KeywordRecognitionModel_js_1.KeywordRecognitionModel; } })); +var SessionEventArgs_js_1 = __webpack_require__(97); +Object.defineProperty(exports, "SessionEventArgs", ({ enumerable: true, get: function () { return SessionEventArgs_js_1.SessionEventArgs; } })); +var RecognitionEventArgs_js_1 = __webpack_require__(98); +Object.defineProperty(exports, "RecognitionEventArgs", ({ enumerable: true, get: function () { return RecognitionEventArgs_js_1.RecognitionEventArgs; } })); +var OutputFormat_js_1 = __webpack_require__(99); +Object.defineProperty(exports, "OutputFormat", ({ enumerable: true, get: function () { return OutputFormat_js_1.OutputFormat; } })); +var RecognitionResult_js_1 = __webpack_require__(100); +Object.defineProperty(exports, "RecognitionResult", ({ enumerable: true, get: function () { return RecognitionResult_js_1.RecognitionResult; } })); +var SpeechRecognitionResult_js_1 = __webpack_require__(101); +Object.defineProperty(exports, "SpeechRecognitionResult", ({ enumerable: true, get: function () { return SpeechRecognitionResult_js_1.SpeechRecognitionResult; } })); +var SpeechRecognitionEventArgs_js_1 = __webpack_require__(102); +Object.defineProperty(exports, "SpeechRecognitionEventArgs", ({ enumerable: true, get: function () { return SpeechRecognitionEventArgs_js_1.SpeechRecognitionEventArgs; } })); +Object.defineProperty(exports, "ConversationTranscriptionEventArgs", ({ enumerable: true, get: function () { return SpeechRecognitionEventArgs_js_1.ConversationTranscriptionEventArgs; } })); +Object.defineProperty(exports, "MeetingTranscriptionEventArgs", ({ enumerable: true, get: function () { return SpeechRecognitionEventArgs_js_1.MeetingTranscriptionEventArgs; } })); +var SpeechRecognitionCanceledEventArgs_js_1 = __webpack_require__(103); +Object.defineProperty(exports, "SpeechRecognitionCanceledEventArgs", ({ enumerable: true, get: function () { return SpeechRecognitionCanceledEventArgs_js_1.SpeechRecognitionCanceledEventArgs; } })); +var TranslationRecognitionEventArgs_js_1 = __webpack_require__(105); +Object.defineProperty(exports, "TranslationRecognitionEventArgs", ({ enumerable: true, get: function () { return TranslationRecognitionEventArgs_js_1.TranslationRecognitionEventArgs; } })); +var TranslationSynthesisEventArgs_js_1 = __webpack_require__(106); +Object.defineProperty(exports, "TranslationSynthesisEventArgs", ({ enumerable: true, get: function () { return TranslationSynthesisEventArgs_js_1.TranslationSynthesisEventArgs; } })); +var TranslationRecognitionResult_js_1 = __webpack_require__(107); +Object.defineProperty(exports, "TranslationRecognitionResult", ({ enumerable: true, get: function () { return TranslationRecognitionResult_js_1.TranslationRecognitionResult; } })); +var TranslationSynthesisResult_js_1 = __webpack_require__(108); +Object.defineProperty(exports, "TranslationSynthesisResult", ({ enumerable: true, get: function () { return TranslationSynthesisResult_js_1.TranslationSynthesisResult; } })); +var ResultReason_js_1 = __webpack_require__(109); +Object.defineProperty(exports, "ResultReason", ({ enumerable: true, get: function () { return ResultReason_js_1.ResultReason; } })); +var SpeechConfig_js_1 = __webpack_require__(110); +Object.defineProperty(exports, "SpeechConfig", ({ enumerable: true, get: function () { return SpeechConfig_js_1.SpeechConfig; } })); +Object.defineProperty(exports, "SpeechConfigImpl", ({ enumerable: true, get: function () { return SpeechConfig_js_1.SpeechConfigImpl; } })); +var SpeechTranslationConfig_js_1 = __webpack_require__(111); +Object.defineProperty(exports, "SpeechTranslationConfig", ({ enumerable: true, get: function () { return SpeechTranslationConfig_js_1.SpeechTranslationConfig; } })); +Object.defineProperty(exports, "SpeechTranslationConfigImpl", ({ enumerable: true, get: function () { return SpeechTranslationConfig_js_1.SpeechTranslationConfigImpl; } })); +var PropertyCollection_js_1 = __webpack_require__(112); +Object.defineProperty(exports, "PropertyCollection", ({ enumerable: true, get: function () { return PropertyCollection_js_1.PropertyCollection; } })); +var PropertyId_js_1 = __webpack_require__(113); +Object.defineProperty(exports, "PropertyId", ({ enumerable: true, get: function () { return PropertyId_js_1.PropertyId; } })); +var Recognizer_js_1 = __webpack_require__(114); +Object.defineProperty(exports, "Recognizer", ({ enumerable: true, get: function () { return Recognizer_js_1.Recognizer; } })); +var SpeechRecognizer_js_1 = __webpack_require__(115); +Object.defineProperty(exports, "SpeechRecognizer", ({ enumerable: true, get: function () { return SpeechRecognizer_js_1.SpeechRecognizer; } })); +var TranslationRecognizer_js_1 = __webpack_require__(117); +Object.defineProperty(exports, "TranslationRecognizer", ({ enumerable: true, get: function () { return TranslationRecognizer_js_1.TranslationRecognizer; } })); +var Translations_js_1 = __webpack_require__(120); +Object.defineProperty(exports, "Translations", ({ enumerable: true, get: function () { return Translations_js_1.Translations; } })); +var NoMatchReason_js_1 = __webpack_require__(121); +Object.defineProperty(exports, "NoMatchReason", ({ enumerable: true, get: function () { return NoMatchReason_js_1.NoMatchReason; } })); +var NoMatchDetails_js_1 = __webpack_require__(122); +Object.defineProperty(exports, "NoMatchDetails", ({ enumerable: true, get: function () { return NoMatchDetails_js_1.NoMatchDetails; } })); +var TranslationRecognitionCanceledEventArgs_js_1 = __webpack_require__(123); +Object.defineProperty(exports, "TranslationRecognitionCanceledEventArgs", ({ enumerable: true, get: function () { return TranslationRecognitionCanceledEventArgs_js_1.TranslationRecognitionCanceledEventArgs; } })); +var CancellationDetailsBase_js_1 = __webpack_require__(124); +Object.defineProperty(exports, "CancellationDetailsBase", ({ enumerable: true, get: function () { return CancellationDetailsBase_js_1.CancellationDetailsBase; } })); +var CancellationDetails_js_1 = __webpack_require__(125); +Object.defineProperty(exports, "CancellationDetails", ({ enumerable: true, get: function () { return CancellationDetails_js_1.CancellationDetails; } })); +var CancellationErrorCodes_js_1 = __webpack_require__(126); +Object.defineProperty(exports, "CancellationErrorCode", ({ enumerable: true, get: function () { return CancellationErrorCodes_js_1.CancellationErrorCode; } })); +var ConnectionEventArgs_js_1 = __webpack_require__(127); +Object.defineProperty(exports, "ConnectionEventArgs", ({ enumerable: true, get: function () { return ConnectionEventArgs_js_1.ConnectionEventArgs; } })); +var ServiceEventArgs_js_1 = __webpack_require__(128); +Object.defineProperty(exports, "ServiceEventArgs", ({ enumerable: true, get: function () { return ServiceEventArgs_js_1.ServiceEventArgs; } })); +var Connection_js_1 = __webpack_require__(118); +Object.defineProperty(exports, "Connection", ({ enumerable: true, get: function () { return Connection_js_1.Connection; } })); +var PhraseListGrammar_js_1 = __webpack_require__(129); +Object.defineProperty(exports, "PhraseListGrammar", ({ enumerable: true, get: function () { return PhraseListGrammar_js_1.PhraseListGrammar; } })); +var DialogServiceConfig_js_1 = __webpack_require__(130); +Object.defineProperty(exports, "DialogServiceConfig", ({ enumerable: true, get: function () { return DialogServiceConfig_js_1.DialogServiceConfig; } })); +var BotFrameworkConfig_js_1 = __webpack_require__(131); +Object.defineProperty(exports, "BotFrameworkConfig", ({ enumerable: true, get: function () { return BotFrameworkConfig_js_1.BotFrameworkConfig; } })); +var CustomCommandsConfig_js_1 = __webpack_require__(132); +Object.defineProperty(exports, "CustomCommandsConfig", ({ enumerable: true, get: function () { return CustomCommandsConfig_js_1.CustomCommandsConfig; } })); +var DialogServiceConnector_js_1 = __webpack_require__(133); +Object.defineProperty(exports, "DialogServiceConnector", ({ enumerable: true, get: function () { return DialogServiceConnector_js_1.DialogServiceConnector; } })); +var ActivityReceivedEventArgs_js_1 = __webpack_require__(137); +Object.defineProperty(exports, "ActivityReceivedEventArgs", ({ enumerable: true, get: function () { return ActivityReceivedEventArgs_js_1.ActivityReceivedEventArgs; } })); +var TurnStatusReceivedEventArgs_js_1 = __webpack_require__(138); +Object.defineProperty(exports, "TurnStatusReceivedEventArgs", ({ enumerable: true, get: function () { return TurnStatusReceivedEventArgs_js_1.TurnStatusReceivedEventArgs; } })); +var ServicePropertyChannel_js_1 = __webpack_require__(140); +Object.defineProperty(exports, "ServicePropertyChannel", ({ enumerable: true, get: function () { return ServicePropertyChannel_js_1.ServicePropertyChannel; } })); +var ProfanityOption_js_1 = __webpack_require__(141); +Object.defineProperty(exports, "ProfanityOption", ({ enumerable: true, get: function () { return ProfanityOption_js_1.ProfanityOption; } })); +var BaseAudioPlayer_js_1 = __webpack_require__(142); +Object.defineProperty(exports, "BaseAudioPlayer", ({ enumerable: true, get: function () { return BaseAudioPlayer_js_1.BaseAudioPlayer; } })); +var ConnectionMessageEventArgs_js_1 = __webpack_require__(143); +Object.defineProperty(exports, "ConnectionMessageEventArgs", ({ enumerable: true, get: function () { return ConnectionMessageEventArgs_js_1.ConnectionMessageEventArgs; } })); +var ConnectionMessage_js_1 = __webpack_require__(119); +Object.defineProperty(exports, "ConnectionMessage", ({ enumerable: true, get: function () { return ConnectionMessage_js_1.ConnectionMessage; } })); +var AutoDetectSourceLanguageConfig_js_1 = __webpack_require__(144); +Object.defineProperty(exports, "AutoDetectSourceLanguageConfig", ({ enumerable: true, get: function () { return AutoDetectSourceLanguageConfig_js_1.AutoDetectSourceLanguageConfig; } })); +var AutoDetectSourceLanguageResult_js_1 = __webpack_require__(146); +Object.defineProperty(exports, "AutoDetectSourceLanguageResult", ({ enumerable: true, get: function () { return AutoDetectSourceLanguageResult_js_1.AutoDetectSourceLanguageResult; } })); +var SourceLanguageConfig_js_1 = __webpack_require__(147); +Object.defineProperty(exports, "SourceLanguageConfig", ({ enumerable: true, get: function () { return SourceLanguageConfig_js_1.SourceLanguageConfig; } })); +var Exports_js_1 = __webpack_require__(148); +Object.defineProperty(exports, "ConversationTranscriber", ({ enumerable: true, get: function () { return Exports_js_1.ConversationTranscriber; } })); +Object.defineProperty(exports, "ConversationTranscriptionResult", ({ enumerable: true, get: function () { return Exports_js_1.ConversationTranscriptionResult; } })); +Object.defineProperty(exports, "Meeting", ({ enumerable: true, get: function () { return Exports_js_1.Meeting; } })); +Object.defineProperty(exports, "MeetingTranscriber", ({ enumerable: true, get: function () { return Exports_js_1.MeetingTranscriber; } })); +Object.defineProperty(exports, "Participant", ({ enumerable: true, get: function () { return Exports_js_1.Participant; } })); +Object.defineProperty(exports, "User", ({ enumerable: true, get: function () { return Exports_js_1.User; } })); +var Synthesizer_js_1 = __webpack_require__(155); +Object.defineProperty(exports, "Synthesizer", ({ enumerable: true, get: function () { return Synthesizer_js_1.Synthesizer; } })); +var SpeechSynthesisOutputFormat_js_1 = __webpack_require__(92); +Object.defineProperty(exports, "SpeechSynthesisOutputFormat", ({ enumerable: true, get: function () { return SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat; } })); +var SpeechSynthesizer_js_1 = __webpack_require__(156); +Object.defineProperty(exports, "SpeechSynthesizer", ({ enumerable: true, get: function () { return SpeechSynthesizer_js_1.SpeechSynthesizer; } })); +var SynthesisResult_js_1 = __webpack_require__(157); +Object.defineProperty(exports, "SynthesisResult", ({ enumerable: true, get: function () { return SynthesisResult_js_1.SynthesisResult; } })); +var SpeechSynthesisResult_js_1 = __webpack_require__(158); +Object.defineProperty(exports, "SpeechSynthesisResult", ({ enumerable: true, get: function () { return SpeechSynthesisResult_js_1.SpeechSynthesisResult; } })); +var SpeechSynthesisEventArgs_js_1 = __webpack_require__(159); +Object.defineProperty(exports, "SpeechSynthesisEventArgs", ({ enumerable: true, get: function () { return SpeechSynthesisEventArgs_js_1.SpeechSynthesisEventArgs; } })); +var SpeechSynthesisWordBoundaryEventArgs_js_1 = __webpack_require__(160); +Object.defineProperty(exports, "SpeechSynthesisWordBoundaryEventArgs", ({ enumerable: true, get: function () { return SpeechSynthesisWordBoundaryEventArgs_js_1.SpeechSynthesisWordBoundaryEventArgs; } })); +var SpeechSynthesisBookmarkEventArgs_js_1 = __webpack_require__(161); +Object.defineProperty(exports, "SpeechSynthesisBookmarkEventArgs", ({ enumerable: true, get: function () { return SpeechSynthesisBookmarkEventArgs_js_1.SpeechSynthesisBookmarkEventArgs; } })); +var SpeechSynthesisVisemeEventArgs_js_1 = __webpack_require__(162); +Object.defineProperty(exports, "SpeechSynthesisVisemeEventArgs", ({ enumerable: true, get: function () { return SpeechSynthesisVisemeEventArgs_js_1.SpeechSynthesisVisemeEventArgs; } })); +var SpeechSynthesisBoundaryType_js_1 = __webpack_require__(163); +Object.defineProperty(exports, "SpeechSynthesisBoundaryType", ({ enumerable: true, get: function () { return SpeechSynthesisBoundaryType_js_1.SpeechSynthesisBoundaryType; } })); +var SpeechSynthesisRequest_js_1 = __webpack_require__(164); +Object.defineProperty(exports, "SpeechSynthesisRequest", ({ enumerable: true, get: function () { return SpeechSynthesisRequest_js_1.SpeechSynthesisRequest; } })); +Object.defineProperty(exports, "SpeechSynthesisRequestInputStream", ({ enumerable: true, get: function () { return SpeechSynthesisRequest_js_1.SpeechSynthesisRequestInputStream; } })); +var SpeechSynthesisRequestInputType_js_1 = __webpack_require__(165); +Object.defineProperty(exports, "SpeechSynthesisRequestInputType", ({ enumerable: true, get: function () { return SpeechSynthesisRequestInputType_js_1.SpeechSynthesisRequestInputType; } })); +var SynthesisVoicesResult_js_1 = __webpack_require__(167); +Object.defineProperty(exports, "SynthesisVoicesResult", ({ enumerable: true, get: function () { return SynthesisVoicesResult_js_1.SynthesisVoicesResult; } })); +var VoiceInfo_js_1 = __webpack_require__(168); +Object.defineProperty(exports, "SynthesisVoiceGender", ({ enumerable: true, get: function () { return VoiceInfo_js_1.SynthesisVoiceGender; } })); +Object.defineProperty(exports, "SynthesisVoiceType", ({ enumerable: true, get: function () { return VoiceInfo_js_1.SynthesisVoiceType; } })); +Object.defineProperty(exports, "VoiceInfo", ({ enumerable: true, get: function () { return VoiceInfo_js_1.VoiceInfo; } })); +var SpeakerAudioDestination_js_1 = __webpack_require__(169); +Object.defineProperty(exports, "SpeakerAudioDestination", ({ enumerable: true, get: function () { return SpeakerAudioDestination_js_1.SpeakerAudioDestination; } })); +var ConversationTranscriptionCanceledEventArgs_js_1 = __webpack_require__(170); +Object.defineProperty(exports, "ConversationTranscriptionCanceledEventArgs", ({ enumerable: true, get: function () { return ConversationTranscriptionCanceledEventArgs_js_1.ConversationTranscriptionCanceledEventArgs; } })); +var MeetingTranscriptionCanceledEventArgs_js_1 = __webpack_require__(171); +Object.defineProperty(exports, "MeetingTranscriptionCanceledEventArgs", ({ enumerable: true, get: function () { return MeetingTranscriptionCanceledEventArgs_js_1.MeetingTranscriptionCanceledEventArgs; } })); +var PronunciationAssessmentGradingSystem_js_1 = __webpack_require__(172); +Object.defineProperty(exports, "PronunciationAssessmentGradingSystem", ({ enumerable: true, get: function () { return PronunciationAssessmentGradingSystem_js_1.PronunciationAssessmentGradingSystem; } })); +var PronunciationAssessmentGranularity_js_1 = __webpack_require__(173); +Object.defineProperty(exports, "PronunciationAssessmentGranularity", ({ enumerable: true, get: function () { return PronunciationAssessmentGranularity_js_1.PronunciationAssessmentGranularity; } })); +var PronunciationAssessmentConfig_js_1 = __webpack_require__(174); +Object.defineProperty(exports, "PronunciationAssessmentConfig", ({ enumerable: true, get: function () { return PronunciationAssessmentConfig_js_1.PronunciationAssessmentConfig; } })); +var PronunciationAssessmentResult_js_1 = __webpack_require__(175); +Object.defineProperty(exports, "PronunciationAssessmentResult", ({ enumerable: true, get: function () { return PronunciationAssessmentResult_js_1.PronunciationAssessmentResult; } })); +var LanguageIdMode_js_1 = __webpack_require__(145); +Object.defineProperty(exports, "LanguageIdMode", ({ enumerable: true, get: function () { return LanguageIdMode_js_1.LanguageIdMode; } })); +var AvatarConfig_js_1 = __webpack_require__(176); +Object.defineProperty(exports, "AvatarConfig", ({ enumerable: true, get: function () { return AvatarConfig_js_1.AvatarConfig; } })); +var AvatarEventArgs_js_1 = __webpack_require__(177); +Object.defineProperty(exports, "AvatarEventArgs", ({ enumerable: true, get: function () { return AvatarEventArgs_js_1.AvatarEventArgs; } })); +var AvatarSceneConfig_js_1 = __webpack_require__(178); +Object.defineProperty(exports, "AvatarSceneConfig", ({ enumerable: true, get: function () { return AvatarSceneConfig_js_1.AvatarSceneConfig; } })); +var AvatarSynthesizer_js_1 = __webpack_require__(179); +Object.defineProperty(exports, "AvatarSynthesizer", ({ enumerable: true, get: function () { return AvatarSynthesizer_js_1.AvatarSynthesizer; } })); +var AvatarVideoFormat_js_1 = __webpack_require__(181); +Object.defineProperty(exports, "AvatarVideoFormat", ({ enumerable: true, get: function () { return AvatarVideoFormat_js_1.AvatarVideoFormat; } })); +Object.defineProperty(exports, "Coordinate", ({ enumerable: true, get: function () { return AvatarVideoFormat_js_1.Coordinate; } })); +var AvatarWebRTCConnectionResult_js_1 = __webpack_require__(182); +Object.defineProperty(exports, "AvatarWebRTCConnectionResult", ({ enumerable: true, get: function () { return AvatarWebRTCConnectionResult_js_1.AvatarWebRTCConnectionResult; } })); +var Diagnostics_js_1 = __webpack_require__(183); +Object.defineProperty(exports, "Diagnostics", ({ enumerable: true, get: function () { return Diagnostics_js_1.Diagnostics; } })); +var LogLevel_js_1 = __webpack_require__(69); +Object.defineProperty(exports, "LogLevel", ({ enumerable: true, get: function () { return LogLevel_js_1.LogLevel; } })); -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 -} -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} +/***/ }), +/* 86 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} +"use strict"; -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AudioOutputConfigImpl = exports.AudioConfigImpl = exports.AudioConfig = void 0; +const Exports_js_1 = __webpack_require__(66); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_2 = __webpack_require__(85); +const AudioFileWriter_js_1 = __webpack_require__(87); +const AudioInputStream_js_1 = __webpack_require__(89); +const AudioOutputStream_js_1 = __webpack_require__(90); +/** + * Represents audio input configuration used for specifying what type of input to use (microphone, file, stream). + * @class AudioConfig + * Updated in version 1.11.0 + */ +class AudioConfig { + /** + * Creates an AudioConfig object representing the default microphone on the system. + * @member AudioConfig.fromDefaultMicrophoneInput + * @function + * @public + * @returns {AudioConfig} The audio input configuration being created. + */ + static fromDefaultMicrophoneInput() { + const pcmRecorder = new Exports_js_1.PcmRecorder(true); + return new AudioConfigImpl(new Exports_js_1.MicAudioSource(pcmRecorder)); + } + /** + * Creates an AudioConfig object representing a microphone with the specified device ID. + * @member AudioConfig.fromMicrophoneInput + * @function + * @public + * @param {string | undefined} deviceId - Specifies the device ID of the microphone to be used. + * Default microphone is used the value is omitted. + * @returns {AudioConfig} The audio input configuration being created. + */ + static fromMicrophoneInput(deviceId) { + const pcmRecorder = new Exports_js_1.PcmRecorder(true); + return new AudioConfigImpl(new Exports_js_1.MicAudioSource(pcmRecorder, deviceId)); + } + /** + * Creates an AudioConfig object representing the specified file. + * @member AudioConfig.fromWavFileInput + * @function + * @public + * @param {File} fileName - Specifies the audio input file. Currently, only WAV / PCM is supported. + * @returns {AudioConfig} The audio input configuration being created. + */ + static fromWavFileInput(file, name = "unnamedBuffer.wav") { + return new AudioConfigImpl(new Exports_js_1.FileAudioSource(file, name)); + } + /** + * Creates an AudioConfig object representing the specified stream. + * @member AudioConfig.fromStreamInput + * @function + * @public + * @param {AudioInputStream | PullAudioInputStreamCallback | MediaStream} audioStream - Specifies the custom audio input + * stream. Currently, only WAV / PCM is supported. + * @returns {AudioConfig} The audio input configuration being created. + */ + static fromStreamInput(audioStream) { + if (audioStream instanceof Exports_js_2.PullAudioInputStreamCallback) { + return new AudioConfigImpl(new AudioInputStream_js_1.PullAudioInputStreamImpl(audioStream)); + } + if (audioStream instanceof Exports_js_2.AudioInputStream) { + return new AudioConfigImpl(audioStream); + } + if (typeof MediaStream !== "undefined" && audioStream instanceof MediaStream) { + const pcmRecorder = new Exports_js_1.PcmRecorder(false); + return new AudioConfigImpl(new Exports_js_1.MicAudioSource(pcmRecorder, null, null, audioStream)); + } + throw new Error("Not Supported Type"); + } + /** + * Creates an AudioConfig object representing the default speaker. + * @member AudioConfig.fromDefaultSpeakerOutput + * @function + * @public + * @returns {AudioConfig} The audio output configuration being created. + * Added in version 1.11.0 + */ + static fromDefaultSpeakerOutput() { + return new AudioOutputConfigImpl(new Exports_js_2.SpeakerAudioDestination()); + } + /** + * Creates an AudioConfig object representing the custom IPlayer object. + * You can use the IPlayer object to control pause, resume, etc. + * @member AudioConfig.fromSpeakerOutput + * @function + * @public + * @param {IPlayer} player - the IPlayer object for playback. + * @returns {AudioConfig} The audio output configuration being created. + * Added in version 1.12.0 + */ + static fromSpeakerOutput(player) { + if (player === undefined) { + return AudioConfig.fromDefaultSpeakerOutput(); + } + if (player instanceof Exports_js_2.SpeakerAudioDestination) { + return new AudioOutputConfigImpl(player); + } + throw new Error("Not Supported Type"); + } + /** + * Creates an AudioConfig object representing a specified output audio file + * @member AudioConfig.fromAudioFileOutput + * @function + * @public + * @param {PathLike} filename - the filename of the output audio file + * @returns {AudioConfig} The audio output configuration being created. + * Added in version 1.11.0 + */ + static fromAudioFileOutput(filename) { + return new AudioOutputConfigImpl(new AudioFileWriter_js_1.AudioFileWriter(filename)); + } + /** + * Creates an AudioConfig object representing a specified audio output stream + * @member AudioConfig.fromStreamOutput + * @function + * @public + * @param {AudioOutputStream | PushAudioOutputStreamCallback} audioStream - Specifies the custom audio output + * stream. + * @returns {AudioConfig} The audio output configuration being created. + * Added in version 1.11.0 + */ + static fromStreamOutput(audioStream) { + if (audioStream instanceof Exports_js_2.PushAudioOutputStreamCallback) { + return new AudioOutputConfigImpl(new AudioOutputStream_js_1.PushAudioOutputStreamImpl(audioStream)); + } + if (audioStream instanceof Exports_js_2.PushAudioOutputStream) { + return new AudioOutputConfigImpl(audioStream); + } + if (audioStream instanceof Exports_js_2.PullAudioOutputStream) { + return new AudioOutputConfigImpl(audioStream); + } + throw new Error("Not Supported Type"); + } } +exports.AudioConfig = AudioConfig; +/** + * Represents audio input stream used for custom audio input configurations. + * @private + * @class AudioConfigImpl + */ +class AudioConfigImpl extends AudioConfig { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {IAudioSource} source - An audio source. + */ + constructor(source) { + super(); + this.privSource = source; + } + /** + * Format information for the audio + */ + get format() { + return this.privSource.format; + } + /** + * @member AudioConfigImpl.prototype.close + * @function + * @public + */ + close(cb, err) { + this.privSource.turnOff().then(() => { + if (!!cb) { + cb(); + } + }, (error) => { + if (!!err) { + err(error); + } + }); + } + /** + * @member AudioConfigImpl.prototype.id + * @function + * @public + */ + id() { + return this.privSource.id(); + } + /** + * @member AudioConfigImpl.prototype.turnOn + * @function + * @public + * @returns {Promise} A promise. + */ + turnOn() { + return this.privSource.turnOn(); + } + /** + * @member AudioConfigImpl.prototype.attach + * @function + * @public + * @param {string} audioNodeId - The audio node id. + * @returns {Promise} A promise. + */ + attach(audioNodeId) { + return this.privSource.attach(audioNodeId); + } + /** + * @member AudioConfigImpl.prototype.detach + * @function + * @public + * @param {string} audioNodeId - The audio node id. + */ + detach(audioNodeId) { + return this.privSource.detach(audioNodeId); + } + /** + * @member AudioConfigImpl.prototype.turnOff + * @function + * @public + * @returns {Promise} A promise. + */ + turnOff() { + return this.privSource.turnOff(); + } + /** + * @member AudioConfigImpl.prototype.events + * @function + * @public + * @returns {EventSource} An event source for audio events. + */ + get events() { + return this.privSource.events; + } + setProperty(name, value) { + Contracts_js_1.Contracts.throwIfNull(value, "value"); + if (undefined !== this.privSource.setProperty) { + this.privSource.setProperty(name, value); + } + else { + throw new Error("This AudioConfig instance does not support setting properties."); + } + } + getProperty(name, def) { + if (undefined !== this.privSource.getProperty) { + return this.privSource.getProperty(name, def); + } + else { + throw new Error("This AudioConfig instance does not support getting properties."); + } + // removed by dead control flow -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 + get deviceInfo() { + return this.privSource.deviceInfo; } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) } - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } +exports.AudioConfigImpl = AudioConfigImpl; +class AudioOutputConfigImpl extends AudioConfig { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {IAudioDestination} destination - An audio destination. + */ + constructor(destination) { + super(); + this.privDestination = destination; } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') + set format(format) { + this.privDestination.format = format; } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) + write(buffer) { + this.privDestination.write(buffer); } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val + close() { + this.privDestination.close(); } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] + id() { + return this.privDestination.id(); } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') + setProperty() { + throw new Error("This AudioConfig instance does not support setting properties."); + } + getProperty() { + throw new Error("This AudioConfig instance does not support getting properties."); } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(68))) - -/***/ }), -/* 68 */ -/***/ (function(module, exports) { - -var g; - -// This works in non-strict mode -g = (function() { - return this; -})(); - -try { - // This works if eval is allowed (see CSP) - g = g || new Function("return this")(); -} catch (e) { - // This works if the window reference is available - if (typeof window === "object") g = window; } +exports.AudioOutputConfigImpl = AudioOutputConfigImpl; -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} - -module.exports = g; /***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { +/* 87 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - - -/***/ }), -/* 70 */ -/***/ (function(module, exports) { - -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AudioFileWriter = void 0; +const fs = __importStar(__webpack_require__(88)); +const Contracts_js_1 = __webpack_require__(70); +class AudioFileWriter { + constructor(filename) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(fs.openSync, "\nFile System access not available, please use Push or PullAudioOutputStream"); + this.privFd = fs.openSync(filename, "w"); } - if (value * c >= 2) { - e++ - c /= 2 + set format(format) { + Contracts_js_1.Contracts.throwIfNotUndefined(this.privAudioFormat, "format is already set"); + this.privAudioFormat = format; + let headerOffset = 0; + if (this.privAudioFormat.hasHeader) { + headerOffset = this.privAudioFormat.header.byteLength; + } + if (this.privFd !== undefined) { + this.privWriteStream = fs.createWriteStream("", { fd: this.privFd, start: headerOffset, autoClose: false }); + } } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 + write(buffer) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privAudioFormat, "must set format before writing."); + if (this.privWriteStream !== undefined) { + this.privWriteStream.write(new Uint8Array(buffer.slice(0))); + } + } + close() { + if (this.privFd !== undefined) { + this.privWriteStream.on("finish", () => { + if (this.privAudioFormat.hasHeader) { + this.privAudioFormat.updateHeader(this.privWriteStream.bytesWritten); + fs.writeSync(this.privFd, new Int8Array(this.privAudioFormat.header), 0, this.privAudioFormat.header.byteLength, 0); + } + fs.closeSync(this.privFd); + this.privFd = undefined; + }); + this.privWriteStream.end(); + } + } + id() { + return this.privId; } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 } +exports.AudioFileWriter = AudioFileWriter; -/***/ }), -/* 71 */ -/***/ (function(module, exports) { - -var toString = {}.toString; -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; +/***/ }), +/* 88 */ +/***/ (() => { +/* (ignored) */ /***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { +/* 89 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AudioStreamFormatImpl = exports.AudioStreamFormat = exports.AudioFormatTag = void 0; -var AudioFormatTag; -(function (AudioFormatTag) { - AudioFormatTag[AudioFormatTag["PCM"] = 1] = "PCM"; - AudioFormatTag[AudioFormatTag["MuLaw"] = 2] = "MuLaw"; - AudioFormatTag[AudioFormatTag["Siren"] = 3] = "Siren"; - AudioFormatTag[AudioFormatTag["MP3"] = 4] = "MP3"; - AudioFormatTag[AudioFormatTag["SILKSkype"] = 5] = "SILKSkype"; - AudioFormatTag[AudioFormatTag["OGG_OPUS"] = 6] = "OGG_OPUS"; - AudioFormatTag[AudioFormatTag["WEBM_OPUS"] = 7] = "WEBM_OPUS"; - AudioFormatTag[AudioFormatTag["ALaw"] = 8] = "ALaw"; - AudioFormatTag[AudioFormatTag["FLAC"] = 9] = "FLAC"; - AudioFormatTag[AudioFormatTag["OPUS"] = 10] = "OPUS"; -})(AudioFormatTag = exports.AudioFormatTag || (exports.AudioFormatTag = {})); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PullAudioInputStreamImpl = exports.PullAudioInputStream = exports.PushAudioInputStreamImpl = exports.PushAudioInputStream = exports.AudioInputStream = void 0; +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const Guid_js_1 = __webpack_require__(7); +const Exports_js_3 = __webpack_require__(85); +const AudioStreamFormat_js_1 = __webpack_require__(73); /** - * Represents audio stream format used for custom audio input configurations. - * @class AudioStreamFormat + * Represents audio input stream used for custom audio input configurations. + * @class AudioInputStream */ -var AudioStreamFormat = /** @class */ (function () { - function AudioStreamFormat() { +class AudioInputStream { + /** + * Creates and initializes an instance. + * @constructor + */ + constructor() { + return; } /** - * Creates an audio stream format object representing the default audio stream - * format (16KHz 16bit mono PCM). - * @member AudioStreamFormat.getDefaultInputFormat + * Creates a memory backed PushAudioInputStream with the specified audio format. + * @member AudioInputStream.createPushStream * @function * @public - * @returns {AudioStreamFormat} The audio stream format being created. + * @param {AudioStreamFormat} format - The audio data format in which audio will be + * written to the push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM). + * @returns {PushAudioInputStream} The audio input stream being created. */ - AudioStreamFormat.getDefaultInputFormat = function () { - return AudioStreamFormatImpl.getDefaultInputFormat(); - }; + static createPushStream(format) { + return PushAudioInputStream.create(format); + } /** - * Creates an audio stream format object with the specified format characteristics. - * @member AudioStreamFormat.getWaveFormat + * Creates a PullAudioInputStream that delegates to the specified callback interface for read() + * and close() methods. + * @member AudioInputStream.createPullStream * @function * @public - * @param {number} samplesPerSecond - Sample rate, in samples per second (Hertz). - * @param {number} bitsPerSample - Bits per sample, typically 16. - * @param {number} channels - Number of channels in the waveform-audio data. Monaural data - * uses one channel and stereo data uses two channels. - * @param {AudioFormatTag} format - Audio format (PCM, alaw or mulaw). - * @returns {AudioStreamFormat} The audio stream format being created. + * @param {PullAudioInputStreamCallback} callback - The custom audio input object, derived from + * PullAudioInputStreamCallback + * @param {AudioStreamFormat} format - The audio data format in which audio will be returned from + * the callback's read() method (Required if format is not 16 kHz 16bit mono PCM). + * @returns {PullAudioInputStream} The audio input stream being created. */ - AudioStreamFormat.getWaveFormat = function (samplesPerSecond, bitsPerSample, channels, format) { - return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels, format); - }; + static createPullStream(callback, format) { + return PullAudioInputStream.create(callback, format); + // throw new Error("Oops"); + } +} +exports.AudioInputStream = AudioInputStream; +/** + * Represents memory backed push audio input stream used for custom audio input configurations. + * @class PushAudioInputStream + */ +class PushAudioInputStream extends AudioInputStream { /** - * Creates an audio stream format object with the specified pcm waveformat characteristics. - * @member AudioStreamFormat.getWaveFormatPCM + * Creates a memory backed PushAudioInputStream with the specified audio format. + * @member PushAudioInputStream.create * @function * @public - * @param {number} samplesPerSecond - Sample rate, in samples per second (Hertz). - * @param {number} bitsPerSample - Bits per sample, typically 16. - * @param {number} channels - Number of channels in the waveform-audio data. Monaural data - * uses one channel and stereo data uses two channels. - * @returns {AudioStreamFormat} The audio stream format being created. + * @param {AudioStreamFormat} format - The audio data format in which audio will be written to the + * push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM). + * @returns {PushAudioInputStream} The push audio input stream being created. */ - AudioStreamFormat.getWaveFormatPCM = function (samplesPerSecond, bitsPerSample, channels) { - return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels); - }; - return AudioStreamFormat; -}()); -exports.AudioStreamFormat = AudioStreamFormat; + static create(format) { + return new PushAudioInputStreamImpl(format); + } +} +exports.PushAudioInputStream = PushAudioInputStream; /** + * Represents memory backed push audio input stream used for custom audio input configurations. * @private - * @class AudioStreamFormatImpl + * @class PushAudioInputStreamImpl */ -// tslint:disable-next-line:max-classes-per-file -var AudioStreamFormatImpl = /** @class */ (function (_super) { - __extends(AudioStreamFormatImpl, _super); +class PushAudioInputStreamImpl extends PushAudioInputStream { /** - * Creates an instance with the given values. + * Creates and initalizes an instance with the given values. * @constructor - * @param {number} samplesPerSec - Samples per second. - * @param {number} bitsPerSample - Bits per sample. - * @param {number} channels - Number of channels. - * @param {AudioFormatTag} format - Audio format (PCM, alaw or mulaw). + * @param {AudioStreamFormat} format - The audio stream format. */ - function AudioStreamFormatImpl(samplesPerSec, bitsPerSample, channels, format) { - if (samplesPerSec === void 0) { samplesPerSec = 16000; } - if (bitsPerSample === void 0) { bitsPerSample = 16; } - if (channels === void 0) { channels = 1; } - if (format === void 0) { format = AudioFormatTag.PCM; } - var _this = _super.call(this) || this; - _this.setString = function (view, offset, str) { - for (var i = 0; i < str.length; i++) { - view.setUint8(offset + i, str.charCodeAt(i)); - } - }; - var isWavFormat = true; - /* 1 for PCM; 6 for alaw; 7 for mulaw */ - switch (format) { - case AudioFormatTag.PCM: - _this.formatTag = 1; - break; - case AudioFormatTag.ALaw: - _this.formatTag = 6; - break; - case AudioFormatTag.MuLaw: - _this.formatTag = 7; - break; - default: - isWavFormat = false; + constructor(format) { + super(); + if (format === undefined) { + this.privFormat = AudioStreamFormat_js_1.AudioStreamFormatImpl.getDefaultInputFormat(); } - _this.bitsPerSample = bitsPerSample; - _this.samplesPerSec = samplesPerSec; - _this.channels = channels; - _this.avgBytesPerSec = _this.samplesPerSec * _this.channels * (_this.bitsPerSample / 8); - _this.blockAlign = _this.channels * Math.max(_this.bitsPerSample, 8); - if (isWavFormat) { - _this.privHeader = new ArrayBuffer(44); - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView - var view = new DataView(_this.privHeader); - /* RIFF identifier */ - _this.setString(view, 0, "RIFF"); - /* file length */ - view.setUint32(4, 0, true); - /* RIFF type & Format */ - _this.setString(view, 8, "WAVEfmt "); - /* format chunk length */ - view.setUint32(16, 16, true); - /* audio format */ - view.setUint16(20, _this.formatTag, true); - /* channel count */ - view.setUint16(22, _this.channels, true); - /* sample rate */ - view.setUint32(24, _this.samplesPerSec, true); - /* byte rate (sample rate * block align) */ - view.setUint32(28, _this.avgBytesPerSec, true); - /* block align (channel count * bytes per sample) */ - view.setUint16(32, _this.channels * (_this.bitsPerSample / 8), true); - /* bits per sample */ - view.setUint16(34, _this.bitsPerSample, true); - /* data chunk identifier */ - _this.setString(view, 36, "data"); - /* data chunk length */ - view.setUint32(40, 0, true); + else { + this.privFormat = format; } - return _this; + this.privEvents = new Exports_js_2.EventSource(); + this.privId = (0, Guid_js_1.createNoDashGuid)(); + this.privStream = new Exports_js_2.ChunkedArrayBufferStream(this.privFormat.avgBytesPerSec / 10); } /** - * Retrieves the default input format. - * @member AudioStreamFormatImpl.getDefaultInputFormat + * Format information for the audio + */ + get format() { + return Promise.resolve(this.privFormat); + } + /** + * Writes the audio data specified by making an internal copy of the data. + * @member PushAudioInputStreamImpl.prototype.write * @function * @public - * @returns {AudioStreamFormatImpl} The default input format. + * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy. */ - AudioStreamFormatImpl.getDefaultInputFormat = function () { - return new AudioStreamFormatImpl(); - }; + write(dataBuffer) { + this.privStream.writeStreamChunk({ + buffer: dataBuffer, + isEnd: false, + timeReceived: Date.now() + }); + } /** - * Creates an audio context appropriate to current browser - * @member AudioStreamFormatImpl.getAudioContext + * Closes the stream. + * @member PushAudioInputStreamImpl.prototype.close * @function * @public - * @returns {AudioContext} An audio context instance */ - AudioStreamFormatImpl.getAudioContext = function (sampleRate) { - // Workaround for Speech SDK bug in Safari. - var AudioContext = window.AudioContext // our preferred impl - || window.webkitAudioContext // fallback, mostly when on Safari - || false; // could not find. - // https://developer.mozilla.org/en-US/docs/Web/API/AudioContext - if (!!AudioContext) { - if (sampleRate !== undefined && navigator.mediaDevices.getSupportedConstraints().sampleRate) { - return new AudioContext({ sampleRate: sampleRate }); - } - else { - return new AudioContext(); - } + close() { + this.privStream.close(); + } + id() { + return this.privId; + } + turnOn() { + this.onEvent(new Exports_js_2.AudioSourceInitializingEvent(this.privId)); // no stream id + this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId)); + return; + } + async attach(audioNodeId) { + this.onEvent(new Exports_js_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId)); + await this.turnOn(); + const stream = this.privStream; + this.onEvent(new Exports_js_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId)); + return { + detach: async () => { + this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); + return this.turnOff(); + }, + id: () => audioNodeId, + read: () => stream.read(), + }; + } + detach(audioNodeId) { + this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); + } + turnOff() { + return; + } + get events() { + return this.privEvents; + } + get deviceInfo() { + return Promise.resolve({ + bitspersample: this.privFormat.bitsPerSample, + channelcount: this.privFormat.channels, + connectivity: Exports_js_1.connectivity.Unknown, + manufacturer: "Speech SDK", + model: "PushStream", + samplerate: this.privFormat.samplesPerSec, + type: Exports_js_1.type.Stream, + }); + } + onEvent(event) { + this.privEvents.onEvent(event); + Exports_js_2.Events.instance.onEvent(event); + } + toBuffer(arrayBuffer) { + const buf = Buffer.alloc(arrayBuffer.byteLength); + const view = new Uint8Array(arrayBuffer); + for (let i = 0; i < buf.length; ++i) { + buf[i] = view[i]; + } + return buf; + } +} +exports.PushAudioInputStreamImpl = PushAudioInputStreamImpl; +/* + * Represents audio input stream used for custom audio input configurations. + * @class PullAudioInputStream + */ +class PullAudioInputStream extends AudioInputStream { + /** + * Creates and initializes and instance. + * @constructor + */ + constructor() { + super(); + } + /** + * Creates a PullAudioInputStream that delegates to the specified callback interface for + * read() and close() methods, using the default format (16 kHz 16bit mono PCM). + * @member PullAudioInputStream.create + * @function + * @public + * @param {PullAudioInputStreamCallback} callback - The custom audio input object, + * derived from PullAudioInputStreamCustomCallback + * @param {AudioStreamFormat} format - The audio data format in which audio will be + * returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM). + * @returns {PullAudioInputStream} The push audio input stream being created. + */ + static create(callback, format) { + return new PullAudioInputStreamImpl(callback, format); + } +} +exports.PullAudioInputStream = PullAudioInputStream; +/** + * Represents audio input stream used for custom audio input configurations. + * @private + * @class PullAudioInputStreamImpl + */ +class PullAudioInputStreamImpl extends PullAudioInputStream { + /** + * Creates a PullAudioInputStream that delegates to the specified callback interface for + * read() and close() methods, using the default format (16 kHz 16bit mono PCM). + * @constructor + * @param {PullAudioInputStreamCallback} callback - The custom audio input object, + * derived from PullAudioInputStreamCustomCallback + * @param {AudioStreamFormat} format - The audio data format in which audio will be + * returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM). + */ + constructor(callback, format) { + super(); + if (undefined === format) { + this.privFormat = Exports_js_3.AudioStreamFormat.getDefaultInputFormat(); } else { - throw new Error("Browser does not support Web Audio API (AudioContext is not available)."); + this.privFormat = format; } - }; + this.privEvents = new Exports_js_2.EventSource(); + this.privId = (0, Guid_js_1.createNoDashGuid)(); + this.privCallback = callback; + this.privIsClosed = false; + this.privBufferSize = this.privFormat.avgBytesPerSec / 10; + } /** - * Closes the configuration object. - * @member AudioStreamFormatImpl.prototype.close + * Format information for the audio + */ + get format() { + return Promise.resolve(this.privFormat); + } + /** + * Closes the stream. + * @member PullAudioInputStreamImpl.prototype.close * @function * @public */ - AudioStreamFormatImpl.prototype.close = function () { return; }; - Object.defineProperty(AudioStreamFormatImpl.prototype, "header", { - get: function () { - return this.privHeader; - }, - enumerable: false, - configurable: true - }); - return AudioStreamFormatImpl; -}(AudioStreamFormat)); -exports.AudioStreamFormatImpl = AudioStreamFormatImpl; + close() { + this.privIsClosed = true; + this.privCallback.close(); + } + id() { + return this.privId; + } + turnOn() { + this.onEvent(new Exports_js_2.AudioSourceInitializingEvent(this.privId)); // no stream id + this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId)); + return; + } + async attach(audioNodeId) { + this.onEvent(new Exports_js_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId)); + await this.turnOn(); + this.onEvent(new Exports_js_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId)); + return { + detach: () => { + this.privCallback.close(); + this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); + return this.turnOff(); + }, + id: () => audioNodeId, + read: () => { + let totalBytes = 0; + let transmitBuff; + // Until we have the minimum number of bytes to send in a transmission, keep asking for more. + while (totalBytes < this.privBufferSize) { + // Sizing the read buffer to the delta between the perfect size and what's left means we won't ever get too much + // data back. + const readBuff = new ArrayBuffer(this.privBufferSize - totalBytes); + const pulledBytes = this.privCallback.read(readBuff); + // If there is no return buffer yet defined, set the return buffer to the that was just populated. + // This was, if we have enough data there's no copy penalty, but if we don't we have a buffer that's the + // preferred size allocated. + if (undefined === transmitBuff) { + transmitBuff = readBuff; + } + else { + // Not the first bite at the apple, so fill the return buffer with the data we got back. + const intView = new Int8Array(transmitBuff); + intView.set(new Int8Array(readBuff), totalBytes); + } + // If there are no bytes to read, just break out and be done. + if (0 === pulledBytes) { + break; + } + totalBytes += pulledBytes; + } + return Promise.resolve({ + buffer: transmitBuff.slice(0, totalBytes), + isEnd: this.privIsClosed || totalBytes === 0, + timeReceived: Date.now(), + }); + }, + }; + } + detach(audioNodeId) { + this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); + } + turnOff() { + return; + } + get events() { + return this.privEvents; + } + get deviceInfo() { + return Promise.resolve({ + bitspersample: this.privFormat.bitsPerSample, + channelcount: this.privFormat.channels, + connectivity: Exports_js_1.connectivity.Unknown, + manufacturer: "Speech SDK", + model: "PullStream", + samplerate: this.privFormat.samplesPerSec, + type: Exports_js_1.type.Stream, + }); + } + onEvent(event) { + this.privEvents.onEvent(event); + Exports_js_2.Events.instance.onEvent(event); + } +} +exports.PullAudioInputStreamImpl = PullAudioInputStreamImpl; /***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { +/* 90 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PushAudioOutputStreamImpl = exports.PushAudioOutputStream = exports.PullAudioOutputStreamImpl = exports.PullAudioOutputStream = exports.AudioOutputStream = void 0; -// tslint:disable:max-classes-per-file -var Exports_1 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var AudioOutputFormat_1 = __webpack_require__(74); +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const AudioOutputFormat_js_1 = __webpack_require__(91); /** * Represents audio output stream used for custom audio output configurations. * @class AudioOutputStream */ -var AudioOutputStream = /** @class */ (function () { +class AudioOutputStream { /** * Creates and initializes an instance. * @constructor */ - function AudioOutputStream() { + constructor() { + return; } /** * Creates a memory backed PullAudioOutputStream with the specified audio format. @@ -7776,21 +6866,16 @@ var AudioOutputStream = /** @class */ (function () { * @public * @returns {PullAudioOutputStream} The audio output stream being created. */ - AudioOutputStream.createPullStream = function () { + static createPullStream() { return PullAudioOutputStream.create(); - }; - return AudioOutputStream; -}()); + } +} exports.AudioOutputStream = AudioOutputStream; /** * Represents memory backed push audio output stream used for custom audio output configurations. * @class PullAudioOutputStream */ -var PullAudioOutputStream = /** @class */ (function (_super) { - __extends(PullAudioOutputStream, _super); - function PullAudioOutputStream() { - return _super !== null && _super.apply(this, arguments) || this; - } +class PullAudioOutputStream extends AudioOutputStream { /** * Creates a memory backed PullAudioOutputStream with the specified audio format. * @member PullAudioOutputStream.create @@ -7798,71 +6883,60 @@ var PullAudioOutputStream = /** @class */ (function (_super) { * @public * @returns {PullAudioOutputStream} The push audio output stream being created. */ - PullAudioOutputStream.create = function () { + static create() { return new PullAudioOutputStreamImpl(); - }; - return PullAudioOutputStream; -}(AudioOutputStream)); + } +} exports.PullAudioOutputStream = PullAudioOutputStream; /** * Represents memory backed push audio output stream used for custom audio output configurations. * @private * @class PullAudioOutputStreamImpl */ -var PullAudioOutputStreamImpl = /** @class */ (function (_super) { - __extends(PullAudioOutputStreamImpl, _super); +class PullAudioOutputStreamImpl extends PullAudioOutputStream { /** * Creates and initializes an instance with the given values. * @constructor */ - function PullAudioOutputStreamImpl() { - var _this = _super.call(this) || this; - _this.privId = Exports_1.createNoDashGuid(); - _this.privStream = new Exports_1.Stream(); - return _this; - } - Object.defineProperty(PullAudioOutputStreamImpl.prototype, "format", { - /** - * Format information for the audio - */ - get: function () { - return this.privFormat; - }, - /** - * Sets the format information to the stream. For internal use only. - * @param {AudioStreamFormat} format - the format to be set. - */ - set: function (format) { - if (format === undefined || format === null) { - this.privFormat = AudioOutputFormat_1.AudioOutputFormatImpl.getDefaultOutputFormat(); - } - this.privFormat = format; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PullAudioOutputStreamImpl.prototype, "isClosed", { - /** - * Checks if the stream is closed - * @member PullAudioOutputStreamImpl.prototype.isClosed - * @property - * @public - */ - get: function () { - return this.privStream.isClosed; - }, - enumerable: false, - configurable: true - }); + constructor() { + super(); + this.privId = (0, Exports_js_1.createNoDashGuid)(); + this.privStream = new Exports_js_1.Stream(); + } + /** + * Sets the format information to the stream. For internal use only. + * @param {AudioStreamFormat} format - the format to be set. + */ + set format(format) { + if (format === undefined || format === null) { + this.privFormat = AudioOutputFormat_js_1.AudioOutputFormatImpl.getDefaultOutputFormat(); + } + this.privFormat = format; + } + /** + * Format information for the audio + */ + get format() { + return this.privFormat; + } + /** + * Checks if the stream is closed + * @member PullAudioOutputStreamImpl.prototype.isClosed + * @property + * @public + */ + get isClosed() { + return this.privStream.isClosed; + } /** * Gets the id of the stream * @member PullAudioOutputStreamImpl.prototype.id * @property * @public */ - PullAudioOutputStreamImpl.prototype.id = function () { + id() { return this.privId; - }; + } /** * Reads audio data from the internal buffer. * @member PullAudioOutputStreamImpl.prototype.read @@ -7871,52 +6945,40 @@ var PullAudioOutputStreamImpl = /** @class */ (function (_super) { * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data. * @returns {Promise} - Audio buffer length has been read. */ - PullAudioOutputStreamImpl.prototype.read = function (dataBuffer) { - return __awaiter(this, void 0, void 0, function () { - var intView, totalBytes, chunk, tmpBuffer; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - intView = new Int8Array(dataBuffer); - totalBytes = 0; - if (this.privLastChunkView !== undefined) { - if (this.privLastChunkView.length > dataBuffer.byteLength) { - intView.set(this.privLastChunkView.slice(0, dataBuffer.byteLength)); - this.privLastChunkView = this.privLastChunkView.slice(dataBuffer.byteLength); - return [2 /*return*/, Promise.resolve(dataBuffer.byteLength)]; - } - intView.set(this.privLastChunkView); - totalBytes = this.privLastChunkView.length; - this.privLastChunkView = undefined; - } - _a.label = 1; - case 1: - if (!(totalBytes < dataBuffer.byteLength && !this.privStream.isReadEnded)) return [3 /*break*/, 6]; - return [4 /*yield*/, this.privStream.read()]; - case 2: - chunk = _a.sent(); - if (!(chunk !== undefined && !chunk.isEnd)) return [3 /*break*/, 3]; - tmpBuffer = void 0; - if (chunk.buffer.byteLength > dataBuffer.byteLength - totalBytes) { - tmpBuffer = chunk.buffer.slice(0, dataBuffer.byteLength - totalBytes); - this.privLastChunkView = new Int8Array(chunk.buffer.slice(dataBuffer.byteLength - totalBytes)); - } - else { - tmpBuffer = chunk.buffer; - } - intView.set(new Int8Array(tmpBuffer), totalBytes); - totalBytes += tmpBuffer.byteLength; - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, this.privStream.readEnded()]; - case 4: - _a.sent(); - _a.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [2 /*return*/, totalBytes]; + async read(dataBuffer) { + const intView = new Int8Array(dataBuffer); + let totalBytes = 0; + if (this.privLastChunkView !== undefined) { + if (this.privLastChunkView.length > dataBuffer.byteLength) { + intView.set(this.privLastChunkView.slice(0, dataBuffer.byteLength)); + this.privLastChunkView = this.privLastChunkView.slice(dataBuffer.byteLength); + return Promise.resolve(dataBuffer.byteLength); + } + intView.set(this.privLastChunkView); + totalBytes = this.privLastChunkView.length; + this.privLastChunkView = undefined; + } + // Until we have the minimum number of bytes to send in a transmission, keep asking for more. + while (totalBytes < dataBuffer.byteLength && !this.privStream.isReadEnded) { + const chunk = await this.privStream.read(); + if (chunk !== undefined && !chunk.isEnd) { + let tmpBuffer; + if (chunk.buffer.byteLength > dataBuffer.byteLength - totalBytes) { + tmpBuffer = chunk.buffer.slice(0, dataBuffer.byteLength - totalBytes); + this.privLastChunkView = new Int8Array(chunk.buffer.slice(dataBuffer.byteLength - totalBytes)); } - }); - }); - }; + else { + tmpBuffer = chunk.buffer; + } + intView.set(new Int8Array(tmpBuffer), totalBytes); + totalBytes += tmpBuffer.byteLength; + } + else { + this.privStream.readEnded(); + } + } + return totalBytes; + } /** * Writes the audio data specified by making an internal copy of the data. * @member PullAudioOutputStreamImpl.prototype.write @@ -7924,38 +6986,36 @@ var PullAudioOutputStreamImpl = /** @class */ (function (_super) { * @public * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy. */ - PullAudioOutputStreamImpl.prototype.write = function (dataBuffer) { - Contracts_1.Contracts.throwIfNullOrUndefined(this.privStream, "must set format before writing"); + write(dataBuffer) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privStream, "must set format before writing"); this.privStream.writeStreamChunk({ buffer: dataBuffer, isEnd: false, timeReceived: Date.now() }); - }; + } /** * Closes the stream. * @member PullAudioOutputStreamImpl.prototype.close * @function * @public */ - PullAudioOutputStreamImpl.prototype.close = function () { + close() { this.privStream.close(); - }; - return PullAudioOutputStreamImpl; -}(PullAudioOutputStream)); + } +} exports.PullAudioOutputStreamImpl = PullAudioOutputStreamImpl; /* * Represents audio output stream used for custom audio output configurations. * @class PushAudioOutputStream */ -var PushAudioOutputStream = /** @class */ (function (_super) { - __extends(PushAudioOutputStream, _super); +class PushAudioOutputStream extends AudioOutputStream { /** * Creates and initializes and instance. * @constructor */ - function PushAudioOutputStream() { - return _super.call(this) || this; + constructor() { + super(); } /** * Creates a PushAudioOutputStream that delegates to the specified callback interface for @@ -7964,94 +7024,71 @@ var PushAudioOutputStream = /** @class */ (function (_super) { * @function * @public * @param {PushAudioOutputStreamCallback} callback - The custom audio output object, - * derived from PushAudioOutputStreamCallback + * derived from PushAudioOutputStreamCallback * @returns {PushAudioOutputStream} The push audio output stream being created. */ - PushAudioOutputStream.create = function (callback) { + static create(callback) { return new PushAudioOutputStreamImpl(callback); - }; - return PushAudioOutputStream; -}(AudioOutputStream)); + } +} exports.PushAudioOutputStream = PushAudioOutputStream; /** * Represents audio output stream used for custom audio output configurations. * @private * @class PushAudioOutputStreamImpl */ -var PushAudioOutputStreamImpl = /** @class */ (function (_super) { - __extends(PushAudioOutputStreamImpl, _super); +class PushAudioOutputStreamImpl extends PushAudioOutputStream { /** * Creates a PushAudioOutputStream that delegates to the specified callback interface for * read() and close() methods. * @constructor * @param {PushAudioOutputStreamCallback} callback - The custom audio output object, - * derived from PushAudioOutputStreamCallback - */ - function PushAudioOutputStreamImpl(callback) { - var _this = _super.call(this) || this; - _this.privId = Exports_1.createNoDashGuid(); - _this.privCallback = callback; - return _this; - } - Object.defineProperty(PushAudioOutputStreamImpl.prototype, "format", { - // tslint:disable-next-line:no-empty - set: function (format) { }, - enumerable: false, - configurable: true - }); - PushAudioOutputStreamImpl.prototype.write = function (buffer) { + * derived from PushAudioOutputStreamCallback + */ + constructor(callback) { + super(); + this.privId = (0, Exports_js_1.createNoDashGuid)(); + this.privCallback = callback; + } + // eslint-disable-next-line @typescript-eslint/no-empty-function + set format(format) { } + write(buffer) { if (!!this.privCallback.write) { this.privCallback.write(buffer); } - }; - PushAudioOutputStreamImpl.prototype.close = function () { + } + close() { if (!!this.privCallback.close) { this.privCallback.close(); } - }; - PushAudioOutputStreamImpl.prototype.id = function () { + } + id() { return this.privId; - }; - return PushAudioOutputStreamImpl; -}(PushAudioOutputStream)); + } +} exports.PushAudioOutputStreamImpl = PushAudioOutputStreamImpl; /***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { +/* 91 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var _a; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AudioOutputFormatImpl = void 0; -var SpeechSynthesisOutputFormat_1 = __webpack_require__(75); -var AudioStreamFormat_1 = __webpack_require__(72); +const SpeechSynthesisOutputFormat_js_1 = __webpack_require__(92); +const AudioStreamFormat_js_1 = __webpack_require__(73); /** * @private * @class AudioOutputFormatImpl * Updated in version 1.17.0 */ -// tslint:disable-next-line:max-classes-per-file -var AudioOutputFormatImpl = /** @class */ (function (_super) { - __extends(AudioOutputFormatImpl, _super); +// eslint-disable-next-line max-classes-per-file +class AudioOutputFormatImpl extends AudioStreamFormat_js_1.AudioStreamFormatImpl { /** * Creates an instance with the given values. * @constructor @@ -8065,129 +7102,132 @@ var AudioOutputFormatImpl = /** @class */ (function (_super) { * @param {string} requestAudioFormatString - Audio format string sent to service. * @param {boolean} hasHeader - If the format has header or not. */ - function AudioOutputFormatImpl(formatTag, channels, samplesPerSec, avgBytesPerSec, blockAlign, bitsPerSample, audioFormatString, requestAudioFormatString, hasHeader) { - var _this = _super.call(this, samplesPerSec, bitsPerSample, channels, formatTag) || this; - _this.formatTag = formatTag; - _this.avgBytesPerSec = avgBytesPerSec; - _this.blockAlign = blockAlign; - _this.priAudioFormatString = audioFormatString; - _this.priRequestAudioFormatString = requestAudioFormatString; - _this.priHasHeader = hasHeader; - return _this; - } - AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat = function (speechSynthesisOutputFormat) { + constructor(formatTag, channels, samplesPerSec, avgBytesPerSec, blockAlign, bitsPerSample, audioFormatString, requestAudioFormatString, hasHeader) { + super(samplesPerSec, bitsPerSample, channels, formatTag); + this.formatTag = formatTag; + this.avgBytesPerSec = avgBytesPerSec; + this.blockAlign = blockAlign; + this.priAudioFormatString = audioFormatString; + this.priRequestAudioFormatString = requestAudioFormatString; + this.priHasHeader = hasHeader; + } + static fromSpeechSynthesisOutputFormat(speechSynthesisOutputFormat) { if (speechSynthesisOutputFormat === undefined) { return AudioOutputFormatImpl.getDefaultOutputFormat(); } return AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString[speechSynthesisOutputFormat]); - }; - AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString = function (speechSynthesisOutputFormatString) { + } + static fromSpeechSynthesisOutputFormatString(speechSynthesisOutputFormatString) { switch (speechSynthesisOutputFormatString) { case "raw-8khz-8bit-mono-mulaw": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MuLaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MuLaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "riff-16khz-16kbps-mono-siren": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.Siren, 1, 16000, 2000, 40, 0, speechSynthesisOutputFormatString, "audio-16khz-16kbps-mono-siren", true); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.Siren, 1, 16000, 2000, 40, 0, speechSynthesisOutputFormatString, "audio-16khz-16kbps-mono-siren", true); case "audio-16khz-16kbps-mono-siren": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.Siren, 1, 16000, 2000, 40, 0, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.Siren, 1, 16000, 2000, 40, 0, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-16khz-32kbitrate-mono-mp3": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 16000, 32 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 16000, 32 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-16khz-128kbitrate-mono-mp3": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 16000, 128 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 16000, 128 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-16khz-64kbitrate-mono-mp3": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 16000, 64 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 16000, 64 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-24khz-48kbitrate-mono-mp3": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 24000, 48 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 24000, 48 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-24khz-96kbitrate-mono-mp3": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 24000, 96 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 24000, 96 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-24khz-160kbitrate-mono-mp3": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 24000, 160 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 24000, 160 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "raw-16khz-16bit-mono-truesilk": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.SILKSkype, 1, 16000, 32000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.SILKSkype, 1, 16000, 32000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "riff-8khz-16bit-mono-pcm": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 8000, 16000, 2, 16, speechSynthesisOutputFormatString, "raw-8khz-16bit-mono-pcm", true); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 8000, 16000, 2, 16, speechSynthesisOutputFormatString, "raw-8khz-16bit-mono-pcm", true); case "riff-24khz-16bit-mono-pcm": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, "raw-24khz-16bit-mono-pcm", true); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, "raw-24khz-16bit-mono-pcm", true); case "riff-8khz-8bit-mono-mulaw": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MuLaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, "raw-8khz-8bit-mono-mulaw", true); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MuLaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, "raw-8khz-8bit-mono-mulaw", true); case "raw-16khz-16bit-mono-pcm": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 16000, 32000, 2, 16, speechSynthesisOutputFormatString, "raw-16khz-16bit-mono-pcm", false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 16000, 32000, 2, 16, speechSynthesisOutputFormatString, "raw-16khz-16bit-mono-pcm", false); case "raw-24khz-16bit-mono-pcm": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, "raw-24khz-16bit-mono-pcm", false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, "raw-24khz-16bit-mono-pcm", false); case "raw-8khz-16bit-mono-pcm": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 8000, 16000, 2, 16, speechSynthesisOutputFormatString, "raw-8khz-16bit-mono-pcm", false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 8000, 16000, 2, 16, speechSynthesisOutputFormatString, "raw-8khz-16bit-mono-pcm", false); case "ogg-16khz-16bit-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OGG_OPUS, 1, 16000, 8192, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OGG_OPUS, 1, 16000, 8192, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "ogg-24khz-16bit-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OGG_OPUS, 1, 24000, 8192, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OGG_OPUS, 1, 24000, 8192, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "raw-48khz-16bit-mono-pcm": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 48000, 96000, 2, 16, speechSynthesisOutputFormatString, "raw-48khz-16bit-mono-pcm", false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 48000, 96000, 2, 16, speechSynthesisOutputFormatString, "raw-48khz-16bit-mono-pcm", false); case "riff-48khz-16bit-mono-pcm": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 48000, 96000, 2, 16, speechSynthesisOutputFormatString, "raw-48khz-16bit-mono-pcm", true); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 48000, 96000, 2, 16, speechSynthesisOutputFormatString, "raw-48khz-16bit-mono-pcm", true); case "audio-48khz-96kbitrate-mono-mp3": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 48000, 96 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 48000, 96 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-48khz-192kbitrate-mono-mp3": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 48000, 192 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 48000, 192 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "ogg-48khz-16bit-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OGG_OPUS, 1, 48000, 12000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OGG_OPUS, 1, 48000, 12000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "webm-16khz-16bit-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.WEBM_OPUS, 1, 16000, 4000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.WEBM_OPUS, 1, 16000, 4000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "webm-24khz-16bit-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.WEBM_OPUS, 1, 24000, 6000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.WEBM_OPUS, 1, 24000, 6000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "webm-24khz-16bit-24kbps-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.WEBM_OPUS, 1, 24000, 3000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.WEBM_OPUS, 1, 24000, 3000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-16khz-16bit-32kbps-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OPUS, 1, 16000, 4000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OPUS, 1, 16000, 4000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-24khz-16bit-48kbps-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OPUS, 1, 24000, 6000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OPUS, 1, 24000, 6000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-24khz-16bit-24kbps-mono-opus": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OPUS, 1, 24000, 3000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OPUS, 1, 24000, 3000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-24khz-16bit-mono-flac": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.FLAC, 1, 24000, 24000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.FLAC, 1, 24000, 24000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "audio-48khz-16bit-mono-flac": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.FLAC, 1, 48000, 30000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.FLAC, 1, 48000, 30000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "raw-24khz-16bit-mono-truesilk": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.SILKSkype, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.SILKSkype, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "raw-8khz-8bit-mono-alaw": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.ALaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.ALaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "riff-8khz-8bit-mono-alaw": - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.ALaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, "raw-8khz-8bit-mono-alaw", true); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.ALaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, "raw-8khz-8bit-mono-alaw", true); + case "raw-22050hz-16bit-mono-pcm": + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 22050, 44100, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + case "riff-22050hz-16bit-mono-pcm": + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 22050, 44100, 2, 16, speechSynthesisOutputFormatString, "raw-22050hz-16bit-mono-pcm", true); + case "raw-44100hz-16bit-mono-pcm": + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 44100, 88200, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + case "riff-44100hz-16bit-mono-pcm": + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 44100, 88200, 2, 16, speechSynthesisOutputFormatString, "raw-44100hz-16bit-mono-pcm", true); + case "amr-wb-16000h": + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.AMR_WB, 1, 16000, 3052, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); + case "g722-16khz-64kbps": + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.G722, 1, 16000, 8000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false); case "riff-16khz-16bit-mono-pcm": default: - return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 16000, 32000, 2, 16, "riff-16khz-16bit-mono-pcm", "raw-16khz-16bit-mono-pcm", true); + return new AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 16000, 32000, 2, 16, "riff-16khz-16bit-mono-pcm", "raw-16khz-16bit-mono-pcm", true); } - }; - AudioOutputFormatImpl.getDefaultOutputFormat = function () { + } + static getDefaultOutputFormat() { return AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString((typeof window !== "undefined") ? "audio-24khz-48kbitrate-mono-mp3" : "riff-16khz-16bit-mono-pcm"); - }; - Object.defineProperty(AudioOutputFormatImpl.prototype, "hasHeader", { - /** - * Specifies if this audio output format has a header - * @boolean AudioOutputFormatImpl.prototype.hasHeader - * @function - * @public - */ - get: function () { - return this.priHasHeader; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AudioOutputFormatImpl.prototype, "header", { - /** - * Specifies the header of this format - * @ArrayBuffer AudioOutputFormatImpl.prototype.header - * @function - * @public - */ - get: function () { - if (this.hasHeader) { - return this.privHeader; - } - return undefined; - }, - enumerable: false, - configurable: true - }); + } + /** + * Specifies if this audio output format has a header + * @boolean AudioOutputFormatImpl.prototype.hasHeader + * @function + * @public + */ + get hasHeader() { + return this.priHasHeader; + } + /** + * Specifies the header of this format + * @ArrayBuffer AudioOutputFormatImpl.prototype.header + * @function + * @public + */ + get header() { + if (this.hasHeader) { + return this.privHeader; + } + return undefined; + } /** * Updates the header based on the audio length * @member AudioOutputFormatImpl.updateHeader @@ -8195,75 +7235,92 @@ var AudioOutputFormatImpl = /** @class */ (function (_super) { * @public * @param {number} audioLength - the audio length */ - AudioOutputFormatImpl.prototype.updateHeader = function (audioLength) { + updateHeader(audioLength) { if (this.priHasHeader) { - var view = new DataView(this.privHeader); + const view = new DataView(this.privHeader); + view.setUint32(4, audioLength + this.privHeader.byteLength - 8, true); view.setUint32(40, audioLength, true); } - }; - Object.defineProperty(AudioOutputFormatImpl.prototype, "requestAudioFormatString", { - /** - * Specifies the audio format string to be sent to the service - * @string AudioOutputFormatImpl.prototype.requestAudioFormatString - * @function - * @public - */ - get: function () { - return this.priRequestAudioFormatString; - }, - enumerable: false, - configurable: true - }); - AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString = (_a = {}, - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw] = "raw-8khz-8bit-mono-mulaw", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren] = "riff-16khz-16kbps-mono-siren", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren] = "audio-16khz-16kbps-mono-siren", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3] = "audio-16khz-32kbitrate-mono-mp3", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3] = "audio-16khz-128kbitrate-mono-mp3", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3] = "audio-16khz-64kbitrate-mono-mp3", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3] = "audio-24khz-48kbitrate-mono-mp3", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3] = "audio-24khz-96kbitrate-mono-mp3", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3] = "audio-24khz-160kbitrate-mono-mp3", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk] = "raw-16khz-16bit-mono-truesilk", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm] = "riff-16khz-16bit-mono-pcm", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm] = "riff-8khz-16bit-mono-pcm", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm] = "riff-24khz-16bit-mono-pcm", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw] = "riff-8khz-8bit-mono-mulaw", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm] = "raw-16khz-16bit-mono-pcm", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm] = "raw-24khz-16bit-mono-pcm", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm] = "raw-8khz-16bit-mono-pcm", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus] = "ogg-16khz-16bit-mono-opus", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus] = "ogg-24khz-16bit-mono-opus", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm] = "raw-48khz-16bit-mono-pcm", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm] = "riff-48khz-16bit-mono-pcm", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3] = "audio-48khz-96kbitrate-mono-mp3", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3] = "audio-48khz-192kbitrate-mono-mp3", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus] = "ogg-48khz-16bit-mono-opus", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus] = "webm-16khz-16bit-mono-opus", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus] = "webm-24khz-16bit-mono-opus", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Webm24Khz16Bit24KbpsMonoOpus] = "webm-24khz-16bit-24kbps-mono-opus", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk] = "raw-24khz-16bit-mono-truesilk", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw] = "raw-8khz-8bit-mono-alaw", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw] = "riff-8khz-8bit-mono-alaw", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz16Bit32KbpsMonoOpus] = "audio-16khz-16bit-32kbps-mono-opus", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz16Bit48KbpsMonoOpus] = "audio-24khz-16bit-48kbps-mono-opus", - _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz16Bit24KbpsMonoOpus] = "audio-24khz-16bit-24kbps-mono-opus", - _a); - return AudioOutputFormatImpl; -}(AudioStreamFormat_1.AudioStreamFormatImpl)); + } + /** + * Specifies the audio format string to be sent to the service + * @string AudioOutputFormatImpl.prototype.requestAudioFormatString + * @function + * @public + */ + get requestAudioFormatString() { + return this.priRequestAudioFormatString; + } + /** + * Adds audio header + * @param audio the raw audio without header + * @returns the audio with header if applicable + */ + addHeader(audio) { + if (!this.hasHeader) { + return audio; + } + this.updateHeader(audio.byteLength); + const tmp = new Uint8Array(audio.byteLength + this.header.byteLength); + tmp.set(new Uint8Array(this.header), 0); + tmp.set(new Uint8Array(audio), this.header.byteLength); + return tmp.buffer; + } +} exports.AudioOutputFormatImpl = AudioOutputFormatImpl; +AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString = { + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw]: "raw-8khz-8bit-mono-mulaw", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren]: "riff-16khz-16kbps-mono-siren", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren]: "audio-16khz-16kbps-mono-siren", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3]: "audio-16khz-32kbitrate-mono-mp3", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3]: "audio-16khz-128kbitrate-mono-mp3", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3]: "audio-16khz-64kbitrate-mono-mp3", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3]: "audio-24khz-48kbitrate-mono-mp3", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3]: "audio-24khz-96kbitrate-mono-mp3", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3]: "audio-24khz-160kbitrate-mono-mp3", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk]: "raw-16khz-16bit-mono-truesilk", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm]: "riff-16khz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm]: "riff-8khz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm]: "riff-24khz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw]: "riff-8khz-8bit-mono-mulaw", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm]: "raw-16khz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm]: "raw-24khz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm]: "raw-8khz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus]: "ogg-16khz-16bit-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus]: "ogg-24khz-16bit-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm]: "raw-48khz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm]: "riff-48khz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3]: "audio-48khz-96kbitrate-mono-mp3", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3]: "audio-48khz-192kbitrate-mono-mp3", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus]: "ogg-48khz-16bit-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus]: "webm-16khz-16bit-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus]: "webm-24khz-16bit-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Webm24Khz16Bit24KbpsMonoOpus]: "webm-24khz-16bit-24kbps-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk]: "raw-24khz-16bit-mono-truesilk", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw]: "raw-8khz-8bit-mono-alaw", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw]: "riff-8khz-8bit-mono-alaw", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz16Bit32KbpsMonoOpus]: "audio-16khz-16bit-32kbps-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz16Bit48KbpsMonoOpus]: "audio-24khz-16bit-48kbps-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz16Bit24KbpsMonoOpus]: "audio-24khz-16bit-24kbps-mono-opus", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw22050Hz16BitMonoPcm]: "raw-22050hz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff22050Hz16BitMonoPcm]: "riff-22050hz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw44100Hz16BitMonoPcm]: "raw-44100hz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff44100Hz16BitMonoPcm]: "riff-44100hz-16bit-mono-pcm", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.AmrWb16000Hz]: "amr-wb-16000hz", + [SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.G72216Khz64Kbps]: "g722-16khz-64kbps", +}; /***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { +/* 92 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpeechSynthesisOutputFormat = void 0; /** * Define speech synthesis audio output formats. @@ -8453,19 +7510,60 @@ var SpeechSynthesisOutputFormat; * @member SpeechSynthesisOutputFormat.Audio24Khz16Bit24KbpsMonoOpus */ SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio24Khz16Bit24KbpsMonoOpus"] = 32] = "Audio24Khz16Bit24KbpsMonoOpus"; + /** + * raw-22050hz-16bit-mono-pcm + * Raw PCM audio at 22050Hz sampling rate and 16-bit depth. + * Added in version 1.22.0 + * @member SpeechSynthesisOutputFormat.Raw22050Hz16BitMonoPcm + */ + SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw22050Hz16BitMonoPcm"] = 33] = "Raw22050Hz16BitMonoPcm"; + /** + * riff-22050hz-16bit-mono-pcm + * PCM audio at 22050Hz sampling rate and 16-bit depth, with RIFF header. + * Added in version 1.22.0 + * @member SpeechSynthesisOutputFormat.Riff22050Hz16BitMonoPcm + */ + SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff22050Hz16BitMonoPcm"] = 34] = "Riff22050Hz16BitMonoPcm"; + /** + * raw-44100hz-16bit-mono-pcm + * Raw PCM audio at 44100Hz sampling rate and 16-bit depth. + * Added in version 1.22.0 + * @member SpeechSynthesisOutputFormat.Raw44100Hz16BitMonoPcm + */ + SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw44100Hz16BitMonoPcm"] = 35] = "Raw44100Hz16BitMonoPcm"; + /** + * riff-44100hz-16bit-mono-pcm + * PCM audio at 44100Hz sampling rate and 16-bit depth, with RIFF header. + * Added in version 1.22.0 + * @member SpeechSynthesisOutputFormat.Riff44100Hz16BitMonoPcm + */ + SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff44100Hz16BitMonoPcm"] = 36] = "Riff44100Hz16BitMonoPcm"; + /** + * amr-wb-16000hz + * AMR-WB audio at 16kHz sampling rate. + * Added in version 1.38.0 + * @member SpeechSynthesisOutputFormat.AmrWb16000Hz + */ + SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["AmrWb16000Hz"] = 37] = "AmrWb16000Hz"; + /** + * g722-16khz-64kbps + * G.722 audio at 16kHz sampling rate and 64kbps bitrate. + * Added in version 1.38.0 + */ + SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["G72216Khz64Kbps"] = 38] = "G72216Khz64Kbps"; })(SpeechSynthesisOutputFormat = exports.SpeechSynthesisOutputFormat || (exports.SpeechSynthesisOutputFormat = {})); /***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { +/* 93 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CancellationReason = void 0; /** * Defines the possible reasons a recognition result might be canceled. @@ -8488,12 +7586,12 @@ var CancellationReason; /***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { +/* 94 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PullAudioInputStreamCallback = void 0; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. @@ -8502,22 +7600,19 @@ exports.PullAudioInputStreamCallback = void 0; * custom audio input streams). * @class PullAudioInputStreamCallback */ -var PullAudioInputStreamCallback = /** @class */ (function () { - function PullAudioInputStreamCallback() { - } - return PullAudioInputStreamCallback; -}()); +class PullAudioInputStreamCallback { +} exports.PullAudioInputStreamCallback = PullAudioInputStreamCallback; /***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { +/* 95 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PushAudioOutputStreamCallback = void 0; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. @@ -8526,38 +7621,36 @@ exports.PushAudioOutputStreamCallback = void 0; * custom audio output streams). * @class PushAudioOutputStreamCallback */ -var PushAudioOutputStreamCallback = /** @class */ (function () { - function PushAudioOutputStreamCallback() { - } - return PushAudioOutputStreamCallback; -}()); +class PushAudioOutputStreamCallback { +} exports.PushAudioOutputStreamCallback = PushAudioOutputStreamCallback; /***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { +/* 96 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KeywordRecognitionModel = void 0; -var Contracts_1 = __webpack_require__(63); +const Contracts_js_1 = __webpack_require__(70); /** * Represents a keyword recognition model for recognizing when * the user says a keyword to initiate further speech recognition. * @class KeywordRecognitionModel */ -var KeywordRecognitionModel = /** @class */ (function () { +class KeywordRecognitionModel { /** * Create and initializes a new instance. * @constructor */ - function KeywordRecognitionModel() { + constructor() { this.privDisposed = false; + return; } /** * Creates a keyword recognition model using the specified filename. @@ -8565,157 +7658,131 @@ var KeywordRecognitionModel = /** @class */ (function () { * @function * @public * @param {string} fileName - A string that represents file name for the keyword recognition model. - * Note, the file can point to a zip file in which case the model - * will be extracted from the zip. + * Note, the file can point to a zip file in which case the model + * will be extracted from the zip. * @returns {KeywordRecognitionModel} The keyword recognition model being created. */ - KeywordRecognitionModel.fromFile = function (fileName) { - Contracts_1.Contracts.throwIfFileDoesNotExist(fileName, "fileName"); + static fromFile(fileName) { + Contracts_js_1.Contracts.throwIfFileDoesNotExist(fileName, "fileName"); throw new Error("Not yet implemented."); - }; + } /** * Creates a keyword recognition model using the specified filename. * @member KeywordRecognitionModel.fromStream * @function * @public * @param {string} file - A File that represents file for the keyword recognition model. - * Note, the file can point to a zip file in which case the model will be extracted from the zip. + * Note, the file can point to a zip file in which case the model will be extracted from the zip. * @returns {KeywordRecognitionModel} The keyword recognition model being created. */ - KeywordRecognitionModel.fromStream = function (file) { - Contracts_1.Contracts.throwIfNull(file, "file"); + static fromStream(file) { + Contracts_js_1.Contracts.throwIfNull(file, "file"); throw new Error("Not yet implemented."); - }; + } /** * Dispose of associated resources. * @member KeywordRecognitionModel.prototype.close * @function * @public */ - KeywordRecognitionModel.prototype.close = function () { + close() { if (this.privDisposed) { return; } this.privDisposed = true; - }; - return KeywordRecognitionModel; -}()); + } +} exports.KeywordRecognitionModel = KeywordRecognitionModel; /***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { +/* 97 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SessionEventArgs = void 0; /** * Defines content for session events like SessionStarted/Stopped, SoundStarted/Stopped. * @class SessionEventArgs */ -var SessionEventArgs = /** @class */ (function () { +class SessionEventArgs { /** * Creates and initializes an instance of this class. * @constructor * @param {string} sessionId - The session id. */ - function SessionEventArgs(sessionId) { + constructor(sessionId) { this.privSessionId = sessionId; } - Object.defineProperty(SessionEventArgs.prototype, "sessionId", { - /** - * Represents the session identifier. - * @member SessionEventArgs.prototype.sessionId - * @function - * @public - * @returns {string} Represents the session identifier. - */ - get: function () { - return this.privSessionId; - }, - enumerable: false, - configurable: true - }); - return SessionEventArgs; -}()); + /** + * Represents the session identifier. + * @member SessionEventArgs.prototype.sessionId + * @function + * @public + * @returns {string} Represents the session identifier. + */ + get sessionId() { + return this.privSessionId; + } +} exports.SessionEventArgs = SessionEventArgs; /***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { +/* 98 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RecognitionEventArgs = void 0; -var Exports_1 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(85); /** * Defines payload for session events like Speech Start/End Detected * @class */ -var RecognitionEventArgs = /** @class */ (function (_super) { - __extends(RecognitionEventArgs, _super); +class RecognitionEventArgs extends Exports_js_1.SessionEventArgs { /** * Creates and initializes an instance of this class. * @constructor * @param {number} offset - The offset. * @param {string} sessionId - The session id. */ - function RecognitionEventArgs(offset, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privOffset = offset; - return _this; - } - Object.defineProperty(RecognitionEventArgs.prototype, "offset", { - /** - * Represents the message offset - * @member RecognitionEventArgs.prototype.offset - * @function - * @public - */ - get: function () { - return this.privOffset; - }, - enumerable: false, - configurable: true - }); - return RecognitionEventArgs; -}(Exports_1.SessionEventArgs)); + constructor(offset, sessionId) { + super(sessionId); + this.privOffset = offset; + } + /** + * Represents the message offset + * @member RecognitionEventArgs.prototype.offset + * @function + * @public + */ + get offset() { + return this.privOffset; + } +} exports.RecognitionEventArgs = RecognitionEventArgs; /***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { +/* 99 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OutputFormat = void 0; /** * Define Speech Recognizer output formats. @@ -8736,82 +7803,20 @@ var OutputFormat; /***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IntentRecognitionEventArgs = void 0; -var Exports_1 = __webpack_require__(61); -/** - * Intent recognition result event arguments. - * @class - */ -var IntentRecognitionEventArgs = /** @class */ (function (_super) { - __extends(IntentRecognitionEventArgs, _super); - /** - * Creates and initializes an instance of this class. - * @constructor - * @param result - The result of the intent recognition. - * @param offset - The offset. - * @param sessionId - The session id. - */ - function IntentRecognitionEventArgs(result, offset, sessionId) { - var _this = _super.call(this, offset, sessionId) || this; - _this.privResult = result; - return _this; - } - Object.defineProperty(IntentRecognitionEventArgs.prototype, "result", { - /** - * Represents the intent recognition result. - * @member IntentRecognitionEventArgs.prototype.result - * @function - * @public - * @returns {IntentRecognitionResult} Represents the intent recognition result. - */ - get: function () { - return this.privResult; - }, - enumerable: false, - configurable: true - }); - return IntentRecognitionEventArgs; -}(Exports_1.RecognitionEventArgs)); -exports.IntentRecognitionEventArgs = IntentRecognitionEventArgs; - - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { +/* 100 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RecognitionResult = void 0; /** * Defines result of speech recognition. * @class RecognitionResult */ -var RecognitionResult = /** @class */ (function () { +class RecognitionResult { /** * Creates and initializes an instance of this class. * @constructor @@ -8825,8 +7830,9 @@ var RecognitionResult = /** @class */ (function () { * @param {string} errorDetails - Error details, if provided. * @param {string} json - Additional Json, if provided. * @param {PropertyCollection} properties - Additional properties, if provided. + * @param {number} channel - The audio channel the result was recognized on. Defaults to 0 in non-multichannel scenarios. */ - function RecognitionResult(resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) { + constructor(resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties, channel) { this.privResultId = resultId; this.privReason = reason; this.privText = text; @@ -8837,183 +7843,140 @@ var RecognitionResult = /** @class */ (function () { this.privErrorDetails = errorDetails; this.privJson = json; this.privProperties = properties; + this.privChannel = channel === undefined ? 0 : channel; } - Object.defineProperty(RecognitionResult.prototype, "resultId", { - /** - * Specifies the result identifier. - * @member RecognitionResult.prototype.resultId - * @function - * @public - * @returns {string} Specifies the result identifier. - */ - get: function () { - return this.privResultId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "reason", { - /** - * Specifies status of the result. - * @member RecognitionResult.prototype.reason - * @function - * @public - * @returns {ResultReason} Specifies status of the result. - */ - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "text", { - /** - * Presents the recognized text in the result. - * @member RecognitionResult.prototype.text - * @function - * @public - * @returns {string} Presents the recognized text in the result. - */ - get: function () { - return this.privText; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "duration", { - /** - * Duration of recognized speech in 100 nano second increments. - * @member RecognitionResult.prototype.duration - * @function - * @public - * @returns {number} Duration of recognized speech in 100 nano second increments. - */ - get: function () { - return this.privDuration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "offset", { - /** - * Offset of recognized speech in 100 nano second increments. - * @member RecognitionResult.prototype.offset - * @function - * @public - * @returns {number} Offset of recognized speech in 100 nano second increments. - */ - get: function () { - return this.privOffset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "language", { - /** - * Primary Language detected. - * @member RecognitionResult.prototype.language - * @function - * @public - * @returns {string} language detected. - */ - get: function () { - return this.privLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "languageDetectionConfidence", { - /** - * Primary Language detection confidence (Unknown, Low, Medium, High). - * @member RecognitionResult.prototype.languageDetectionConfidence - * @function - * @public - * @returns {string} detection confidence strength. - */ - get: function () { - return this.privLanguageDetectionConfidence; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "errorDetails", { - /** - * In case of an unsuccessful recognition, provides details of the occurred error. - * @member RecognitionResult.prototype.errorDetails - * @function - * @public - * @returns {string} a brief description of an error. - */ - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "json", { - /** - * A string containing Json serialized recognition result as it was received from the service. - * @member RecognitionResult.prototype.json - * @function - * @private - * @returns {string} Json serialized representation of the result. - */ - get: function () { - return this.privJson; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionResult.prototype, "properties", { - /** - * The set of properties exposed in the result. - * @member RecognitionResult.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The set of properties exposed in the result. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - return RecognitionResult; -}()); + /** + * Specifies the result identifier. + * @member RecognitionResult.prototype.resultId + * @function + * @public + * @returns {string} Specifies the result identifier. + */ + get resultId() { + return this.privResultId; + } + /** + * Specifies status of the result. + * @member RecognitionResult.prototype.reason + * @function + * @public + * @returns {ResultReason} Specifies status of the result. + */ + get reason() { + return this.privReason; + } + /** + * Presents the recognized text in the result. + * @member RecognitionResult.prototype.text + * @function + * @public + * @returns {string} Presents the recognized text in the result. + */ + get text() { + return this.privText; + } + /** + * Duration of recognized speech in 100 nano second increments. + * @member RecognitionResult.prototype.duration + * @function + * @public + * @returns {number} Duration of recognized speech in 100 nano second increments. + */ + get duration() { + return this.privDuration; + } + /** + * Offset of recognized speech in 100 nano second increments. + * @member RecognitionResult.prototype.offset + * @function + * @public + * @returns {number} Offset of recognized speech in 100 nano second increments. + */ + get offset() { + return this.privOffset; + } + /** + * Primary Language detected. + * @member RecognitionResult.prototype.language + * @function + * @public + * @returns {string} language detected. + */ + get language() { + return this.privLanguage; + } + /** + * Primary Language detection confidence (Unknown, Low, Medium, High). + * @member RecognitionResult.prototype.languageDetectionConfidence + * @function + * @public + * @returns {string} detection confidence strength. + */ + get languageDetectionConfidence() { + return this.privLanguageDetectionConfidence; + } + /** + * In case of an unsuccessful recognition, provides details of the occurred error. + * @member RecognitionResult.prototype.errorDetails + * @function + * @public + * @returns {string} a brief description of an error. + */ + get errorDetails() { + return this.privErrorDetails; + } + /** + * A string containing Json serialized recognition result as it was received from the service. + * @member RecognitionResult.prototype.json + * @function + * @private + * @returns {string} Json serialized representation of the result. + */ + get json() { + return this.privJson; + } + /** + * The set of properties exposed in the result. + * @member RecognitionResult.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The set of properties exposed in the result. + */ + get properties() { + return this.privProperties; + } + /** + * The audio channel the result was recognized on. In non-multichannel + * scenarios this defaults to 0. + * @member RecognitionResult.prototype.channel + * @function + * @public + * @returns {number} The zero-based audio channel index of the result. + */ + get channel() { + return this.privChannel; + } +} exports.RecognitionResult = RecognitionResult; /***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { +/* 101 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpeechRecognitionResult = void 0; -var Exports_1 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(85); /** * Defines result of speech recognition. * @class SpeechRecognitionResult */ -var SpeechRecognitionResult = /** @class */ (function (_super) { - __extends(SpeechRecognitionResult, _super); +class SpeechRecognitionResult extends Exports_js_1.RecognitionResult { /** * Creates and initializes an instance of this class. * @constructor @@ -9029,368 +7992,138 @@ var SpeechRecognitionResult = /** @class */ (function (_super) { * @param {string} errorDetails - Error details, if provided. * @param {string} json - Additional Json, if provided. * @param {PropertyCollection} properties - Additional properties, if provided. + * @param {number} channel - The audio channel the result was recognized on. Defaults to 0 in non-multichannel scenarios. */ - function SpeechRecognitionResult(resultId, reason, text, duration, offset, language, languageDetectionConfidence, speakerId, errorDetails, json, properties) { - var _this = _super.call(this, resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) || this; - _this.privSpeakerId = speakerId; - return _this; - } - Object.defineProperty(SpeechRecognitionResult.prototype, "speakerId", { - /** - * speaker id from conversation transcription/id scenarios - * @member SpeechRecognitionResult.prototype.speakerId - * @function - * @public - * @returns {string} id of speaker in given result - */ - get: function () { - return this.privSpeakerId; - }, - enumerable: false, - configurable: true - }); - return SpeechRecognitionResult; -}(Exports_1.RecognitionResult)); + constructor(resultId, reason, text, duration, offset, language, languageDetectionConfidence, speakerId, errorDetails, json, properties, channel) { + super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties, channel); + this.privSpeakerId = speakerId; + } + /** + * speaker id from conversation transcription/id scenarios + * @member SpeechRecognitionResult.prototype.speakerId + * @function + * @public + * @returns {string} id of speaker in given result + */ + get speakerId() { + return this.privSpeakerId; + } +} exports.SpeechRecognitionResult = SpeechRecognitionResult; /***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { +/* 102 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IntentRecognitionResult = void 0; -var Exports_1 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MeetingTranscriptionEventArgs = exports.ConversationTranscriptionEventArgs = exports.SpeechRecognitionEventArgs = void 0; +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(85); /** - * Intent recognition result. - * @class + * Defines contents of speech recognizing/recognized event. + * @class SpeechRecognitionEventArgs */ -var IntentRecognitionResult = /** @class */ (function (_super) { - __extends(IntentRecognitionResult, _super); +class SpeechRecognitionEventArgs extends Exports_js_1.RecognitionEventArgs { /** * Creates and initializes an instance of this class. * @constructor - * @param intentId - The intent id. - * @param resultId - The result id. - * @param reason - The reason. - * @param text - The recognized text. - * @param duration - The duration. - * @param offset - The offset into the stream. - * @param language - Primary Language detected, if provided. - * @param languageDetectionConfidence - Primary Language confidence ("Unknown," "Low," "Medium," "High"...), if provided. - * @param errorDetails - Error details, if provided. - * @param json - Additional Json, if provided. - * @param properties - Additional properties, if provided. - */ - function IntentRecognitionResult(intentId, resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) { - var _this = _super.call(this, resultId, reason, text, duration, offset, language, languageDetectionConfidence, undefined, errorDetails, json, properties) || this; - _this.privIntentId = intentId; - return _this; - } - Object.defineProperty(IntentRecognitionResult.prototype, "intentId", { - /** - * A String that represents the intent identifier being recognized. - * @member IntentRecognitionResult.prototype.intentId - * @function - * @public - * @returns {string} A String that represents the intent identifier being recognized. - */ - get: function () { - return this.privIntentId; - }, - enumerable: false, - configurable: true - }); - return IntentRecognitionResult; -}(Exports_1.SpeechRecognitionResult)); -exports.IntentRecognitionResult = IntentRecognitionResult; - - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LanguageUnderstandingModelImpl = exports.LanguageUnderstandingModel = void 0; -var Contracts_1 = __webpack_require__(63); -/** - * Language understanding model - * @class LanguageUnderstandingModel - */ -var LanguageUnderstandingModel = /** @class */ (function () { - /** - * Creates and initializes a new instance - * @constructor + * @param {SpeechRecognitionResult} result - The speech recognition result. + * @param {number} offset - The offset. + * @param {string} sessionId - The session id. */ - function LanguageUnderstandingModel() { + constructor(result, offset, sessionId) { + super(offset, sessionId); + this.privResult = result; } /** - * Creates an language understanding model using the specified endpoint. - * @member LanguageUnderstandingModel.fromEndpoint - * @function - * @public - * @param {URL} uri - A String that represents the endpoint of the language understanding model. - * @returns {LanguageUnderstandingModel} The language understanding model being created. - */ - LanguageUnderstandingModel.fromEndpoint = function (uri) { - Contracts_1.Contracts.throwIfNull(uri, "uri"); - Contracts_1.Contracts.throwIfNullOrWhitespace(uri.hostname, "uri"); - var langModelImp = new LanguageUnderstandingModelImpl(); - // Need to extract the app ID from the URL. - // URL is in the format: https://.api.cognitive.microsoft.com/luis/v2.0/apps/?subscription-key=&timezoneOffset=-360 - // Start tearing the string apart. - // region can be extracted from the host name. - var firstDot = uri.host.indexOf("."); - if (-1 === firstDot) { - throw new Error("Could not determine region from endpoint"); - } - langModelImp.region = uri.host.substr(0, firstDot); - // Now the app ID. - var lastSegment = uri.pathname.lastIndexOf("/") + 1; - if (-1 === lastSegment) { - throw new Error("Could not determine appId from endpoint"); - } - langModelImp.appId = uri.pathname.substr(lastSegment); - // And finally the key. - langModelImp.subscriptionKey = uri.searchParams.get("subscription-key"); - if (undefined === langModelImp.subscriptionKey) { - throw new Error("Could not determine subscription key from endpoint"); - } - return langModelImp; - }; - /** - * Creates an language understanding model using the application id of Language Understanding service. - * @member LanguageUnderstandingModel.fromAppId - * @function - * @public - * @param {string} appId - A String that represents the application id of Language Understanding service. - * @returns {LanguageUnderstandingModel} The language understanding model being created. - */ - LanguageUnderstandingModel.fromAppId = function (appId) { - Contracts_1.Contracts.throwIfNullOrWhitespace(appId, "appId"); - var langModelImp = new LanguageUnderstandingModelImpl(); - langModelImp.appId = appId; - return langModelImp; - }; - /** - * Creates a language understanding model using hostname, subscription key and application - * id of Language Understanding service. - * @member LanguageUnderstandingModel.fromSubscription + * Specifies the recognition result. + * @member SpeechRecognitionEventArgs.prototype.result * @function * @public - * @param {string} subscriptionKey - A String that represents the subscription key of - * Language Understanding service. - * @param {string} appId - A String that represents the application id of Language - * Understanding service. - * @param {LanguageUnderstandingModel} region - A String that represents the region - * of the Language Understanding service (see the region page). - * @returns {LanguageUnderstandingModel} The language understanding model being created. - */ - LanguageUnderstandingModel.fromSubscription = function (subscriptionKey, appId, region) { - Contracts_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey"); - Contracts_1.Contracts.throwIfNullOrWhitespace(appId, "appId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var langModelImp = new LanguageUnderstandingModelImpl(); - langModelImp.appId = appId; - langModelImp.region = region; - langModelImp.subscriptionKey = subscriptionKey; - return langModelImp; - }; - return LanguageUnderstandingModel; -}()); -exports.LanguageUnderstandingModel = LanguageUnderstandingModel; -/** - * @private - * @class LanguageUnderstandingModelImpl - */ -// tslint:disable-next-line:max-classes-per-file -var LanguageUnderstandingModelImpl = /** @class */ (function (_super) { - __extends(LanguageUnderstandingModelImpl, _super); - function LanguageUnderstandingModelImpl() { - return _super !== null && _super.apply(this, arguments) || this; + * @returns {SpeechRecognitionResult} the recognition result. + */ + get result() { + return this.privResult; } - return LanguageUnderstandingModelImpl; -}(LanguageUnderstandingModel)); -exports.LanguageUnderstandingModelImpl = LanguageUnderstandingModelImpl; - - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranscriptionEventArgs = exports.SpeechRecognitionEventArgs = void 0; -var Exports_1 = __webpack_require__(61); +} +exports.SpeechRecognitionEventArgs = SpeechRecognitionEventArgs; /** - * Defines contents of speech recognizing/recognized event. - * @class SpeechRecognitionEventArgs + * Defines contents of conversation transcribed/transcribing event. + * @class ConversationTranscriptionEventArgs */ -var SpeechRecognitionEventArgs = /** @class */ (function (_super) { - __extends(SpeechRecognitionEventArgs, _super); +class ConversationTranscriptionEventArgs extends Exports_js_1.RecognitionEventArgs { /** * Creates and initializes an instance of this class. * @constructor - * @param {SpeechRecognitionResult} result - The speech recognition result. + * @param {ConversationTranscriptionResult} result - The conversation transcription result. * @param {number} offset - The offset. * @param {string} sessionId - The session id. */ - function SpeechRecognitionEventArgs(result, offset, sessionId) { - var _this = _super.call(this, offset, sessionId) || this; - _this.privResult = result; - return _this; - } - Object.defineProperty(SpeechRecognitionEventArgs.prototype, "result", { - /** - * Specifies the recognition result. - * @member SpeechRecognitionEventArgs.prototype.result - * @function - * @public - * @returns {SpeechRecognitionResult} the recognition result. - */ - get: function () { - return this.privResult; - }, - enumerable: false, - configurable: true - }); - return SpeechRecognitionEventArgs; -}(Exports_1.RecognitionEventArgs)); -exports.SpeechRecognitionEventArgs = SpeechRecognitionEventArgs; + constructor(result, offset, sessionId) { + super(offset, sessionId); + this.privResult = result; + } + /** + * Specifies the transcription result. + * @member ConversationTranscription1EventArgs.prototype.result + * @function + * @public + * @returns {ConversationTranscriptionResult} the recognition result. + */ + get result() { + return this.privResult; + } +} +exports.ConversationTranscriptionEventArgs = ConversationTranscriptionEventArgs; /** - * Defines contents of conversation transcribed/transcribing event. - * @class ConversationTranscriptionEventArgs + * Defines contents of meeting transcribed/transcribing event. + * @class MeetingTranscriptionEventArgs */ -// tslint:disable-next-line:max-classes-per-file -var ConversationTranscriptionEventArgs = /** @class */ (function (_super) { - __extends(ConversationTranscriptionEventArgs, _super); - function ConversationTranscriptionEventArgs() { - return _super !== null && _super.apply(this, arguments) || this; - } - return ConversationTranscriptionEventArgs; -}(SpeechRecognitionEventArgs)); -exports.ConversationTranscriptionEventArgs = ConversationTranscriptionEventArgs; +class MeetingTranscriptionEventArgs extends SpeechRecognitionEventArgs { +} +exports.MeetingTranscriptionEventArgs = MeetingTranscriptionEventArgs; /***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { +/* 103 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpeechRecognitionCanceledEventArgs = void 0; -var CancellationEventArgsBase_1 = __webpack_require__(90); -var SpeechRecognitionCanceledEventArgs = /** @class */ (function (_super) { - __extends(SpeechRecognitionCanceledEventArgs, _super); - function SpeechRecognitionCanceledEventArgs() { - return _super !== null && _super.apply(this, arguments) || this; - } - return SpeechRecognitionCanceledEventArgs; -}(CancellationEventArgsBase_1.CancellationEventArgsBase)); +const CancellationEventArgsBase_js_1 = __webpack_require__(104); +class SpeechRecognitionCanceledEventArgs extends CancellationEventArgsBase_js_1.CancellationEventArgsBase { +} exports.SpeechRecognitionCanceledEventArgs = SpeechRecognitionCanceledEventArgs; /***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { +/* 104 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CancellationEventArgsBase = void 0; -var Exports_1 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(85); /** * Defines content of a CancellationEvent. * @class CancellationEventArgsBase */ -var CancellationEventArgsBase = /** @class */ (function (_super) { - __extends(CancellationEventArgsBase, _super); +class CancellationEventArgsBase extends Exports_js_1.RecognitionEventArgs { /** * Creates and initializes an instance of this class. * @constructor @@ -9399,88 +8132,60 @@ var CancellationEventArgsBase = /** @class */ (function (_super) { * @param {number} offset - The offset. * @param {string} sessionId - The session id. */ - function CancellationEventArgsBase(reason, errorDetails, errorCode, offset, sessionId) { - var _this = _super.call(this, offset, sessionId) || this; - _this.privReason = reason; - _this.privErrorDetails = errorDetails; - _this.privErrorCode = errorCode; - return _this; - } - Object.defineProperty(CancellationEventArgsBase.prototype, "reason", { - /** - * The reason the recognition was canceled. - * @member CancellationEventArgsBase.prototype.reason - * @function - * @public - * @returns {CancellationReason} Specifies the reason canceled. - */ - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CancellationEventArgsBase.prototype, "errorCode", { - /** - * The error code in case of an unsuccessful operation. - * @return An error code that represents the error reason. - */ - get: function () { - return this.privErrorCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CancellationEventArgsBase.prototype, "errorDetails", { - /** - * In case of an unsuccessful operation, provides details of the occurred error. - * @member CancellationEventArgsBase.prototype.errorDetails - * @function - * @public - * @returns {string} A String that represents the error details. - */ - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - return CancellationEventArgsBase; -}(Exports_1.RecognitionEventArgs)); + constructor(reason, errorDetails, errorCode, offset, sessionId) { + super(offset, sessionId); + this.privReason = reason; + this.privErrorDetails = errorDetails; + this.privErrorCode = errorCode; + } + /** + * The reason the recognition was canceled. + * @member CancellationEventArgsBase.prototype.reason + * @function + * @public + * @returns {CancellationReason} Specifies the reason canceled. + */ + get reason() { + return this.privReason; + } + /** + * The error code in case of an unsuccessful operation. + * @return An error code that represents the error reason. + */ + get errorCode() { + return this.privErrorCode; + } + /** + * In case of an unsuccessful operation, provides details of the occurred error. + * @member CancellationEventArgsBase.prototype.errorDetails + * @function + * @public + * @returns {string} A String that represents the error details. + */ + get errorDetails() { + return this.privErrorDetails; + } +} exports.CancellationEventArgsBase = CancellationEventArgsBase; /***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { +/* 105 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TranslationRecognitionEventArgs = void 0; -var Exports_1 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(85); /** * Translation text result event arguments. * @class TranslationRecognitionEventArgs */ -var TranslationRecognitionEventArgs = /** @class */ (function (_super) { - __extends(TranslationRecognitionEventArgs, _super); +class TranslationRecognitionEventArgs extends Exports_js_1.RecognitionEventArgs { /** * Creates and initializes an instance of this class. * @constructor @@ -9488,122 +8193,82 @@ var TranslationRecognitionEventArgs = /** @class */ (function (_super) { * @param {number} offset - The offset. * @param {string} sessionId - The session id. */ - function TranslationRecognitionEventArgs(result, offset, sessionId) { - var _this = _super.call(this, offset, sessionId) || this; - _this.privResult = result; - return _this; - } - Object.defineProperty(TranslationRecognitionEventArgs.prototype, "result", { - /** - * Specifies the recognition result. - * @member TranslationRecognitionEventArgs.prototype.result - * @function - * @public - * @returns {TranslationRecognitionResult} the recognition result. - */ - get: function () { - return this.privResult; - }, - enumerable: false, - configurable: true - }); - return TranslationRecognitionEventArgs; -}(Exports_1.RecognitionEventArgs)); + constructor(result, offset, sessionId) { + super(offset, sessionId); + this.privResult = result; + } + /** + * Specifies the recognition result. + * @member TranslationRecognitionEventArgs.prototype.result + * @function + * @public + * @returns {TranslationRecognitionResult} the recognition result. + */ + get result() { + return this.privResult; + } +} exports.TranslationRecognitionEventArgs = TranslationRecognitionEventArgs; /***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { +/* 106 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TranslationSynthesisEventArgs = void 0; -var Exports_1 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(85); /** * Translation Synthesis event arguments * @class TranslationSynthesisEventArgs */ -var TranslationSynthesisEventArgs = /** @class */ (function (_super) { - __extends(TranslationSynthesisEventArgs, _super); +class TranslationSynthesisEventArgs extends Exports_js_1.SessionEventArgs { /** * Creates and initializes an instance of this class. * @constructor * @param {TranslationSynthesisResult} result - The translation synthesis result. * @param {string} sessionId - The session id. */ - function TranslationSynthesisEventArgs(result, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privResult = result; - return _this; - } - Object.defineProperty(TranslationSynthesisEventArgs.prototype, "result", { - /** - * Specifies the translation synthesis result. - * @member TranslationSynthesisEventArgs.prototype.result - * @function - * @public - * @returns {TranslationSynthesisResult} Specifies the translation synthesis result. - */ - get: function () { - return this.privResult; - }, - enumerable: false, - configurable: true - }); - return TranslationSynthesisEventArgs; -}(Exports_1.SessionEventArgs)); + constructor(result, sessionId) { + super(sessionId); + this.privResult = result; + } + /** + * Specifies the translation synthesis result. + * @member TranslationSynthesisEventArgs.prototype.result + * @function + * @public + * @returns {TranslationSynthesisResult} Specifies the translation synthesis result. + */ + get result() { + return this.privResult; + } +} exports.TranslationSynthesisEventArgs = TranslationSynthesisEventArgs; /***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { +/* 107 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TranslationRecognitionResult = void 0; -var Exports_1 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(85); /** * Translation text result. * @class TranslationRecognitionResult */ -var TranslationRecognitionResult = /** @class */ (function (_super) { - __extends(TranslationRecognitionResult, _super); +class TranslationRecognitionResult extends Exports_js_1.SpeechRecognitionResult { /** * Creates and initializes an instance of this class. * @constructor @@ -9613,107 +8278,97 @@ var TranslationRecognitionResult = /** @class */ (function (_super) { * @param {string} text - The recognized text. * @param {number} duration - The duration. * @param {number} offset - The offset into the stream. + * @param {string} language - Primary Language detected, if provided. + * @param {string} languageDetectionConfidence - Primary Language confidence ("Unknown," "Low," "Medium," "High"...), if provided. * @param {string} errorDetails - Error details, if provided. * @param {string} json - Additional Json, if provided. * @param {PropertyCollection} properties - Additional properties, if provided. */ - function TranslationRecognitionResult(translations, resultId, reason, text, duration, offset, errorDetails, json, properties) { - var _this = _super.call(this, resultId, reason, text, duration, offset, undefined, undefined, undefined, errorDetails, json, properties) || this; - _this.privTranslations = translations; - return _this; - } - Object.defineProperty(TranslationRecognitionResult.prototype, "translations", { - /** - * Presents the translation results. Each item in the dictionary represents - * a translation result in one of target languages, where the key is the name - * of the target language, in BCP-47 format, and the value is the translation - * text in the specified language. - * @member TranslationRecognitionResult.prototype.translations - * @function - * @public - * @returns {Translations} the current translation map that holds all translations requested. - */ - get: function () { - return this.privTranslations; - }, - enumerable: false, - configurable: true - }); - return TranslationRecognitionResult; -}(Exports_1.SpeechRecognitionResult)); + constructor(translations, resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) { + super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, undefined, errorDetails, json, properties); + this.privTranslations = translations; + } + static fromSpeechRecognitionResult(result) { + return new TranslationRecognitionResult(undefined, result.resultId, result.reason, result.text, result.duration, result.offset, result.language, result.languageDetectionConfidence, result.errorDetails, result.json, result.properties); + } + /** + * Presents the translation results. Each item in the dictionary represents + * a translation result in one of target languages, where the key is the name + * of the target language, in BCP-47 format, and the value is the translation + * text in the specified language. + * @member TranslationRecognitionResult.prototype.translations + * @function + * @public + * @returns {Translations} the current translation map that holds all translations requested. + */ + get translations() { + return this.privTranslations; + } +} exports.TranslationRecognitionResult = TranslationRecognitionResult; /***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { +/* 108 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TranslationSynthesisResult = void 0; /** * Defines translation synthesis result, i.e. the voice output of the translated * text in the target language. * @class TranslationSynthesisResult */ -var TranslationSynthesisResult = /** @class */ (function () { +class TranslationSynthesisResult { /** * Creates and initializes an instance of this class. * @constructor * @param {ResultReason} reason - The synthesis reason. * @param {ArrayBuffer} audio - The audio data. */ - function TranslationSynthesisResult(reason, audio) { + constructor(reason, audio) { this.privReason = reason; this.privAudio = audio; } - Object.defineProperty(TranslationSynthesisResult.prototype, "audio", { - /** - * Translated text in the target language. - * @member TranslationSynthesisResult.prototype.audio - * @function - * @public - * @returns {ArrayBuffer} Translated audio in the target language. - */ - get: function () { - return this.privAudio; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationSynthesisResult.prototype, "reason", { - /** - * The synthesis status. - * @member TranslationSynthesisResult.prototype.reason - * @function - * @public - * @returns {ResultReason} The synthesis status. - */ - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - return TranslationSynthesisResult; -}()); + /** + * Translated text in the target language. + * @member TranslationSynthesisResult.prototype.audio + * @function + * @public + * @returns {ArrayBuffer} Translated audio in the target language. + */ + get audio() { + return this.privAudio; + } + /** + * The synthesis status. + * @member TranslationSynthesisResult.prototype.reason + * @function + * @public + * @returns {ResultReason} The synthesis status. + */ + get reason() { + return this.privReason; + } +} exports.TranslationSynthesisResult = TranslationSynthesisResult; /***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { +/* 109 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ResultReason = void 0; /** * Defines the possible reasons a recognition result might be generated. @@ -9750,122 +8405,95 @@ var ResultReason; * @member ResultReason.RecognizedKeyword */ ResultReason[ResultReason["RecognizedKeyword"] = 4] = "RecognizedKeyword"; - /** - * Indicates the intent result contains hypothesis text and intent. - * @member ResultReason.RecognizingIntent - */ - ResultReason[ResultReason["RecognizingIntent"] = 5] = "RecognizingIntent"; - /** - * Indicates the intent result contains final text and intent. - * Speech Recognition and Intent determination are now complete for this phrase. - * @member ResultReason.RecognizedIntent - */ - ResultReason[ResultReason["RecognizedIntent"] = 6] = "RecognizedIntent"; /** * Indicates the translation result contains hypothesis text and its translation(s). * @member ResultReason.TranslatingSpeech */ - ResultReason[ResultReason["TranslatingSpeech"] = 7] = "TranslatingSpeech"; + ResultReason[ResultReason["TranslatingSpeech"] = 5] = "TranslatingSpeech"; /** * Indicates the translation result contains final text and corresponding translation(s). * Speech Recognition and Translation are now complete for this phrase. * @member ResultReason.TranslatedSpeech */ - ResultReason[ResultReason["TranslatedSpeech"] = 8] = "TranslatedSpeech"; + ResultReason[ResultReason["TranslatedSpeech"] = 6] = "TranslatedSpeech"; /** * Indicates the synthesized audio result contains a non-zero amount of audio data * @member ResultReason.SynthesizingAudio */ - ResultReason[ResultReason["SynthesizingAudio"] = 9] = "SynthesizingAudio"; + ResultReason[ResultReason["SynthesizingAudio"] = 7] = "SynthesizingAudio"; /** * Indicates the synthesized audio is now complete for this phrase. * @member ResultReason.SynthesizingAudioCompleted */ - ResultReason[ResultReason["SynthesizingAudioCompleted"] = 10] = "SynthesizingAudioCompleted"; + ResultReason[ResultReason["SynthesizingAudioCompleted"] = 8] = "SynthesizingAudioCompleted"; /** * Indicates the speech synthesis is now started * @member ResultReason.SynthesizingAudioStarted */ - ResultReason[ResultReason["SynthesizingAudioStarted"] = 11] = "SynthesizingAudioStarted"; - /** - * Indicates the voice profile is being enrolled and customers need to send more audio to create a voice profile. - * @member ResultReason.EnrollingVoiceProfile - */ - ResultReason[ResultReason["EnrollingVoiceProfile"] = 12] = "EnrollingVoiceProfile"; - /** - * Indicates the voice profile has been enrolled. - * @member ResultReason.EnrolledVoiceProfile - */ - ResultReason[ResultReason["EnrolledVoiceProfile"] = 13] = "EnrolledVoiceProfile"; + ResultReason[ResultReason["SynthesizingAudioStarted"] = 9] = "SynthesizingAudioStarted"; /** - * Indicates successful identification of some speakers. - * @member ResultReason.RecognizedSpeakers + * Indicates synthesis voices list has been successfully retrieved. + * @member ResultReason.VoicesListRetrieved */ - ResultReason[ResultReason["RecognizedSpeakers"] = 14] = "RecognizedSpeakers"; + ResultReason[ResultReason["VoicesListRetrieved"] = 10] = "VoicesListRetrieved"; /** - * Indicates successfully verified one speaker. - * @member ResultReason.RecognizedSpeaker + * Indicates the transcription result contains hypothesis text and its translation(s) for + * other participants in the conversation. + * @member ResultReason.TranslatingParticipantSpeech */ - ResultReason[ResultReason["RecognizedSpeaker"] = 15] = "RecognizedSpeaker"; + ResultReason[ResultReason["TranslatingParticipantSpeech"] = 11] = "TranslatingParticipantSpeech"; /** - * Indicates a voice profile has been reset successfully. - * @member ResultReason.ResetVoiceProfile + * Indicates the transcription result contains final text and corresponding translation(s) + * for other participants in the conversation. Speech Recognition and Translation are now + * complete for this phrase. + * @member ResultReason.TranslatedParticipantSpeech */ - ResultReason[ResultReason["ResetVoiceProfile"] = 16] = "ResetVoiceProfile"; + ResultReason[ResultReason["TranslatedParticipantSpeech"] = 12] = "TranslatedParticipantSpeech"; /** - * Indicates a voice profile has been deleted successfully. - * @member ResultReason.DeletedVoiceProfile + * + * Indicates the transcription result contains the instant message and corresponding + * translation(s). + * @member ResultReason.TranslatedInstantMessage */ - ResultReason[ResultReason["DeletedVoiceProfile"] = 17] = "DeletedVoiceProfile"; + ResultReason[ResultReason["TranslatedInstantMessage"] = 13] = "TranslatedInstantMessage"; /** - * Indicates synthesis voices list has been successfully retrieved. - * @member ResultReason.VoicesListRetrieved + * Indicates the transcription result contains the instant message for other participants + * in the conversation and corresponding translation(s). + * @member ResultReason.TranslatedParticipantInstantMessage */ - ResultReason[ResultReason["VoicesListRetrieved"] = 18] = "VoicesListRetrieved"; + ResultReason[ResultReason["TranslatedParticipantInstantMessage"] = 14] = "TranslatedParticipantInstantMessage"; })(ResultReason = exports.ResultReason || (exports.ResultReason = {})); /***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { +/* 110 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +/* eslint-disable max-classes-per-file */ +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpeechConfigImpl = exports.SpeechConfig = void 0; -var Exports_1 = __webpack_require__(53); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(2); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_2 = __webpack_require__(85); /** * Speech configuration. * @class SpeechConfig */ -var SpeechConfig = /** @class */ (function () { +class SpeechConfig { /** * Creates and initializes an instance. * @constructor */ - function SpeechConfig() { + constructor() { + return; } /** * Static instance of SpeechConfig returned by passing subscriptionKey and service region. - * Note: Please use your LanguageUnderstanding subscription key in case you want to use the Intent recognizer. * @member SpeechConfig.fromSubscription * @function * @public @@ -9873,43 +8501,44 @@ var SpeechConfig = /** @class */ (function () { * @param {string} region - The region name (see the region page). * @returns {SpeechConfig} The speech factory */ - SpeechConfig.fromSubscription = function (subscriptionKey, region) { - Contracts_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var speechImpl = new SpeechConfigImpl(); - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, region); - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_IntentRegion, region); - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); + static fromSubscription(subscriptionKey, region) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region"); + const speechImpl = new SpeechConfigImpl(); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, region); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); return speechImpl; - }; + } /** - * Creates an instance of the speech config with specified endpoint and subscription key. - * This method is intended only for users who use a non-standard service endpoint or parameters. - * Note: Please use your LanguageUnderstanding subscription key in case you want to use the Intent recognizer. - * Note: The query parameters specified in the endpoint URL are not changed, even if they are set by any other APIs. - * For example, if language is defined in the uri as query parameter "language=de-DE", and also set by - * SpeechConfig.speechRecognitionLanguage = "en-US", the language setting in uri takes precedence, - * and the effective language is "de-DE". Only the parameters that are not specified in the - * endpoint URL can be set by other APIs. - * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the - * fromEndpoint method, and then set authorizationToken="token" on the created SpeechConfig instance to - * use the authorization token. - * @member SpeechConfig.fromEndpoint - * @function - * @public - * @param {URL} endpoint - The service endpoint to connect to. - * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set. - * @returns {SpeechConfig} A speech factory instance. + * Internal implementation of fromEndpoint() overloads. Accepts either a subscription key or a TokenCredential. + * @private */ - SpeechConfig.fromEndpoint = function (endpoint, subscriptionKey) { - Contracts_1.Contracts.throwIfNull(endpoint, "endpoint"); - var speechImpl = new SpeechConfigImpl(); - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, endpoint.href); - if (undefined !== subscriptionKey) { - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); + static fromEndpoint(endpoint, auth) { + Contracts_js_1.Contracts.throwIfNull(endpoint, "endpoint"); + const isValidString = typeof auth === "string" && auth.trim().length > 0; + const isTokenCredential = typeof auth === "object" && auth !== null && typeof auth.getToken === "function"; + const isKeyCredential = typeof auth === "object" && auth !== null && typeof auth.key === "string"; + if (auth !== undefined && !isValidString && !isTokenCredential && !isKeyCredential) { + throw new Error("Invalid 'auth' parameter: expected a non-empty API key string, a TokenCredential, or a KeyCredential."); + } + let speechImpl; + if (typeof auth === "string") { + speechImpl = new SpeechConfigImpl(); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, auth); + } + else if (typeof auth === "object" && typeof auth.getToken === "function") { + speechImpl = new SpeechConfigImpl(auth); + } + else if (typeof auth === "object" && typeof auth.key === "string") { + speechImpl = new SpeechConfigImpl(); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, auth.key); } + else { + speechImpl = new SpeechConfigImpl(); + } + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, endpoint.href); return speechImpl; - }; + } /** * Creates an instance of the speech config with specified host and subscription key. * This method is intended only for users who use a non-default service host. Standard resource path will be assumed. @@ -9925,24 +8554,25 @@ var SpeechConfig = /** @class */ (function () { * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set. * @returns {SpeechConfig} A speech factory instance. */ - SpeechConfig.fromHost = function (hostName, subscriptionKey) { - Contracts_1.Contracts.throwIfNull(hostName, "hostName"); - var speechImpl = new SpeechConfigImpl(); - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port)); + static fromHost(hostName, subscriptionKey) { + Contracts_js_1.Contracts.throwIfNull(hostName, "hostName"); + const speechImpl = new SpeechConfigImpl(); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port)); + // Containers do not yet have /stt/speech/universal/v2 routes. + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "1"); if (undefined !== subscriptionKey) { - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); } return speechImpl; - }; + } /** * Creates an instance of the speech factory with specified initial authorization token and region. * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token - * expires, the caller needs to refresh it by calling this setter with a new valid token. - * Note: Please use a token derived from your LanguageUnderstanding subscription key in case you want - * to use the Intent recognizer. As configuration values are copied when creating a new recognizer, - * the new token value will not apply to recognizers that have already been created. For recognizers - * that have been created before, you need to set authorization token of the corresponding recognizer - * to refresh the token. Otherwise, the recognizers will encounter errors during recognition. + * expires, the caller needs to refresh it by calling this setter with a new valid token. + * Note: As configuration values are copied when creating a new recognizer, + * the new token value will not apply to recognizers that have already been created. For recognizers + * that have been created before, you need to set authorization token of the corresponding recognizer + * to refresh the token. Otherwise, the recognizers will encounter errors during recognition. * @member SpeechConfig.fromAuthorizationToken * @function * @public @@ -9950,433 +8580,352 @@ var SpeechConfig = /** @class */ (function () { * @param {string} region - The region name (see the region page). * @returns {SpeechConfig} A speech factory instance. */ - SpeechConfig.fromAuthorizationToken = function (authorizationToken, region) { - Contracts_1.Contracts.throwIfNull(authorizationToken, "authorizationToken"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var speechImpl = new SpeechConfigImpl(); - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, region); - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_IntentRegion, region); + static fromAuthorizationToken(authorizationToken, region) { + Contracts_js_1.Contracts.throwIfNull(authorizationToken, "authorizationToken"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region"); + const speechImpl = new SpeechConfigImpl(); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, region); speechImpl.authorizationToken = authorizationToken; return speechImpl; - }; + } /** * Closes the configuration. * @member SpeechConfig.prototype.close * @function * @public */ - /* tslint:disable:no-empty */ - SpeechConfig.prototype.close = function () { }; - return SpeechConfig; -}()); + // eslint-disable-next-line @typescript-eslint/no-empty-function + close() { } +} exports.SpeechConfig = SpeechConfig; /** * @public * @class SpeechConfigImpl */ -// tslint:disable-next-line:max-classes-per-file -var SpeechConfigImpl = /** @class */ (function (_super) { - __extends(SpeechConfigImpl, _super); - function SpeechConfigImpl() { - var _this = _super.call(this) || this; - _this.privProperties = new Exports_2.PropertyCollection(); - _this.speechRecognitionLanguage = "en-US"; // Should we have a default? - _this.outputFormat = Exports_2.OutputFormat.Simple; - return _this; - } - Object.defineProperty(SpeechConfigImpl.prototype, "properties", { - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "endPoint", { - get: function () { - return new URL(this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint)); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "subscriptionKey", { - get: function () { - return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Key); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "region", { - get: function () { - return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "authorizationToken", { - get: function () { - return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token); - }, - set: function (value) { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "speechRecognitionLanguage", { - get: function () { - return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage); - }, - set: function (value) { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage, value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "autoDetectSourceLanguages", { - get: function () { - return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages); - }, - set: function (value) { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "outputFormat", { - get: function () { - return Exports_2.OutputFormat[this.privProperties.getProperty(Exports_1.OutputFormatPropertyName, undefined)]; - }, - set: function (value) { - this.privProperties.setProperty(Exports_1.OutputFormatPropertyName, Exports_2.OutputFormat[value]); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "endpointId", { - get: function () { - return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId); - }, - set: function (value) { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId, value); - }, - enumerable: false, - configurable: true - }); - SpeechConfigImpl.prototype.setProperty = function (name, value) { - Contracts_1.Contracts.throwIfNull(value, "value"); +class SpeechConfigImpl extends SpeechConfig { + constructor(tokenCredential) { + super(); + this.privProperties = new Exports_js_2.PropertyCollection(); + this.speechRecognitionLanguage = "en-US"; // Should we have a default? + this.outputFormat = Exports_js_2.OutputFormat.Simple; + this.privTokenCredential = tokenCredential; + } + get properties() { + return this.privProperties; + } + get endPoint() { + return new URL(this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint)); + } + get subscriptionKey() { + return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key); + } + get region() { + return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region); + } + get authorizationToken() { + return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token); + } + set authorizationToken(value) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, value); + } + get speechRecognitionLanguage() { + return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage); + } + set speechRecognitionLanguage(value) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, value); + } + get autoDetectSourceLanguages() { + return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages); + } + set autoDetectSourceLanguages(value) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, value); + } + get outputFormat() { + return Exports_js_2.OutputFormat[this.privProperties.getProperty(Exports_js_1.OutputFormatPropertyName, undefined)]; + } + set outputFormat(value) { + this.privProperties.setProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_2.OutputFormat[value]); + } + get endpointId() { + return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId); + } + set endpointId(value) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, value); + } + get tokenCredential() { + return this.privTokenCredential; + } + setProperty(name, value) { + Contracts_js_1.Contracts.throwIfNull(value, "value"); this.privProperties.setProperty(name, value); - }; - SpeechConfigImpl.prototype.getProperty = function (name, def) { + } + getProperty(name, def) { return this.privProperties.getProperty(name, def); - }; - SpeechConfigImpl.prototype.setProxy = function (proxyHostName, proxyPort, proxyUserName, proxyPassword) { - this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName); - this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyPort], proxyPort); - this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName); - this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword); - }; - SpeechConfigImpl.prototype.setServiceProperty = function (name, value, channel) { - var currentProperties = JSON.parse(this.privProperties.getProperty(Exports_1.ServicePropertiesPropertyName, "{}")); + } + setProxy(proxyHostName, proxyPort, proxyUserName, proxyPassword) { + this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName); + this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyPort], proxyPort); + this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName); + this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword); + } + setServiceProperty(name, value) { + const currentProperties = JSON.parse(this.privProperties.getProperty(Exports_js_1.ServicePropertiesPropertyName, "{}")); currentProperties[name] = value; - this.privProperties.setProperty(Exports_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties)); - }; - SpeechConfigImpl.prototype.setProfanity = function (profanity) { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_ProfanityOption, Exports_2.ProfanityOption[profanity]); - }; - SpeechConfigImpl.prototype.enableAudioLogging = function () { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, "true"); - }; - SpeechConfigImpl.prototype.requestWordLevelTimestamps = function () { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true"); - }; - SpeechConfigImpl.prototype.enableDictation = function () { - this.privProperties.setProperty(Exports_1.ForceDictationPropertyName, "true"); - }; - SpeechConfigImpl.prototype.clone = function () { - var ret = new SpeechConfigImpl(); + this.privProperties.setProperty(Exports_js_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties)); + } + setProfanity(profanity) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_ProfanityOption, Exports_js_2.ProfanityOption[profanity]); + } + enableAudioLogging() { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, "true"); + } + requestWordLevelTimestamps() { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true"); + this.privProperties.setProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_2.OutputFormat[Exports_js_2.OutputFormat.Detailed]); + } + enableDictation() { + this.privProperties.setProperty(Exports_js_1.ForceDictationPropertyName, "true"); + } + clone() { + const ret = new SpeechConfigImpl(this.tokenCredential); ret.privProperties = this.privProperties.clone(); return ret; - }; - Object.defineProperty(SpeechConfigImpl.prototype, "speechSynthesisLanguage", { - get: function () { - return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthLanguage); - }, - set: function (language) { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthLanguage, language); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "speechSynthesisVoiceName", { - get: function () { - return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthVoice); - }, - set: function (voice) { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthVoice, voice); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConfigImpl.prototype, "speechSynthesisOutputFormat", { - get: function () { - return Exports_2.SpeechSynthesisOutputFormat[this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)]; - }, - set: function (format) { - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, Exports_2.SpeechSynthesisOutputFormat[format]); - }, - enumerable: false, - configurable: true - }); - return SpeechConfigImpl; -}(SpeechConfig)); + } + get speechSynthesisLanguage() { + return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage); + } + set speechSynthesisLanguage(language) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage, language); + } + get speechSynthesisVoiceName() { + return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice); + } + set speechSynthesisVoiceName(voice) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice, voice); + } + get speechSynthesisOutputFormat() { + return Exports_js_2.SpeechSynthesisOutputFormat[this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)]; + } + set speechSynthesisOutputFormat(format) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, Exports_js_2.SpeechSynthesisOutputFormat[format]); + } +} exports.SpeechConfigImpl = SpeechConfigImpl; /***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { +/* 111 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpeechTranslationConfigImpl = exports.SpeechTranslationConfig = void 0; -var Exports_1 = __webpack_require__(53); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(2); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_2 = __webpack_require__(85); /** * Speech translation configuration. * @class SpeechTranslationConfig */ -var SpeechTranslationConfig = /** @class */ (function (_super) { - __extends(SpeechTranslationConfig, _super); +class SpeechTranslationConfig extends Exports_js_2.SpeechConfig { + /** + * Creates an instance of recognizer config. + */ + constructor() { + super(); + } + /** + * Static instance of SpeechTranslationConfig returned by passing a subscription key and service region. + * @member SpeechTranslationConfig.fromSubscription + * @function + * @public + * @param {string} subscriptionKey - The subscription key. + * @param {string} region - The region name (see the region page). + * @returns {SpeechTranslationConfig} The speech translation config. + */ + static fromSubscription(subscriptionKey, region) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region"); + const ret = new SpeechTranslationConfigImpl(); + ret.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); + ret.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, region); + return ret; + } + /** + * Static instance of SpeechTranslationConfig returned by passing authorization token and service region. + * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token + * expires, the caller needs to refresh it by setting the property authorizationToken with a new + * valid token. Otherwise, all the recognizers created by this SpeechTranslationConfig instance + * will encounter errors during recognition. + * As configuration values are copied when creating a new recognizer, the new token value will not apply + * to recognizers that have already been created. + * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer + * to refresh the token. Otherwise, the recognizers will encounter errors during recognition. + * @member SpeechTranslationConfig.fromAuthorizationToken + * @function + * @public + * @param {string} authorizationToken - The authorization token. + * @param {string} region - The region name (see the region page). + * @returns {SpeechTranslationConfig} The speech translation config. + */ + static fromAuthorizationToken(authorizationToken, region) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region"); + const ret = new SpeechTranslationConfigImpl(); + ret.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, authorizationToken); + ret.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, region); + return ret; + } + /** + * Creates an instance of the speech config with specified host and subscription key. + * This method is intended only for users who use a non-default service host. Standard resource path will be assumed. + * For services with a non-standard resource path or no path at all, use fromEndpoint instead. + * Note: Query parameters are not allowed in the host URI and must be set by other APIs. + * Note: To use an authorization token with fromHost, use fromHost(URL), + * and then set the AuthorizationToken property on the created SpeechConfig instance. + * Note: Added in version 1.9.0. + * @member SpeechConfig.fromHost + * @function + * @public + * @param {URL} host - The service endpoint to connect to. Format is "protocol://host:port" where ":port" is optional. + * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set. + * @returns {SpeechConfig} A speech factory instance. + */ + static fromHost(hostName, subscriptionKey) { + Contracts_js_1.Contracts.throwIfNull(hostName, "hostName"); + const speechImpl = new SpeechTranslationConfigImpl(); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port)); + if (undefined !== subscriptionKey) { + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); + } + return speechImpl; + } + /** + * Internal implementation of fromEndpoint() overloads. Accepts either a subscription key or a TokenCredential. + * @private + */ + static fromEndpoint(endpoint, auth) { + Contracts_js_1.Contracts.throwIfNull(endpoint, "endpoint"); + const isValidString = typeof auth === "string" && auth.trim().length > 0; + const isTokenCredential = typeof auth === "object" && auth !== null && typeof auth.getToken === "function"; + const isKeyCredential = typeof auth === "object" && auth !== null && typeof auth.key === "string"; + if (auth !== undefined && !isValidString && !isTokenCredential && !isKeyCredential) { + throw new Error("Invalid 'auth' parameter: expected a non-empty API key string, a TokenCredential, or a KeyCredential."); + } + let speechImpl; + if (typeof auth === "string") { + speechImpl = new SpeechTranslationConfigImpl(); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, auth); + } + else if (typeof auth === "object" && typeof auth.getToken === "function") { + speechImpl = new SpeechTranslationConfigImpl(auth); + } + else if (typeof auth === "object" && typeof auth.key === "string") { + speechImpl = new SpeechTranslationConfigImpl(); + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, auth.key); + } + else { + speechImpl = new SpeechTranslationConfigImpl(); + } + speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, endpoint.href); + return speechImpl; + } +} +exports.SpeechTranslationConfig = SpeechTranslationConfig; +/** + * @private + * @class SpeechTranslationConfigImpl + */ +class SpeechTranslationConfigImpl extends SpeechTranslationConfig { + constructor(tokenCredential) { + super(); + this.privSpeechProperties = new Exports_js_2.PropertyCollection(); + this.outputFormat = Exports_js_2.OutputFormat.Simple; + this.privTokenCredential = tokenCredential; + } + /** + * Gets/Sets the authorization token. + * If this is set, subscription key is ignored. + * User needs to make sure the provided authorization token is valid and not expired. + * @member SpeechTranslationConfigImpl.prototype.authorizationToken + * @function + * @public + * @param {string} value - The authorization token. + */ + set authorizationToken(value) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value"); + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, value); + } + /** + * Sets the speech recognition language. + * @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage + * @function + * @public + * @param {string} value - The authorization token. + */ + set speechRecognitionLanguage(value) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value"); + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, value); + } + /** + * Gets the speech recognition language. + * @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage + * @function + * @public + * @return {string} The speechRecognitionLanguage. + */ + get speechRecognitionLanguage() { + return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage]); + } /** - * Creates an instance of recognizer config. + * @member SpeechTranslationConfigImpl.prototype.subscriptionKey + * @function + * @public */ - function SpeechTranslationConfig() { - return _super.call(this) || this; + get subscriptionKey() { + return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_Key]); } /** - * Static instance of SpeechTranslationConfig returned by passing a subscription key and service region. - * @member SpeechTranslationConfig.fromSubscription + * Gets the output format + * @member SpeechTranslationConfigImpl.prototype.outputFormat * @function * @public - * @param {string} subscriptionKey - The subscription key. - * @param {string} region - The region name (see the region page). - * @returns {SpeechTranslationConfig} The speech translation config. */ - SpeechTranslationConfig.fromSubscription = function (subscriptionKey, region) { - Contracts_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var ret = new SpeechTranslationConfigImpl(); - ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); - ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, region); - return ret; - }; + get outputFormat() { + // eslint-disable-next-line + return Exports_js_2.OutputFormat[this.privSpeechProperties.getProperty(Exports_js_1.OutputFormatPropertyName, undefined)]; + } /** - * Static instance of SpeechTranslationConfig returned by passing authorization token and service region. - * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token - * expires, the caller needs to refresh it by setting the property authorizationToken with a new - * valid token. Otherwise, all the recognizers created by this SpeechTranslationConfig instance - * will encounter errors during recognition. - * As configuration values are copied when creating a new recognizer, the new token value will not apply - * to recognizers that have already been created. - * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer - * to refresh the token. Otherwise, the recognizers will encounter errors during recognition. - * @member SpeechTranslationConfig.fromAuthorizationToken + * Gets/Sets the output format + * @member SpeechTranslationConfigImpl.prototype.outputFormat * @function * @public - * @param {string} authorizationToken - The authorization token. - * @param {string} region - The region name (see the region page). - * @returns {SpeechTranslationConfig} The speech translation config. */ - SpeechTranslationConfig.fromAuthorizationToken = function (authorizationToken, region) { - Contracts_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var ret = new SpeechTranslationConfigImpl(); - ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, authorizationToken); - ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, region); - return ret; - }; + set outputFormat(value) { + this.privSpeechProperties.setProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_2.OutputFormat[value]); + } /** - * Creates an instance of the speech config with specified host and subscription key. - * This method is intended only for users who use a non-default service host. Standard resource path will be assumed. - * For services with a non-standard resource path or no path at all, use fromEndpoint instead. - * Note: Query parameters are not allowed in the host URI and must be set by other APIs. - * Note: To use an authorization token with fromHost, use fromHost(URL), - * and then set the AuthorizationToken property on the created SpeechConfig instance. - * Note: Added in version 1.9.0. - * @member SpeechConfig.fromHost + * Gets the endpoint id. + * @member SpeechTranslationConfigImpl.prototype.endpointId * @function * @public - * @param {URL} host - The service endpoint to connect to. Format is "protocol://host:port" where ":port" is optional. - * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set. - * @returns {SpeechConfig} A speech factory instance. */ - SpeechTranslationConfig.fromHost = function (hostName, subscriptionKey) { - Contracts_1.Contracts.throwIfNull(hostName, "hostName"); - var speechImpl = new SpeechTranslationConfigImpl(); - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port)); - if (undefined !== subscriptionKey) { - speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); - } - return speechImpl; - }; - /** - * Creates an instance of the speech translation config with specified endpoint and subscription key. - * This method is intended only for users who use a non-standard service endpoint or paramters. - * Note: The query properties specified in the endpoint URL are not changed, even if they are - * set by any other APIs. For example, if language is defined in the uri as query parameter - * "language=de-DE", and also set by the speechRecognitionLanguage property, the language - * setting in uri takes precedence, and the effective language is "de-DE". - * Only the properties that are not specified in the endpoint URL can be set by other APIs. - * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the - * fromEndpoint method, and then set authorizationToken="token" on the created SpeechConfig instance to - * use the authorization token. - * @member SpeechTranslationConfig.fromEndpoint + get endpointId() { + return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId); + } + /** + * Gets/Sets the endpoint id. + * @member SpeechTranslationConfigImpl.prototype.endpointId * @function * @public - * @param {URL} endpoint - The service endpoint to connect to. - * @param {string} subscriptionKey - The subscription key. - * @returns {SpeechTranslationConfig} A speech config instance. - */ - SpeechTranslationConfig.fromEndpoint = function (endpoint, subscriptionKey) { - Contracts_1.Contracts.throwIfNull(endpoint, "endpoint"); - Contracts_1.Contracts.throwIfNull(subscriptionKey, "subscriptionKey"); - var ret = new SpeechTranslationConfigImpl(); - ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, endpoint.href); - ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey); - return ret; - }; - return SpeechTranslationConfig; -}(Exports_2.SpeechConfig)); -exports.SpeechTranslationConfig = SpeechTranslationConfig; -/** - * @private - * @class SpeechTranslationConfigImpl - */ -// tslint:disable-next-line:max-classes-per-file -var SpeechTranslationConfigImpl = /** @class */ (function (_super) { - __extends(SpeechTranslationConfigImpl, _super); - function SpeechTranslationConfigImpl() { - var _this = _super.call(this) || this; - _this.privSpeechProperties = new Exports_2.PropertyCollection(); - _this.outputFormat = Exports_2.OutputFormat.Simple; - return _this; - } - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "authorizationToken", { - /** - * Gets/Sets the authorization token. - * If this is set, subscription key is ignored. - * User needs to make sure the provided authorization token is valid and not expired. - * @member SpeechTranslationConfigImpl.prototype.authorizationToken - * @function - * @public - * @param {string} value - The authorization token. - */ - set: function (value) { - Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value"); - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "speechRecognitionLanguage", { - /** - * Gets the speech recognition language. - * @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage - * @function - * @public - * @return {string} The speechRecognitionLanguage. - */ - get: function () { - return this.privSpeechProperties.getProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage]); - }, - /** - * Sets the speech recognition language. - * @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage - * @function - * @public - * @param {string} value - The authorization token. - */ - set: function (value) { - Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value"); - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage, value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "subscriptionKey", { - /** - * @member SpeechTranslationConfigImpl.prototype.subscriptionKey - * @function - * @public - */ - get: function () { - return this.privSpeechProperties.getProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_Key]); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "outputFormat", { - /** - * Gets the output format - * @member SpeechTranslationConfigImpl.prototype.outputFormat - * @function - * @public - */ - get: function () { - return Exports_2.OutputFormat[this.privSpeechProperties.getProperty(Exports_1.OutputFormatPropertyName, undefined)]; - }, - /** - * Gets/Sets the output format - * @member SpeechTranslationConfigImpl.prototype.outputFormat - * @function - * @public - */ - set: function (value) { - this.privSpeechProperties.setProperty(Exports_1.OutputFormatPropertyName, Exports_2.OutputFormat[value]); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "endpointId", { - /** - * Gets the endpoint id. - * @member SpeechTranslationConfigImpl.prototype.endpointId - * @function - * @public - */ - get: function () { - return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId); - }, - /** - * Gets/Sets the endpoint id. - * @member SpeechTranslationConfigImpl.prototype.endpointId - * @function - * @public - */ - set: function (value) { - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId, value); - }, - enumerable: false, - configurable: true - }); + */ + set endpointId(value) { + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, value); + } /** * Add a (text) target language to translate into. * @member SpeechTranslationConfigImpl.prototype.addTargetLanguage @@ -10384,75 +8933,68 @@ var SpeechTranslationConfigImpl = /** @class */ (function (_super) { * @public * @param {string} value - The language such as de-DE */ - SpeechTranslationConfigImpl.prototype.addTargetLanguage = function (value) { - Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value"); - var languages = this.targetLanguages; - languages.push(value); - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(",")); - }; - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "targetLanguages", { - /** - * Gets the (text) target language to translate into. - * @member SpeechTranslationConfigImpl.prototype.targetLanguages - * @function - * @public - * @param {string} value - The language such as de-DE - */ - get: function () { - if (this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) { - return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","); - } - else { - return []; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "voiceName", { - /** - * Gets the voice name. - * @member SpeechTranslationConfigImpl.prototype.voiceName - * @function - * @public - */ - get: function () { - return this.getProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_TranslationVoice]); - }, - /** - * Gets/Sets the voice of the translated language, enable voice synthesis output. - * @member SpeechTranslationConfigImpl.prototype.voiceName - * @function - * @public - * @param {string} value - The name of the voice. - */ - set: function (value) { - Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value"); - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationVoice, value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "region", { - /** - * Provides the region. - * @member SpeechTranslationConfigImpl.prototype.region - * @function - * @public - * @returns {string} The region. - */ - get: function () { - return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region); - }, - enumerable: false, - configurable: true - }); - SpeechTranslationConfigImpl.prototype.setProxy = function (proxyHostName, proxyPort, proxyUserName, proxyPassword) { - this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName); - this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyPort], proxyPort); - this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName); - this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword); - }; + addTargetLanguage(value) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value"); + const languages = this.targetLanguages; + if (!languages.includes(value)) { + languages.push(value); + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(",")); + } + } + /** + * Gets the (text) target language to translate into. + * @member SpeechTranslationConfigImpl.prototype.targetLanguages + * @function + * @public + * @param {string} value - The language such as de-DE + */ + get targetLanguages() { + if (this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) { + return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","); + } + else { + return []; + } + } + /** + * Gets the voice name. + * @member SpeechTranslationConfigImpl.prototype.voiceName + * @function + * @public + */ + get voiceName() { + return this.getProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_TranslationVoice]); + } + /** + * Gets/Sets the voice of the translated language, enable voice synthesis output. + * @member SpeechTranslationConfigImpl.prototype.voiceName + * @function + * @public + * @param {string} value - The name of the voice. + */ + set voiceName(value) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value"); + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationVoice, value); + } + /** + * Provides the region. + * @member SpeechTranslationConfigImpl.prototype.region + * @function + * @public + * @returns {string} The region. + */ + get region() { + return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region); + } + get tokenCredential() { + return this.privTokenCredential; + } + setProxy(proxyHostName, proxyPort, proxyUserName, proxyPassword) { + this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName); + this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyPort], proxyPort); + this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName); + this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword); + } /** * Gets an arbitrary property value. * @member SpeechTranslationConfigImpl.prototype.getProperty @@ -10462,143 +9004,130 @@ var SpeechTranslationConfigImpl = /** @class */ (function (_super) { * @param {string} def - The default value of the property in case it is not set. * @returns {string} The value of the property. */ - SpeechTranslationConfigImpl.prototype.getProperty = function (name, def) { + getProperty(name, def) { return this.privSpeechProperties.getProperty(name, def); - }; + } /** * Gets/Sets an arbitrary property value. * @member SpeechTranslationConfigImpl.prototype.setProperty * @function * @public - * @param {string} name - The name of the property. + * @param {string | PropertyId} name - The name of the property to set. * @param {string} value - The value of the property. */ - SpeechTranslationConfigImpl.prototype.setProperty = function (name, value) { + setProperty(name, value) { this.privSpeechProperties.setProperty(name, value); - }; - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "properties", { - /** - * Provides access to custom properties. - * @member SpeechTranslationConfigImpl.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The properties. - */ - get: function () { - return this.privSpeechProperties; - }, - enumerable: false, - configurable: true - }); + } + /** + * Provides access to custom properties. + * @member SpeechTranslationConfigImpl.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The properties. + */ + get properties() { + return this.privSpeechProperties; + } /** * Dispose of associated resources. * @member SpeechTranslationConfigImpl.prototype.close * @function * @public */ - SpeechTranslationConfigImpl.prototype.close = function () { + close() { return; - }; - SpeechTranslationConfigImpl.prototype.setServiceProperty = function (name, value, channel) { - var currentProperties = JSON.parse(this.privSpeechProperties.getProperty(Exports_1.ServicePropertiesPropertyName, "{}")); + } + setServiceProperty(name, value) { + const currentProperties = JSON.parse(this.privSpeechProperties.getProperty(Exports_js_1.ServicePropertiesPropertyName, "{}")); currentProperties[name] = value; - this.privSpeechProperties.setProperty(Exports_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties)); - }; - SpeechTranslationConfigImpl.prototype.setProfanity = function (profanity) { - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_ProfanityOption, Exports_2.ProfanityOption[profanity]); - }; - SpeechTranslationConfigImpl.prototype.enableAudioLogging = function () { - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, "true"); - }; - SpeechTranslationConfigImpl.prototype.requestWordLevelTimestamps = function () { - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true"); - }; - SpeechTranslationConfigImpl.prototype.enableDictation = function () { - this.privSpeechProperties.setProperty(Exports_1.ForceDictationPropertyName, "true"); - }; - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "speechSynthesisLanguage", { - get: function () { - return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthLanguage); - }, - set: function (language) { - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthLanguage, language); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "speechSynthesisVoiceName", { - get: function () { - return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthVoice); - }, - set: function (voice) { - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthVoice, voice); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechTranslationConfigImpl.prototype, "speechSynthesisOutputFormat", { - get: function () { - return Exports_2.SpeechSynthesisOutputFormat[this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)]; - }, - set: function (format) { - this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, Exports_2.SpeechSynthesisOutputFormat[format]); - }, - enumerable: false, - configurable: true - }); - return SpeechTranslationConfigImpl; -}(SpeechTranslationConfig)); + this.privSpeechProperties.setProperty(Exports_js_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties)); + } + setProfanity(profanity) { + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_ProfanityOption, Exports_js_2.ProfanityOption[profanity]); + } + enableAudioLogging() { + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, "true"); + } + requestWordLevelTimestamps() { + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true"); + } + enableDictation() { + this.privSpeechProperties.setProperty(Exports_js_1.ForceDictationPropertyName, "true"); + } + get speechSynthesisLanguage() { + return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage); + } + set speechSynthesisLanguage(language) { + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage, language); + } + get speechSynthesisVoiceName() { + return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice); + } + set speechSynthesisVoiceName(voice) { + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice, voice); + } + get speechSynthesisOutputFormat() { + // eslint-disable-next-line + return Exports_js_2.SpeechSynthesisOutputFormat[this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)]; + } + set speechSynthesisOutputFormat(format) { + this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, Exports_js_2.SpeechSynthesisOutputFormat[format]); + } +} exports.SpeechTranslationConfigImpl = SpeechTranslationConfigImpl; /***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { +/* 112 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropertyCollection = void 0; -var Exports_1 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(85); /** * Represents collection of properties and their values. * @class PropertyCollection */ -var PropertyCollection = /** @class */ (function () { - function PropertyCollection() { +class PropertyCollection { + constructor() { this.privKeys = []; this.privValues = []; } /** - * Returns the property value in type String. The parameter must have the same type as String. + * Returns the property value in type String. * Currently only String, int and bool are allowed. * If the name is not available, the specified defaultValue is returned. * @member PropertyCollection.prototype.getProperty * @function * @public * @param {string} key - The parameter name. - * @param {string} def - The default value which is returned if the parameter - * is not available in the collection. + * @param {string | number | boolean} def - The default value which is returned if the parameter + * is not available in the collection. * @returns {string} value of the parameter. */ - PropertyCollection.prototype.getProperty = function (key, def) { - var keyToUse; + getProperty(key, def) { + let keyToUse; if (typeof key === "string") { keyToUse = key; } else { - keyToUse = Exports_1.PropertyId[key]; + keyToUse = Exports_js_1.PropertyId[key]; } - for (var n = 0; n < this.privKeys.length; n++) { + for (let n = 0; n < this.privKeys.length; n++) { if (this.privKeys[n] === keyToUse) { return this.privValues[n]; } } - return def; - }; + if (def === undefined) { + return undefined; + } + return String(def); + } /** * Sets the String value of the parameter specified by name. * @member PropertyCollection.prototype.setProperty @@ -10607,15 +9136,15 @@ var PropertyCollection = /** @class */ (function () { * @param {string} key - The parameter name. * @param {string} value - The value of the parameter. */ - PropertyCollection.prototype.setProperty = function (key, value) { - var keyToUse; + setProperty(key, value) { + let keyToUse; if (typeof key === "string") { keyToUse = key; } else { - keyToUse = Exports_1.PropertyId[key]; + keyToUse = Exports_js_1.PropertyId[key]; } - for (var n = 0; n < this.privKeys.length; n++) { + for (let n = 0; n < this.privKeys.length; n++) { if (this.privKeys[n] === keyToUse) { this.privValues[n] = value; return; @@ -10623,7 +9152,7 @@ var PropertyCollection = /** @class */ (function () { } this.privKeys.push(keyToUse); this.privValues.push(value); - }; + } /** * Clones the collection. * @member PropertyCollection.prototype.clone @@ -10631,59 +9160,53 @@ var PropertyCollection = /** @class */ (function () { * @public * @returns {PropertyCollection} A copy of the collection. */ - PropertyCollection.prototype.clone = function () { - var clonedMap = new PropertyCollection(); - for (var n = 0; n < this.privKeys.length; n++) { + clone() { + const clonedMap = new PropertyCollection(); + for (let n = 0; n < this.privKeys.length; n++) { clonedMap.privKeys.push(this.privKeys[n]); clonedMap.privValues.push(this.privValues[n]); } return clonedMap; - }; + } /** * Merges this set of properties into another, no overwrites. * @member PropertyCollection.prototype.mergeTo * @function * @public - * @param {PropertyCollection} The collection to merge into. + * @param {PropertyCollection} destinationCollection - The collection to merge into. */ - PropertyCollection.prototype.mergeTo = function (destinationCollection) { - var _this = this; - this.privKeys.forEach(function (key) { + mergeTo(destinationCollection) { + this.privKeys.forEach((key) => { if (destinationCollection.getProperty(key, undefined) === undefined) { - var value = _this.getProperty(key); + const value = this.getProperty(key); destinationCollection.setProperty(key, value); } }); - }; - Object.defineProperty(PropertyCollection.prototype, "keys", { - /** - * Get the keys in Property Collection. - * @member PropertyCollection.prototype.keys - * @function - * @public - * @returns {string []} Keys in the collection. - */ - get: function () { - return this.privKeys; - }, - enumerable: false, - configurable: true - }); - return PropertyCollection; -}()); + } + /** + * Get the keys in Property Collection. + * @member PropertyCollection.prototype.keys + * @function + * @public + * @returns {string []} Keys in the collection. + */ + get keys() { + return this.privKeys; + } +} exports.PropertyCollection = PropertyCollection; /***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { +/* 113 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropertyId = void 0; /** * Defines speech property ids. @@ -10692,8 +9215,7 @@ exports.PropertyId = void 0; var PropertyId; (function (PropertyId) { /** - * The Cognitive Services Speech Service subscription Key. If you are using an intent recognizer, you need to specify - * to specify the LUIS endpoint key for your particular LUIS app. Under normal circumstances, you shouldn't + * The Cognitive Services Speech Service subscription Key. Under normal circumstances, you shouldn't * have to use this property directly. * Instead, use [[SpeechConfig.fromSubscription]]. * @member PropertyId.SpeechServiceConnection_Key @@ -10718,7 +9240,7 @@ var PropertyId; * The Cognitive Services Speech Service authorization token (aka access token). Under normal circumstances, * you shouldn't have to use this property directly. * Instead, use [[SpeechConfig.fromAuthorizationToken]], [[SpeechRecognizer.authorizationToken]], - * [[IntentRecognizer.authorizationToken]], [[TranslationRecognizer.authorizationToken]], [[SpeakerRecognizer.authorizationToken]]. + * [[TranslationRecognizer.authorizationToken]], [[SpeakerRecognizer.authorizationToken]]. * @member PropertyId.SpeechServiceAuthorization_Token */ PropertyId[PropertyId["SpeechServiceAuthorization_Token"] = 3] = "SpeechServiceAuthorization_Token"; @@ -10757,11 +9279,10 @@ var PropertyId; */ PropertyId[PropertyId["SpeechServiceConnection_TranslationFeatures"] = 8] = "SpeechServiceConnection_TranslationFeatures"; /** - * The Language Understanding Service Region. Under normal circumstances, you shouldn't have to use this property directly. - * Instead, use [[LanguageUnderstandingModel]]. - * @member PropertyId.SpeechServiceConnection_IntentRegion + * The category ID for translation. + * @member PropertyId.SpeechServiceConnection_TranslationCategoryId */ - PropertyId[PropertyId["SpeechServiceConnection_IntentRegion"] = 9] = "SpeechServiceConnection_IntentRegion"; + PropertyId[PropertyId["SpeechServiceConnection_TranslationCategoryId"] = 9] = "SpeechServiceConnection_TranslationCategoryId"; /** * The host name of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments. * You shouldn't have to use this property directly. @@ -10852,2387 +9373,805 @@ var PropertyId; /** * The Cognitive Services Speech Service error details (in JSON format). Under normal circumstances, you shouldn't have to * use this property directly. Instead use [[CancellationDetails.errorDetails]]. - * @member PropertyId.SpeechServiceResponse_JsonErrorDetails - */ - PropertyId[PropertyId["SpeechServiceResponse_JsonErrorDetails"] = 24] = "SpeechServiceResponse_JsonErrorDetails"; - /** - * The cancellation reason. Currently unused. - * @member PropertyId.CancellationDetails_Reason - */ - PropertyId[PropertyId["CancellationDetails_Reason"] = 25] = "CancellationDetails_Reason"; - /** - * The cancellation text. Currently unused. - * @member PropertyId.CancellationDetails_ReasonText - */ - PropertyId[PropertyId["CancellationDetails_ReasonText"] = 26] = "CancellationDetails_ReasonText"; - /** - * The Cancellation detailed text. Currently unused. - * @member PropertyId.CancellationDetails_ReasonDetailedText - */ - PropertyId[PropertyId["CancellationDetails_ReasonDetailedText"] = 27] = "CancellationDetails_ReasonDetailedText"; - /** - * The Language Understanding Service response output (in JSON format). Available via [[IntentRecognitionResult]] - * @member PropertyId.LanguageUnderstandingServiceResponse_JsonResult - */ - PropertyId[PropertyId["LanguageUnderstandingServiceResponse_JsonResult"] = 28] = "LanguageUnderstandingServiceResponse_JsonResult"; - /** - * The URL string built from speech configuration. - * This property is intended to be read-only. The SDK is using it internally. - * NOTE: Added in version 1.7.0. - */ - PropertyId[PropertyId["SpeechServiceConnection_Url"] = 29] = "SpeechServiceConnection_Url"; - /** - * The initial silence timeout value (in milliseconds) used by the service. - * Added in version 1.7.0 - */ - PropertyId[PropertyId["SpeechServiceConnection_InitialSilenceTimeoutMs"] = 30] = "SpeechServiceConnection_InitialSilenceTimeoutMs"; - /** - * The end silence timeout value (in milliseconds) used by the service. - * Added in version 1.7.0 - */ - PropertyId[PropertyId["SpeechServiceConnection_EndSilenceTimeoutMs"] = 31] = "SpeechServiceConnection_EndSilenceTimeoutMs"; - /** - * A boolean value specifying whether audio logging is enabled in the service or not. - * Added in version 1.7.0 - */ - PropertyId[PropertyId["SpeechServiceConnection_EnableAudioLogging"] = 32] = "SpeechServiceConnection_EnableAudioLogging"; - /** - * The requested Cognitive Services Speech Service response output profanity setting. - * Allowed values are "masked", "removed", and "raw". - * Added in version 1.7.0. - */ - PropertyId[PropertyId["SpeechServiceResponse_ProfanityOption"] = 33] = "SpeechServiceResponse_ProfanityOption"; - /** - * A string value specifying which post processing option should be used by service. - * Allowed values are "TrueText". - * Added in version 1.7.0 - */ - PropertyId[PropertyId["SpeechServiceResponse_PostProcessingOption"] = 34] = "SpeechServiceResponse_PostProcessingOption"; - /** - * A boolean value specifying whether to include word-level timestamps in the response result. - * Added in version 1.7.0 - */ - PropertyId[PropertyId["SpeechServiceResponse_RequestWordLevelTimestamps"] = 35] = "SpeechServiceResponse_RequestWordLevelTimestamps"; - /** - * The number of times a word has to be in partial results to be returned. - * Added in version 1.7.0 - */ - PropertyId[PropertyId["SpeechServiceResponse_StablePartialResultThreshold"] = 36] = "SpeechServiceResponse_StablePartialResultThreshold"; - /** - * A string value specifying the output format option in the response result. Internal use only. - * Added in version 1.7.0. - */ - PropertyId[PropertyId["SpeechServiceResponse_OutputFormatOption"] = 37] = "SpeechServiceResponse_OutputFormatOption"; - /** - * A boolean value to request for stabilizing translation partial results by omitting words in the end. - * Added in version 1.7.0. - */ - PropertyId[PropertyId["SpeechServiceResponse_TranslationRequestStablePartialResult"] = 38] = "SpeechServiceResponse_TranslationRequestStablePartialResult"; - /** - * Identifier used to connect to the backend service. - * @member PropertyId.Conversation_ApplicationId - */ - PropertyId[PropertyId["Conversation_ApplicationId"] = 39] = "Conversation_ApplicationId"; - /** - * Type of dialog backend to connect to. - * @member PropertyId.Conversation_DialogType - */ - PropertyId[PropertyId["Conversation_DialogType"] = 40] = "Conversation_DialogType"; - /** - * Silence timeout for listening - * @member PropertyId.Conversation_Initial_Silence_Timeout - */ - PropertyId[PropertyId["Conversation_Initial_Silence_Timeout"] = 41] = "Conversation_Initial_Silence_Timeout"; - /** - * From Id to add to speech recognition activities. - * @member PropertyId.Conversation_From_Id - */ - PropertyId[PropertyId["Conversation_From_Id"] = 42] = "Conversation_From_Id"; - /** - * ConversationId for the session. - * @member PropertyId.Conversation_Conversation_Id - */ - PropertyId[PropertyId["Conversation_Conversation_Id"] = 43] = "Conversation_Conversation_Id"; - /** - * Comma separated list of custom voice deployment ids. - * @member PropertyId.Conversation_Custom_Voice_Deployment_Ids - */ - PropertyId[PropertyId["Conversation_Custom_Voice_Deployment_Ids"] = 44] = "Conversation_Custom_Voice_Deployment_Ids"; - /** - * Speech activity template, stamp properties from the template on the activity generated by the service for speech. - * @member PropertyId.Conversation_Speech_Activity_Template - * Added in version 1.10.0. - */ - PropertyId[PropertyId["Conversation_Speech_Activity_Template"] = 45] = "Conversation_Speech_Activity_Template"; - /** - * Enables or disables the receipt of turn status messages as obtained on the turnStatusReceived event. - * @member PropertyId.Conversation_Request_Bot_Status_Messages - * Added in version 1.15.0. - */ - PropertyId[PropertyId["Conversation_Request_Bot_Status_Messages"] = 46] = "Conversation_Request_Bot_Status_Messages"; - /** - * Specifies the connection ID to be provided in the Agent configuration message, e.g. a Direct Line token for - * channel authentication. - * Added in version 1.15.1. - */ - PropertyId[PropertyId["Conversation_Agent_Connection_Id"] = 47] = "Conversation_Agent_Connection_Id"; - /** - * The Cognitive Services Speech Service host (url). Under normal circumstances, you shouldn't have to use this property directly. - * Instead, use [[SpeechConfig.fromHost]]. - */ - PropertyId[PropertyId["SpeechServiceConnection_Host"] = 48] = "SpeechServiceConnection_Host"; - /** - * Set the host for service calls to the Conversation Translator REST management and websocket calls. - */ - PropertyId[PropertyId["ConversationTranslator_Host"] = 49] = "ConversationTranslator_Host"; - /** - * Optionally set the the host's display name. - * Used when joining a conversation. - */ - PropertyId[PropertyId["ConversationTranslator_Name"] = 50] = "ConversationTranslator_Name"; - /** - * Optionally set a value for the X-CorrelationId request header. - * Used for troubleshooting errors in the server logs. It should be a valid guid. - */ - PropertyId[PropertyId["ConversationTranslator_CorrelationId"] = 51] = "ConversationTranslator_CorrelationId"; - /** - * Set the conversation token to be sent to the speech service. This enables the - * service to service call from the speech service to the Conversation Translator service for relaying - * recognitions. For internal use. - */ - PropertyId[PropertyId["ConversationTranslator_Token"] = 52] = "ConversationTranslator_Token"; - /** - * The reference text of the audio for pronunciation evaluation. - * For this and the following pronunciation assessment parameters, see - * https://docs.microsoft.com/azure/cognitive-services/speech-service/rest-speech-to-text#pronunciation-assessment-parameters for details. - * Under normal circumstances, you shouldn't have to use this property directly. - * Added in version 1.15.0 - */ - PropertyId[PropertyId["PronunciationAssessment_ReferenceText"] = 53] = "PronunciationAssessment_ReferenceText"; - /** - * The point system for pronunciation score calibration (FivePoint or HundredMark). - * Under normal circumstances, you shouldn't have to use this property directly. - * Added in version 1.15.0 + * @member PropertyId.SpeechServiceResponse_JsonErrorDetails */ - PropertyId[PropertyId["PronunciationAssessment_GradingSystem"] = 54] = "PronunciationAssessment_GradingSystem"; + PropertyId[PropertyId["SpeechServiceResponse_JsonErrorDetails"] = 24] = "SpeechServiceResponse_JsonErrorDetails"; /** - * The pronunciation evaluation granularity (Phoneme, Word, or FullText). - * Under normal circumstances, you shouldn't have to use this property directly. - * Added in version 1.15.0 + * The cancellation reason. Currently unused. + * @member PropertyId.CancellationDetails_Reason */ - PropertyId[PropertyId["PronunciationAssessment_Granularity"] = 55] = "PronunciationAssessment_Granularity"; + PropertyId[PropertyId["CancellationDetails_Reason"] = 25] = "CancellationDetails_Reason"; /** - * Defines if enable miscue calculation. - * With this enabled, the pronounced words will be compared to the reference text, - * and will be marked with omission/insertion based on the comparison. The default setting is False. - * Under normal circumstances, you shouldn't have to use this property directly. - * Added in version 1.15.0 + * The cancellation text. Currently unused. + * @member PropertyId.CancellationDetails_ReasonText */ - PropertyId[PropertyId["PronunciationAssessment_EnableMiscue"] = 56] = "PronunciationAssessment_EnableMiscue"; + PropertyId[PropertyId["CancellationDetails_ReasonText"] = 26] = "CancellationDetails_ReasonText"; /** - * The json string of pronunciation assessment parameters - * Under normal circumstances, you shouldn't have to use this property directly. - * Added in version 1.15.0 + * The Cancellation detailed text. Currently unused. + * @member PropertyId.CancellationDetails_ReasonDetailedText */ - PropertyId[PropertyId["PronunciationAssessment_Json"] = 57] = "PronunciationAssessment_Json"; + PropertyId[PropertyId["CancellationDetails_ReasonDetailedText"] = 27] = "CancellationDetails_ReasonDetailedText"; /** - * Pronunciation assessment parameters. + * The URL string built from speech configuration. * This property is intended to be read-only. The SDK is using it internally. - * Added in version 1.15.0 + * NOTE: Added in version 1.7.0. */ - PropertyId[PropertyId["PronunciationAssessment_Params"] = 58] = "PronunciationAssessment_Params"; + PropertyId[PropertyId["SpeechServiceConnection_Url"] = 28] = "SpeechServiceConnection_Url"; /** - * Version of Speaker Recognition API to use. - * Added in version 1.18.0 + * The initial silence timeout value (in milliseconds) used by the service. + * Added in version 1.7.0 */ - PropertyId[PropertyId["SpeakerRecognition_Api_Version"] = 59] = "SpeakerRecognition_Api_Version"; -})(PropertyId = exports.PropertyId || (exports.PropertyId = {})); - - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Recognizer = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -/** - * Defines the base class Recognizer which mainly contains common event handlers. - * @class Recognizer - */ -var Recognizer = /** @class */ (function () { + PropertyId[PropertyId["SpeechServiceConnection_InitialSilenceTimeoutMs"] = 29] = "SpeechServiceConnection_InitialSilenceTimeoutMs"; /** - * Creates and initializes an instance of a Recognizer - * @constructor - * @param {AudioConfig} audioInput - An optional audio input stream associated with the recognizer + * This property is deprecated. + * For current information about silence timeouts, please visit https://aka.ms/csspeech/timeouts. */ - function Recognizer(audioConfig, properties, connectionFactory) { - this.audioConfig = (audioConfig !== undefined) ? audioConfig : Exports_3.AudioConfig.fromDefaultMicrophoneInput(); - this.privDisposed = false; - this.privProperties = properties.clone(); - this.privConnectionFactory = connectionFactory; - this.implCommonRecognizerSetup(); - } + PropertyId[PropertyId["SpeechServiceConnection_EndSilenceTimeoutMs"] = 30] = "SpeechServiceConnection_EndSilenceTimeoutMs"; /** - * Dispose of associated resources. - * @member Recognizer.prototype.close - * @function - * @public + * A duration of detected silence, measured in milliseconds, after which speech-to-text will determine a spoken + * phrase has ended and generate a final Recognized result. Configuring this timeout may be helpful in situations + * where spoken input is significantly faster or slower than usual and default segmentation behavior consistently + * yields results that are too long or too short. Segmentation timeout values that are inappropriately high or low + * can negatively affect speech-to-text accuracy; this property should be carefully configured and the resulting + * behavior should be thoroughly validated as intended. + * + * Refer to the documentation for valid value ranges and additional details: + * https://aka.ms/csspeech/timeouts + * + * Added in version 1.42.0. */ - Recognizer.prototype.close = function (cb, errorCb) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposed); - Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb); - }; - Object.defineProperty(Recognizer.prototype, "internalData", { - /** - * @Internal - * Internal data member to support fromRecognizer* pattern methods on other classes. - * Do not use externally, object returned will change without warning or notice. - */ - get: function () { - return this.privReco; - }, - enumerable: false, - configurable: true - }); + PropertyId[PropertyId["Speech_SegmentationSilenceTimeoutMs"] = 31] = "Speech_SegmentationSilenceTimeoutMs"; /** - * This method performs cleanup of resources. - * The Boolean parameter disposing indicates whether the method is called - * from Dispose (if disposing is true) or from the finalizer (if disposing is false). - * Derived classes should override this method to dispose resource if needed. - * @member Recognizer.prototype.dispose - * @function - * @public - * @param {boolean} disposing - Flag to request disposal. + * SegmentationMaximumTimeMs represents the maximum length of a spoken phrase when using the Time segmentation strategy. + * @member Speech_SegmentationSilenceTimeoutMs must be set in order to use this setting. + * As the length of a spoken phrase approaches this value, the @member Speech_SegmentationSilenceTimeoutMs will be reduced until either + * the phrase silence timeout is reached or the phrase reaches the maximum length. + * + * Valid range: **20,000 to 70,000** milliseconds. + * + * Added in version 1.42.0. */ - Recognizer.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privDisposed) { - return [2 /*return*/]; - } - this.privDisposed = true; - if (!disposing) return [3 /*break*/, 3]; - if (!this.privReco) return [3 /*break*/, 3]; - return [4 /*yield*/, this.privReco.audioSource.turnOff()]; - case 1: - _a.sent(); - return [4 /*yield*/, this.privReco.dispose()]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - Object.defineProperty(Recognizer, "telemetryEnabled", { - /** - * This method returns the current state of the telemetry setting. - * @member Recognizer.prototype.telemetryEnabled - * @function - * @public - * @returns true if the telemetry is enabled, false otherwise. - */ - get: function () { - return Exports_1.ServiceRecognizerBase.telemetryDataEnabled; - }, - enumerable: false, - configurable: true - }); + PropertyId[PropertyId["Speech_SegmentationMaximumTimeMs"] = 32] = "Speech_SegmentationMaximumTimeMs"; /** - * This method globally enables or disables telemetry. - * @member Recognizer.prototype.enableTelemetry - * @function - * @public - * @param enabled - Global setting for telemetry collection. - * If set to true, telemetry information like microphone errors, - * recognition errors are collected and sent to Microsoft. - * If set to false, no telemetry is sent to Microsoft. + * Specifies the strategy used to determine when a spoken phrase has ended, + * triggering the generation of a final recognition result. + * + * Supported values: + * - "Default": Uses the Speech Service's default segmentation strategy. Recommended for most use cases. + * - "Time": Uses a silence-based timeout. A final result is generated after a defined period of silence. + * Requires @member Speech_SegmentationMaximumTimeMs to be configured appropriately. + * Optional: Adjust @member Speech_SegmentationSilenceTimeoutMs to control how much silence ends a phrase. + * - "Semantic": Uses an AI model to semantically infer phrase boundaries based on content. + * No adjustable parameters are available for this strategy. + * + * Introduced in version 1.42.0. */ - /* tslint:disable:member-ordering */ - Recognizer.enableTelemetry = function (enabled) { - Exports_1.ServiceRecognizerBase.telemetryDataEnabled = enabled; - }; - // Does the generic recognizer setup that is common across all recognizer types. - Recognizer.prototype.implCommonRecognizerSetup = function () { - var osPlatform = (typeof window !== "undefined") ? "Browser" : "Node"; - var osName = "unknown"; - var osVersion = "unknown"; - if (typeof navigator !== "undefined") { - osPlatform = osPlatform + "/" + navigator.platform; - osName = navigator.userAgent; - osVersion = navigator.appVersion; - } - var recognizerConfig = this.createRecognizerConfig(new Exports_1.SpeechServiceConfig(new Exports_1.Context(new Exports_1.OS(osPlatform, osName, osVersion)))); - this.privReco = this.createServiceRecognizer(Recognizer.getAuthFromProperties(this.privProperties), this.privConnectionFactory, this.audioConfig, recognizerConfig); - }; - Recognizer.prototype.recognizeOnceAsyncImpl = function (recognitionMode) { - return __awaiter(this, void 0, void 0, function () { - var ret, result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - Contracts_1.Contracts.throwIfDisposed(this.privDisposed); - ret = new Exports_2.Deferred(); - return [4 /*yield*/, this.implRecognizerStop()]; - case 1: - _a.sent(); - return [4 /*yield*/, this.privReco.recognize(recognitionMode, ret.resolve, ret.reject)]; - case 2: - _a.sent(); - return [4 /*yield*/, ret.promise]; - case 3: - result = _a.sent(); - return [4 /*yield*/, this.implRecognizerStop()]; - case 4: - _a.sent(); - return [2 /*return*/, result]; - } - }); - }); - }; - Recognizer.prototype.startContinuousRecognitionAsyncImpl = function (recognitionMode) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - Contracts_1.Contracts.throwIfDisposed(this.privDisposed); - return [4 /*yield*/, this.implRecognizerStop()]; - case 1: - _a.sent(); - return [4 /*yield*/, this.privReco.recognize(recognitionMode, undefined, undefined)]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - Recognizer.prototype.stopContinuousRecognitionAsyncImpl = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - Contracts_1.Contracts.throwIfDisposed(this.privDisposed); - return [4 /*yield*/, this.implRecognizerStop()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - Recognizer.prototype.implRecognizerStop = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.privReco) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privReco.stopRecognizing()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - Recognizer.getAuthFromProperties = function (properties) { - var subscriptionKey = properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Key, undefined); - var authentication = (subscriptionKey && subscriptionKey !== "") ? - new Exports_1.CognitiveSubscriptionKeyAuthentication(subscriptionKey) : - new Exports_1.CognitiveTokenAuthentication(function (authFetchEventId) { - var authorizationToken = properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, undefined); - return Promise.resolve(authorizationToken); - }, function (authFetchEventId) { - var authorizationToken = properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, undefined); - return Promise.resolve(authorizationToken); - }); - return authentication; - }; - return Recognizer; -}()); -exports.Recognizer = Recognizer; - - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechRecognizer = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -/** - * Performs speech recognition from microphone, file, or other audio input streams, and gets transcribed text as result. - * @class SpeechRecognizer - */ -var SpeechRecognizer = /** @class */ (function (_super) { - __extends(SpeechRecognizer, _super); + PropertyId[PropertyId["Speech_SegmentationStrategy"] = 33] = "Speech_SegmentationStrategy"; /** - * SpeechRecognizer constructor. - * @constructor - * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer - * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer + * The sensitivity of how soon a potential speech start can be signaled. + * Allowed values are "low" (default), "medium" and "high". */ - function SpeechRecognizer(speechConfig, audioConfig) { - var _this = this; - var speechConfigImpl = speechConfig; - Contracts_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig"); - Contracts_1.Contracts.throwIfNullOrWhitespace(speechConfigImpl.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]); - _this = _super.call(this, audioConfig, speechConfigImpl.properties, new Exports_1.SpeechConnectionFactory()) || this; - _this.privDisposedRecognizer = false; - return _this; - } + PropertyId[PropertyId["Speech_StartEventSensitivity"] = 34] = "Speech_StartEventSensitivity"; /** - * SpeechRecognizer constructor. - * @constructor - * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer - * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the recognizer - * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer + * A boolean value specifying whether to process stereo input channels separately (instead of downmixing). + * Default is false. */ - SpeechRecognizer.FromConfig = function (speechConfig, autoDetectSourceLanguageConfig, audioConfig) { - var speechConfigImpl = speechConfig; - autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties); - var recognizer = new SpeechRecognizer(speechConfig, audioConfig); - return recognizer; - }; - Object.defineProperty(SpeechRecognizer.prototype, "endpointId", { - /** - * Gets the endpoint id of a customized speech model that is used for speech recognition. - * @member SpeechRecognizer.prototype.endpointId - * @function - * @public - * @returns {string} the endpoint id of a customized speech model that is used for speech recognition. - */ - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_EndpointId, "00000000-0000-0000-0000-000000000000"); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechRecognizer.prototype, "authorizationToken", { - /** - * Gets the authorization token used to communicate with the service. - * @member SpeechRecognizer.prototype.authorizationToken - * @function - * @public - * @returns {string} Authorization token. - */ - get: function () { - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token); - }, - /** - * Gets/Sets the authorization token used to communicate with the service. - * @member SpeechRecognizer.prototype.authorizationToken - * @function - * @public - * @param {string} token - Authorization token. - */ - set: function (token) { - Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token"); - this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, token); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechRecognizer.prototype, "speechRecognitionLanguage", { - /** - * Gets the spoken language of recognition. - * @member SpeechRecognizer.prototype.speechRecognitionLanguage - * @function - * @public - * @returns {string} The spoken language of recognition. - */ - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechRecognizer.prototype, "outputFormat", { - /** - * Gets the output format of recognition. - * @member SpeechRecognizer.prototype.outputFormat - * @function - * @public - * @returns {OutputFormat} The output format of recognition. - */ - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); - if (this.properties.getProperty(Exports_1.OutputFormatPropertyName, Exports_3.OutputFormat[Exports_3.OutputFormat.Simple]) === Exports_3.OutputFormat[Exports_3.OutputFormat.Simple]) { - return Exports_3.OutputFormat.Simple; - } - else { - return Exports_3.OutputFormat.Detailed; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechRecognizer.prototype, "properties", { - /** - * The collection of properties and their values defined for this SpeechRecognizer. - * @member SpeechRecognizer.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechRecognizer. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); + PropertyId[PropertyId["Speech_EnableMultiChannelProcessing"] = 35] = "Speech_EnableMultiChannelProcessing"; /** - * Starts speech recognition, and stops after the first utterance is recognized. - * The task returns the recognition text as result. - * Note: RecognizeOnceAsync() returns when the first utterance has been recognized, - * so it is suitable only for single shot recognition - * like command or query. For long-running recognition, use StartContinuousRecognitionAsync() instead. - * @member SpeechRecognizer.prototype.recognizeOnceAsync - * @function - * @public - * @param cb - Callback that received the SpeechRecognitionResult. - * @param err - Callback invoked in case of an error. + * A boolean value specifying whether audio logging is enabled in the service or not. + * Audio and content logs are stored either in Microsoft-owned storage, or in your own storage account linked + * to your Cognitive Services subscription (Bring Your Own Storage (BYOS) enabled Speech resource). + * The logs will be removed after 30 days. + * Added in version 1.7.0 */ - SpeechRecognizer.prototype.recognizeOnceAsync = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(Exports_1.RecognitionMode.Interactive), cb, err); - }; + PropertyId[PropertyId["SpeechServiceConnection_EnableAudioLogging"] = 36] = "SpeechServiceConnection_EnableAudioLogging"; /** - * Starts speech recognition, until stopContinuousRecognitionAsync() is called. - * User must subscribe to events to receive recognition results. - * @member SpeechRecognizer.prototype.startContinuousRecognitionAsync - * @function - * @public - * @param cb - Callback invoked once the recognition has started. - * @param err - Callback invoked in case of an error. - */ - SpeechRecognizer.prototype.startContinuousRecognitionAsync = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(Exports_1.RecognitionMode.Conversation), cb, err); - }; + * The speech service connection language identifier mode. + * Can be "AtStart" (the default), or "Continuous". See Language + * Identification document https://aka.ms/speech/lid?pivots=programming-language-javascript + * for more details. + * Added in 1.25.0 + **/ + PropertyId[PropertyId["SpeechServiceConnection_LanguageIdMode"] = 37] = "SpeechServiceConnection_LanguageIdMode"; /** - * Stops continuous speech recognition. - * @member SpeechRecognizer.prototype.stopContinuousRecognitionAsync - * @function - * @public - * @param cb - Callback invoked once the recognition has stopped. - * @param err - Callback invoked in case of an error. + * A string value representing the desired endpoint version to target for Speech Recognition. + * Added in version 1.21.0 */ - SpeechRecognizer.prototype.stopContinuousRecognitionAsync = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err); - }; + PropertyId[PropertyId["SpeechServiceConnection_RecognitionEndpointVersion"] = 38] = "SpeechServiceConnection_RecognitionEndpointVersion"; /** - * Starts speech recognition with keyword spotting, until - * stopKeywordRecognitionAsync() is called. - * User must subscribe to events to receive recognition results. - * Note: Key word spotting functionality is only available on the - * Speech Devices SDK. This functionality is currently not included in the SDK itself. - * @member SpeechRecognizer.prototype.startKeywordRecognitionAsync - * @function - * @public - * @param {KeywordRecognitionModel} model The keyword recognition model that - * specifies the keyword to be recognized. - * @param cb - Callback invoked once the recognition has started. - * @param err - Callback invoked in case of an error. + * The requested Cognitive Services Speech Service response output profanity setting. + * Allowed values are "masked", "removed", and "raw". + * Added in version 1.7.0. */ - SpeechRecognizer.prototype.startKeywordRecognitionAsync = function (model, cb, err) { - Contracts_1.Contracts.throwIfNull(model, "model"); - if (!!err) { - err("Not yet implemented."); - } - }; + PropertyId[PropertyId["SpeechServiceResponse_ProfanityOption"] = 39] = "SpeechServiceResponse_ProfanityOption"; /** - * Stops continuous speech recognition. - * Note: Key word spotting functionality is only available on the - * Speech Devices SDK. This functionality is currently not included in the SDK itself. - * @member SpeechRecognizer.prototype.stopKeywordRecognitionAsync - * @function - * @public - * @param cb - Callback invoked once the recognition has stopped. - * @param err - Callback invoked in case of an error. + * A string value specifying which post processing option should be used by service. + * Allowed values are "TrueText". + * Added in version 1.7.0 */ - SpeechRecognizer.prototype.stopKeywordRecognitionAsync = function (cb, err) { - if (!!cb) { - cb(); - } - }; + PropertyId[PropertyId["SpeechServiceResponse_PostProcessingOption"] = 40] = "SpeechServiceResponse_PostProcessingOption"; /** - * closes all external resources held by an instance of this class. - * @member SpeechRecognizer.prototype.close - * @function - * @public + * A boolean value specifying whether to include word-level timestamps in the response result. + * Added in version 1.7.0 */ - SpeechRecognizer.prototype.close = function (cb, errorCb) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); - Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb); - }; + PropertyId[PropertyId["SpeechServiceResponse_RequestWordLevelTimestamps"] = 41] = "SpeechServiceResponse_RequestWordLevelTimestamps"; /** - * Disposes any resources held by the object. - * @member SpeechRecognizer.prototype.dispose - * @function - * @public - * @param {boolean} disposing - true if disposing the object. + * The number of times a word has to be in partial results to be returned. + * Added in version 1.7.0 */ - SpeechRecognizer.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privDisposedRecognizer) { - return [2 /*return*/]; - } - if (!disposing) return [3 /*break*/, 2]; - this.privDisposedRecognizer = true; - return [4 /*yield*/, this.implRecognizerStop()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)]; - case 3: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - SpeechRecognizer.prototype.createRecognizerConfig = function (speechConfig) { - return new Exports_1.RecognizerConfig(speechConfig, this.properties); - }; - SpeechRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) { - var configImpl = audioConfig; - return new Exports_1.SpeechServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this); - }; - return SpeechRecognizer; -}(Exports_3.Recognizer)); -exports.SpeechRecognizer = SpeechRecognizer; - - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IntentRecognizer = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -/** - * Intent recognizer. - * @class - */ -var IntentRecognizer = /** @class */ (function (_super) { - __extends(IntentRecognizer, _super); + PropertyId[PropertyId["SpeechServiceResponse_StablePartialResultThreshold"] = 42] = "SpeechServiceResponse_StablePartialResultThreshold"; /** - * Initializes an instance of the IntentRecognizer. - * @constructor - * @param {SpeechConfig} speechConfig - The set of configuration properties. - * @param {AudioConfig} audioConfig - An optional audio input config associated with the recognizer - */ - function IntentRecognizer(speechConfig, audioConfig) { - var _this = this; - Contracts_1.Contracts.throwIfNullOrUndefined(speechConfig, "speechConfig"); - var configImpl = speechConfig; - Contracts_1.Contracts.throwIfNullOrUndefined(configImpl, "speechConfig"); - _this = _super.call(this, audioConfig, configImpl.properties, new Exports_1.IntentConnectionFactory()) || this; - _this.privAddedIntents = []; - _this.privAddedLmIntents = {}; - _this.privDisposedIntentRecognizer = false; - _this.privProperties = configImpl.properties; - Contracts_1.Contracts.throwIfNullOrWhitespace(_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]); - return _this; - } - Object.defineProperty(IntentRecognizer.prototype, "speechRecognitionLanguage", { - /** - * Gets the spoken language of recognition. - * @member IntentRecognizer.prototype.speechRecognitionLanguage - * @function - * @public - * @returns {string} the spoken language of recognition. - */ - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer); - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(IntentRecognizer.prototype, "authorizationToken", { - /** - * Gets the authorization token used to communicate with the service. - * @member IntentRecognizer.prototype.authorizationToken - * @function - * @public - * @returns {string} Authorization token. - */ - get: function () { - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token); - }, - /** - * Gets/Sets the authorization token used to communicate with the service. - * Note: Please use a token derived from your LanguageUnderstanding subscription key for the Intent recognizer. - * @member IntentRecognizer.prototype.authorizationToken - * @function - * @public - * @param {string} value - Authorization token. - */ - set: function (value) { - this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(IntentRecognizer.prototype, "properties", { - /** - * The collection of properties and their values defined for this IntentRecognizer. - * @member IntentRecognizer.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The collection of properties and their - * values defined for this IntentRecognizer. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); + * A string value specifying the output format option in the response result. Internal use only. + * Added in version 1.7.0. + */ + PropertyId[PropertyId["SpeechServiceResponse_OutputFormatOption"] = 43] = "SpeechServiceResponse_OutputFormatOption"; /** - * Starts intent recognition, and stops after the first utterance is recognized. - * The task returns the recognition text and intent as result. - * Note: RecognizeOnceAsync() returns when the first utterance has been recognized, - * so it is suitable only for single shot recognition like command or query. - * For long-running recognition, use StartContinuousRecognitionAsync() instead. - * @member IntentRecognizer.prototype.recognizeOnceAsync - * @function - * @public - * @param cb - Callback that received the recognition has finished with an IntentRecognitionResult. - * @param err - Callback invoked in case of an error. + * A boolean value to request for stabilizing translation partial results by omitting words in the end. + * Added in version 1.7.0. + */ + PropertyId[PropertyId["SpeechServiceResponse_TranslationRequestStablePartialResult"] = 44] = "SpeechServiceResponse_TranslationRequestStablePartialResult"; + /** + * A boolean value specifying whether to request WordBoundary events. + * @member PropertyId.SpeechServiceResponse_RequestWordBoundary + * Added in version 1.21.0. */ - IntentRecognizer.prototype.recognizeOnceAsync = function (cb, err) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer); - if (Object.keys(this.privAddedLmIntents).length !== 0 || undefined !== this.privUmbrellaIntent) { - var context = this.buildSpeechContext(); - this.privReco.speechContext.setSection("intent", context.Intent); - this.privReco.dynamicGrammar.addReferenceGrammar(context.ReferenceGrammars); - var intentReco = this.privReco; - intentReco.setIntents(this.privAddedLmIntents, this.privUmbrellaIntent); - } - Exports_2.marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(Exports_1.RecognitionMode.Interactive), cb, err); - }; + PropertyId[PropertyId["SpeechServiceResponse_RequestWordBoundary"] = 45] = "SpeechServiceResponse_RequestWordBoundary"; /** - * Starts speech recognition, until stopContinuousRecognitionAsync() is called. - * User must subscribe to events to receive recognition results. - * @member IntentRecognizer.prototype.startContinuousRecognitionAsync - * @function - * @public - * @param cb - Callback invoked once the recognition has started. - * @param err - Callback invoked in case of an error. + * A boolean value specifying whether to request punctuation boundary in WordBoundary Events. Default is true. + * @member PropertyId.SpeechServiceResponse_RequestPunctuationBoundary + * Added in version 1.21.0. */ - IntentRecognizer.prototype.startContinuousRecognitionAsync = function (cb, err) { - if (Object.keys(this.privAddedLmIntents).length !== 0 || undefined !== this.privUmbrellaIntent) { - var context = this.buildSpeechContext(); - this.privReco.speechContext.setSection("intent", context.Intent); - this.privReco.dynamicGrammar.addReferenceGrammar(context.ReferenceGrammars); - var intentReco = this.privReco; - intentReco.setIntents(this.privAddedLmIntents, this.privUmbrellaIntent); - } - Exports_2.marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(Exports_1.RecognitionMode.Conversation), cb, err); - }; + PropertyId[PropertyId["SpeechServiceResponse_RequestPunctuationBoundary"] = 46] = "SpeechServiceResponse_RequestPunctuationBoundary"; /** - * Stops continuous intent recognition. - * @member IntentRecognizer.prototype.stopContinuousRecognitionAsync - * @function - * @public - * @param cb - Callback invoked once the recognition has stopped. - * @param err - Callback invoked in case of an error. + * A boolean value specifying whether to request sentence boundary in WordBoundary Events. Default is false. + * @member PropertyId.SpeechServiceResponse_RequestSentenceBoundary + * Added in version 1.21.0. */ - IntentRecognizer.prototype.stopContinuousRecognitionAsync = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err); - }; + PropertyId[PropertyId["SpeechServiceResponse_RequestSentenceBoundary"] = 47] = "SpeechServiceResponse_RequestSentenceBoundary"; /** - * Starts speech recognition with keyword spotting, until stopKeywordRecognitionAsync() is called. - * User must subscribe to events to receive recognition results. - * Note: Key word spotting functionality is only available on the Speech Devices SDK. - * This functionality is currently not included in the SDK itself. - * @member IntentRecognizer.prototype.startKeywordRecognitionAsync - * @function - * @public - * @param {KeywordRecognitionModel} model - The keyword recognition model that specifies the keyword to be recognized. - * @param cb - Callback invoked once the recognition has started. - * @param err - Callback invoked in case of an error. + * Determines if intermediate results contain speaker identification. + * Allowed values are "true" or "false". If set to "true", the intermediate results will contain speaker identification. + * The default value if unset or set to an invalid value is "false". + * This is currently only supported for scenarios using the ConversationTranscriber". + * @member PropertyId.SpeechServiceResponse_DiarizeIntermediateResults + * Adding in version 1.41. */ - IntentRecognizer.prototype.startKeywordRecognitionAsync = function (model, cb, err) { - Contracts_1.Contracts.throwIfNull(model, "model"); - if (!!err) { - err("Not yet implemented."); - } - }; + PropertyId[PropertyId["SpeechServiceResponse_DiarizeIntermediateResults"] = 48] = "SpeechServiceResponse_DiarizeIntermediateResults"; /** - * Stops continuous speech recognition. - * Note: Key word spotting functionality is only available on the Speech Devices SDK. - * This functionality is currently not included in the SDK itself. - * @member IntentRecognizer.prototype.stopKeywordRecognitionAsync - * @function - * @public - * @param cb - Callback invoked once the recognition has stopped. - * @param err - Callback invoked in case of an error. + * Identifier used to connect to the backend service. + * @member PropertyId.Conversation_ApplicationId */ - IntentRecognizer.prototype.stopKeywordRecognitionAsync = function (cb, err) { - if (!!cb) { - cb(); - } - }; + PropertyId[PropertyId["Conversation_ApplicationId"] = 49] = "Conversation_ApplicationId"; /** - * Adds a phrase that should be recognized as intent. - * @member IntentRecognizer.prototype.addIntent - * @function - * @public - * @param {string} intentId - A String that represents the identifier of the intent to be recognized. - * @param {string} phrase - A String that specifies the phrase representing the intent. - */ - IntentRecognizer.prototype.addIntent = function (simplePhrase, intentId) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer); - Contracts_1.Contracts.throwIfNullOrWhitespace(intentId, "intentId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(simplePhrase, "simplePhrase"); - this.privAddedIntents.push([intentId, simplePhrase]); - }; - /** - * Adds an intent from Language Understanding service for recognition. - * @member IntentRecognizer.prototype.addIntentWithLanguageModel - * @function - * @public - * @param {string} intentId - A String that represents the identifier of the intent - * to be recognized. Ignored if intentName is empty. - * @param {string} model - The intent model from Language Understanding service. - * @param {string} intentName - The intent name defined in the intent model. If it - * is empty, all intent names defined in the model will be added. - */ - IntentRecognizer.prototype.addIntentWithLanguageModel = function (intentId, model, intentName) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer); - Contracts_1.Contracts.throwIfNullOrWhitespace(intentId, "intentId"); - Contracts_1.Contracts.throwIfNull(model, "model"); - var modelImpl = model; - Contracts_1.Contracts.throwIfNullOrWhitespace(modelImpl.appId, "model.appId"); - this.privAddedLmIntents[intentId] = new Exports_1.AddedLmIntent(modelImpl, intentName); - }; - /** - * @summary Adds all intents from the specified Language Understanding Model. - * @member IntentRecognizer.prototype.addAllIntents - * @function - * @public - * @function - * @public - * @param {LanguageUnderstandingModel} model - The language understanding model containing the intents. - * @param {string} intentId - A custom id String to be returned in the IntentRecognitionResult's getIntentId() method. + * Type of dialog backend to connect to. + * @member PropertyId.Conversation_DialogType */ - IntentRecognizer.prototype.addAllIntents = function (model, intentId) { - Contracts_1.Contracts.throwIfNull(model, "model"); - var modelImpl = model; - Contracts_1.Contracts.throwIfNullOrWhitespace(modelImpl.appId, "model.appId"); - this.privUmbrellaIntent = new Exports_1.AddedLmIntent(modelImpl, intentId); - }; + PropertyId[PropertyId["Conversation_DialogType"] = 50] = "Conversation_DialogType"; /** - * closes all external resources held by an instance of this class. - * @member IntentRecognizer.prototype.close - * @function - * @public + * Silence timeout for listening + * @member PropertyId.Conversation_Initial_Silence_Timeout */ - IntentRecognizer.prototype.close = function (cb, errorCb) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer); - Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb); - }; - IntentRecognizer.prototype.createRecognizerConfig = function (speechConfig) { - return new Exports_1.RecognizerConfig(speechConfig, this.properties); - }; - IntentRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) { - var audioImpl = audioConfig; - return new Exports_1.IntentServiceRecognizer(authentication, connectionFactory, audioImpl, recognizerConfig, this); - }; - IntentRecognizer.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privDisposedIntentRecognizer) { - return [2 /*return*/]; - } - if (!disposing) return [3 /*break*/, 2]; - this.privDisposedIntentRecognizer = true; - return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - IntentRecognizer.prototype.buildSpeechContext = function () { - var appId; - var region; - var subscriptionKey; - var refGrammers = []; - if (undefined !== this.privUmbrellaIntent) { - appId = this.privUmbrellaIntent.modelImpl.appId; - region = this.privUmbrellaIntent.modelImpl.region; - subscriptionKey = this.privUmbrellaIntent.modelImpl.subscriptionKey; - } - // Build the reference grammer array. - for (var _i = 0, _a = Object.keys(this.privAddedLmIntents); _i < _a.length; _i++) { - var intentId = _a[_i]; - var addedLmIntent = this.privAddedLmIntents[intentId]; - // validate all the same model, region, and key... - if (appId === undefined) { - appId = addedLmIntent.modelImpl.appId; - } - else { - if (appId !== addedLmIntent.modelImpl.appId) { - throw new Error("Intents must all be from the same LUIS model"); - } - } - if (region === undefined) { - region = addedLmIntent.modelImpl.region; - } - else { - if (region !== addedLmIntent.modelImpl.region) { - throw new Error("Intents must all be from the same LUIS model in a single region"); - } - } - if (subscriptionKey === undefined) { - subscriptionKey = addedLmIntent.modelImpl.subscriptionKey; - } - else { - if (subscriptionKey !== addedLmIntent.modelImpl.subscriptionKey) { - throw new Error("Intents must all use the same subscription key"); - } - } - var grammer = "luis/" + appId + "-PRODUCTION#" + intentId; - refGrammers.push(grammer); - } - return { - Intent: { - id: appId, - key: (subscriptionKey === undefined) ? this.privProperties.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Key]) : subscriptionKey, - provider: "LUIS", - }, - ReferenceGrammars: (undefined === this.privUmbrellaIntent) ? refGrammers : ["luis/" + appId + "-PRODUCTION"], - }; - }; - return IntentRecognizer; -}(Exports_3.Recognizer)); -exports.IntentRecognizer = IntentRecognizer; - - - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VoiceProfileType = void 0; -/** - * Output format - * @class VoiceProfileType - */ -var VoiceProfileType; -(function (VoiceProfileType) { + PropertyId[PropertyId["Conversation_Initial_Silence_Timeout"] = 51] = "Conversation_Initial_Silence_Timeout"; /** - * Text independent speaker identification - * @member VoiceProfileType.TextIndependentIdentification + * From Id to add to speech recognition activities. + * @member PropertyId.Conversation_From_Id */ - VoiceProfileType[VoiceProfileType["TextIndependentIdentification"] = 0] = "TextIndependentIdentification"; + PropertyId[PropertyId["Conversation_From_Id"] = 52] = "Conversation_From_Id"; /** - * Text dependent speaker verification - * @member VoiceProfileType.TextDependentVerification + * ConversationId for the session. + * @member PropertyId.Conversation_Conversation_Id */ - VoiceProfileType[VoiceProfileType["TextDependentVerification"] = 1] = "TextDependentVerification"; + PropertyId[PropertyId["Conversation_Conversation_Id"] = 53] = "Conversation_Conversation_Id"; /** - * Text independent speaker verification - * @member VoiceProfileType.TextIndependentVerification + * Comma separated list of custom voice deployment ids. + * @member PropertyId.Conversation_Custom_Voice_Deployment_Ids */ - VoiceProfileType[VoiceProfileType["TextIndependentVerification"] = 2] = "TextIndependentVerification"; -})(VoiceProfileType = exports.VoiceProfileType || (exports.VoiceProfileType = {})); - - - -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranslationRecognizer = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Connection_1 = __webpack_require__(105); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -/** - * Translation recognizer - * @class TranslationRecognizer - */ -var TranslationRecognizer = /** @class */ (function (_super) { - __extends(TranslationRecognizer, _super); + PropertyId[PropertyId["Conversation_Custom_Voice_Deployment_Ids"] = 54] = "Conversation_Custom_Voice_Deployment_Ids"; /** - * Initializes an instance of the TranslationRecognizer. - * @constructor - * @param {SpeechTranslationConfig} speechConfig - Set of properties to configure this recognizer. - * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer + * Speech activity template, stamp properties from the template on the activity generated by the service for speech. + * @member PropertyId.Conversation_Speech_Activity_Template + * Added in version 1.10.0. */ - function TranslationRecognizer(speechConfig, audioConfig) { - var _this = this; - var configImpl = speechConfig; - Contracts_1.Contracts.throwIfNull(configImpl, "speechConfig"); - _this = _super.call(this, audioConfig, configImpl.properties, new Exports_1.TranslationConnectionFactory()) || this; - _this.privDisposedTranslationRecognizer = false; - if (_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) { - Contracts_1.Contracts.throwIfNullOrWhitespace(_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationVoice), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_TranslationVoice]); - } - Contracts_1.Contracts.throwIfNullOrWhitespace(_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages]); - Contracts_1.Contracts.throwIfNullOrWhitespace(_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]); - return _this; - } - Object.defineProperty(TranslationRecognizer.prototype, "speechRecognitionLanguage", { - /** - * Gets the language name that was set when the recognizer was created. - * @member TranslationRecognizer.prototype.speechRecognitionLanguage - * @function - * @public - * @returns {string} Gets the language name that was set when the recognizer was created. - */ - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationRecognizer.prototype, "targetLanguages", { - /** - * Gets target languages for translation that were set when the recognizer was created. - * The language is specified in BCP-47 format. The translation will provide translated text for each of language. - * @member TranslationRecognizer.prototype.targetLanguages - * @function - * @public - * @returns {string[]} Gets target languages for translation that were set when the recognizer was created. - */ - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationRecognizer.prototype, "voiceName", { - /** - * Gets the name of output voice. - * @member TranslationRecognizer.prototype.voiceName - * @function - * @public - * @returns {string} the name of output voice. - */ - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationRecognizer.prototype, "authorizationToken", { - /** - * Gets the authorization token used to communicate with the service. - * @member TranslationRecognizer.prototype.authorizationToken - * @function - * @public - * @returns {string} Authorization token. - */ - get: function () { - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token); - }, - /** - * Gets/Sets the authorization token used to communicate with the service. - * @member TranslationRecognizer.prototype.authorizationToken - * @function - * @public - * @param {string} value - Authorization token. - */ - set: function (value) { - this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationRecognizer.prototype, "properties", { - /** - * The collection of properties and their values defined for this TranslationRecognizer. - * @member TranslationRecognizer.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The collection of properties and their values defined for this TranslationRecognizer. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); + PropertyId[PropertyId["Conversation_Speech_Activity_Template"] = 55] = "Conversation_Speech_Activity_Template"; /** - * Starts recognition and translation, and stops after the first utterance is recognized. - * The task returns the translation text as result. - * Note: recognizeOnceAsync returns when the first utterance has been recognized, so it is suitableonly - * for single shot recognition like command or query. For long-running recognition, - * use startContinuousRecognitionAsync() instead. - * @member TranslationRecognizer.prototype.recognizeOnceAsync - * @function - * @public - * @param cb - Callback that received the result when the translation has completed. - * @param err - Callback invoked in case of an error. + * Enables or disables the receipt of turn status messages as obtained on the turnStatusReceived event. + * @member PropertyId.Conversation_Request_Bot_Status_Messages + * Added in version 1.15.0. */ - TranslationRecognizer.prototype.recognizeOnceAsync = function (cb, err) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); - Exports_2.marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(Exports_1.RecognitionMode.Conversation), cb, err); - }; + PropertyId[PropertyId["Conversation_Request_Bot_Status_Messages"] = 56] = "Conversation_Request_Bot_Status_Messages"; /** - * Starts recognition and translation, until stopContinuousRecognitionAsync() is called. - * User must subscribe to events to receive translation results. - * @member TranslationRecognizer.prototype.startContinuousRecognitionAsync - * @function - * @public - * @param cb - Callback that received the translation has started. - * @param err - Callback invoked in case of an error. + * Specifies the connection ID to be provided in the Agent configuration message, e.g. a Direct Line token for + * channel authentication. + * Added in version 1.15.1. */ - TranslationRecognizer.prototype.startContinuousRecognitionAsync = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(Exports_1.RecognitionMode.Conversation), cb, err); - }; + PropertyId[PropertyId["Conversation_Agent_Connection_Id"] = 57] = "Conversation_Agent_Connection_Id"; /** - * Stops continuous recognition and translation. - * @member TranslationRecognizer.prototype.stopContinuousRecognitionAsync - * @function - * @public - * @param cb - Callback that received the translation has stopped. - * @param err - Callback invoked in case of an error. + * The Cognitive Services Speech Service host (url). Under normal circumstances, you shouldn't have to use this property directly. + * Instead, use [[SpeechConfig.fromHost]]. */ - TranslationRecognizer.prototype.stopContinuousRecognitionAsync = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err); - }; + PropertyId[PropertyId["SpeechServiceConnection_Host"] = 58] = "SpeechServiceConnection_Host"; /** - * dynamically remove a language from list of target language - * (can be used while recognition is ongoing) - * @member TranslationRecognizer.prototype.removeTargetLanguage - * @function - * @param lang - language to be removed - * @public + * The reference text of the audio for pronunciation evaluation. + * For this and the following pronunciation assessment parameters, see + * https://docs.microsoft.com/azure/cognitive-services/speech-service/rest-speech-to-text#pronunciation-assessment-parameters for details. + * Under normal circumstances, you shouldn't have to use this property directly. + * Added in version 1.15.0 */ - TranslationRecognizer.prototype.removeTargetLanguage = function (lang) { - Contracts_1.Contracts.throwIfNullOrUndefined(lang, "language to be removed"); - if (this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) { - var languages = this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","); - var index = languages.indexOf(lang); - if (index > -1) { - languages.splice(index, 1); - this.properties.setProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(",")); - this.updateLanguages(languages); - } - } - }; + PropertyId[PropertyId["PronunciationAssessment_ReferenceText"] = 59] = "PronunciationAssessment_ReferenceText"; /** - * dynamically add a language to list of target language - * (can be used while recognition is ongoing) - * @member TranslationRecognizer.prototype.addTargetLanguage - * @function - * @param lang - language to be added - * @public + * The point system for pronunciation score calibration (FivePoint or HundredMark). + * Under normal circumstances, you shouldn't have to use this property directly. + * Added in version 1.15.0 */ - TranslationRecognizer.prototype.addTargetLanguage = function (lang) { - Contracts_1.Contracts.throwIfNullOrUndefined(lang, "language to be added"); - var languages = []; - if (this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) { - languages = this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","); - if (!languages.includes(lang)) { - languages.push(lang); - this.properties.setProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(",")); - } - } - else { - this.properties.setProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, lang); - languages = [lang]; - } - this.updateLanguages(languages); - }; + PropertyId[PropertyId["PronunciationAssessment_GradingSystem"] = 60] = "PronunciationAssessment_GradingSystem"; /** - * closes all external resources held by an instance of this class. - * @member TranslationRecognizer.prototype.close - * @function - * @public + * The pronunciation evaluation granularity (Phoneme, Word, or FullText). + * Under normal circumstances, you shouldn't have to use this property directly. + * Added in version 1.15.0 */ - TranslationRecognizer.prototype.close = function (cb, errorCb) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); - Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb); - }; + PropertyId[PropertyId["PronunciationAssessment_Granularity"] = 61] = "PronunciationAssessment_Granularity"; /** - * handles ConnectionEstablishedEvent for conversation translation scenarios. - * @member TranslationRecognizer.prototype.onConnection - * @function - * @public + * Defines if enable miscue calculation. + * With this enabled, the pronounced words will be compared to the reference text, + * and will be marked with omission/insertion based on the comparison. The default setting is False. + * Under normal circumstances, you shouldn't have to use this property directly. + * Added in version 1.15.0 */ - /* tslint:disable:no-empty */ - TranslationRecognizer.prototype.onConnection = function () { }; + PropertyId[PropertyId["PronunciationAssessment_EnableMiscue"] = 62] = "PronunciationAssessment_EnableMiscue"; /** - * handles disconnection events for conversation translation scenarios. - * @member TranslationRecognizer.prototype.onDisconnection - * @function - * @public + * The json string of pronunciation assessment parameters + * Under normal circumstances, you shouldn't have to use this property directly. + * Added in version 1.15.0 */ - /* tslint:disable:no-empty */ - TranslationRecognizer.prototype.onDisconnection = function () { - return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { - return [2 /*return*/]; - }); }); - }; - TranslationRecognizer.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privDisposedTranslationRecognizer) { - return [2 /*return*/]; - } - this.privDisposedTranslationRecognizer = true; - if (!disposing) return [3 /*break*/, 3]; - return [4 /*yield*/, this.implRecognizerStop()]; - case 1: - _a.sent(); - return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - TranslationRecognizer.prototype.createRecognizerConfig = function (speechConfig) { - return new Exports_1.RecognizerConfig(speechConfig, this.properties); - }; - TranslationRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) { - var configImpl = audioConfig; - return new Exports_1.TranslationServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this); - }; - TranslationRecognizer.prototype.updateLanguages = function (languages) { - var conn = Connection_1.Connection.fromRecognizer(this); - if (!!conn) { - conn.setMessageProperty("speech.context", "translationcontext", { to: languages }); - conn.sendMessageAsync("event", JSON.stringify({ - id: "translation", - name: "updateLanguage", - to: languages - })); - } - }; - return TranslationRecognizer; -}(Exports_3.Recognizer)); -exports.TranslationRecognizer = TranslationRecognizer; - - - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. -// -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Connection = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var ConnectionMessage_1 = __webpack_require__(106); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -/** - * Connection is a proxy class for managing connection to the speech service of the specified Recognizer. - * By default, a Recognizer autonomously manages connection to service when needed. - * The Connection class provides additional methods for users to explicitly open or close a connection and - * to subscribe to connection status changes. - * The use of Connection is optional, and mainly for scenarios where fine tuning of application - * behavior based on connection status is needed. Users can optionally call Open() to manually set up a connection - * in advance before starting recognition on the Recognizer associated with this Connection. - * If the Recognizer needs to connect or disconnect to service, it will - * setup or shutdown the connection independently. In this case the Connection will be notified by change of connection - * status via Connected/Disconnected events. - * Added in version 1.2.1. - */ -var Connection = /** @class */ (function () { - function Connection() { - } + PropertyId[PropertyId["PronunciationAssessment_Json"] = 63] = "PronunciationAssessment_Json"; /** - * Gets the Connection instance from the specified recognizer. - * @param recognizer The recognizer associated with the connection. - * @return The Connection instance of the recognizer. + * Pronunciation assessment parameters. + * This property is intended to be read-only. The SDK is using it internally. + * Added in version 1.15.0 */ - Connection.fromRecognizer = function (recognizer) { - var recoBase = recognizer.internalData; - var ret = new Connection(); - ret.privInternalData = recoBase; - ret.setupEvents(); - return ret; - }; + PropertyId[PropertyId["PronunciationAssessment_Params"] = 64] = "PronunciationAssessment_Params"; /** - * Gets the Connection instance from the specified synthesizer. - * @param synthesizer The synthesizer associated with the connection. - * @return The Connection instance of the synthesizer. + * Specifies whether to allow load of data URL for web worker + * Allowed values are "off" and "on". Default is "on". + * Added in version 1.32.0 */ - Connection.fromSynthesizer = function (synthesizer) { - var synthBase = synthesizer.internalData; - var ret = new Connection(); - ret.privInternalData = synthBase; - ret.setupEvents(); - return ret; - }; + PropertyId[PropertyId["WebWorkerLoadType"] = 65] = "WebWorkerLoadType"; /** - * Starts to set up connection to the service. - * Users can optionally call openConnection() to manually set up a connection in advance before starting recognition on the - * Recognizer associated with this Connection. After starting recognition, calling Open() will have no effect - * - * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to - * be notified when the connection is established. + * Talking avatar service WebRTC session description protocol. + * This property is intended to be read-only. The SDK is using it internally. + * Added in version 1.33.0 */ - Connection.prototype.openConnection = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.privInternalData.connect(), cb, err); - }; + PropertyId[PropertyId["TalkingAvatarService_WebRTC_SDP"] = 66] = "TalkingAvatarService_WebRTC_SDP"; /** - * Closes the connection the service. - * Users can optionally call closeConnection() to manually shutdown the connection of the associated Recognizer. + * The timeout (in milliseconds) for stopping a recognizer. + * When set, if stopContinuousRecognitionAsync() doesn't complete within this time + * (due to the service being behind in processing audio), the operation will be + * cancelled and an error will be thrown. * - * If closeConnection() is called during recognition, recognition will fail and cancel with an error. + * If not set or set to 0, the stop operation will wait indefinitely for the service + * to complete (existing behavior). + * + * Note: This timeout only applies to the graceful stop operation. It does not affect + * the disconnect() method which always cancels immediately. + * + * Added in version 1.48.0 */ - Connection.prototype.closeConnection = function (cb, err) { - if (this.privInternalData instanceof Exports_1.SynthesisAdapterBase) { - throw new Error("Disconnecting a synthesizer's connection is currently not supported"); - } - else { - Exports_2.marshalPromiseToCallbacks(this.privInternalData.disconnect(), cb, err); - } - }; + PropertyId[PropertyId["Recognizer_StopTimeoutMs"] = 67] = "Recognizer_StopTimeoutMs"; /** - * Appends a parameter in a message to service. - * Added in version 1.12.1. - * @param path The path of the network message. - * @param propertyName Name of the property - * @param propertyValue Value of the property. This is a json string. + * The recognition latency in milliseconds. Read-only, available on speech/translation recognition results. + * This measures the latency between when an audio input is received by the SDK, and the moment the result + * is received from the service. + * The SDK computes the time difference between the last audio fragment from the audio input that is + * contributing to the result, and the time the result is received from the speech service. + * Added in version 1.48.0 */ - Connection.prototype.setMessageProperty = function (path, propertyName, propertyValue) { - Contracts_1.Contracts.throwIfNullOrWhitespace(propertyName, "propertyName"); - if (this.privInternalData instanceof Exports_1.ServiceRecognizerBase) { - if (path.toLowerCase() !== "speech.context") { - throw new Error("Only speech.context message property sets are currently supported for recognizer"); - } - else { - this.privInternalData.speechContext.setSection(propertyName, propertyValue); - } - } - else if (this.privInternalData instanceof Exports_1.SynthesisAdapterBase) { - if (path.toLowerCase() !== "synthesis.context") { - throw new Error("Only synthesis.context message property sets are currently supported for synthesizer"); - } - else { - this.privInternalData.synthesisContext.setSection(propertyName, propertyValue); - } - } - }; + PropertyId[PropertyId["SpeechServiceResponse_RecognitionLatencyMs"] = 68] = "SpeechServiceResponse_RecognitionLatencyMs"; /** - * Sends a message to the speech service. - * Added in version 1.13.0. - * @param path The WebSocket path of the message - * @param payload The payload of the message. This is a json string or a ArrayBuffer. - * @param success A callback to indicate success. - * @param error A callback to indicate an error. + * The speech synthesis first byte latency in milliseconds. Read-only, available on speech synthesis results. + * This measures the time from when the synthesis request is sent to when the first audio byte is received + * from the service, including network latency. */ - Connection.prototype.sendMessageAsync = function (path, payload, success, error) { - Exports_2.marshalPromiseToCallbacks(this.privInternalData.sendNetworkMessage(path, payload), success, error); - }; + PropertyId[PropertyId["SpeechServiceResponse_SynthesisFirstByteLatencyMs"] = 69] = "SpeechServiceResponse_SynthesisFirstByteLatencyMs"; /** - * Dispose of associated resources. + * The speech synthesis finish latency in milliseconds. Read-only, available on speech synthesis results. + * This measures the time from when the synthesis request is sent to when the full synthesized audio is + * received from the service, including network latency. */ - Connection.prototype.close = function () { - /* tslint:disable:no-empty */ - }; - Connection.prototype.setupEvents = function () { - var _this = this; - this.privEventListener = this.privInternalData.connectionEvents.attach(function (connectionEvent) { - if (connectionEvent.name === "ConnectionEstablishedEvent") { - if (!!_this.connected) { - _this.connected(new Exports_3.ConnectionEventArgs(connectionEvent.connectionId)); - } - } - else if (connectionEvent.name === "ConnectionClosedEvent") { - if (!!_this.disconnected) { - _this.disconnected(new Exports_3.ConnectionEventArgs(connectionEvent.connectionId)); - } - } - else if (connectionEvent.name === "ConnectionMessageSentEvent") { - if (!!_this.messageSent) { - _this.messageSent(new Exports_3.ConnectionMessageEventArgs(new ConnectionMessage_1.ConnectionMessageImpl(connectionEvent.message))); - } - } - else if (connectionEvent.name === "ConnectionMessageReceivedEvent") { - if (!!_this.messageReceived) { - _this.messageReceived(new Exports_3.ConnectionMessageEventArgs(new ConnectionMessage_1.ConnectionMessageImpl(connectionEvent.message))); - } - } - }); - this.privServiceEventListener = this.privInternalData.serviceEvents.attach(function (e) { - if (!!_this.receivedServiceMessage) { - _this.receivedServiceMessage(new Exports_3.ServiceEventArgs(e.jsonString, e.name)); - } - }); - }; - return Connection; -}()); -exports.Connection = Connection; - - - -/***/ }), -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. -// -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionMessageImpl = exports.ConnectionMessage = void 0; -var HeaderNames_1 = __webpack_require__(55); -var Exports_1 = __webpack_require__(4); -var PropertyCollection_1 = __webpack_require__(98); -var PropertyId_1 = __webpack_require__(99); -/** - * ConnectionMessage represents implementation specific messages sent to and received from - * the speech service. These messages are provided for debugging purposes and should not - * be used for production use cases with the Azure Cognitive Services Speech Service. - * Messages sent to and received from the Speech Service are subject to change without - * notice. This includes message contents, headers, payloads, ordering, etc. - * Added in version 1.11.0. - */ -var ConnectionMessage = /** @class */ (function () { - function ConnectionMessage() { - } - return ConnectionMessage; -}()); -exports.ConnectionMessage = ConnectionMessage; -// tslint:disable-next-line:max-classes-per-file -var ConnectionMessageImpl = /** @class */ (function () { - function ConnectionMessageImpl(message) { - var _this = this; - this.privConnectionMessage = message; - this.privProperties = new PropertyCollection_1.PropertyCollection(); - if (!!this.privConnectionMessage.headers[HeaderNames_1.HeaderNames.ConnectionId]) { - this.privProperties.setProperty(PropertyId_1.PropertyId.Speech_SessionId, this.privConnectionMessage.headers[HeaderNames_1.HeaderNames.ConnectionId]); - } - Object.keys(this.privConnectionMessage.headers).forEach(function (header, index, array) { - _this.privProperties.setProperty(header, _this.privConnectionMessage.headers[header]); - }); - } - Object.defineProperty(ConnectionMessageImpl.prototype, "path", { - /** - * The message path. - */ - get: function () { - return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find(function (key) { return key.toLowerCase() === "path".toLowerCase(); })]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessageImpl.prototype, "isTextMessage", { - /** - * Checks to see if the ConnectionMessage is a text message. - * See also IsBinaryMessage(). - */ - get: function () { - return this.privConnectionMessage.messageType === Exports_1.MessageType.Text; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessageImpl.prototype, "isBinaryMessage", { - /** - * Checks to see if the ConnectionMessage is a binary message. - * See also GetBinaryMessage(). - */ - get: function () { - return this.privConnectionMessage.messageType === Exports_1.MessageType.Binary; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessageImpl.prototype, "TextMessage", { - /** - * Gets the text message payload. Typically the text message content-type is - * application/json. To determine other content-types use - * Properties.GetProperty("Content-Type"). - */ - get: function () { - return this.privConnectionMessage.textBody; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessageImpl.prototype, "binaryMessage", { - /** - * Gets the binary message payload. - */ - get: function () { - return this.privConnectionMessage.binaryBody; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConnectionMessageImpl.prototype, "properties", { - /** - * A collection of properties and their values defined for this . - * Message headers can be accessed via this collection (e.g. "Content-Type"). - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); + PropertyId[PropertyId["SpeechServiceResponse_SynthesisFinishLatencyMs"] = 70] = "SpeechServiceResponse_SynthesisFinishLatencyMs"; /** - * Returns a string that represents the connection message. + * The speech synthesis connection latency in milliseconds. Read-only, available on speech synthesis results. + * This measures the time to establish the WebSocket connection to the service. + * If the connection is reused from a previous synthesis, this value is 0. */ - ConnectionMessageImpl.prototype.toString = function () { - return ""; - }; - return ConnectionMessageImpl; -}()); -exports.ConnectionMessageImpl = ConnectionMessageImpl; - - - -/***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Translations = void 0; -var Exports_1 = __webpack_require__(61); -/** - * Represents collection of parameters and their values. - * @class Translations - */ -var Translations = /** @class */ (function () { - function Translations() { - // Use an PropertyCollection internally, just wrapping it to hide the | enum syntax it has. - this.privMap = new Exports_1.PropertyCollection(); - } + PropertyId[PropertyId["SpeechServiceResponse_SynthesisConnectionLatencyMs"] = 71] = "SpeechServiceResponse_SynthesisConnectionLatencyMs"; /** - * Returns the parameter value in type String. The parameter must have the same type as String. - * Currently only String, int and bool are allowed. - * If the name is not available, the specified defaultValue is returned. - * @member Translations.prototype.get - * @function - * @public - * @param {string} key - The parameter name. - * @param {string} def - The default value which is returned if the parameter is not available in the collection. - * @returns {string} value of the parameter. + * The speech synthesis network latency in milliseconds. Read-only, available on speech synthesis results. + * This measures the network round-trip time between the client and the Azure TTS service. */ - Translations.prototype.get = function (key, def) { - return this.privMap.getProperty(key, def); - }; + PropertyId[PropertyId["SpeechServiceResponse_SynthesisNetworkLatencyMs"] = 72] = "SpeechServiceResponse_SynthesisNetworkLatencyMs"; /** - * Sets the String value of the parameter specified by name. - * @member Translations.prototype.set - * @function - * @public - * @param {string} key - The parameter name. - * @param {string} value - The value of the parameter. + * The speech synthesis service latency in milliseconds. Read-only, available on speech synthesis results. + * This measures the time from when the Azure TTS service receives the synthesis request to when it sends + * back the first audio chunk. */ - Translations.prototype.set = function (key, value) { - this.privMap.setProperty(key, value); - }; - Object.defineProperty(Translations.prototype, "languages", { - /** - * Get the languages in the object in a String array. - * @member Translations.prototype.languages - * @function - * @public - * @returns {string[]} languages in translations object. - */ - get: function () { - return this.privMap.keys; - }, - enumerable: false, - configurable: true - }); - return Translations; -}()); -exports.Translations = Translations; - - - -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoMatchReason = void 0; -/** - * Defines the possible reasons a recognition result might not be recognized. - * @class NoMatchReason - */ -var NoMatchReason; -(function (NoMatchReason) { + PropertyId[PropertyId["SpeechServiceResponse_SynthesisServiceLatencyMs"] = 73] = "SpeechServiceResponse_SynthesisServiceLatencyMs"; + /* + * The pitch of the voice for a speech synthesis request. + * @member PropertyId.SpeechSynthesisRequest_Pitch + */ + PropertyId[PropertyId["SpeechSynthesisRequest_Pitch"] = 74] = "SpeechSynthesisRequest_Pitch"; /** - * Indicates that speech was detected, but not recognized. - * @member NoMatchReason.NotRecognized + * The speaking rate of the voice for a speech synthesis request. + * @member PropertyId.SpeechSynthesisRequest_Rate */ - NoMatchReason[NoMatchReason["NotRecognized"] = 0] = "NotRecognized"; + PropertyId[PropertyId["SpeechSynthesisRequest_Rate"] = 75] = "SpeechSynthesisRequest_Rate"; /** - * Indicates that the start of the audio stream contained only silence, - * and the service timed out waiting for speech. - * @member NoMatchReason.InitialSilenceTimeout + * The volume of the voice for a speech synthesis request. + * @member PropertyId.SpeechSynthesisRequest_Volume */ - NoMatchReason[NoMatchReason["InitialSilenceTimeout"] = 1] = "InitialSilenceTimeout"; + PropertyId[PropertyId["SpeechSynthesisRequest_Volume"] = 76] = "SpeechSynthesisRequest_Volume"; /** - * Indicates that the start of the audio stream contained only noise, - * and the service timed out waiting for speech. - * @member NoMatchReason.InitialBabbleTimeout + * The style of the voice for a speech synthesis request. + * @member PropertyId.SpeechSynthesisRequest_Style */ - NoMatchReason[NoMatchReason["InitialBabbleTimeout"] = 2] = "InitialBabbleTimeout"; -})(NoMatchReason = exports.NoMatchReason || (exports.NoMatchReason = {})); - - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoMatchDetails = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(61); -/** - * Contains detailed information for NoMatch recognition results. - * @class NoMatchDetails - */ -var NoMatchDetails = /** @class */ (function () { + PropertyId[PropertyId["SpeechSynthesisRequest_Style"] = 77] = "SpeechSynthesisRequest_Style"; /** - * Creates and initializes an instance of this class. - * @constructor - * @param {NoMatchReason} reason - The no-match reason. + * The temperature of the voice synthesis for a speech synthesis request. + * @member PropertyId.SpeechSynthesisRequest_Temperature */ - function NoMatchDetails(reason) { - this.privReason = reason; - } + PropertyId[PropertyId["SpeechSynthesisRequest_Temperature"] = 78] = "SpeechSynthesisRequest_Temperature"; /** - * Creates an instance of NoMatchDetails object for the NoMatch SpeechRecognitionResults. - * @member NoMatchDetails.fromResult - * @function - * @public - * @param {SpeechRecognitionResult | IntentRecognitionResult | TranslationRecognitionResult} - * result - The recognition result that was not recognized. - * @returns {NoMatchDetails} The no match details object being created. + * The custom lexicon URL for a speech synthesis request. + * @member PropertyId.SpeechSynthesisRequest_CustomLexiconUrl */ - NoMatchDetails.fromResult = function (result) { - var simpleSpeech = Exports_1.SimpleSpeechPhrase.fromJSON(result.json); - var reason = Exports_2.NoMatchReason.NotRecognized; - switch (simpleSpeech.RecognitionStatus) { - case Exports_1.RecognitionStatus.BabbleTimeout: - reason = Exports_2.NoMatchReason.InitialBabbleTimeout; - break; - case Exports_1.RecognitionStatus.InitialSilenceTimeout: - reason = Exports_2.NoMatchReason.InitialSilenceTimeout; - break; - default: - reason = Exports_2.NoMatchReason.NotRecognized; - break; - } - return new NoMatchDetails(reason); - }; - Object.defineProperty(NoMatchDetails.prototype, "reason", { - /** - * The reason the recognition was canceled. - * @member NoMatchDetails.prototype.reason - * @function - * @public - * @returns {NoMatchReason} Specifies the reason canceled. - */ - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - return NoMatchDetails; -}()); -exports.NoMatchDetails = NoMatchDetails; - - - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranslationRecognitionCanceledEventArgs = void 0; -/** - * Define payload of speech recognition canceled result events. - * @class TranslationRecognitionCanceledEventArgs - */ -var TranslationRecognitionCanceledEventArgs = /** @class */ (function () { + PropertyId[PropertyId["SpeechSynthesisRequest_CustomLexiconUrl"] = 79] = "SpeechSynthesisRequest_CustomLexiconUrl"; /** - * Creates and initializes an instance of this class. - * @constructor - * @param {string} sessionid - The session id. - * @param {CancellationReason} cancellationReason - The cancellation reason. - * @param {string} errorDetails - Error details, if provided. - * @param {TranslationRecognitionResult} result - The result. + * The preferred locales for a speech synthesis request. + * @member PropertyId.SpeechSynthesisRequest_PreferLocales */ - function TranslationRecognitionCanceledEventArgs(sessionid, cancellationReason, errorDetails, errorCode, result) { - this.privCancelReason = cancellationReason; - this.privErrorDetails = errorDetails; - this.privResult = result; - this.privSessionId = sessionid; - this.privErrorCode = errorCode; - } - Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "result", { - /** - * Specifies the recognition result. - * @member TranslationRecognitionCanceledEventArgs.prototype.result - * @function - * @public - * @returns {TranslationRecognitionResult} the recognition result. - */ - get: function () { - return this.privResult; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "sessionId", { - /** - * Specifies the session identifier. - * @member TranslationRecognitionCanceledEventArgs.prototype.sessionId - * @function - * @public - * @returns {string} the session identifier. - */ - get: function () { - return this.privSessionId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "reason", { - /** - * The reason the recognition was canceled. - * @member TranslationRecognitionCanceledEventArgs.prototype.reason - * @function - * @public - * @returns {CancellationReason} Specifies the reason canceled. - */ - get: function () { - return this.privCancelReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "errorCode", { - /** - * The error code in case of an unsuccessful recognition. - * Added in version 1.1.0. - * @return An error code that represents the error reason. - */ - get: function () { - return this.privErrorCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "errorDetails", { - /** - * In case of an unsuccessful recognition, provides details of the occurred error. - * @member TranslationRecognitionCanceledEventArgs.prototype.errorDetails - * @function - * @public - * @returns {string} A String that represents the error details. - */ - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - return TranslationRecognitionCanceledEventArgs; -}()); -exports.TranslationRecognitionCanceledEventArgs = TranslationRecognitionCanceledEventArgs; - - - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IntentRecognitionCanceledEventArgs = void 0; -var Exports_1 = __webpack_require__(61); -/** - * Define payload of intent recognition canceled result events. - * @class IntentRecognitionCanceledEventArgs - */ -var IntentRecognitionCanceledEventArgs = /** @class */ (function (_super) { - __extends(IntentRecognitionCanceledEventArgs, _super); + PropertyId[PropertyId["SpeechSynthesisRequest_PreferLocales"] = 80] = "SpeechSynthesisRequest_PreferLocales"; /** - * Creates and initializes an instance of this class. - * @constructor - * @param {CancellationReason} result - The result of the intent recognition. - * @param {string} offset - The offset. - * @param {IntentRecognitionResult} sessionId - The session id. - */ - function IntentRecognitionCanceledEventArgs(reason, errorDetails, errorCode, result, offset, sessionId) { - var _this = _super.call(this, result, offset, sessionId) || this; - _this.privReason = reason; - _this.privErrorDetails = errorDetails; - _this.privErrorCode = errorCode; - return _this; - } - Object.defineProperty(IntentRecognitionCanceledEventArgs.prototype, "reason", { - /** - * The reason the recognition was canceled. - * @member IntentRecognitionCanceledEventArgs.prototype.reason - * @function - * @public - * @returns {CancellationReason} Specifies the reason canceled. - */ - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(IntentRecognitionCanceledEventArgs.prototype, "errorCode", { - /** - * The error code in case of an unsuccessful recognition. - * Added in version 1.1.0. - * @return An error code that represents the error reason. - */ - get: function () { - return this.privErrorCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(IntentRecognitionCanceledEventArgs.prototype, "errorDetails", { - /** - * In case of an unsuccessful recognition, provides details of the occurred error. - * @member IntentRecognitionCanceledEventArgs.prototype.errorDetails - * @function - * @public - * @returns {string} A String that represents the error details. - */ - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - return IntentRecognitionCanceledEventArgs; -}(Exports_1.IntentRecognitionEventArgs)); -exports.IntentRecognitionCanceledEventArgs = IntentRecognitionCanceledEventArgs; - - - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CancellationDetailsBase = void 0; -/** - * Contains detailed information about why a result was canceled. - * @class CancellationDetailsBase - */ -var CancellationDetailsBase = /** @class */ (function () { + * The frame timeout interval (in ticks) for speech synthesis. + * @member PropertyId.SpeechSynthesis_FrameTimeoutInterval + */ + PropertyId[PropertyId["SpeechSynthesis_FrameTimeoutInterval"] = 81] = "SpeechSynthesis_FrameTimeoutInterval"; /** - * Creates and initializes an instance of this class. - * @constructor - * @param {CancellationReason} reason - The cancellation reason. - * @param {string} errorDetails - The error details, if provided. + * The RTF (Real-Time Factor) timeout threshold for speech synthesis. + * @member PropertyId.SpeechSynthesis_RtfTimeoutThreshold */ - function CancellationDetailsBase(reason, errorDetails, errorCode) { - this.privReason = reason; - this.privErrorDetails = errorDetails; - this.privErrorCode = errorCode; - } - Object.defineProperty(CancellationDetailsBase.prototype, "reason", { - /** - * The reason the recognition was canceled. - * @member CancellationDetailsBase.prototype.reason - * @function - * @public - * @returns {CancellationReason} Specifies the reason canceled. - */ - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CancellationDetailsBase.prototype, "errorDetails", { - /** - * In case of an unsuccessful recognition, provides details of the occurred error. - * @member CancellationDetailsBase.prototype.errorDetails - * @function - * @public - * @returns {string} A String that represents the error details. - */ - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CancellationDetailsBase.prototype, "ErrorCode", { - /** - * The error code in case of an unsuccessful recognition. - * Added in version 1.1.0. - * @return An error code that represents the error reason. - */ - get: function () { - return this.privErrorCode; - }, - enumerable: false, - configurable: true - }); - return CancellationDetailsBase; -}()); -exports.CancellationDetailsBase = CancellationDetailsBase; + PropertyId[PropertyId["SpeechSynthesis_RtfTimeoutThreshold"] = 82] = "SpeechSynthesis_RtfTimeoutThreshold"; +})(PropertyId = exports.PropertyId || (exports.PropertyId = {})); /***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { +/* 114 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CancellationDetails = void 0; -var Exports_1 = __webpack_require__(53); -var CancellationDetailsBase_1 = __webpack_require__(112); -var Exports_2 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Recognizer = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); /** - * Contains detailed information about why a result was canceled. - * @class CancellationDetails + * Defines the base class Recognizer which mainly contains common event handlers. + * @class Recognizer */ -var CancellationDetails = /** @class */ (function (_super) { - __extends(CancellationDetails, _super); - function CancellationDetails(reason, errorDetails, errorCode) { - return _super.call(this, reason, errorDetails, errorCode) || this; +class Recognizer { + /** + * Creates and initializes an instance of a Recognizer + * @constructor + * @param {AudioConfig} audioInput - An optional audio input stream associated with the recognizer + * @param {PropertyCollection} properties - A set of properties to set on the recognizer + * @param {IConnectionFactory} connectionFactory - The factory class used to create a custom IConnection for the recognizer + */ + constructor(audioConfig, properties, connectionFactory, tokenCredential) { + this.audioConfig = (audioConfig !== undefined) ? audioConfig : Exports_js_3.AudioConfig.fromDefaultMicrophoneInput(); + this.privDisposed = false; + this.privProperties = properties.clone(); + this.privConnectionFactory = connectionFactory; + this.tokenCredential = tokenCredential; + this.implCommonRecognizerSetup(); } /** - * Creates an instance of CancellationDetails object for the canceled RecognitionResult. - * @member CancellationDetails.fromResult + * Dispose of associated resources. + * @member Recognizer.prototype.close * @function * @public - * @param {RecognitionResult | SpeechSynthesisResult} result - The result that was canceled. - * @returns {CancellationDetails} The cancellation details object being created. */ - CancellationDetails.fromResult = function (result) { - var reason = Exports_2.CancellationReason.Error; - var errorCode = Exports_2.CancellationErrorCode.NoError; - if (result instanceof Exports_2.RecognitionResult && !!result.json) { - var simpleSpeech = Exports_1.SimpleSpeechPhrase.fromJSON(result.json); - reason = Exports_1.EnumTranslation.implTranslateCancelResult(simpleSpeech.RecognitionStatus); + close(cb, errorCb) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb); + } + /** + * @Internal + * Internal data member to support fromRecognizer* pattern methods on other classes. + * Do not use externally, object returned will change without warning or notice. + */ + get internalData() { + return this.privReco; + } + /** + * This method performs cleanup of resources. + * The Boolean parameter disposing indicates whether the method is called + * from Dispose (if disposing is true) or from the finalizer (if disposing is false). + * Derived classes should override this method to dispose resource if needed. + * @member Recognizer.prototype.dispose + * @function + * @public + * @param {boolean} disposing - Flag to request disposal. + */ + async dispose(disposing) { + if (this.privDisposed) { + return; } - if (!!result.properties) { - errorCode = Exports_2.CancellationErrorCode[result.properties.getProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.NoError])]; + this.privDisposed = true; + if (disposing) { + if (this.privReco) { + await this.privReco.audioSource.turnOff(); + await this.privReco.dispose(); + } } - return new CancellationDetails(reason, result.errorDetails || Exports_1.EnumTranslation.implTranslateErrorDetails(errorCode), errorCode); - }; - return CancellationDetails; -}(CancellationDetailsBase_1.CancellationDetailsBase)); -exports.CancellationDetails = CancellationDetails; + } + /** + * This method returns the current state of the telemetry setting. + * @member Recognizer.prototype.telemetryEnabled + * @function + * @public + * @returns true if the telemetry is enabled, false otherwise. + */ + static get telemetryEnabled() { + return Exports_js_1.ServiceRecognizerBase.telemetryDataEnabled; + } + /** + * This method globally enables or disables telemetry. + * @member Recognizer.prototype.enableTelemetry + * @function + * @public + * @param enabled - Global setting for telemetry collection. + * If set to true, telemetry information like microphone errors, + * recognition errors are collected and sent to Microsoft. + * If set to false, no telemetry is sent to Microsoft. + */ + static enableTelemetry(enabled) { + Exports_js_1.ServiceRecognizerBase.telemetryDataEnabled = enabled; + } + // Does the generic recognizer setup that is common across all recognizer types. + implCommonRecognizerSetup() { + let osPlatform = (typeof window !== "undefined") ? "Browser" : "Node"; + let osName = "unknown"; + let osVersion = "unknown"; + if (typeof navigator !== "undefined") { + osPlatform = osPlatform + "/" + navigator.platform; + osName = navigator.userAgent; + osVersion = navigator.appVersion; + } + const recognizerConfig = this.createRecognizerConfig(new Exports_js_1.SpeechServiceConfig(new Exports_js_1.Context(new Exports_js_1.OS(osPlatform, osName, osVersion)))); + this.privReco = this.createServiceRecognizer(Recognizer.getAuth(this.privProperties, this.tokenCredential), this.privConnectionFactory, this.audioConfig, recognizerConfig); + } + async recognizeOnceAsyncImpl(recognitionMode) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + const ret = new Exports_js_2.Deferred(); + await this.implRecognizerStop(); + await this.privReco.recognize(recognitionMode, ret.resolve, ret.reject); + const result = await ret.promise; + await this.implRecognizerStop(); + return result; + } + async startContinuousRecognitionAsyncImpl(recognitionMode) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + await this.implRecognizerStop(); + await this.privReco.recognize(recognitionMode, undefined, undefined); + } + async stopContinuousRecognitionAsyncImpl() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + await this.implRecognizerStop(); + } + async implRecognizerStop() { + if (this.privReco) { + // Get timeout property - undefined/empty means no timeout (existing behavior) + const timeoutProperty = this.privProperties.getProperty(Exports_js_3.PropertyId.Recognizer_StopTimeoutMs, undefined); + // Only apply timeout if explicitly set to a positive value + if (timeoutProperty !== undefined && timeoutProperty !== "") { + const timeoutMs = parseInt(timeoutProperty, 10); + if (timeoutMs > 0) { + // User wants timeout protection + try { + await this.withTimeout(this.privReco.stopRecognizing(), timeoutMs, `Stop operation timed out after ${timeoutMs}ms waiting for service to complete turn`); + } + catch (error) { + // On timeout, use existing disconnect() which cancels immediately + await this.privReco.disconnect(); + throw error; + } + return; + } + } + // No timeout configured - use existing behavior (wait indefinitely) + await this.privReco.stopRecognizing(); + } + return; + } + withTimeout(promise, timeoutMs, errorMessage) { + return Promise.race([ + promise, + new Promise((_, reject) => { + setTimeout(() => { + reject(new Error(errorMessage)); + }, timeoutMs); + }) + ]); + } + static getAuth(properties, tokenCredential) { + const subscriptionKey = properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Key, undefined); + if (subscriptionKey && subscriptionKey !== "") { + return new Exports_js_1.CognitiveSubscriptionKeyAuthentication(subscriptionKey); + } + if (tokenCredential) { + return new Exports_js_1.CognitiveTokenAuthentication(async () => { + try { + const tokenResponse = await tokenCredential.getToken("https://cognitiveservices.azure.com/.default"); + return tokenResponse?.token ?? ""; + } + catch (err) { + throw err; + } + }, async () => { + try { + const tokenResponse = await tokenCredential.getToken("https://cognitiveservices.azure.com/.default"); + return tokenResponse?.token ?? ""; + } + catch (err) { + throw err; + } + }); + } + return new Exports_js_1.CognitiveTokenAuthentication(() => { + const authorizationToken = properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, undefined); + return Promise.resolve(authorizationToken); + }, () => { + const authorizationToken = properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, undefined); + return Promise.resolve(authorizationToken); + }); + } +} +exports.Recognizer = Recognizer; /***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { +/* 115 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CancellationErrorCode = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechRecognizer = void 0; +const Exports_js_1 = __webpack_require__(2); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +const Exports_js_2 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); /** - * Defines error code in case that CancellationReason is Error. - * Added in version 1.1.0. + * Performs speech recognition from microphone, file, or other audio input streams, and gets transcribed text as result. + * @class SpeechRecognizer */ -var CancellationErrorCode; -(function (CancellationErrorCode) { +class SpeechRecognizer extends Exports_js_3.Recognizer { /** - * Indicates that no error occurred during speech recognition. + * SpeechRecognizer constructor. + * @constructor + * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer + * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer */ - CancellationErrorCode[CancellationErrorCode["NoError"] = 0] = "NoError"; + constructor(speechConfig, audioConfig) { + const speechConfigImpl = speechConfig; + Contracts_js_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(speechConfigImpl.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]); + super(audioConfig, speechConfigImpl.properties, new Exports_js_1.SpeechConnectionFactory(), speechConfig.tokenCredential); + this.privDisposedRecognizer = false; + } /** - * Indicates an authentication error. + * SpeechRecognizer constructor. + * @constructor + * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer + * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the recognizer + * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer */ - CancellationErrorCode[CancellationErrorCode["AuthenticationFailure"] = 1] = "AuthenticationFailure"; + static FromConfig(speechConfig, autoDetectSourceLanguageConfig, audioConfig) { + const speechConfigImpl = speechConfig; + autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties); + const recognizer = new SpeechRecognizer(speechConfig, audioConfig); + return recognizer; + } /** - * Indicates that one or more recognition parameters are invalid. + * Gets the endpoint id of a customized speech model that is used for speech recognition. + * @member SpeechRecognizer.prototype.endpointId + * @function + * @public + * @returns {string} the endpoint id of a customized speech model that is used for speech recognition. */ - CancellationErrorCode[CancellationErrorCode["BadRequestParameters"] = 2] = "BadRequestParameters"; + get endpointId() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_EndpointId, "00000000-0000-0000-0000-000000000000"); + } /** - * Indicates that the number of parallel requests exceeded the number of allowed - * concurrent transcriptions for the subscription. + * Gets the authorization token used to communicate with the service. + * @member SpeechRecognizer.prototype.authorizationToken + * @function + * @public + * @returns {string} Authorization token. */ - CancellationErrorCode[CancellationErrorCode["TooManyRequests"] = 3] = "TooManyRequests"; + get authorizationToken() { + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token); + } /** - * Indicates a connection error. + * Gets/Sets the authorization token used to communicate with the service. + * @member SpeechRecognizer.prototype.authorizationToken + * @function + * @public + * @param {string} token - Authorization token. */ - CancellationErrorCode[CancellationErrorCode["ConnectionFailure"] = 4] = "ConnectionFailure"; + set authorizationToken(token) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token"); + this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, token); + } /** - * Indicates a time-out error when waiting for response from service. + * Gets the spoken language of recognition. + * @member SpeechRecognizer.prototype.speechRecognitionLanguage + * @function + * @public + * @returns {string} The spoken language of recognition. */ - CancellationErrorCode[CancellationErrorCode["ServiceTimeout"] = 5] = "ServiceTimeout"; + get speechRecognitionLanguage() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage); + } /** - * Indicates that an error is returned by the service. + * Gets the output format of recognition. + * @member SpeechRecognizer.prototype.outputFormat + * @function + * @public + * @returns {OutputFormat} The output format of recognition. */ - CancellationErrorCode[CancellationErrorCode["ServiceError"] = 6] = "ServiceError"; + get outputFormat() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + if (this.properties.getProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]) === Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]) { + return Exports_js_3.OutputFormat.Simple; + } + else { + return Exports_js_3.OutputFormat.Detailed; + } + } /** - * Indicates an unexpected runtime error. + * The collection of properties and their values defined for this SpeechRecognizer. + * @member SpeechRecognizer.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechRecognizer. */ - CancellationErrorCode[CancellationErrorCode["RuntimeError"] = 7] = "RuntimeError"; + get properties() { + return this.privProperties; + } /** - * Indicates an quota overrun on existing key. + * Starts speech recognition, and stops after the first utterance is recognized. + * The task returns the recognition text as result. + * Note: RecognizeOnceAsync() returns when the first utterance has been recognized, + * so it is suitable only for single shot recognition + * like command or query. For long-running recognition, use StartContinuousRecognitionAsync() instead. + * @member SpeechRecognizer.prototype.recognizeOnceAsync + * @function + * @public + * @param cb - Callback that received the SpeechRecognitionResult. + * @param err - Callback invoked in case of an error. */ - CancellationErrorCode[CancellationErrorCode["Forbidden"] = 8] = "Forbidden"; -})(CancellationErrorCode = exports.CancellationErrorCode || (exports.CancellationErrorCode = {})); - - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. -// -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionEventArgs = void 0; -var Exports_1 = __webpack_require__(61); -/** - * Defines payload for connection events like Connected/Disconnected. - * Added in version 1.2.0 - */ -var ConnectionEventArgs = /** @class */ (function (_super) { - __extends(ConnectionEventArgs, _super); - function ConnectionEventArgs() { - return _super !== null && _super.apply(this, arguments) || this; + recognizeOnceAsync(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(PhraseDetectionContext_js_1.RecognitionMode.Interactive), cb, err); + } + /** + * Starts speech recognition, until stopContinuousRecognitionAsync() is called. + * User must subscribe to events to receive recognition results. + * @member SpeechRecognizer.prototype.startContinuousRecognitionAsync + * @function + * @public + * @param cb - Callback invoked once the recognition has started. + * @param err - Callback invoked in case of an error. + */ + startContinuousRecognitionAsync(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(this.properties.getProperty(Exports_js_1.ForceDictationPropertyName, undefined) === undefined ? PhraseDetectionContext_js_1.RecognitionMode.Conversation : PhraseDetectionContext_js_1.RecognitionMode.Dictation), cb, err); + } + /** + * Stops continuous speech recognition. + * @member SpeechRecognizer.prototype.stopContinuousRecognitionAsync + * @function + * @public + * @param cb - Callback invoked once the recognition has stopped. + * @param err - Callback invoked in case of an error. + */ + stopContinuousRecognitionAsync(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(), cb, err); + } + /** + * Starts speech recognition with keyword spotting, until + * stopKeywordRecognitionAsync() is called. + * User must subscribe to events to receive recognition results. + * Note: Key word spotting functionality is only available on the + * Speech Devices SDK. This functionality is currently not included in the SDK itself. + * @member SpeechRecognizer.prototype.startKeywordRecognitionAsync + * @function + * @public + * @param {KeywordRecognitionModel} model The keyword recognition model that + * specifies the keyword to be recognized. + * @param cb - Callback invoked once the recognition has started. + * @param err - Callback invoked in case of an error. + */ + startKeywordRecognitionAsync(model, cb, err) { + Contracts_js_1.Contracts.throwIfNull(model, "model"); + if (!!err) { + err("Not yet implemented."); + } + } + /** + * Stops continuous speech recognition. + * Note: Key word spotting functionality is only available on the + * Speech Devices SDK. This functionality is currently not included in the SDK itself. + * @member SpeechRecognizer.prototype.stopKeywordRecognitionAsync + * @function + * @public + * @param cb - Callback invoked once the recognition has stopped. + * @param err - Callback invoked in case of an error. + */ + stopKeywordRecognitionAsync(cb) { + if (!!cb) { + cb(); + } + } + /** + * closes all external resources held by an instance of this class. + * @member SpeechRecognizer.prototype.close + * @function + * @public + */ + close(cb, errorCb) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb); + } + /** + * Disposes any resources held by the object. + * @member SpeechRecognizer.prototype.dispose + * @function + * @public + * @param {boolean} disposing - true if disposing the object. + */ + async dispose(disposing) { + if (this.privDisposedRecognizer) { + return; + } + if (disposing) { + this.privDisposedRecognizer = true; + await this.implRecognizerStop(); + } + await super.dispose(disposing); } - return ConnectionEventArgs; -}(Exports_1.SessionEventArgs)); -exports.ConnectionEventArgs = ConnectionEventArgs; + createRecognizerConfig(speechConfig) { + return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties); + } + createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) { + const configImpl = audioConfig; + return new Exports_js_1.SpeechServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this); + } +} +exports.SpeechRecognizer = SpeechRecognizer; /***/ }), /* 116 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -13240,1460 +10179,991 @@ exports.ConnectionEventArgs = ConnectionEventArgs; // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ServiceEventArgs = void 0; -var Exports_1 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechStartEventSensitivity = exports.RecognitionMode = void 0; /** - * Defines payload for any Service message event - * Added in version 1.9.0 + * The Recognition modes */ -var ServiceEventArgs = /** @class */ (function (_super) { - __extends(ServiceEventArgs, _super); - /** - * Creates and initializes an instance of this class. - * @constructor - * @param {string} json - json payload of the USP message. - */ - function ServiceEventArgs(json, name, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privJsonResult = json; - _this.privEventName = name; - return _this; - } - Object.defineProperty(ServiceEventArgs.prototype, "jsonString", { - get: function () { - return this.privJsonResult; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ServiceEventArgs.prototype, "eventName", { - get: function () { - return this.privEventName; - }, - enumerable: false, - configurable: true - }); - return ServiceEventArgs; -}(Exports_1.SessionEventArgs)); -exports.ServiceEventArgs = ServiceEventArgs; +var RecognitionMode; +(function (RecognitionMode) { + RecognitionMode["Interactive"] = "Interactive"; + RecognitionMode["Dictation"] = "Dictation"; + RecognitionMode["Conversation"] = "Conversation"; + RecognitionMode["None"] = "None"; +})(RecognitionMode = exports.RecognitionMode || (exports.RecognitionMode = {})); +/** + * The speech start event sensitivity. + */ +var SpeechStartEventSensitivity; +(function (SpeechStartEventSensitivity) { + SpeechStartEventSensitivity["Low"] = "low"; + SpeechStartEventSensitivity["Medium"] = "medium"; + SpeechStartEventSensitivity["High"] = "high"; +})(SpeechStartEventSensitivity = exports.SpeechStartEventSensitivity || (exports.SpeechStartEventSensitivity = {})); /***/ }), /* 117 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PhraseListGrammar = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranslationRecognizer = void 0; +const Exports_js_1 = __webpack_require__(2); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +const Exports_js_2 = __webpack_require__(4); +const Connection_js_1 = __webpack_require__(118); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); /** - * Allows additions of new phrases to improve speech recognition. - * - * Phrases added to the recognizer are effective at the start of the next recognition, or the next time the SpeechSDK must reconnect - * to the speech service. + * Translation recognizer + * @class TranslationRecognizer */ -var PhraseListGrammar = /** @class */ (function () { - function PhraseListGrammar(recogBase) { - this.privGrammerBuilder = recogBase.dynamicGrammar; - } - /** - * Creates a PhraseListGrammar from a given speech recognizer. Will accept any recognizer that derives from @class Recognizer. - * @param recognizer The recognizer to add phrase lists to. - */ - PhraseListGrammar.fromRecognizer = function (recognizer) { - var recoBase = recognizer.internalData; - return new PhraseListGrammar(recoBase); - }; - /** - * Adds a single phrase to the current recognizer. - * @param phrase Phrase to add. - */ - PhraseListGrammar.prototype.addPhrase = function (phrase) { - this.privGrammerBuilder.addPhrase(phrase); - }; - /** - * Adds multiple phrases to the current recognizer. - * @param phrases Array of phrases to add. - */ - PhraseListGrammar.prototype.addPhrases = function (phrases) { - this.privGrammerBuilder.addPhrase(phrases); - }; +class TranslationRecognizer extends Exports_js_3.Recognizer { /** - * Clears all phrases added to the current recognizer. + * Initializes an instance of the TranslationRecognizer. + * @constructor + * @param {SpeechTranslationConfig} speechConfig - Set of properties to configure this recognizer. + * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer + * @param {IConnectionFactory} connectionFactory - An optional connection factory to use to generate the endpoint URIs, headers to set, etc... */ - PhraseListGrammar.prototype.clear = function () { - this.privGrammerBuilder.clearPhrases(); - }; - return PhraseListGrammar; -}()); -exports.PhraseListGrammar = PhraseListGrammar; - - - -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DialogServiceConfigImpl = exports.DialogServiceConfig = void 0; -var Contracts_1 = __webpack_require__(63); -var Exports_1 = __webpack_require__(61); -/** - * Class that defines base configurations for dialog service connector - * @class DialogServiceConfig - */ -var DialogServiceConfig = /** @class */ (function () { + constructor(speechConfig, audioConfig, connectionFactory) { + const configImpl = speechConfig; + Contracts_js_1.Contracts.throwIfNull(configImpl, "speechConfig"); + super(audioConfig, configImpl.properties, connectionFactory || new Exports_js_1.TranslationConnectionFactory(), speechConfig.tokenCredential); + this.privDisposedTranslationRecognizer = false; + if (this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice]); + } + Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages]); + if (this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, undefined) === undefined) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]); + } + } /** - * Creates an instance of DialogService config. + * TranslationRecognizer constructor. * @constructor + * @param {SpeechTranslationConfig} speechTranslationConfig - an set of initial properties for this recognizer + * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the recognizer + * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer */ - function DialogServiceConfig() { - } - Object.defineProperty(DialogServiceConfig.prototype, "applicationId", { - /** - * Sets the corresponding backend application identifier. - * @member DialogServiceConfig.prototype.Conversation_ApplicationId - * @function - * @public - * @param {string} value - The application identifier to set. - */ - // tslint:disable-next-line: no-empty - set: function (value) { }, - enumerable: false, - configurable: true - }); - var _a; - DialogServiceConfig.DialogTypes = (_a = /** @class */ (function () { - function class_1() { - } - return class_1; - }()), - _a.BotFramework = "bot_framework", - _a.CustomCommands = "custom_commands", - _a); - return DialogServiceConfig; -}()); -exports.DialogServiceConfig = DialogServiceConfig; -/** - * Dialog Service configuration. - * @class DialogServiceConfigImpl - */ -// tslint:disable-next-line:max-classes-per-file -var DialogServiceConfigImpl = /** @class */ (function (_super) { - __extends(DialogServiceConfigImpl, _super); + static FromConfig(speechTranslationConfig, autoDetectSourceLanguageConfig, audioConfig) { + const speechTranslationConfigImpl = speechTranslationConfig; + autoDetectSourceLanguageConfig.properties.mergeTo(speechTranslationConfigImpl.properties); + if (autoDetectSourceLanguageConfig.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, undefined) === Exports_js_1.AutoDetectSourceLanguagesOpenRangeOptionName) { + speechTranslationConfigImpl.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-US"); + } + return new TranslationRecognizer(speechTranslationConfig, audioConfig); + } /** - * Creates an instance of dialogService config. + * Gets the language name that was set when the recognizer was created. + * @member TranslationRecognizer.prototype.speechRecognitionLanguage + * @function + * @public + * @returns {string} Gets the language name that was set when the recognizer was created. */ - function DialogServiceConfigImpl() { - var _this = _super.call(this) || this; - _this.privSpeechConfig = new Exports_1.SpeechConfigImpl(); - return _this; - } - Object.defineProperty(DialogServiceConfigImpl.prototype, "properties", { - /** - * Provides access to custom properties. - * @member DialogServiceConfigImpl.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The properties. - */ - get: function () { - return this.privSpeechConfig.properties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DialogServiceConfigImpl.prototype, "speechRecognitionLanguage", { - /** - * Gets the speech recognition language. - * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage - * @function - * @public - */ - get: function () { - return this.privSpeechConfig.speechRecognitionLanguage; - }, - /** - * Sets the speech recognition language. - * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage - * @function - * @public - * @param {string} value - The language to set. - */ - set: function (value) { - Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value"); - this.privSpeechConfig.speechRecognitionLanguage = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DialogServiceConfigImpl.prototype, "outputFormat", { - get: function () { - return this.privSpeechConfig.outputFormat; - }, - set: function (value) { - this.privSpeechConfig.outputFormat = value; - }, - enumerable: false, - configurable: true - }); + get speechRecognitionLanguage() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage); + } /** - * Sets a named property as value - * @member DialogServiceConfigImpl.prototype.setProperty + * Gets target languages for translation that were set when the recognizer was created. + * The language is specified in BCP-47 format. The translation will provide translated text for each of language. + * @member TranslationRecognizer.prototype.targetLanguages * @function * @public - * @param {PropertyId | string} name - The property to set. - * @param {string} value - The value. + * @returns {string[]} Gets target languages for translation that were set when the recognizer was created. */ - DialogServiceConfigImpl.prototype.setProperty = function (name, value) { - this.privSpeechConfig.setProperty(name, value); - }; + get targetLanguages() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","); + } /** - * Sets a named property as value - * @member DialogServiceConfigImpl.prototype.getProperty + * Gets the name of output voice. + * @member TranslationRecognizer.prototype.voiceName * @function * @public - * @param {PropertyId | string} name - The property to get. - * @param {string} def - The default value to return in case the property is not known. - * @returns {string} The current value, or provided default, of the given property. + * @returns {string} the name of output voice. */ - DialogServiceConfigImpl.prototype.getProperty = function (name, def) { - return this.privSpeechConfig.getProperty(name); - }; + get voiceName() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined); + } /** - * Sets the proxy configuration. - * Only relevant in Node.js environments. - * Added in version 1.4.0. - * @param proxyHostName The host name of the proxy server, without the protocol scheme (http://) - * @param proxyPort The port number of the proxy server. - * @param proxyUserName The user name of the proxy server. - * @param proxyPassword The password of the proxy server. + * The collection of properties and their values defined for this TranslationRecognizer. + * @member TranslationRecognizer.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The collection of properties and their values defined for this TranslationRecognizer. */ - DialogServiceConfigImpl.prototype.setProxy = function (proxyHostName, proxyPort, proxyUserName, proxyPassword) { - this.setProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyHostName, proxyHostName); - this.setProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyPort, "" + proxyPort); - if (proxyUserName) { - this.setProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyUserName, proxyUserName); - } - if (proxyPassword) { - this.setProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyPassword, proxyPassword); - } - }; - DialogServiceConfigImpl.prototype.setServiceProperty = function (name, value, channel) { - this.privSpeechConfig.setServiceProperty(name, value, channel); - }; + get properties() { + return this.privProperties; + } /** - * Dispose of associated resources. - * @member DialogServiceConfigImpl.prototype.close + * Gets the authorization token used to communicate with the service. + * @member TranslationRecognizer.prototype.authorizationToken * @function * @public + * @returns {string} Authorization token. */ - DialogServiceConfigImpl.prototype.close = function () { - return; - }; - return DialogServiceConfigImpl; -}(DialogServiceConfig)); -exports.DialogServiceConfigImpl = DialogServiceConfigImpl; - - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BotFrameworkConfig = void 0; -var Contracts_1 = __webpack_require__(63); -var DialogServiceConfig_1 = __webpack_require__(118); -var Exports_1 = __webpack_require__(61); -/** - * Class that defines configurations for the dialog service connector object for using a Bot Framework backend. - * @class BotFrameworkConfig - */ -var BotFrameworkConfig = /** @class */ (function (_super) { - __extends(BotFrameworkConfig, _super); + get authorizationToken() { + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token); + } /** - * Creates an instance of BotFrameworkConfig. + * Gets/Sets the authorization token used to communicate with the service. + * @member TranslationRecognizer.prototype.authorizationToken + * @function + * @public + * @param {string} value - Authorization token. */ - function BotFrameworkConfig() { - return _super.call(this) || this; + set authorizationToken(value) { + this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, value); } /** - * Creates a bot framework configuration instance with the provided subscription information. - * @member BotFrameworkConfig.fromSubscription + * Starts recognition and translation, and stops after the first utterance is recognized. + * The task returns the translation text as result. + * Note: recognizeOnceAsync returns when the first utterance has been recognized, so it is suitable only + * for single shot recognition like command or query. For long-running recognition, + * use startContinuousRecognitionAsync() instead. + * @member TranslationRecognizer.prototype.recognizeOnceAsync * @function * @public - * @param subscription Subscription key associated with the bot - * @param region The region name (see the region page). - * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the - * resource name. - * @returns {BotFrameworkConfig} A new bot framework configuration instance. + * @param cb - Callback that received the result when the translation has completed. + * @param err - Callback invoked in case of an error. */ - BotFrameworkConfig.fromSubscription = function (subscription, region, botId) { - Contracts_1.Contracts.throwIfNullOrWhitespace(subscription, "subscription"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var botFrameworkConfig = new DialogServiceConfig_1.DialogServiceConfigImpl(); - botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.BotFramework); - botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Key, subscription); - botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Region, region); - if (botId) { - botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, botId); - } - return botFrameworkConfig; - }; + recognizeOnceAsync(cb, err) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(PhraseDetectionContext_js_1.RecognitionMode.Interactive), cb, err); + } /** - * Creates a bot framework configuration instance for the specified authorization token and region. - * Note: The caller must ensure that an authorization token is valid. Before an authorization token expires, the - * caller must refresh it by setting the authorizationToken property on the corresponding - * DialogServiceConnector instance created with this config. The contents of configuration objects are copied - * when connectors are created, so setting authorizationToken on a DialogServiceConnector will not update the - * original configuration's authorization token. Create a new configuration instance or set the - * SpeechServiceAuthorization_Token property to update an existing instance if it will be used to create - * further DialogServiceConnectors. - * @member BotFrameworkConfig.fromAuthorizationToken + * Starts recognition and translation, until stopContinuousRecognitionAsync() is called. + * User must subscribe to events to receive translation results. + * @member TranslationRecognizer.prototype.startContinuousRecognitionAsync * @function * @public - * @param authorizationToken The authorization token associated with the bot - * @param region The region name (see the region page). - * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the - * resource name. - * @returns {BotFrameworkConfig} A new bot framework configuration instance. + * @param cb - Callback that received the translation has started. + * @param err - Callback invoked in case of an error. */ - BotFrameworkConfig.fromAuthorizationToken = function (authorizationToken, region, botId) { - Contracts_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var botFrameworkConfig = new DialogServiceConfig_1.DialogServiceConfigImpl(); - botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.BotFramework); - botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceAuthorization_Token, authorizationToken); - botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Region, region); - if (botId) { - botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, botId); - } - return botFrameworkConfig; - }; + startContinuousRecognitionAsync(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(PhraseDetectionContext_js_1.RecognitionMode.Conversation), cb, err); + } /** - * Creates an instance of a BotFrameworkConfig. - * This method is intended only for users who use a non-default service host. The standard resource path will be - * assumed. For services with a non-standard resource path or no path at all, use fromEndpoint instead. - * Note: Query parameters are not allowed in the host URI and must be set by other APIs. - * Note: To use an authorization token with fromHost, use fromHost(URL) and then set the AuthorizationToken - * property on the created BotFrameworkConfig instance. - * Note: Added in version 1.15.0. - * @member BotFrameworkConfig.fromHost + * Stops continuous recognition and translation. + * @member TranslationRecognizer.prototype.stopContinuousRecognitionAsync * @function * @public - * @param {URL | string} host - If a URL is provided, the fully-qualified host with protocol (e.g. - * wss://your.host.com:1234) will be used. If a string is provided, it will be embedded in - * wss://{host}.convai.speech.azure.us. - * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization - * token must be set. - * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the - * resource name. - * @returns {BotFrameworkConfig} A new bot framework configuration instance. + * @param cb - Callback that received the translation has stopped. + * @param err - Callback invoked in case of an error. */ - BotFrameworkConfig.fromHost = function (host, subscriptionKey, botId) { - Contracts_1.Contracts.throwIfNullOrUndefined(host, "host"); - var resolvedHost = host instanceof URL ? host : new URL("wss://" + host + ".convai.speech.azure.us"); - Contracts_1.Contracts.throwIfNullOrUndefined(resolvedHost, "resolvedHost"); - var botFrameworkConfig = new DialogServiceConfig_1.DialogServiceConfigImpl(); - botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.BotFramework); - botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Host, resolvedHost.toString()); - if (undefined !== subscriptionKey) { - botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Key, subscriptionKey); - } - return botFrameworkConfig; - }; + stopContinuousRecognitionAsync(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(), cb, err); + } /** - * Creates an instance of a BotFrameworkConfig. - * This method is intended only for users who use a non-standard service endpoint or parameters. - * Note: The query parameters specified in the endpoint URL are not changed, even if they are set by any other APIs. - * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the - * fromEndpoint method, and then set authorizationToken="token" on the created BotFrameworkConfig instance to - * use the authorization token. - * Note: Added in version 1.15.0. - * @member BotFrameworkConfig.fromEndpoint + * dynamically remove a language from list of target language + * (can be used while recognition is ongoing) + * @member TranslationRecognizer.prototype.removeTargetLanguage * @function + * @param lang - language to be removed * @public - * @param {URL} endpoint - The service endpoint to connect to. - * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization - * token must be set. - * @returns {BotFrameworkConfig} - A new bot framework configuration instance using the provided endpoint. */ - BotFrameworkConfig.fromEndpoint = function (endpoint, subscriptionKey) { - Contracts_1.Contracts.throwIfNull(endpoint, "endpoint"); - var botFrameworkConfig = new DialogServiceConfig_1.DialogServiceConfigImpl(); - botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.BotFramework); - botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Endpoint, endpoint.toString()); - if (undefined !== subscriptionKey) { - botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Key, subscriptionKey); + removeTargetLanguage(lang) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(lang, "language to be removed"); + if (this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) { + const languages = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","); + const index = languages.indexOf(lang); + if (index > -1) { + languages.splice(index, 1); + this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(",")); + this.updateLanguages(languages); + } } - return botFrameworkConfig; - }; - return BotFrameworkConfig; -}(DialogServiceConfig_1.DialogServiceConfigImpl)); -exports.BotFrameworkConfig = BotFrameworkConfig; - - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CustomCommandsConfig = void 0; -var Contracts_1 = __webpack_require__(63); -var DialogServiceConfig_1 = __webpack_require__(118); -var Exports_1 = __webpack_require__(61); -/** - * Class that defines configurations for the dialog service connector object for using a CustomCommands backend. - * @class CustomCommandsConfig - */ -var CustomCommandsConfig = /** @class */ (function (_super) { - __extends(CustomCommandsConfig, _super); + } /** - * Creates an instance of CustomCommandsConfig. + * dynamically add a language to list of target language + * (can be used while recognition is ongoing) + * @member TranslationRecognizer.prototype.addTargetLanguage + * @function + * @param lang - language to be added + * @public */ - function CustomCommandsConfig() { - return _super.call(this) || this; + addTargetLanguage(lang) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(lang, "language to be added"); + let languages = []; + if (this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) { + languages = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(","); + if (!languages.includes(lang)) { + languages.push(lang); + this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(",")); + } + } + else { + this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, lang); + languages = [lang]; + } + this.updateLanguages(languages); } /** - * Creates an instance of the bot framework config with the specified subscription and region. - * @member CustomCommandsConfig.fromSubscription + * closes all external resources held by an instance of this class. + * @member TranslationRecognizer.prototype.close * @function * @public - * @param applicationId Speech Commands application id. - * @param subscription Subscription key associated with the bot - * @param region The region name (see the region page). - * @returns {CustomCommandsConfig} A new bot framework config. */ - CustomCommandsConfig.fromSubscription = function (applicationId, subscription, region) { - Contracts_1.Contracts.throwIfNullOrWhitespace(applicationId, "applicationId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(subscription, "subscription"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var customCommandsConfig = new DialogServiceConfig_1.DialogServiceConfigImpl(); - customCommandsConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.CustomCommands); - customCommandsConfig.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, applicationId); - customCommandsConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Key, subscription); - customCommandsConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Region, region); - return customCommandsConfig; - }; + close(cb, errorCb) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb); + } /** - * Creates an instance of the bot framework config with the specified Speech Commands application id, authorization token and region. - * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token - * expires, the caller needs to refresh it by calling this setter with a new valid token. - * As configuration values are copied when creating a new recognizer, the new token value will not apply to recognizers that have already been created. - * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer - * to refresh the token. Otherwise, the recognizers will encounter errors during recognition. - * @member CustomCommandsConfig.fromAuthorizationToken + * handles ConnectionEstablishedEvent for conversation translation scenarios. + * @member TranslationRecognizer.prototype.onConnection * @function * @public - * @param applicationId Speech Commands application id. - * @param authorizationToken The authorization token associated with the application. - * @param region The region name (see the region page). - * @returns {CustomCommandsConfig} A new speech commands config. */ - CustomCommandsConfig.fromAuthorizationToken = function (applicationId, authorizationToken, region) { - Contracts_1.Contracts.throwIfNullOrWhitespace(applicationId, "applicationId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken"); - Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region"); - var customCommandsConfig = new DialogServiceConfig_1.DialogServiceConfigImpl(); - customCommandsConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.CustomCommands); - customCommandsConfig.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, applicationId); - customCommandsConfig.setProperty(Exports_1.PropertyId.SpeechServiceAuthorization_Token, authorizationToken); - customCommandsConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Region, region); - return customCommandsConfig; - }; - Object.defineProperty(CustomCommandsConfig.prototype, "applicationId", { - /** - * Gets the corresponding backend application identifier. - * @member CustomCommandsConfig.prototype.Conversation_ApplicationId - * @function - * @public - * @param {string} value - The application identifier to get. - */ - get: function () { - return this.getProperty(Exports_1.PropertyId.Conversation_ApplicationId); - }, - /** - * Sets the corresponding backend application identifier. - * @member CustomCommandsConfig.prototype.Conversation_ApplicationId - * @function - * @public - * @param {string} value - The application identifier to set. - */ - set: function (value) { - Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value"); - this.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, value); - }, - enumerable: false, - configurable: true - }); - return CustomCommandsConfig; -}(DialogServiceConfig_1.DialogServiceConfigImpl)); -exports.CustomCommandsConfig = CustomCommandsConfig; + // eslint-disable-next-line @typescript-eslint/no-empty-function + onConnection() { } + async dispose(disposing) { + if (this.privDisposedTranslationRecognizer) { + return; + } + this.privDisposedTranslationRecognizer = true; + if (disposing) { + await this.implRecognizerStop(); + await super.dispose(disposing); + } + } + createRecognizerConfig(speechConfig) { + return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties); + } + createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) { + const configImpl = audioConfig; + return new Exports_js_1.TranslationServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this); + } + updateLanguages(languages) { + const conn = Connection_js_1.Connection.fromRecognizer(this); + if (!!conn) { + conn.setMessageProperty("speech.context", "translationcontext", { to: languages }); + const voiceName = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined); + let payload; + if (!!voiceName) { + const languageToVoiceMap = {}; + for (const lang of languages) { + languageToVoiceMap[lang] = voiceName; + } + payload = JSON.stringify({ + id: "translation", + name: "updateLanguage", + synthesis: { defaultVoices: languageToVoiceMap }, + to: languages, + }); + } + else { + payload = JSON.stringify({ + id: "translation", + name: "updateLanguage", + to: languages + }); + } + conn.sendMessageAsync("event", payload); + } + } +} +exports.TranslationRecognizer = TranslationRecognizer; /***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { +/* 118 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DialogServiceConnector = void 0; -var DialogConnectorFactory_1 = __webpack_require__(122); -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -var PropertyId_1 = __webpack_require__(99); +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Connection = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const ConnectionMessage_js_1 = __webpack_require__(119); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); /** - * Dialog Service Connector - * @class DialogServiceConnector + * Connection is a proxy class for managing connection to the speech service of the specified Recognizer. + * By default, a Recognizer autonomously manages connection to service when needed. + * The Connection class provides additional methods for users to explicitly open or close a connection and + * to subscribe to connection status changes. + * The use of Connection is optional, and mainly for scenarios where fine tuning of application + * behavior based on connection status is needed. Users can optionally call Open() to manually set up a connection + * in advance before starting recognition on the Recognizer associated with this Connection. + * If the Recognizer needs to connect or disconnect to service, it will + * setup or shutdown the connection independently. In this case the Connection will be notified by change of connection + * status via Connected/Disconnected events. + * Added in version 1.2.1. */ -var DialogServiceConnector = /** @class */ (function (_super) { - __extends(DialogServiceConnector, _super); +class Connection { /** - * Initializes an instance of the DialogServiceConnector. - * @constructor - * @param {DialogServiceConfig} dialogConfig - Set of properties to configure this recognizer. - * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer + * Gets the Connection instance from the specified recognizer. + * @param recognizer The recognizer associated with the connection. + * @return The Connection instance of the recognizer. */ - function DialogServiceConnector(dialogConfig, audioConfig) { - var _this = this; - var dialogServiceConfigImpl = dialogConfig; - Contracts_1.Contracts.throwIfNull(dialogConfig, "dialogConfig"); - _this = _super.call(this, audioConfig, dialogServiceConfigImpl.properties, new DialogConnectorFactory_1.DialogConnectionFactory()) || this; - _this.isTurnComplete = true; - _this.privIsDisposed = false; - _this.privProperties = dialogServiceConfigImpl.properties.clone(); - var agentConfig = _this.buildAgentConfig(); - _this.privReco.agentConfig.set(agentConfig); - return _this; + static fromRecognizer(recognizer) { + const recoBase = recognizer.internalData; + const ret = new Connection(); + ret.privInternalData = recoBase; + ret.setupEvents(); + return ret; } /** - * Starts a connection to the service. - * Users can optionally call connect() to manually set up a connection in advance, before starting interactions. + * Gets the Connection instance from the specified synthesizer. + * @param synthesizer The synthesizer associated with the connection. + * @return The Connection instance of the synthesizer. + */ + static fromSynthesizer(synthesizer) { + const synthBase = synthesizer.internalData; + const ret = new Connection(); + ret.privInternalData = synthBase; + ret.setupEvents(); + return ret; + } + /** + * Starts to set up connection to the service. + * Users can optionally call openConnection() to manually set up a connection in advance before starting recognition on the + * Recognizer associated with this Connection. After starting recognition, calling Open() will have no effect * * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to * be notified when the connection is established. - * @member DialogServiceConnector.prototype.connect - * @function - * @public */ - DialogServiceConnector.prototype.connect = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.privReco.connect(), cb, err); - }; + openConnection(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.privInternalData.connect(), cb, err); + } /** * Closes the connection the service. - * Users can optionally call disconnect() to manually shutdown the connection of the associated DialogServiceConnector. + * Users can optionally call closeConnection() to manually shutdown the connection of the associated Recognizer. * - * If disconnect() is called during a recognition, recognition will fail and cancel with an error. + * If closeConnection() is called during recognition, recognition will fail and cancel with an error. */ - DialogServiceConnector.prototype.disconnect = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.privReco.disconnect(), cb, err); - }; - Object.defineProperty(DialogServiceConnector.prototype, "authorizationToken", { - /** - * Gets the authorization token used to communicate with the service. - * @member DialogServiceConnector.prototype.authorizationToken - * @function - * @public - * @returns {string} Authorization token. - */ - get: function () { - return this.properties.getProperty(PropertyId_1.PropertyId.SpeechServiceAuthorization_Token); - }, - /** - * Sets the authorization token used to communicate with the service. - * @member DialogServiceConnector.prototype.authorizationToken - * @function - * @public - * @param {string} token - Authorization token. - */ - set: function (token) { - Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token"); - this.properties.setProperty(PropertyId_1.PropertyId.SpeechServiceAuthorization_Token, token); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DialogServiceConnector.prototype, "properties", { - /** - * The collection of properties and their values defined for this DialogServiceConnector. - * @member DialogServiceConnector.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The collection of properties and their values defined for this DialogServiceConnector. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DialogServiceConnector.prototype, "speechActivityTemplate", { - /** Gets the template for the activity generated by service from speech. - * Properties from the template will be stamped on the generated activity. - * It can be empty - */ - get: function () { - return this.properties.getProperty(PropertyId_1.PropertyId.Conversation_Speech_Activity_Template); - }, - /** Sets the template for the activity generated by service from speech. - * Properties from the template will be stamped on the generated activity. - * It can be null or empty. - * Note: it has to be a valid Json object. - */ - set: function (speechActivityTemplate) { - this.properties.setProperty(PropertyId_1.PropertyId.Conversation_Speech_Activity_Template, speechActivityTemplate); - }, - enumerable: false, - configurable: true - }); + closeConnection(cb, err) { + if (this.privInternalData instanceof Exports_js_1.SynthesisAdapterBase) { + throw new Error("Disconnecting a synthesizer's connection is currently not supported"); + } + else { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.privInternalData.disconnect(), cb, err); + } + } /** - * Starts recognition and stops after the first utterance is recognized. - * @member DialogServiceConnector.prototype.listenOnceAsync - * @function - * @public - * @param cb - Callback that received the result when the reco has completed. - * @param err - Callback invoked in case of an error. + * Appends a parameter in a message to service. + * Added in version 1.12.1. + * @param path The path of the network message. + * @param propertyName Name of the property + * @param propertyValue Value of the property. This is a json string. */ - DialogServiceConnector.prototype.listenOnceAsync = function (cb, err) { - var _this = this; - if (this.isTurnComplete) { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - var callbackHolder = function () { return __awaiter(_this, void 0, void 0, function () { - var ret, e; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privReco.connect()]; - case 1: - _a.sent(); - return [4 /*yield*/, this.implRecognizerStop()]; - case 2: - _a.sent(); - this.isTurnComplete = false; - ret = new Exports_2.Deferred(); - return [4 /*yield*/, this.privReco.recognize(Exports_1.RecognitionMode.Conversation, ret.resolve, ret.reject)]; - case 3: - _a.sent(); - return [4 /*yield*/, ret.promise]; - case 4: - e = _a.sent(); - return [4 /*yield*/, this.implRecognizerStop()]; - case 5: - _a.sent(); - return [2 /*return*/, e]; - } - }); - }); }; - var retPromise = callbackHolder(); - retPromise.catch(function () { - // Destroy the recognizer. - /* tslint:disable:no-empty */ // We've done all we can here. - _this.dispose(true).catch(function () { }); - }); - Exports_2.marshalPromiseToCallbacks(retPromise.finally(function () { - _this.isTurnComplete = true; - }), cb, err); + setMessageProperty(path, propertyName, propertyValue) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(propertyName, "propertyName"); + if (this.privInternalData instanceof Exports_js_1.ServiceRecognizerBase) { + if (path.toLowerCase() !== "speech.context") { + throw new Error("Only speech.context message property sets are currently supported for recognizer"); + } + else { + const context = this.privInternalData.speechContext.getContext(); + context[propertyName] = propertyValue; + } + } + else if (this.privInternalData instanceof Exports_js_1.SynthesisAdapterBase) { + if (path.toLowerCase() !== "speech.config" && path.toLowerCase() !== "synthesis.context") { + throw new Error("Only speech.config and synthesis.context message paths are currently supported for synthesizer"); + } + else if (path.toLowerCase() === "speech.config") { + if (propertyName.toLowerCase() !== "context") { + throw new Error("Only context property is currently supported for speech.config message path for synthesizer"); + } + else { + this.privInternalData.synthesizerConfig.setContextFromJson(propertyValue); + } + } + else { + this.privInternalData.synthesisContext.setSection(propertyName, propertyValue); + } } - }; - DialogServiceConnector.prototype.sendActivityAsync = function (activity, cb, errCb) { - Exports_2.marshalPromiseToCallbacks(this.privReco.sendMessage(activity), cb, errCb); - }; + } /** - * closes all external resources held by an instance of this class. - * @member DialogServiceConnector.prototype.close - * @function - * @public + * Sends a message to the speech service. + * Added in version 1.13.0. + * @param path The WebSocket path of the message + * @param payload The payload of the message. This is a json string or a ArrayBuffer. + * @param success A callback to indicate success. + * @param error A callback to indicate an error. */ - DialogServiceConnector.prototype.close = function (cb, err) { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, err); - }; - DialogServiceConnector.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privIsDisposed) { - return [2 /*return*/]; - } - if (!disposing) return [3 /*break*/, 3]; - this.privIsDisposed = true; - return [4 /*yield*/, this.implRecognizerStop()]; - case 1: - _a.sent(); - return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; + sendMessageAsync(path, payload, success, error) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.privInternalData.sendNetworkMessage(path, payload), success, error); + } + /** + * Dispose of associated resources. + */ + close() { + /* eslint-disable no-empty */ + } + setupEvents() { + this.privEventListener = this.privInternalData.connectionEvents.attach((connectionEvent) => { + if (connectionEvent.name === "ConnectionEstablishedEvent") { + if (!!this.connected) { + this.connected(new Exports_js_3.ConnectionEventArgs(connectionEvent.connectionId)); } - }); + } + else if (connectionEvent.name === "ConnectionClosedEvent") { + if (!!this.disconnected) { + this.disconnected(new Exports_js_3.ConnectionEventArgs(connectionEvent.connectionId)); + } + } + else if (connectionEvent.name === "ConnectionMessageSentEvent") { + if (!!this.messageSent) { + this.messageSent(new Exports_js_3.ConnectionMessageEventArgs(new ConnectionMessage_js_1.ConnectionMessageImpl(connectionEvent.message))); + } + } + else if (connectionEvent.name === "ConnectionMessageReceivedEvent") { + if (!!this.messageReceived) { + this.messageReceived(new Exports_js_3.ConnectionMessageEventArgs(new ConnectionMessage_js_1.ConnectionMessageImpl(connectionEvent.message))); + } + } }); - }; - DialogServiceConnector.prototype.createRecognizerConfig = function (speechConfig) { - return new Exports_1.RecognizerConfig(speechConfig, this.privProperties); - }; - DialogServiceConnector.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) { - var audioSource = audioConfig; - return new Exports_1.DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this); - }; - DialogServiceConnector.prototype.buildAgentConfig = function () { - var communicationType = this.properties.getProperty("Conversation_Communication_Type", "Default"); - return { - botInfo: { - commType: communicationType, - commandsCulture: undefined, - connectionId: this.properties.getProperty(PropertyId_1.PropertyId.Conversation_Agent_Connection_Id), - conversationId: this.properties.getProperty(PropertyId_1.PropertyId.Conversation_Conversation_Id, undefined), - fromId: this.properties.getProperty(PropertyId_1.PropertyId.Conversation_From_Id, undefined), - ttsAudioFormat: this.properties.getProperty(PropertyId_1.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined) - }, - version: 0.2 - }; - }; - return DialogServiceConnector; -}(Exports_3.Recognizer)); -exports.DialogServiceConnector = DialogServiceConnector; + this.privServiceEventListener = this.privInternalData.serviceEvents.attach((e) => { + if (!!this.receivedServiceMessage) { + this.receivedServiceMessage(new Exports_js_3.ServiceEventArgs(e.jsonString, e.name)); + } + }); + } +} +exports.Connection = Connection; /***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { +/* 119 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DialogConnectionFactory = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(53); -var Exports_3 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -var Exports_4 = __webpack_require__(53); -var HeaderNames_1 = __webpack_require__(55); -var QueryParameterNames_1 = __webpack_require__(124); -var DialogConnectionFactory = /** @class */ (function (_super) { - __extends(DialogConnectionFactory, _super); - function DialogConnectionFactory() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.create = function (config, authInfo, connectionId) { - var applicationId = config.parameters.getProperty(Exports_3.PropertyId.Conversation_ApplicationId, ""); - var dialogType = config.parameters.getProperty(Exports_3.PropertyId.Conversation_DialogType); - var region = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Region); - var language = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-US"); - var requestTurnStatus = config.parameters.getProperty(Exports_3.PropertyId.Conversation_Request_Bot_Status_Messages, "true"); - var queryParams = {}; - queryParams[HeaderNames_1.HeaderNames.ConnectionId] = connectionId; - queryParams[QueryParameterNames_1.QueryParameterNames.Format] = config.parameters.getProperty(Exports_2.OutputFormatPropertyName, Exports_3.OutputFormat[Exports_3.OutputFormat.Simple]).toLowerCase(); - queryParams[QueryParameterNames_1.QueryParameterNames.Language] = language; - queryParams[QueryParameterNames_1.QueryParameterNames.RequestBotStatusMessages] = requestTurnStatus; - if (applicationId) { - queryParams[QueryParameterNames_1.QueryParameterNames.BotId] = applicationId; - if (dialogType === Exports_3.DialogServiceConfig.DialogTypes.CustomCommands) { - queryParams[HeaderNames_1.HeaderNames.CustomCommandsAppId] = applicationId; - } - } - var resourceInfix = dialogType === Exports_3.DialogServiceConfig.DialogTypes.CustomCommands ? "commands/" - : ""; - var version = dialogType === Exports_3.DialogServiceConfig.DialogTypes.CustomCommands ? "v1" - : dialogType === Exports_3.DialogServiceConfig.DialogTypes.BotFramework ? "v3" - : "v0"; - var headers = {}; - if (authInfo.token != null && authInfo.token !== "") { - headers[authInfo.headerName] = authInfo.token; - } - // The URL used for connection is chosen in a priority order of specification: - // 1. If a custom endpoint is provided, that URL is used verbatim. - // 2. If a custom host is provided (e.g. "wss://my.custom.endpoint.com:1123"), a URL is constructed from it. - // 3. If no custom connection details are provided, a URL is constructed from default values. - var endpoint = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Endpoint, ""); - if (!endpoint) { - var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region); - var host = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Host, "wss://" + region + "." + DialogConnectionFactory.Constants.BaseUrl + hostSuffix); - var standardizedHost = host.endsWith("/") ? host : host + "/"; - endpoint = "" + standardizedHost + resourceInfix + DialogConnectionFactory.Constants.ApiKey + "/" + version; - } - _this.setCommonUrlParams(config, queryParams, endpoint); - var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; - return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_4.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); - }; - return _this; - } - var _a; - DialogConnectionFactory.Constants = (_a = /** @class */ (function () { - function class_1() { - } - return class_1; - }()), - _a.ApiKey = "api", - _a.BaseUrl = "convai.speech", - _a); - return DialogConnectionFactory; -}(ConnectionFactoryBase_1.ConnectionFactoryBase)); -exports.DialogConnectionFactory = DialogConnectionFactory; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConnectionMessageImpl = exports.ConnectionMessage = void 0; +// eslint-disable-next-line max-classes-per-file +const HeaderNames_js_1 = __webpack_require__(59); +const Exports_js_1 = __webpack_require__(4); +const PropertyCollection_js_1 = __webpack_require__(112); +const PropertyId_js_1 = __webpack_require__(113); +/** + * ConnectionMessage represents implementation specific messages sent to and received from + * the speech service. These messages are provided for debugging purposes and should not + * be used for production use cases with the Azure Cognitive Services Speech Service. + * Messages sent to and received from the Speech Service are subject to change without + * notice. This includes message contents, headers, payloads, ordering, etc. + * Added in version 1.11.0. + */ +class ConnectionMessage { +} +exports.ConnectionMessage = ConnectionMessage; +class ConnectionMessageImpl { + constructor(message) { + this.privConnectionMessage = message; + this.privProperties = new PropertyCollection_js_1.PropertyCollection(); + if (!!this.privConnectionMessage.headers[HeaderNames_js_1.HeaderNames.ConnectionId]) { + this.privProperties.setProperty(PropertyId_js_1.PropertyId.Speech_SessionId, this.privConnectionMessage.headers[HeaderNames_js_1.HeaderNames.ConnectionId]); + } + Object.keys(this.privConnectionMessage.headers).forEach((header) => { + this.privProperties.setProperty(header, this.privConnectionMessage.headers[header]); + }); + } + /** + * The message path. + */ + get path() { + return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find((key) => key.toLowerCase() === "path".toLowerCase())]; + } + /** + * Checks to see if the ConnectionMessage is a text message. + * See also IsBinaryMessage(). + */ + get isTextMessage() { + return this.privConnectionMessage.messageType === Exports_js_1.MessageType.Text; + } + /** + * Checks to see if the ConnectionMessage is a binary message. + * See also GetBinaryMessage(). + */ + get isBinaryMessage() { + return this.privConnectionMessage.messageType === Exports_js_1.MessageType.Binary; + } + /** + * Gets the text message payload. Typically the text message content-type is + * application/json. To determine other content-types use + * Properties.GetProperty("Content-Type"). + */ + get TextMessage() { + return this.privConnectionMessage.textBody; + } + /** + * Gets the binary message payload. + */ + get binaryMessage() { + return this.privConnectionMessage.binaryBody; + } + /** + * A collection of properties and their values defined for this . + * Message headers can be accessed via this collection (e.g. "Content-Type"). + */ + get properties() { + return this.privProperties; + } + /** + * Returns a string that represents the connection message. + */ + toString() { + return ""; + } +} +exports.ConnectionMessageImpl = ConnectionMessageImpl; /***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { +/* 120 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionFactoryBase = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(61); -var QueryParameterNames_1 = __webpack_require__(124); -var ConnectionFactoryBase = /** @class */ (function () { - function ConnectionFactoryBase() { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Translations = void 0; +const Exports_js_1 = __webpack_require__(85); +/** + * Represents collection of parameters and their values. + * @class Translations + */ +class Translations { + constructor() { + // Use an PropertyCollection internally, just wrapping it to hide the | enum syntax it has. + this.privMap = new Exports_js_1.PropertyCollection(); + } + /** + * Get the languages in the object in a String array. + * @member Translations.prototype.languages + * @function + * @public + * @returns {string[]} languages in translations object. + */ + get languages() { + return this.privMap.keys; + } + /** + * Returns the parameter value in type String. The parameter must have the same type as String. + * Currently only String, int and bool are allowed. + * If the name is not available, the specified defaultValue is returned. + * @member Translations.prototype.get + * @function + * @public + * @param {string} key - The parameter name. + * @param {string} def - The default value which is returned if the parameter is not available in the collection. + * @returns {string} value of the parameter. + */ + get(key, def) { + return this.privMap.getProperty(key, def); } - ConnectionFactoryBase.getHostSuffix = function (region) { - if (!!region) { - if (region.toLowerCase().startsWith("china")) { - return ".azure.cn"; - } - if (region.toLowerCase().startsWith("usgov")) { - return ".azure.us"; - } - } - return ".microsoft.com"; - }; - ConnectionFactoryBase.prototype.setCommonUrlParams = function (config, queryParams, endpoint) { - this.setUrlParameter(Exports_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, QueryParameterNames_1.QueryParameterNames.EnableAudioLogging, config, queryParams, endpoint); - this.setUrlParameter(Exports_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, QueryParameterNames_1.QueryParameterNames.EnableWordLevelTimestamps, config, queryParams, endpoint); - this.setUrlParameter(Exports_2.PropertyId.SpeechServiceResponse_ProfanityOption, QueryParameterNames_1.QueryParameterNames.Profanity, config, queryParams, endpoint); - this.setUrlParameter(Exports_2.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, QueryParameterNames_1.QueryParameterNames.InitialSilenceTimeoutMs, config, queryParams, endpoint); - this.setUrlParameter(Exports_2.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs, QueryParameterNames_1.QueryParameterNames.EndSilenceTimeoutMs, config, queryParams, endpoint); - this.setUrlParameter(Exports_2.PropertyId.SpeechServiceResponse_StablePartialResultThreshold, QueryParameterNames_1.QueryParameterNames.StableIntermediateThreshold, config, queryParams, endpoint); - var serviceProperties = JSON.parse(config.parameters.getProperty(Exports_1.ServicePropertiesPropertyName, "{}")); - Object.keys(serviceProperties).forEach(function (value, num, array) { - queryParams[value] = serviceProperties[value]; - }); - }; - ConnectionFactoryBase.prototype.setUrlParameter = function (propId, parameterName, config, queryParams, endpoint) { - var value = config.parameters.getProperty(propId, undefined); - if (value && (!endpoint || endpoint.search(parameterName) === -1)) { - queryParams[parameterName] = value.toLocaleLowerCase(); - } - }; - return ConnectionFactoryBase; -}()); -exports.ConnectionFactoryBase = ConnectionFactoryBase; + /** + * Sets the String value of the parameter specified by name. + * @member Translations.prototype.set + * @function + * @public + * @param {string} key - The parameter name. + * @param {string} value - The value of the parameter. + */ + set(key, value) { + this.privMap.setProperty(key, value); + } +} +exports.Translations = Translations; /***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { +/* 121 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.QueryParameterNames = void 0; -var QueryParameterNames = /** @class */ (function () { - function QueryParameterNames() { - } - QueryParameterNames.BotId = "botid"; - QueryParameterNames.CustomSpeechDeploymentId = "cid"; - QueryParameterNames.CustomVoiceDeploymentId = "deploymentId"; - QueryParameterNames.EnableAudioLogging = "storeAudio"; - QueryParameterNames.EnableLanguageId = "lidEnabled"; - QueryParameterNames.EnableWordLevelTimestamps = "wordLevelTimestamps"; - QueryParameterNames.EndSilenceTimeoutMs = "endSilenceTimeoutMs"; - QueryParameterNames.Format = "format"; - QueryParameterNames.InitialSilenceTimeoutMs = "initialSilenceTimeoutMs"; - QueryParameterNames.Language = "language"; - QueryParameterNames.Profanity = "profanity"; - QueryParameterNames.RequestBotStatusMessages = "enableBotMessageStatus"; - QueryParameterNames.StableIntermediateThreshold = "stableIntermediateThreshold"; - QueryParameterNames.StableTranslation = "stableTranslation"; - QueryParameterNames.TestHooks = "testhooks"; - return QueryParameterNames; -}()); -exports.QueryParameterNames = QueryParameterNames; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NoMatchReason = void 0; +/** + * Defines the possible reasons a recognition result might not be recognized. + * @class NoMatchReason + */ +var NoMatchReason; +(function (NoMatchReason) { + /** + * Indicates that speech was detected, but not recognized. + * @member NoMatchReason.NotRecognized + */ + NoMatchReason[NoMatchReason["NotRecognized"] = 0] = "NotRecognized"; + /** + * Indicates that the start of the audio stream contained only silence, + * and the service timed out waiting for speech. + * @member NoMatchReason.InitialSilenceTimeout + */ + NoMatchReason[NoMatchReason["InitialSilenceTimeout"] = 1] = "InitialSilenceTimeout"; + /** + * Indicates that the start of the audio stream contained only noise, + * and the service timed out waiting for speech. + * @member NoMatchReason.InitialBabbleTimeout + */ + NoMatchReason[NoMatchReason["InitialBabbleTimeout"] = 2] = "InitialBabbleTimeout"; +})(NoMatchReason = exports.NoMatchReason || (exports.NoMatchReason = {})); /***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { +/* 122 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ActivityReceivedEventArgs = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NoMatchDetails = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(85); /** - * Defines contents of received message/events. - * @class ActivityReceivedEventArgs + * Contains detailed information for NoMatch recognition results. + * @class NoMatchDetails */ -var ActivityReceivedEventArgs = /** @class */ (function () { +class NoMatchDetails { /** * Creates and initializes an instance of this class. * @constructor - * @param {any} activity - The activity.. + * @param {NoMatchReason} reason - The no-match reason. */ - function ActivityReceivedEventArgs(activity, audioStream) { - this.privActivity = activity; - this.privAudioStream = audioStream; + constructor(reason) { + this.privReason = reason; } - Object.defineProperty(ActivityReceivedEventArgs.prototype, "activity", { - /** - * Gets the received activity - * @member ActivityReceivedEventArgs.prototype.activity - * @function - * @public - * @returns {any} the received activity. - */ - get: function () { - return this.privActivity; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ActivityReceivedEventArgs.prototype, "audioStream", { - get: function () { - return this.privAudioStream; - }, - enumerable: false, - configurable: true - }); - return ActivityReceivedEventArgs; -}()); -exports.ActivityReceivedEventArgs = ActivityReceivedEventArgs; + /** + * Creates an instance of NoMatchDetails object for the NoMatch SpeechRecognitionResults. + * @member NoMatchDetails.fromResult + * @function + * @public + * @param {SpeechRecognitionResult | TranslationRecognitionResult} + * result - The recognition result that was not recognized. + * @returns {NoMatchDetails} The no match details object being created. + */ + static fromResult(result) { + const simpleSpeech = Exports_js_1.SimpleSpeechPhrase.fromJSON(result.json, 0); // Offset fixups are already done. + let reason = Exports_js_2.NoMatchReason.NotRecognized; + switch (simpleSpeech.RecognitionStatus) { + case Exports_js_1.RecognitionStatus.BabbleTimeout: + reason = Exports_js_2.NoMatchReason.InitialBabbleTimeout; + break; + case Exports_js_1.RecognitionStatus.InitialSilenceTimeout: + reason = Exports_js_2.NoMatchReason.InitialSilenceTimeout; + break; + default: + reason = Exports_js_2.NoMatchReason.NotRecognized; + break; + } + return new NoMatchDetails(reason); + } + /** + * The reason the recognition was canceled. + * @member NoMatchDetails.prototype.reason + * @function + * @public + * @returns {NoMatchReason} Specifies the reason canceled. + */ + get reason() { + return this.privReason; + } +} +exports.NoMatchDetails = NoMatchDetails; /***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { +/* 123 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TurnStatusReceivedEventArgs = void 0; -var TurnStatusPayload_1 = __webpack_require__(127); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranslationRecognitionCanceledEventArgs = void 0; /** - * Defines contents of received message/events. - * @class TurnStatusReceivedEventArgs + * Define payload of speech recognition canceled result events. + * @class TranslationRecognitionCanceledEventArgs */ -var TurnStatusReceivedEventArgs = /** @class */ (function () { +class TranslationRecognitionCanceledEventArgs { /** * Creates and initializes an instance of this class. * @constructor - * @param {string} turnStatus - The JSON-encoded turn status message. + * @param {string} sessionid - The session id. + * @param {CancellationReason} cancellationReason - The cancellation reason. + * @param {string} errorDetails - Error details, if provided. + * @param {TranslationRecognitionResult} result - The result. */ - function TurnStatusReceivedEventArgs(turnStatus) { - this.privTurnStatus = TurnStatusPayload_1.TurnStatusResponsePayload.fromJSON(turnStatus); - } - Object.defineProperty(TurnStatusReceivedEventArgs.prototype, "interactionId", { - /** - * Gets the interaction identifier associated with this turn status event. - * @member TurnStatusReceivedEventArgs.prototype.interactionId - * @function - * @public - * @returns {any} the received interaction id. - */ - get: function () { - return this.privTurnStatus.interactionId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TurnStatusReceivedEventArgs.prototype, "conversationId", { - /** - * Gets the conversation identifier associated with this turn status event. - * @member TurnStatusReceivedEventArgs.prototype.conversationId - * @function - * @public - * @returns {any} the received conversation id. - */ - get: function () { - return this.privTurnStatus.conversationId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TurnStatusReceivedEventArgs.prototype, "statusCode", { - /** - * Gets the received turn status code. - * @member TurnStatusReceivedEventArgs.prototype.statusCode - * @function - * @public - * @returns {number} the received turn status. - */ - get: function () { - return this.privTurnStatus.statusCode; - }, - enumerable: false, - configurable: true - }); - return TurnStatusReceivedEventArgs; -}()); -exports.TurnStatusReceivedEventArgs = TurnStatusReceivedEventArgs; + constructor(sessionid, cancellationReason, errorDetails, errorCode, result) { + this.privCancelReason = cancellationReason; + this.privErrorDetails = errorDetails; + this.privResult = result; + this.privSessionId = sessionid; + this.privErrorCode = errorCode; + } + /** + * Specifies the recognition result. + * @member TranslationRecognitionCanceledEventArgs.prototype.result + * @function + * @public + * @returns {TranslationRecognitionResult} the recognition result. + */ + get result() { + return this.privResult; + } + /** + * Specifies the session identifier. + * @member TranslationRecognitionCanceledEventArgs.prototype.sessionId + * @function + * @public + * @returns {string} the session identifier. + */ + get sessionId() { + return this.privSessionId; + } + /** + * The reason the recognition was canceled. + * @member TranslationRecognitionCanceledEventArgs.prototype.reason + * @function + * @public + * @returns {CancellationReason} Specifies the reason canceled. + */ + get reason() { + return this.privCancelReason; + } + /** + * The error code in case of an unsuccessful recognition. + * Added in version 1.1.0. + * @return An error code that represents the error reason. + */ + get errorCode() { + return this.privErrorCode; + } + /** + * In case of an unsuccessful recognition, provides details of the occurred error. + * @member TranslationRecognitionCanceledEventArgs.prototype.errorDetails + * @function + * @public + * @returns {string} A String that represents the error details. + */ + get errorDetails() { + return this.privErrorDetails; + } +} +exports.TranslationRecognitionCanceledEventArgs = TranslationRecognitionCanceledEventArgs; /***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { +/* 124 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TurnStatusResponsePayload = void 0; -var TurnStatusResponsePayload = /** @class */ (function () { - function TurnStatusResponsePayload(json) { - this.privMessageStatusResponse = JSON.parse(json); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CancellationDetailsBase = void 0; +/** + * Contains detailed information about why a result was canceled. + * @class CancellationDetailsBase + */ +class CancellationDetailsBase { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {CancellationReason} reason - The cancellation reason. + * @param {string} errorDetails - The error details, if provided. + */ + constructor(reason, errorDetails, errorCode) { + this.privReason = reason; + this.privErrorDetails = errorDetails; + this.privErrorCode = errorCode; } - TurnStatusResponsePayload.fromJSON = function (json) { - return new TurnStatusResponsePayload(json); - }; - Object.defineProperty(TurnStatusResponsePayload.prototype, "interactionId", { - get: function () { - return this.privMessageStatusResponse.interactionId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TurnStatusResponsePayload.prototype, "conversationId", { - get: function () { - return this.privMessageStatusResponse.conversationId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TurnStatusResponsePayload.prototype, "statusCode", { - get: function () { - // Payloads may contain a limited set of textual representations or a numeric status - // code. The textual values are here converted into numeric ones. - switch (this.privMessageStatusResponse.statusCode) { - case "Success": - return 200; - case "Failed": - return 400; - case "TimedOut": - return 429; - default: - return this.privMessageStatusResponse.statusCode; - } - }, - enumerable: false, - configurable: true - }); - return TurnStatusResponsePayload; -}()); -exports.TurnStatusResponsePayload = TurnStatusResponsePayload; + /** + * The reason the recognition was canceled. + * @member CancellationDetailsBase.prototype.reason + * @function + * @public + * @returns {CancellationReason} Specifies the reason canceled. + */ + get reason() { + return this.privReason; + } + /** + * In case of an unsuccessful recognition, provides details of the occurred error. + * @member CancellationDetailsBase.prototype.errorDetails + * @function + * @public + * @returns {string} A String that represents the error details. + */ + get errorDetails() { + return this.privErrorDetails; + } + /** + * The error code in case of an unsuccessful recognition. + * Added in version 1.1.0. + * @return An error code that represents the error reason. + */ + get ErrorCode() { + return this.privErrorCode; + } +} +exports.CancellationDetailsBase = CancellationDetailsBase; /***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { +/* 125 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// Copyright (c) Microsoft Corporation. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ServicePropertyChannel = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CancellationDetails = void 0; +const Exports_js_1 = __webpack_require__(2); +const CancellationDetailsBase_js_1 = __webpack_require__(124); +const Exports_js_2 = __webpack_require__(85); /** - * Defines channels used to pass property settings to service. - * Added in version 1.7.0. + * Contains detailed information about why a result was canceled. + * @class CancellationDetails */ -var ServicePropertyChannel; -(function (ServicePropertyChannel) { +class CancellationDetails extends CancellationDetailsBase_js_1.CancellationDetailsBase { + constructor(reason, errorDetails, errorCode) { + super(reason, errorDetails, errorCode); + } /** - * Uses URI query parameter to pass property settings to service. + * Creates an instance of CancellationDetails object for the canceled RecognitionResult. + * @member CancellationDetails.fromResult + * @function + * @public + * @param {RecognitionResult | SpeechSynthesisResult} result - The result that was canceled. + * @returns {CancellationDetails} The cancellation details object being created. */ - ServicePropertyChannel[ServicePropertyChannel["UriQueryParameter"] = 0] = "UriQueryParameter"; -})(ServicePropertyChannel = exports.ServicePropertyChannel || (exports.ServicePropertyChannel = {})); + static fromResult(result) { + let reason = Exports_js_2.CancellationReason.Error; + let errorCode = Exports_js_2.CancellationErrorCode.NoError; + if (result instanceof Exports_js_2.RecognitionResult && !!result.json) { + const simpleSpeech = Exports_js_1.SimpleSpeechPhrase.fromJSON(result.json, 0); // Offset fixups are already done. + reason = Exports_js_1.EnumTranslation.implTranslateCancelResult(simpleSpeech.RecognitionStatus); + } + if (!!result.properties) { + errorCode = Exports_js_2.CancellationErrorCode[result.properties.getProperty(Exports_js_1.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[Exports_js_2.CancellationErrorCode.NoError])]; + } + return new CancellationDetails(reason, result.errorDetails || Exports_js_1.EnumTranslation.implTranslateErrorDetails(errorCode), errorCode); + } +} +exports.CancellationDetails = CancellationDetails; /***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { +/* 126 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProfanityOption = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CancellationErrorCode = void 0; /** - * Profanity option. - * Added in version 1.7.0. + * Defines error code in case that CancellationReason is Error. + * Added in version 1.1.0. */ -var ProfanityOption; -(function (ProfanityOption) { - ProfanityOption[ProfanityOption["Masked"] = 0] = "Masked"; - ProfanityOption[ProfanityOption["Removed"] = 1] = "Removed"; - ProfanityOption[ProfanityOption["Raw"] = 2] = "Raw"; -})(ProfanityOption = exports.ProfanityOption || (exports.ProfanityOption = {})); +var CancellationErrorCode; +(function (CancellationErrorCode) { + /** + * Indicates that no error occurred during speech recognition. + */ + CancellationErrorCode[CancellationErrorCode["NoError"] = 0] = "NoError"; + /** + * Indicates an authentication error. + */ + CancellationErrorCode[CancellationErrorCode["AuthenticationFailure"] = 1] = "AuthenticationFailure"; + /** + * Indicates that one or more recognition parameters are invalid. + */ + CancellationErrorCode[CancellationErrorCode["BadRequestParameters"] = 2] = "BadRequestParameters"; + /** + * Indicates that the number of parallel requests exceeded the number of allowed + * concurrent transcriptions for the subscription. + */ + CancellationErrorCode[CancellationErrorCode["TooManyRequests"] = 3] = "TooManyRequests"; + /** + * Indicates a connection error. + */ + CancellationErrorCode[CancellationErrorCode["ConnectionFailure"] = 4] = "ConnectionFailure"; + /** + * Indicates a time-out error when waiting for response from service. + */ + CancellationErrorCode[CancellationErrorCode["ServiceTimeout"] = 5] = "ServiceTimeout"; + /** + * Indicates that an error is returned by the service. + */ + CancellationErrorCode[CancellationErrorCode["ServiceError"] = 6] = "ServiceError"; + /** + * Indicates an unexpected runtime error. + */ + CancellationErrorCode[CancellationErrorCode["RuntimeError"] = 7] = "RuntimeError"; + /** + * Indicates an quota overrun on existing key. + */ + CancellationErrorCode[CancellationErrorCode["Forbidden"] = 8] = "Forbidden"; +})(CancellationErrorCode = exports.CancellationErrorCode || (exports.CancellationErrorCode = {})); /***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { +/* 127 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BaseAudioPlayer = void 0; -var Error_1 = __webpack_require__(25); -var Promise_1 = __webpack_require__(40); -var Exports_1 = __webpack_require__(61); -var AudioStreamFormat_1 = __webpack_require__(72); +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConnectionEventArgs = void 0; +const Exports_js_1 = __webpack_require__(85); /** - * Base audio player class - * TODO: Plays only PCM for now. - * @class + * Defines payload for connection events like Connected/Disconnected. + * Added in version 1.2.0 */ -var BaseAudioPlayer = /** @class */ (function () { - /** - * Creates and initializes an instance of this class. - * @constructor - * @param {AudioStreamFormat} audioFormat audio stream format recognized by the player. - */ - function BaseAudioPlayer(audioFormat) { - this.audioContext = null; - this.gainNode = null; - this.autoUpdateBufferTimer = 0; - if (audioFormat === undefined) { - audioFormat = Exports_1.AudioStreamFormat.getDefaultInputFormat(); - } - this.init(audioFormat); - } - /** - * play Audio sample - * @param newAudioData audio data to be played. - */ - BaseAudioPlayer.prototype.playAudioSample = function (newAudioData, cb, err) { - var _this = this; - Promise_1.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () { - var audioData, newSamplesData; - return __generator(this, function (_a) { - this.ensureInitializedContext(); - audioData = this.formatAudioData(newAudioData); - newSamplesData = new Float32Array(this.samples.length + audioData.length); - newSamplesData.set(this.samples, 0); - newSamplesData.set(audioData, this.samples.length); - this.samples = newSamplesData; - return [2 /*return*/]; - }); - }); })(), cb, err); - }; - /** - * stops audio and clears the buffers - */ - BaseAudioPlayer.prototype.stopAudio = function (cb, err) { - if (this.audioContext !== null) { - this.samples = new Float32Array(); - clearInterval(this.autoUpdateBufferTimer); - this.audioContext.close().then(function () { - if (!!cb) { - cb(); - } - }, function (error) { - if (!!err) { - err(error); - } - }); - this.audioContext = null; - } - }; - BaseAudioPlayer.prototype.init = function (audioFormat) { - this.audioFormat = audioFormat; - this.samples = new Float32Array(); - }; - BaseAudioPlayer.prototype.ensureInitializedContext = function () { - var _this = this; - if (this.audioContext === null) { - this.createAudioContext(); - var timerPeriod = 200; - this.autoUpdateBufferTimer = setInterval(function () { - _this.updateAudioBuffer(); - }, timerPeriod); - } - }; - BaseAudioPlayer.prototype.createAudioContext = function () { - // new ((window as any).AudioContext || (window as any).webkitAudioContext)(); - this.audioContext = AudioStreamFormat_1.AudioStreamFormatImpl.getAudioContext(); - // TODO: Various examples shows this gain node, it does not seem to be needed unless we plan - // to control the volume, not likely - this.gainNode = this.audioContext.createGain(); - this.gainNode.gain.value = 1; - this.gainNode.connect(this.audioContext.destination); - this.startTime = this.audioContext.currentTime; - }; - BaseAudioPlayer.prototype.formatAudioData = function (audioData) { - switch (this.audioFormat.bitsPerSample) { - case 8: - return this.formatArrayBuffer(new Int8Array(audioData), 128); - case 16: - return this.formatArrayBuffer(new Int16Array(audioData), 32768); - case 32: - return this.formatArrayBuffer(new Int32Array(audioData), 2147483648); - default: - throw new Error_1.InvalidOperationError("Only WAVE_FORMAT_PCM (8/16/32 bps) format supported at this time"); - } - }; - BaseAudioPlayer.prototype.formatArrayBuffer = function (audioData, maxValue) { - var float32Data = new Float32Array(audioData.length); - for (var i = 0; i < audioData.length; i++) { - float32Data[i] = audioData[i] / maxValue; - } - return float32Data; - }; - BaseAudioPlayer.prototype.updateAudioBuffer = function () { - if (this.samples.length === 0) { - return; - } - var channelCount = this.audioFormat.channels; - var bufferSource = this.audioContext.createBufferSource(); - var frameCount = this.samples.length / channelCount; - var audioBuffer = this.audioContext.createBuffer(channelCount, frameCount, this.audioFormat.samplesPerSec); - // TODO: Should we do the conversion in the pushAudioSample instead? - for (var channel = 0; channel < channelCount; channel++) { - // Fill in individual channel data - var channelOffset = channel; - var audioData = audioBuffer.getChannelData(channel); - for (var i = 0; i < this.samples.length; i++, channelOffset += channelCount) { - audioData[i] = this.samples[channelOffset]; - } - } - if (this.startTime < this.audioContext.currentTime) { - this.startTime = this.audioContext.currentTime; - } - bufferSource.buffer = audioBuffer; - bufferSource.connect(this.gainNode); - bufferSource.start(this.startTime); - // Make sure we play the next sample after the current one. - this.startTime += audioBuffer.duration; - // Clear the samples for the next pushed data. - this.samples = new Float32Array(); - }; - BaseAudioPlayer.prototype.playAudio = function (audioData) { - return __awaiter(this, void 0, void 0, function () { - var source, destination; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.audioContext === null) { - this.createAudioContext(); - } - source = this.audioContext.createBufferSource(); - destination = this.audioContext.destination; - return [4 /*yield*/, this.audioContext.decodeAudioData(audioData, function (newBuffer) { - source.buffer = newBuffer; - source.connect(destination); - source.start(0); - })]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - return BaseAudioPlayer; -}()); -exports.BaseAudioPlayer = BaseAudioPlayer; +class ConnectionEventArgs extends Exports_js_1.SessionEventArgs { +} +exports.ConnectionEventArgs = ConnectionEventArgs; /***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { +/* 128 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; @@ -14701,3857 +11171,2553 @@ exports.BaseAudioPlayer = BaseAudioPlayer; // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionMessageEventArgs = void 0; -var ConnectionMessageEventArgs = /** @class */ (function () { - function ConnectionMessageEventArgs(message) { - this.privConnectionMessage = message; - } - Object.defineProperty(ConnectionMessageEventArgs.prototype, "message", { - /** - * Gets the associated with this . - */ - get: function () { - return this.privConnectionMessage; - }, - enumerable: false, - configurable: true - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServiceEventArgs = void 0; +const Exports_js_1 = __webpack_require__(85); +/** + * Defines payload for any Service message event + * Added in version 1.9.0 + */ +class ServiceEventArgs extends Exports_js_1.SessionEventArgs { /** - * Returns a string that represents the connection message event. + * Creates and initializes an instance of this class. + * @constructor + * @param {string} json - json payload of the USP message. */ - ConnectionMessageEventArgs.prototype.toString = function () { - return "Message: " + this.privConnectionMessage.toString(); - }; - return ConnectionMessageEventArgs; -}()); -exports.ConnectionMessageEventArgs = ConnectionMessageEventArgs; + constructor(json, name, sessionId) { + super(sessionId); + this.privJsonResult = json; + this.privEventName = name; + } + get jsonString() { + return this.privJsonResult; + } + get eventName() { + return this.privEventName; + } +} +exports.ServiceEventArgs = ServiceEventArgs; /***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { +/* 129 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VoiceProfile = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PhraseListGrammar = void 0; +const Contracts_js_1 = __webpack_require__(70); /** - * Defines Voice Profile class for Speaker Recognition - * @class VoiceProfile + * Allows additions of new phrases to improve speech recognition. + * + * Phrases added to the recognizer are effective at the start of the next recognition, or the next time the SpeechSDK must reconnect + * to the speech service. */ -var VoiceProfile = /** @class */ (function () { +class PhraseListGrammar { + constructor(recogBase) { + this.privGrammerBuilder = recogBase.dynamicGrammar; + } /** - * Creates and initializes an instance of this class. - * @constructor - * @param {string} profileId - profileId of this Voice Profile. - * @param {VoiceProfileType} profileType - profileType of this Voice Profile. - */ - function VoiceProfile(profileId, profileType) { - this.privId = profileId; - this.privProfileType = profileType; - } - Object.defineProperty(VoiceProfile.prototype, "profileId", { - /** - * profileId of this Voice Profile instance - * @member VoiceProfile.prototype.profileId - * @function - * @public - * @returns {string} profileId of this Voice Profile instance. - */ - get: function () { - return this.privId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfile.prototype, "profileType", { - /** - * profileType of this Voice Profile instance - * @member VoiceProfile.prototype.profileType - * @function - * @public - * @returns {VoiceProfileType} profile type of this Voice Profile instance. - */ - get: function () { - return this.privProfileType; - }, - enumerable: false, - configurable: true - }); - return VoiceProfile; -}()); -exports.VoiceProfile = VoiceProfile; + * Creates a PhraseListGrammar from a given speech recognizer. Will accept any recognizer that derives from @class Recognizer. + * @param recognizer The recognizer to add phrase lists to. + */ + static fromRecognizer(recognizer) { + const recoBase = recognizer.internalData; + return new PhraseListGrammar(recoBase); + } + /** + * Adds a single phrase to the current recognizer. + * @param phrase Phrase to add. + */ + addPhrase(phrase) { + this.privGrammerBuilder.addPhrase(phrase); + } + /** + * Adds multiple phrases to the current recognizer. + * @param phrases Array of phrases to add. + */ + addPhrases(phrases) { + this.privGrammerBuilder.addPhrase(phrases); + } + /** + * Clears all phrases added to the current recognizer. + */ + clear() { + this.privGrammerBuilder.clearPhrases(); + } + /** + * Sets the phrase list grammar biasing weight. + * The allowed range is [0.0, 2.0]. + * The default weight is 1.0. Value zero disables the phrase list. + * @param weight Phrase list grammar biasing weight. + */ + setWeight(weight) { + Contracts_js_1.Contracts.throwIfNumberOutOfRange(weight, "weight", 0.0, 2.0); + this.privGrammerBuilder.setWeight(weight); + } +} +exports.PhraseListGrammar = PhraseListGrammar; /***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { +/* 130 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VoiceProfileEnrollmentCancellationDetails = exports.VoiceProfileEnrollmentResult = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DialogServiceConfigImpl = exports.DialogServiceConfig = void 0; +/* eslint-disable max-classes-per-file */ +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_1 = __webpack_require__(85); /** - * Output format - * @class VoiceProfileEnrollmentResult + * Class that defines base configurations for dialog service connector + * @class DialogServiceConfig */ -var VoiceProfileEnrollmentResult = /** @class */ (function () { - function VoiceProfileEnrollmentResult(reason, json, statusText) { - this.privReason = reason; - this.privProperties = new Exports_2.PropertyCollection(); - if (this.privReason !== Exports_2.ResultReason.Canceled) { - if (!!json) { - this.privDetails = JSON.parse(json); - if (this.privDetails.enrollmentStatus.toLowerCase() === "enrolling") { - this.privReason = Exports_2.ResultReason.EnrollingVoiceProfile; - } - } - } - else { - this.privErrorDetails = statusText; - this.privProperties.setProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.ServiceError]); - } - } - VoiceProfileEnrollmentResult.FromIdentificationProfileList = function (json) { - var results = []; - for (var _i = 0, _a = json.value; _i < _a.length; _i++) { - var item = _a[_i]; - var reason = item.enrollmentStatus.toLowerCase() === "enrolling" ? - Exports_2.ResultReason.EnrollingVoiceProfile : item.enrollmentStatus.toLowerCase() === "enrolled" ? - Exports_2.ResultReason.EnrolledVoiceProfile : Exports_2.ResultReason.Canceled; - var result = new VoiceProfileEnrollmentResult(reason, null, null); - result.privDetails = this.getIdentificationDetails(item); - results.push(result); - } - return results; - }; - VoiceProfileEnrollmentResult.FromVerificationProfileList = function (json) { - var results = []; - for (var _i = 0, _a = json.value; _i < _a.length; _i++) { - var item = _a[_i]; - var reason = item.enrollmentStatus.toLowerCase() === "enrolling" ? - Exports_2.ResultReason.EnrollingVoiceProfile : item.enrollmentStatus.toLowerCase() === "enrolled" ? - Exports_2.ResultReason.EnrolledVoiceProfile : Exports_2.ResultReason.Canceled; - var result = new VoiceProfileEnrollmentResult(reason, null, null); - result.privDetails = this.getVerificationDetails(item); - results.push(result); - } - return results; - }; - Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "reason", { - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "enrollmentsCount", { - get: function () { - return this.privDetails.enrollmentsCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "enrollmentsLengthInSec", { - get: function () { - return this.privDetails.enrollmentsLengthInSec; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "properties", { - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "enrollmentResultDetails", { - get: function () { - return this.privDetails; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "errorDetails", { - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - VoiceProfileEnrollmentResult.getIdentificationDetails = function (json) { - return { - audioLengthInSec: json.audioLengthInSec ? parseFloat(json.audioLengthInSec) : 0, - audioSpeechLengthInSec: json.audioSpeechLengthInSec ? parseFloat(json.audioSpeechLengthInSec) : 0, - enrollmentStatus: json.enrollmentStatus, - enrollmentsCount: json.enrollmentsCount || 0, - enrollmentsLengthInSec: json.enrollmentsLengthInSec ? parseFloat(json.enrollmentsLengthInSec) : 0, - enrollmentsSpeechLengthInSec: json.enrollmentsSpeechLengthInSec ? parseFloat(json.enrollmentsSpeechLengthInSec) : 0, - profileId: json.profileId || json.identificationProfileId, - remainingEnrollmentsSpeechLengthInSec: json.remainingEnrollmentsSpeechLengthInSec ? parseFloat(json.remainingEnrollmentsSpeechLengthInSec) : 0 - }; - }; - VoiceProfileEnrollmentResult.getVerificationDetails = function (json) { +class DialogServiceConfig { + /** + * Creates an instance of DialogService config. + * @constructor + */ + constructor() { + return; + } + /** + * Sets the corresponding backend application identifier. + * @member DialogServiceConfig.prototype.Conversation_ApplicationId + * @function + * @public + * @param {string} value - The application identifier to set. + */ + // eslint-disable-next-line @typescript-eslint/no-empty-function + set applicationId(value) { } + static get DialogTypes() { return { - audioLengthInSec: json.audioLengthInSec ? parseFloat(json.audioLengthInSec) : 0, - audioSpeechLengthInSec: json.audioSpeechLengthInSec ? parseFloat(json.audioSpeechLengthInSec) : 0, - enrollmentStatus: json.enrollmentStatus, - enrollmentsCount: json.enrollmentsCount, - enrollmentsLengthInSec: json.enrollmentsLengthInSec ? parseFloat(json.enrollmentsLengthInSec) : 0, - enrollmentsSpeechLengthInSec: json.enrollmentsSpeechLengthInSec ? parseFloat(json.enrollmentsSpeechLengthInSec) : 0, - profileId: json.profileId || json.verificationProfileId, - remainingEnrollmentsCount: json.remainingEnrollments || json.remainingEnrollmentsCount, - remainingEnrollmentsSpeechLengthInSec: json.remainingEnrollmentsSpeechLengthInSec ? parseFloat(json.remainingEnrollmentsSpeechLengthInSec) : 0 + BotFramework: "bot_framework", + CustomCommands: "custom_commands" }; - }; - return VoiceProfileEnrollmentResult; -}()); -exports.VoiceProfileEnrollmentResult = VoiceProfileEnrollmentResult; + } +} +exports.DialogServiceConfig = DialogServiceConfig; /** - * @class VoiceProfileEnrollmentCancellationDetails + * Dialog Service configuration. + * @class DialogServiceConfigImpl */ -// tslint:disable-next-line:max-classes-per-file -var VoiceProfileEnrollmentCancellationDetails = /** @class */ (function (_super) { - __extends(VoiceProfileEnrollmentCancellationDetails, _super); - function VoiceProfileEnrollmentCancellationDetails(reason, errorDetails, errorCode) { - return _super.call(this, reason, errorDetails, errorCode) || this; +class DialogServiceConfigImpl extends DialogServiceConfig { + /** + * Creates an instance of dialogService config. + */ + constructor() { + super(); + this.privSpeechConfig = new Exports_js_1.SpeechConfigImpl(); + } + /** + * Provides access to custom properties. + * @member DialogServiceConfigImpl.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The properties. + */ + get properties() { + return this.privSpeechConfig.properties; + } + /** + * Gets the speech recognition language. + * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage + * @function + * @public + */ + get speechRecognitionLanguage() { + return this.privSpeechConfig.speechRecognitionLanguage; + } + /** + * Sets the speech recognition language. + * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage + * @function + * @public + * @param {string} value - The language to set. + */ + set speechRecognitionLanguage(value) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value"); + this.privSpeechConfig.speechRecognitionLanguage = value; + } + get outputFormat() { + return this.privSpeechConfig.outputFormat; + } + set outputFormat(value) { + this.privSpeechConfig.outputFormat = value; + } + /** + * Sets a named property as value + * @member DialogServiceConfigImpl.prototype.setProperty + * @function + * @public + * @param {PropertyId | string} name - The property to set. + * @param {string} value - The value. + */ + setProperty(name, value) { + this.privSpeechConfig.setProperty(name, value); + } + /** + * Sets a named property as value + * @member DialogServiceConfigImpl.prototype.getProperty + * @function + * @public + * @param {PropertyId | string} name - The property to get. + * @param {string} def - The default value to return in case the property is not known. + * @returns {string} The current value, or provided default, of the given property. + */ + getProperty(name, def) { + void def; + return this.privSpeechConfig.getProperty(name); + } + /** + * Sets the proxy configuration. + * Only relevant in Node.js environments. + * Added in version 1.4.0. + * @param proxyHostName The host name of the proxy server, without the protocol scheme (http://) + * @param proxyPort The port number of the proxy server. + * @param proxyUserName The user name of the proxy server. + * @param proxyPassword The password of the proxy server. + */ + setProxy(proxyHostName, proxyPort, proxyUserName, proxyPassword) { + this.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyHostName, proxyHostName); + this.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyPort, `${proxyPort}`); + if (proxyUserName) { + this.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyUserName, proxyUserName); + } + if (proxyPassword) { + this.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyPassword, proxyPassword); + } + } + setServiceProperty(name, value, channel) { + void channel; + this.privSpeechConfig.setServiceProperty(name, value); } /** - * Creates an instance of VoiceProfileEnrollmentCancellationDetails object for the canceled VoiceProfileEnrollmentResult. - * @member VoiceProfileEnrollmentCancellationDetails.fromResult + * Dispose of associated resources. + * @member DialogServiceConfigImpl.prototype.close * @function * @public - * @param {VoiceProfileEnrollmentResult} result - The result that was canceled. - * @returns {VoiceProfileEnrollmentCancellationDetails} The cancellation details object being created. */ - VoiceProfileEnrollmentCancellationDetails.fromResult = function (result) { - var reason = Exports_2.CancellationReason.Error; - var errorCode = Exports_2.CancellationErrorCode.NoError; - if (!!result.properties) { - errorCode = Exports_2.CancellationErrorCode[result.properties.getProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.NoError])]; - } - return new VoiceProfileEnrollmentCancellationDetails(reason, result.errorDetails, errorCode); - }; - return VoiceProfileEnrollmentCancellationDetails; -}(Exports_2.CancellationDetailsBase)); -exports.VoiceProfileEnrollmentCancellationDetails = VoiceProfileEnrollmentCancellationDetails; + close() { + return; + } +} +exports.DialogServiceConfigImpl = DialogServiceConfigImpl; /***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { +/* 131 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VoiceProfileCancellationDetails = exports.VoiceProfileResult = void 0; -var Exports_1 = __webpack_require__(53); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); -/** - * Output format - * @class VoiceProfileResult - */ -var VoiceProfileResult = /** @class */ (function () { - function VoiceProfileResult(reason, statusText) { - this.privReason = reason; - this.privProperties = new Exports_2.PropertyCollection(); - if (reason === Exports_2.ResultReason.Canceled) { - Contracts_1.Contracts.throwIfNullOrUndefined(statusText, "statusText"); - this.privErrorDetails = statusText; - this.privProperties.setProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.ServiceError]); - } - } - Object.defineProperty(VoiceProfileResult.prototype, "reason", { - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfileResult.prototype, "properties", { - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfileResult.prototype, "errorDetails", { - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - return VoiceProfileResult; -}()); -exports.VoiceProfileResult = VoiceProfileResult; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BotFrameworkConfig = void 0; +const Contracts_js_1 = __webpack_require__(70); +const DialogServiceConfig_js_1 = __webpack_require__(130); +const Exports_js_1 = __webpack_require__(85); /** - * @class VoiceProfileCancellationDetails + * Class that defines configurations for the dialog service connector object for using a Bot Framework backend. + * @class BotFrameworkConfig */ -// tslint:disable-next-line:max-classes-per-file -var VoiceProfileCancellationDetails = /** @class */ (function (_super) { - __extends(VoiceProfileCancellationDetails, _super); - function VoiceProfileCancellationDetails(reason, errorDetails, errorCode) { - return _super.call(this, reason, errorDetails, errorCode) || this; +class BotFrameworkConfig extends DialogServiceConfig_js_1.DialogServiceConfigImpl { + /** + * Creates an instance of BotFrameworkConfig. + */ + constructor() { + super(); } /** - * Creates an instance of VoiceProfileCancellationDetails object for the canceled VoiceProfileResult. - * @member VoiceProfileCancellationDetails.fromResult + * Creates a bot framework configuration instance with the provided subscription information. + * @member BotFrameworkConfig.fromSubscription * @function * @public - * @param {VoiceProfileResult} result - The result that was canceled. - * @returns {VoiceProfileCancellationDetails} The cancellation details object being created. + * @param subscription Subscription key associated with the bot + * @param region The region name (see the region page). + * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the + * resource name. + * @returns {BotFrameworkConfig} A new bot framework configuration instance. */ - VoiceProfileCancellationDetails.fromResult = function (result) { - var reason = Exports_2.CancellationReason.Error; - var errorCode = Exports_2.CancellationErrorCode.NoError; - if (!!result.properties) { - errorCode = Exports_2.CancellationErrorCode[result.properties.getProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.NoError])]; + static fromSubscription(subscription, region, botId) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscription, "subscription"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region"); + const botFrameworkConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl(); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.BotFramework); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Key, subscription); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Region, region); + if (botId) { + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_ApplicationId, botId); + } + return botFrameworkConfig; + } + /** + * Creates a bot framework configuration instance for the specified authorization token and region. + * Note: The caller must ensure that an authorization token is valid. Before an authorization token expires, the + * caller must refresh it by setting the authorizationToken property on the corresponding + * DialogServiceConnector instance created with this config. The contents of configuration objects are copied + * when connectors are created, so setting authorizationToken on a DialogServiceConnector will not update the + * original configuration's authorization token. Create a new configuration instance or set the + * SpeechServiceAuthorization_Token property to update an existing instance if it will be used to create + * further DialogServiceConnectors. + * @member BotFrameworkConfig.fromAuthorizationToken + * @function + * @public + * @param authorizationToken The authorization token associated with the bot + * @param region The region name (see the region page). + * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the + * resource name. + * @returns {BotFrameworkConfig} A new bot framework configuration instance. + */ + static fromAuthorizationToken(authorizationToken, region, botId) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region"); + const botFrameworkConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl(); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.BotFramework); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceAuthorization_Token, authorizationToken); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Region, region); + if (botId) { + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_ApplicationId, botId); + } + return botFrameworkConfig; + } + /** + * Creates an instance of a BotFrameworkConfig. + * This method is intended only for users who use a non-default service host. The standard resource path will be + * assumed. For services with a non-standard resource path or no path at all, use fromEndpoint instead. + * Note: Query parameters are not allowed in the host URI and must be set by other APIs. + * Note: To use an authorization token with fromHost, use fromHost(URL) and then set the AuthorizationToken + * property on the created BotFrameworkConfig instance. + * Note: Added in version 1.15.0. + * @member BotFrameworkConfig.fromHost + * @function + * @public + * @param {URL | string} host - If a URL is provided, the fully-qualified host with protocol (e.g. + * wss://your.host.com:1234) will be used. If a string is provided, it will be embedded in + * wss://{host}.convai.speech.azure.us. + * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization + * token must be set. + * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the + * resource name. + * @returns {BotFrameworkConfig} A new bot framework configuration instance. + */ + static fromHost(host, subscriptionKey, botId) { + void botId; + Contracts_js_1.Contracts.throwIfNullOrUndefined(host, "host"); + const resolvedHost = host instanceof URL ? host : new URL(`wss://${host}.convai.speech.azure.us`); + Contracts_js_1.Contracts.throwIfNullOrUndefined(resolvedHost, "resolvedHost"); + const botFrameworkConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl(); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.BotFramework); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Host, resolvedHost.toString()); + if (undefined !== subscriptionKey) { + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Key, subscriptionKey); + } + return botFrameworkConfig; + } + /** + * Creates an instance of a BotFrameworkConfig. + * This method is intended only for users who use a non-standard service endpoint or parameters. + * Note: The query parameters specified in the endpoint URL are not changed, even if they are set by any other APIs. + * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the + * fromEndpoint method, and then set authorizationToken="token" on the created BotFrameworkConfig instance to + * use the authorization token. + * Note: Added in version 1.15.0. + * @member BotFrameworkConfig.fromEndpoint + * @function + * @public + * @param {URL} endpoint - The service endpoint to connect to. + * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization + * token must be set. + * @returns {BotFrameworkConfig} - A new bot framework configuration instance using the provided endpoint. + */ + static fromEndpoint(endpoint, subscriptionKey) { + Contracts_js_1.Contracts.throwIfNull(endpoint, "endpoint"); + const botFrameworkConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl(); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.BotFramework); + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Endpoint, endpoint.toString()); + if (undefined !== subscriptionKey) { + botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Key, subscriptionKey); } - return new VoiceProfileCancellationDetails(reason, result.errorDetails, errorCode); - }; - return VoiceProfileCancellationDetails; -}(Exports_2.CancellationDetailsBase)); -exports.VoiceProfileCancellationDetails = VoiceProfileCancellationDetails; + return botFrameworkConfig; + } +} +exports.BotFrameworkConfig = BotFrameworkConfig; /***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { +/* 132 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VoiceProfilePhraseResult = void 0; -var Contracts_1 = __webpack_require__(63); -var Exports_1 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CustomCommandsConfig = void 0; +const Contracts_js_1 = __webpack_require__(70); +const DialogServiceConfig_js_1 = __webpack_require__(130); +const Exports_js_1 = __webpack_require__(85); /** - * Output format - * @class VoiceProfilePhraseResult + * Class that defines configurations for the dialog service connector object for using a CustomCommands backend. + * @class CustomCommandsConfig */ -var VoiceProfilePhraseResult = /** @class */ (function (_super) { - __extends(VoiceProfilePhraseResult, _super); - function VoiceProfilePhraseResult(reason, statusText, json) { - var _this = _super.call(this, reason, statusText) || this; - _this.privPhrases = []; - Contracts_1.Contracts.throwIfNullOrUndefined(json, "phrase result JSON"); - if (!!json.value && !!json.value[0]) { - for (var _i = 0, _a = json.value; _i < _a.length; _i++) { - var item = _a[_i]; - _this.privPhrases.push(item.passPhrase || item.activationPhrase); - } - } - return _this; - } - Object.defineProperty(VoiceProfilePhraseResult.prototype, "phrases", { - get: function () { - return this.privPhrases; - }, - enumerable: false, - configurable: true - }); - return VoiceProfilePhraseResult; -}(Exports_1.VoiceProfileResult)); -exports.VoiceProfilePhraseResult = VoiceProfilePhraseResult; +class CustomCommandsConfig extends DialogServiceConfig_js_1.DialogServiceConfigImpl { + /** + * Creates an instance of CustomCommandsConfig. + */ + constructor() { + super(); + } + /** + * Creates an instance of the bot framework config with the specified subscription and region. + * @member CustomCommandsConfig.fromSubscription + * @function + * @public + * @param applicationId Speech Commands application id. + * @param subscription Subscription key associated with the bot + * @param region The region name (see the region page). + * @returns {CustomCommandsConfig} A new bot framework config. + */ + static fromSubscription(applicationId, subscription, region) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(applicationId, "applicationId"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscription, "subscription"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region"); + const customCommandsConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl(); + customCommandsConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.CustomCommands); + customCommandsConfig.setProperty(Exports_js_1.PropertyId.Conversation_ApplicationId, applicationId); + customCommandsConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Key, subscription); + customCommandsConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Region, region); + return customCommandsConfig; + } + /** + * Creates an instance of the bot framework config with the specified Speech Commands application id, authorization token and region. + * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token + * expires, the caller needs to refresh it by calling this setter with a new valid token. + * As configuration values are copied when creating a new recognizer, the new token value will not apply to recognizers that have already been created. + * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer + * to refresh the token. Otherwise, the recognizers will encounter errors during recognition. + * @member CustomCommandsConfig.fromAuthorizationToken + * @function + * @public + * @param applicationId Speech Commands application id. + * @param authorizationToken The authorization token associated with the application. + * @param region The region name (see the region page). + * @returns {CustomCommandsConfig} A new speech commands config. + */ + static fromAuthorizationToken(applicationId, authorizationToken, region) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(applicationId, "applicationId"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region"); + const customCommandsConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl(); + customCommandsConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.CustomCommands); + customCommandsConfig.setProperty(Exports_js_1.PropertyId.Conversation_ApplicationId, applicationId); + customCommandsConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceAuthorization_Token, authorizationToken); + customCommandsConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Region, region); + return customCommandsConfig; + } + /** + * Sets the corresponding backend application identifier. + * @member CustomCommandsConfig.prototype.Conversation_ApplicationId + * @function + * @public + * @param {string} value - The application identifier to set. + */ + set applicationId(value) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value"); + this.setProperty(Exports_js_1.PropertyId.Conversation_ApplicationId, value); + } + /** + * Gets the corresponding backend application identifier. + * @member CustomCommandsConfig.prototype.Conversation_ApplicationId + * @function + * @public + * @param {string} value - The application identifier to get. + */ + get applicationId() { + return this.getProperty(Exports_js_1.PropertyId.Conversation_ApplicationId); + } +} +exports.CustomCommandsConfig = CustomCommandsConfig; /***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { +/* 133 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VoiceProfileClient = void 0; -var Exports_1 = __webpack_require__(53); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DialogServiceConnector = void 0; +const DialogConnectorFactory_js_1 = __webpack_require__(134); +const Exports_js_1 = __webpack_require__(2); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +const Exports_js_2 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); +const PropertyId_js_1 = __webpack_require__(113); /** - * Defines VoiceProfileClient class for Speaker Recognition - * Handles operations from user for Voice Profile operations (e.g. createProfile, deleteProfile) - * @class VoiceProfileClient + * Dialog Service Connector + * @class DialogServiceConnector */ -var VoiceProfileClient = /** @class */ (function () { +class DialogServiceConnector extends Exports_js_3.Recognizer { /** - * VoiceProfileClient constructor. + * Initializes an instance of the DialogServiceConnector. * @constructor - * @param {SpeechConfig} speechConfig - An set of initial properties for this synthesizer (authentication key, region, &c) + * @param {DialogServiceConfig} dialogConfig - Set of properties to configure this recognizer. + * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer */ - function VoiceProfileClient(speechConfig) { - var speechConfigImpl = speechConfig; - Contracts_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig"); - this.privProperties = speechConfigImpl.properties.clone(); - this.implClientSetup(); - } - Object.defineProperty(VoiceProfileClient.prototype, "authorizationToken", { - /** - * Gets the authorization token used to communicate with the service. - * @member VoiceProfileClient.prototype.authorizationToken - * @function - * @public - * @returns {string} Authorization token. - */ - get: function () { - return this.properties.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token); - }, - /** - * Gets/Sets the authorization token used to communicate with the service. - * @member VoiceProfileClient.prototype.authorizationToken - * @function - * @public - * @param {string} token - Authorization token. - */ - set: function (token) { - Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token"); - this.properties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, token); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceProfileClient.prototype, "properties", { - /** - * The collection of properties and their values defined for this VoiceProfileClient. - * @member VoiceProfileClient.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The collection of properties and their values defined for this VoiceProfileClient. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - /** - * Create a speaker recognition voice profile - * @member VoiceProfileClient.prototype.createProfileAsync - * @function - * @public - * @async - * @param {VoiceProfileType} profileType Type of Voice Profile to be created - * specifies the keyword to be recognized. - * @param {string} lang Language string (locale) for Voice Profile - * @return {Promise} - Promise of a VoiceProfile. - */ - VoiceProfileClient.prototype.createProfileAsync = function (profileType, lang) { - return __awaiter(this, void 0, void 0, function () { - var result, response, profile; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privAdapter.createProfile(profileType, lang)]; - case 1: - result = _a.sent(); - if (!result.ok) { - throw new Error("createProfileAsync failed with code: " + result.status + ", message: " + result.statusText); - } - response = result.json; - profile = new Exports_2.VoiceProfile(response.profileId, profileType); - return [2 /*return*/, profile]; - } - }); - }); - }; + constructor(dialogConfig, audioConfig) { + const dialogServiceConfigImpl = dialogConfig; + Contracts_js_1.Contracts.throwIfNull(dialogConfig, "dialogConfig"); + super(audioConfig, dialogServiceConfigImpl.properties, new DialogConnectorFactory_js_1.DialogConnectionFactory()); + this.isTurnComplete = true; + this.privIsDisposed = false; + this.privProperties = dialogServiceConfigImpl.properties.clone(); + const agentConfig = this.buildAgentConfig(); + this.privReco.agentConfig.set(agentConfig); + } /** - * Get current information of a voice profile - * @member VoiceProfileClient.prototype.retrieveEnrollmentResultAsync + * Starts a connection to the service. + * Users can optionally call connect() to manually set up a connection in advance, before starting interactions. + * + * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to + * be notified when the connection is established. + * @member DialogServiceConnector.prototype.connect * @function * @public - * @async - * @param {VoiceProfile} profile Voice Profile to retrieve info for - * @return {Promise} - Promise of a VoiceProfileEnrollmentResult. - */ - VoiceProfileClient.prototype.retrieveEnrollmentResultAsync = function (profile) { - return __awaiter(this, void 0, void 0, function () { - var result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privAdapter.getProfileStatus(profile)]; - case 1: - result = _a.sent(); - return [2 /*return*/, new Exports_2.VoiceProfileEnrollmentResult(result.ok ? Exports_2.ResultReason.EnrolledVoiceProfile : Exports_2.ResultReason.Canceled, result.data, result.statusText)]; - } - }); - }); - }; + */ + connect(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.privReco.connect(), cb, err); + } /** - * Get all voice profiles on account with given voice profile type - * @member VoiceProfileClient.prototype.getAllProfilesAsync - * @function - * @public - * @async - * @param {VoiceProfileType} profileType profile type (identification/verification) for which to list profiles - * @return {Promise} - Promise of an array of VoiceProfileEnrollmentResults. - */ - VoiceProfileClient.prototype.getAllProfilesAsync = function (profileType) { - return __awaiter(this, void 0, void 0, function () { - var result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privAdapter.getProfiles(profileType)]; - case 1: - result = _a.sent(); - if (profileType === Exports_2.VoiceProfileType.TextIndependentIdentification) { - return [2 /*return*/, Exports_2.VoiceProfileEnrollmentResult.FromIdentificationProfileList(result.json)]; - } - return [2 /*return*/, Exports_2.VoiceProfileEnrollmentResult.FromVerificationProfileList(result.json)]; - } - }); - }); - }; + * Closes the connection the service. + * Users can optionally call disconnect() to manually shutdown the connection of the associated DialogServiceConnector. + * + * If disconnect() is called during a recognition, recognition will fail and cancel with an error. + */ + disconnect(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.privReco.disconnect(), cb, err); + } /** - * Get valid authorization phrases for voice profile enrollment - * @member VoiceProfileClient.prototype.getAuthorizationPhrasesAsync + * Gets the authorization token used to communicate with the service. + * @member DialogServiceConnector.prototype.authorizationToken * @function * @public - * @async - * @param {VoiceProfileType} profileType Profile Type to get activation phrases for - * @param {string} lang Language string (locale) for Voice Profile - */ - VoiceProfileClient.prototype.getActivationPhrasesAsync = function (profileType, lang) { - return __awaiter(this, void 0, void 0, function () { - var result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privAdapter.getPhrases(profileType, lang)]; - case 1: - result = _a.sent(); - return [2 /*return*/, new Exports_2.VoiceProfilePhraseResult(result.ok ? Exports_2.ResultReason.EnrollingVoiceProfile : Exports_2.ResultReason.Canceled, result.statusText, result.json)]; - } - }); - }); - }; + * @returns {string} Authorization token. + */ + get authorizationToken() { + return this.properties.getProperty(PropertyId_js_1.PropertyId.SpeechServiceAuthorization_Token); + } /** - * Create a speaker recognition voice profile - * @member VoiceProfileClient.prototype.enrollProfileAsync + * Sets the authorization token used to communicate with the service. + * @member DialogServiceConnector.prototype.authorizationToken * @function * @public - * @async - * @param {VoiceProfile} profile Voice Profile to create enrollment for - * @param {AudioConfig} audioConfig source info from which to create enrollment - * @return {Promise} - Promise of a VoiceProfileEnrollmentResult. - */ - VoiceProfileClient.prototype.enrollProfileAsync = function (profile, audioConfig) { - return __awaiter(this, void 0, void 0, function () { - var configImpl, result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - configImpl = audioConfig; - Contracts_1.Contracts.throwIfNullOrUndefined(configImpl, "audioConfig"); - return [4 /*yield*/, this.privAdapter.createEnrollment(profile, configImpl)]; - case 1: - result = _a.sent(); - return [2 /*return*/, new Exports_2.VoiceProfileEnrollmentResult(result.ok ? Exports_2.ResultReason.EnrolledVoiceProfile : Exports_2.ResultReason.Canceled, result.data, result.statusText)]; - } - }); - }); - }; + * @param {string} token - Authorization token. + */ + set authorizationToken(token) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token"); + this.properties.setProperty(PropertyId_js_1.PropertyId.SpeechServiceAuthorization_Token, token); + } /** - * Delete a speaker recognition voice profile - * @member VoiceProfileClient.prototype.deleteProfileAsync + * The collection of properties and their values defined for this DialogServiceConnector. + * @member DialogServiceConnector.prototype.properties * @function * @public - * @async - * @param {VoiceProfile} profile Voice Profile to be deleted - * @return {Promise} - Promise of a VoiceProfileResult. - */ - VoiceProfileClient.prototype.deleteProfileAsync = function (profile) { - return __awaiter(this, void 0, void 0, function () { - var result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privAdapter.deleteProfile(profile)]; - case 1: - result = _a.sent(); - return [2 /*return*/, this.getResult(result, Exports_2.ResultReason.DeletedVoiceProfile)]; - } - }); - }); - }; + * @returns {PropertyCollection} The collection of properties and their values defined for this DialogServiceConnector. + */ + get properties() { + return this.privProperties; + } + /** Gets the template for the activity generated by service from speech. + * Properties from the template will be stamped on the generated activity. + * It can be empty + */ + get speechActivityTemplate() { + return this.properties.getProperty(PropertyId_js_1.PropertyId.Conversation_Speech_Activity_Template); + } + /** Sets the template for the activity generated by service from speech. + * Properties from the template will be stamped on the generated activity. + * It can be null or empty. + * Note: it has to be a valid Json object. + */ + set speechActivityTemplate(speechActivityTemplate) { + this.properties.setProperty(PropertyId_js_1.PropertyId.Conversation_Speech_Activity_Template, speechActivityTemplate); + } /** - * Remove all enrollments for a speaker recognition voice profile - * @member VoiceProfileClient.prototype.resetProfileAsync + * Starts recognition and stops after the first utterance is recognized. + * @member DialogServiceConnector.prototype.listenOnceAsync * @function * @public - * @async - * @param {VoiceProfile} profile Voice Profile to be reset - * @return {Promise} - Promise of a VoiceProfileResult. - */ - VoiceProfileClient.prototype.resetProfileAsync = function (profile) { - return __awaiter(this, void 0, void 0, function () { - var result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privAdapter.resetProfile(profile)]; - case 1: - result = _a.sent(); - return [2 /*return*/, this.getResult(result, Exports_2.ResultReason.ResetVoiceProfile)]; - } + * @param cb - Callback that received the result when the reco has completed. + * @param err - Callback invoked in case of an error. + */ + listenOnceAsync(cb, err) { + if (this.isTurnComplete) { + Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed); + const callbackHolder = async () => { + await this.privReco.connect(); + await this.implRecognizerStop(); + this.isTurnComplete = false; + const ret = new Exports_js_2.Deferred(); + await this.privReco.recognize(PhraseDetectionContext_js_1.RecognitionMode.Conversation, ret.resolve, ret.reject); + const e = await ret.promise; + await this.implRecognizerStop(); + return e; + }; + const retPromise = callbackHolder(); + retPromise.catch(() => { + // Destroy the recognizer. + // We've done all we can here. + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.dispose(true).catch(() => { }); }); - }); - }; + (0, Exports_js_2.marshalPromiseToCallbacks)(retPromise.finally(() => { + this.isTurnComplete = true; + }), cb, err); + } + } + sendActivityAsync(activity, cb, errCb) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.privReco.sendMessage(activity), cb, errCb); + } /** - * Included for compatibility - * @member VoiceProfileClient.prototype.close + * closes all external resources held by an instance of this class. + * @member DialogServiceConnector.prototype.close * @function * @public */ - VoiceProfileClient.prototype.close = function () { - return; - }; - // Does class setup, swiped from Recognizer. - VoiceProfileClient.prototype.implClientSetup = function () { - var osPlatform = (typeof window !== "undefined") ? "Browser" : "Node"; - var osName = "unknown"; - var osVersion = "unknown"; - if (typeof navigator !== "undefined") { - osPlatform = osPlatform + "/" + navigator.platform; - osName = navigator.userAgent; - osVersion = navigator.appVersion; + close(cb, err) { + Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, err); + } + async dispose(disposing) { + if (this.privIsDisposed) { + return; + } + if (disposing) { + this.privIsDisposed = true; + await this.implRecognizerStop(); + await super.dispose(disposing); } - var recognizerConfig = new Exports_1.SpeakerRecognitionConfig(new Exports_1.Context(new Exports_1.OS(osPlatform, osName, osVersion)), this.privProperties); - this.privAdapter = new Exports_1.SpeakerIdMessageAdapter(recognizerConfig); - }; - VoiceProfileClient.prototype.getResult = function (result, successReason, cb) { - var response = new Exports_2.VoiceProfileResult(result.ok ? successReason : Exports_2.ResultReason.Canceled, result.statusText); - return (response); - }; - return VoiceProfileClient; -}()); -exports.VoiceProfileClient = VoiceProfileClient; + } + createRecognizerConfig(speechConfig) { + return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties); + } + createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) { + const audioSource = audioConfig; + return new Exports_js_1.DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this); + } + buildAgentConfig() { + const communicationType = this.properties.getProperty("Conversation_Communication_Type", "Default"); + return { + botInfo: { + commType: communicationType, + commandsCulture: undefined, + connectionId: this.properties.getProperty(PropertyId_js_1.PropertyId.Conversation_Agent_Connection_Id), + conversationId: this.properties.getProperty(PropertyId_js_1.PropertyId.Conversation_Conversation_Id, undefined), + fromId: this.properties.getProperty(PropertyId_js_1.PropertyId.Conversation_From_Id, undefined), + ttsAudioFormat: this.properties.getProperty(PropertyId_js_1.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined) + }, + version: 0.2 + }; + } +} +exports.DialogServiceConnector = DialogServiceConnector; /***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { +/* 134 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeakerRecognizer = void 0; -var Exports_1 = __webpack_require__(53); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); -/** - * Defines SpeakerRecognizer class for Speaker Recognition - * Handles operations from user for Voice Profile operations (e.g. createProfile, deleteProfile) - * @class SpeakerRecognizer - */ -var SpeakerRecognizer = /** @class */ (function () { - /** - * SpeakerRecognizer constructor. - * @constructor - * @param {SpeechConfig} speechConfig - An set of initial properties for this recognizer (authentication key, region, &c) - */ - function SpeakerRecognizer(speechConfig, audioConfig) { - var speechConfigImpl = speechConfig; - Contracts_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig"); - this.privAudioConfigImpl = audioConfig; - Contracts_1.Contracts.throwIfNull(this.privAudioConfigImpl, "audioConfig"); - this.privProperties = speechConfigImpl.properties.clone(); - this.implSRSetup(); - } - Object.defineProperty(SpeakerRecognizer.prototype, "authorizationToken", { - /** - * Gets the authorization token used to communicate with the service. - * @member SpeakerRecognizer.prototype.authorizationToken - * @function - * @public - * @returns {string} Authorization token. - */ - get: function () { - return this.properties.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token); - }, - /** - * Gets/Sets the authorization token used to communicate with the service. - * @member SpeakerRecognizer.prototype.authorizationToken - * @function - * @public - * @param {string} token - Authorization token. - */ - set: function (token) { - Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token"); - this.properties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, token); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeakerRecognizer.prototype, "properties", { - /** - * The collection of properties and their values defined for this SpeakerRecognizer. - * @member SpeakerRecognizer.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The collection of properties and their values defined for this SpeakerRecognizer. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - /** - * Get recognition result for model using given audio - * @member SpeakerRecognizer.prototype.recognizeOnceAsync - * @function - * @public - * @async - * @param {SpeakerIdentificationModel} model Model containing Voice Profiles to be identified - * @param cb - Callback invoked once result is returned. - * @param err - Callback invoked in case of an error. - */ - SpeakerRecognizer.prototype.recognizeOnceAsync = function (model) { - return __awaiter(this, void 0, void 0, function () { - var responsePromise, responsePromise; - return __generator(this, function (_a) { - if (model instanceof Exports_2.SpeakerIdentificationModel) { - responsePromise = this.privAdapter.identifySpeaker(model, this.privAudioConfigImpl); - return [2 /*return*/, this.getResult(responsePromise, Exports_2.SpeakerRecognitionResultType.Identify, undefined)]; - } - else if (model instanceof Exports_2.SpeakerVerificationModel) { - responsePromise = this.privAdapter.verifySpeaker(model, this.privAudioConfigImpl); - return [2 /*return*/, this.getResult(responsePromise, Exports_2.SpeakerRecognitionResultType.Verify, model.voiceProfile.profileId)]; - } - else { - throw new Error("SpeakerRecognizer.recognizeOnce: Unexpected model type"); - } - return [2 /*return*/]; - }); - }); - }; - /** - * Included for compatibility - * @member SpeakerRecognizer.prototype.close - * @function - * @public - */ - SpeakerRecognizer.prototype.close = function () { - return; - }; - // Does class setup, swiped from Recognizer. - SpeakerRecognizer.prototype.implSRSetup = function () { - var osPlatform = (typeof window !== "undefined") ? "Browser" : "Node"; - var osName = "unknown"; - var osVersion = "unknown"; - if (typeof navigator !== "undefined") { - osPlatform = osPlatform + "/" + navigator.platform; - osName = navigator.userAgent; - osVersion = navigator.appVersion; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DialogConnectionFactory = void 0; +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(66); +const Exports_js_2 = __webpack_require__(2); +const Exports_js_3 = __webpack_require__(85); +const ConnectionFactoryBase_js_1 = __webpack_require__(135); +const Exports_js_4 = __webpack_require__(2); +const HeaderNames_js_1 = __webpack_require__(59); +const QueryParameterNames_js_1 = __webpack_require__(136); +class DialogConnectionFactory extends ConnectionFactoryBase_js_1.ConnectionFactoryBase { + create(config, authInfo, connectionId) { + const applicationId = config.parameters.getProperty(Exports_js_3.PropertyId.Conversation_ApplicationId, ""); + const dialogType = config.parameters.getProperty(Exports_js_3.PropertyId.Conversation_DialogType); + const region = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Region); + const language = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-US"); + const requestTurnStatus = config.parameters.getProperty(Exports_js_3.PropertyId.Conversation_Request_Bot_Status_Messages, "true"); + const queryParams = {}; + queryParams[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId; + queryParams[QueryParameterNames_js_1.QueryParameterNames.Format] = config.parameters.getProperty(Exports_js_2.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]).toLowerCase(); + queryParams[QueryParameterNames_js_1.QueryParameterNames.Language] = language; + queryParams[QueryParameterNames_js_1.QueryParameterNames.RequestBotStatusMessages] = requestTurnStatus; + if (applicationId) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.BotId] = applicationId; + if (dialogType === Exports_js_3.DialogServiceConfig.DialogTypes.CustomCommands) { + queryParams[HeaderNames_js_1.HeaderNames.CustomCommandsAppId] = applicationId; + } + } + const resourceInfix = dialogType === Exports_js_3.DialogServiceConfig.DialogTypes.CustomCommands ? "commands/" + : ""; + const version = dialogType === Exports_js_3.DialogServiceConfig.DialogTypes.CustomCommands ? "v1" + : dialogType === Exports_js_3.DialogServiceConfig.DialogTypes.BotFramework ? "v3" + : "v0"; + const headers = {}; + if (authInfo.token != null && authInfo.token !== "") { + headers[authInfo.headerName] = authInfo.token; + } + // The URL used for connection is chosen in a priority order of specification: + // 1. If a custom endpoint is provided, that URL is used verbatim. + // 2. If a custom host is provided (e.g. "wss://my.custom.endpoint.com:1123"), a URL is constructed from it. + // 3. If no custom connection details are provided, a URL is constructed from default values. + let endpoint = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Endpoint, ""); + if (!endpoint) { + const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region); + const host = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Host, `wss://${region}.${DialogConnectionFactory.BaseUrl}${hostSuffix}`); + const standardizedHost = host.endsWith("/") ? host : host + "/"; + endpoint = `${standardizedHost}${resourceInfix}${DialogConnectionFactory.ApiKey}/${version}`; } - var recognizerConfig = new Exports_1.SpeakerRecognitionConfig(new Exports_1.Context(new Exports_1.OS(osPlatform, osName, osVersion)), this.privProperties); - this.privAdapter = new Exports_1.SpeakerIdMessageAdapter(recognizerConfig); - }; - SpeakerRecognizer.prototype.getResult = function (responsePromise, resultType, profileId) { - return __awaiter(this, void 0, void 0, function () { - var response; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, responsePromise]; - case 1: - response = _a.sent(); - return [2 /*return*/, new Exports_2.SpeakerRecognitionResult(resultType, response.data, profileId, response.ok ? Exports_2.ResultReason.RecognizedSpeaker : Exports_2.ResultReason.Canceled)]; - } - }); - }); - }; - return SpeakerRecognizer; -}()); -exports.SpeakerRecognizer = SpeakerRecognizer; + this.setCommonUrlParams(config, queryParams, endpoint); + const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; + return Promise.resolve(new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_4.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId)); + } +} +exports.DialogConnectionFactory = DialogConnectionFactory; +DialogConnectionFactory.ApiKey = "api"; +DialogConnectionFactory.BaseUrl = "convai.speech"; /***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { +/* 135 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeakerIdentificationModel = void 0; -var Contracts_1 = __webpack_require__(63); -var Exports_1 = __webpack_require__(61); -/** - * Defines SpeakerIdentificationModel class for Speaker Recognition - * Model contains a set of profiles against which to identify speaker(s) - * @class SpeakerIdentificationModel - */ -var SpeakerIdentificationModel = /** @class */ (function () { - function SpeakerIdentificationModel(profiles) { - var _this = this; - this.privVoiceProfiles = []; - Contracts_1.Contracts.throwIfNullOrUndefined(profiles, "VoiceProfiles"); - if (profiles.length === 0) { - throw new Error("Empty Voice Profiles array"); - } - profiles.forEach(function (profile) { - if (profile.profileType !== Exports_1.VoiceProfileType.TextIndependentIdentification) { - throw new Error("Identification model can only be created from Identification profile: " + profile.profileId); - } - _this.privVoiceProfiles.push(profile); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConnectionFactoryBase = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const Exports_js_3 = __webpack_require__(85); +const QueryParameterNames_js_1 = __webpack_require__(136); +class ConnectionFactoryBase { + static getHostSuffix(region) { + if (!!region) { + if (region.toLowerCase().startsWith("china")) { + return ".azure.cn"; + } + if (region.toLowerCase().startsWith("usgov")) { + return ".azure.us"; + } + } + return ".microsoft.com"; + } + setCommonUrlParams(config, queryParams, endpoint) { + const propertyIdToParameterMap = new Map([ + [Exports_js_3.PropertyId.Speech_SegmentationSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.SegmentationSilenceTimeoutMs], + [Exports_js_3.PropertyId.SpeechServiceConnection_EnableAudioLogging, QueryParameterNames_js_1.QueryParameterNames.EnableAudioLogging], + [Exports_js_3.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.EndSilenceTimeoutMs], + [Exports_js_3.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.InitialSilenceTimeoutMs], + [Exports_js_3.PropertyId.SpeechServiceResponse_ProfanityOption, QueryParameterNames_js_1.QueryParameterNames.Profanity], + [Exports_js_3.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, QueryParameterNames_js_1.QueryParameterNames.EnableWordLevelTimestamps], + [Exports_js_3.PropertyId.SpeechServiceResponse_StablePartialResultThreshold, QueryParameterNames_js_1.QueryParameterNames.StableIntermediateThreshold], + ]); + propertyIdToParameterMap.forEach((parameterName, propertyId) => { + this.setUrlParameter(propertyId, parameterName, config, queryParams, endpoint); + }); + const serviceProperties = JSON.parse(config.parameters.getProperty(Exports_js_1.ServicePropertiesPropertyName, "{}")); + Object.keys(serviceProperties).forEach((value) => { + queryParams[value] = serviceProperties[value]; }); } - SpeakerIdentificationModel.fromProfiles = function (profiles) { - return new SpeakerIdentificationModel(profiles); - }; - Object.defineProperty(SpeakerIdentificationModel.prototype, "voiceProfileIds", { - get: function () { - return this.privVoiceProfiles.map(function (profile) { return profile.profileId; }).join(","); - }, - enumerable: false, - configurable: true - }); - return SpeakerIdentificationModel; -}()); -exports.SpeakerIdentificationModel = SpeakerIdentificationModel; + setUrlParameter(propId, parameterName, config, queryParams, endpoint) { + const value = config.parameters.getProperty(propId, undefined); + // FIXME: The .search() check will incorrectly match parameter name anywhere in the string + // including e.g. the path portion, or even as a substring of other query parameters + if (value && (!endpoint || endpoint.search(parameterName) === -1)) { + queryParams[parameterName] = value.toLocaleLowerCase(); + } + } + static async getRedirectUrlFromEndpoint(endpoint, useWebSocketProtocol = true) { + // make a rest call to the endpoint to get the redirect url + const redirectUrl = new URL(endpoint); + redirectUrl.protocol = "https:"; + redirectUrl.port = "443"; + const params = redirectUrl.searchParams; + params.append("GenerateRedirectResponse", "true"); + const redirectedUrlString = redirectUrl.toString(); + Exports_js_2.Events.instance.onEvent(new Exports_js_2.ConnectionRedirectEvent("", redirectedUrlString, undefined, "ConnectionFactoryBase: redirectUrl request")); + const redirectResponse = await fetch(redirectedUrlString); + if (redirectResponse.status !== 200) { + return endpoint; + } + // Fix: properly read the response text + const redirectUrlString = await redirectResponse.text(); + Exports_js_2.Events.instance.onEvent(new Exports_js_2.ConnectionRedirectEvent("", redirectUrlString, endpoint, "ConnectionFactoryBase: redirectUrlString")); + try { + // Validate the URL before returning + const redirectUrl = new URL(redirectUrlString.trim()); + // WebSocket callers need the ws(s) scheme; REST callers (e.g. voices/list) must keep http(s). + if (useWebSocketProtocol) { + if (redirectUrl.protocol === "https:") { + redirectUrl.protocol = "wss:"; + } + else if (redirectUrl.protocol === "http:") { + redirectUrl.protocol = "ws:"; + } + } + return redirectUrl.toString(); + } + catch (error) { + return endpoint; // Return original endpoint if the redirect URL is invalid + } + } +} +exports.ConnectionFactoryBase = ConnectionFactoryBase; /***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { +/* 136 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeakerVerificationModel = void 0; -var Contracts_1 = __webpack_require__(63); -var Exports_1 = __webpack_require__(61); -/** - * Defines SpeakerVerificationModel class for Speaker Recognition - * Model contains a profile against which to verify a speaker - * @class SpeakerVerificationModel - */ -var SpeakerVerificationModel = /** @class */ (function () { - function SpeakerVerificationModel(profile) { - Contracts_1.Contracts.throwIfNullOrUndefined(profile, "VoiceProfile"); - if (profile.profileType === Exports_1.VoiceProfileType.TextIndependentIdentification) { - throw new Error("Verification model cannot be created from Identification profile"); - } - this.privVoiceProfile = profile; - } - SpeakerVerificationModel.fromProfile = function (profile) { - return new SpeakerVerificationModel(profile); - }; - Object.defineProperty(SpeakerVerificationModel.prototype, "voiceProfile", { - get: function () { - return this.privVoiceProfile; - }, - enumerable: false, - configurable: true - }); - return SpeakerVerificationModel; -}()); -exports.SpeakerVerificationModel = SpeakerVerificationModel; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.QueryParameterNames = void 0; +class QueryParameterNames { +} +exports.QueryParameterNames = QueryParameterNames; +QueryParameterNames.BotId = "botid"; +QueryParameterNames.CustomSpeechDeploymentId = "cid"; +QueryParameterNames.CustomVoiceDeploymentId = "deploymentId"; +QueryParameterNames.EnableAudioLogging = "storeAudio"; +QueryParameterNames.EnableLanguageId = "lidEnabled"; +QueryParameterNames.EnableWordLevelTimestamps = "wordLevelTimestamps"; +QueryParameterNames.EndSilenceTimeoutMs = "endSilenceTimeoutMs"; +QueryParameterNames.SegmentationSilenceTimeoutMs = "segmentationSilenceTimeoutMs"; +QueryParameterNames.SegmentationMaximumTimeMs = "segmentationMaximumTimeMs"; +QueryParameterNames.SegmentationStrategy = "segmentationStrategy"; +QueryParameterNames.Format = "format"; +QueryParameterNames.InitialSilenceTimeoutMs = "initialSilenceTimeoutMs"; +QueryParameterNames.Language = "language"; +QueryParameterNames.Profanity = "profanity"; +QueryParameterNames.RequestBotStatusMessages = "enableBotMessageStatus"; +QueryParameterNames.StableIntermediateThreshold = "stableIntermediateThreshold"; +QueryParameterNames.StableTranslation = "stableTranslation"; +QueryParameterNames.TestHooks = "testhooks"; +QueryParameterNames.Postprocessing = "postprocessing"; +QueryParameterNames.CtsMeetingId = "meetingId"; +QueryParameterNames.CtsDeviceId = "deviceId"; +QueryParameterNames.CtsIsParticipant = "isParticipant"; +QueryParameterNames.EnableAvatar = "enableTalkingAvatar"; /***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { +/* 137 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AutoDetectSourceLanguageConfig = void 0; -var Exports_1 = __webpack_require__(53); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ActivityReceivedEventArgs = void 0; /** - * Language auto detect configuration. - * @class AutoDetectSourceLanguageConfig - * Added in version 1.13.0. + * Defines contents of received message/events. + * @class ActivityReceivedEventArgs */ -var AutoDetectSourceLanguageConfig = /** @class */ (function () { - function AutoDetectSourceLanguageConfig() { - this.privProperties = new Exports_2.PropertyCollection(); - } - /** - * @member AutoDetectSourceLanguageConfig.fromOpenRange - * @function - * @public - * Only [[SpeechSynthesizer]] supports source language auto detection from open range, - * for [[Recognizer]], please use AutoDetectSourceLanguageConfig with specific source languages. - * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig - * @summary Creates an instance of the AutoDetectSourceLanguageConfig with open range. - */ - AutoDetectSourceLanguageConfig.fromOpenRange = function () { - var config = new AutoDetectSourceLanguageConfig(); - config.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, Exports_1.AutoDetectSourceLanguagesOpenRangeOptionName); - return config; - }; +class ActivityReceivedEventArgs { /** - * @member AutoDetectSourceLanguageConfig.fromLanguages - * @function - * @public - * @param {string[]} languages Comma-separated string of languages (eg. "en-US,fr-FR") to populate properties of config. - * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig - * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given languages. + * Creates and initializes an instance of this class. + * @constructor + * @param {any} activity - The activity.. */ - AutoDetectSourceLanguageConfig.fromLanguages = function (languages) { - Contracts_1.Contracts.throwIfArrayEmptyOrWhitespace(languages, "languages"); - var config = new AutoDetectSourceLanguageConfig(); - config.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, languages.join()); - return config; - }; + constructor(activity, audioStream) { + this.privActivity = activity; + this.privAudioStream = audioStream; + } /** - * @member AutoDetectSourceLanguageConfig.fromSourceLanguageConfigs + * Gets the received activity + * @member ActivityReceivedEventArgs.prototype.activity * @function * @public - * @param {SourceLanguageConfig[]} configs SourceLanguageConfigs to populate properties of config. - * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig - * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given SourceLanguageConfigs. + * @returns {any} the received activity. */ - AutoDetectSourceLanguageConfig.fromSourceLanguageConfigs = function (configs) { - if (configs.length < 1) { - throw new Error("Expected non-empty SourceLanguageConfig array."); - } - var autoConfig = new AutoDetectSourceLanguageConfig(); - var langs = []; - configs.forEach(function (config) { - langs.push(config.language); - if (config.endpointId !== undefined && config.endpointId !== "") { - var customProperty = config.language + Exports_2.PropertyId.SpeechServiceConnection_EndpointId.toString(); - autoConfig.properties.setProperty(customProperty, config.endpointId); - } - }); - autoConfig.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, langs.join()); - return autoConfig; - }; - Object.defineProperty(AutoDetectSourceLanguageConfig.prototype, "properties", { - /** - * @member AutoDetectSourceLanguageConfig.prototype.properties - * @function - * @public - * @return {PropertyCollection} Properties of the config. - * @summary Gets an auto detected language config properties - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - return AutoDetectSourceLanguageConfig; -}()); -exports.AutoDetectSourceLanguageConfig = AutoDetectSourceLanguageConfig; + get activity() { + return this.privActivity; + } + get audioStream() { + return this.privAudioStream; + } +} +exports.ActivityReceivedEventArgs = ActivityReceivedEventArgs; /***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { +/* 138 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AutoDetectSourceLanguageResult = void 0; -var Contracts_1 = __webpack_require__(63); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TurnStatusReceivedEventArgs = void 0; +const TurnStatusPayload_js_1 = __webpack_require__(139); /** - * Output format - * @class AutoDetectSourceLanguageResult + * Defines contents of received message/events. + * @class TurnStatusReceivedEventArgs */ -var AutoDetectSourceLanguageResult = /** @class */ (function () { - function AutoDetectSourceLanguageResult(language, languageDetectionConfidence) { - Contracts_1.Contracts.throwIfNullOrUndefined(language, "language"); - Contracts_1.Contracts.throwIfNullOrUndefined(languageDetectionConfidence, "languageDetectionConfidence"); - this.privLanguage = language; - this.privLanguageDetectionConfidence = languageDetectionConfidence; +class TurnStatusReceivedEventArgs { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {string} turnStatus - The JSON-encoded turn status message. + */ + constructor(turnStatus) { + this.privTurnStatus = TurnStatusPayload_js_1.TurnStatusResponsePayload.fromJSON(turnStatus); } /** - * Creates an instance of AutoDetectSourceLanguageResult object from a SpeechRecognitionResult instance. - * @member AutoDetectSourceLanguageResult.fromResult + * Gets the interaction identifier associated with this turn status event. + * @member TurnStatusReceivedEventArgs.prototype.interactionId * @function * @public - * @param {SpeechRecognitionResult} result - The recognition result. - * @returns {AutoDetectSourceLanguageResult} AutoDetectSourceLanguageResult object being created. + * @returns {any} the received interaction id. */ - AutoDetectSourceLanguageResult.fromResult = function (result) { - return new AutoDetectSourceLanguageResult(result.language, result.languageDetectionConfidence); - }; - Object.defineProperty(AutoDetectSourceLanguageResult.prototype, "language", { - get: function () { - return this.privLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AutoDetectSourceLanguageResult.prototype, "languageDetectionConfidence", { - get: function () { - return this.privLanguageDetectionConfidence; - }, - enumerable: false, - configurable: true - }); - return AutoDetectSourceLanguageResult; -}()); -exports.AutoDetectSourceLanguageResult = AutoDetectSourceLanguageResult; + get interactionId() { + return this.privTurnStatus.interactionId; + } + /** + * Gets the conversation identifier associated with this turn status event. + * @member TurnStatusReceivedEventArgs.prototype.conversationId + * @function + * @public + * @returns {any} the received conversation id. + */ + get conversationId() { + return this.privTurnStatus.conversationId; + } + /** + * Gets the received turn status code. + * @member TurnStatusReceivedEventArgs.prototype.statusCode + * @function + * @public + * @returns {number} the received turn status. + */ + get statusCode() { + return this.privTurnStatus.statusCode; // eslint-disable-line @typescript-eslint/no-unsafe-return + } +} +exports.TurnStatusReceivedEventArgs = TurnStatusReceivedEventArgs; /***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { +/* 139 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SourceLanguageConfig = void 0; -var Contracts_1 = __webpack_require__(63); -/** - * Source Language configuration. - * @class SourceLanguageConfig - */ -var SourceLanguageConfig = /** @class */ (function () { - function SourceLanguageConfig(language, endpointId) { - Contracts_1.Contracts.throwIfNullOrUndefined(language, "language"); - this.privLanguage = language; - this.privEndpointId = endpointId; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TurnStatusResponsePayload = void 0; +class TurnStatusResponsePayload { + constructor(json) { + this.privMessageStatusResponse = JSON.parse(json); } - /** - * @member SourceLanguageConfig.fromLanguage - * @function - * @public - * @param {string} language language (eg. "en-US") value of config. - * @param {string?} endpointId endpointId of model bound to given language of config. - * @return {SourceLanguageConfig} Instance of SourceLanguageConfig - * @summary Creates an instance of the SourceLanguageConfig with the given language and optional endpointId. - * Added in version 1.13.0. - */ - SourceLanguageConfig.fromLanguage = function (language, endpointId) { - return new SourceLanguageConfig(language, endpointId); - }; - Object.defineProperty(SourceLanguageConfig.prototype, "language", { - get: function () { - return this.privLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SourceLanguageConfig.prototype, "endpointId", { - get: function () { - return this.privEndpointId; - }, - enumerable: false, - configurable: true - }); - return SourceLanguageConfig; -}()); -exports.SourceLanguageConfig = SourceLanguageConfig; + static fromJSON(json) { + return new TurnStatusResponsePayload(json); + } + get interactionId() { + return this.privMessageStatusResponse.interactionId; + } + get conversationId() { + return this.privMessageStatusResponse.conversationId; + } + get statusCode() { + // Payloads may contain a limited set of textual representations or a numeric status + // code. The textual values are here converted into numeric ones. + switch (this.privMessageStatusResponse.statusCode) { + case "Success": + return 200; + case "Failed": + return 400; + case "TimedOut": + return 429; + default: + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this.privMessageStatusResponse.statusCode; + } + } +} +exports.TurnStatusResponsePayload = TurnStatusResponsePayload; /***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { +/* 140 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeakerRecognitionCancellationDetails = exports.SpeakerRecognitionResult = exports.SpeakerRecognitionResultType = void 0; -var Exports_1 = __webpack_require__(53); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); -var SpeakerRecognitionResultType; -(function (SpeakerRecognitionResultType) { - SpeakerRecognitionResultType[SpeakerRecognitionResultType["Verify"] = 0] = "Verify"; - SpeakerRecognitionResultType[SpeakerRecognitionResultType["Identify"] = 1] = "Identify"; -})(SpeakerRecognitionResultType = exports.SpeakerRecognitionResultType || (exports.SpeakerRecognitionResultType = {})); -/** - * Output format - * @class SpeakerRecognitionResult - */ -var SpeakerRecognitionResult = /** @class */ (function () { - function SpeakerRecognitionResult(resultType, data, profileId, resultReason) { - if (resultReason === void 0) { resultReason = Exports_2.ResultReason.RecognizedSpeaker; } - this.privProperties = new Exports_2.PropertyCollection(); - this.privReason = resultReason; - if (this.privReason !== Exports_2.ResultReason.Canceled) { - if (resultType === SpeakerRecognitionResultType.Identify) { - var json = JSON.parse(data); - Contracts_1.Contracts.throwIfNullOrUndefined(json, "JSON"); - this.privProfileId = json.identifiedProfile.profileId; - this.privScore = json.identifiedProfile.score; - } - else { - var json = JSON.parse(data); - Contracts_1.Contracts.throwIfNullOrUndefined(json, "JSON"); - this.privScore = json.score; - if (json.recognitionResult.toLowerCase() !== "accept") { - this.privReason = Exports_2.ResultReason.NoMatch; - } - if (profileId !== undefined && profileId !== "") { - this.privProfileId = profileId; - } - } - } - else { - var json = JSON.parse(data); - Contracts_1.Contracts.throwIfNullOrUndefined(json, "JSON"); - this.privErrorDetails = json.statusText; - this.privProperties.setProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.ServiceError]); - } - this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_JsonResult, data); - } - Object.defineProperty(SpeakerRecognitionResult.prototype, "properties", { - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeakerRecognitionResult.prototype, "reason", { - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeakerRecognitionResult.prototype, "profileId", { - get: function () { - return this.privProfileId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeakerRecognitionResult.prototype, "errorDetails", { - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeakerRecognitionResult.prototype, "score", { - get: function () { - return this.privScore; - }, - enumerable: false, - configurable: true - }); - return SpeakerRecognitionResult; -}()); -exports.SpeakerRecognitionResult = SpeakerRecognitionResult; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServicePropertyChannel = void 0; /** - * @class SpeakerRecognitionCancellationDetails + * Defines channels used to pass property settings to service. + * Added in version 1.7.0. */ -// tslint:disable-next-line:max-classes-per-file -var SpeakerRecognitionCancellationDetails = /** @class */ (function (_super) { - __extends(SpeakerRecognitionCancellationDetails, _super); - function SpeakerRecognitionCancellationDetails(reason, errorDetails, errorCode) { - return _super.call(this, reason, errorDetails, errorCode) || this; - } +var ServicePropertyChannel; +(function (ServicePropertyChannel) { /** - * Creates an instance of SpeakerRecognitionCancellationDetails object for the canceled SpeakerRecognitionResult - * @member SpeakerRecognitionCancellationDetails.fromResult - * @function - * @public - * @param {SpeakerRecognitionResult} result - The result that was canceled. - * @returns {SpeakerRecognitionCancellationDetails} The cancellation details object being created. + * Uses URI query parameter to pass property settings to service. */ - SpeakerRecognitionCancellationDetails.fromResult = function (result) { - var reason = Exports_2.CancellationReason.Error; - var errorCode = Exports_2.CancellationErrorCode.NoError; - if (!!result.properties) { - errorCode = Exports_2.CancellationErrorCode[result.properties.getProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.NoError])]; - } - return new SpeakerRecognitionCancellationDetails(reason, result.errorDetails, errorCode); - }; - return SpeakerRecognitionCancellationDetails; -}(Exports_2.CancellationDetailsBase)); -exports.SpeakerRecognitionCancellationDetails = SpeakerRecognitionCancellationDetails; + ServicePropertyChannel[ServicePropertyChannel["UriQueryParameter"] = 0] = "UriQueryParameter"; +})(ServicePropertyChannel = exports.ServicePropertyChannel || (exports.ServicePropertyChannel = {})); /***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { +/* 141 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -Object.defineProperty(exports, "__esModule", { value: true }); -var Conversation_1 = __webpack_require__(145); -Object.defineProperty(exports, "Conversation", { enumerable: true, get: function () { return Conversation_1.Conversation; } }); -Object.defineProperty(exports, "ConversationImpl", { enumerable: true, get: function () { return Conversation_1.ConversationImpl; } }); -var ConversationCommon_1 = __webpack_require__(146); -Object.defineProperty(exports, "ConversationCommon", { enumerable: true, get: function () { return ConversationCommon_1.ConversationCommon; } }); -var ConversationExpirationEventArgs_1 = __webpack_require__(147); -Object.defineProperty(exports, "ConversationExpirationEventArgs", { enumerable: true, get: function () { return ConversationExpirationEventArgs_1.ConversationExpirationEventArgs; } }); -var ConversationParticipantsChangedEventArgs_1 = __webpack_require__(148); -Object.defineProperty(exports, "ConversationParticipantsChangedEventArgs", { enumerable: true, get: function () { return ConversationParticipantsChangedEventArgs_1.ConversationParticipantsChangedEventArgs; } }); -var ConversationTranslationCanceledEventArgs_1 = __webpack_require__(149); -Object.defineProperty(exports, "ConversationTranslationCanceledEventArgs", { enumerable: true, get: function () { return ConversationTranslationCanceledEventArgs_1.ConversationTranslationCanceledEventArgs; } }); -var ConversationTranslationEventArgs_1 = __webpack_require__(150); -Object.defineProperty(exports, "ConversationTranslationEventArgs", { enumerable: true, get: function () { return ConversationTranslationEventArgs_1.ConversationTranslationEventArgs; } }); -var ConversationTranslationResult_1 = __webpack_require__(151); -Object.defineProperty(exports, "ConversationTranslationResult", { enumerable: true, get: function () { return ConversationTranslationResult_1.ConversationTranslationResult; } }); -var ConversationTranslator_1 = __webpack_require__(152); -Object.defineProperty(exports, "ConversationTranslator", { enumerable: true, get: function () { return ConversationTranslator_1.ConversationTranslator; } }); -var ConversationTranscriber_1 = __webpack_require__(153); -Object.defineProperty(exports, "ConversationTranscriber", { enumerable: true, get: function () { return ConversationTranscriber_1.ConversationTranscriber; } }); -var IParticipant_1 = __webpack_require__(154); -Object.defineProperty(exports, "Participant", { enumerable: true, get: function () { return IParticipant_1.Participant; } }); -Object.defineProperty(exports, "User", { enumerable: true, get: function () { return IParticipant_1.User; } }); -var ParticipantChangedReason_1 = __webpack_require__(155); -Object.defineProperty(exports, "ParticipantChangedReason", { enumerable: true, get: function () { return ParticipantChangedReason_1.ParticipantChangedReason; } }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProfanityOption = void 0; +/** + * Profanity option. + * Added in version 1.7.0. + */ +var ProfanityOption; +(function (ProfanityOption) { + ProfanityOption[ProfanityOption["Masked"] = 0] = "Masked"; + ProfanityOption[ProfanityOption["Removed"] = 1] = "Removed"; + ProfanityOption[ProfanityOption["Raw"] = 2] = "Raw"; +})(ProfanityOption = exports.ProfanityOption || (exports.ProfanityOption = {})); /***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { +/* 142 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -var __spreadArrays = (this && this.__spreadArrays) || function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationImpl = exports.Conversation = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -var Conversation = /** @class */ (function () { - function Conversation() { - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseAudioPlayer = void 0; +const Error_js_1 = __webpack_require__(31); +const Exports_js_1 = __webpack_require__(85); +const AudioStreamFormat_js_1 = __webpack_require__(73); +/** + * Base audio player class + * TODO: Plays only PCM for now. + * @class + */ +class BaseAudioPlayer { /** - * Create a conversation - * @param speechConfig - * @param cb - * @param err + * Creates and initializes an instance of this class. + * @constructor + * @param {AudioStreamFormat} audioFormat audio stream format recognized by the player. */ - Conversation.createConversationAsync = function (speechConfig, arg2, arg3, arg4) { - Contracts_1.Contracts.throwIfNullOrUndefined(speechConfig, Exports_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "config")); - Contracts_1.Contracts.throwIfNullOrUndefined(speechConfig.region, Exports_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Region")); - if (!speechConfig.subscriptionKey && !speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceAuthorization_Token])) { - Contracts_1.Contracts.throwIfNullOrUndefined(speechConfig.subscriptionKey, Exports_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Key")); - } - var conversationImpl; - var cb; - var err; - if (typeof arg2 === "string") { - conversationImpl = new ConversationImpl(speechConfig, arg2); - cb = arg3; - err = arg4; - } - else { - conversationImpl = new ConversationImpl(speechConfig); - cb = arg2; - err = arg3; - } - conversationImpl.createConversationAsync((function () { - if (!!cb) { - cb(); - } - }), function (error) { - if (!!err) { - err(error); - } - }); - return conversationImpl; - }; - return Conversation; -}()); -exports.Conversation = Conversation; -// tslint:disable-next-line:max-classes-per-file -var ConversationImpl = /** @class */ (function (_super) { - __extends(ConversationImpl, _super); - /** - * Create a conversation impl - * @param speechConfig - * @param {string} id - optional conversationId - */ - function ConversationImpl(speechConfig, id) { - var _this = _super.call(this) || this; - _this.privIsDisposed = false; - _this.privIsConnected = false; - _this.privErrors = Exports_1.ConversationConnectionConfig.restErrors; - _this.privConversationId = ""; - /** websocket callbacks */ - _this.onConnected = function (e) { - var _a, _b; - _this.privIsConnected = true; - try { - if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.sessionStarted)) { - _this.privConversationTranslator.sessionStarted(_this.privConversationTranslator, e); - } - if (!!((_b = _this.privTranscriberRecognizer) === null || _b === void 0 ? void 0 : _b.conversationStarted)) { - _this.privTranscriberRecognizer.conversationStarted(_this.privTranscriberRecognizer, e); - } - } - catch (e) { - // - } - }; - _this.onDisconnected = function (e) { return __awaiter(_this, void 0, void 0, function () { - var e_1; - var _a, _b; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - _c.trys.push([0, 1, 2, 4]); - if (!!((_a = this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.sessionStopped)) { - this.privConversationTranslator.sessionStopped(this.privConversationTranslator, e); - } - if (!!((_b = this.privTranscriberRecognizer) === null || _b === void 0 ? void 0 : _b.conversationStopped)) { - this.privTranscriberRecognizer.conversationStopped(this.privTranscriberRecognizer, e); - } - return [3 /*break*/, 4]; - case 1: - e_1 = _c.sent(); - return [3 /*break*/, 4]; - case 2: return [4 /*yield*/, this.close(false)]; - case 3: - _c.sent(); - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); }; - _this.onCanceled = function (r, e) { return __awaiter(_this, void 0, void 0, function () { - var _a, _b; - return __generator(this, function (_c) { - try { - if (!!((_a = this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.canceled)) { - this.privConversationTranslator.canceled(this.privConversationTranslator, e); - } - if (!!((_b = this.privTranscriberRecognizer) === null || _b === void 0 ? void 0 : _b.conversationCanceled)) { - this.privTranscriberRecognizer.conversationCanceled(this.privTranscriberRecognizer, e); - } - } - catch (e) { - // - } - return [2 /*return*/]; - }); - }); }; - _this.onParticipantUpdateCommandReceived = function (r, e) { - var _a, _b; - try { - var updatedParticipant = _this.privParticipants.getParticipant(e.id); - if (updatedParticipant !== undefined) { - switch (e.key) { - case Exports_1.ConversationTranslatorCommandTypes.changeNickname: - updatedParticipant.displayName = e.value; - break; - case Exports_1.ConversationTranslatorCommandTypes.setUseTTS: - updatedParticipant.useTts = e.value; - break; - case Exports_1.ConversationTranslatorCommandTypes.setProfanityFiltering: - updatedParticipant.profanity = e.value; - break; - case Exports_1.ConversationTranslatorCommandTypes.setMute: - updatedParticipant.isMuted = e.value; - break; - case Exports_1.ConversationTranslatorCommandTypes.setTranslateToLanguages: - updatedParticipant.translateToLanguages = e.value; - break; - } - _this.privParticipants.addOrUpdateParticipant(updatedParticipant); - if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) { - (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.Updated, [_this.toParticipant(updatedParticipant)], e.sessionId)); - } - } - } - catch (e) { - // - } - }; - _this.onLockRoomCommandReceived = function (r, e) { - // TODO - }; - _this.onMuteAllCommandReceived = function (r, e) { - var _a, _b; - try { - _this.privParticipants.participants.forEach(function (p) { return p.isMuted = (p.isHost ? false : e.isMuted); }); - if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) { - (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.Updated, _this.toParticipants(false), e.sessionId)); - } - } - catch (e) { - // - } - }; - _this.onParticipantJoinCommandReceived = function (r, e) { - var _a, _b; - try { - var newParticipant = _this.privParticipants.addOrUpdateParticipant(e.participant); - if (newParticipant !== undefined) { - if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) { - (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.JoinedConversation, [_this.toParticipant(newParticipant)], e.sessionId)); - } - } - } - catch (e) { - // - } - }; - _this.onParticipantLeaveCommandReceived = function (r, e) { - var _a, _b; - try { - var ejectedParticipant = _this.privParticipants.getParticipant(e.participant.id); - if (ejectedParticipant !== undefined) { - // remove the participant from the internal participants list - _this.privParticipants.deleteParticipant(e.participant.id); - if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) { - // notify subscribers that the participant has left the conversation - (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.LeftConversation, [_this.toParticipant(ejectedParticipant)], e.sessionId)); - } - } - } - catch (e) { - // - } - }; - _this.onTranslationReceived = function (r, e) { - var _a, _b, _c, _d, _e, _f; - try { - switch (e.command) { - case Exports_1.ConversationTranslatorMessageTypes.final: - if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.transcribed)) { - (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.transcribed(_this.privConversationTranslator, new Exports_3.ConversationTranslationEventArgs(e.payload, undefined, e.sessionId)); - } - break; - case Exports_1.ConversationTranslatorMessageTypes.partial: - if (!!((_c = _this.privConversationTranslator) === null || _c === void 0 ? void 0 : _c.transcribing)) { - (_d = _this.privConversationTranslator) === null || _d === void 0 ? void 0 : _d.transcribing(_this.privConversationTranslator, new Exports_3.ConversationTranslationEventArgs(e.payload, undefined, e.sessionId)); - } - break; - case Exports_1.ConversationTranslatorMessageTypes.instantMessage: - if (!!((_e = _this.privConversationTranslator) === null || _e === void 0 ? void 0 : _e.textMessageReceived)) { - (_f = _this.privConversationTranslator) === null || _f === void 0 ? void 0 : _f.textMessageReceived(_this.privConversationTranslator, new Exports_3.ConversationTranslationEventArgs(e.payload, undefined, e.sessionId)); - } - break; - } - } - catch (e) { - // - } - }; - _this.onParticipantsListReceived = function (r, e) { - var _a, _b, _c; - try { - // check if the session token needs to be updated - if (e.sessionToken !== undefined && e.sessionToken !== null) { - _this.privRoom.token = e.sessionToken; - } - // save the participants - _this.privParticipants.participants = __spreadArrays(e.participants); - // enable the conversation - if (_this.privParticipants.me !== undefined) { - _this.privIsReady = true; - } - if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) { - (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.JoinedConversation, _this.toParticipants(true), e.sessionId)); - } - // if this is the host, update the nickname if needed - if (_this.me.isHost) { - var nickname = (_c = _this.privConversationTranslator) === null || _c === void 0 ? void 0 : _c.properties.getProperty(Exports_3.PropertyId.ConversationTranslator_Name); - if (nickname !== undefined && nickname.length > 0 && nickname !== _this.me.displayName) { - // issue a change nickname request - _this.changeNicknameAsync(nickname); - } - } - } - catch (e) { - // - } - }; - _this.onConversationExpiration = function (r, e) { - var _a, _b; - try { - if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.conversationExpiration)) { - (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.conversationExpiration(_this.privConversationTranslator, e); - } - } - catch (e) { - // - } - }; - _this.privProperties = new Exports_3.PropertyCollection(); - _this.privManager = new Exports_1.ConversationManager(); - // check the speech language - var language = speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]); - if (!language) { - speechConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage], Exports_1.ConversationConnectionConfig.defaultLanguageCode); - } - _this.privLanguage = speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]); - if (!id) { - // check the target language(s) - if (speechConfig.targetLanguages.length === 0) { - speechConfig.addTargetLanguage(_this.privLanguage); - } - // check the profanity setting: speech and conversationTranslator should be in sync - var profanity = speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceResponse_ProfanityOption]); - if (!profanity) { - speechConfig.setProfanity(Exports_3.ProfanityOption.Masked); - } - // check the nickname: it should pass this regex: ^\w+([\s-][\w\(\)]+)*$" - // TODO: specify the regex required. Nicknames must be unique or get the duplicate nickname error - // TODO: check what the max length is and if a truncation is required or if the service handles it without an error - var hostNickname = speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.ConversationTranslator_Name]); - if (hostNickname === undefined || hostNickname === null || hostNickname.length <= 1 || hostNickname.length > 50) { - hostNickname = "Host"; - } - speechConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.ConversationTranslator_Name], hostNickname); - } - else { - _this.privConversationId = id; + constructor(audioFormat) { + this.audioContext = null; + this.gainNode = null; + this.autoUpdateBufferTimer = 0; + if (audioFormat === undefined) { + audioFormat = Exports_js_1.AudioStreamFormat.getDefaultInputFormat(); } - // save the speech config for future usage - _this.privConfig = speechConfig; - // save the config properties - var configImpl = speechConfig; - Contracts_1.Contracts.throwIfNull(configImpl, "speechConfig"); - _this.privProperties = configImpl.properties.clone(); - _this.privIsConnected = false; - _this.privParticipants = new Exports_1.InternalParticipants(); - _this.privIsReady = false; - _this.privTextMessageMaxLength = 1000; - return _this; - } - Object.defineProperty(ConversationImpl.prototype, "conversationTranslator", { - set: function (conversationTranslator) { - this.privConversationTranslator = conversationTranslator; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "room", { - // get the internal data about a conversation - get: function () { - return this.privRoom; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "connection", { - // get the wrapper for connecting to the websockets - get: function () { - return this.privConversationRecognizer; // this.privConnection; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "authorizationToken", { - // get / set the speech auth token - get: function () { - return this.privToken; - }, - set: function (value) { - Contracts_1.Contracts.throwIfNullOrWhitespace(value, "authorizationToken"); - this.privToken = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "config", { - // get the config - get: function () { - return this.privConfig; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "conversationId", { - // get the conversation Id - get: function () { - return this.privRoom ? this.privRoom.roomId : this.privConversationId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "properties", { - // get the properties - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "speechRecognitionLanguage", { - // get the speech language - get: function () { - return this.privLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "isMutedByHost", { - get: function () { - var _a, _b; - return ((_a = this.privParticipants.me) === null || _a === void 0 ? void 0 : _a.isHost) ? false : (_b = this.privParticipants.me) === null || _b === void 0 ? void 0 : _b.isMuted; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "isConnected", { - get: function () { - return this.privIsConnected && this.privIsReady; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "participants", { - get: function () { - return this.toParticipants(true); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "me", { - get: function () { - return this.toParticipant(this.privParticipants.me); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "host", { - get: function () { - return this.toParticipant(this.privParticipants.host); - }, - enumerable: false, - configurable: true - }); + this.init(audioFormat); + } /** - * Create a new conversation as Host - * @param cb - * @param err + * play Audio sample + * @param newAudioData audio data to be played. */ - ConversationImpl.prototype.createConversationAsync = function (cb, err) { - var _this = this; + playAudioSample(newAudioData, cb, err) { try { - if (!!this.privConversationRecognizer) { - this.handleError(new Error(this.privErrors.permissionDeniedStart), err); + this.ensureInitializedContext(); + const audioData = this.formatAudioData(newAudioData); + const newSamplesData = new Float32Array(this.samples.length + audioData.length); + newSamplesData.set(this.samples, 0); + newSamplesData.set(audioData, this.samples.length); + this.samples = newSamplesData; + if (!!cb) { + cb(); } - this.privManager.createOrJoin(this.privProperties, undefined, (function (room) { - if (!room) { - _this.handleError(new Error(_this.privErrors.permissionDeniedConnect), err); - } - _this.privRoom = room; - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); - } - catch (error) { - this.handleError(error, err); - } - }; - /** - * Starts a new conversation as host. - * @param cb - * @param err - */ - ConversationImpl.prototype.startConversationAsync = function (cb, err) { - var _this = this; - try { - // check if there is already a recognizer - if (!!this.privConversationRecognizer) { - this.handleError(new Error(this.privErrors.permissionDeniedStart), err); - } - // check if there is conversation data available - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedConnect); - // connect to the conversation websocket - this.privParticipants.meId = this.privRoom.participantId; - this.privConversationRecognizer = Exports_1.ConversationRecognizerFactory.fromConfig(this, this.privConfig); - // Because ConversationTranslator manually sets up and manages the connection, Conversation - // has to forward serviceRecognizer connection events that usually get passed automatically - this.privConversationRecognizer.connected = this.onConnected; - this.privConversationRecognizer.disconnected = this.onDisconnected; - this.privConversationRecognizer.canceled = this.onCanceled; - this.privConversationRecognizer.participantUpdateCommandReceived = this.onParticipantUpdateCommandReceived; - this.privConversationRecognizer.lockRoomCommandReceived = this.onLockRoomCommandReceived; - this.privConversationRecognizer.muteAllCommandReceived = this.onMuteAllCommandReceived; - this.privConversationRecognizer.participantJoinCommandReceived = this.onParticipantJoinCommandReceived; - this.privConversationRecognizer.participantLeaveCommandReceived = this.onParticipantLeaveCommandReceived; - this.privConversationRecognizer.translationReceived = this.onTranslationReceived; - this.privConversationRecognizer.participantsListReceived = this.onParticipantsListReceived; - this.privConversationRecognizer.conversationExpiration = this.onConversationExpiration; - this.privConversationRecognizer.connect(this.privRoom.token, (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); } - catch (error) { - this.handleError(error, err); + catch (e) { + if (!!err) { + err(e); + } } - }; - /** - * Join a conversation as a participant. - * @param { IParticipant } participant - participant to add - * @param cb - * @param err - */ - ConversationImpl.prototype.addParticipantAsync = function (participant, cb, err) { - Contracts_1.Contracts.throwIfNullOrUndefined(participant, "Participant"); - Exports_2.marshalPromiseToCallbacks(this.addParticipantImplAsync(participant), cb, err); - }; + } /** - * Join a conversation as a participant. - * @param conversation - * @param nickname - * @param lang - * @param cb - * @param err + * stops audio and clears the buffers */ - ConversationImpl.prototype.joinConversationAsync = function (conversationId, nickname, lang, cb, err) { - var _this = this; - try { - // TODO - // if (!!this.privConversationRecognizer) { - // throw new Error(this.privErrors.permissionDeniedStart); - // } - Contracts_1.Contracts.throwIfNullOrWhitespace(conversationId, this.privErrors.invalidArgs.replace("{arg}", "conversationId")); - Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname")); - Contracts_1.Contracts.throwIfNullOrWhitespace(lang, this.privErrors.invalidArgs.replace("{arg}", "language")); - // join the conversation - this.privManager.createOrJoin(this.privProperties, conversationId, (function (room) { - Contracts_1.Contracts.throwIfNullOrUndefined(room, _this.privErrors.permissionDeniedConnect); - _this.privRoom = room; - _this.privConfig.authorizationToken = room.cognitiveSpeechAuthToken; - // join callback + stopAudio(cb, err) { + if (this.audioContext !== null) { + this.samples = new Float32Array(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + clearInterval(this.autoUpdateBufferTimer); + this.audioContext.close().then(() => { if (!!cb) { - cb(room.cognitiveSpeechAuthToken); + cb(); } - }), (function (error) { - _this.handleError(error, err); - })); - } - catch (error) { - this.handleError(error, err); - } - }; - /** - * Deletes a conversation - * @param cb - * @param err - */ - ConversationImpl.prototype.deleteConversationAsync = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.deleteConversationImplAsync(), cb, err); - }; - ConversationImpl.prototype.deleteConversationImplAsync = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - Contracts_1.Contracts.throwIfNullOrUndefined(this.privProperties, this.privErrors.permissionDeniedConnect); - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.token, this.privErrors.permissionDeniedConnect); - return [4 /*yield*/, this.privManager.leave(this.privProperties, this.privRoom.token)]; - case 1: - _a.sent(); - this.dispose(); - return [2 /*return*/]; + }, (error) => { + if (!!err) { + err(error); } }); - }); - }; - /** - * Issues a request to close the client websockets - * @param cb - * @param err - */ - ConversationImpl.prototype.endConversationAsync = function (cb, err) { - Exports_2.marshalPromiseToCallbacks(this.endConversationImplAsync(), cb, err); - }; - ConversationImpl.prototype.endConversationImplAsync = function () { - return this.close(true); - }; - /** - * Issues a request to lock the conversation - * @param cb - * @param err - */ - ConversationImpl.prototype.lockConversationAsync = function (cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - if (!this.canSendAsHost) { - this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "lock")), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getLockCommand(true), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); - } - catch (error) { - this.handleError(error, err); - } - }; - /** - * Issues a request to mute the conversation - * @param cb - * @param err - */ - ConversationImpl.prototype.muteAllParticipantsAsync = function (cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversationRecognizer, this.privErrors.permissionDeniedSend); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - // check the user's permissions - if (!this.canSendAsHost) { - this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "mute")), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMuteAllCommand(true), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); + this.audioContext = null; } - catch (error) { - this.handleError(error, err); + } + init(audioFormat) { + this.audioFormat = audioFormat; + this.samples = new Float32Array(); + } + ensureInitializedContext() { + if (this.audioContext === null) { + this.createAudioContext(); + const timerPeriod = 200; + this.autoUpdateBufferTimer = setInterval(() => { + this.updateAudioBuffer(); + }, timerPeriod); } - }; - /** - * Issues a request to mute a participant in the conversation - * @param userId - * @param cb - * @param err - */ - ConversationImpl.prototype.muteParticipantAsync = function (userId, cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace("{arg}", "userId")); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - // check the connection is open (host + participant can perform the mute command) - if (!this.canSend) { - this.handleError(new Error(this.privErrors.permissionDeniedSend), err); - } - // if not host, check the participant is not muting another participant - if (!this.me.isHost && this.me.id !== userId) { - this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "mute")), err); - } - // check the user exists - var exists = this.privParticipants.getParticipantIndex(userId); - if (exists === -1) { - this.handleError(new Error(this.privErrors.invalidParticipantRequest), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMuteCommand(userId, true), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); + } + createAudioContext() { + // new ((window as any).AudioContext || (window as any).webkitAudioContext)(); + this.audioContext = AudioStreamFormat_js_1.AudioStreamFormatImpl.getAudioContext(); + // TODO: Various examples shows this gain node, it does not seem to be needed unless we plan + // to control the volume, not likely + this.gainNode = this.audioContext.createGain(); + this.gainNode.gain.value = 1; + this.gainNode.connect(this.audioContext.destination); + this.startTime = this.audioContext.currentTime; + } + formatAudioData(audioData) { + switch (this.audioFormat.bitsPerSample) { + case 8: + return this.formatArrayBuffer(new Int8Array(audioData), 128); + case 16: + return this.formatArrayBuffer(new Int16Array(audioData), 32768); + case 32: + return this.formatArrayBuffer(new Int32Array(audioData), 2147483648); + default: + throw new Error_js_1.InvalidOperationError("Only WAVE_FORMAT_PCM (8/16/32 bps) format supported at this time"); } - catch (error) { - this.handleError(error, err); + } + formatArrayBuffer(audioData, maxValue) { + const float32Data = new Float32Array(audioData.length); + for (let i = 0; i < audioData.length; i++) { + float32Data[i] = audioData[i] / maxValue; } - }; - /** - * Issues a request to remove a participant from the conversation - * @param userId - * @param cb - * @param err - */ - ConversationImpl.prototype.removeParticipantAsync = function (userId, cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - if (!!this.privTranscriberRecognizer && userId.hasOwnProperty("id")) { - // Assume this is a transcription participant - Exports_2.marshalPromiseToCallbacks(this.removeParticipantImplAsync(userId), cb, err); - } - else { - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - if (!this.canSendAsHost) { - this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "remove")), err); - } - var participantId_1 = ""; - if (typeof userId === "string") { - participantId_1 = userId; - } - else if (userId.hasOwnProperty("id")) { - var participant = userId; - participantId_1 = participant.id; - } - else if (userId.hasOwnProperty("userId")) { - var user = userId; - participantId_1 = user.userId; - } - Contracts_1.Contracts.throwIfNullOrWhitespace(participantId_1, this.privErrors.invalidArgs.replace("{arg}", "userId")); - // check the participant exists - var index = this.participants.findIndex(function (p) { return p.id === participantId_1; }); - if (index === -1) { - this.handleError(new Error(this.privErrors.invalidParticipantRequest), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getEjectCommand(participantId_1), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); + return float32Data; + } + updateAudioBuffer() { + if (this.samples.length === 0) { + return; + } + const channelCount = this.audioFormat.channels; + const bufferSource = this.audioContext.createBufferSource(); + const frameCount = this.samples.length / channelCount; + const audioBuffer = this.audioContext.createBuffer(channelCount, frameCount, this.audioFormat.samplesPerSec); + // TODO: Should we do the conversion in the pushAudioSample instead? + for (let channel = 0; channel < channelCount; channel++) { + // Fill in individual channel data + let channelOffset = channel; + const audioData = audioBuffer.getChannelData(channel); + for (let i = 0; i < this.samples.length; i++, channelOffset += channelCount) { + audioData[i] = this.samples[channelOffset]; } } - catch (error) { - this.handleError(error, err); + if (this.startTime < this.audioContext.currentTime) { + this.startTime = this.audioContext.currentTime; + } + bufferSource.buffer = audioBuffer; + bufferSource.connect(this.gainNode); + bufferSource.start(this.startTime); + // Make sure we play the next sample after the current one. + this.startTime += audioBuffer.duration; + // Clear the samples for the next pushed data. + this.samples = new Float32Array(); + } + async playAudio(audioData) { + if (this.audioContext === null) { + this.createAudioContext(); } - }; + const source = this.audioContext.createBufferSource(); + const destination = this.audioContext.destination; + await this.audioContext.decodeAudioData(audioData, (newBuffer) => { + source.buffer = newBuffer; + source.connect(destination); + source.start(0); + }); + } +} +exports.BaseAudioPlayer = BaseAudioPlayer; + + + +/***/ }), +/* 143 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConnectionMessageEventArgs = void 0; +class ConnectionMessageEventArgs { + constructor(message) { + this.privConnectionMessage = message; + } /** - * Issues a request to unlock the conversation - * @param cb - * @param err + * Gets the associated with this . */ - ConversationImpl.prototype.unlockConversationAsync = function (cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - if (!this.canSendAsHost) { - this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "unlock")), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getLockCommand(false), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); - } - catch (error) { - this.handleError(error, err); - } - }; + get message() { + return this.privConnectionMessage; + } /** - * Issues a request to unmute all participants in the conversation - * @param cb - * @param err + * Returns a string that represents the connection message event. */ - ConversationImpl.prototype.unmuteAllParticipantsAsync = function (cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - if (!this.canSendAsHost) { - this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "unmute all")), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMuteAllCommand(false), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); - } - catch (error) { - this.handleError(error, err); - } - }; + toString() { + return "Message: " + this.privConnectionMessage.toString(); + } +} +exports.ConnectionMessageEventArgs = ConnectionMessageEventArgs; + + + +/***/ }), +/* 144 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AutoDetectSourceLanguageConfig = void 0; +const Exports_js_1 = __webpack_require__(2); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_2 = __webpack_require__(85); +const LanguageIdMode_js_1 = __webpack_require__(145); +/** + * Language auto detect configuration. + * @class AutoDetectSourceLanguageConfig + * Added in version 1.13.0. + */ +class AutoDetectSourceLanguageConfig { + constructor() { + this.privProperties = new Exports_js_2.PropertyCollection(); + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_LanguageIdMode, "AtStart"); + this.privLanguageIdMode = LanguageIdMode_js_1.LanguageIdMode.AtStart; + } /** - * Issues a request to unmute a participant in the conversation - * @param userId - * @param cb - * @param err + * @member AutoDetectSourceLanguageConfig.fromOpenRange + * @function + * @public + * Only [[SpeechSynthesizer]] supports source language auto detection from open range, + * for [[Recognizer]], please use AutoDetectSourceLanguageConfig with specific source languages. + * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig + * @summary Creates an instance of the AutoDetectSourceLanguageConfig with open range. */ - ConversationImpl.prototype.unmuteParticipantAsync = function (userId, cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace("{arg}", "userId")); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - // check the connection is open (host + participant can perform the mute command) - if (!this.canSend) { - this.handleError(new Error(this.privErrors.permissionDeniedSend), err); - } - // if not host, check the participant is not muting another participant - if (!this.me.isHost && this.me.id !== userId) { - this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "mute")), err); - } - // check the user exists - var exists = this.privParticipants.getParticipantIndex(userId); - if (exists === -1) { - this.handleError(new Error(this.privErrors.invalidParticipantRequest), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMuteCommand(userId, false), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); - } - catch (error) { - this.handleError(error, err); - } - }; + static fromOpenRange() { + const config = new AutoDetectSourceLanguageConfig(); + config.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, Exports_js_1.AutoDetectSourceLanguagesOpenRangeOptionName); + config.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, "en-US"); + return config; + } /** - * Send a text message - * @param message - * @param cb - * @param err + * @member AutoDetectSourceLanguageConfig.fromLanguages + * @function + * @public + * @param {string[]} languages Comma-separated string of languages (eg. "en-US,fr-FR") to populate properties of config. + * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig + * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given languages. */ - ConversationImpl.prototype.sendTextMessageAsync = function (message, cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace("{arg}", "message")); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - if (!this.canSend) { - this.handleError(new Error(this.privErrors.permissionDeniedSend), err); - } - // TODO: is a max length check required? - if (message.length > this.privTextMessageMaxLength) { - this.handleError(new Error(this.privErrors.invalidArgs.replace("{arg}", "message length")), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMessageCommand(message), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); - } - catch (error) { - this.handleError(error, err); - } - }; + static fromLanguages(languages) { + Contracts_js_1.Contracts.throwIfArrayEmptyOrWhitespace(languages, "languages"); + const config = new AutoDetectSourceLanguageConfig(); + config.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, languages.join()); + return config; + } /** - * Change nickname - * @param message - * @param cb - * @param err + * @member AutoDetectSourceLanguageConfig.fromSourceLanguageConfigs + * @function + * @public + * @param {SourceLanguageConfig[]} configs SourceLanguageConfigs to populate properties of config. + * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig + * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given SourceLanguageConfigs. */ - ConversationImpl.prototype.changeNicknameAsync = function (nickname, cb, err) { - var _this = this; - var _a; - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed()); - Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname")); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend); - if (!this.canSend) { - this.handleError(new Error(this.privErrors.permissionDeniedSend), err); - } - (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getChangeNicknameCommand(nickname), (function () { - _this.handleCallback(cb, err); - }), (function (error) { - _this.handleError(error, err); - })); - } - catch (error) { - this.handleError(error, err); - } - }; - ConversationImpl.prototype.isDisposed = function () { - return this.privIsDisposed; - }; - ConversationImpl.prototype.dispose = function (reason) { - var _a; - if (this.isDisposed) { - return; + static fromSourceLanguageConfigs(configs) { + if (configs.length < 1) { + throw new Error("Expected non-empty SourceLanguageConfig array."); } - this.privIsDisposed = true; - (_a = this.config) === null || _a === void 0 ? void 0 : _a.close(); - this.privConfig = undefined; - this.privLanguage = undefined; - this.privProperties = undefined; - this.privRoom = undefined; - this.privToken = undefined; - this.privManager = undefined; - this.privIsConnected = false; - this.privIsReady = false; - this.privParticipants = undefined; - }; - Object.defineProperty(ConversationImpl.prototype, "transcriberRecognizer", { - get: function () { - return this.privTranscriberRecognizer; - }, - enumerable: false, - configurable: true - }); - ConversationImpl.prototype.connectTranscriberRecognizer = function (recognizer) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!!this.privTranscriberRecognizer) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privTranscriberRecognizer.close()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - this.privTranscriberRecognizer = recognizer; - this.privTranscriberRecognizer.conversation = this; - return [2 /*return*/]; - } - }); - }); - }; - Object.defineProperty(ConversationImpl.prototype, "conversationInfo", { - get: function () { - var convId = this.conversationId; - var p = this.participants.map(function (part) { - return { - id: part.id, - preferredLanguage: part.preferredLanguage, - voice: part.voice - }; - }); - var props = {}; - for (var _i = 0, _a = Exports_1.ConversationConnectionConfig.transcriptionEventKeys; _i < _a.length; _i++) { - var key = _a[_i]; - var val = this.properties.getProperty(key, ""); - if (val !== "") { - props[key] = val; - } - } - var info = { id: convId, participants: p, conversationProperties: props }; - return info; - }, - enumerable: false, - configurable: true - }); - ConversationImpl.prototype.getKeepAlive = function () { - var nickname = (!!this.me) ? this.me.displayName : "default_nickname"; - return JSON.stringify({ - // tslint:disable-next-line: object-literal-shorthand - id: "0", - nickname: nickname, - participantId: this.privRoom.participantId, - roomId: this.privRoom.roomId, - type: Exports_1.ConversationTranslatorMessageTypes.keepAlive - }); - }; - ConversationImpl.prototype.addParticipantImplAsync = function (participant) { - var newParticipant = this.privParticipants.addOrUpdateParticipant(participant); - if (newParticipant !== undefined) { - if (!!this.privTranscriberRecognizer) { - var conversationInfo = this.conversationInfo; - conversationInfo.participants = [participant]; - return this.privTranscriberRecognizer.pushConversationEvent(conversationInfo, "join"); + const autoConfig = new AutoDetectSourceLanguageConfig(); + const langs = []; + configs.forEach((config) => { + langs.push(config.language); + if (config.endpointId !== undefined && config.endpointId !== "") { + const customProperty = config.language + Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId.toString(); + autoConfig.properties.setProperty(customProperty, config.endpointId); } - } - }; - ConversationImpl.prototype.removeParticipantImplAsync = function (participant) { - this.privParticipants.deleteParticipant(participant.id); - var conversationInfo = this.conversationInfo; - conversationInfo.participants = [participant]; - return this.privTranscriberRecognizer.pushConversationEvent(conversationInfo, "leave"); - }; - ConversationImpl.prototype.close = function (dispose) { - var _a, _b; - return __awaiter(this, void 0, void 0, function () { - var e_2; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - _c.trys.push([0, 2, , 3]); - this.privIsConnected = false; - return [4 /*yield*/, ((_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.close())]; - case 1: - _c.sent(); - this.privConversationRecognizer = undefined; - (_b = this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.dispose(); - return [3 /*break*/, 3]; - case 2: - e_2 = _c.sent(); - // ignore error - throw e_2; - case 3: - if (dispose) { - this.dispose(); - } - return [2 /*return*/]; - } - }); }); - }; - Object.defineProperty(ConversationImpl.prototype, "canSend", { - /** Helpers */ - get: function () { - var _a; - return this.privIsConnected && !((_a = this.privParticipants.me) === null || _a === void 0 ? void 0 : _a.isMuted); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationImpl.prototype, "canSendAsHost", { - get: function () { - var _a; - return this.privIsConnected && ((_a = this.privParticipants.me) === null || _a === void 0 ? void 0 : _a.isHost); - }, - enumerable: false, - configurable: true - }); - ConversationImpl.prototype.handleCallback = function (cb, err) { - if (!!cb) { - try { - cb(); - } - catch (e) { - if (!!err) { - err(e); - } - } - cb = undefined; - } - }; - ConversationImpl.prototype.handleError = function (error, err) { - if (!!err) { - if (error instanceof Error) { - var typedError = error; - err(typedError.name + ": " + typedError.message); - } - else { - err(error); - } + autoConfig.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, langs.join()); + return autoConfig; + } + /** + * @member AutoDetectSourceLanguageConfig.prototype.properties + * @function + * @public + * @return {PropertyCollection} Properties of the config. + * @summary Gets an auto detected language config properties + */ + get properties() { + return this.privProperties; + } + /** + * @member AutoDetectSourceLanguageConfig.prototype.mode + * @function + * @public + * @param {LanguageIdMode} mode LID mode desired. + * @summary Sets LID operation to desired mode + */ + set mode(mode) { + if (mode === LanguageIdMode_js_1.LanguageIdMode.Continuous) { + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "2"); + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_LanguageIdMode, "Continuous"); } - }; - /** Participant Helpers */ - ConversationImpl.prototype.toParticipants = function (includeHost) { - var _this = this; - var participants = this.privParticipants.participants.map(function (p) { - return _this.toParticipant(p); - }); - if (!includeHost) { - return participants.filter(function (p) { return p.isHost === false; }); + else { // LanguageIdMode.AtStart + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "1"); + this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_LanguageIdMode, "AtStart"); } - else { - return participants; - } - }; - ConversationImpl.prototype.toParticipant = function (p) { - return new Exports_3.Participant(p.id, p.avatar, p.displayName, p.isHost, p.isMuted, p.isUsingTts, p.preferredLanguage, p.voice); - }; - ConversationImpl.prototype.getMuteAllCommand = function (isMuted) { - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId"); - return JSON.stringify({ - command: Exports_1.ConversationTranslatorCommandTypes.setMuteAll, - // tslint:disable-next-line: object-literal-shorthand - participantId: this.privRoom.participantId, - roomid: this.privRoom.roomId, - type: Exports_1.ConversationTranslatorMessageTypes.participantCommand, - value: isMuted - }); - }; - ConversationImpl.prototype.getMuteCommand = function (participantId, isMuted) { - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(participantId, "participantId"); - return JSON.stringify({ - command: Exports_1.ConversationTranslatorCommandTypes.setMute, - // tslint:disable-next-line: object-literal-shorthand - participantId: participantId, - roomid: this.privRoom.roomId, - type: Exports_1.ConversationTranslatorMessageTypes.participantCommand, - value: isMuted - }); - }; - ConversationImpl.prototype.getLockCommand = function (isLocked) { - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId"); - return JSON.stringify({ - command: Exports_1.ConversationTranslatorCommandTypes.setLockState, - // tslint:disable-next-line: object-literal-shorthand - participantId: this.privRoom.participantId, - roomid: this.privRoom.roomId, - type: Exports_1.ConversationTranslatorMessageTypes.participantCommand, - value: isLocked - }); - }; - ConversationImpl.prototype.getEjectCommand = function (participantId) { - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(participantId, "participantId"); - return JSON.stringify({ - command: Exports_1.ConversationTranslatorCommandTypes.ejectParticipant, - // tslint:disable-next-line: object-literal-shorthand - participantId: participantId, - roomid: this.privRoom.roomId, - type: Exports_1.ConversationTranslatorMessageTypes.participantCommand, - }); - }; - ConversationImpl.prototype.getChangeNicknameCommand = function (nickname) { - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, "nickname"); - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId"); - return JSON.stringify({ - command: Exports_1.ConversationTranslatorCommandTypes.changeNickname, - nickname: nickname, - // tslint:disable-next-line: object-literal-shorthand - participantId: this.privRoom.participantId, - roomid: this.privRoom.roomId, - type: Exports_1.ConversationTranslatorMessageTypes.participantCommand, - value: nickname - }); - }; - ConversationImpl.prototype.getMessageCommand = function (message) { - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId"); - Contracts_1.Contracts.throwIfNullOrWhitespace(message, "message"); - return JSON.stringify({ - // tslint:disable-next-line: object-literal-shorthand - participantId: this.privRoom.participantId, - roomId: this.privRoom.roomId, - text: message, - type: Exports_1.ConversationTranslatorMessageTypes.instantMessage - }); - }; - return ConversationImpl; -}(Conversation)); -exports.ConversationImpl = ConversationImpl; + this.privLanguageIdMode = mode; + } +} +exports.AutoDetectSourceLanguageConfig = AutoDetectSourceLanguageConfig; /***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { +/* 145 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationCommon = void 0; -var ConversationCommon = /** @class */ (function () { - function ConversationCommon(audioConfig) { - this.privAudioConfig = audioConfig; - } - ConversationCommon.prototype.handleCallback = function (cb, err) { - if (!!cb) { - try { - cb(); - } - catch (e) { - if (!!err) { - err(e); - } - } - cb = undefined; - } - }; - ConversationCommon.prototype.handleError = function (error, err) { - if (!!err) { - if (error instanceof Error) { - var typedError = error; - err(typedError.name + ": " + typedError.message); - } - else { - err(error); - } - } - }; - return ConversationCommon; -}()); -exports.ConversationCommon = ConversationCommon; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LanguageIdMode = void 0; +/** + * Language Identification mode + * @class LanguageIdMode + */ +var LanguageIdMode; +(function (LanguageIdMode) { + /** + * Detect language at audio start + * @member LanguageIdMode.AtStart + */ + LanguageIdMode[LanguageIdMode["AtStart"] = 0] = "AtStart"; + /** + * Continuously detect language + * @member LanguageIdMode.Continuous + */ + LanguageIdMode[LanguageIdMode["Continuous"] = 1] = "Continuous"; +})(LanguageIdMode = exports.LanguageIdMode || (exports.LanguageIdMode = {})); /***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { +/* 146 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationExpirationEventArgs = void 0; -var Exports_1 = __webpack_require__(61); -var ConversationExpirationEventArgs = /** @class */ (function (_super) { - __extends(ConversationExpirationEventArgs, _super); - function ConversationExpirationEventArgs(expirationTime, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privExpirationTime = expirationTime; - return _this; - } - Object.defineProperty(ConversationExpirationEventArgs.prototype, "expirationTime", { - /** How much longer until the conversation expires (in minutes). */ - get: function () { - return this.privExpirationTime; - }, - enumerable: false, - configurable: true - }); - return ConversationExpirationEventArgs; -}(Exports_1.SessionEventArgs)); -exports.ConversationExpirationEventArgs = ConversationExpirationEventArgs; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AutoDetectSourceLanguageResult = void 0; +const Contracts_js_1 = __webpack_require__(70); +/** + * Output format + * @class AutoDetectSourceLanguageResult + */ +class AutoDetectSourceLanguageResult { + constructor(language, languageDetectionConfidence) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(language, "language"); + Contracts_js_1.Contracts.throwIfNullOrUndefined(languageDetectionConfidence, "languageDetectionConfidence"); + this.privLanguage = language; + this.privLanguageDetectionConfidence = languageDetectionConfidence; + } + /** + * Creates an instance of AutoDetectSourceLanguageResult object from a SpeechRecognitionResult instance. + * @member AutoDetectSourceLanguageResult.fromResult + * @function + * @public + * @param {SpeechRecognitionResult} result - The recognition result. + * @returns {AutoDetectSourceLanguageResult} AutoDetectSourceLanguageResult object being created. + */ + static fromResult(result) { + return new AutoDetectSourceLanguageResult(result.language, result.languageDetectionConfidence); + } + /** + * Creates an instance of AutoDetectSourceLanguageResult object from a ConversationTranscriptionResult instance. + * @member AutoDetectSourceLanguageResult.fromConversationTranscriptionResult + * @function + * @public + * @param {ConversationTranscriptionResult} result - The transcription result. + * @returns {AutoDetectSourceLanguageResult} AutoDetectSourceLanguageResult object being created. + */ + static fromConversationTranscriptionResult(result) { + return new AutoDetectSourceLanguageResult(result.language, result.languageDetectionConfidence); + } + get language() { + return this.privLanguage; + } + get languageDetectionConfidence() { + return this.privLanguageDetectionConfidence; + } +} +exports.AutoDetectSourceLanguageResult = AutoDetectSourceLanguageResult; /***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { +/* 147 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationParticipantsChangedEventArgs = void 0; -var Exports_1 = __webpack_require__(61); -var ConversationParticipantsChangedEventArgs = /** @class */ (function (_super) { - __extends(ConversationParticipantsChangedEventArgs, _super); - function ConversationParticipantsChangedEventArgs(reason, participants, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privReason = reason; - _this.privParticipant = participants; - return _this; - } - Object.defineProperty(ConversationParticipantsChangedEventArgs.prototype, "reason", { - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationParticipantsChangedEventArgs.prototype, "participants", { - get: function () { - return this.privParticipant; - }, - enumerable: false, - configurable: true - }); - return ConversationParticipantsChangedEventArgs; -}(Exports_1.SessionEventArgs)); -exports.ConversationParticipantsChangedEventArgs = ConversationParticipantsChangedEventArgs; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SourceLanguageConfig = void 0; +const Contracts_js_1 = __webpack_require__(70); +/** + * Source Language configuration. + * @class SourceLanguageConfig + */ +class SourceLanguageConfig { + constructor(language, endpointId) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(language, "language"); + this.privLanguage = language; + this.privEndpointId = endpointId; + } + /** + * @member SourceLanguageConfig.fromLanguage + * @function + * @public + * @param {string} language language (eg. "en-US") value of config. + * @param {string?} endpointId endpointId of model bound to given language of config. + * @return {SourceLanguageConfig} Instance of SourceLanguageConfig + * @summary Creates an instance of the SourceLanguageConfig with the given language and optional endpointId. + * Added in version 1.13.0. + */ + static fromLanguage(language, endpointId) { + return new SourceLanguageConfig(language, endpointId); + } + get language() { + return this.privLanguage; + } + get endpointId() { + return this.privEndpointId; + } +} +exports.SourceLanguageConfig = SourceLanguageConfig; /***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { +/* 148 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranslationCanceledEventArgs = void 0; -var CancellationEventArgsBase_1 = __webpack_require__(90); -var ConversationTranslationCanceledEventArgs = /** @class */ (function (_super) { - __extends(ConversationTranslationCanceledEventArgs, _super); - function ConversationTranslationCanceledEventArgs() { - return _super !== null && _super.apply(this, arguments) || this; - } - return ConversationTranslationCanceledEventArgs; -}(CancellationEventArgsBase_1.CancellationEventArgsBase)); -exports.ConversationTranslationCanceledEventArgs = ConversationTranslationCanceledEventArgs; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationTranscriptionResult = exports.MeetingTranscriber = exports.MeetingTranscriptionCanceledEventArgs = exports.MeetingImpl = exports.Meeting = exports.User = exports.Participant = exports.ConversationTranscriber = void 0; +var ConversationTranscriber_js_1 = __webpack_require__(149); +Object.defineProperty(exports, "ConversationTranscriber", ({ enumerable: true, get: function () { return ConversationTranscriber_js_1.ConversationTranscriber; } })); +var IParticipant_js_1 = __webpack_require__(150); +Object.defineProperty(exports, "Participant", ({ enumerable: true, get: function () { return IParticipant_js_1.Participant; } })); +Object.defineProperty(exports, "User", ({ enumerable: true, get: function () { return IParticipant_js_1.User; } })); +var Meeting_js_1 = __webpack_require__(151); +Object.defineProperty(exports, "Meeting", ({ enumerable: true, get: function () { return Meeting_js_1.Meeting; } })); +Object.defineProperty(exports, "MeetingImpl", ({ enumerable: true, get: function () { return Meeting_js_1.MeetingImpl; } })); +var MeetingTranscriptionCanceledEventArgs_js_1 = __webpack_require__(152); +Object.defineProperty(exports, "MeetingTranscriptionCanceledEventArgs", ({ enumerable: true, get: function () { return MeetingTranscriptionCanceledEventArgs_js_1.MeetingTranscriptionCanceledEventArgs; } })); +var MeetingTranscriber_js_1 = __webpack_require__(153); +Object.defineProperty(exports, "MeetingTranscriber", ({ enumerable: true, get: function () { return MeetingTranscriber_js_1.MeetingTranscriber; } })); +var ConversationTranscriptionResult_js_1 = __webpack_require__(154); +Object.defineProperty(exports, "ConversationTranscriptionResult", ({ enumerable: true, get: function () { return ConversationTranscriptionResult_js_1.ConversationTranscriptionResult; } })); /***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { +/* 149 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranslationEventArgs = void 0; -var Exports_1 = __webpack_require__(61); -var ConversationTranslationEventArgs = /** @class */ (function (_super) { - __extends(ConversationTranslationEventArgs, _super); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationTranscriber = void 0; +const Exports_js_1 = __webpack_require__(2); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +const Exports_js_2 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); +/** + * Performs speech recognition with speaker separation from microphone, file, or other audio input streams, and gets transcribed text as result. + * @class ConversationTranscriber + */ +class ConversationTranscriber extends Exports_js_3.Recognizer { /** - * Creates and initializes an instance of this class. + * ConversationTranscriber constructor. * @constructor - * @param {ConversationTranslationResult} result - The translation recognition result. - * @param {number} offset - The offset. - * @param {string} sessionId - The session id. + * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer + * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer */ - function ConversationTranslationEventArgs(result, offset, sessionId) { - var _this = _super.call(this, offset, sessionId) || this; - _this.privResult = result; - return _this; - } - Object.defineProperty(ConversationTranslationEventArgs.prototype, "result", { - /** - * Specifies the recognition result. - * @returns {ConversationTranslationResult} the recognition result. - */ - get: function () { - return this.privResult; - }, - enumerable: false, - configurable: true - }); - return ConversationTranslationEventArgs; -}(Exports_1.RecognitionEventArgs)); -exports.ConversationTranslationEventArgs = ConversationTranslationEventArgs; + constructor(speechConfig, audioConfig) { + const speechConfigImpl = speechConfig; + Contracts_js_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(speechConfigImpl.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]); + super(audioConfig, speechConfigImpl.properties, new Exports_js_1.ConversationTranscriberConnectionFactory(), speechConfig.tokenCredential); + this.privProperties.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "2"); + this.privDisposedRecognizer = false; + } + /** + * ConversationTranscriber constructor. + * @constructor + * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer + * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the recognizer + * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer + */ + static FromConfig(speechConfig, autoDetectSourceLanguageConfig, audioConfig) { + const speechConfigImpl = speechConfig; + autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties); + const recognizer = new ConversationTranscriber(speechConfig, audioConfig); + return recognizer; + } + /** + * Gets the endpoint id of a customized speech model that is used for transcription. + * @member ConversationTranscriber.prototype.endpointId + * @function + * @public + * @returns {string} the endpoint id of a customized speech model that is used for speech recognition. + */ + get endpointId() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_EndpointId, "00000000-0000-0000-0000-000000000000"); + } + /** + * Gets the authorization token used to communicate with the service. + * @member ConversationTranscriber.prototype.authorizationToken + * @function + * @public + * @returns {string} Authorization token. + */ + get authorizationToken() { + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token); + } + /** + * Gets/Sets the authorization token used to communicate with the service. + * @member ConversationTranscriber.prototype.authorizationToken + * @function + * @public + * @param {string} token - Authorization token. + */ + set authorizationToken(token) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token"); + this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, token); + } + /** + * Gets the spoken language of transcription. + * @member ConversationTranscriber.prototype.speechRecognitionLanguage + * @function + * @public + * @returns {string} The spoken language of transcription. + */ + get speechRecognitionLanguage() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage); + } + /** + * Gets the output format of transcription. + * @member ConversationTranscriber.prototype.outputFormat + * @function + * @public + * @returns {OutputFormat} The output format of transcription. + */ + get outputFormat() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + if (this.properties.getProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]) === Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]) { + return Exports_js_3.OutputFormat.Simple; + } + else { + return Exports_js_3.OutputFormat.Detailed; + } + } + /** + * The collection of properties and their values defined for this conversation transcriber. + * @member ConversationTranscriber.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechRecognizer. + */ + get properties() { + return this.privProperties; + } + /** + * Starts conversation transcription, until stopTranscribingAsync() is called. + * User must subscribe to events to receive transcription results. + * @member ConversationTranscriber.prototype.startTranscribingAsync + * @function + * @public + * @param cb - Callback invoked once the transcription has started. + * @param err - Callback invoked in case of an error. + */ + startTranscribingAsync(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(PhraseDetectionContext_js_1.RecognitionMode.Conversation), cb, err); + } + /** + * Stops conversation transcription. + * @member ConversationTranscriber.prototype.stopTranscribingAsync + * @function + * @public + * @param cb - Callback invoked once the transcription has stopped. + * @param err - Callback invoked in case of an error. + */ + stopTranscribingAsync(cb, err) { + (0, Exports_js_2.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(), cb, err); + } + /** + * closes all external resources held by an instance of this class. + * @member ConversationTranscriber.prototype.close + * @function + * @public + */ + close(cb, errorCb) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb); + } + /** + * Disposes any resources held by the object. + * @member SpeechRecognizer.prototype.dispose + * @function + * @public + * @param {boolean} disposing - true if disposing the object. + */ + async dispose(disposing) { + if (this.privDisposedRecognizer) { + return; + } + if (disposing) { + this.privDisposedRecognizer = true; + await this.implRecognizerStop(); + } + await super.dispose(disposing); + } + createRecognizerConfig(speechConfig) { + return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties); + } + createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) { + const configImpl = audioConfig; + recognizerConfig.isSpeakerDiarizationEnabled = true; + return new Exports_js_1.ConversationTranscriptionServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this); + } +} +exports.ConversationTranscriber = ConversationTranscriber; /***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { +/* 150 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranslationResult = void 0; -var TranslationRecognitionResult_1 = __webpack_require__(93); -var ConversationTranslationResult = /** @class */ (function (_super) { - __extends(ConversationTranslationResult, _super); - function ConversationTranslationResult(participantId, translations, originalLanguage, resultId, reason, text, duration, offset, errorDetails, json, properties) { - var _this = _super.call(this, translations, resultId, reason, text, duration, offset, errorDetails, json, properties) || this; - _this.privId = participantId; - _this.privOrigLang = originalLanguage; - return _this; - } - Object.defineProperty(ConversationTranslationResult.prototype, "participantId", { - /** - * The unique identifier for the participant this result is for. - */ - get: function () { - return this.privId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationTranslationResult.prototype, "originalLang", { - /** - * The original language this result was in. - */ - get: function () { - return this.privOrigLang; - }, - enumerable: false, - configurable: true - }); - return ConversationTranslationResult; -}(TranslationRecognitionResult_1.TranslationRecognitionResult)); -exports.ConversationTranslationResult = ConversationTranslationResult; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Participant = exports.User = void 0; +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(85); +class User { + constructor(userId) { + this.privUserId = userId; + } + get userId() { + return this.privUserId; + } +} +exports.User = User; +class Participant { + constructor(id, preferredLanguage, voice) { + this.privId = id; + this.privPreferredLanguage = preferredLanguage; + this.privVoice = voice; + this.privProperties = new Exports_js_1.PropertyCollection(); + } + get id() { + return this.privId; + } + get preferredLanguage() { + return this.privPreferredLanguage; + } + get voice() { + return this.privVoice; + } + get properties() { + return this.privProperties; + } + static From(id, language, voice) { + return new Participant(id, language, voice); + } +} +exports.Participant = Participant; /***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { +/* 151 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MeetingImpl = exports.Meeting = void 0; +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); +class Meeting { + constructor() { + return; } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranslator = exports.SpeechState = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -var Conversation_1 = __webpack_require__(145); -var Exports_4 = __webpack_require__(144); -var SpeechState; -(function (SpeechState) { - SpeechState[SpeechState["Inactive"] = 0] = "Inactive"; - SpeechState[SpeechState["Connecting"] = 1] = "Connecting"; - SpeechState[SpeechState["Connected"] = 2] = "Connected"; -})(SpeechState = exports.SpeechState || (exports.SpeechState = {})); -// tslint:disable:max-classes-per-file -// child class of TranslationRecognizer meant only for use with ConversationTranslator -var ConversationTranslationRecognizer = /** @class */ (function (_super) { - __extends(ConversationTranslationRecognizer, _super); - function ConversationTranslationRecognizer(speechConfig, audioConfig, translator) { - var _this = _super.call(this, speechConfig, audioConfig) || this; - _this.privSpeechState = SpeechState.Inactive; - if (!!translator) { - _this.privTranslator = translator; - _this.sessionStarted = function () { - _this.privSpeechState = SpeechState.Connected; - }; - _this.sessionStopped = function () { - _this.privSpeechState = SpeechState.Inactive; - }; - _this.recognized = function (tr, e) { return __awaiter(_this, void 0, void 0, function () { - var _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!((_a = e.result) === null || _a === void 0 ? void 0 : _a.errorDetails)) return [3 /*break*/, 2]; - return [4 /*yield*/, this.cancelSpeech()]; - case 1: - _b.sent(); - // TODO: format the error message contained in 'errorDetails' - this.fireCancelEvent(e.result.errorDetails); - _b.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); }; - _this.canceled = function (r, e) { return __awaiter(_this, void 0, void 0, function () { - var error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(this.privSpeechState !== SpeechState.Inactive)) return [3 /*break*/, 4]; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, this.cancelSpeech()]; - case 2: - _a.sent(); - return [3 /*break*/, 4]; - case 3: - error_1 = _a.sent(); - this.privSpeechState = SpeechState.Inactive; - return [3 /*break*/, 4]; - case 4: return [2 /*return*/]; - } - }); - }); }; - } - return _this; - } - Object.defineProperty(ConversationTranslationRecognizer.prototype, "state", { - get: function () { - return this.privSpeechState; - }, - set: function (newState) { - this.privSpeechState = newState; - }, - enumerable: false, - configurable: true - }); - ConversationTranslationRecognizer.prototype.onConnection = function () { - this.privSpeechState = SpeechState.Connected; - }; - ConversationTranslationRecognizer.prototype.onDisconnection = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privSpeechState = SpeechState.Inactive; - return [4 /*yield*/, this.cancelSpeech()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - /** - * Fire a cancel event - * @param error - */ - ConversationTranslationRecognizer.prototype.fireCancelEvent = function (error) { - var _a, _b, _c; - try { - if (!!this.privTranslator.canceled) { - var cancelEvent = new Exports_4.ConversationTranslationCanceledEventArgs((_a = error === null || error === void 0 ? void 0 : error.reason) !== null && _a !== void 0 ? _a : Exports_3.CancellationReason.Error, (_b = error === null || error === void 0 ? void 0 : error.errorDetails) !== null && _b !== void 0 ? _b : error, (_c = error === null || error === void 0 ? void 0 : error.errorCode) !== null && _c !== void 0 ? _c : Exports_3.CancellationErrorCode.RuntimeError, undefined, error === null || error === void 0 ? void 0 : error.sessionId); - this.privTranslator.canceled(this.privTranslator, cancelEvent); - } - } - catch (e) { - // - } - }; - ConversationTranslationRecognizer.prototype.cancelSpeech = function () { - var _a; - return __awaiter(this, void 0, void 0, function () { - var e_1; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - this.stopContinuousRecognitionAsync(); - return [4 /*yield*/, ((_a = this.privReco) === null || _a === void 0 ? void 0 : _a.disconnect())]; - case 1: - _b.sent(); - this.privSpeechState = SpeechState.Inactive; - return [3 /*break*/, 3]; - case 2: - e_1 = _b.sent(); - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); - }; - return ConversationTranslationRecognizer; -}(Exports_3.TranslationRecognizer)); -/*** - * Join, leave or connect to a conversation. - */ -var ConversationTranslator = /** @class */ (function (_super) { - __extends(ConversationTranslator, _super); - function ConversationTranslator(audioConfig) { - var _this = _super.call(this, audioConfig) || this; - _this.privIsDisposed = false; - _this.privIsSpeaking = false; - _this.privErrors = Exports_1.ConversationConnectionConfig.restErrors; - _this.privPlaceholderKey = "abcdefghijklmnopqrstuvwxyz012345"; - _this.privPlaceholderRegion = "westus"; - _this.privProperties = new Exports_3.PropertyCollection(); - return _this; - } - Object.defineProperty(ConversationTranslator.prototype, "properties", { - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationTranslator.prototype, "speechRecognitionLanguage", { - get: function () { - return this.privSpeechRecognitionLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationTranslator.prototype, "participants", { - get: function () { - var _a; - return (_a = this.privConversation) === null || _a === void 0 ? void 0 : _a.participants; - }, - enumerable: false, - configurable: true - }); - ConversationTranslator.prototype.joinConversationAsync = function (conversation, nickname, param1, param2, param3) { - var _this = this; - try { - if (typeof conversation === "string") { - Contracts_1.Contracts.throwIfNullOrUndefined(conversation, this.privErrors.invalidArgs.replace("{arg}", "conversation id")); - Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname")); - if (!!this.privConversation) { - this.handleError(new Error(this.privErrors.permissionDeniedStart), param3); - } - var lang = param1; - if (lang === undefined || lang === null || lang === "") { - lang = Exports_1.ConversationConnectionConfig.defaultLanguageCode; - } - // create a placeholder config - this.privSpeechTranslationConfig = Exports_3.SpeechTranslationConfig.fromSubscription(this.privPlaceholderKey, this.privPlaceholderRegion); - this.privSpeechTranslationConfig.setProfanity(Exports_3.ProfanityOption.Masked); - this.privSpeechTranslationConfig.addTargetLanguage(lang); - this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage], lang); - this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.ConversationTranslator_Name], nickname); - var endpoint = this.privProperties.getProperty(Exports_3.PropertyId.ConversationTranslator_Host); - if (endpoint) { - this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.ConversationTranslator_Host], endpoint); - } - var speechEndpointHost = this.privProperties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Host); - if (speechEndpointHost) { - this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Host], speechEndpointHost); - } - // join the conversation - this.privConversation = new Conversation_1.ConversationImpl(this.privSpeechTranslationConfig); - this.privConversation.conversationTranslator = this; - this.privConversation.joinConversationAsync(conversation, nickname, lang, (function (result) { - if (!result) { - _this.handleError(new Error(_this.privErrors.permissionDeniedConnect), param3); - } - _this.privSpeechTranslationConfig.authorizationToken = result; - // connect to the ws - _this.privConversation.startConversationAsync((function () { - _this.handleCallback(param2, param3); - }), (function (error) { - _this.handleError(error, param3); - })); - }), (function (error) { - _this.handleError(error, param3); - })); - } - else if (typeof conversation === "object") { - Contracts_1.Contracts.throwIfNullOrUndefined(conversation, this.privErrors.invalidArgs.replace("{arg}", "conversation id")); - Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname")); - // save the nickname - this.privProperties.setProperty(Exports_3.PropertyId.ConversationTranslator_Name, nickname); - // ref the conversation object - this.privConversation = conversation; - // ref the conversation translator object - this.privConversation.conversationTranslator = this; - Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedConnect); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation.room.token, this.privErrors.permissionDeniedConnect); - this.privSpeechTranslationConfig = conversation.config; - this.handleCallback(param1, param2); - } - else { - this.handleError(new Error(this.privErrors.invalidArgs.replace("{arg}", "invalid conversation type")), param2); - } - } - catch (error) { - this.handleError(error, typeof param1 === "string" ? param3 : param2); - } - }; - /** - * Leave the conversation - * @param cb - * @param err - */ - ConversationTranslator.prototype.leaveConversationAsync = function (cb, err) { - var _this = this; - Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - // stop the speech websocket - return [4 /*yield*/, this.cancelSpeech()]; - case 1: - // stop the speech websocket - _a.sent(); - // stop the websocket - return [4 /*yield*/, this.privConversation.endConversationImplAsync()]; - case 2: - // stop the websocket - _a.sent(); - // https delete request - return [4 /*yield*/, this.privConversation.deleteConversationImplAsync()]; - case 3: - // https delete request - _a.sent(); - this.dispose(); - return [2 /*return*/]; - } - }); - }); })(), cb, err); - }; /** - * Send a text message - * @param message + * Create a meeting + * @param speechConfig + * @param meetingId * @param cb * @param err */ - ConversationTranslator.prototype.sendTextMessageAsync = function (message, cb, err) { - var _a; - try { - Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedSend); - Contracts_1.Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace("{arg}", message)); - (_a = this.privConversation) === null || _a === void 0 ? void 0 : _a.sendTextMessageAsync(message, cb, err); + static createMeetingAsync(speechConfig, meetingId, arg3, arg4) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "config")); + Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig.region, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Region")); + Contracts_js_1.Contracts.throwIfNull(meetingId, "meetingId"); + if (meetingId.length === 0) { + throw new Error("meetingId cannot be empty"); } - catch (error) { - this.handleError(error, err); + if (!speechConfig.subscriptionKey && !speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceAuthorization_Token])) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig.subscriptionKey, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Key")); } - }; + const meetingImpl = new MeetingImpl(speechConfig, meetingId); + // eslint-disable-next-line @typescript-eslint/no-empty-function + (0, Exports_js_2.marshalPromiseToCallbacks)((async () => { })(), arg3, arg4); + return meetingImpl; + } +} +exports.Meeting = Meeting; +class MeetingImpl extends Meeting { /** - * Start speaking - * @param cb - * @param err + * Create a Meeting impl + * @param speechConfig + * @param {string} id - meetingId */ - ConversationTranslator.prototype.startTranscribingAsync = function (cb, err) { - var _this = this; - Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () { - var error_2; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 4, , 6]); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedSend); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation.room.token, this.privErrors.permissionDeniedConnect); - if (!(this.privCTRecognizer === undefined)) return [3 /*break*/, 2]; - return [4 /*yield*/, this.connectTranslatorRecognizer()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - Contracts_1.Contracts.throwIfNullOrUndefined(this.privCTRecognizer, this.privErrors.permissionDeniedSend); - if (!this.canSpeak) { - this.handleError(new Error(this.privErrors.permissionDeniedSend), err); - } - return [4 /*yield*/, this.startContinuousRecognition()]; - case 3: - _a.sent(); - this.privIsSpeaking = true; - return [3 /*break*/, 6]; - case 4: - error_2 = _a.sent(); - this.privIsSpeaking = false; - return [4 /*yield*/, this.cancelSpeech()]; - case 5: - _a.sent(); - throw error_2; - case 6: return [2 /*return*/]; - } - }); - }); })(), cb, err); - }; + constructor(speechConfig, id) { + super(); + this.privErrors = Exports_js_1.ConversationConnectionConfig.restErrors; + this.privIsDisposed = false; + this.privMeetingId = ""; + this.privProperties = new Exports_js_3.PropertyCollection(); + // check the speech language + const language = speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]); + if (!language) { + speechConfig.setProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage], Exports_js_1.ConversationConnectionConfig.defaultLanguageCode); + } + this.privLanguage = speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]); + this.privMeetingId = id; + // save the speech config for future usage + this.privConfig = speechConfig; + // save the config properties + const configImpl = speechConfig; + Contracts_js_1.Contracts.throwIfNull(configImpl, "speechConfig"); + this.privProperties = configImpl.properties.clone(); + this.privParticipants = new Exports_js_1.InternalParticipants(); + } + // get the config + get config() { + return this.privConfig; + } + // get the meeting Id + get meetingId() { + return this.privMeetingId; + } + // get the properties + get properties() { + return this.privProperties; + } + // get the speech language + get speechRecognitionLanguage() { + return this.privLanguage; + } + get participants() { + return this.privParticipants.participants.map((p) => this.toParticipant(p)); + } + get transcriberRecognizer() { + return this.privTranscriberRecognizer; + } + get meetingInfo() { + const meetingId = this.meetingId; + const p = this.participants.map((part) => ({ + id: part.id, + preferredLanguage: part.preferredLanguage, + voice: part.voice + })); + const props = {}; + for (const key of Exports_js_1.ConversationConnectionConfig.transcriptionEventKeys) { + const val = this.properties.getProperty(key, ""); + if (val !== "") { + props[key] = val; + } + } + const info = { id: meetingId, participants: p, meetingProperties: props }; + return info; + } + // get / set the speech auth token + // eslint-disable-next-line @typescript-eslint/member-ordering + get authorizationToken() { + return this.privToken; + } + set authorizationToken(value) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "authorizationToken"); + this.privToken = value; + } /** - * Stop speaking + * Add a participant to the meeting. + * @param { IParticipant } participant - participant to add * @param cb * @param err */ - ConversationTranslator.prototype.stopTranscribingAsync = function (cb, err) { - var _this = this; - Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () { - var error_3; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 4, , 6]); - if (!!this.privIsSpeaking) return [3 /*break*/, 2]; - // stop speech - return [4 /*yield*/, this.cancelSpeech()]; - case 1: - // stop speech - _a.sent(); - return [2 /*return*/]; - case 2: - // stop the recognition but leave the websocket open - this.privIsSpeaking = false; - return [4 /*yield*/, new Promise(function (resolve, reject) { - var _a; - (_a = _this.privCTRecognizer) === null || _a === void 0 ? void 0 : _a.stopContinuousRecognitionAsync(resolve, reject); - })]; - case 3: - _a.sent(); - return [3 /*break*/, 6]; - case 4: - error_3 = _a.sent(); - return [4 /*yield*/, this.cancelSpeech()]; - case 5: - _a.sent(); - return [3 /*break*/, 6]; - case 6: return [2 /*return*/]; - } - }); - }); })(), cb, err); - }; - ConversationTranslator.prototype.isDisposed = function () { - return this.privIsDisposed; - }; - ConversationTranslator.prototype.dispose = function (reason, success, err) { - var _this = this; - Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () { - var _a, _b; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - if (this.isDisposed && !this.privIsSpeaking) { - return [2 /*return*/]; - } - return [4 /*yield*/, this.cancelSpeech()]; - case 1: - _c.sent(); - this.privIsDisposed = true; - (_a = this.privSpeechTranslationConfig) === null || _a === void 0 ? void 0 : _a.close(); - this.privSpeechRecognitionLanguage = undefined; - this.privProperties = undefined; - this.privAudioConfig = undefined; - this.privSpeechTranslationConfig = undefined; - (_b = this.privConversation) === null || _b === void 0 ? void 0 : _b.dispose(); - this.privConversation = undefined; - return [2 /*return*/]; - } - }); - }); })(), success, err); - }; - /** - * Cancel the speech websocket - */ - ConversationTranslator.prototype.cancelSpeech = function () { - var _a; - return __awaiter(this, void 0, void 0, function () { - var e_2; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - this.privIsSpeaking = false; - return [4 /*yield*/, ((_a = this.privCTRecognizer) === null || _a === void 0 ? void 0 : _a.onDisconnection())]; - case 1: - _b.sent(); - this.privCTRecognizer = undefined; - return [3 /*break*/, 3]; - case 2: - e_2 = _b.sent(); - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); - }; - /** - * Connect to the speech translation recognizer. - * Currently there is no language validation performed before sending the SpeechLanguage code to the service. - * If it's an invalid language the raw error will be: 'Error during WebSocket handshake: Unexpected response code: 400' - * e.g. pass in 'fr' instead of 'fr-FR', or a text-only language 'cy' - */ - ConversationTranslator.prototype.connectTranslatorRecognizer = function () { - return __awaiter(this, void 0, void 0, function () { - var token, endpointHost, url, error_4; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 1, , 3]); - if (this.privAudioConfig === undefined) { - this.privAudioConfig = Exports_3.AudioConfig.fromDefaultMicrophoneInput(); - } - // clear the temp subscription key if it's a participant joining - if (this.privSpeechTranslationConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Key]) - === this.privPlaceholderKey) { - this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Key], ""); - } - token = encodeURIComponent(this.privConversation.room.token); - endpointHost = this.privSpeechTranslationConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Host], Exports_1.ConversationConnectionConfig.speechHost); - endpointHost = endpointHost.replace("{region}", this.privConversation.room.cognitiveSpeechRegion); - url = "wss://" + endpointHost + Exports_1.ConversationConnectionConfig.speechPath + "?" + Exports_1.ConversationConnectionConfig.configParams.token + "=" + token; - this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Endpoint], url); - this.privCTRecognizer = new ConversationTranslationRecognizer(this.privSpeechTranslationConfig, this.privAudioConfig, this); - return [3 /*break*/, 3]; - case 1: - error_4 = _a.sent(); - return [4 /*yield*/, this.cancelSpeech()]; - case 2: - _a.sent(); - throw error_4; - case 3: return [2 /*return*/]; - } - }); - }); - }; + addParticipantAsync(participant, cb, err) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(participant, "Participant"); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.addParticipantImplAsync(participant), cb, err); + } /** - * Handle the start speaking request + * Remove a participant from the meeting. + * @param userId + * @param cb + * @param err */ - ConversationTranslator.prototype.startContinuousRecognition = function () { - var _this = this; - return new Promise(function (resolve, reject) { - _this.privCTRecognizer.startContinuousRecognitionAsync(resolve, reject); - }); - }; - Object.defineProperty(ConversationTranslator.prototype, "canSpeak", { - get: function () { - // is there a Conversation websocket available and has the Recognizer been set up - if (!this.privConversation.isConnected || !this.privCTRecognizer) { - return false; - } - // is the user already speaking - if (this.privIsSpeaking || this.privCTRecognizer.state === SpeechState.Connected || this.privCTRecognizer.state === SpeechState.Connecting) { - return false; - } - // is the user muted - if (this.privConversation.isMutedByHost) { - return false; + removeParticipantAsync(userId, cb, err) { + Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed); + Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privTranscriberRecognizer, "Recognizer"); + Contracts_js_1.Contracts.throwIfNullOrUndefined(userId, this.privErrors.invalidArgs.replace("{arg}", "userId")); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.removeParticipantImplAsync(userId), cb, err); + } + isDisposed() { + return this.privIsDisposed; + } + dispose() { + if (this.isDisposed) { + return; + } + this.privIsDisposed = true; + if (!!this.config) { + this.config.close(); + } + this.privConfig = undefined; + this.privLanguage = undefined; + this.privProperties = undefined; + this.privToken = undefined; + this.privParticipants = undefined; + } + async connectTranscriberRecognizer(recognizer) { + if (!!this.privTranscriberRecognizer) { + await this.privTranscriberRecognizer.close(); + } + await recognizer.enforceAudioGating(); + this.privTranscriberRecognizer = recognizer; + this.privTranscriberRecognizer.meeting = this; + } + addParticipantImplAsync(participant) { + const newParticipant = this.privParticipants.addOrUpdateParticipant(participant); + if (newParticipant !== undefined) { + if (!!this.privTranscriberRecognizer) { + const meetingInfo = this.meetingInfo; + meetingInfo.participants = [participant]; + return this.privTranscriberRecognizer.pushMeetingEvent(meetingInfo, "join"); } - return true; - }, - enumerable: false, - configurable: true - }); - return ConversationTranslator; -}(Exports_4.ConversationCommon)); -exports.ConversationTranslator = ConversationTranslator; + } + } + removeParticipantImplAsync(participant) { + this.privParticipants.deleteParticipant(participant.id); + const meetingInfo = this.meetingInfo; + meetingInfo.participants = [participant]; + return this.privTranscriberRecognizer.pushMeetingEvent(meetingInfo, "leave"); + } + /** Participant Helpers */ + toParticipant(p) { + return new Exports_js_3.Participant(p.id, p.preferredLanguage, p.voice); + } +} +exports.MeetingImpl = MeetingImpl; + + + +/***/ }), +/* 152 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +// Multi-device Conversation is a Preview feature. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MeetingTranscriptionCanceledEventArgs = void 0; +const CancellationEventArgsBase_js_1 = __webpack_require__(104); +class MeetingTranscriptionCanceledEventArgs extends CancellationEventArgsBase_js_1.CancellationEventArgsBase { +} +exports.MeetingTranscriptionCanceledEventArgs = MeetingTranscriptionCanceledEventArgs; /***/ }), /* 153 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranscriber = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -var ConversationTranscriber = /** @class */ (function () { - /** - * ConversationTranscriber constructor. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MeetingTranscriber = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); +const Exports_js_4 = __webpack_require__(148); +class MeetingTranscriber { + /** + * MeetingTranscriber constructor. * @constructor * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer */ - function ConversationTranscriber(audioConfig) { + constructor(audioConfig) { this.privAudioConfig = audioConfig; - this.privProperties = new Exports_3.PropertyCollection(); + this.privProperties = new Exports_js_3.PropertyCollection(); this.privRecognizer = undefined; this.privDisposedRecognizer = false; } /** - * @param {Conversation} converation - conversation to be recognized + * Gets the spoken language of recognition. + * @member MeetingTranscriber.prototype.speechRecognitionLanguage + * @function + * @public + * @returns {string} The spoken language of recognition. + */ + get speechRecognitionLanguage() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage); + } + /** + * The collection of properties and their values defined for this MeetingTranscriber. + * @member MeetingTranscriber.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The collection of properties and their values defined for this MeetingTranscriber. + */ + get properties() { + return this.privProperties; + } + /** + * @Internal + * Internal data member to support fromRecognizer* pattern methods on other classes. + * Do not use externally, object returned will change without warning or notice. + */ + get internalData() { + return this.privRecognizer.internalData; + } + /** + * @Deprecated + * @Obsolete + * Please use the Connection.fromRecognizer pattern to obtain a connection object + */ + get connection() { + return Exports_js_3.Connection.fromRecognizer(this.privRecognizer); + } + /** + * Gets the authorization token used to communicate with the service. + * @member MeetingTranscriber.prototype.authorizationToken + * @function + * @public + * @returns {string} Authorization token. + */ + get authorizationToken() { + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token); + } + /** + * Gets/Sets the authorization token used to communicate with the service. + * @member MeetingTranscriber.prototype.authorizationToken + * @function + * @public + * @param {string} token - Authorization token. + */ + set authorizationToken(token) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token"); + this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, token); + } + /** + * @param {Meeting} meeting - meeting to be recognized */ - ConversationTranscriber.prototype.joinConversationAsync = function (conversation, cb, err) { - var conversationImpl = conversation; - Contracts_1.Contracts.throwIfNullOrUndefined(conversationImpl, "Conversation"); - // ref the conversation object + joinMeetingAsync(meeting, cb, err) { + /* eslint-disable no-console */ + // console.log(">> MeetingTranscriber::joinMeetingAsync"); + /* eslint-enable no-console */ + const meetingImpl = meeting; + Contracts_js_1.Contracts.throwIfNullOrUndefined(Exports_js_4.MeetingImpl, "Meeting"); + // ref the meeting object // create recognizer and subscribe to recognizer events - this.privRecognizer = new Exports_1.TranscriberRecognizer(conversation.config, this.privAudioConfig); - Contracts_1.Contracts.throwIfNullOrUndefined(this.privRecognizer, "Recognizer"); - this.privRecognizer.connectCallbacks(this); - Exports_2.marshalPromiseToCallbacks(conversationImpl.connectTranscriberRecognizer(this.privRecognizer), cb, err); - }; - Object.defineProperty(ConversationTranscriber.prototype, "authorizationToken", { - /** - * Gets the authorization token used to communicate with the service. - * @member ConversationTranscriber.prototype.authorizationToken - * @function - * @public - * @returns {string} Authorization token. - */ - get: function () { - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token); - }, - /** - * Gets/Sets the authorization token used to communicate with the service. - * @member ConversationTranscriber.prototype.authorizationToken - * @function - * @public - * @param {string} token - Authorization token. - */ - set: function (token) { - Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token"); - this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, token); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationTranscriber.prototype, "speechRecognitionLanguage", { - /** - * Gets the spoken language of recognition. - * @member ConversationTranscriber.prototype.speechRecognitionLanguage - * @function - * @public - * @returns {string} The spoken language of recognition. - */ - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationTranscriber.prototype, "properties", { - /** - * The collection of properties and their values defined for this ConversationTranscriber. - * @member ConversationTranscriber.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The collection of properties and their values defined for this ConversationTranscriber. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); + this.privRecognizer = new Exports_js_1.TranscriberRecognizer(meeting.config, this.privAudioConfig); + Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRecognizer, "Recognizer"); + this.privRecognizer.connectMeetingCallbacks(this); + (0, Exports_js_2.marshalPromiseToCallbacks)(meetingImpl.connectTranscriberRecognizer(this.privRecognizer), cb, err); + } /** - * Starts conversation transcription, until stopTranscribingAsync() is called. + * Starts meeting transcription, until stopTranscribingAsync() is called. * User must subscribe to events to receive transcription results. - * @member ConversationTranscriber.prototype.startTranscribingAsync + * @member MeetingTranscriber.prototype.startTranscribingAsync * @function * @public * @param cb - Callback invoked once the transcription has started. * @param err - Callback invoked in case of an error. */ - ConversationTranscriber.prototype.startTranscribingAsync = function (cb, err) { + startTranscribingAsync(cb, err) { this.privRecognizer.startContinuousRecognitionAsync(cb, err); - }; + } /** - * Starts conversation transcription, until stopTranscribingAsync() is called. + * Starts meeting transcription, until stopTranscribingAsync() is called. * User must subscribe to events to receive transcription results. - * @member ConversationTranscriber.prototype.stopTranscribingAsync + * @member MeetingTranscriber.prototype.stopTranscribingAsync * @function * @public * @param cb - Callback invoked once the transcription has started. * @param err - Callback invoked in case of an error. */ - ConversationTranscriber.prototype.stopTranscribingAsync = function (cb, err) { + stopTranscribingAsync(cb, err) { this.privRecognizer.stopContinuousRecognitionAsync(cb, err); - }; + } /** - * Leave the current conversation. After this is called, you will no longer receive any events. + * Leave the current meeting. After this is called, you will no longer receive any events. */ - ConversationTranscriber.prototype.leaveConversationAsync = function (cb, err) { - var _this = this; + leaveMeetingAsync(cb, err) { this.privRecognizer.disconnectCallbacks(); - Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { - return [2 /*return*/]; - }); }); })(), cb, err); - }; + // eslint-disable-next-line + (0, Exports_js_2.marshalPromiseToCallbacks)((async () => { return; })(), cb, err); + } /** * closes all external resources held by an instance of this class. - * @member ConversationTranscriber.prototype.close + * @member MeetingTranscriber.prototype.close * @function * @public */ - ConversationTranscriber.prototype.close = function (cb, errorCb) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); - Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb); - }; + close(cb, errorCb) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb); + } /** * Disposes any resources held by the object. - * @member ConversationTranscriber.prototype.dispose + * @member MeetingTranscriber.prototype.dispose * @function * @public * @param {boolean} disposing - true if disposing the object. */ - ConversationTranscriber.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privDisposedRecognizer) { - return [2 /*return*/]; - } - if (!!!this.privRecognizer) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privRecognizer.close()]; - case 1: - _a.sent(); - this.privRecognizer = undefined; - _a.label = 2; - case 2: - if (disposing) { - this.privDisposedRecognizer = true; - } - return [2 /*return*/]; - } - }); - }); - }; - return ConversationTranscriber; -}()); -exports.ConversationTranscriber = ConversationTranscriber; + async dispose(disposing) { + if (this.privDisposedRecognizer) { + return; + } + if (!!this.privRecognizer) { + await this.privRecognizer.close(); + this.privRecognizer = undefined; + } + if (disposing) { + this.privDisposedRecognizer = true; + } + } +} +exports.MeetingTranscriber = MeetingTranscriber; /***/ }), /* 154 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Participant = exports.User = void 0; -var Exports_1 = __webpack_require__(61); -var User = /** @class */ (function () { - function User(userId) { - this.privUserId = userId; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationTranscriptionResult = void 0; +const Exports_js_1 = __webpack_require__(85); +/** + * Defines result of conversation transcription. + * @class ConversationTranscriptionResult + */ +class ConversationTranscriptionResult extends Exports_js_1.RecognitionResult { + /** + * Creates and initializes an instance of this class. + * @constructor + * @public + * @param {string} resultId - The result id. + * @param {ResultReason} reason - The reason. + * @param {string} text - The recognized text. + * @param {number} duration - The duration. + * @param {number} offset - The offset into the stream. + * @param {string} language - Primary Language detected, if provided. + * @param {string} languageDetectionConfidence - Primary Language confidence ("Unknown," "Low," "Medium," "High"...), if provided. + * @param {string} speakerId - speaker id for conversation transcription. + * @param {string} errorDetails - Error details, if provided. + * @param {string} json - Additional Json, if provided. + * @param {PropertyCollection} properties - Additional properties, if provided. + */ + constructor(resultId, reason, text, duration, offset, language, languageDetectionConfidence, speakerId, errorDetails, json, properties) { + super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties); + this.privSpeakerId = speakerId; } - Object.defineProperty(User.prototype, "userId", { - get: function () { - return this.privUserId; - }, - enumerable: false, - configurable: true - }); - return User; -}()); -exports.User = User; -// tslint:disable-next-line: max-classes-per-file -var Participant = /** @class */ (function () { - function Participant(id, avatar, displayName, isHost, isMuted, isUsingTts, preferredLanguage, voice) { - this.privId = id; - this.privAvatar = avatar; - this.privDisplayName = displayName; - this.privIsHost = isHost; - this.privIsMuted = isMuted; - this.privIsUsingTts = isUsingTts; - this.privPreferredLanguage = preferredLanguage; - this.privVoice = voice; - this.privProperties = new Exports_1.PropertyCollection(); - } - Participant.From = function (id, language, voice) { - return new Participant(id, "", id, false, false, false, language, voice); - }; - Object.defineProperty(Participant.prototype, "avatar", { - get: function () { - return this.privAvatar; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Participant.prototype, "displayName", { - get: function () { - return this.privDisplayName; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Participant.prototype, "id", { - get: function () { - return this.privId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Participant.prototype, "preferredLanguage", { - get: function () { - return this.privPreferredLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Participant.prototype, "isHost", { - get: function () { - return this.privIsHost; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Participant.prototype, "isMuted", { - get: function () { - return this.privIsMuted; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Participant.prototype, "isUsingTts", { - get: function () { - return this.privIsUsingTts; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Participant.prototype, "voice", { - get: function () { - return this.privVoice; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Participant.prototype, "properties", { - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - return Participant; -}()); -exports.Participant = Participant; + /** + * speaker id + * @member ConversationTranscriptionResult.prototype.speakerId + * @function + * @public + * @returns {string} id of speaker in given result + */ + get speakerId() { + return this.privSpeakerId; + } +} +exports.ConversationTranscriptionResult = ConversationTranscriptionResult; /***/ }), /* 155 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -// Multi-device Conversation is a Preview feature. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ParticipantChangedReason = void 0; -var ParticipantChangedReason; -(function (ParticipantChangedReason) { - /** Participant has joined the conversation. */ - ParticipantChangedReason[ParticipantChangedReason["JoinedConversation"] = 0] = "JoinedConversation"; - /** Participant has left the conversation. This could be voluntary, or involuntary - * (e.g. they are experiencing networking issues). +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StreamingSynthesisRequest = exports.SynthesisRequest = exports.Synthesizer = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); +class Synthesizer { + /** + * Creates and initializes an instance of a Recognizer + * @constructor + * @param {SpeechConfig} speechConfig - The speech config to initialize the synthesizer. + */ + constructor(speechConfig) { + const speechConfigImpl = speechConfig; + Contracts_js_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig"); + this.privProperties = speechConfigImpl.properties.clone(); + this.privDisposed = false; + this.privSynthesizing = false; + this.synthesisRequestQueue = new Exports_js_2.Queue(); + this.tokenCredential = speechConfig.tokenCredential; + } + /** + * Gets the authorization token used to communicate with the service. + * @member Synthesizer.prototype.authorizationToken + * @function + * @public + * @returns {string} Authorization token. + */ + get authorizationToken() { + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token); + } + /** + * Gets/Sets the authorization token used to communicate with the service. + * @member Synthesizer.prototype.authorizationToken + * @function + * @public + * @param {string} token - Authorization token. + */ + set authorizationToken(token) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token"); + this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, token); + } + /** + * The collection of properties and their values defined for this Synthesizer. + * @member Synthesizer.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechSynthesizer. + */ + get properties() { + return this.privProperties; + } + /** + * Indicates if auto detect source language is enabled + * @member Synthesizer.prototype.autoDetectSourceLanguage + * @function + * @public + * @returns {boolean} if auto detect source language is enabled + */ + get autoDetectSourceLanguage() { + return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages) === Exports_js_1.AutoDetectSourceLanguagesOpenRangeOptionName; + } + buildSsml(text) { + const languageToDefaultVoice = { + ["af-ZA"]: "af-ZA-AdriNeural", + ["am-ET"]: "am-ET-AmehaNeural", + ["ar-AE"]: "ar-AE-FatimaNeural", + ["ar-BH"]: "ar-BH-AliNeural", + ["ar-DZ"]: "ar-DZ-AminaNeural", + ["ar-EG"]: "ar-EG-SalmaNeural", + ["ar-IQ"]: "ar-IQ-BasselNeural", + ["ar-JO"]: "ar-JO-SanaNeural", + ["ar-KW"]: "ar-KW-FahedNeural", + ["ar-LY"]: "ar-LY-ImanNeural", + ["ar-MA"]: "ar-MA-JamalNeural", + ["ar-QA"]: "ar-QA-AmalNeural", + ["ar-SA"]: "ar-SA-HamedNeural", + ["ar-SY"]: "ar-SY-AmanyNeural", + ["ar-TN"]: "ar-TN-HediNeural", + ["ar-YE"]: "ar-YE-MaryamNeural", + ["bg-BG"]: "bg-BG-BorislavNeural", + ["bn-BD"]: "bn-BD-NabanitaNeural", + ["bn-IN"]: "bn-IN-BashkarNeural", + ["ca-ES"]: "ca-ES-JoanaNeural", + ["cs-CZ"]: "cs-CZ-AntoninNeural", + ["cy-GB"]: "cy-GB-AledNeural", + ["da-DK"]: "da-DK-ChristelNeural", + ["de-AT"]: "de-AT-IngridNeural", + ["de-CH"]: "de-CH-JanNeural", + ["de-DE"]: "de-DE-KatjaNeural", + ["el-GR"]: "el-GR-AthinaNeural", + ["en-AU"]: "en-AU-NatashaNeural", + ["en-CA"]: "en-CA-ClaraNeural", + ["en-GB"]: "en-GB-LibbyNeural", + ["en-HK"]: "en-HK-SamNeural", + ["en-IE"]: "en-IE-ConnorNeural", + ["en-IN"]: "en-IN-NeerjaNeural", + ["en-KE"]: "en-KE-AsiliaNeural", + ["en-NG"]: "en-NG-AbeoNeural", + ["en-NZ"]: "en-NZ-MitchellNeural", + ["en-PH"]: "en-PH-JamesNeural", + ["en-SG"]: "en-SG-LunaNeural", + ["en-TZ"]: "en-TZ-ElimuNeural", + ["en-US"]: "en-US-AvaMultilingualNeural", + ["en-ZA"]: "en-ZA-LeahNeural", + ["es-AR"]: "es-AR-ElenaNeural", + ["es-BO"]: "es-BO-MarceloNeural", + ["es-CL"]: "es-CL-CatalinaNeural", + ["es-CO"]: "es-CO-GonzaloNeural", + ["es-CR"]: "es-CR-JuanNeural", + ["es-CU"]: "es-CU-BelkysNeural", + ["es-DO"]: "es-DO-EmilioNeural", + ["es-EC"]: "es-EC-AndreaNeural", + ["es-ES"]: "es-ES-AlvaroNeural", + ["es-GQ"]: "es-GQ-JavierNeural", + ["es-GT"]: "es-GT-AndresNeural", + ["es-HN"]: "es-HN-CarlosNeural", + ["es-MX"]: "es-MX-DaliaNeural", + ["es-NI"]: "es-NI-FedericoNeural", + ["es-PA"]: "es-PA-MargaritaNeural", + ["es-PE"]: "es-PE-AlexNeural", + ["es-PR"]: "es-PR-KarinaNeural", + ["es-PY"]: "es-PY-MarioNeural", + ["es-SV"]: "es-SV-LorenaNeural", + ["es-US"]: "es-US-AlonsoNeural", + ["es-UY"]: "es-UY-MateoNeural", + ["es-VE"]: "es-VE-PaolaNeural", + ["et-EE"]: "et-EE-AnuNeural", + ["fa-IR"]: "fa-IR-DilaraNeural", + ["fi-FI"]: "fi-FI-SelmaNeural", + ["fil-PH"]: "fil-PH-AngeloNeural", + ["fr-BE"]: "fr-BE-CharlineNeural", + ["fr-CA"]: "fr-CA-SylvieNeural", + ["fr-CH"]: "fr-CH-ArianeNeural", + ["fr-FR"]: "fr-FR-DeniseNeural", + ["ga-IE"]: "ga-IE-ColmNeural", + ["gl-ES"]: "gl-ES-RoiNeural", + ["gu-IN"]: "gu-IN-DhwaniNeural", + ["he-IL"]: "he-IL-AvriNeural", + ["hi-IN"]: "hi-IN-MadhurNeural", + ["hr-HR"]: "hr-HR-GabrijelaNeural", + ["hu-HU"]: "hu-HU-NoemiNeural", + ["id-ID"]: "id-ID-ArdiNeural", + ["is-IS"]: "is-IS-GudrunNeural", + ["it-IT"]: "it-IT-IsabellaNeural", + ["ja-JP"]: "ja-JP-NanamiNeural", + ["jv-ID"]: "jv-ID-DimasNeural", + ["kk-KZ"]: "kk-KZ-AigulNeural", + ["km-KH"]: "km-KH-PisethNeural", + ["kn-IN"]: "kn-IN-GaganNeural", + ["ko-KR"]: "ko-KR-SunHiNeural", + ["lo-LA"]: "lo-LA-ChanthavongNeural", + ["lt-LT"]: "lt-LT-LeonasNeural", + ["lv-LV"]: "lv-LV-EveritaNeural", + ["mk-MK"]: "mk-MK-AleksandarNeural", + ["ml-IN"]: "ml-IN-MidhunNeural", + ["mr-IN"]: "mr-IN-AarohiNeural", + ["ms-MY"]: "ms-MY-OsmanNeural", + ["mt-MT"]: "mt-MT-GraceNeural", + ["my-MM"]: "my-MM-NilarNeural", + ["nb-NO"]: "nb-NO-PernilleNeural", + ["nl-BE"]: "nl-BE-ArnaudNeural", + ["nl-NL"]: "nl-NL-ColetteNeural", + ["pl-PL"]: "pl-PL-AgnieszkaNeural", + ["ps-AF"]: "ps-AF-GulNawazNeural", + ["pt-BR"]: "pt-BR-FranciscaNeural", + ["pt-PT"]: "pt-PT-DuarteNeural", + ["ro-RO"]: "ro-RO-AlinaNeural", + ["ru-RU"]: "ru-RU-SvetlanaNeural", + ["si-LK"]: "si-LK-SameeraNeural", + ["sk-SK"]: "sk-SK-LukasNeural", + ["sl-SI"]: "sl-SI-PetraNeural", + ["so-SO"]: "so-SO-MuuseNeural", + ["sr-RS"]: "sr-RS-NicholasNeural", + ["su-ID"]: "su-ID-JajangNeural", + ["sv-SE"]: "sv-SE-SofieNeural", + ["sw-KE"]: "sw-KE-RafikiNeural", + ["sw-TZ"]: "sw-TZ-DaudiNeural", + ["ta-IN"]: "ta-IN-PallaviNeural", + ["ta-LK"]: "ta-LK-KumarNeural", + ["ta-SG"]: "ta-SG-AnbuNeural", + ["te-IN"]: "te-IN-MohanNeural", + ["th-TH"]: "th-TH-PremwadeeNeural", + ["tr-TR"]: "tr-TR-AhmetNeural", + ["uk-UA"]: "uk-UA-OstapNeural", + ["ur-IN"]: "ur-IN-GulNeural", + ["ur-PK"]: "ur-PK-AsadNeural", + ["uz-UZ"]: "uz-UZ-MadinaNeural", + ["vi-VN"]: "vi-VN-HoaiMyNeural", + ["zh-CN"]: "zh-CN-XiaoxiaoNeural", + ["zh-HK"]: "zh-HK-HiuMaanNeural", + ["zh-TW"]: "zh-TW-HsiaoChenNeural", + ["zu-ZA"]: "zu-ZA-ThandoNeural", + }; + let language = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SynthLanguage, "en-US"); + let voice = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SynthVoice, ""); + let ssml = Synthesizer.XMLEncode(text); + if (this.autoDetectSourceLanguage) { + language = "en-US"; + } + else { + voice = voice || languageToDefaultVoice[language]; + } + if (voice) { + ssml = `${ssml}`; + } + ssml = `${ssml}`; + return ssml; + } + /** + * This method performs cleanup of resources. + * The Boolean parameter disposing indicates whether the method is called + * from Dispose (if disposing is true) or from the finalizer (if disposing is false). + * Derived classes should override this method to dispose resource if needed. + * @member Synthesizer.prototype.dispose + * @function + * @public + * @param {boolean} disposing - Flag to request disposal. */ - ParticipantChangedReason[ParticipantChangedReason["LeftConversation"] = 1] = "LeftConversation"; - /** The participants' state has changed (e.g. they became muted, changed their nickname). */ - ParticipantChangedReason[ParticipantChangedReason["Updated"] = 2] = "Updated"; -})(ParticipantChangedReason = exports.ParticipantChangedReason || (exports.ParticipantChangedReason = {})); + async dispose(disposing) { + if (this.privDisposed) { + return; + } + if (disposing) { + if (this.privAdapter) { + await this.privAdapter.dispose(); + } + } + this.privDisposed = true; + } + async adapterSpeak() { + if (!this.privDisposed && !this.privSynthesizing) { + this.privSynthesizing = true; + const request = await this.synthesisRequestQueue.dequeue(); + if (request instanceof StreamingSynthesisRequest) { + return this.privAdapter.SpeakStream(request.speechSynthesisRequest, request.requestId, request.cb, request.err, request.dataStream); + } + return this.privAdapter.Speak(request.text, request.isSSML, request.requestId, request.cb, request.err, request.dataStream); + } + } + createSynthesizerConfig(speechConfig) { + return new Exports_js_1.SynthesizerConfig(speechConfig, this.privProperties); + } + // Does the generic synthesizer setup that is common across all synthesizer types. + implCommonSynthesizeSetup() { + let osPlatform = (typeof window !== "undefined") ? "Browser" : "Node"; + let osName = "unknown"; + let osVersion = "unknown"; + if (typeof navigator !== "undefined") { + osPlatform = osPlatform + "/" + navigator.platform; + osName = navigator.userAgent; + osVersion = navigator.appVersion; + } + const synthesizerConfig = this.createSynthesizerConfig(new Exports_js_1.SpeechServiceConfig(new Exports_js_1.Context(new Exports_js_1.OS(osPlatform, osName, osVersion)))); + const subscriptionKey = this.privProperties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Key, undefined); + const authentication = (subscriptionKey && subscriptionKey !== "") + ? new Exports_js_1.CognitiveSubscriptionKeyAuthentication(subscriptionKey) + : (this.tokenCredential) + ? new Exports_js_1.CognitiveTokenAuthentication(async () => { + try { + const tokenResponse = await this.tokenCredential.getToken("https://cognitiveservices.azure.com/.default"); + return tokenResponse?.token ?? ""; + } + catch (err) { + throw err; + } + }, async () => { + try { + const tokenResponse = await this.tokenCredential.getToken("https://cognitiveservices.azure.com/.default"); + return tokenResponse?.token ?? ""; + } + catch (err) { + throw err; + } + }) + : new Exports_js_1.CognitiveTokenAuthentication(() => { + const authorizationToken = this.privProperties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, undefined); + return Promise.resolve(authorizationToken); + }, () => { + const authorizationToken = this.privProperties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, undefined); + return Promise.resolve(authorizationToken); + }); + this.privAdapter = this.createSynthesisAdapter(authentication, this.privConnectionFactory, synthesizerConfig); + this.privRestAdapter = this.createRestSynthesisAdapter(authentication, synthesizerConfig); + } + static XMLEncode(text) { + return text.replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); + } +} +exports.Synthesizer = Synthesizer; +class SynthesisRequest { + constructor(requestId, text, isSSML, cb, err, dataStream) { + this.requestId = requestId; + this.text = text; + this.isSSML = isSSML; + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.cb = cb ?? (() => { }); + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.err = err ?? (() => { }); + this.dataStream = dataStream ?? undefined; + } +} +exports.SynthesisRequest = SynthesisRequest; +class StreamingSynthesisRequest { + constructor(requestId, speechSynthesisRequest, cb, err, dataStream) { + this.requestId = requestId; + this.speechSynthesisRequest = speechSynthesisRequest; + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.cb = cb ?? (() => { }); + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.err = err ?? (() => { }); + this.dataStream = dataStream ?? undefined; + } +} +exports.StreamingSynthesisRequest = StreamingSynthesisRequest; /***/ }), /* 156 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesisRequest = exports.SpeechSynthesizer = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var AudioFileWriter_1 = __webpack_require__(64); -var AudioOutputFormat_1 = __webpack_require__(74); -var AudioOutputStream_1 = __webpack_require__(73); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesizer = void 0; +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const AudioFileWriter_js_1 = __webpack_require__(87); +const AudioOutputFormat_js_1 = __webpack_require__(91); +const AudioOutputStream_js_1 = __webpack_require__(90); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_3 = __webpack_require__(85); +const Synthesizer_js_1 = __webpack_require__(155); /** * Defines the class SpeechSynthesizer for text to speech. * Updated in version 1.16.0 * @class SpeechSynthesizer */ -var SpeechSynthesizer = /** @class */ (function () { +class SpeechSynthesizer extends Exports_js_3.Synthesizer { /** * SpeechSynthesizer constructor. * @constructor * @param {SpeechConfig} speechConfig - An set of initial properties for this synthesizer. * @param {AudioConfig} audioConfig - An optional audio configuration associated with the synthesizer. */ - function SpeechSynthesizer(speechConfig, audioConfig) { - var speechConfigImpl = speechConfig; - Contracts_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig"); + constructor(speechConfig, audioConfig) { + super(speechConfig); if (audioConfig !== null) { if (audioConfig === undefined) { - this.audioConfig = (typeof window === "undefined") ? undefined : Exports_3.AudioConfig.fromDefaultSpeakerOutput(); + this.audioConfig = (typeof window === "undefined") ? undefined : Exports_js_3.AudioConfig.fromDefaultSpeakerOutput(); } else { this.audioConfig = audioConfig; } } - this.privProperties = speechConfigImpl.properties.clone(); - this.privDisposed = false; - this.privSynthesizing = false; - this.privConnectionFactory = new Exports_1.SpeechSynthesisConnectionFactory(); - this.synthesisRequestQueue = new Exports_2.Queue(); + this.privConnectionFactory = new Exports_js_1.SpeechSynthesisConnectionFactory(); this.implCommonSynthesizeSetup(); } - Object.defineProperty(SpeechSynthesizer.prototype, "authorizationToken", { - /** - * Gets the authorization token used to communicate with the service. - * @member SpeechSynthesizer.prototype.authorizationToken - * @function - * @public - * @returns {string} Authorization token. - */ - get: function () { - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token); - }, - /** - * Gets/Sets the authorization token used to communicate with the service. - * @member SpeechSynthesizer.prototype.authorizationToken - * @function - * @public - * @param {string} token - Authorization token. - */ - set: function (token) { - Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token"); - this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, token); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechSynthesizer.prototype, "properties", { - /** - * The collection of properties and their values defined for this SpeechSynthesizer. - * @member SpeechSynthesizer.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechSynthesizer. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechSynthesizer.prototype, "autoDetectSourceLanguage", { - /** - * Indicates if auto detect source language is enabled - * @member SpeechSynthesizer.prototype.properties - * @function - * @public - * @returns {boolean} if auto detect source language is enabled - */ - get: function () { - return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages) === Exports_1.AutoDetectSourceLanguagesOpenRangeOptionName; - }, - enumerable: false, - configurable: true - }); /** * SpeechSynthesizer constructor. * @constructor @@ -18559,149 +13725,11 @@ var SpeechSynthesizer = /** @class */ (function () { * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the synthesizer * @param {AudioConfig} audioConfig - An optional audio configuration associated with the synthesizer */ - SpeechSynthesizer.FromConfig = function (speechConfig, autoDetectSourceLanguageConfig, audioConfig) { - var speechConfigImpl = speechConfig; + static FromConfig(speechConfig, autoDetectSourceLanguageConfig, audioConfig) { + const speechConfigImpl = speechConfig; autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties); return new SpeechSynthesizer(speechConfig, audioConfig); - }; - SpeechSynthesizer.prototype.buildSsml = function (text) { - var _a; - var languageToDefaultVoice = (_a = {}, - _a["af-ZA"] = "af-ZA-AdriNeural", - _a["am-ET"] = "am-ET-AmehaNeural", - _a["ar-AE"] = "ar-AE-FatimaNeural", - _a["ar-BH"] = "ar-BH-AliNeural", - _a["ar-DZ"] = "ar-DZ-AminaNeural", - _a["ar-EG"] = "ar-EG-SalmaNeural", - _a["ar-IQ"] = "ar-IQ-BasselNeural", - _a["ar-JO"] = "ar-JO-SanaNeural", - _a["ar-KW"] = "ar-KW-FahedNeural", - _a["ar-LY"] = "ar-LY-ImanNeural", - _a["ar-MA"] = "ar-MA-JamalNeural", - _a["ar-QA"] = "ar-QA-AmalNeural", - _a["ar-SA"] = "ar-SA-HamedNeural", - _a["ar-SY"] = "ar-SY-AmanyNeural", - _a["ar-TN"] = "ar-TN-HediNeural", - _a["ar-YE"] = "ar-YE-MaryamNeural", - _a["bg-BG"] = "bg-BG-BorislavNeural", - _a["bn-BD"] = "bn-BD-NabanitaNeural", - _a["ca-ES"] = "ca-ES-JoanaNeural", - _a["cs-CZ"] = "cs-CZ-AntoninNeural", - _a["cy-GB"] = "cy-GB-AledNeural", - _a["da-DK"] = "da-DK-ChristelNeural", - _a["de-AT"] = "de-AT-IngridNeural", - _a["de-CH"] = "de-CH-JanNeural", - _a["de-DE"] = "de-DE-KatjaNeural", - _a["el-GR"] = "el-GR-AthinaNeural", - _a["en-AU"] = "en-AU-NatashaNeural", - _a["en-CA"] = "en-CA-ClaraNeural", - _a["en-GB"] = "en-GB-LibbyNeural", - _a["en-HK"] = "en-HK-SamNeural", - _a["en-IE"] = "en-IE-ConnorNeural", - _a["en-IN"] = "en-IN-NeerjaNeural", - _a["en-KE"] = "en-KE-AsiliaNeural", - _a["en-NG"] = "en-NG-AbeoNeural", - _a["en-NZ"] = "en-NZ-MitchellNeural", - _a["en-PH"] = "en-PH-JamesNeural", - _a["en-SG"] = "en-SG-LunaNeural", - _a["en-TZ"] = "en-TZ-ElimuNeural", - _a["en-US"] = "en-US-JennyNeural", - _a["en-ZA"] = "en-ZA-LeahNeural", - _a["es-AR"] = "es-AR-ElenaNeural", - _a["es-BO"] = "es-BO-MarceloNeural", - _a["es-CL"] = "es-CL-CatalinaNeural", - _a["es-CO"] = "es-CO-GonzaloNeural", - _a["es-CR"] = "es-CR-JuanNeural", - _a["es-CU"] = "es-CU-BelkysNeural", - _a["es-DO"] = "es-DO-EmilioNeural", - _a["es-EC"] = "es-EC-AndreaNeural", - _a["es-ES"] = "es-ES-AlvaroNeural", - _a["es-GQ"] = "es-GQ-JavierNeural", - _a["es-GT"] = "es-GT-AndresNeural", - _a["es-HN"] = "es-HN-CarlosNeural", - _a["es-MX"] = "es-MX-DaliaNeural", - _a["es-NI"] = "es-NI-FedericoNeural", - _a["es-PA"] = "es-PA-MargaritaNeural", - _a["es-PE"] = "es-PE-AlexNeural", - _a["es-PR"] = "es-PR-KarinaNeural", - _a["es-PY"] = "es-PY-MarioNeural", - _a["es-SV"] = "es-SV-LorenaNeural", - _a["es-US"] = "es-US-AlonsoNeural", - _a["es-UY"] = "es-UY-MateoNeural", - _a["es-VE"] = "es-VE-PaolaNeural", - _a["et-EE"] = "et-EE-AnuNeural", - _a["fa-IR"] = "fa-IR-DilaraNeural", - _a["fi-FI"] = "fi-FI-SelmaNeural", - _a["fil-PH"] = "fil-PH-AngeloNeural", - _a["fr-BE"] = "fr-BE-CharlineNeural", - _a["fr-CA"] = "fr-CA-SylvieNeural", - _a["fr-CH"] = "fr-CH-ArianeNeural", - _a["fr-FR"] = "fr-FR-DeniseNeural", - _a["ga-IE"] = "ga-IE-ColmNeural", - _a["gl-ES"] = "gl-ES-RoiNeural", - _a["gu-IN"] = "gu-IN-DhwaniNeural", - _a["he-IL"] = "he-IL-AvriNeural", - _a["hi-IN"] = "hi-IN-MadhurNeural", - _a["hr-HR"] = "hr-HR-GabrijelaNeural", - _a["hu-HU"] = "hu-HU-NoemiNeural", - _a["id-ID"] = "id-ID-ArdiNeural", - _a["it-IT"] = "it-IT-IsabellaNeural", - _a["ja-JP"] = "ja-JP-NanamiNeural", - _a["jv-ID"] = "jv-ID-DimasNeural", - _a["km-KH"] = "km-KH-PisethNeural", - _a["ko-KR"] = "ko-KR-SunHiNeural", - _a["lt-LT"] = "lt-LT-LeonasNeural", - _a["lv-LV"] = "lv-LV-EveritaNeural", - _a["mr-IN"] = "mr-IN-AarohiNeural", - _a["ms-MY"] = "ms-MY-OsmanNeural", - _a["mt-MT"] = "mt-MT-GraceNeural", - _a["my-MM"] = "my-MM-NilarNeural", - _a["nb-NO"] = "nb-NO-PernilleNeural", - _a["nl-BE"] = "nl-BE-ArnaudNeural", - _a["nl-NL"] = "nl-NL-ColetteNeural", - _a["pl-PL"] = "pl-PL-AgnieszkaNeural", - _a["pt-BR"] = "pt-BR-FranciscaNeural", - _a["pt-PT"] = "pt-PT-DuarteNeural", - _a["ro-RO"] = "ro-RO-AlinaNeural", - _a["ru-RU"] = "ru-RU-SvetlanaNeural", - _a["sk-SK"] = "sk-SK-LukasNeural", - _a["sl-SI"] = "sl-SI-PetraNeural", - _a["so-SO"] = "so-SO-MuuseNeural", - _a["su-ID"] = "su-ID-JajangNeural", - _a["sv-SE"] = "sv-SE-SofieNeural", - _a["sw-KE"] = "sw-KE-RafikiNeural", - _a["sw-TZ"] = "sw-TZ-DaudiNeural", - _a["ta-IN"] = "ta-IN-PallaviNeural", - _a["ta-LK"] = "ta-LK-KumarNeural", - _a["ta-SG"] = "ta-SG-AnbuNeural", - _a["te-IN"] = "te-IN-MohanNeural", - _a["th-TH"] = "th-TH-PremwadeeNeural", - _a["tr-TR"] = "tr-TR-AhmetNeural", - _a["uk-UA"] = "uk-UA-OstapNeural", - _a["ur-IN"] = "ur-IN-GulNeural", - _a["ur-PK"] = "ur-PK-AsadNeural", - _a["uz-UZ"] = "uz-UZ-MadinaNeural", - _a["vi-VN"] = "vi-VN-HoaiMyNeural", - _a["zh-CN"] = "zh-CN-XiaoxiaoNeural", - _a["zh-HK"] = "zh-HK-HiuMaanNeural", - _a["zh-TW"] = "zh-TW-HsiaoChenNeural", - _a["zu-ZA"] = "zu-ZA-ThandoNeural", - _a); - var language = this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_SynthLanguage, "en-US"); - var voice = this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_SynthVoice, ""); - var ssml = SpeechSynthesizer.XMLEncode(text); - if (this.autoDetectSourceLanguage) { - language = "en-US"; - } - else { - voice = voice || languageToDefaultVoice[language]; - } - if (voice) { - ssml = "" + ssml + ""; - } - ssml = "" + ssml + ""; - return ssml; - }; + } /** * Executes speech synthesis on plain text. * The task returns the synthesis result. @@ -18713,9 +13741,9 @@ var SpeechSynthesizer = /** @class */ (function () { * @param err - Callback invoked in case of an error. * @param stream - AudioOutputStream to receive the synthesized audio. */ - SpeechSynthesizer.prototype.speakTextAsync = function (text, cb, err, stream) { + speakTextAsync(text, cb, err, stream) { this.speakImpl(text, false, cb, err, stream); - }; + } /** * Executes speech synthesis on SSML. * The task returns the synthesis result. @@ -18727,9 +13755,37 @@ var SpeechSynthesizer = /** @class */ (function () { * @param err - Callback invoked in case of an error. * @param stream - AudioOutputStream to receive the synthesized audio. */ - SpeechSynthesizer.prototype.speakSsmlAsync = function (ssml, cb, err, stream) { + speakSsmlAsync(ssml, cb, err, stream) { this.speakImpl(ssml, true, cb, err, stream); - }; + } + /** + * Performs synthesis using a SpeechSynthesisRequest, which supports text streaming. + * This method is in preview and may be subject to change in future versions. + * @member SpeechSynthesizer.prototype.speakAsync + * @function + * @public + * @param request - The speech synthesis request (supports text streaming input). + * @param cb - Callback that received the SpeechSynthesisResult. + * @param err - Callback invoked in case of an error. + * @param stream - AudioOutputStream to receive the synthesized audio. + */ + speakAsync(request, cb, err, stream) { + try { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + const requestId = (0, Exports_js_2.createNoDashGuid)(); + const audioDestination = this.resolveAudioDestination(stream); + const { onSuccess, onError } = this.createSynthesisCallbacks(cb, err, () => { + /* eslint-disable no-empty */ + this.adapterSpeak().catch(() => { }); + }); + this.synthesisRequestQueue.enqueue(new Synthesizer_js_1.StreamingSynthesisRequest(requestId, request, onSuccess, onError, audioDestination)); + /* eslint-disable no-empty-function */ + this.adapterSpeak().catch(() => { }); + } + catch (error) { + this.handleSpeakError(error, err); + } + } /** * Get list of synthesis voices available. * The task returns the synthesis voice result. @@ -18740,127 +13796,88 @@ var SpeechSynthesizer = /** @class */ (function () { * @param locale - Locale of voices in BCP-47 format; if left empty, get all available voices. * @return {Promise} - Promise of a SynthesisVoicesResult. */ - SpeechSynthesizer.prototype.getVoicesAsync = function (locale) { - if (locale === void 0) { locale = ""; } - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, this.getVoices(locale)]; - }); - }); - }; + async getVoicesAsync(locale = "") { + return this.getVoices(locale); + } /** * Dispose of associated resources. * @member SpeechSynthesizer.prototype.close * @function * @public */ - SpeechSynthesizer.prototype.close = function (cb, err) { - Contracts_1.Contracts.throwIfDisposed(this.privDisposed); - Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, err); - }; - Object.defineProperty(SpeechSynthesizer.prototype, "internalData", { - /** - * @Internal - * Do not use externally, object returned will change without warning or notice. - */ - get: function () { - return this.privAdapter; - }, - enumerable: false, - configurable: true - }); + close(cb, err) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + (0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, err); + } /** - * This method performs cleanup of resources. - * The Boolean parameter disposing indicates whether the method is called - * from Dispose (if disposing is true) or from the finalizer (if disposing is false). - * Derived classes should override this method to dispose resource if needed. - * @member SpeechSynthesizer.prototype.dispose - * @function - * @public - * @param {boolean} disposing - Flag to request disposal. + * @Internal + * Do not use externally, object returned will change without warning or notice. */ - SpeechSynthesizer.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privDisposed) { - return [2 /*return*/]; - } - if (!disposing) return [3 /*break*/, 2]; - if (!this.privAdapter) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privAdapter.dispose()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - this.privDisposed = true; - return [2 /*return*/]; - } - }); - }); - }; + get internalData() { + return this.privAdapter; + } // // ################################################################################################################ // IMPLEMENTATION. - // Move to independent class // ################################################################################################################ // - SpeechSynthesizer.prototype.createSynthesizerConfig = function (speechConfig) { - return new Exports_1.SynthesizerConfig(speechConfig, this.privProperties); - }; // Creates the synthesis adapter - SpeechSynthesizer.prototype.createSynthesisAdapter = function (authentication, connectionFactory, audioConfig, synthesizerConfig) { - return new Exports_1.SynthesisAdapterBase(authentication, connectionFactory, synthesizerConfig, this, this.audioConfig); - }; - SpeechSynthesizer.prototype.implCommonSynthesizeSetup = function () { - var _this = this; - var osPlatform = (typeof window !== "undefined") ? "Browser" : "Node"; - var osName = "unknown"; - var osVersion = "unknown"; - if (typeof navigator !== "undefined") { - osPlatform = osPlatform + "/" + navigator.platform; - osName = navigator.userAgent; - osVersion = navigator.appVersion; - } - var synthesizerConfig = this.createSynthesizerConfig(new Exports_1.SpeechServiceConfig(new Exports_1.Context(new Exports_1.OS(osPlatform, osName, osVersion)))); - var subscriptionKey = this.privProperties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Key, undefined); - var authentication = (subscriptionKey && subscriptionKey !== "") ? - new Exports_1.CognitiveSubscriptionKeyAuthentication(subscriptionKey) : - new Exports_1.CognitiveTokenAuthentication(function (authFetchEventId) { - var authorizationToken = _this.privProperties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, undefined); - return Promise.resolve(authorizationToken); - }, function (authFetchEventId) { - var authorizationToken = _this.privProperties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, undefined); - return Promise.resolve(authorizationToken); - }); - this.privAdapter = this.createSynthesisAdapter(authentication, this.privConnectionFactory, this.audioConfig, synthesizerConfig); - this.privAdapter.audioOutputFormat = AudioOutputFormat_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(Exports_3.SpeechSynthesisOutputFormat[this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)]); - this.privRestAdapter = new Exports_1.SynthesisRestAdapter(synthesizerConfig); - }; - SpeechSynthesizer.prototype.speakImpl = function (text, IsSsml, cb, err, dataStream) { - var _this = this; + createSynthesisAdapter(authentication, connectionFactory, synthesizerConfig) { + return new Exports_js_1.SpeechSynthesisAdapter(authentication, connectionFactory, synthesizerConfig, this, this.audioConfig); + } + createRestSynthesisAdapter(authentication, synthesizerConfig) { + return new Exports_js_1.SynthesisRestAdapter(synthesizerConfig, authentication); + } + implCommonSynthesizeSetup() { + super.implCommonSynthesizeSetup(); + this.privAdapter.audioOutputFormat = AudioOutputFormat_js_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(Exports_js_3.SpeechSynthesisOutputFormat[this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)]); + } + speakImpl(text, IsSsml, cb, err, dataStream) { try { - Contracts_1.Contracts.throwIfDisposed(this.privDisposed); - var requestId = Exports_2.createNoDashGuid(); - var audioDestination = void 0; - if (dataStream instanceof Exports_3.PushAudioOutputStreamCallback) { - audioDestination = new AudioOutputStream_1.PushAudioOutputStreamImpl(dataStream); - } - else if (dataStream instanceof Exports_3.PullAudioOutputStream) { - audioDestination = dataStream; - } - else if (dataStream !== undefined) { - audioDestination = new AudioFileWriter_1.AudioFileWriter(dataStream); - } - else { - audioDestination = undefined; - } - this.synthesisRequestQueue.enqueue(new SynthesisRequest(requestId, text, IsSsml, function (e) { - _this.privSynthesizing = false; - if (!!cb) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + const requestId = (0, Exports_js_2.createNoDashGuid)(); + const audioDestination = this.resolveAudioDestination(dataStream); + const { onSuccess, onError } = this.createSynthesisCallbacks(cb, err, () => { + /* eslint-disable no-empty */ + this.adapterSpeak().catch(() => { }); + }); + this.synthesisRequestQueue.enqueue(new Synthesizer_js_1.SynthesisRequest(requestId, text, IsSsml, onSuccess, onError, audioDestination)); + /* eslint-disable no-empty-function */ + this.adapterSpeak().catch(() => { }); + } + catch (error) { + this.handleSpeakError(error, err); + } + } + resolveAudioDestination(stream) { + if (stream instanceof Exports_js_3.PushAudioOutputStreamCallback) { + return new AudioOutputStream_js_1.PushAudioOutputStreamImpl(stream); + } + else if (stream instanceof Exports_js_3.PullAudioOutputStream) { + return stream; + } + else if (stream !== undefined) { + return new AudioFileWriter_js_1.AudioFileWriter(stream); + } + return undefined; + } + createSynthesisCallbacks(cb, err, processNext) { + let successCb = cb; + return { + onError: (e) => { + this.privSynthesizing = false; + if (!!err) { + err(e); + } + if (processNext) { + processNext(); + } + }, + onSuccess: (e) => { + this.privSynthesizing = false; + if (!!successCb) { try { - cb(e); + successCb(e); } catch (e) { if (!!err) { @@ -18868,116 +13885,62 @@ var SpeechSynthesizer = /** @class */ (function () { } } } - cb = undefined; - /* tslint:disable:no-empty */ - _this.adapterSpeak().catch(function () { }); - }, function (e) { - if (!!err) { - err(e); + successCb = undefined; + if (processNext) { + processNext(); } - }, audioDestination)); - /* tslint:disable:no-empty */ - this.adapterSpeak().catch(function () { }); + } + }; + } + handleSpeakError(error, err) { + if (!!err) { + if (error instanceof Error) { + const typedError = error; + err(typedError.name + ": " + typedError.message); + } + else { + err(error); + } } - catch (error) { - if (!!err) { - if (error instanceof Error) { - var typedError = error; - err(typedError.name + ": " + typedError.message); - } - else { - err(error); - } + // Destroy the synthesizer. + /* eslint-disable no-empty */ + this.dispose(true).catch(() => { }); + } + async getVoices(locale) { + const requestId = (0, Exports_js_2.createNoDashGuid)(); + const response = await this.privRestAdapter.getVoicesList(requestId); + if (response.ok && Array.isArray(response.json)) { + let json = response.json; + if (!!locale && locale.length > 0) { + json = json.filter((item) => !!item.Locale && item.Locale.toLowerCase() === locale.toLowerCase()); } - // Destroy the synthesizer. - /* tslint:disable:no-empty */ - this.dispose(true).catch(function () { }); - } - }; - SpeechSynthesizer.prototype.getVoices = function (locale) { - return __awaiter(this, void 0, void 0, function () { - var requestId, response, json; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - requestId = Exports_2.createNoDashGuid(); - return [4 /*yield*/, this.privRestAdapter.getVoicesList(requestId)]; - case 1: - response = _a.sent(); - if (response.ok && Array.isArray(response.json)) { - json = response.json; - if (!!locale && locale.length > 0) { - json = json.filter(function (item) { return !!item.Locale && item.Locale.toLowerCase() === locale.toLowerCase(); }); - } - return [2 /*return*/, new Exports_3.SynthesisVoicesResult(requestId, json)]; - } - else { - return [2 /*return*/, new Exports_3.SynthesisVoicesResult(requestId, { errorDetails: "Error: " + response.status + ": " + response.statusText })]; - } - return [2 /*return*/]; - } - }); - }); - }; - SpeechSynthesizer.prototype.adapterSpeak = function () { - return __awaiter(this, void 0, void 0, function () { - var request; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!this.privDisposed && !this.privSynthesizing)) return [3 /*break*/, 2]; - this.privSynthesizing = true; - return [4 /*yield*/, this.synthesisRequestQueue.dequeue()]; - case 1: - request = _a.sent(); - return [2 /*return*/, this.privAdapter.Speak(request.text, request.isSSML, request.requestId, request.cb, request.err, request.dataStream)]; - case 2: return [2 /*return*/]; - } - }); - }); - }; - SpeechSynthesizer.XMLEncode = function (text) { - return text.replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); - }; - return SpeechSynthesizer; -}()); -exports.SpeechSynthesizer = SpeechSynthesizer; -// tslint:disable-next-line:max-classes-per-file -var SynthesisRequest = /** @class */ (function () { - function SynthesisRequest(requestId, text, isSSML, cb, err, dataStream) { - this.requestId = requestId; - this.text = text; - this.isSSML = isSSML; - this.cb = cb; - this.err = err; - this.dataStream = dataStream; + return new Exports_js_3.SynthesisVoicesResult(requestId, json, undefined); + } + else { + return new Exports_js_3.SynthesisVoicesResult(requestId, undefined, `Error: ${response.status}: ${response.statusText}`); + } } - return SynthesisRequest; -}()); -exports.SynthesisRequest = SynthesisRequest; +} +exports.SpeechSynthesizer = SpeechSynthesizer; /***/ }), /* 157 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SynthesisResult = void 0; /** * Base class for synthesis results * @class SynthesisResult * Added in version 1.20.0 */ -var SynthesisResult = /** @class */ (function () { +class SynthesisResult { /** * Creates and initializes an instance of this class. * @constructor @@ -18986,13455 +13949,8399 @@ var SynthesisResult = /** @class */ (function () { * @param {string} errorDetails - Error details, if provided. * @param {PropertyCollection} properties - Additional properties, if provided. */ - function SynthesisResult(resultId, reason, errorDetails, properties) { + constructor(resultId, reason, errorDetails, properties) { this.privResultId = resultId; this.privReason = reason; this.privErrorDetails = errorDetails; this.privProperties = properties; } - Object.defineProperty(SynthesisResult.prototype, "resultId", { - /** - * Specifies the result identifier. - * @member SynthesisResult.prototype.resultId - * @function - * @public - * @returns {string} Specifies the result identifier. - */ - get: function () { - return this.privResultId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisResult.prototype, "reason", { - /** - * Specifies status of the result. - * @member SynthesisResult.prototype.reason - * @function - * @public - * @returns {ResultReason} Specifies status of the result. - */ - get: function () { - return this.privReason; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisResult.prototype, "errorDetails", { - /** - * In case of an unsuccessful synthesis, provides details of the occurred error. - * @member SynthesisResult.prototype.errorDetails - * @function - * @public - * @returns {string} a brief description of an error. - */ - get: function () { - return this.privErrorDetails; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisResult.prototype, "properties", { - /** - * The set of properties exposed in the result. - * @member SynthesisResult.prototype.properties - * @function - * @public - * @returns {PropertyCollection} The set of properties exposed in the result. - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - return SynthesisResult; -}()); + /** + * Specifies the result identifier. + * @member SynthesisResult.prototype.resultId + * @function + * @public + * @returns {string} Specifies the result identifier. + */ + get resultId() { + return this.privResultId; + } + /** + * Specifies status of the result. + * @member SynthesisResult.prototype.reason + * @function + * @public + * @returns {ResultReason} Specifies status of the result. + */ + get reason() { + return this.privReason; + } + /** + * In case of an unsuccessful synthesis, provides details of the occurred error. + * @member SynthesisResult.prototype.errorDetails + * @function + * @public + * @returns {string} a brief description of an error. + */ + get errorDetails() { + return this.privErrorDetails; + } + /** + * The set of properties exposed in the result. + * @member SynthesisResult.prototype.properties + * @function + * @public + * @returns {PropertyCollection} The set of properties exposed in the result. + */ + get properties() { + return this.privProperties; + } +} exports.SynthesisResult = SynthesisResult; /***/ }), /* 158 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpeechSynthesisResult = void 0; -var Exports_1 = __webpack_require__(61); +const Exports_js_1 = __webpack_require__(85); /** * Defines result of speech synthesis. * @class SpeechSynthesisResult * Added in version 1.11.0 */ -var SpeechSynthesisResult = /** @class */ (function (_super) { - __extends(SpeechSynthesisResult, _super); +class SpeechSynthesisResult extends Exports_js_1.SynthesisResult { /** * Creates and initializes an instance of this class. * @constructor * @param {string} resultId - The result id. * @param {ResultReason} reason - The reason. - * @param {number} audioData - The offset into the stream. + * @param {ArrayBuffer} audioData - The synthesized audio binary. * @param {string} errorDetails - Error details, if provided. * @param {PropertyCollection} properties - Additional properties, if provided. + * @param {number} audioDuration - The audio duration. */ - function SpeechSynthesisResult(resultId, reason, audioData, errorDetails, properties) { - var _this = _super.call(this, resultId, reason, errorDetails, properties) || this; - _this.privAudioData = audioData; - return _this; - } - Object.defineProperty(SpeechSynthesisResult.prototype, "audioData", { - /** - * The synthesized audio data - * @member SpeechSynthesisResult.prototype.audioData - * @function - * @public - * @returns {ArrayBuffer} The synthesized audio data. - */ - get: function () { - return this.privAudioData; - }, - enumerable: false, - configurable: true - }); - return SpeechSynthesisResult; -}(Exports_1.SynthesisResult)); -exports.SpeechSynthesisResult = SpeechSynthesisResult; - - - -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechSynthesisEventArgs = void 0; -/** - * Defines contents of speech synthesis events. - * @class SpeechSynthesisEventArgs - * Added in version 1.11.0 - */ -var SpeechSynthesisEventArgs = /** @class */ (function () { - /** - * Creates and initializes an instance of this class. - * @constructor - * @param {SpeechSynthesisResult} result - The speech synthesis result. - */ - function SpeechSynthesisEventArgs(result) { - this.privResult = result; - } - Object.defineProperty(SpeechSynthesisEventArgs.prototype, "result", { - /** - * Specifies the synthesis result. - * @member SpeechSynthesisEventArgs.prototype.result - * @function - * @public - * @returns {SpeechSynthesisResult} the synthesis result. - */ - get: function () { - return this.privResult; - }, - enumerable: false, - configurable: true - }); - return SpeechSynthesisEventArgs; -}()); -exports.SpeechSynthesisEventArgs = SpeechSynthesisEventArgs; - - - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechSynthesisWordBoundaryEventArgs = void 0; -/** - * Defines contents of speech synthesis word boundary event. - * @class SpeechSynthesisWordBoundaryEventArgs - * Added in version 1.11.0 - */ -var SpeechSynthesisWordBoundaryEventArgs = /** @class */ (function () { - /** - * Creates and initializes an instance of this class. - * @constructor - * @param {number} audioOffset - The audio offset. - * @param {string} text - The text. - * @param {number} wordLength - The length of the word. - * @param {number} textOffset - The text offset. - */ - function SpeechSynthesisWordBoundaryEventArgs(audioOffset, text, wordLength, textOffset) { - this.privAudioOffset = audioOffset; - this.privText = text; - this.privWordLength = wordLength; - this.privTextOffset = textOffset; + constructor(resultId, reason, audioData, errorDetails, properties, audioDuration) { + super(resultId, reason, errorDetails, properties); + this.privAudioData = audioData; + this.privAudioDuration = audioDuration; } - Object.defineProperty(SpeechSynthesisWordBoundaryEventArgs.prototype, "audioOffset", { - /** - * Specifies the audio offset. - * @member SpeechSynthesisWordBoundaryEventArgs.prototype.audioOffset - * @function - * @public - * @returns {number} the audio offset. - */ - get: function () { - return this.privAudioOffset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechSynthesisWordBoundaryEventArgs.prototype, "text", { - /** - * Specifies the text of the word boundary event. - * @member SpeechSynthesisWordBoundaryEventArgs.prototype.text - * @function - * @public - * @returns {string} the text. - */ - get: function () { - return this.privText; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechSynthesisWordBoundaryEventArgs.prototype, "wordLength", { - /** - * Specifies the word length - * @member SpeechSynthesisWordBoundaryEventArgs.prototype.wordLength - * @function - * @public - * @returns {number} the word length - */ - get: function () { - return this.privWordLength; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechSynthesisWordBoundaryEventArgs.prototype, "textOffset", { - /** - * Specifies the text offset. - * @member SpeechSynthesisWordBoundaryEventArgs.prototype.textOffset - * @function - * @public - * @returns {number} the text offset. - */ - get: function () { - return this.privTextOffset; - }, - enumerable: false, - configurable: true - }); - return SpeechSynthesisWordBoundaryEventArgs; -}()); -exports.SpeechSynthesisWordBoundaryEventArgs = SpeechSynthesisWordBoundaryEventArgs; - - - -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechSynthesisBookmarkEventArgs = void 0; -/** - * Defines contents of speech synthesis bookmark event. - * @class SpeechSynthesisBookmarkEventArgs - * Added in version 1.16.0 - */ -var SpeechSynthesisBookmarkEventArgs = /** @class */ (function () { /** - * Creates and initializes an instance of this class. - * @constructor - * @param {number} audioOffset - The audio offset. - * @param {string} text - The bookmark text. + * The synthesized audio data + * @member SpeechSynthesisResult.prototype.audioData + * @function + * @public + * @returns {ArrayBuffer} The synthesized audio data. */ - function SpeechSynthesisBookmarkEventArgs(audioOffset, text) { - this.privAudioOffset = audioOffset; - this.privText = text; + get audioData() { + return this.privAudioData; } - Object.defineProperty(SpeechSynthesisBookmarkEventArgs.prototype, "audioOffset", { - /** - * Specifies the audio offset. - * @member SpeechSynthesisBookmarkEventArgs.prototype.audioOffset - * @function - * @public - * @returns {number} the audio offset. - */ - get: function () { - return this.privAudioOffset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechSynthesisBookmarkEventArgs.prototype, "text", { - /** - * Specifies the bookmark. - * @member SpeechSynthesisBookmarkEventArgs.prototype.text - * @function - * @public - * @returns {string} the bookmark text. - */ - get: function () { - return this.privText; - }, - enumerable: false, - configurable: true - }); - return SpeechSynthesisBookmarkEventArgs; -}()); -exports.SpeechSynthesisBookmarkEventArgs = SpeechSynthesisBookmarkEventArgs; - - - -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechSynthesisVisemeEventArgs = void 0; -/** - * Defines contents of speech synthesis viseme event. - * @class SpeechSynthesisVisemeEventArgs - * Added in version 1.16.0 - */ -var SpeechSynthesisVisemeEventArgs = /** @class */ (function () { /** - * Creates and initializes an instance of this class. - * @constructor - * @param {number} audioOffset - The audio offset. - * @param {number} visemeId - The viseme ID. - * @param {string} animation - The animation, could be in svg or other format. - */ - function SpeechSynthesisVisemeEventArgs(audioOffset, visemeId, animation) { - this.privAudioOffset = audioOffset; - this.privVisemeId = visemeId; - this.privAnimation = animation; - } - Object.defineProperty(SpeechSynthesisVisemeEventArgs.prototype, "audioOffset", { - /** - * Specifies the audio offset. - * @member SpeechSynthesisVisemeEventArgs.prototype.audioOffset - * @function - * @public - * @returns {number} the audio offset. - */ - get: function () { - return this.privAudioOffset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechSynthesisVisemeEventArgs.prototype, "visemeId", { - /** - * Specifies the viseme ID. - * @member SpeechSynthesisVisemeEventArgs.prototype.visemeId - * @function - * @public - * @returns {number} the viseme ID. - */ - get: function () { - return this.privVisemeId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechSynthesisVisemeEventArgs.prototype, "animation", { - /** - * Specifies the animation. - * @member SpeechSynthesisVisemeEventArgs.prototype.animation - * @function - * @public - * @returns {string} the animation, could be in svg or other format. - */ - get: function () { - return this.privAnimation; - }, - enumerable: false, - configurable: true - }); - return SpeechSynthesisVisemeEventArgs; -}()); -exports.SpeechSynthesisVisemeEventArgs = SpeechSynthesisVisemeEventArgs; + * The time duration of synthesized audio, in ticks (100 nanoseconds). + * @member SpeechSynthesisResult.prototype.audioDuration + * @function + * @public + * @returns {number} The time duration of synthesized audio. + */ + get audioDuration() { + return this.privAudioDuration; + } +} +exports.SpeechSynthesisResult = SpeechSynthesisResult; /***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { +/* 159 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesisVoicesResult = void 0; -var Exports_1 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisEventArgs = void 0; /** - * Defines result of speech synthesis. - * @class SynthesisVoicesResult - * Added in version 1.20.0 + * Defines contents of speech synthesis events. + * @class SpeechSynthesisEventArgs + * Added in version 1.11.0 */ -var SynthesisVoicesResult = /** @class */ (function (_super) { - __extends(SynthesisVoicesResult, _super); +class SpeechSynthesisEventArgs { /** * Creates and initializes an instance of this class. * @constructor - * @param requestId - result id for request. - * @param json - json payload from endpoint. + * @param {SpeechSynthesisResult} result - The speech synthesis result. */ - function SynthesisVoicesResult(requestId, json) { - var _this = this; - if (Array.isArray(json)) { - _this = _super.call(this, requestId, Exports_1.ResultReason.VoicesListRetrieved, undefined, new Exports_1.PropertyCollection()) || this; - _this.privVoices = []; - for (var _i = 0, json_1 = json; _i < json_1.length; _i++) { - var item = json_1[_i]; - _this.privVoices.push(new Exports_1.VoiceInfo(item)); - } - } - else { - _this = _super.call(this, requestId, Exports_1.ResultReason.Canceled, !!json.errorDetails ? json.errorDetails : "Error information unavailable", new Exports_1.PropertyCollection()) || this; - } - return _this; - } - Object.defineProperty(SynthesisVoicesResult.prototype, "voices", { - /** - * The list of voices - * @member SynthesisVoicesResult.prototype.voices - * @function - * @public - * @returns {VoiceInfo[]} List of synthesized voices. - */ - get: function () { - return this.privVoices; - }, - enumerable: false, - configurable: true - }); - return SynthesisVoicesResult; -}(Exports_1.SynthesisResult)); -exports.SynthesisVoicesResult = SynthesisVoicesResult; + constructor(result) { + this.privResult = result; + } + /** + * Specifies the synthesis result. + * @member SpeechSynthesisEventArgs.prototype.result + * @function + * @public + * @returns {SpeechSynthesisResult} the synthesis result. + */ + get result() { + return this.privResult; + } +} +exports.SpeechSynthesisEventArgs = SpeechSynthesisEventArgs; /***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { +/* 160 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VoiceInfo = exports.SynthesisVoiceType = exports.SynthesisVoiceGender = void 0; -/** - * Defines the gender of synthesis voices. - * Added in version 1.20.0. - */ -var SynthesisVoiceGender; -(function (SynthesisVoiceGender) { - /** Gender unknown */ - SynthesisVoiceGender[SynthesisVoiceGender["Unknown"] = 0] = "Unknown"; - /** Female voice */ - SynthesisVoiceGender[SynthesisVoiceGender["Female"] = 1] = "Female"; - /** Male voice */ - SynthesisVoiceGender[SynthesisVoiceGender["Male"] = 2] = "Male"; -})(SynthesisVoiceGender = exports.SynthesisVoiceGender || (exports.SynthesisVoiceGender = {})); -var SynthesisVoiceType; -(function (SynthesisVoiceType) { - SynthesisVoiceType[SynthesisVoiceType["OnlineNeural"] = 1] = "OnlineNeural"; - SynthesisVoiceType[SynthesisVoiceType["OnlineStandard"] = 2] = "OnlineStandard"; - SynthesisVoiceType[SynthesisVoiceType["OfflineNeural"] = 3] = "OfflineNeural"; - SynthesisVoiceType[SynthesisVoiceType["OfflineStandard"] = 4] = "OfflineStandard"; -})(SynthesisVoiceType = exports.SynthesisVoiceType || (exports.SynthesisVoiceType = {})); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisWordBoundaryEventArgs = void 0; /** - * Information about Speech Synthesis voice - * Added in version 1.20.0. - * @class VoiceInfo + * Defines contents of speech synthesis word boundary event. + * @class SpeechSynthesisWordBoundaryEventArgs + * Added in version 1.11.0 */ -var VoiceInfo = /** @class */ (function () { - function VoiceInfo(json) { - this.privStyleList = []; - this.privVoicePath = ""; - if (!!json) { - this.privName = json.Name; - this.privLocale = json.Locale; - this.privShortName = json.ShortName; - this.privLocalName = json.LocalName; - this.privVoiceType = json.VoiceType.endsWith("Standard") ? SynthesisVoiceType.OnlineStandard : SynthesisVoiceType.OnlineNeural; - this.privGender = json.Gender === "Male" ? SynthesisVoiceGender.Male : json.Gender === "Female" ? SynthesisVoiceGender.Female : SynthesisVoiceGender.Unknown; - if (!!json.StyleList && Array.isArray(json.StyleList)) { - for (var _i = 0, _a = json.StyleList; _i < _a.length; _i++) { - var style = _a[_i]; - this.privStyleList.push(style); - } - } - } +class SpeechSynthesisWordBoundaryEventArgs { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {number} audioOffset - The audio offset. + * @param {number} duration - The audio duration. + * @param {string} text - The text. + * @param {number} wordLength - The length of the word. + * @param {number} textOffset - The text offset. + * @param {SpeechSynthesisBoundaryType} boundaryType - The boundary type + */ + constructor(audioOffset, duration, text, wordLength, textOffset, boundaryType) { + this.privAudioOffset = audioOffset; + this.privDuration = duration; + this.privText = text; + this.privWordLength = wordLength; + this.privTextOffset = textOffset; + this.privBoundaryType = boundaryType; } - Object.defineProperty(VoiceInfo.prototype, "name", { - get: function () { - return this.privName; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceInfo.prototype, "locale", { - get: function () { - return this.privLocale; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceInfo.prototype, "shortName", { - get: function () { - return this.privShortName; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceInfo.prototype, "localName", { - get: function () { - return this.privLocalName; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceInfo.prototype, "gender", { - get: function () { - return this.privGender; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceInfo.prototype, "voiceType", { - get: function () { - return this.privVoiceType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceInfo.prototype, "styleList", { - get: function () { - return this.privStyleList; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VoiceInfo.prototype, "voicePath", { - get: function () { - return this.privVoicePath; - }, - enumerable: false, - configurable: true - }); - return VoiceInfo; -}()); -exports.VoiceInfo = VoiceInfo; - - - -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + /** + * Specifies the audio offset. + * @member SpeechSynthesisWordBoundaryEventArgs.prototype.audioOffset + * @function + * @public + * @returns {number} the audio offset. + */ + get audioOffset() { + return this.privAudioOffset; } -}; -var _a; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeakerAudioDestination = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var AudioOutputStream_1 = __webpack_require__(73); -var AudioStreamFormat_1 = __webpack_require__(72); -var MediaDurationPlaceholderSeconds = 60 * 30; -var AudioFormatToMimeType = (_a = {}, - _a[AudioStreamFormat_1.AudioFormatTag.PCM] = "audio/wav", - _a[AudioStreamFormat_1.AudioFormatTag.MuLaw] = "audio/x-wav", - _a[AudioStreamFormat_1.AudioFormatTag.MP3] = "audio/mpeg", - _a[AudioStreamFormat_1.AudioFormatTag.OGG_OPUS] = "audio/ogg", - _a[AudioStreamFormat_1.AudioFormatTag.WEBM_OPUS] = "audio/webm; codecs=opus", - _a[AudioStreamFormat_1.AudioFormatTag.ALaw] = "audio/x-wav", - _a[AudioStreamFormat_1.AudioFormatTag.FLAC] = "audio/flac", - _a); -/** - * Represents the speaker playback audio destination, which only works in browser. - * Note: the SDK will try to use Media Source Extensions to play audio. - * Mp3 format has better supports on Microsoft Edge, Chrome and Safari (desktop), so, it's better to specify mp3 format for playback. - * @class SpeakerAudioDestination - * Updated in version 1.17.0 - */ -var SpeakerAudioDestination = /** @class */ (function () { - function SpeakerAudioDestination(audioDestinationId) { - this.privPlaybackStarted = false; - this.privAppendingToBuffer = false; - this.privMediaSourceOpened = false; - this.privBytesReceived = 0; - this.privId = audioDestinationId ? audioDestinationId : Exports_2.createNoDashGuid(); - this.privIsPaused = false; - this.privIsClosed = false; + /** + * Specifies the duration, in ticks (100 nanoseconds). + * @member SpeechSynthesisWordBoundaryEventArgs.prototype.duration + * @function + * @public + * @returns {number} Duration in 100 nanosecond increments. + */ + get duration() { + return this.privDuration; } - SpeakerAudioDestination.prototype.id = function () { - return this.privId; - }; - SpeakerAudioDestination.prototype.write = function (buffer, cb, err) { - if (this.privAudioBuffer !== undefined) { - this.privAudioBuffer.push(buffer); - this.updateSourceBuffer().then(function () { - if (!!cb) { - cb(); - } - }, function (error) { - if (!!err) { - err(error); - } - }); - } - else if (this.privAudioOutputStream !== undefined) { - this.privAudioOutputStream.write(buffer); - this.privBytesReceived += buffer.byteLength; - } - }; - SpeakerAudioDestination.prototype.close = function (cb, err) { - var _this = this; - this.privIsClosed = true; - if (this.privSourceBuffer !== undefined) { - this.handleSourceBufferUpdateEnd().then(function () { - if (!!cb) { - cb(); - } - }, function (error) { - if (!!err) { - err(error); - } - }); - } - else if (this.privAudioOutputStream !== undefined) { - if ((this.privFormat.formatTag === AudioStreamFormat_1.AudioFormatTag.PCM || this.privFormat.formatTag === AudioStreamFormat_1.AudioFormatTag.MuLaw - || this.privFormat.formatTag === AudioStreamFormat_1.AudioFormatTag.ALaw) && this.privFormat.hasHeader === false) { - // tslint:disable-next-line:no-console - console.warn("Play back is not supported for raw PCM, mulaw or alaw format without header."); - if (!!this.onAudioEnd) { - this.onAudioEnd(this); - } - } - else { - var receivedAudio_1 = new ArrayBuffer(this.privBytesReceived); - this.privAudioOutputStream.read(receivedAudio_1).then(function (_) { - receivedAudio_1 = Exports_1.SynthesisAdapterBase.addHeader(receivedAudio_1, _this.privFormat); - var audioBlob = new Blob([receivedAudio_1], { type: AudioFormatToMimeType[_this.privFormat.formatTag] }); - _this.privAudio.src = window.URL.createObjectURL(audioBlob); - _this.notifyPlayback().then(function () { - if (!!cb) { - cb(); - } - }, function (error) { - if (!!err) { - err(error); - } - }); - }, function (error) { - if (!!err) { - err(error); - } - }); - } - } - else { - // unsupported format, call onAudioEnd directly. - if (!!this.onAudioEnd) { - this.onAudioEnd(this); - } - } - }; - Object.defineProperty(SpeakerAudioDestination.prototype, "format", { - set: function (format) { - var _this = this; - if (typeof (AudioContext) !== "undefined" || typeof (window.webkitAudioContext) !== "undefined") { - this.privFormat = format; - var mimeType_1 = AudioFormatToMimeType[this.privFormat.formatTag]; - if (mimeType_1 === undefined) { - // tslint:disable-next-line:no-console - console.warn("Unknown mimeType for format " + AudioStreamFormat_1.AudioFormatTag[this.privFormat.formatTag] + "; playback is not supported."); - } - else if (typeof (MediaSource) !== "undefined" && MediaSource.isTypeSupported(mimeType_1)) { - this.privAudio = new Audio(); - this.privAudioBuffer = []; - this.privMediaSource = new MediaSource(); - this.privAudio.src = URL.createObjectURL(this.privMediaSource); - this.privAudio.load(); - this.privMediaSource.onsourceopen = function (event) { - _this.privMediaSourceOpened = true; - _this.privMediaSource.duration = MediaDurationPlaceholderSeconds; - _this.privSourceBuffer = _this.privMediaSource.addSourceBuffer(mimeType_1); - _this.privSourceBuffer.onupdate = function (_) { - _this.updateSourceBuffer().catch(function (reason) { - Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason)); - }); - }; - _this.privSourceBuffer.onupdateend = function (_) { - _this.handleSourceBufferUpdateEnd().catch(function (reason) { - Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason)); - }); - }; - _this.privSourceBuffer.onupdatestart = function (_) { - _this.privAppendingToBuffer = false; - }; - }; - this.updateSourceBuffer().catch(function (reason) { - Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason)); - }); - } - else { - // tslint:disable-next-line:no-console - console.warn("Format " + AudioStreamFormat_1.AudioFormatTag[this.privFormat.formatTag] + " could not be played by MSE, streaming playback is not enabled."); - this.privAudioOutputStream = new AudioOutputStream_1.PullAudioOutputStreamImpl(); - this.privAudioOutputStream.format = this.privFormat; - this.privAudio = new Audio(); - } - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeakerAudioDestination.prototype, "volume", { - get: function () { - return this.privAudio.volume; - }, - set: function (volume) { - this.privAudio.volume = volume; - }, - enumerable: false, - configurable: true - }); - SpeakerAudioDestination.prototype.mute = function () { - this.privAudio.muted = true; - }; - SpeakerAudioDestination.prototype.unmute = function () { - this.privAudio.muted = false; - }; - Object.defineProperty(SpeakerAudioDestination.prototype, "isClosed", { - get: function () { - return this.privIsClosed; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeakerAudioDestination.prototype, "currentTime", { - get: function () { - if (this.privAudio !== undefined) { - return this.privAudio.currentTime; - } - return -1; - }, - enumerable: false, - configurable: true - }); - SpeakerAudioDestination.prototype.pause = function () { - if (!this.privIsPaused && this.privAudio !== undefined) { - this.privAudio.pause(); - this.privIsPaused = true; - } - }; - SpeakerAudioDestination.prototype.resume = function (cb, err) { - if (this.privIsPaused && this.privAudio !== undefined) { - this.privAudio.play().then(function () { - if (!!cb) { - cb(); - } - }, function (error) { - if (!!err) { - err(error); - } - }); - this.privIsPaused = false; - } - }; - Object.defineProperty(SpeakerAudioDestination.prototype, "internalAudio", { - get: function () { - return this.privAudio; - }, - enumerable: false, - configurable: true - }); - SpeakerAudioDestination.prototype.updateSourceBuffer = function () { - return __awaiter(this, void 0, void 0, function () { - var binary; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(this.privAudioBuffer !== undefined && (this.privAudioBuffer.length > 0) && this.sourceBufferAvailable())) return [3 /*break*/, 2]; - this.privAppendingToBuffer = true; - binary = this.privAudioBuffer.shift(); - try { - this.privSourceBuffer.appendBuffer(binary); - } - catch (error) { - this.privAudioBuffer.unshift(binary); - // tslint:disable-next-line:no-console - console.log("buffer filled, pausing addition of binaries until space is made"); - return [2 /*return*/]; - } - return [4 /*yield*/, this.notifyPlayback()]; - case 1: - _a.sent(); - return [3 /*break*/, 4]; - case 2: - if (!this.canEndStream()) return [3 /*break*/, 4]; - return [4 /*yield*/, this.handleSourceBufferUpdateEnd()]; - case 3: - _a.sent(); - _a.label = 4; - case 4: return [2 /*return*/]; - } - }); - }); - }; - SpeakerAudioDestination.prototype.handleSourceBufferUpdateEnd = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(this.canEndStream() && this.sourceBufferAvailable())) return [3 /*break*/, 2]; - this.privMediaSource.endOfStream(); - return [4 /*yield*/, this.notifyPlayback()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - SpeakerAudioDestination.prototype.notifyPlayback = function () { - return __awaiter(this, void 0, void 0, function () { - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!this.privPlaybackStarted && this.privAudio !== undefined)) return [3 /*break*/, 2]; - this.privPlaybackStarted = true; - if (!!this.onAudioStart) { - this.onAudioStart(this); - } - this.privAudio.onended = function () { - if (!!_this.onAudioEnd) { - _this.onAudioEnd(_this); - } - }; - if (!!this.privIsPaused) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privAudio.play()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - SpeakerAudioDestination.prototype.canEndStream = function () { - return (this.isClosed && this.privSourceBuffer !== undefined && (this.privAudioBuffer.length === 0) - && this.privMediaSourceOpened && !this.privAppendingToBuffer && this.privMediaSource.readyState === "open"); - }; - SpeakerAudioDestination.prototype.sourceBufferAvailable = function () { - return (this.privSourceBuffer !== undefined && !this.privSourceBuffer.updating); - }; - return SpeakerAudioDestination; -}()); -exports.SpeakerAudioDestination = SpeakerAudioDestination; + /** + * Specifies the text of the word boundary event. + * @member SpeechSynthesisWordBoundaryEventArgs.prototype.text + * @function + * @public + * @returns {string} the text. + */ + get text() { + return this.privText; + } + /** + * Specifies the word length + * @member SpeechSynthesisWordBoundaryEventArgs.prototype.wordLength + * @function + * @public + * @returns {number} the word length + */ + get wordLength() { + return this.privWordLength; + } + /** + * Specifies the text offset. + * @member SpeechSynthesisWordBoundaryEventArgs.prototype.textOffset + * @function + * @public + * @returns {number} the text offset. + */ + get textOffset() { + return this.privTextOffset; + } + /** + * Specifies the boundary type. + * @member SpeechSynthesisWordBoundaryEventArgs.prototype.boundaryType + * @function + * @public + * @returns {SpeechSynthesisBoundaryType} the boundary type. + */ + get boundaryType() { + return this.privBoundaryType; + } +} +exports.SpeechSynthesisWordBoundaryEventArgs = SpeechSynthesisWordBoundaryEventArgs; /***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { +/* 161 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranscriptionCanceledEventArgs = void 0; -var CancellationEventArgsBase_1 = __webpack_require__(90); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisBookmarkEventArgs = void 0; /** - * Defines content of a RecognitionErrorEvent. - * @class ConversationTranscriptionCanceledEventArgs + * Defines contents of speech synthesis bookmark event. + * @class SpeechSynthesisBookmarkEventArgs + * Added in version 1.16.0 */ -var ConversationTranscriptionCanceledEventArgs = /** @class */ (function (_super) { - __extends(ConversationTranscriptionCanceledEventArgs, _super); - function ConversationTranscriptionCanceledEventArgs() { - return _super !== null && _super.apply(this, arguments) || this; +class SpeechSynthesisBookmarkEventArgs { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {number} audioOffset - The audio offset. + * @param {string} text - The bookmark text. + */ + constructor(audioOffset, text) { + this.privAudioOffset = audioOffset; + this.privText = text; } - return ConversationTranscriptionCanceledEventArgs; -}(CancellationEventArgsBase_1.CancellationEventArgsBase)); -exports.ConversationTranscriptionCanceledEventArgs = ConversationTranscriptionCanceledEventArgs; + /** + * Specifies the audio offset. + * @member SpeechSynthesisBookmarkEventArgs.prototype.audioOffset + * @function + * @public + * @returns {number} the audio offset. + */ + get audioOffset() { + return this.privAudioOffset; + } + /** + * Specifies the bookmark. + * @member SpeechSynthesisBookmarkEventArgs.prototype.text + * @function + * @public + * @returns {string} the bookmark text. + */ + get text() { + return this.privText; + } +} +exports.SpeechSynthesisBookmarkEventArgs = SpeechSynthesisBookmarkEventArgs; /***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { +/* 162 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PronunciationAssessmentGradingSystem = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisVisemeEventArgs = void 0; /** - * Defines the point system for pronunciation score calibration; default value is FivePoint. - * Added in version 1.15.0 - * @class PronunciationAssessmentGradingSystem + * Defines contents of speech synthesis viseme event. + * @class SpeechSynthesisVisemeEventArgs + * Added in version 1.16.0 */ -var PronunciationAssessmentGradingSystem; -(function (PronunciationAssessmentGradingSystem) { +class SpeechSynthesisVisemeEventArgs { /** - * Five point calibration - * @member PronunciationAssessmentGradingSystem.FivePoint + * Creates and initializes an instance of this class. + * @constructor + * @param {number} audioOffset - The audio offset. + * @param {number} visemeId - The viseme ID. + * @param {string} animation - The animation, could be in svg or other format. */ - PronunciationAssessmentGradingSystem[PronunciationAssessmentGradingSystem["FivePoint"] = 1] = "FivePoint"; + constructor(audioOffset, visemeId, animation) { + this.privAudioOffset = audioOffset; + this.privVisemeId = visemeId; + this.privAnimation = animation; + } /** - * Hundred mark - * @member PronunciationAssessmentGradingSystem.HundredMark + * Specifies the audio offset. + * @member SpeechSynthesisVisemeEventArgs.prototype.audioOffset + * @function + * @public + * @returns {number} the audio offset. */ - PronunciationAssessmentGradingSystem[PronunciationAssessmentGradingSystem["HundredMark"] = 2] = "HundredMark"; -})(PronunciationAssessmentGradingSystem = exports.PronunciationAssessmentGradingSystem || (exports.PronunciationAssessmentGradingSystem = {})); + get audioOffset() { + return this.privAudioOffset; + } + /** + * Specifies the viseme ID. + * @member SpeechSynthesisVisemeEventArgs.prototype.visemeId + * @function + * @public + * @returns {number} the viseme ID. + */ + get visemeId() { + return this.privVisemeId; + } + /** + * Specifies the animation. + * @member SpeechSynthesisVisemeEventArgs.prototype.animation + * @function + * @public + * @returns {string} the animation, could be in svg or other format. + */ + get animation() { + return this.privAnimation; + } +} +exports.SpeechSynthesisVisemeEventArgs = SpeechSynthesisVisemeEventArgs; /***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { +/* 163 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PronunciationAssessmentGranularity = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisBoundaryType = void 0; /** - * Defines the pronunciation evaluation granularity; default value is Phoneme. - * Added in version 1.15.0 - * @class PronunciationAssessmentGranularity + * Defines the boundary type of speech synthesis boundary event. + * @class SpeechSynthesisBoundaryType + * Added in version 1.21.0 */ -var PronunciationAssessmentGranularity; -(function (PronunciationAssessmentGranularity) { +var SpeechSynthesisBoundaryType; +(function (SpeechSynthesisBoundaryType) { /** - * Shows the score on the full text, word and phoneme level - * @member PronunciationAssessmentGranularity.Phoneme + * Indicates the boundary text is a word. + * @member SpeechSynthesisBoundaryType.Word */ - PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["Phoneme"] = 1] = "Phoneme"; + SpeechSynthesisBoundaryType["Word"] = "WordBoundary"; /** - * Shows the score on the full text and word level - * @member PronunciationAssessmentGranularity.Word + * Indicates the boundary text is a punctuation. + * @member SpeechSynthesisBoundaryType.Punctuation */ - PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["Word"] = 2] = "Word"; + SpeechSynthesisBoundaryType["Punctuation"] = "PunctuationBoundary"; /** - * Shows the score on the full text level only - * @member PronunciationAssessmentGranularity.FullText + * Indicates the boundary text is a sentence. + * @member SpeechSynthesisBoundaryType.Sentence */ - PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["FullText"] = 3] = "FullText"; -})(PronunciationAssessmentGranularity = exports.PronunciationAssessmentGranularity || (exports.PronunciationAssessmentGranularity = {})); + SpeechSynthesisBoundaryType["Sentence"] = "SentenceBoundary"; +})(SpeechSynthesisBoundaryType = exports.SpeechSynthesisBoundaryType || (exports.SpeechSynthesisBoundaryType = {})); /***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { +/* 164 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PronunciationAssessmentConfig = void 0; -var Contracts_1 = __webpack_require__(63); -var Exports_1 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisRequest = exports.SpeechSynthesisRequestInputStream = void 0; +const Exports_js_1 = __webpack_require__(85); +const SpeechSynthesisRequestInputType_js_1 = __webpack_require__(165); +const SpeechSynthesisRequestInputStream_js_1 = __webpack_require__(166); +var SpeechSynthesisRequestInputStream_js_2 = __webpack_require__(166); +Object.defineProperty(exports, "SpeechSynthesisRequestInputStream", ({ enumerable: true, get: function () { return SpeechSynthesisRequestInputStream_js_2.SpeechSynthesisRequestInputStream; } })); /** - * Pronunciation assessment configuration. - * @class PronunciationAssessmentConfig - * Added in version 1.15.0. + * Represents a speech synthesis request with support for text streaming. + * Note: This class is in preview and may be subject to change in future versions. + * @class SpeechSynthesisRequest */ -var PronunciationAssessmentConfig = /** @class */ (function () { +class SpeechSynthesisRequest { /** - * PronunciationAssessmentConfig constructor. - * @constructor - * @param {string} referenceText - * @param gradingSystem - * @param granularity - * @param enableMiscue + * Creates a speech synthesis request. + * @param inputType The input type for the speech synthesis request. */ - function PronunciationAssessmentConfig(referenceText, gradingSystem, granularity, enableMiscue) { - if (gradingSystem === void 0) { gradingSystem = Exports_1.PronunciationAssessmentGradingSystem.FivePoint; } - if (granularity === void 0) { granularity = Exports_1.PronunciationAssessmentGranularity.Phoneme; } - if (enableMiscue === void 0) { enableMiscue = false; } - Contracts_1.Contracts.throwIfNullOrUndefined(referenceText, "referenceText"); - this.privProperties = new Exports_1.PropertyCollection(); - this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_ReferenceText, referenceText); - this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_GradingSystem, Exports_1.PronunciationAssessmentGradingSystem[gradingSystem]); - this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_Granularity, Exports_1.PronunciationAssessmentGranularity[granularity]); - this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_EnableMiscue, String(enableMiscue)); + constructor(inputType) { + this.privBufferedTextPieces = []; + this.privStreamClosedBeforeReady = false; + if (inputType !== SpeechSynthesisRequestInputType_js_1.SpeechSynthesisRequestInputType.TextStream) { + throw new Error("Only TextStream input type is supported in this version."); + } + this.privInputType = inputType; + this.privInputStream = new SpeechSynthesisRequestInputStream_js_1.SpeechSynthesisRequestInputStream(this); + this.privProperties = new Exports_js_1.PropertyCollection(); } /** - * @member PronunciationAssessmentConfig.fromJSON - * @function - * @public - * @param {string} json The json string containing the pronunciation assessment parameters. - * @return {PronunciationAssessmentConfig} Instance of PronunciationAssessmentConfig - * @summary Creates an instance of the PronunciationAssessmentConfig from json. + * Gets the input type of this request. */ - PronunciationAssessmentConfig.fromJSON = function (json) { - Contracts_1.Contracts.throwIfNullOrUndefined(json, "json"); - var config = new PronunciationAssessmentConfig(""); - config.privProperties = new Exports_1.PropertyCollection(); - config.properties.setProperty(Exports_1.PropertyId.PronunciationAssessment_Json, json); - return config; - }; - PronunciationAssessmentConfig.prototype.toJSON = function () { - this.updateJson(); - return this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_Params); - }; - PronunciationAssessmentConfig.prototype.applyTo = function (recognizer) { - this.updateJson(); - var recoBase = recognizer.internalData; - recoBase.speechContext.setPronunciationAssessmentParams(this.properties.getProperty(Exports_1.PropertyId.PronunciationAssessment_Params)); - }; - Object.defineProperty(PronunciationAssessmentConfig.prototype, "referenceText", { - /** - * Gets the reference text. - * @member PronunciationAssessmentConfig.prototype.referenceText - * @function - * @public - * @returns {string} Reference text. - */ - get: function () { - return this.properties.getProperty(Exports_1.PropertyId.PronunciationAssessment_ReferenceText); - }, - /** - * Gets/Sets the reference text. - * @member PronunciationAssessmentConfig.prototype.referenceText - * @function - * @public - * @param {string} referenceText - Reference text. - */ - set: function (referenceText) { - Contracts_1.Contracts.throwIfNullOrWhitespace(referenceText, "referenceText"); - this.properties.setProperty(Exports_1.PropertyId.PronunciationAssessment_ReferenceText, referenceText); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PronunciationAssessmentConfig.prototype, "phonemeAlphabet", { - /** - * Sets the phoneme alphabet. - * The valid values are "SAPI" (default) and "IPA". - * Added in version 1.20.0 - * @member PronunciationAssessmentConfig.prototype.phonemeAlphabet - * @function - * @public - * @param {string} phonemeAlphabet - Phoneme alphabet. - */ - set: function (phonemeAlphabet) { - Contracts_1.Contracts.throwIfNullOrWhitespace(phonemeAlphabet, "phonemeAlphabet"); - this.privPhonemeAlphabet = phonemeAlphabet; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PronunciationAssessmentConfig.prototype, "nbestPhonemeCount", { - /** - * Sets the nbest phoneme count - * Added in version 1.20.0 - * @member PronunciationAssessmentConfig.prototype.nbestPhonemeCount - * @function - * @public - * @param {number} nbestPhonemeCount - NBest phoneme count. - */ - set: function (nbestPhonemeCount) { - this.privNBestPhonemeCount = nbestPhonemeCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PronunciationAssessmentConfig.prototype, "properties", { - /** - * @member PronunciationAssessmentConfig.prototype.properties - * @function - * @public - * @return {PropertyCollection} Properties of the config. - * @summary Gets a pronunciation assessment config properties - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - PronunciationAssessmentConfig.prototype.updateJson = function () { - var jsonString = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_Json, "{}"); - var paramsJson = JSON.parse(jsonString); - var referenceText = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_ReferenceText); - if (referenceText) { - paramsJson.referenceText = referenceText; - } - var gradingSystem = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_GradingSystem); - if (gradingSystem) { - paramsJson.gradingSystem = gradingSystem; + get inputType() { + return this.privInputType; + } + /** + * Gets the input stream for writing text pieces. + */ + get inputStream() { + return this.privInputStream; + } + /** + * Gets the properties collection for this request. + */ + get properties() { + return this.privProperties; + } + /** + * Sets the pitch of the voice. + */ + set pitch(value) { + this.privProperties.setProperty(Exports_js_1.PropertyId.SpeechSynthesisRequest_Pitch, value); + } + /** + * Sets the speaking rate of the voice. + */ + set rate(value) { + this.privProperties.setProperty(Exports_js_1.PropertyId.SpeechSynthesisRequest_Rate, value); + } + /** + * Sets the volume of the voice. + */ + set volume(value) { + this.privProperties.setProperty(Exports_js_1.PropertyId.SpeechSynthesisRequest_Volume, value); + } + /** + * Sets the style of the voice. + */ + set style(value) { + this.privProperties.setProperty(Exports_js_1.PropertyId.SpeechSynthesisRequest_Style, value); + } + /** + * Sets the temperature of the voice synthesis. + */ + set temperature(value) { + this.privProperties.setProperty(Exports_js_1.PropertyId.SpeechSynthesisRequest_Temperature, value.toString()); + } + /** + * Sets the custom lexicon URL. + */ + set customLexiconUrl(value) { + this.privProperties.setProperty(Exports_js_1.PropertyId.SpeechSynthesisRequest_CustomLexiconUrl, value); + } + /** + * Sets the preferred locales for the voice. + */ + set preferLocales(value) { + this.privProperties.setProperty(Exports_js_1.PropertyId.SpeechSynthesisRequest_PreferLocales, value); + } + /** + * @internal + * Called by InputStream when a text piece is written. + * Buffers text if no callback is registered yet. + */ + onTextPieceReceived(text) { + if (this.privTextPieceCallback) { + this.privTextPieceCallback(text); } - var granularity = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_Granularity); - if (granularity) { - paramsJson.granularity = granularity; + else { + this.privBufferedTextPieces.push(text); } - if (this.privPhonemeAlphabet) { - paramsJson.phonemeAlphabet = this.privPhonemeAlphabet; + } + /** + * @internal + * Called by InputStream when it is closed. + * Buffers close event if no callback is registered yet. + */ + onInputStreamClosed() { + if (this.privStreamCloseCallback) { + this.privStreamCloseCallback(); } - if (this.privNBestPhonemeCount) { - paramsJson.nbestPhonemeCount = this.privNBestPhonemeCount; + else { + this.privStreamClosedBeforeReady = true; } - // always set dimension to Comprehensive - paramsJson.dimension = "Comprehensive"; - var enableMiscueString = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_EnableMiscue); - if (enableMiscueString === "true") { - paramsJson.enableMiscue = true; + } + /** + * @internal + * Sets the callback for receiving text pieces. + * Flushes any buffered text pieces immediately. + */ + set onTextPiece(callback) { + this.privTextPieceCallback = callback; + // Flush buffered text pieces + for (const text of this.privBufferedTextPieces) { + callback(text); } - else if (enableMiscueString === "false") { - paramsJson.enableMiscue = false; + this.privBufferedTextPieces = []; + } + /** + * @internal + * Sets the callback for stream close events. + * Fires immediately if stream was already closed. + */ + set onClose(callback) { + this.privStreamCloseCallback = callback; + // Fire if stream was already closed before callback was set + if (this.privStreamClosedBeforeReady) { + this.privStreamClosedBeforeReady = false; + callback(); } - this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_Params, JSON.stringify(paramsJson)); - }; - return PronunciationAssessmentConfig; -}()); -exports.PronunciationAssessmentConfig = PronunciationAssessmentConfig; + } +} +exports.SpeechSynthesisRequest = SpeechSynthesisRequest; /***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { +/* 165 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PronunciationAssessmentResult = void 0; -var Contracts_1 = __webpack_require__(63); -var Exports_1 = __webpack_require__(61); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisRequestInputType = void 0; /** - * Pronunciation assessment results. - * @class PronunciationAssessmentResult - * Added in version 1.15.0. + * Defines the input type of speech synthesis request. + * @enum SpeechSynthesisRequestInputType */ -var PronunciationAssessmentResult = /** @class */ (function () { - function PronunciationAssessmentResult(jsonString) { - var j = JSON.parse(jsonString); - Contracts_1.Contracts.throwIfNullOrUndefined(j.NBest[0], "NBest"); - this.privPronJson = j.NBest[0]; - } +var SpeechSynthesisRequestInputType; +(function (SpeechSynthesisRequestInputType) { /** - * @member PronunciationAssessmentResult.fromResult - * @function - * @public - * @param {RecognitionResult} result The recognition result. - * @return {PronunciationAssessmentConfig} Instance of PronunciationAssessmentConfig - * @summary Creates an instance of the PronunciationAssessmentResult from recognition result. + * Plain text input. */ - PronunciationAssessmentResult.fromResult = function (result) { - Contracts_1.Contracts.throwIfNullOrUndefined(result, "result"); - var json = result.properties.getProperty(Exports_1.PropertyId.SpeechServiceResponse_JsonResult); - Contracts_1.Contracts.throwIfNullOrUndefined(json, "json"); - return new PronunciationAssessmentResult(json); - }; - Object.defineProperty(PronunciationAssessmentResult.prototype, "detailResult", { - /** - * Gets the detail result of pronunciation assessment. - * @member PronunciationAssessmentConfig.prototype.detailResult - * @function - * @public - * @returns {any} detail result. - */ - get: function () { - return this.privPronJson; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PronunciationAssessmentResult.prototype, "accuracyScore", { - /** - * The score indicating the pronunciation accuracy of the given speech, which indicates - * how closely the phonemes match a native speaker's pronunciation. - * @member PronunciationAssessmentResult.prototype.accuracyScore - * @function - * @public - * @returns {number} Accuracy score. - */ - get: function () { - return this.detailResult.PronunciationAssessment.AccuracyScore; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PronunciationAssessmentResult.prototype, "pronunciationScore", { - /** - * The overall score indicating the pronunciation quality of the given speech. - * This is calculated from AccuracyScore, FluencyScore and CompletenessScore with weight. - * @member PronunciationAssessmentResult.prototype.pronunciationScore - * @function - * @public - * @returns {number} Pronunciation score. - */ - get: function () { - return this.detailResult.PronunciationAssessment.PronScore; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PronunciationAssessmentResult.prototype, "completenessScore", { - /** - * The score indicating the completeness of the given speech by calculating the ratio of pronounced words towards entire input. - * @member PronunciationAssessmentResult.prototype.completenessScore - * @function - * @public - * @returns {number} Completeness score. - */ - get: function () { - return this.detailResult.PronunciationAssessment.CompletenessScore; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(PronunciationAssessmentResult.prototype, "fluencyScore", { - /** - * The score indicating the fluency of the given speech. - * @member PronunciationAssessmentResult.prototype.fluencyScore - * @function - * @public - * @returns {number} Fluency score. - */ - get: function () { - return this.detailResult.PronunciationAssessment.FluencyScore; - }, - enumerable: false, - configurable: true - }); - return PronunciationAssessmentResult; -}()); -exports.PronunciationAssessmentResult = PronunciationAssessmentResult; + SpeechSynthesisRequestInputType[SpeechSynthesisRequestInputType["Text"] = 1] = "Text"; + /** + * SSML (Speech Synthesis Markup Language) input. + */ + SpeechSynthesisRequestInputType[SpeechSynthesisRequestInputType["SSML"] = 2] = "SSML"; + /** + * Text stream input, for streaming text to the synthesizer. + */ + SpeechSynthesisRequestInputType[SpeechSynthesisRequestInputType["TextStream"] = 3] = "TextStream"; +})(SpeechSynthesisRequestInputType = exports.SpeechSynthesisRequestInputType || (exports.SpeechSynthesisRequestInputType = {})); /***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { +/* 166 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RecognitionEndedEvent = exports.RecognitionCompletionStatus = exports.RecognitionStartedEvent = exports.ConnectingToServiceEvent = exports.ListeningStartedEvent = exports.RecognitionTriggeredEvent = exports.SpeechRecognitionEvent = void 0; -// tslint:disable:max-classes-per-file -var Exports_1 = __webpack_require__(4); -var SpeechRecognitionEvent = /** @class */ (function (_super) { - __extends(SpeechRecognitionEvent, _super); - function SpeechRecognitionEvent(eventName, requestId, sessionId, eventType) { - if (eventType === void 0) { eventType = Exports_1.EventType.Info; } - var _this = _super.call(this, eventName, eventType) || this; - _this.privRequestId = requestId; - _this.privSessionId = sessionId; - return _this; - } - Object.defineProperty(SpeechRecognitionEvent.prototype, "requestId", { - get: function () { - return this.privRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechRecognitionEvent.prototype, "sessionId", { - get: function () { - return this.privSessionId; - }, - enumerable: false, - configurable: true - }); - return SpeechRecognitionEvent; -}(Exports_1.PlatformEvent)); -exports.SpeechRecognitionEvent = SpeechRecognitionEvent; -var RecognitionTriggeredEvent = /** @class */ (function (_super) { - __extends(RecognitionTriggeredEvent, _super); - function RecognitionTriggeredEvent(requestId, sessionId, audioSourceId, audioNodeId) { - var _this = _super.call(this, "RecognitionTriggeredEvent", requestId, sessionId) || this; - _this.privAudioSourceId = audioSourceId; - _this.privAudioNodeId = audioNodeId; - return _this; - } - Object.defineProperty(RecognitionTriggeredEvent.prototype, "audioSourceId", { - get: function () { - return this.privAudioSourceId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionTriggeredEvent.prototype, "audioNodeId", { - get: function () { - return this.privAudioNodeId; - }, - enumerable: false, - configurable: true - }); - return RecognitionTriggeredEvent; -}(SpeechRecognitionEvent)); -exports.RecognitionTriggeredEvent = RecognitionTriggeredEvent; -var ListeningStartedEvent = /** @class */ (function (_super) { - __extends(ListeningStartedEvent, _super); - function ListeningStartedEvent(requestId, sessionId, audioSourceId, audioNodeId) { - var _this = _super.call(this, "ListeningStartedEvent", requestId, sessionId) || this; - _this.privAudioSourceId = audioSourceId; - _this.privAudioNodeId = audioNodeId; - return _this; - } - Object.defineProperty(ListeningStartedEvent.prototype, "audioSourceId", { - get: function () { - return this.privAudioSourceId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ListeningStartedEvent.prototype, "audioNodeId", { - get: function () { - return this.privAudioNodeId; - }, - enumerable: false, - configurable: true - }); - return ListeningStartedEvent; -}(SpeechRecognitionEvent)); -exports.ListeningStartedEvent = ListeningStartedEvent; -var ConnectingToServiceEvent = /** @class */ (function (_super) { - __extends(ConnectingToServiceEvent, _super); - function ConnectingToServiceEvent(requestId, authFetchEventid, sessionId) { - var _this = _super.call(this, "ConnectingToServiceEvent", requestId, sessionId) || this; - _this.privAuthFetchEventid = authFetchEventid; - return _this; - } - Object.defineProperty(ConnectingToServiceEvent.prototype, "authFetchEventid", { - get: function () { - return this.privAuthFetchEventid; - }, - enumerable: false, - configurable: true - }); - return ConnectingToServiceEvent; -}(SpeechRecognitionEvent)); -exports.ConnectingToServiceEvent = ConnectingToServiceEvent; -var RecognitionStartedEvent = /** @class */ (function (_super) { - __extends(RecognitionStartedEvent, _super); - function RecognitionStartedEvent(requestId, audioSourceId, audioNodeId, authFetchEventId, sessionId) { - var _this = _super.call(this, "RecognitionStartedEvent", requestId, sessionId) || this; - _this.privAudioSourceId = audioSourceId; - _this.privAudioNodeId = audioNodeId; - _this.privAuthFetchEventId = authFetchEventId; - return _this; - } - Object.defineProperty(RecognitionStartedEvent.prototype, "audioSourceId", { - get: function () { - return this.privAudioSourceId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionStartedEvent.prototype, "audioNodeId", { - get: function () { - return this.privAudioNodeId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionStartedEvent.prototype, "authFetchEventId", { - get: function () { - return this.privAuthFetchEventId; - }, - enumerable: false, - configurable: true - }); - return RecognitionStartedEvent; -}(SpeechRecognitionEvent)); -exports.RecognitionStartedEvent = RecognitionStartedEvent; -var RecognitionCompletionStatus; -(function (RecognitionCompletionStatus) { - RecognitionCompletionStatus[RecognitionCompletionStatus["Success"] = 0] = "Success"; - RecognitionCompletionStatus[RecognitionCompletionStatus["AudioSourceError"] = 1] = "AudioSourceError"; - RecognitionCompletionStatus[RecognitionCompletionStatus["AudioSourceTimeout"] = 2] = "AudioSourceTimeout"; - RecognitionCompletionStatus[RecognitionCompletionStatus["AuthTokenFetchError"] = 3] = "AuthTokenFetchError"; - RecognitionCompletionStatus[RecognitionCompletionStatus["AuthTokenFetchTimeout"] = 4] = "AuthTokenFetchTimeout"; - RecognitionCompletionStatus[RecognitionCompletionStatus["UnAuthorized"] = 5] = "UnAuthorized"; - RecognitionCompletionStatus[RecognitionCompletionStatus["ConnectTimeout"] = 6] = "ConnectTimeout"; - RecognitionCompletionStatus[RecognitionCompletionStatus["ConnectError"] = 7] = "ConnectError"; - RecognitionCompletionStatus[RecognitionCompletionStatus["ClientRecognitionActivityTimeout"] = 8] = "ClientRecognitionActivityTimeout"; - RecognitionCompletionStatus[RecognitionCompletionStatus["UnknownError"] = 9] = "UnknownError"; -})(RecognitionCompletionStatus = exports.RecognitionCompletionStatus || (exports.RecognitionCompletionStatus = {})); -var RecognitionEndedEvent = /** @class */ (function (_super) { - __extends(RecognitionEndedEvent, _super); - function RecognitionEndedEvent(requestId, audioSourceId, audioNodeId, authFetchEventId, sessionId, serviceTag, status, error) { - var _this = _super.call(this, "RecognitionEndedEvent", requestId, sessionId, status === RecognitionCompletionStatus.Success ? Exports_1.EventType.Info : Exports_1.EventType.Error) || this; - _this.privAudioSourceId = audioSourceId; - _this.privAudioNodeId = audioNodeId; - _this.privAuthFetchEventId = authFetchEventId; - _this.privStatus = status; - _this.privError = error; - _this.privServiceTag = serviceTag; - return _this; - } - Object.defineProperty(RecognitionEndedEvent.prototype, "audioSourceId", { - get: function () { - return this.privAudioSourceId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionEndedEvent.prototype, "audioNodeId", { - get: function () { - return this.privAudioNodeId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionEndedEvent.prototype, "authFetchEventId", { - get: function () { - return this.privAuthFetchEventId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionEndedEvent.prototype, "serviceTag", { - get: function () { - return this.privServiceTag; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionEndedEvent.prototype, "status", { - get: function () { - return this.privStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognitionEndedEvent.prototype, "error", { - get: function () { - return this.privError; - }, - enumerable: false, - configurable: true - }); - return RecognitionEndedEvent; -}(SpeechRecognitionEvent)); -exports.RecognitionEndedEvent = RecognitionEndedEvent; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisRequestInputStream = void 0; +/** + * Represents an input stream for speech synthesis request text streaming. + * Note: This class is in preview and may be subject to change in future versions. + * @class SpeechSynthesisRequestInputStream + */ +class SpeechSynthesisRequestInputStream { + /** + * Constructor for internal use. + * @param parent The parent SpeechSynthesisRequest. + */ + constructor(parent) { + this.privClosed = false; + this.privParent = parent; + } + /** + * Writes the specified text to the input stream. + * @param text The text to be written to the input stream. + */ + write(text) { + if (this.privClosed) { + throw new Error("Cannot write to a closed input stream."); + } + this.privParent.onTextPieceReceived(text); + } + /** + * Closes the input stream, signaling that no more text will be written. + */ + close() { + if (!this.privClosed) { + this.privClosed = true; + this.privParent.onInputStreamClosed(); + } + } + /** + * Gets whether the input stream is closed. + */ + get isClosed() { + return this.privClosed; + } +} +exports.SpeechSynthesisRequestInputStream = SpeechSynthesisRequestInputStream; + + + +/***/ }), +/* 167 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SynthesisVoicesResult = void 0; +const Exports_js_1 = __webpack_require__(85); +/** + * Defines result of speech synthesis. + * @class SynthesisVoicesResult + * Added in version 1.20.0 + */ +class SynthesisVoicesResult extends Exports_js_1.SynthesisResult { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param requestId - result id for request. + * @param json - json payload from endpoint. + */ + constructor(requestId, json, errorDetails) { + if (Array.isArray(json)) { + super(requestId, Exports_js_1.ResultReason.VoicesListRetrieved, undefined, new Exports_js_1.PropertyCollection()); + this.privVoices = []; + for (const item of json) { + this.privVoices.push(new Exports_js_1.VoiceInfo(item)); + } + } + else { + super(requestId, Exports_js_1.ResultReason.Canceled, errorDetails ? errorDetails : "Error information unavailable", new Exports_js_1.PropertyCollection()); + } + } + /** + * The list of voices + * @member SynthesisVoicesResult.prototype.voices + * @function + * @public + * @returns {VoiceInfo[]} List of synthesized voices. + */ + get voices() { + return this.privVoices; + } +} +exports.SynthesisVoicesResult = SynthesisVoicesResult; /***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { +/* 168 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VoiceInfo = exports.SynthesisVoiceType = exports.SynthesisVoiceGender = void 0; +/** + * Defines the gender of synthesis voices. + * Added in version 1.20.0. + */ +var SynthesisVoiceGender; +(function (SynthesisVoiceGender) { + /** Gender unknown */ + SynthesisVoiceGender[SynthesisVoiceGender["Unknown"] = 0] = "Unknown"; + /** Female voice */ + SynthesisVoiceGender[SynthesisVoiceGender["Female"] = 1] = "Female"; + /** Male voice */ + SynthesisVoiceGender[SynthesisVoiceGender["Male"] = 2] = "Male"; + /** Neutral voice */ + SynthesisVoiceGender[SynthesisVoiceGender["Neutral"] = 3] = "Neutral"; +})(SynthesisVoiceGender = exports.SynthesisVoiceGender || (exports.SynthesisVoiceGender = {})); +var SynthesisVoiceType; +(function (SynthesisVoiceType) { + /** + * Voice type is not known. + */ + SynthesisVoiceType[SynthesisVoiceType["Unknown"] = 0] = "Unknown"; + /** + * Online neural voices. + */ + SynthesisVoiceType[SynthesisVoiceType["OnlineNeural"] = 1] = "OnlineNeural"; + /** + * Online standard voices. These voices are deprecated. + */ + SynthesisVoiceType[SynthesisVoiceType["OnlineStandard"] = 2] = "OnlineStandard"; + /** + * Offline neural voices. + */ + SynthesisVoiceType[SynthesisVoiceType["OfflineNeural"] = 3] = "OfflineNeural"; + /** + * Offline standard voices. + */ + SynthesisVoiceType[SynthesisVoiceType["OfflineStandard"] = 4] = "OfflineStandard"; + /** + * High definition (HD) voices. Refer to https://learn.microsoft.com/azure/ai-services/speech-service/high-definition-voices + */ + SynthesisVoiceType[SynthesisVoiceType["OnlineNeuralHD"] = 5] = "OnlineNeuralHD"; +})(SynthesisVoiceType = exports.SynthesisVoiceType || (exports.SynthesisVoiceType = {})); +const GENDER_LOOKUP = { + [SynthesisVoiceGender[SynthesisVoiceGender.Neutral]]: SynthesisVoiceGender.Neutral, + [SynthesisVoiceGender[SynthesisVoiceGender.Male]]: SynthesisVoiceGender.Male, + [SynthesisVoiceGender[SynthesisVoiceGender.Female]]: SynthesisVoiceGender.Female, }; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } +const VOICE_TYPE_LOOKUP = { + Neural: SynthesisVoiceType.OnlineNeural, + NeuralHD: SynthesisVoiceType.OnlineNeuralHD, }; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ServiceRecognizerBase = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(4); -var Exports_3 = __webpack_require__(61); -var Exports_4 = __webpack_require__(53); -var SpeechConnectionMessage_Internal_1 = __webpack_require__(173); -var ServiceRecognizerBase = /** @class */ (function () { - function ServiceRecognizerBase(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) { - var _this = this; - this.privSetTimeout = setTimeout; - this.privIsLiveAudio = false; - this.recognizeOverride = undefined; - this.disconnectOverride = undefined; - this.receiveMessageOverride = undefined; - this.sendSpeechContext = function (connection) { - var speechContextJson = _this.speechContext.toJSON(); - _this.privRequestSession.onSpeechContext(); - if (speechContextJson) { - return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "speech.context", _this.privRequestSession.requestId, "application/json", speechContextJson)); - } - return; - }; - this.sendPrePayloadJSONOverride = undefined; - this.postConnectImplOverride = undefined; - this.configConnectionOverride = undefined; - this.sendSpeechServiceConfig = function (connection, requestSession, SpeechServiceConfigJson) { - // filter out anything that is not required for the service to work. - if (ServiceRecognizerBase.telemetryDataEnabled !== true) { - var withTelemetry = JSON.parse(SpeechServiceConfigJson); - var replacement = { - context: { - system: withTelemetry.context.system, - }, - }; - SpeechServiceConfigJson = JSON.stringify(replacement); - } - if (_this.privRecognizerConfig.parameters.getProperty("TranscriptionService_SingleChannel", "false").toLowerCase() === "true") { - var json = JSON.parse(SpeechServiceConfigJson); - json.context.DisableReferenceChannel = "True"; - json.context.MicSpec = "1_0_0"; - SpeechServiceConfigJson = JSON.stringify(json); - } - if (SpeechServiceConfigJson) { - return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "speech.config", requestSession.requestId, "application/json", SpeechServiceConfigJson)); - } - return; - }; - if (!authentication) { - throw new Exports_2.ArgumentNullError("authentication"); - } - if (!connectionFactory) { - throw new Exports_2.ArgumentNullError("connectionFactory"); - } - if (!audioSource) { - throw new Exports_2.ArgumentNullError("audioSource"); - } - if (!recognizerConfig) { - throw new Exports_2.ArgumentNullError("recognizerConfig"); - } - this.privMustReportEndOfStream = false; - this.privAuthentication = authentication; - this.privConnectionFactory = connectionFactory; - this.privAudioSource = audioSource; - this.privRecognizerConfig = recognizerConfig; - this.privIsDisposed = false; - this.privRecognizer = recognizer; - this.privRequestSession = new Exports_4.RequestSession(this.privAudioSource.id()); - this.privConnectionEvents = new Exports_2.EventSource(); - this.privServiceEvents = new Exports_2.EventSource(); - this.privDynamicGrammar = new Exports_4.DynamicGrammarBuilder(); - this.privSpeechContext = new Exports_4.SpeechContext(this.privDynamicGrammar); - this.privAgentConfig = new Exports_4.AgentConfig(); - if (typeof (Blob) !== "undefined" && typeof (Worker) !== "undefined") { - this.privSetTimeout = Exports_2.Timeout.setTimeout; - } - this.connectionEvents.attach(function (connectionEvent) { return __awaiter(_this, void 0, void 0, function () { - var connectionClosedEvent; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(connectionEvent.name === "ConnectionClosedEvent")) return [3 /*break*/, 2]; - connectionClosedEvent = connectionEvent; - if (!(connectionClosedEvent.statusCode === 1003 || - connectionClosedEvent.statusCode === 1007 || - connectionClosedEvent.statusCode === 1002 || - connectionClosedEvent.statusCode === 4000 || - this.privRequestSession.numConnectionAttempts > this.privRecognizerConfig.maxRetryCount)) return [3 /*break*/, 2]; - return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.Error, connectionClosedEvent.statusCode === 1007 ? Exports_3.CancellationErrorCode.BadRequestParameters : Exports_3.CancellationErrorCode.ConnectionFailure, connectionClosedEvent.reason + " websocket error code: " + connectionClosedEvent.statusCode)]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); }); - } - Object.defineProperty(ServiceRecognizerBase.prototype, "audioSource", { - get: function () { - return this.privAudioSource; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ServiceRecognizerBase.prototype, "speechContext", { - get: function () { - return this.privSpeechContext; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ServiceRecognizerBase.prototype, "dynamicGrammar", { - get: function () { - return this.privDynamicGrammar; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ServiceRecognizerBase.prototype, "agentConfig", { - get: function () { - return this.privAgentConfig; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ServiceRecognizerBase.prototype, "conversationTranslatorToken", { - set: function (token) { - this.privRecognizerConfig.parameters.setProperty(Exports_3.PropertyId.ConversationTranslator_Token, token); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ServiceRecognizerBase.prototype, "authentication", { - set: function (auth) { - this.privAuthentication = this.authentication; - }, - enumerable: false, - configurable: true - }); - ServiceRecognizerBase.prototype.isDisposed = function () { - return this.privIsDisposed; - }; - ServiceRecognizerBase.prototype.dispose = function (reason) { - return __awaiter(this, void 0, void 0, function () { - var connection, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privIsDisposed = true; - if (!this.privConnectionConfigurationPromise) return [3 /*break*/, 5]; - _a.label = 1; - case 1: - _a.trys.push([1, 4, , 5]); - return [4 /*yield*/, this.privConnectionConfigurationPromise]; - case 2: - connection = _a.sent(); - return [4 /*yield*/, connection.dispose(reason)]; - case 3: - _a.sent(); - return [3 /*break*/, 5]; - case 4: - error_1 = _a.sent(); - // The connection is in a bad state. But we're trying to kill it, so... - return [2 /*return*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - Object.defineProperty(ServiceRecognizerBase.prototype, "connectionEvents", { - get: function () { - return this.privConnectionEvents; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ServiceRecognizerBase.prototype, "serviceEvents", { - get: function () { - return this.privServiceEvents; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ServiceRecognizerBase.prototype, "recognitionMode", { - get: function () { - return this.privRecognizerConfig.recognitionMode; - }, - enumerable: false, - configurable: true - }); - ServiceRecognizerBase.prototype.recognize = function (recoMode, successCallback, errorCallBack) { - return __awaiter(this, void 0, void 0, function () { - var conPromise, audioNode, audioStreamNode, format, deviceInfo, error_2, error_3, sessionStartEventArgs, messageRetrievalPromise, audioSendPromise; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.recognizeOverride !== undefined) { - return [2 /*return*/, this.recognizeOverride(recoMode, successCallback, errorCallBack)]; - } - // Clear the existing configuration promise to force a re-transmission of config and context. - this.privConnectionConfigurationPromise = null; - this.privRecognizerConfig.recognitionMode = recoMode; - this.privSuccessCallback = successCallback; - this.privErrorCallback = errorCallBack; - this.privRequestSession.startNewRecognition(); - this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events); - conPromise = this.connectImpl(); - _a.label = 1; - case 1: - _a.trys.push([1, 6, , 8]); - return [4 /*yield*/, this.audioSource.attach(this.privRequestSession.audioNodeId)]; - case 2: - audioStreamNode = _a.sent(); - return [4 /*yield*/, this.audioSource.format]; - case 3: - format = _a.sent(); - return [4 /*yield*/, this.audioSource.deviceInfo]; - case 4: - deviceInfo = _a.sent(); - this.privIsLiveAudio = deviceInfo.type && deviceInfo.type === Exports_4.type.Microphones; - audioNode = new Exports_1.ReplayableAudioNode(audioStreamNode, format.avgBytesPerSec); - return [4 /*yield*/, this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false)]; - case 5: - _a.sent(); - this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo }; - return [3 /*break*/, 8]; - case 6: - error_2 = _a.sent(); - return [4 /*yield*/, this.privRequestSession.onStopRecognizing()]; - case 7: - _a.sent(); - throw error_2; - case 8: - _a.trys.push([8, 10, , 12]); - return [4 /*yield*/, conPromise]; - case 9: - _a.sent(); - return [3 /*break*/, 12]; - case 10: - error_3 = _a.sent(); - return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.ConnectionFailure, error_3)]; - case 11: - _a.sent(); - return [2 /*return*/]; - case 12: - sessionStartEventArgs = new Exports_3.SessionEventArgs(this.privRequestSession.sessionId); - if (!!this.privRecognizer.sessionStarted) { - this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs); - } - messageRetrievalPromise = this.receiveMessage(); - audioSendPromise = this.sendAudio(audioNode); - audioSendPromise.catch(function (error) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.RuntimeError, error)]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); }); - return [2 /*return*/]; - } - }); - }); - }; - ServiceRecognizerBase.prototype.stopRecognizing = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.privRequestSession.isRecognizing) return [3 /*break*/, 8]; - _a.label = 1; - case 1: - _a.trys.push([1, , 6, 8]); - return [4 /*yield*/, this.audioSource.turnOff()]; - case 2: - _a.sent(); - return [4 /*yield*/, this.sendFinalAudio()]; - case 3: - _a.sent(); - return [4 /*yield*/, this.privRequestSession.onStopRecognizing()]; - case 4: - _a.sent(); - return [4 /*yield*/, this.privRequestSession.turnCompletionPromise]; - case 5: - _a.sent(); - return [3 /*break*/, 8]; - case 6: return [4 /*yield*/, this.privRequestSession.dispose()]; - case 7: - _a.sent(); - return [7 /*endfinally*/]; - case 8: return [2 /*return*/]; - } - }); - }); - }; - ServiceRecognizerBase.prototype.connect = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.connectImpl()]; - case 1: - _a.sent(); - return [2 /*return*/, Promise.resolve()]; - } - }); - }); - }; - ServiceRecognizerBase.prototype.connectAsync = function (cb, err) { - this.connectImpl().then(function (connection) { - try { - if (!!cb) { - cb(); +/** + * Information about Speech Synthesis voice + * Added in version 1.20.0. + * @class VoiceInfo + */ +class VoiceInfo { + constructor(json) { + this.privStyleList = []; + if (!!json) { + this.privName = json.Name; + this.privLocale = json.Locale; + this.privShortName = json.ShortName; + this.privLocaleName = json.LocaleName; + this.privDisplayName = json.DisplayName; + this.privLocalName = json.LocalName; + this.privVoiceType = VOICE_TYPE_LOOKUP[json.VoiceType] || SynthesisVoiceType.Unknown; + this.privGender = GENDER_LOOKUP[json.Gender] || SynthesisVoiceGender.Unknown; + if (!!json.StyleList && Array.isArray(json.StyleList)) { + for (const style of json.StyleList) { + this.privStyleList.push(style); } } - catch (e) { - if (!!err) { - err(e); - } + this.privSampleRateHertz = json.SampleRateHertz; + this.privStatus = json.Status; + if (json.ExtendedPropertyMap) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + this.privExtendedPropertyMap = json.ExtendedPropertyMap; } - }, function (reason) { - try { - if (!!err) { - err(reason); - } - /* tslint:disable:no-empty */ + this.privWordsPerMinute = json.WordsPerMinute; + if (Array.isArray(json.SecondaryLocaleList)) { + this.privSecondaryLocaleList = [...json.SecondaryLocaleList]; } - catch (error) { + if (Array.isArray(json.RolePlayList)) { + this.privRolePlayList = [...json.RolePlayList]; } - }); - }; - ServiceRecognizerBase.prototype.disconnect = function () { - return __awaiter(this, void 0, void 0, function () { - var error_4; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.NoError, "Disconnecting")]; - case 1: - _a.sent(); - if (!(this.disconnectOverride !== undefined)) return [3 /*break*/, 3]; - return [4 /*yield*/, this.disconnectOverride()]; - case 2: - _a.sent(); - _a.label = 3; - case 3: - _a.trys.push([3, 6, , 7]); - return [4 /*yield*/, this.privConnectionPromise]; - case 4: return [4 /*yield*/, (_a.sent()).dispose()]; - case 5: - _a.sent(); - return [3 /*break*/, 7]; - case 6: - error_4 = _a.sent(); - return [3 /*break*/, 7]; - case 7: - this.privConnectionPromise = null; - return [2 /*return*/]; - } - }); - }); - }; - ServiceRecognizerBase.prototype.sendMessage = function (message) { }; - ServiceRecognizerBase.prototype.sendNetworkMessage = function (path, payload) { - return __awaiter(this, void 0, void 0, function () { - var type, contentType, connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - type = typeof payload === "string" ? Exports_2.MessageType.Text : Exports_2.MessageType.Binary; - contentType = typeof payload === "string" ? "application/json" : ""; - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [2 /*return*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(type, path, this.privRequestSession.requestId, contentType, payload))]; - } - }); - }); - }; - Object.defineProperty(ServiceRecognizerBase.prototype, "activityTemplate", { - get: function () { return this.privActivityTemplate; }, - set: function (messagePayload) { this.privActivityTemplate = messagePayload; }, - enumerable: false, - configurable: true - }); - ServiceRecognizerBase.prototype.sendTelemetryData = function () { - return __awaiter(this, void 0, void 0, function () { - var telemetryData, connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - telemetryData = this.privRequestSession.getTelemetry(); - if (ServiceRecognizerBase.telemetryDataEnabled !== true || - this.privIsDisposed || - null === telemetryData) { - return [2 /*return*/]; - } - if (!!ServiceRecognizerBase.telemetryData) { - try { - ServiceRecognizerBase.telemetryData(telemetryData); - /* tslint:disable:no-empty */ - } - catch (_b) { } - } - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [4 /*yield*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "telemetry", this.privRequestSession.requestId, "application/json", telemetryData))]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - // Cancels recognition. - ServiceRecognizerBase.prototype.cancelRecognitionLocal = function (cancellationReason, errorCode, error) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!!this.privRequestSession.isRecognizing) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privRequestSession.onStopRecognizing()]; - case 1: - _a.sent(); - this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, cancellationReason, errorCode, error); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - ServiceRecognizerBase.prototype.receiveMessage = function () { - return __awaiter(this, void 0, void 0, function () { - var connection, message, connectionMessage, _a, speechStartDetected, speechStartEventArgs, json, speechStopDetected, speechStopEventArgs, sessionStopEventArgs, error_5; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 18, , 19]); - if (this.privIsDisposed) { - // We're done. - return [2 /*return*/]; - } - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _b.sent(); - return [4 /*yield*/, connection.read()]; - case 2: - message = _b.sent(); - if (this.receiveMessageOverride !== undefined) { - return [2 /*return*/, this.receiveMessageOverride()]; - } - // indicates we are draining the queue and it came with no message; - if (!message) { - if (!this.privRequestSession.isRecognizing) { - return [2 /*return*/]; - } - else { - return [2 /*return*/, this.receiveMessage()]; - } - } - this.privServiceHasSentMessage = true; - connectionMessage = SpeechConnectionMessage_Internal_1.SpeechConnectionMessage.fromConnectionMessage(message); - if (!(connectionMessage.requestId.toLowerCase() === this.privRequestSession.requestId.toLowerCase())) return [3 /*break*/, 17]; - _a = connectionMessage.path.toLowerCase(); - switch (_a) { - case "turn.start": return [3 /*break*/, 3]; - case "speech.startdetected": return [3 /*break*/, 4]; - case "speech.enddetected": return [3 /*break*/, 5]; - case "turn.end": return [3 /*break*/, 6]; - } - return [3 /*break*/, 15]; - case 3: - this.privMustReportEndOfStream = true; - this.privRequestSession.onServiceTurnStartResponse(); - return [3 /*break*/, 17]; - case 4: - speechStartDetected = Exports_4.SpeechDetected.fromJSON(connectionMessage.textBody); - speechStartEventArgs = new Exports_3.RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId); - if (!!this.privRecognizer.speechStartDetected) { - this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs); - } - return [3 /*break*/, 17]; - case 5: - json = void 0; - if (connectionMessage.textBody.length > 0) { - json = connectionMessage.textBody; - } - else { - // If the request was empty, the JSON returned is empty. - json = "{ Offset: 0 }"; - } - speechStopDetected = Exports_4.SpeechDetected.fromJSON(json); - // Only shrink the buffers for continuous recognition. - // For single shot, the speech.phrase message will come after the speech.end and it should own buffer shrink. - if (this.privRecognizerConfig.isContinuousRecognition) { - this.privRequestSession.onServiceRecognized(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset); - } - speechStopEventArgs = new Exports_3.RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId); - if (!!this.privRecognizer.speechEndDetected) { - this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs); - } - return [3 /*break*/, 17]; - case 6: return [4 /*yield*/, this.sendTelemetryData()]; - case 7: - _b.sent(); - if (!(this.privRequestSession.isSpeechEnded && this.privMustReportEndOfStream)) return [3 /*break*/, 9]; - this.privMustReportEndOfStream = false; - return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.EndOfStream, Exports_3.CancellationErrorCode.NoError, undefined)]; - case 8: - _b.sent(); - _b.label = 9; - case 9: - sessionStopEventArgs = new Exports_3.SessionEventArgs(this.privRequestSession.sessionId); - return [4 /*yield*/, this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition)]; - case 10: - _b.sent(); - if (!(!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing)) return [3 /*break*/, 11]; - if (!!this.privRecognizer.sessionStopped) { - this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs); - } - return [2 /*return*/]; - case 11: return [4 /*yield*/, this.fetchConnection()]; - case 12: - connection = _b.sent(); - return [4 /*yield*/, this.sendPrePayloadJSON(connection)]; - case 13: - _b.sent(); - _b.label = 14; - case 14: return [3 /*break*/, 17]; - case 15: return [4 /*yield*/, this.processTypeSpecificMessages(connectionMessage)]; - case 16: - if (!(_b.sent())) { - // here are some messages that the derived class has not processed, dispatch them to connect class - if (!!this.privServiceEvents) { - this.serviceEvents.onEvent(new Exports_2.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody)); - } - } - _b.label = 17; - case 17: return [2 /*return*/, this.receiveMessage()]; - case 18: - error_5 = _b.sent(); - return [2 /*return*/, null]; - case 19: return [2 /*return*/]; - } - }); - }); - }; - // Encapsulated for derived service recognizers that need to send additional JSON - ServiceRecognizerBase.prototype.sendPrePayloadJSON = function (connection) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.sendPrePayloadJSONOverride !== undefined) { - return [2 /*return*/, this.sendPrePayloadJSONOverride(connection)]; - } - return [4 /*yield*/, this.sendSpeechContext(connection)]; - case 1: - _a.sent(); - return [4 /*yield*/, this.sendWaveHeader(connection)]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - ServiceRecognizerBase.prototype.sendWaveHeader = function (connection) { - return __awaiter(this, void 0, void 0, function () { - var format; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.audioSource.format]; - case 1: - format = _a.sent(); - // this.writeBufferToConsole(format.header); - return [2 /*return*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Binary, "audio", this.privRequestSession.requestId, "audio/x-wav", format.header))]; + if (json.VoiceTag) { + this.privVoiceTag = json.VoiceTag; + } + } + } + get name() { + return this.privName; + } + get locale() { + return this.privLocale; + } + get shortName() { + return this.privShortName; + } + get displayName() { + return this.privDisplayName; + } + get localName() { + return this.privLocalName; + } + get localeName() { + return this.privLocaleName; + } + get gender() { + return this.privGender; + } + get voiceType() { + return this.privVoiceType; + } + get styleList() { + return this.privStyleList; + } + get sampleRateHertz() { + return this.privSampleRateHertz; + } + get status() { + return this.privStatus; + } + get extendedPropertyMap() { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this.privExtendedPropertyMap; + } + get wordsPerMinute() { + return this.privWordsPerMinute; + } + get secondaryLocaleList() { + return this.privSecondaryLocaleList; + } + get rolePlayList() { + return this.privRolePlayList; + } + get voiceTag() { + return this.privVoiceTag; + } +} +exports.VoiceInfo = VoiceInfo; + + + +/***/ }), +/* 169 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeakerAudioDestination = void 0; +const Exports_js_1 = __webpack_require__(4); +const AudioOutputStream_js_1 = __webpack_require__(90); +const AudioStreamFormat_js_1 = __webpack_require__(73); +const MediaDurationPlaceholderSeconds = 60 * 30; +const AudioFormatToMimeType = { + [AudioStreamFormat_js_1.AudioFormatTag.PCM]: "audio/wav", + [AudioStreamFormat_js_1.AudioFormatTag.MuLaw]: "audio/x-wav", + [AudioStreamFormat_js_1.AudioFormatTag.MP3]: "audio/mpeg", + [AudioStreamFormat_js_1.AudioFormatTag.OGG_OPUS]: "audio/ogg", + [AudioStreamFormat_js_1.AudioFormatTag.WEBM_OPUS]: "audio/webm; codecs=opus", + [AudioStreamFormat_js_1.AudioFormatTag.ALaw]: "audio/x-wav", + [AudioStreamFormat_js_1.AudioFormatTag.FLAC]: "audio/flac", + [AudioStreamFormat_js_1.AudioFormatTag.AMR_WB]: "audio/amr-wb", + [AudioStreamFormat_js_1.AudioFormatTag.G722]: "audio/G722", +}; +/** + * Represents the speaker playback audio destination, which only works in browser. + * Note: the SDK will try to use Media Source Extensions to play audio. + * Mp3 format has better supports on Microsoft Edge, Chrome and Safari (desktop), so, it's better to specify mp3 format for playback. + * @class SpeakerAudioDestination + * Updated in version 1.17.0 + */ +class SpeakerAudioDestination { + constructor(audioDestinationId) { + this.privPlaybackStarted = false; + this.privAppendingToBuffer = false; + this.privMediaSourceOpened = false; + this.privBytesReceived = 0; + this.privId = audioDestinationId ? audioDestinationId : (0, Exports_js_1.createNoDashGuid)(); + this.privIsPaused = false; + this.privIsClosed = false; + } + id() { + return this.privId; + } + write(buffer, cb, err) { + if (this.privAudioBuffer !== undefined) { + this.privAudioBuffer.push(buffer); + this.updateSourceBuffer().then(() => { + if (!!cb) { + cb(); } - }); - }); - }; - // Establishes a websocket connection to the end point. - ServiceRecognizerBase.prototype.connectImpl = function () { - var _this = this; - if (this.privConnectionPromise) { - return this.privConnectionPromise.then(function (connection) { - if (connection.state() === Exports_2.ConnectionState.Disconnected) { - _this.privConnectionId = null; - _this.privConnectionPromise = null; - _this.privServiceHasSentMessage = false; - return _this.connectImpl(); + }, (error) => { + if (!!err) { + err(error); } - return _this.privConnectionPromise; - }, function (error) { - _this.privConnectionId = null; - _this.privConnectionPromise = null; - _this.privServiceHasSentMessage = false; - return _this.connectImpl(); }); } - this.privConnectionPromise = this.retryableConnect(); - // Attach an empty handler to allow the promise to run in the background while - // other startup events happen. It'll eventually be awaited on. - this.privConnectionPromise.catch(function () { }); - if (this.postConnectImplOverride !== undefined) { - return this.postConnectImplOverride(this.privConnectionPromise); + else if (this.privAudioOutputStream !== undefined) { + this.privAudioOutputStream.write(buffer); + this.privBytesReceived += buffer.byteLength; } - return this.privConnectionPromise; - }; - ServiceRecognizerBase.prototype.fetchConnection = function () { - return __awaiter(this, void 0, void 0, function () { - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privConnectionConfigurationPromise) { - return [2 /*return*/, this.privConnectionConfigurationPromise.then(function (connection) { - if (connection.state() === Exports_2.ConnectionState.Disconnected) { - _this.privConnectionId = null; - _this.privConnectionConfigurationPromise = null; - _this.privServiceHasSentMessage = false; - return _this.fetchConnection(); - } - return _this.privConnectionConfigurationPromise; - }, function (error) { - _this.privConnectionId = null; - _this.privConnectionConfigurationPromise = null; - _this.privServiceHasSentMessage = false; - return _this.fetchConnection(); - })]; - } - this.privConnectionConfigurationPromise = this.configureConnection(); - return [4 /*yield*/, this.privConnectionConfigurationPromise]; - case 1: return [2 /*return*/, _a.sent()]; + } + close(cb, err) { + this.privIsClosed = true; + if (this.privSourceBuffer !== undefined) { + this.handleSourceBufferUpdateEnd().then(() => { + if (!!cb) { + cb(); } - }); - }); - }; - ServiceRecognizerBase.prototype.sendAudio = function (audioStreamNode) { - return __awaiter(this, void 0, void 0, function () { - var audioFormat, nextSendTime, fastLaneSizeMs, maxSendUnthrottledBytes, startRecogNumber, readAndUploadCycle; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.audioSource.format]; - case 1: - audioFormat = _a.sent(); - nextSendTime = Date.now(); - fastLaneSizeMs = this.privRecognizerConfig.parameters.getProperty("SPEECH-TransmitLengthBeforThrottleMs", "5000"); - maxSendUnthrottledBytes = audioFormat.avgBytesPerSec / 1000 * parseInt(fastLaneSizeMs, 10); - startRecogNumber = this.privRequestSession.recogNumber; - readAndUploadCycle = function () { return __awaiter(_this, void 0, void 0, function () { - var connection, audioStreamChunk, payload, sendDelay; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!this.privIsDisposed && - !this.privRequestSession.isSpeechEnded && - this.privRequestSession.isRecognizing && - this.privRequestSession.recogNumber === startRecogNumber)) return [3 /*break*/, 5]; - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [4 /*yield*/, audioStreamNode.read()]; - case 2: - audioStreamChunk = _a.sent(); - // we have a new audio chunk to upload. - if (this.privRequestSession.isSpeechEnded) { - // If service already recognized audio end then don't send any more audio - return [2 /*return*/]; - } - payload = void 0; - sendDelay = void 0; - if (!audioStreamChunk || audioStreamChunk.isEnd) { - payload = null; - sendDelay = 0; - } - else { - payload = audioStreamChunk.buffer; - this.privRequestSession.onAudioSent(payload.byteLength); - if (maxSendUnthrottledBytes >= this.privRequestSession.bytesSent) { - sendDelay = 0; - } - else { - sendDelay = Math.max(0, nextSendTime - Date.now()); - } - } - if (!(0 !== sendDelay)) return [3 /*break*/, 4]; - return [4 /*yield*/, this.delay(sendDelay)]; - case 3: - _a.sent(); - _a.label = 4; - case 4: - if (payload !== null) { - nextSendTime = Date.now() + (payload.byteLength * 1000 / (audioFormat.avgBytesPerSec * 2)); - } - // Are we still alive? - if (!this.privIsDisposed && - !this.privRequestSession.isSpeechEnded && - this.privRequestSession.isRecognizing && - this.privRequestSession.recogNumber === startRecogNumber) { - connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Binary, "audio", this.privRequestSession.requestId, null, payload)).catch(function () { - _this.privRequestSession.onServiceTurnEndResponse(_this.privRecognizerConfig.isContinuousRecognition).catch(function () { }); - }); - if (!(audioStreamChunk === null || audioStreamChunk === void 0 ? void 0 : audioStreamChunk.isEnd)) { - // this.writeBufferToConsole(payload); - // Regardless of success or failure, schedule the next upload. - // If the underlying connection was broken, the next cycle will - // get a new connection and re-transmit missing audio automatically. - return [2 /*return*/, readAndUploadCycle()]; - } - else { - // the audio stream has been closed, no need to schedule next - // read-upload cycle. - if (!this.privIsLiveAudio) { - this.privRequestSession.onSpeechEnded(); - } - } - } - _a.label = 5; - case 5: return [2 /*return*/]; - } - }); - }); }; - return [2 /*return*/, readAndUploadCycle()]; + }, (error) => { + if (!!err) { + err(error); } }); - }); - }; - ServiceRecognizerBase.prototype.retryableConnect = function () { - return __awaiter(this, void 0, void 0, function () { - var isUnAuthorized, sessionId, lastStatusCode, lastReason, authPromise, auth, connection, response; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - isUnAuthorized = false; - this.privAuthFetchEventId = Exports_2.createNoDashGuid(); - sessionId = this.privRequestSession.sessionId; - this.privConnectionId = (sessionId !== undefined) ? sessionId : Exports_2.createNoDashGuid(); - this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId); - lastStatusCode = 0; - lastReason = ""; - _a.label = 1; - case 1: - if (!(this.privRequestSession.numConnectionAttempts <= this.privRecognizerConfig.maxRetryCount)) return [3 /*break*/, 8]; - authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId); - return [4 /*yield*/, authPromise]; - case 2: - auth = _a.sent(); - return [4 /*yield*/, this.privRequestSession.onAuthCompleted(false)]; - case 3: - _a.sent(); - connection = this.privConnectionFactory.create(this.privRecognizerConfig, auth, this.privConnectionId); - // Attach the telemetry handlers. - this.privRequestSession.listenForServiceTelemetry(connection.events); - // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away, - // it'll stop sending events. - connection.events.attach(function (event) { - _this.connectionEvents.onEvent(event); - }); - return [4 /*yield*/, connection.open()]; - case 4: - response = _a.sent(); - if (!(response.statusCode === 200)) return [3 /*break*/, 6]; - return [4 /*yield*/, this.privRequestSession.onConnectionEstablishCompleted(response.statusCode)]; - case 5: - _a.sent(); - return [2 /*return*/, Promise.resolve(connection)]; - case 6: - if (response.statusCode === 1006) { - isUnAuthorized = true; - } - _a.label = 7; - case 7: - lastStatusCode = response.statusCode; - lastReason = response.reason; - this.privRequestSession.onRetryConnection(); - return [3 /*break*/, 1]; - case 8: return [4 /*yield*/, this.privRequestSession.onConnectionEstablishCompleted(lastStatusCode, lastReason)]; - case 9: - _a.sent(); - return [2 /*return*/, Promise.reject("Unable to contact server. StatusCode: " + lastStatusCode + ", " + this.privRecognizerConfig.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Endpoint) + " Reason: " + lastReason)]; + } + else if (this.privAudioOutputStream !== undefined && typeof window !== "undefined") { + if ((this.privFormat.formatTag === AudioStreamFormat_js_1.AudioFormatTag.PCM || this.privFormat.formatTag === AudioStreamFormat_js_1.AudioFormatTag.MuLaw + || this.privFormat.formatTag === AudioStreamFormat_js_1.AudioFormatTag.ALaw) && this.privFormat.hasHeader === false) { + // eslint-disable-next-line no-console + console.warn("Play back is not supported for raw PCM, mulaw or alaw format without header."); + if (!!this.onAudioEnd) { + this.onAudioEnd(this); } - }); - }); - }; - ServiceRecognizerBase.prototype.delay = function (delayMs) { - var _this = this; - return new Promise(function (resolve, reject) { - _this.privSetTimeout(resolve, delayMs); - }); - }; - ServiceRecognizerBase.prototype.writeBufferToConsole = function (buffer) { - var out = "Buffer Size: "; - if (null === buffer) { - out += "null"; + } + else { + let receivedAudio = new ArrayBuffer(this.privBytesReceived); + this.privAudioOutputStream.read(receivedAudio).then(() => { + receivedAudio = this.privFormat.addHeader(receivedAudio); + const audioBlob = new Blob([receivedAudio], { type: AudioFormatToMimeType[this.privFormat.formatTag] }); + this.privAudio.src = window.URL.createObjectURL(audioBlob); + this.notifyPlayback().then(() => { + if (!!cb) { + cb(); + } + }, (error) => { + if (!!err) { + err(error); + } + }); + }, (error) => { + if (!!err) { + err(error); + } + }); + } } else { - var readView = new Uint8Array(buffer); - out += buffer.byteLength + "\r\n"; - for (var i = 0; i < buffer.byteLength; i++) { - out += readView[i].toString(16).padStart(2, "0") + " "; + // unsupported format, call onAudioEnd directly. + if (!!this.onAudioEnd) { + this.onAudioEnd(this); } } - // tslint:disable-next-line:no-console - console.info(out); - }; - ServiceRecognizerBase.prototype.sendFinalAudio = function () { - return __awaiter(this, void 0, void 0, function () { - var connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [4 /*yield*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Binary, "audio", this.privRequestSession.requestId, null, null))]; - case 2: - _a.sent(); - return [2 /*return*/]; + } + set format(format) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (typeof (AudioContext) !== "undefined" || (typeof (window) !== "undefined" && typeof (window.webkitAudioContext) !== "undefined")) { + this.privFormat = format; + const mimeType = AudioFormatToMimeType[this.privFormat.formatTag]; + if (mimeType === undefined) { + // eslint-disable-next-line no-console + console.warn(`Unknown mimeType for format ${AudioStreamFormat_js_1.AudioFormatTag[this.privFormat.formatTag]}; playback is not supported.`); + } + else if (typeof (MediaSource) !== "undefined" && MediaSource.isTypeSupported(mimeType)) { + 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 = true; + this.privMediaSource.duration = MediaDurationPlaceholderSeconds; + this.privSourceBuffer = this.privMediaSource.addSourceBuffer(mimeType); + this.privSourceBuffer.onupdate = () => { + this.updateSourceBuffer().catch((reason) => { + Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason)); + }); + }; + this.privSourceBuffer.onupdateend = () => { + this.handleSourceBufferUpdateEnd().catch((reason) => { + Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason)); + }); + }; + this.privSourceBuffer.onupdatestart = () => { + this.privAppendingToBuffer = false; + }; + }; + this.updateSourceBuffer().catch((reason) => { + Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason)); + }); + } + else { + // eslint-disable-next-line no-console + console.warn(`Format ${AudioStreamFormat_js_1.AudioFormatTag[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`); + this.privAudioOutputStream = new AudioOutputStream_js_1.PullAudioOutputStreamImpl(); + this.privAudioOutputStream.format = this.privFormat; + this.privAudio = new Audio(); + } + } + } + get volume() { + return this.privAudio?.volume ?? -1; + } + set volume(volume) { + if (!!this.privAudio) { + this.privAudio.volume = volume; + } + } + mute() { + if (!!this.privAudio) { + this.privAudio.muted = true; + } + } + unmute() { + if (!!this.privAudio) { + this.privAudio.muted = false; + } + } + get isClosed() { + return this.privIsClosed; + } + get currentTime() { + if (this.privAudio !== undefined) { + return this.privAudio.currentTime; + } + return -1; + } + pause() { + if (!this.privIsPaused && this.privAudio !== undefined) { + this.privAudio.pause(); + this.privIsPaused = true; + } + } + resume(cb, err) { + if (this.privIsPaused && this.privAudio !== undefined) { + this.privAudio.play().then(() => { + if (!!cb) { + cb(); } - }); - }); - }; - // Takes an established websocket connection to the endpoint and sends speech configuration information. - ServiceRecognizerBase.prototype.configureConnection = function () { - return __awaiter(this, void 0, void 0, function () { - var connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.connectImpl()]; - case 1: - connection = _a.sent(); - if (this.configConnectionOverride !== undefined) { - return [2 /*return*/, this.configConnectionOverride(connection)]; - } - return [4 /*yield*/, this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize())]; - case 2: - _a.sent(); - return [4 /*yield*/, this.sendPrePayloadJSON(connection)]; - case 3: - _a.sent(); - return [2 /*return*/, connection]; + }, (error) => { + if (!!err) { + err(error); } }); - }); - }; - ServiceRecognizerBase.telemetryDataEnabled = true; - return ServiceRecognizerBase; -}()); -exports.ServiceRecognizerBase = ServiceRecognizerBase; + this.privIsPaused = false; + } + } + get internalAudio() { + return this.privAudio; + } + async updateSourceBuffer() { + if (this.privAudioBuffer !== undefined && (this.privAudioBuffer.length > 0) && this.sourceBufferAvailable()) { + this.privAppendingToBuffer = true; + const binary = this.privAudioBuffer.shift(); + try { + this.privSourceBuffer.appendBuffer(binary); + } + catch (error) { + this.privAudioBuffer.unshift(binary); + // eslint-disable-next-line no-console + console.log("buffer filled, pausing addition of binaries until space is made"); + return; + } + await this.notifyPlayback(); + } + else if (this.canEndStream()) { + await this.handleSourceBufferUpdateEnd(); + } + } + async handleSourceBufferUpdateEnd() { + if (this.canEndStream() && this.sourceBufferAvailable()) { + this.privMediaSource.endOfStream(); + await this.notifyPlayback(); + } + } + async notifyPlayback() { + if (!this.privPlaybackStarted && this.privAudio !== undefined) { + this.privPlaybackStarted = true; + if (!!this.onAudioStart) { + this.onAudioStart(this); + } + this.privAudio.onended = () => { + if (!!this.onAudioEnd) { + this.onAudioEnd(this); + } + }; + if (!this.privIsPaused) { + await this.privAudio.play(); + } + } + } + canEndStream() { + return (this.isClosed && this.privSourceBuffer !== undefined && (this.privAudioBuffer.length === 0) + && this.privMediaSourceOpened && !this.privAppendingToBuffer && this.privMediaSource.readyState === "open"); + } + sourceBufferAvailable() { + return (this.privSourceBuffer !== undefined && !this.privSourceBuffer.updating); + } +} +exports.SpeakerAudioDestination = SpeakerAudioDestination; + + + +/***/ }), +/* 170 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationTranscriptionCanceledEventArgs = void 0; +const CancellationEventArgsBase_js_1 = __webpack_require__(104); +/** + * Defines content of a RecognitionErrorEvent. + * @class ConversationTranscriptionCanceledEventArgs + */ +class ConversationTranscriptionCanceledEventArgs extends CancellationEventArgsBase_js_1.CancellationEventArgsBase { +} +exports.ConversationTranscriptionCanceledEventArgs = ConversationTranscriptionCanceledEventArgs; + + + +/***/ }), +/* 171 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MeetingTranscriptionCanceledEventArgs = void 0; +const CancellationEventArgsBase_js_1 = __webpack_require__(104); +/** + * Defines content of a MeetingTranscriptionCanceledEvent. + * @class MeetingTranscriptionCanceledEventArgs + */ +class MeetingTranscriptionCanceledEventArgs extends CancellationEventArgsBase_js_1.CancellationEventArgsBase { +} +exports.MeetingTranscriptionCanceledEventArgs = MeetingTranscriptionCanceledEventArgs; + + + +/***/ }), +/* 172 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PronunciationAssessmentGradingSystem = void 0; +/** + * Defines the point system for pronunciation score calibration; default value is FivePoint. + * Added in version 1.15.0 + * @class PronunciationAssessmentGradingSystem + */ +var PronunciationAssessmentGradingSystem; +(function (PronunciationAssessmentGradingSystem) { + /** + * Five point calibration + * @member PronunciationAssessmentGradingSystem.FivePoint + */ + PronunciationAssessmentGradingSystem[PronunciationAssessmentGradingSystem["FivePoint"] = 1] = "FivePoint"; + /** + * Hundred mark + * @member PronunciationAssessmentGradingSystem.HundredMark + */ + PronunciationAssessmentGradingSystem[PronunciationAssessmentGradingSystem["HundredMark"] = 2] = "HundredMark"; +})(PronunciationAssessmentGradingSystem = exports.PronunciationAssessmentGradingSystem || (exports.PronunciationAssessmentGradingSystem = {})); /***/ }), /* 173 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechConnectionMessage = void 0; -var Exports_1 = __webpack_require__(4); -var HeaderNames_1 = __webpack_require__(55); -var SpeechConnectionMessage = /** @class */ (function (_super) { - __extends(SpeechConnectionMessage, _super); - function SpeechConnectionMessage(messageType, path, requestId, contentType, body, streamId, additionalHeaders, id) { - var _this = this; - if (!path) { - throw new Exports_1.ArgumentNullError("path"); - } - if (!requestId) { - throw new Exports_1.ArgumentNullError("requestId"); - } - var headers = {}; - headers[HeaderNames_1.HeaderNames.Path] = path; - headers[HeaderNames_1.HeaderNames.RequestId] = requestId; - headers[HeaderNames_1.HeaderNames.RequestTimestamp] = new Date().toISOString(); - if (contentType) { - headers[HeaderNames_1.HeaderNames.ContentType] = contentType; - } - if (streamId) { - headers[HeaderNames_1.HeaderNames.RequestStreamId] = streamId; - } - if (additionalHeaders) { - for (var headerName in additionalHeaders) { - if (headerName) { - headers[headerName] = additionalHeaders[headerName]; - } - } - } - if (id) { - _this = _super.call(this, messageType, body, headers, id) || this; - } - else { - _this = _super.call(this, messageType, body, headers) || this; - } - _this.privPath = path; - _this.privRequestId = requestId; - _this.privContentType = contentType; - _this.privStreamId = streamId; - _this.privAdditionalHeaders = additionalHeaders; - return _this; - } - Object.defineProperty(SpeechConnectionMessage.prototype, "path", { - get: function () { - return this.privPath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConnectionMessage.prototype, "requestId", { - get: function () { - return this.privRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConnectionMessage.prototype, "contentType", { - get: function () { - return this.privContentType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConnectionMessage.prototype, "streamId", { - get: function () { - return this.privStreamId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechConnectionMessage.prototype, "additionalHeaders", { - get: function () { - return this.privAdditionalHeaders; - }, - enumerable: false, - configurable: true - }); - SpeechConnectionMessage.fromConnectionMessage = function (message) { - var path = null; - var requestId = null; - var contentType = null; - var requestTimestamp = null; - var streamId = null; - var additionalHeaders = {}; - if (message.headers) { - for (var headerName in message.headers) { - if (headerName) { - if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.Path.toLowerCase()) { - path = message.headers[headerName]; - } - else if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.RequestId.toLowerCase()) { - requestId = message.headers[headerName]; - } - else if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.RequestTimestamp.toLowerCase()) { - requestTimestamp = message.headers[headerName]; - } - else if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.ContentType.toLowerCase()) { - contentType = message.headers[headerName]; - } - else if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.RequestStreamId.toLowerCase()) { - streamId = message.headers[headerName]; - } - else { - additionalHeaders[headerName] = message.headers[headerName]; - } - } - } - } - return new SpeechConnectionMessage(message.messageType, path, requestId, contentType, message.body, streamId, additionalHeaders, message.id); - }; - return SpeechConnectionMessage; -}(Exports_1.ConnectionMessage)); -exports.SpeechConnectionMessage = SpeechConnectionMessage; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PronunciationAssessmentGranularity = void 0; +/** + * Defines the pronunciation evaluation granularity; default value is Phoneme. + * Added in version 1.15.0 + * @class PronunciationAssessmentGranularity + */ +var PronunciationAssessmentGranularity; +(function (PronunciationAssessmentGranularity) { + /** + * Shows the score on the full text, word and phoneme level + * @member PronunciationAssessmentGranularity.Phoneme + */ + PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["Phoneme"] = 1] = "Phoneme"; + /** + * Shows the score on the full text and word level + * @member PronunciationAssessmentGranularity.Word + */ + PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["Word"] = 2] = "Word"; + /** + * Shows the score on the full text level only + * @member PronunciationAssessmentGranularity.FullText + */ + PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["FullText"] = 3] = "FullText"; +})(PronunciationAssessmentGranularity = exports.PronunciationAssessmentGranularity || (exports.PronunciationAssessmentGranularity = {})); /***/ }), /* 174 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.type = exports.connectivity = exports.Device = exports.OS = exports.System = exports.Context = exports.SpeechServiceConfig = exports.RecognizerConfig = exports.SpeechResultFormat = exports.RecognitionMode = void 0; -// tslint:disable:max-classes-per-file -var Exports_1 = __webpack_require__(61); -var RecognitionMode; -(function (RecognitionMode) { - RecognitionMode[RecognitionMode["Interactive"] = 0] = "Interactive"; - RecognitionMode[RecognitionMode["Conversation"] = 1] = "Conversation"; - RecognitionMode[RecognitionMode["Dictation"] = 2] = "Dictation"; -})(RecognitionMode = exports.RecognitionMode || (exports.RecognitionMode = {})); -var SpeechResultFormat; -(function (SpeechResultFormat) { - SpeechResultFormat[SpeechResultFormat["Simple"] = 0] = "Simple"; - SpeechResultFormat[SpeechResultFormat["Detailed"] = 1] = "Detailed"; -})(SpeechResultFormat = exports.SpeechResultFormat || (exports.SpeechResultFormat = {})); -var RecognizerConfig = /** @class */ (function () { - function RecognizerConfig(speechServiceConfig, parameters) { - this.privRecognitionMode = RecognitionMode.Interactive; - this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new SpeechServiceConfig(new Context(null)); - this.privParameters = parameters; - this.privMaxRetryCount = parseInt(parameters.getProperty("SPEECH-Error-MaxRetryCount", "4"), 10); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PronunciationAssessmentConfig = void 0; +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_1 = __webpack_require__(85); +/** + * Pronunciation assessment configuration. + * @class PronunciationAssessmentConfig + * Added in version 1.15.0. + */ +class PronunciationAssessmentConfig { + /** + * PronunciationAssessmentConfig constructor. + * @constructor + * @param {string} referenceText + * @param gradingSystem + * @param granularity + * @param enableMiscue + */ + constructor(referenceText, gradingSystem = Exports_js_1.PronunciationAssessmentGradingSystem.FivePoint, granularity = Exports_js_1.PronunciationAssessmentGranularity.Phoneme, enableMiscue = false) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(referenceText, "referenceText"); + this.privProperties = new Exports_js_1.PropertyCollection(); + this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_ReferenceText, referenceText); + this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_GradingSystem, Exports_js_1.PronunciationAssessmentGradingSystem[gradingSystem]); + this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_Granularity, Exports_js_1.PronunciationAssessmentGranularity[granularity]); + this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_EnableMiscue, String(enableMiscue)); } - Object.defineProperty(RecognizerConfig.prototype, "parameters", { - get: function () { - return this.privParameters; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognizerConfig.prototype, "recognitionMode", { - get: function () { - return this.privRecognitionMode; - }, - set: function (value) { - this.privRecognitionMode = value; - this.privRecognitionActivityTimeout = value === RecognitionMode.Interactive ? 8000 : 25000; - this.privSpeechServiceConfig.Recognition = RecognitionMode[value]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognizerConfig.prototype, "SpeechServiceConfig", { - get: function () { - return this.privSpeechServiceConfig; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognizerConfig.prototype, "recognitionActivityTimeout", { - get: function () { - return this.privRecognitionActivityTimeout; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognizerConfig.prototype, "isContinuousRecognition", { - get: function () { - return this.privRecognitionMode !== RecognitionMode.Interactive; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognizerConfig.prototype, "autoDetectSourceLanguages", { - get: function () { - return this.parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, undefined); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RecognizerConfig.prototype, "maxRetryCount", { - get: function () { - return this.privMaxRetryCount; - }, - enumerable: false, - configurable: true - }); - return RecognizerConfig; -}()); -exports.RecognizerConfig = RecognizerConfig; -// The config is serialized and sent as the Speech.Config -var SpeechServiceConfig = /** @class */ (function () { - function SpeechServiceConfig(context) { - var _this = this; - this.serialize = function () { - return JSON.stringify(_this, function (key, value) { - if (value && typeof value === "object") { - var replacement = {}; - for (var k in value) { - if (Object.hasOwnProperty.call(value, k)) { - replacement[k && k.charAt(0).toLowerCase() + k.substring(1)] = value[k]; - } - } - return replacement; - } - return value; - }); - }; - this.context = context; + /** + * @member PronunciationAssessmentConfig.fromJSON + * @function + * @public + * @param {string} json The json string containing the pronunciation assessment parameters. + * @return {PronunciationAssessmentConfig} Instance of PronunciationAssessmentConfig + * @summary Creates an instance of the PronunciationAssessmentConfig from json. + * This method is designed to support the pronunciation assessment parameters still in preview. + * Under normal circumstances, use the constructor instead. + */ + static fromJSON(json) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(json, "json"); + const config = new PronunciationAssessmentConfig(""); + config.privProperties = new Exports_js_1.PropertyCollection(); + config.properties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_Json, json); + return config; } - Object.defineProperty(SpeechServiceConfig.prototype, "Context", { - get: function () { - return this.context; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechServiceConfig.prototype, "Recognition", { - get: function () { - return this.recognition; - }, - set: function (value) { - this.recognition = value.toLowerCase(); - }, - enumerable: false, - configurable: true - }); - return SpeechServiceConfig; -}()); -exports.SpeechServiceConfig = SpeechServiceConfig; -var Context = /** @class */ (function () { - function Context(os) { - this.system = new System(); - this.os = os; + toJSON() { + this.updateJson(); + return this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_Params); } - return Context; -}()); -exports.Context = Context; -var System = /** @class */ (function () { - function System() { - // Note: below will be patched for official builds. - var SPEECHSDK_CLIENTSDK_VERSION = "1.20.0"; - this.name = "SpeechSDK"; - this.version = SPEECHSDK_CLIENTSDK_VERSION; - this.build = "JavaScript"; - this.lang = "JavaScript"; + applyTo(recognizer) { + this.updateJson(); + const recoBase = recognizer.internalData; + recoBase.speechContext.setPronunciationAssessmentParams(this.properties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_Params), recoBase.isSpeakerDiarizationEnabled); } - return System; -}()); -exports.System = System; -var OS = /** @class */ (function () { - function OS(platform, name, version) { - this.platform = platform; - this.name = name; - this.version = version; + /** + * Gets the reference text. + * @member PronunciationAssessmentConfig.prototype.referenceText + * @function + * @public + * @returns {string} Reference text. + */ + get referenceText() { + return this.properties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_ReferenceText); } - return OS; -}()); -exports.OS = OS; -var Device = /** @class */ (function () { - function Device(manufacturer, model, version) { - this.manufacturer = manufacturer; - this.model = model; - this.version = version; + /** + * Gets/Sets the reference text. + * @member PronunciationAssessmentConfig.prototype.referenceText + * @function + * @public + * @param {string} referenceText - Reference text. + */ + set referenceText(referenceText) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(referenceText, "referenceText"); + this.properties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_ReferenceText, referenceText); } - return Device; -}()); -exports.Device = Device; -var connectivity; -(function (connectivity) { - connectivity["Bluetooth"] = "Bluetooth"; - connectivity["Wired"] = "Wired"; - connectivity["WiFi"] = "WiFi"; - connectivity["Cellular"] = "Cellular"; - connectivity["InBuilt"] = "InBuilt"; - connectivity["Unknown"] = "Unknown"; -})(connectivity = exports.connectivity || (exports.connectivity = {})); -var type; -(function (type) { - type["Phone"] = "Phone"; - type["Speaker"] = "Speaker"; - type["Car"] = "Car"; - type["Headset"] = "Headset"; - type["Thermostat"] = "Thermostat"; - type["Microphones"] = "Microphones"; - type["Deskphone"] = "Deskphone"; - type["RemoteControl"] = "RemoteControl"; - type["Unknown"] = "Unknown"; - type["File"] = "File"; - type["Stream"] = "Stream"; -})(type = exports.type || (exports.type = {})); + /** + * Sets the phoneme alphabet. + * The valid values are "SAPI" (default) and "IPA". + * Added in version 1.20.0 + * @member PronunciationAssessmentConfig.prototype.phonemeAlphabet + * @function + * @public + * @param {string} phonemeAlphabet - Phoneme alphabet. + */ + set phonemeAlphabet(phonemeAlphabet) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(phonemeAlphabet, "phonemeAlphabet"); + this.privPhonemeAlphabet = phonemeAlphabet; + } + /** + * Sets the boolean enableMiscue property. + * Added in version 1.26.0 + * @member PronunciationAssessmentConfig.prototype.enableMiscue + * @function + * @public + * @param {boolean} enableMiscue - enable miscue. + */ + set enableMiscue(enableMiscue) { + const enableMiscueString = enableMiscue ? "true" : "false"; + this.properties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_EnableMiscue, enableMiscueString); + } + /** + * Gets the boolean enableMiscue property. + * Added in version 1.26.0 + * @member PronunciationAssessmentConfig.prototype.enableMiscue + * @function + * @public + * @return {boolean} enableMiscue - enable miscue. + */ + get enableMiscue() { + const enableMiscueString = this.properties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_EnableMiscue, "false"); + return (enableMiscueString.toLowerCase() === "true"); + } + /** + * Sets the nbest phoneme count + * Added in version 1.20.0 + * @member PronunciationAssessmentConfig.prototype.nbestPhonemeCount + * @function + * @public + * @param {number} nbestPhonemeCount - NBest phoneme count. + */ + set nbestPhonemeCount(nbestPhonemeCount) { + this.privNBestPhonemeCount = nbestPhonemeCount; + } + /** + * Enables the prosody assessment. + * Added in version 1.34.0 + * @member PronunciationAssessmentConfig.prototype.enableProsodyAssessment + * @function + * @public + * @param {boolean} enableProsodyAssessment - enable prosody assessment. + */ + set enableProsodyAssessment(enableProsodyAssessment) { + this.privEnableProsodyAssessment = enableProsodyAssessment; + } + /** + * @member PronunciationAssessmentConfig.prototype.properties + * @function + * @public + * @return {PropertyCollection} Properties of the config. + * @summary Gets a pronunciation assessment config properties + */ + get properties() { + return this.privProperties; + } + updateJson() { + const jsonString = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_Json, "{}"); + const paramsJson = JSON.parse(jsonString); + const referenceText = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_ReferenceText); + if (referenceText) { + paramsJson.referenceText = referenceText; + } + const gradingSystem = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_GradingSystem); + if (gradingSystem) { + paramsJson.gradingSystem = gradingSystem; + } + const granularity = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_Granularity); + if (granularity) { + paramsJson.granularity = granularity; + } + if (this.privPhonemeAlphabet) { + paramsJson.phonemeAlphabet = this.privPhonemeAlphabet; + } + if (this.privNBestPhonemeCount) { + paramsJson.nbestPhonemeCount = this.privNBestPhonemeCount; + } + paramsJson.enableProsodyAssessment = this.privEnableProsodyAssessment; + // always set dimension to Comprehensive + paramsJson.dimension = "Comprehensive"; + const enableMiscueString = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_EnableMiscue); + if (enableMiscueString) { + paramsJson.enableMiscue = this.enableMiscue; + } + this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_Params, JSON.stringify(paramsJson)); + } +} +exports.PronunciationAssessmentConfig = PronunciationAssessmentConfig; /***/ }), /* 175 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); - - - -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.WebsocketMessageFormatter = void 0; -var Exports_1 = __webpack_require__(4); -var CRLF = "\r\n"; -var WebsocketMessageFormatter = /** @class */ (function () { - function WebsocketMessageFormatter() { - var _this = this; - this.toConnectionMessage = function (message) { - var deferral = new Exports_1.Deferred(); - try { - if (message.messageType === Exports_1.MessageType.Text) { - var textMessage = message.textContent; - var headers = {}; - var body = null; - if (textMessage) { - var headerBodySplit = textMessage.split("\r\n\r\n"); - if (headerBodySplit && headerBodySplit.length > 0) { - headers = _this.parseHeaders(headerBodySplit[0]); - if (headerBodySplit.length > 1) { - body = headerBodySplit[1]; - } - } - } - deferral.resolve(new Exports_1.ConnectionMessage(message.messageType, body, headers, message.id)); - } - else if (message.messageType === Exports_1.MessageType.Binary) { - var binaryMessage = message.binaryContent; - var headers = {}; - var body = null; - if (!binaryMessage || binaryMessage.byteLength < 2) { - throw new Error("Invalid binary message format. Header length missing."); - } - var dataView = new DataView(binaryMessage); - var headerLength = dataView.getInt16(0); - if (binaryMessage.byteLength < headerLength + 2) { - throw new Error("Invalid binary message format. Header content missing."); - } - var headersString = ""; - for (var i = 0; i < headerLength; i++) { - headersString += String.fromCharCode((dataView).getInt8(i + 2)); - } - headers = _this.parseHeaders(headersString); - if (binaryMessage.byteLength > headerLength + 2) { - body = binaryMessage.slice(2 + headerLength); - } - deferral.resolve(new Exports_1.ConnectionMessage(message.messageType, body, headers, message.id)); - } - } - catch (e) { - deferral.reject("Error formatting the message. Error: " + e); - } - return deferral.promise; - }; - this.fromConnectionMessage = function (message) { - var deferral = new Exports_1.Deferred(); - try { - if (message.messageType === Exports_1.MessageType.Text) { - var payload = "" + _this.makeHeaders(message) + CRLF + (message.textBody ? message.textBody : ""); - deferral.resolve(new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Text, payload, message.id)); - } - else if (message.messageType === Exports_1.MessageType.Binary) { - var headersString = _this.makeHeaders(message); - var content = message.binaryBody; - var headerBuffer = _this.stringToArrayBuffer(headersString); - var headerInt8Array = new Int8Array(headerBuffer); - var headerLength = headerInt8Array.byteLength; - var payloadInt8Array = new Int8Array(2 + headerLength + (content ? content.byteLength : 0)); - payloadInt8Array[0] = ((headerLength >> 8) & 0xff); - payloadInt8Array[1] = headerLength & 0xff; - payloadInt8Array.set(headerInt8Array, 2); - if (content) { - var bodyInt8Array = new Int8Array(content); - payloadInt8Array.set(bodyInt8Array, 2 + headerLength); - } - var payload = payloadInt8Array.buffer; - deferral.resolve(new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Binary, payload, message.id)); - } - } - catch (e) { - deferral.reject("Error formatting the message. " + e); - } - return deferral.promise; - }; - this.makeHeaders = function (message) { - var headersString = ""; - if (message.headers) { - for (var header in message.headers) { - if (header) { - headersString += header + ": " + message.headers[header] + CRLF; - } - } - } - return headersString; - }; - this.parseHeaders = function (headersString) { - var headers = {}; - if (headersString) { - var headerMatches = headersString.match(/[^\r\n]+/g); - if (headers) { - for (var _i = 0, headerMatches_1 = headerMatches; _i < headerMatches_1.length; _i++) { - var header = headerMatches_1[_i]; - if (header) { - var separatorIndex = header.indexOf(":"); - var headerName = separatorIndex > 0 ? header.substr(0, separatorIndex).trim().toLowerCase() : header; - var headerValue = separatorIndex > 0 && header.length > (separatorIndex + 1) ? - header.substr(separatorIndex + 1).trim() : - ""; - headers[headerName] = headerValue; - } - } - } - } - return headers; - }; - this.stringToArrayBuffer = function (str) { - var buffer = new ArrayBuffer(str.length); - var view = new DataView(buffer); - for (var i = 0; i < str.length; i++) { - view.setUint8(i, str.charCodeAt(i)); - } - return buffer; - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PronunciationAssessmentResult = void 0; +/* eslint-disable max-classes-per-file */ +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_1 = __webpack_require__(85); +/** + * Pronunciation assessment results. + * @class PronunciationAssessmentResult + * Added in version 1.15.0. + */ +class PronunciationAssessmentResult { + constructor(jsonString) { + const j = JSON.parse(jsonString); + Contracts_js_1.Contracts.throwIfNullOrUndefined(j.NBest[0], "NBest"); + this.privPronJson = j.NBest[0]; + } + /** + * @member PronunciationAssessmentResult.fromResult + * @function + * @public + * @param {RecognitionResult} result The recognition result. + * @return {PronunciationAssessmentConfig} Instance of PronunciationAssessmentConfig + * @summary Creates an instance of the PronunciationAssessmentResult from recognition result. + */ + static fromResult(result) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(result, "result"); + const json = result.properties.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult); + Contracts_js_1.Contracts.throwIfNullOrUndefined(json, "json"); + return new PronunciationAssessmentResult(json); + } + /** + * Gets the detail result of pronunciation assessment. + * @member PronunciationAssessmentConfig.prototype.detailResult + * @function + * @public + * @returns {DetailResult} detail result. + */ + get detailResult() { + return this.privPronJson; + } + /** + * The score indicating the pronunciation accuracy of the given speech, which indicates + * how closely the phonemes match a native speaker's pronunciation. + * @member PronunciationAssessmentResult.prototype.accuracyScore + * @function + * @public + * @returns {number} Accuracy score. + */ + get accuracyScore() { + return this.detailResult.PronunciationAssessment?.AccuracyScore; + } + /** + * The overall score indicating the pronunciation quality of the given speech. + * This is calculated from AccuracyScore, FluencyScore and CompletenessScore with weight. + * @member PronunciationAssessmentResult.prototype.pronunciationScore + * @function + * @public + * @returns {number} Pronunciation score. + */ + get pronunciationScore() { + return this.detailResult.PronunciationAssessment?.PronScore; + } + /** + * The score indicating the completeness of the given speech by calculating the ratio of pronounced words towards entire input. + * @member PronunciationAssessmentResult.prototype.completenessScore + * @function + * @public + * @returns {number} Completeness score. + */ + get completenessScore() { + return this.detailResult.PronunciationAssessment?.CompletenessScore; + } + /** + * The score indicating the fluency of the given speech. + * @member PronunciationAssessmentResult.prototype.fluencyScore + * @function + * @public + * @returns {number} Fluency score. + */ + get fluencyScore() { + return this.detailResult.PronunciationAssessment?.FluencyScore; + } + /** + * The prosody score, which indicates how nature of the given speech, including stress, intonation, speaking speed and rhythm. + * @member PronunciationAssessmentResult.prototype.prosodyScore + * @function + * @public + * @returns {number} Prosody score. + */ + get prosodyScore() { + return this.detailResult.PronunciationAssessment?.ProsodyScore; } - return WebsocketMessageFormatter; -}()); -exports.WebsocketMessageFormatter = WebsocketMessageFormatter; +} +exports.PronunciationAssessmentResult = PronunciationAssessmentResult; /***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { +/* 176 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechConnectionFactory = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(53); -var Exports_3 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -var Exports_4 = __webpack_require__(53); -var HeaderNames_1 = __webpack_require__(55); -var QueryParameterNames_1 = __webpack_require__(124); -var SpeechConnectionFactory = /** @class */ (function (_super) { - __extends(SpeechConnectionFactory, _super); - function SpeechConnectionFactory() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.interactiveRelativeUri = "/speech/recognition/interactive/cognitiveservices/v1"; - _this.conversationRelativeUri = "/speech/recognition/conversation/cognitiveservices/v1"; - _this.dictationRelativeUri = "/speech/recognition/dictation/cognitiveservices/v1"; - _this.create = function (config, authInfo, connectionId) { - var endpoint = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Endpoint, undefined); - var region = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Region, undefined); - var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region); - var host = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".stt.speech" + hostSuffix); - var queryParams = {}; - var endpointId = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_EndpointId, undefined); - var language = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage, undefined); - if (endpointId) { - if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.CustomSpeechDeploymentId) === -1) { - queryParams[QueryParameterNames_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId; - } - } - else if (language) { - if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.Language) === -1) { - queryParams[QueryParameterNames_1.QueryParameterNames.Language] = language; - } - } - if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.Format) === -1) { - queryParams[QueryParameterNames_1.QueryParameterNames.Format] = config.parameters.getProperty(Exports_2.OutputFormatPropertyName, Exports_3.OutputFormat[Exports_3.OutputFormat.Simple]).toLowerCase(); - } - if (config.autoDetectSourceLanguages !== undefined) { - queryParams[QueryParameterNames_1.QueryParameterNames.EnableLanguageId] = "true"; - } - _this.setCommonUrlParams(config, queryParams, endpoint); - if (!endpoint) { - switch (config.recognitionMode) { - case Exports_4.RecognitionMode.Conversation: - if (config.parameters.getProperty(Exports_2.ForceDictationPropertyName, "false") === "true") { - endpoint = host + _this.dictationRelativeUri; - } - else { - endpoint = host + _this.conversationRelativeUri; - } - break; - case Exports_4.RecognitionMode.Dictation: - endpoint = host + _this.dictationRelativeUri; - break; - default: - endpoint = host + _this.interactiveRelativeUri; // default is interactive - break; - } - } - var headers = {}; - if (authInfo.token !== undefined && authInfo.token !== "") { - headers[authInfo.headerName] = authInfo.token; - } - headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId; - config.parameters.setProperty(Exports_3.PropertyId.SpeechServiceConnection_Url, endpoint); - var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; - return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_4.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); - }; - return _this; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AvatarConfig = void 0; +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_1 = __webpack_require__(85); +/** + * Defines the talking avatar configuration. + * @class AvatarConfig + * Added in version 1.33.0 + * + * @experimental This feature is experimental and might change or have limited support. + */ +class AvatarConfig { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {string} character - The avatar character. + * @param {string} style - The avatar style. + * @param {AvatarVideoFormat} videoFormat - The talking avatar output video format. + */ + constructor(character, style, videoFormat) { + this.privCustomized = false; + this.privUseBuiltInVoice = false; + Contracts_js_1.Contracts.throwIfNullOrWhitespace(character, "character"); + this.character = character; + this.style = style; + if (videoFormat === undefined) { + videoFormat = new Exports_js_1.AvatarVideoFormat(); + } + this.videoFormat = videoFormat; } - return SpeechConnectionFactory; -}(ConnectionFactoryBase_1.ConnectionFactoryBase)); -exports.SpeechConnectionFactory = SpeechConnectionFactory; + /** + * Indicates if the talking avatar is customized. + */ + get customized() { + return this.privCustomized; + } + /** + * Sets if the talking avatar is customized. + */ + set customized(value) { + this.privCustomized = value; + } + /** + * Indicates whether to use built-in voice for custom avatar. + */ + get useBuiltInVoice() { + return this.privUseBuiltInVoice; + } + /** + * Sets whether to use built-in voice for custom avatar. + */ + set useBuiltInVoice(value) { + this.privUseBuiltInVoice = value; + } + /** + * Gets the photo avatar base model name. + */ + get photoAvatarBaseModel() { + return this.privPhotoAvatarBaseModel; + } + /** + * Sets the photo avatar base model name. + */ + set photoAvatarBaseModel(value) { + this.privPhotoAvatarBaseModel = value; + } + /** + * Gets the background color. + */ + get backgroundColor() { + return this.privBackgroundColor; + } + /** + * Sets the background color. + */ + set backgroundColor(value) { + this.privBackgroundColor = value; + } + /** + * Gets the background image. + */ + get backgroundImage() { + return this.privBackgroundImage; + } + /** + * Sets the background image. + * @param {URL} value - The background image. + */ + set backgroundImage(value) { + this.privBackgroundImage = value; + } + /** + * Gets the remote ICE servers. + * @remarks This method is designed to be used internally in the SDK. + * @returns {RTCIceServer[]} The remote ICE servers. + */ + get remoteIceServers() { + return this.privRemoteIceServers; + } + /** + * Sets the remote ICE servers. + * @remarks Normally, the ICE servers are gathered from the PeerConnection, + * set this property to override the ICE servers. E.g., the ICE servers are + * different in client and server side. + * @param {RTCIceServer[]} value - The remote ICE servers. + */ + set remoteIceServers(value) { + this.privRemoteIceServers = value; + } + /** + * Gets the scene configuration for avatar positioning and orientation. + * @returns {AvatarSceneConfig} The scene configuration. + */ + get scene() { + return this.privScene; + } + /** + * Sets the scene configuration for avatar positioning and orientation. + * @param {AvatarSceneConfig} value - The scene configuration. + */ + set scene(value) { + this.privScene = value; + } +} +exports.AvatarConfig = AvatarConfig; /***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { +/* 177 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranscriberConnectionFactory = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -var Exports_3 = __webpack_require__(53); -var HeaderNames_1 = __webpack_require__(55); -var QueryParameterNames_1 = __webpack_require__(124); -var TranscriberConnectionFactory = /** @class */ (function (_super) { - __extends(TranscriberConnectionFactory, _super); - function TranscriberConnectionFactory() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.multiaudioRelativeUri = "/speech/recognition/multiaudio"; - _this.create = function (config, authInfo, connectionId) { - var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); - var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, "centralus"); - var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region); - var hostDefault = "wss://transcribe." + region + ".cts.speech" + hostSuffix + _this.multiaudioRelativeUri; - var host = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, hostDefault); - var queryParams = {}; - var endpointId = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId, undefined); - var language = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage, undefined); - if (endpointId) { - if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.CustomSpeechDeploymentId) === -1) { - queryParams[QueryParameterNames_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId; - } - } - else if (language) { - if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.Language) === -1) { - queryParams[QueryParameterNames_1.QueryParameterNames.Language] = language; - } - } - _this.setCommonUrlParams(config, queryParams, endpoint); - if (!endpoint) { - endpoint = host; - } - var headers = {}; - if (authInfo.token !== undefined && authInfo.token !== "") { - headers[authInfo.headerName] = authInfo.token; - } - headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId; - config.parameters.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Url, endpoint); - var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; - return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_3.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); - }; - return _this; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AvatarEventArgs = exports.AvatarEventTypes = void 0; +var AvatarEventTypes; +(function (AvatarEventTypes) { + AvatarEventTypes["SwitchedToSpeaking"] = "SwitchedToSpeaking"; + AvatarEventTypes["SwitchedToIdle"] = "SwitchedToIdle"; + AvatarEventTypes["SessionClosed"] = "SessionClosed"; +})(AvatarEventTypes = exports.AvatarEventTypes || (exports.AvatarEventTypes = {})); +/** + * Defines content for talking avatar events. + * @class AvatarEventArgs + * Added in version 1.33.0 + * + * @experimental This feature is experimental and might change or have limited support. + */ +class AvatarEventArgs { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {number} audioOffset - The audio offset. + * @param {string} description - The description of the event. + */ + constructor(audioOffset, description) { + this.privOffset = audioOffset; + this.privDescription = description; } - return TranscriberConnectionFactory; -}(ConnectionFactoryBase_1.ConnectionFactoryBase)); -exports.TranscriberConnectionFactory = TranscriberConnectionFactory; + /** + * The type of the event. + * @public + * @returns {AvatarEventTypes} The type of the event. + */ + get type() { + return this.privType; + } + /** + * The time offset associated with this event. + * @public + * @returns {number} The time offset associated with this event. + */ + get offset() { + return this.privOffset; + } + /** + * The description of the event. + * @public + * @returns {string} The description of the event. + */ + get description() { + return this.privDescription; + } +} +exports.AvatarEventArgs = AvatarEventArgs; /***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { +/* 178 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranslationConnectionFactory = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -var Exports_3 = __webpack_require__(53); -var HeaderNames_1 = __webpack_require__(55); -var QueryParameterNames_1 = __webpack_require__(124); -var TranslationConnectionFactory = /** @class */ (function (_super) { - __extends(TranslationConnectionFactory, _super); - function TranslationConnectionFactory() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.create = function (config, authInfo, connectionId) { - var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); - if (!endpoint) { - var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, undefined); - var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region); - var host = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".s2s.speech" + hostSuffix); - endpoint = host + "/speech/translation/cognitiveservices/v1"; - } - var queryParams = { - from: config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage), - to: config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationToLanguages), - }; - _this.setCommonUrlParams(config, queryParams, endpoint); - _this.setUrlParameter(Exports_2.PropertyId.SpeechServiceResponse_TranslationRequestStablePartialResult, QueryParameterNames_1.QueryParameterNames.StableTranslation, config, queryParams, endpoint); - var voiceName = "voice"; - var featureName = "features"; - if (config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) { - queryParams[voiceName] = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationVoice); - queryParams[featureName] = "texttospeech"; - } - var headers = {}; - if (authInfo.token !== undefined && authInfo.token !== "") { - headers[authInfo.headerName] = authInfo.token; - } - headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId; - config.parameters.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Url, endpoint); - var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; - return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_3.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); - }; - return _this; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AvatarSceneConfig = void 0; +/** + * Defines the avatar scene configuration for controlling avatar positioning and orientation. + * @class AvatarSceneConfig + * Added in version 1.44.0 + * + * @experimental This feature is experimental and might change or have limited support. + */ +class AvatarSceneConfig { + /** + * Creates and initializes an instance of this class with default values. + * @constructor + * @param {number} zoom - The zoom level (0-1, default 1.0). + * @param {number} positionX - The horizontal position offset (-1 to 1, default 0.0). + * @param {number} positionY - The vertical position offset (-1 to 1, default 0.0). + * @param {number} rotationX - The rotation around the X axis in radians (default 0.0). + * @param {number} rotationY - The rotation around the Y axis in radians (default 0.0). + * @param {number} rotationZ - The rotation around the Z axis in radians (default 0.0). + * @param {number} amplitude - The amplitude of the avatar's movements (0 to 1, default 1.0). + */ + constructor(zoom = 1.0, positionX = 0.0, positionY = 0.0, rotationX = 0.0, rotationY = 0.0, rotationZ = 0.0, amplitude = 1.0) { + this.zoom = zoom; + this.positionX = positionX; + this.positionY = positionY; + this.rotationX = rotationX; + this.rotationY = rotationY; + this.rotationZ = rotationZ; + this.amplitude = amplitude; } - return TranslationConnectionFactory; -}(ConnectionFactoryBase_1.ConnectionFactoryBase)); -exports.TranslationConnectionFactory = TranslationConnectionFactory; +} +exports.AvatarSceneConfig = AvatarSceneConfig; /***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { +/* 179 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechSynthesisConnectionFactory = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -var Exports_3 = __webpack_require__(53); -var HeaderNames_1 = __webpack_require__(55); -var QueryParameterNames_1 = __webpack_require__(124); -var SpeechSynthesisConnectionFactory = /** @class */ (function () { - function SpeechSynthesisConnectionFactory() { - var _this = this; - this.synthesisUri = "/cognitiveservices/websocket/v1"; - this.create = function (config, authInfo, connectionId) { - var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); - var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, undefined); - var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region); - var endpointId = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId, undefined); - var hostPrefix = (endpointId === undefined) ? "tts" : "voice"; - var host = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + "." + hostPrefix + ".speech" + hostSuffix); - var queryParams = {}; - if (!endpoint) { - endpoint = host + _this.synthesisUri; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AvatarSynthesizer = void 0; +const SpeechSynthesisConnectionFactory_js_1 = __webpack_require__(180); +const Exports_js_1 = __webpack_require__(2); +const Exports_js_2 = __webpack_require__(4); +const AudioOutputFormat_js_1 = __webpack_require__(91); +const Exports_js_3 = __webpack_require__(85); +const Contracts_js_1 = __webpack_require__(70); +const Synthesizer_js_1 = __webpack_require__(155); +/** + * Defines the avatar synthesizer. + * @class AvatarSynthesizer + * Added in version 1.33.0 + * + * @experimental This feature is experimental and might change or have limited support. + */ +class AvatarSynthesizer extends Exports_js_3.Synthesizer { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {SpeechConfig} speechConfig - The speech config. + * @param {AvatarConfig} avatarConfig - The talking avatar config. + */ + constructor(speechConfig, avatarConfig) { + super(speechConfig); + Contracts_js_1.Contracts.throwIfNullOrUndefined(avatarConfig, "avatarConfig"); + this.privConnectionFactory = new SpeechSynthesisConnectionFactory_js_1.SpeechSynthesisConnectionFactory(); + this.privAvatarConfig = avatarConfig; + this.implCommonSynthesizeSetup(); + } + implCommonSynthesizeSetup() { + super.implCommonSynthesizeSetup(); + // The service checks the audio format setting while it ignores it in avatar synthesis. + this.privAdapter.audioOutputFormat = AudioOutputFormat_js_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(Exports_js_3.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm); + } + /** + * Starts the talking avatar session and establishes the WebRTC connection. + * @member AvatarSynthesizer.prototype.startAvatarAsync + * @function + * @public + * @param {AvatarWebRTCConnectionInfo} peerConnection - The peer connection. + * @returns {Promise} The promise of the connection result. + */ + async startAvatarAsync(peerConnection) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(peerConnection, "peerConnection"); + this.privIceServers = peerConnection.getConfiguration().iceServers; + Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privIceServers, "Ice servers must be set."); + const iceGatheringDone = new Exports_js_2.Deferred(); + // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/icegatheringstatechange_event + peerConnection.onicegatheringstatechange = () => { + Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice gathering state: " + peerConnection.iceGatheringState, Exports_js_2.EventType.Debug)); + if (peerConnection.iceGatheringState === "complete") { + Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice gathering complete.", Exports_js_2.EventType.Info)); + iceGatheringDone.resolve(); } - var headers = {}; - if (authInfo.token !== undefined && authInfo.token !== "") { - headers[authInfo.headerName] = authInfo.token; + }; + peerConnection.onicecandidate = (event) => { + if (event.candidate) { + Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice candidate: " + event.candidate.candidate, Exports_js_2.EventType.Debug)); } - headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId; - if (endpointId !== undefined) { - headers[QueryParameterNames_1.QueryParameterNames.CustomVoiceDeploymentId] = endpointId; + else { + Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice candidate: complete", Exports_js_2.EventType.Debug)); + iceGatheringDone.resolve(); } - config.parameters.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Url, endpoint); - var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; - return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_3.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromParameters(config.parameters), enableCompression, connectionId); }; + // Set a timeout for ice gathering, currently 2 seconds. + setTimeout(() => { + if (peerConnection.iceGatheringState !== "complete") { + Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice gathering timeout.", Exports_js_2.EventType.Warning)); + iceGatheringDone.resolve(); + } + }, 2000); + const sdp = await peerConnection.createOffer(); + await peerConnection.setLocalDescription(sdp); + await iceGatheringDone.promise; + Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: got local SDP.", Exports_js_2.EventType.Info)); + this.privProperties.setProperty(Exports_js_3.PropertyId.TalkingAvatarService_WebRTC_SDP, JSON.stringify(peerConnection.localDescription)); + const result = await this.speak("", false); + if (result.reason !== Exports_js_3.ResultReason.SynthesizingAudioCompleted) { + return new Exports_js_3.SynthesisResult(result.resultId, result.reason, result.errorDetails, result.properties); + } + const sdpAnswerString = atob(result.properties.getProperty(Exports_js_3.PropertyId.TalkingAvatarService_WebRTC_SDP)); + const sdpAnswer = new RTCSessionDescription(JSON.parse(sdpAnswerString)); + await peerConnection.setRemoteDescription(sdpAnswer); + return new Exports_js_3.SynthesisResult(result.resultId, result.reason, undefined, result.properties); + } + /** + * Speaks plain text asynchronously. The rendered audio and video will be sent via the WebRTC connection. + * @member AvatarSynthesizer.prototype.speakTextAsync + * @function + * @public + * @param {string} text - The plain text to speak. + * @returns {Promise} The promise of the synthesis result. + */ + async speakTextAsync(text) { + const r = await this.speak(text, false); + return new Exports_js_3.SynthesisResult(r.resultId, r.reason, r.errorDetails, r.properties); } - return SpeechSynthesisConnectionFactory; -}()); -exports.SpeechSynthesisConnectionFactory = SpeechSynthesisConnectionFactory; - - - -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EnumTranslation = void 0; -var Exports_1 = __webpack_require__(61); -var Exports_2 = __webpack_require__(53); -var EnumTranslation = /** @class */ (function () { - function EnumTranslation() { + /** + * Speaks SSML asynchronously. The rendered audio and video will be sent via the WebRTC connection. + * @member AvatarSynthesizer.prototype.speakSsmlAsync + * @function + * @public + * @param {string} ssml - The SSML text to speak. + * @returns {Promise} The promise of the synthesis result. + */ + async speakSsmlAsync(ssml) { + const r = await this.speak(ssml, true); + return new Exports_js_3.SynthesisResult(r.resultId, r.reason, r.errorDetails, r.properties); } - EnumTranslation.implTranslateRecognitionResult = function (recognitionStatus) { - var reason = Exports_1.ResultReason.Canceled; - switch (recognitionStatus) { - case Exports_2.RecognitionStatus.Success: - reason = Exports_1.ResultReason.RecognizedSpeech; - break; - case Exports_2.RecognitionStatus.NoMatch: - case Exports_2.RecognitionStatus.InitialSilenceTimeout: - case Exports_2.RecognitionStatus.BabbleTimeout: - case Exports_2.RecognitionStatus.EndOfDictation: - reason = Exports_1.ResultReason.NoMatch; - break; - case Exports_2.RecognitionStatus.Error: - case Exports_2.RecognitionStatus.BadRequest: - case Exports_2.RecognitionStatus.Forbidden: - default: - reason = Exports_1.ResultReason.Canceled; - break; - } - return reason; - }; - EnumTranslation.implTranslateCancelResult = function (recognitionStatus) { - var reason = Exports_1.CancellationReason.EndOfStream; - switch (recognitionStatus) { - case Exports_2.RecognitionStatus.Success: - case Exports_2.RecognitionStatus.EndOfDictation: - case Exports_2.RecognitionStatus.NoMatch: - reason = Exports_1.CancellationReason.EndOfStream; - break; - case Exports_2.RecognitionStatus.InitialSilenceTimeout: - case Exports_2.RecognitionStatus.BabbleTimeout: - case Exports_2.RecognitionStatus.Error: - case Exports_2.RecognitionStatus.BadRequest: - case Exports_2.RecognitionStatus.Forbidden: - default: - reason = Exports_1.CancellationReason.Error; - break; - } - return reason; - }; - EnumTranslation.implTranslateCancelErrorCode = function (recognitionStatus) { - var reason = Exports_1.CancellationErrorCode.NoError; - switch (recognitionStatus) { - case Exports_2.RecognitionStatus.Error: - reason = Exports_1.CancellationErrorCode.ServiceError; - break; - case Exports_2.RecognitionStatus.TooManyRequests: - reason = Exports_1.CancellationErrorCode.TooManyRequests; - break; - case Exports_2.RecognitionStatus.BadRequest: - reason = Exports_1.CancellationErrorCode.BadRequestParameters; - break; - case Exports_2.RecognitionStatus.Forbidden: - reason = Exports_1.CancellationErrorCode.Forbidden; - break; - default: - reason = Exports_1.CancellationErrorCode.NoError; - break; - } - return reason; - }; - EnumTranslation.implTranslateErrorDetails = function (cancellationErrorCode) { - var errorDetails = "The speech service encountered an internal error and could not continue."; - switch (cancellationErrorCode) { - case Exports_1.CancellationErrorCode.Forbidden: - errorDetails = "The recognizer is using a free subscription that ran out of quota."; - break; - case Exports_1.CancellationErrorCode.BadRequestParameters: - errorDetails = "Invalid parameter or unsupported audio format in the request."; - break; - case Exports_1.CancellationErrorCode.TooManyRequests: - errorDetails = "The number of parallel requests exceeded the number of allowed concurrent transcriptions."; - break; - default: - break; - } - return errorDetails; - }; - return EnumTranslation; -}()); -exports.EnumTranslation = EnumTranslation; - - - -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RecognitionStatus = exports.SynthesisStatus = void 0; -/** - * @class SynthesisStatus - * @private - */ -var SynthesisStatus; -(function (SynthesisStatus) { /** - * The response contains valid audio data. - * @member SynthesisStatus.Success + * Speaks text asynchronously. The avatar will switch to idle state. + * @member AvatarSynthesizer.prototype.stopSpeakingAsync + * @function + * @public + * @returns {Promise} The promise of the void result. */ - SynthesisStatus[SynthesisStatus["Success"] = 0] = "Success"; + async stopSpeakingAsync() { + while (this.synthesisRequestQueue.length() > 0) { + const request = await this.synthesisRequestQueue.dequeue(); + request.err("Synthesis is canceled by user."); + } + return this.privAdapter.stopSpeaking(); + } /** - * Indicates the end of audio data. No valid audio data is included in the message. - * @member SynthesisStatus.SynthesisEnd + * Updates the avatar scene configuration at runtime. + * This allows changing the avatar's zoom, position, amplitude, and rotation while the session is active. + * @member AvatarSynthesizer.prototype.updateSceneAsync + * @function + * @public + * @param {AvatarSceneConfig} sceneConfig - The new scene configuration to apply. + * @returns {Promise} The promise of the void result. + */ + async updateSceneAsync(sceneConfig) { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + Contracts_js_1.Contracts.throwIfNullOrUndefined(sceneConfig, "sceneConfig"); + const sceneMessage = { + avatarScene: { + amplitude: sceneConfig.amplitude, + positionX: sceneConfig.positionX, + positionY: sceneConfig.positionY, + rotationX: sceneConfig.rotationX, + rotationY: sceneConfig.rotationY, + rotationZ: sceneConfig.rotationZ, + zoom: sceneConfig.zoom, + } + }; + return this.privAdapter.sendNetworkMessage("synthesis.control", JSON.stringify(sceneMessage)); + } + /** + * Stops the talking avatar session and closes the WebRTC connection. + * For now, this is the same as close(). + * You need to create a new AvatarSynthesizer instance to start a new session. + * @member AvatarSynthesizer.prototype.stopAvatarAsync + * @function + * @public + * @returns {Promise} The promise of the void result. */ - SynthesisStatus[SynthesisStatus["SynthesisEnd"] = 1] = "SynthesisEnd"; + async stopAvatarAsync() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed); + return this.dispose(true); + } /** - * Indicates an error occurred during synthesis data processing. - * @member SynthesisStatus.Error + * Dispose of associated resources. + * @member AvatarSynthesizer.prototype.close + * @function + * @public */ - SynthesisStatus[SynthesisStatus["Error"] = 2] = "Error"; -})(SynthesisStatus = exports.SynthesisStatus || (exports.SynthesisStatus = {})); -var RecognitionStatus; -(function (RecognitionStatus) { - RecognitionStatus[RecognitionStatus["Success"] = 0] = "Success"; - RecognitionStatus[RecognitionStatus["NoMatch"] = 1] = "NoMatch"; - RecognitionStatus[RecognitionStatus["InitialSilenceTimeout"] = 2] = "InitialSilenceTimeout"; - RecognitionStatus[RecognitionStatus["BabbleTimeout"] = 3] = "BabbleTimeout"; - RecognitionStatus[RecognitionStatus["Error"] = 4] = "Error"; - RecognitionStatus[RecognitionStatus["EndOfDictation"] = 5] = "EndOfDictation"; - RecognitionStatus[RecognitionStatus["TooManyRequests"] = 6] = "TooManyRequests"; - RecognitionStatus[RecognitionStatus["BadRequest"] = 7] = "BadRequest"; - RecognitionStatus[RecognitionStatus["Forbidden"] = 8] = "Forbidden"; -})(RecognitionStatus = exports.RecognitionStatus || (exports.RecognitionStatus = {})); + async close() { + if (this.privDisposed) { + return; + } + return this.dispose(true); + } + /** + * Gets the ICE servers. Internal use only. + */ + get iceServers() { + return this.privIceServers; + } + // Creates the synthesis adapter + createSynthesisAdapter(authentication, connectionFactory, synthesizerConfig) { + return new Exports_js_1.AvatarSynthesisAdapter(authentication, connectionFactory, synthesizerConfig, this, this.privAvatarConfig); + } + createRestSynthesisAdapter(_authentication, _synthesizerConfig) { + return undefined; + } + createSynthesizerConfig(speechConfig) { + const config = super.createSynthesizerConfig(speechConfig); + config.avatarEnabled = true; + return config; + } + async speak(text, isSSML) { + const requestId = (0, Exports_js_2.createNoDashGuid)(); + const deferredResult = new Exports_js_2.Deferred(); + this.synthesisRequestQueue.enqueue(new Synthesizer_js_1.SynthesisRequest(requestId, text, isSSML, (e) => { + deferredResult.resolve(e); + this.privSynthesizing = false; + void this.adapterSpeak(); + }, (e) => { + deferredResult.reject(e); + this.privSynthesizing = false; + })); + void this.adapterSpeak(); + return deferredResult.promise; + } +} +exports.AvatarSynthesizer = AvatarSynthesizer; /***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { +/* 180 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranslationSynthesisEnd = void 0; -var Exports_1 = __webpack_require__(53); -var TranslationSynthesisEnd = /** @class */ (function () { - function TranslationSynthesisEnd(json) { - this.privSynthesisEnd = JSON.parse(json); - this.privSynthesisEnd.SynthesisStatus = Exports_1.SynthesisStatus[this.privSynthesisEnd.SynthesisStatus]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisConnectionFactory = void 0; +const Exports_js_1 = __webpack_require__(66); +const Exports_js_2 = __webpack_require__(85); +const ConnectionFactoryBase_js_1 = __webpack_require__(135); +const Exports_js_3 = __webpack_require__(2); +const HeaderNames_js_1 = __webpack_require__(59); +const QueryParameterNames_js_1 = __webpack_require__(136); +class SpeechSynthesisConnectionFactory { + constructor() { + this.synthesisUri = "/tts/cognitiveservices/websocket/v1"; + } + async create(config, authInfo, connectionId) { + let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); + const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, undefined); + const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region); + const endpointId = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, undefined); + const hostPrefix = (endpointId === undefined) ? "tts" : "voice"; + const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + "." + hostPrefix + ".speech" + hostSuffix); + const queryParams = {}; + const headers = {}; + if (authInfo.token !== undefined && authInfo.token !== "") { + headers[authInfo.headerName] = authInfo.token; + } + headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId; + if (endpointId !== undefined && endpointId !== "") { + if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.CustomVoiceDeploymentId) === -1) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.CustomVoiceDeploymentId] = endpointId; + } + } + if (config.avatarEnabled) { + if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.EnableAvatar) === -1) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.EnableAvatar] = "true"; + } + } + if (!!endpoint) { + const endpointUrl = new URL(endpoint); + const pathName = endpointUrl.pathname; + if (pathName === "" || pathName === "/" || pathName.toLowerCase() === this.synthesisUri) { + // We need to generate the path, and we need to check for a redirect. + endpointUrl.pathname = this.synthesisUri; + endpoint = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString()); + } + } + if (!endpoint) { + endpoint = host + this.synthesisUri; + } + config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, endpoint); + const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; + return new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromParameters(config.parameters), enableCompression, connectionId); } - TranslationSynthesisEnd.fromJSON = function (json) { - return new TranslationSynthesisEnd(json); - }; - Object.defineProperty(TranslationSynthesisEnd.prototype, "SynthesisStatus", { - get: function () { - return this.privSynthesisEnd.SynthesisStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationSynthesisEnd.prototype, "FailureReason", { - get: function () { - return this.privSynthesisEnd.FailureReason; - }, - enumerable: false, - configurable: true - }); - return TranslationSynthesisEnd; -}()); -exports.TranslationSynthesisEnd = TranslationSynthesisEnd; +} +exports.SpeechSynthesisConnectionFactory = SpeechSynthesisConnectionFactory; /***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { +/* 181 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranslationHypothesis = void 0; -var TranslationStatus_1 = __webpack_require__(45); -var TranslationHypothesis = /** @class */ (function () { - function TranslationHypothesis(json) { - this.privTranslationHypothesis = JSON.parse(json); - this.privTranslationHypothesis.Translation.TranslationStatus = TranslationStatus_1.TranslationStatus[this.privTranslationHypothesis.Translation.TranslationStatus]; - } - TranslationHypothesis.fromJSON = function (json) { - return new TranslationHypothesis(json); - }; - Object.defineProperty(TranslationHypothesis.prototype, "Duration", { - get: function () { - return this.privTranslationHypothesis.Duration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationHypothesis.prototype, "Offset", { - get: function () { - return this.privTranslationHypothesis.Offset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationHypothesis.prototype, "Text", { - get: function () { - return this.privTranslationHypothesis.Text; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationHypothesis.prototype, "Translation", { - get: function () { - return this.privTranslationHypothesis.Translation; - }, - enumerable: false, - configurable: true - }); - return TranslationHypothesis; -}()); -exports.TranslationHypothesis = TranslationHypothesis; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AvatarVideoFormat = exports.Coordinate = void 0; +/* eslint-disable max-classes-per-file */ +/** + * Defines a coordinate in 2D space. + * @class Coordinate + * Added in version 1.33.0 + */ +class Coordinate { + constructor(x, y) { + this.x = x; + this.y = y; + } +} +exports.Coordinate = Coordinate; +/** + * Defines the avatar output video format. + * @class AvatarVideoFormat + * Added in version 1.33.0 + * + * @experimental This feature is experimental and might change in the future. + */ +class AvatarVideoFormat { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {string} codec - The video codec. + * @param {number} bitrate - The video bitrate. + * @param {number} width - The video width. + * @param {number} height - The video height. + */ + constructor(codec = "H264", bitrate = 2000000, width = 1920, height = 1080) { + this.codec = codec; + this.bitrate = bitrate; + this.width = width; + this.height = height; + } + /** + * Sets the video crop range. + */ + setCropRange(topLeft, bottomRight) { + this.cropRange = { + bottomRight, + topLeft, + }; + } +} +exports.AvatarVideoFormat = AvatarVideoFormat; /***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { +/* 182 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranslationPhrase = void 0; -var Contracts_1 = __webpack_require__(63); -var Exports_1 = __webpack_require__(53); -var TranslationStatus_1 = __webpack_require__(45); -var TranslationPhrase = /** @class */ (function () { - function TranslationPhrase(phrase) { - this.privTranslationPhrase = phrase; - this.privTranslationPhrase.RecognitionStatus = Exports_1.RecognitionStatus[this.privTranslationPhrase.RecognitionStatus]; - if (this.privTranslationPhrase.Translation !== undefined) { - this.privTranslationPhrase.Translation.TranslationStatus = TranslationStatus_1.TranslationStatus[this.privTranslationPhrase.Translation.TranslationStatus]; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AvatarWebRTCConnectionResult = void 0; +const Exports_js_1 = __webpack_require__(85); +/** + * Defines the avatar WebRTC connection result. + * @class AvatarWebRTCConnectionResult + * Added in version 1.33.0 + * + * @experimental This feature is experimental and might change in the future. + */ +class AvatarWebRTCConnectionResult extends Exports_js_1.SynthesisResult { + /** + * Creates and initializes an instance of this class. + * @constructor + * @param {RTCSessionDescriptionInit} SDPAnswer - The SDP answer of WebRTC connection. + * @param {string} resultId - The result id. + * @param {ResultReason} reason - The reason. + * @param {string} errorDetails - Error details, if provided. + * @param {PropertyCollection} properties - Additional properties, if provided. + */ + constructor(SDPAnswer, resultId, reason, errorDetails, properties) { + super(resultId, reason, errorDetails, properties); + this.privSDPAnswer = SDPAnswer; } - TranslationPhrase.fromJSON = function (json) { - return new TranslationPhrase(JSON.parse(json)); - }; - TranslationPhrase.fromTranslationResponse = function (translationResponse) { - Contracts_1.Contracts.throwIfNullOrUndefined(translationResponse, "translationResponse"); - var phrase = translationResponse.SpeechPhrase; - translationResponse.SpeechPhrase = undefined; - phrase.Translation = translationResponse; - phrase.Text = phrase.DisplayText; - return new TranslationPhrase(phrase); - }; - Object.defineProperty(TranslationPhrase.prototype, "RecognitionStatus", { - get: function () { - return this.privTranslationPhrase.RecognitionStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationPhrase.prototype, "Offset", { - get: function () { - return this.privTranslationPhrase.Offset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationPhrase.prototype, "Duration", { - get: function () { - return this.privTranslationPhrase.Duration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationPhrase.prototype, "Text", { - get: function () { - return this.privTranslationPhrase.Text; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranslationPhrase.prototype, "Translation", { - get: function () { - return this.privTranslationPhrase.Translation; - }, - enumerable: false, - configurable: true - }); - return TranslationPhrase; -}()); -exports.TranslationPhrase = TranslationPhrase; + /** + * Specifies SDP (Session Description Protocol) answer of WebRTC connection. + * @member AvatarWebRTCConnectionResult.prototype.SDPAnswer + * @function + * @public + * @returns {RTCSessionDescriptionInit} Specifies the SDP answer of WebRTC connection. + */ + get SDPAnswer() { + return this.privSDPAnswer; + } +} +exports.AvatarWebRTCConnectionResult = AvatarWebRTCConnectionResult; /***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { +/* 183 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Diagnostics = void 0; +const Exports_js_1 = __webpack_require__(66); +const Exports_js_2 = __webpack_require__(4); +/** + * Defines diagnostics API for managing console output + * Added in version 1.21.0 + */ +class Diagnostics { + static SetLoggingLevel(logLevel) { + this.privListener = new Exports_js_1.ConsoleLoggingListener(logLevel); + Exports_js_2.Events.instance.attachConsoleListener(this.privListener); } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranslationServiceRecognizer = void 0; -var Exports_1 = __webpack_require__(4); -var Exports_2 = __webpack_require__(61); -var Exports_3 = __webpack_require__(53); -// tslint:disable-next-line:max-classes-per-file -var TranslationServiceRecognizer = /** @class */ (function (_super) { - __extends(TranslationServiceRecognizer, _super); - function TranslationServiceRecognizer(authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer) { - var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer) || this; - _this.privTranslationRecognizer = translationRecognizer; - _this.connectionEvents.attach(function (connectionEvent) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(connectionEvent.name === "ConnectionEstablishedEvent")) return [3 /*break*/, 1]; - this.privTranslationRecognizer.onConnection(); - return [3 /*break*/, 3]; - case 1: - if (!(connectionEvent.name === "ConnectionClosedEvent")) return [3 /*break*/, 3]; - return [4 /*yield*/, this.privTranslationRecognizer.onDisconnection()]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); }); - return _this; - } - TranslationServiceRecognizer.prototype.processTypeSpecificMessages = function (connectionMessage) { - return __awaiter(this, void 0, void 0, function () { - var resultProps, processed, handleTranslationPhrase, _a, result, phrase, synthEnd, result_1, retEvent, canceledResult; - var _this = this; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - resultProps = new Exports_2.PropertyCollection(); - processed = false; - handleTranslationPhrase = function (translatedPhrase) { return __awaiter(_this, void 0, void 0, function () { - var result, reason, result, cancelReason, cancellationErrorCode, ev; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + translatedPhrase.Offset + translatedPhrase.Duration); - if (!(translatedPhrase.RecognitionStatus === Exports_3.RecognitionStatus.Success)) return [3 /*break*/, 1]; - result = this.fireEventForResult(translatedPhrase, resultProps); - if (!!this.privTranslationRecognizer.recognized) { - try { - this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, result); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - // report result to promise. - if (!!this.privSuccessCallback) { - try { - this.privSuccessCallback(result.result); - } - catch (e) { - if (!!this.privErrorCallback) { - this.privErrorCallback(e); - } - } - // Only invoke the call back once. - // and if it's successful don't invoke the - // error after that. - this.privSuccessCallback = undefined; - this.privErrorCallback = undefined; - } - return [3 /*break*/, 5]; - case 1: - reason = Exports_3.EnumTranslation.implTranslateRecognitionResult(translatedPhrase.RecognitionStatus); - result = new Exports_2.TranslationRecognitionResult(undefined, this.privRequestSession.requestId, reason, translatedPhrase.Text, translatedPhrase.Duration, this.privRequestSession.currentTurnAudioOffset + translatedPhrase.Offset, undefined, connectionMessage.textBody, resultProps); - if (!(reason === Exports_2.ResultReason.Canceled)) return [3 /*break*/, 3]; - cancelReason = Exports_3.EnumTranslation.implTranslateCancelResult(translatedPhrase.RecognitionStatus); - cancellationErrorCode = Exports_3.EnumTranslation.implTranslateCancelErrorCode(translatedPhrase.RecognitionStatus); - return [4 /*yield*/, this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_3.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode))]; - case 2: - _a.sent(); - return [3 /*break*/, 4]; - case 3: - if (!(this.privRequestSession.isSpeechEnded && reason === Exports_2.ResultReason.NoMatch && translatedPhrase.RecognitionStatus !== Exports_3.RecognitionStatus.InitialSilenceTimeout)) { - ev = new Exports_2.TranslationRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId); - if (!!this.privTranslationRecognizer.recognized) { - try { - this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, ev); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - } - // report result to promise. - if (!!this.privSuccessCallback) { - try { - this.privSuccessCallback(result); - } - catch (e) { - if (!!this.privErrorCallback) { - this.privErrorCallback(e); - } - } - // Only invoke the call back once. - // and if it's successful don't invoke the - // error after that. - this.privSuccessCallback = undefined; - this.privErrorCallback = undefined; - } - _a.label = 4; - case 4: - processed = true; - _a.label = 5; - case 5: return [2 /*return*/]; - } - }); - }); }; - if (connectionMessage.messageType === Exports_1.MessageType.Text) { - resultProps.setProperty(Exports_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody); - } - _a = connectionMessage.path.toLowerCase(); - switch (_a) { - case "translation.hypothesis": return [3 /*break*/, 1]; - case "translation.response": return [3 /*break*/, 2]; - case "translation.phrase": return [3 /*break*/, 5]; - case "translation.synthesis": return [3 /*break*/, 7]; - case "translation.synthesis.end": return [3 /*break*/, 8]; - } - return [3 /*break*/, 9]; - case 1: - result = this.fireEventForResult(Exports_3.TranslationHypothesis.fromJSON(connectionMessage.textBody), resultProps); - this.privRequestSession.onHypothesis(this.privRequestSession.currentTurnAudioOffset + result.offset); - if (!!this.privTranslationRecognizer.recognizing) { - try { - this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer, result); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - processed = true; - return [3 /*break*/, 10]; - case 2: - phrase = JSON.parse(connectionMessage.textBody); - if (!!!phrase.SpeechPhrase) return [3 /*break*/, 4]; - return [4 /*yield*/, handleTranslationPhrase(Exports_3.TranslationPhrase.fromTranslationResponse(phrase))]; - case 3: - _b.sent(); - _b.label = 4; - case 4: return [3 /*break*/, 10]; - case 5: return [4 /*yield*/, handleTranslationPhrase(Exports_3.TranslationPhrase.fromJSON(connectionMessage.textBody))]; - case 6: - _b.sent(); - return [3 /*break*/, 10]; - case 7: - this.sendSynthesisAudio(connectionMessage.binaryBody, this.privRequestSession.sessionId); - processed = true; - return [3 /*break*/, 10]; - case 8: - synthEnd = Exports_3.TranslationSynthesisEnd.fromJSON(connectionMessage.textBody); - switch (synthEnd.SynthesisStatus) { - case Exports_3.SynthesisStatus.Error: - if (!!this.privTranslationRecognizer.synthesizing) { - result_1 = new Exports_2.TranslationSynthesisResult(Exports_2.ResultReason.Canceled, undefined); - retEvent = new Exports_2.TranslationSynthesisEventArgs(result_1, this.privRequestSession.sessionId); - try { - this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - if (!!this.privTranslationRecognizer.canceled) { - canceledResult = new Exports_2.TranslationRecognitionCanceledEventArgs(this.privRequestSession.sessionId, Exports_2.CancellationReason.Error, synthEnd.FailureReason, Exports_2.CancellationErrorCode.ServiceError, null); - try { - this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, canceledResult); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - break; - case Exports_3.SynthesisStatus.Success: - this.sendSynthesisAudio(undefined, this.privRequestSession.sessionId); - break; - default: - break; - } - processed = true; - return [3 /*break*/, 10]; - case 9: return [3 /*break*/, 10]; - case 10: return [2 /*return*/, processed]; - } - }); - }); - }; - // Cancels recognition. - TranslationServiceRecognizer.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) { - var properties = new Exports_2.PropertyCollection(); - properties.setProperty(Exports_3.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[errorCode]); - if (!!this.privTranslationRecognizer.canceled) { - var cancelEvent = new Exports_2.TranslationRecognitionCanceledEventArgs(sessionId, cancellationReason, error, errorCode, undefined); - try { - this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, cancelEvent); - /* tslint:disable:no-empty */ - } - catch (_a) { } - } - if (!!this.privSuccessCallback) { - var result = new Exports_2.TranslationRecognitionResult(undefined, // Translations - requestId, Exports_2.ResultReason.Canceled, undefined, // Text - undefined, // Druation - undefined, // Offset - error, undefined, // Json - properties); - try { - this.privSuccessCallback(result); - /* tslint:disable:no-empty */ - this.privSuccessCallback = undefined; - } - catch (_b) { } + static StartConsoleOutput() { + if (!!this.privListener) { + this.privListener.enableConsoleOutput = true; } - }; - TranslationServiceRecognizer.prototype.fireEventForResult = function (serviceResult, properties) { - var translations; - if (undefined !== serviceResult.Translation.Translations) { - translations = new Exports_2.Translations(); - for (var _i = 0, _a = serviceResult.Translation.Translations; _i < _a.length; _i++) { - var translation = _a[_i]; - translations.set(translation.Language, translation.Text || translation.DisplayText); - } + } + static StopConsoleOutput() { + if (!!this.privListener) { + this.privListener.enableConsoleOutput = false; } - var resultReason; - if (serviceResult instanceof Exports_3.TranslationPhrase) { - if (serviceResult.Translation.TranslationStatus === Exports_1.TranslationStatus.Success) { - resultReason = Exports_2.ResultReason.TranslatedSpeech; - } - else { - resultReason = Exports_2.ResultReason.RecognizedSpeech; + } + static SetLogOutputPath(path) { + if (typeof window === "undefined") { + if (!!this.privListener) { + this.privListener.logPath = path; } } else { - resultReason = Exports_2.ResultReason.TranslatingSpeech; + throw new Error("File system logging not available in browser."); } - var offset = serviceResult.Offset + this.privRequestSession.currentTurnAudioOffset; - var result = new Exports_2.TranslationRecognitionResult(translations, this.privRequestSession.requestId, resultReason, serviceResult.Text, serviceResult.Duration, offset, serviceResult.Translation.FailureReason, JSON.stringify(serviceResult), properties); - var ev = new Exports_2.TranslationRecognitionEventArgs(result, offset, this.privRequestSession.sessionId); - return ev; - }; - TranslationServiceRecognizer.prototype.sendSynthesisAudio = function (audio, sessionId) { - var reason = (undefined === audio) ? Exports_2.ResultReason.SynthesizingAudioCompleted : Exports_2.ResultReason.SynthesizingAudio; - var result = new Exports_2.TranslationSynthesisResult(reason, audio); - var retEvent = new Exports_2.TranslationSynthesisEventArgs(result, sessionId); - if (!!this.privTranslationRecognizer.synthesizing) { - try { - this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } + } + static set onLogOutput(callback) { + if (!!this.privListener) { + this.privListener.logCallback = callback; } - }; - return TranslationServiceRecognizer; -}(Exports_3.ServiceRecognizerBase)); -exports.TranslationServiceRecognizer = TranslationServiceRecognizer; + } +} +exports.Diagnostics = Diagnostics; +Diagnostics.privListener = undefined; /***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { +/* 184 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechDetected = void 0; -var SpeechDetected = /** @class */ (function () { - function SpeechDetected(json) { - this.privSpeechStartDetected = JSON.parse(json); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RestMessageAdapter = exports.RestRequestType = void 0; +const bent_1 = __importDefault(__webpack_require__(185)); +const Exports_js_1 = __webpack_require__(4); +var RestRequestType; +(function (RestRequestType) { + RestRequestType["Get"] = "GET"; + RestRequestType["Post"] = "POST"; + RestRequestType["Delete"] = "DELETE"; + RestRequestType["File"] = "file"; +})(RestRequestType = exports.RestRequestType || (exports.RestRequestType = {})); +// accept rest operations via request method and return abstracted objects from server response +class RestMessageAdapter { + constructor(configParams) { + if (!configParams) { + throw new Exports_js_1.ArgumentNullError("configParams"); + } + this.privHeaders = configParams.headers; + this.privIgnoreCache = configParams.ignoreCache; + } + static extractHeaderValue(headerKey, headers) { + let headerValue = ""; + try { + const arr = headers.trim().split(/[\r\n]+/); + const headerMap = {}; + arr.forEach((line) => { + const parts = line.split(": "); + const header = parts.shift().toLowerCase(); + const value = parts.join(": "); + headerMap[header] = value; + }); + headerValue = headerMap[headerKey.toLowerCase()]; + } + catch (e) { + // ignore the error + } + return headerValue; + } + set options(configParams) { + this.privHeaders = configParams.headers; + this.privIgnoreCache = configParams.ignoreCache; + } + setHeaders(key, value) { + this.privHeaders[key] = value; + } + request(method, uri, queryParams = {}, body = null) { + const responseReceivedDeferral = new Exports_js_1.Deferred(); + const requestCommand = method === RestRequestType.File ? "POST" : method; + const handleRestResponse = (data, j = {}) => { + const d = data; + return { + data: JSON.stringify(j), + headers: JSON.stringify(data.headers), + json: j, + ok: data.statusCode >= 200 && data.statusCode < 300, + status: data.statusCode, + statusText: j.error ? j.error.message : d.statusText ? d.statusText : d.statusMessage + }; + }; + const send = (postData) => { + const sendRequest = (0, bent_1.default)(uri, requestCommand, this.privHeaders, 200, 201, 202, 204, 400, 401, 402, 403, 404); + const params = this.queryParams(queryParams) === "" ? "" : `?${this.queryParams(queryParams)}`; + sendRequest(params, postData).then(async (data) => { + if (method === RestRequestType.Delete || data.statusCode === 204) { + // No JSON from Delete and reset (204) operations + responseReceivedDeferral.resolve(handleRestResponse(data)); + } + else { + try { + const j = await data.json(); + responseReceivedDeferral.resolve(handleRestResponse(data, j)); + } + catch { + responseReceivedDeferral.resolve(handleRestResponse(data)); + } + } + }).catch((error) => { + responseReceivedDeferral.reject(error); + }); + }; + if (this.privIgnoreCache) { + this.privHeaders["Cache-Control"] = "no-cache"; + } + if (method === RestRequestType.Post && body) { + this.privHeaders["content-type"] = "application/json"; + this.privHeaders["Content-Type"] = "application/json"; + } + send(body); + return responseReceivedDeferral.promise; + } + queryParams(params = {}) { + return Object.keys(params) + .map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(params[k])) + .join("&"); + } +} +exports.RestMessageAdapter = RestMessageAdapter; + + + +/***/ }), +/* 185 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +/* global fetch, btoa, Headers */ +const core = __webpack_require__(186) + +class StatusError extends Error { + constructor (res, ...params) { + super(...params) + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, StatusError) + } + + this.name = 'StatusError' + this.message = res.statusMessage + this.statusCode = res.status + this.res = res + this.json = res.json.bind(res) + this.text = res.text.bind(res) + this.arrayBuffer = res.arrayBuffer.bind(res) + let buffer + const get = () => { + if (!buffer) buffer = this.arrayBuffer() + return buffer } - SpeechDetected.fromJSON = function (json) { - return new SpeechDetected(json); - }; - Object.defineProperty(SpeechDetected.prototype, "Offset", { - get: function () { - return this.privSpeechStartDetected.Offset; - }, - enumerable: false, - configurable: true - }); - return SpeechDetected; -}()); -exports.SpeechDetected = SpeechDetected; - - + Object.defineProperty(this, 'responseBody', { get }) + // match Node.js headers object + this.headers = {} + for (const [key, value] of res.headers.entries()) { + this.headers[key.toLowerCase()] = value + } + } +} -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { +const mkrequest = (statusCodes, method, encoding, headers, baseurl) => async (_url, body, _headers = {}) => { + _url = baseurl + (_url || '') + let parsed = new URL(_url) -"use strict"; + if (!headers) headers = {} + if (parsed.username) { + headers.Authorization = 'Basic ' + btoa(parsed.username + ':' + parsed.password) + parsed = new URL(parsed.protocol + '//' + parsed.host + parsed.pathname + parsed.search) + } + if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') { + throw new Error(`Unknown protocol, ${parsed.protocol}`) + } -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechHypothesis = void 0; -var SpeechHypothesis = /** @class */ (function () { - function SpeechHypothesis(json) { - this.privSpeechHypothesis = JSON.parse(json); + if (body) { + if (body instanceof ArrayBuffer || + ArrayBuffer.isView(body) || + typeof body === 'string' + ) { + // noop + } else if (typeof body === 'object') { + body = JSON.stringify(body) + headers['Content-Type'] = 'application/json' + } else { + throw new Error('Unknown body type.') } - SpeechHypothesis.fromJSON = function (json) { - return new SpeechHypothesis(json); - }; - Object.defineProperty(SpeechHypothesis.prototype, "Text", { - get: function () { - return this.privSpeechHypothesis.Text; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechHypothesis.prototype, "Offset", { - get: function () { - return this.privSpeechHypothesis.Offset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechHypothesis.prototype, "Duration", { - get: function () { - return this.privSpeechHypothesis.Duration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechHypothesis.prototype, "Language", { - get: function () { - return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Language; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechHypothesis.prototype, "LanguageDetectionConfidence", { - get: function () { - return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Confidence; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechHypothesis.prototype, "SpeakerId", { - get: function () { - return this.privSpeechHypothesis.SpeakerId; - }, - enumerable: false, - configurable: true - }); - return SpeechHypothesis; -}()); -exports.SpeechHypothesis = SpeechHypothesis; - + } + _headers = new Headers({ ...(headers || {}), ..._headers }) -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { + const resp = await fetch(parsed, { method, headers: _headers, body }) + resp.statusCode = resp.status -"use strict"; + if (!statusCodes.has(resp.status)) { + throw new StatusError(resp) + } -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechKeyword = void 0; -var SpeechKeyword = /** @class */ (function () { - function SpeechKeyword(json) { - this.privSpeechKeyword = JSON.parse(json); - } - SpeechKeyword.fromJSON = function (json) { - return new SpeechKeyword(json); - }; - Object.defineProperty(SpeechKeyword.prototype, "Status", { - get: function () { - return this.privSpeechKeyword.Status; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechKeyword.prototype, "Text", { - get: function () { - return this.privSpeechKeyword.Text; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechKeyword.prototype, "Offset", { - get: function () { - return this.privSpeechKeyword.Offset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechKeyword.prototype, "Duration", { - get: function () { - return this.privSpeechKeyword.Duration; - }, - enumerable: false, - configurable: true - }); - return SpeechKeyword; -}()); -exports.SpeechKeyword = SpeechKeyword; + if (encoding === 'json') return resp.json() + else if (encoding === 'buffer') return resp.arrayBuffer() + else if (encoding === 'string') return resp.text() + else return resp +} +module.exports = core(mkrequest) /***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { +/* 186 */ +/***/ ((module) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechServiceRecognizer = void 0; -var Exports_1 = __webpack_require__(61); -var Exports_2 = __webpack_require__(53); -// tslint:disable-next-line:max-classes-per-file -var SpeechServiceRecognizer = /** @class */ (function (_super) { - __extends(SpeechServiceRecognizer, _super); - function SpeechServiceRecognizer(authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer) { - var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer) || this; - _this.privSpeechRecognizer = speechRecognizer; - if (recognizerConfig.autoDetectSourceLanguages !== undefined) { - var sourceLanguages = recognizerConfig.autoDetectSourceLanguages.split(","); - _this.privSpeechContext.setSection("languageId", { - languages: sourceLanguages, - onSuccess: { action: "Recognize" }, - onUnknown: { action: "None" } - }); - _this.privSpeechContext.setSection("phraseOutput", { - interimResults: { - resultType: "Auto" - }, - phraseResults: { - resultType: "Always" - } - }); - } - return _this; - } - SpeechServiceRecognizer.prototype.processTypeSpecificMessages = function (connectionMessage) { - return __awaiter(this, void 0, void 0, function () { - var result, resultProps, processed, _a, hypothesis, offset, ev, simple, resultReason, cancelReason, cancellationErrorCode, detailed, totalOffset, offsetCorrectedJson, event_1; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - resultProps = new Exports_1.PropertyCollection(); - resultProps.setProperty(Exports_1.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody); - processed = false; - _a = connectionMessage.path.toLowerCase(); - switch (_a) { - case "speech.hypothesis": return [3 /*break*/, 1]; - case "speech.fragment": return [3 /*break*/, 1]; - case "speech.phrase": return [3 /*break*/, 2]; - } - return [3 /*break*/, 6]; - case 1: - hypothesis = Exports_2.SpeechHypothesis.fromJSON(connectionMessage.textBody); - offset = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset; - result = new Exports_1.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_1.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, undefined, // Speaker Id - undefined, connectionMessage.textBody, resultProps); - this.privRequestSession.onHypothesis(offset); - ev = new Exports_1.SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId); - if (!!this.privSpeechRecognizer.recognizing) { - try { - this.privSpeechRecognizer.recognizing(this.privSpeechRecognizer, ev); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - processed = true; - return [3 /*break*/, 7]; - case 2: - simple = Exports_2.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody); - resultReason = Exports_2.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus); - this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + simple.Offset + simple.Duration); - if (!(Exports_1.ResultReason.Canceled === resultReason)) return [3 /*break*/, 4]; - cancelReason = Exports_2.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus); - cancellationErrorCode = Exports_2.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus); - return [4 /*yield*/, this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_2.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode))]; - case 3: - _b.sent(); - return [3 /*break*/, 5]; - case 4: - if (!(this.privRequestSession.isSpeechEnded && resultReason === Exports_1.ResultReason.NoMatch && simple.RecognitionStatus !== Exports_2.RecognitionStatus.InitialSilenceTimeout)) { - if (this.privRecognizerConfig.parameters.getProperty(Exports_2.OutputFormatPropertyName) === Exports_1.OutputFormat[Exports_1.OutputFormat.Simple]) { - result = new Exports_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset + this.privRequestSession.currentTurnAudioOffset, simple.Language, simple.LanguageDetectionConfidence, undefined, // Speaker Id - undefined, connectionMessage.textBody, resultProps); - } - else { - detailed = Exports_2.DetailedSpeechPhrase.fromJSON(connectionMessage.textBody); - totalOffset = detailed.Offset + this.privRequestSession.currentTurnAudioOffset; - offsetCorrectedJson = detailed.getJsonWithCorrectedOffsets(totalOffset); - result = new Exports_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, detailed.RecognitionStatus === Exports_2.RecognitionStatus.Success ? detailed.NBest[0].Display : undefined, detailed.Duration, totalOffset, detailed.Language, detailed.LanguageDetectionConfidence, undefined, // Speaker Id - undefined, offsetCorrectedJson, resultProps); - } - event_1 = new Exports_1.SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId); - if (!!this.privSpeechRecognizer.recognized) { - try { - this.privSpeechRecognizer.recognized(this.privSpeechRecognizer, event_1); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - } - if (!!this.privSuccessCallback) { - try { - this.privSuccessCallback(result); - } - catch (e) { - if (!!this.privErrorCallback) { - this.privErrorCallback(e); - } - } - // Only invoke the call back once. - // and if it's successful don't invoke the - // error after that. - this.privSuccessCallback = undefined; - this.privErrorCallback = undefined; - } - _b.label = 5; - case 5: - processed = true; - return [3 /*break*/, 7]; - case 6: return [3 /*break*/, 7]; - case 7: return [2 /*return*/, processed]; - } - }); - }); - }; - // Cancels recognition. - SpeechServiceRecognizer.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) { - var properties = new Exports_1.PropertyCollection(); - properties.setProperty(Exports_2.CancellationErrorCodePropertyName, Exports_1.CancellationErrorCode[errorCode]); - if (!!this.privSpeechRecognizer.canceled) { - var cancelEvent = new Exports_1.SpeechRecognitionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId); - try { - this.privSpeechRecognizer.canceled(this.privSpeechRecognizer, cancelEvent); - /* tslint:disable:no-empty */ - } - catch (_a) { } - } - if (!!this.privSuccessCallback) { - var result = new Exports_1.SpeechRecognitionResult(requestId, Exports_1.ResultReason.Canceled, undefined, // Text - undefined, // Duration - undefined, // Offset - undefined, // Language - undefined, // Language Detection Confidence - undefined, // Speaker Id - error, undefined, // Json - properties); - try { - this.privSuccessCallback(result); - this.privSuccessCallback = undefined; - /* tslint:disable:no-empty */ - } - catch (_b) { } - } - }; - return SpeechServiceRecognizer; -}(Exports_2.ServiceRecognizerBase)); -exports.SpeechServiceRecognizer = SpeechServiceRecognizer; - - - -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { +const encodings = new Set(['json', 'buffer', 'string']) -"use strict"; +module.exports = mkrequest => (...args) => { + const statusCodes = new Set() + let method + let encoding + let headers + let baseurl = '' -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranscriptionServiceRecognizer = void 0; -var Exports_1 = __webpack_require__(4); -var Exports_2 = __webpack_require__(61); -var Exports_3 = __webpack_require__(53); -var SpeechConnectionMessage_Internal_1 = __webpack_require__(173); -// tslint:disable-next-line:max-classes-per-file -var TranscriptionServiceRecognizer = /** @class */ (function (_super) { - __extends(TranscriptionServiceRecognizer, _super); - function TranscriptionServiceRecognizer(authentication, connectionFactory, audioSource, recognizerConfig, transcriber) { - var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, transcriber) || this; - _this.sendSpeechEvent = function (connection, payload) { - var speechEventJson = JSON.stringify(payload); - if (speechEventJson) { - return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_1.MessageType.Text, "speech.event", _this.privRequestSession.requestId, "application/json", speechEventJson)); - } - return; - }; - _this.privTranscriberRecognizer = transcriber; - _this.sendPrePayloadJSONOverride = _this.sendTranscriptionStartJSON; - return _this; - } - TranscriptionServiceRecognizer.prototype.sendSpeechEventAsync = function (info, command) { - return __awaiter(this, void 0, void 0, function () { - var connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!!this.privRequestSession.isRecognizing) return [3 /*break*/, 3]; - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [4 /*yield*/, this.sendSpeechEvent(connection, this.createSpeechEventPayload(info, command))]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - TranscriptionServiceRecognizer.prototype.processTypeSpecificMessages = function (connectionMessage) { - return __awaiter(this, void 0, void 0, function () { - var result, resultProps, processed, _a, hypothesis, offset, ev, simple, resultReason, cancelReason, cancellationErrorCode, detailed, totalOffset, offsetCorrectedJson, event_1; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - resultProps = new Exports_2.PropertyCollection(); - resultProps.setProperty(Exports_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody); - processed = false; - _a = connectionMessage.path.toLowerCase(); - switch (_a) { - case "speech.hypothesis": return [3 /*break*/, 1]; - case "speech.fragment": return [3 /*break*/, 1]; - case "speech.phrase": return [3 /*break*/, 2]; - } - return [3 /*break*/, 6]; - case 1: - hypothesis = Exports_3.SpeechHypothesis.fromJSON(connectionMessage.textBody); - offset = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset; - result = new Exports_2.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_2.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, hypothesis.SpeakerId, undefined, connectionMessage.textBody, resultProps); - this.privRequestSession.onHypothesis(offset); - ev = new Exports_2.SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId); - if (!!this.privTranscriberRecognizer.recognizing) { - try { - this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer, ev); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - processed = true; - return [3 /*break*/, 7]; - case 2: - simple = Exports_3.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody); - resultReason = Exports_3.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus); - this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + simple.Offset + simple.Duration); - if (!(Exports_2.ResultReason.Canceled === resultReason)) return [3 /*break*/, 4]; - cancelReason = Exports_3.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus); - cancellationErrorCode = Exports_3.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus); - return [4 /*yield*/, this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_3.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode))]; - case 3: - _b.sent(); - return [3 /*break*/, 5]; - case 4: - if (!(this.privRequestSession.isSpeechEnded && resultReason === Exports_2.ResultReason.NoMatch && simple.RecognitionStatus !== Exports_3.RecognitionStatus.InitialSilenceTimeout)) { - if (this.privRecognizerConfig.parameters.getProperty(Exports_3.OutputFormatPropertyName) === Exports_2.OutputFormat[Exports_2.OutputFormat.Simple]) { - result = new Exports_2.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset + this.privRequestSession.currentTurnAudioOffset, simple.Language, simple.LanguageDetectionConfidence, simple.SpeakerId, undefined, connectionMessage.textBody, resultProps); - } - else { - detailed = Exports_3.DetailedSpeechPhrase.fromJSON(connectionMessage.textBody); - totalOffset = detailed.Offset + this.privRequestSession.currentTurnAudioOffset; - offsetCorrectedJson = detailed.getJsonWithCorrectedOffsets(totalOffset); - result = new Exports_2.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, detailed.Text, detailed.Duration, totalOffset, detailed.Language, detailed.LanguageDetectionConfidence, detailed.SpeakerId, undefined, offsetCorrectedJson, resultProps); - } - event_1 = new Exports_2.SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId); - if (!!this.privTranscriberRecognizer.recognized) { - try { - this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer, event_1); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - } - if (!!this.privSuccessCallback) { - try { - this.privSuccessCallback(result); - } - catch (e) { - if (!!this.privErrorCallback) { - this.privErrorCallback(e); - } - } - // Only invoke the call back once. - // and if it's successful don't invoke the - // error after that. - this.privSuccessCallback = undefined; - this.privErrorCallback = undefined; - } - _b.label = 5; - case 5: - processed = true; - return [3 /*break*/, 7]; - case 6: return [3 /*break*/, 7]; - case 7: return [2 /*return*/, processed]; - } - }); - }); - }; - // Cancels recognition. - TranscriptionServiceRecognizer.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) { - var properties = new Exports_2.PropertyCollection(); - properties.setProperty(Exports_3.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[errorCode]); - if (!!this.privTranscriberRecognizer.canceled) { - var cancelEvent = new Exports_2.ConversationTranscriptionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId); - try { - this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer, cancelEvent); - /* tslint:disable:no-empty */ - } - catch (_a) { } + args.forEach(arg => { + if (typeof arg === 'string') { + if (arg.toUpperCase() === arg) { + if (method) { + const msg = `Can't set method to ${arg}, already set to ${method}.` + throw new Error(msg) + } else { + method = arg } - if (!!this.privSuccessCallback) { - var result = new Exports_2.SpeechRecognitionResult(requestId, Exports_2.ResultReason.Canceled, undefined, // Text - undefined, // Duration - undefined, // Offset - undefined, // Language - undefined, // Language Detection Confidence - undefined, // Speaker Id - error, undefined, // Json - properties); - try { - this.privSuccessCallback(result); - this.privSuccessCallback = undefined; - /* tslint:disable:no-empty */ - } - catch (_b) { } + } else if (arg.startsWith('http:') || arg.startsWith('https:')) { + baseurl = arg + } else { + if (encodings.has(arg)) { + encoding = arg + } else { + throw new Error(`Unknown encoding, ${arg}`) } - }; - // Encapsulated for derived service recognizers that need to send additional JSON - TranscriptionServiceRecognizer.prototype.sendTranscriptionStartJSON = function (connection) { - return __awaiter(this, void 0, void 0, function () { - var info, payload; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.sendSpeechContext(connection)]; - case 1: - _a.sent(); - info = this.privTranscriberRecognizer.getConversationInfo(); - payload = this.createSpeechEventPayload(info, "start"); - return [4 /*yield*/, this.sendSpeechEvent(connection, payload)]; - case 2: - _a.sent(); - return [4 /*yield*/, this.sendWaveHeader(connection)]; - case 3: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - TranscriptionServiceRecognizer.prototype.createSpeechEventPayload = function (info, command) { - var meeting = "meeting"; - var eventDict = { id: meeting, name: command, meeting: info.conversationProperties }; - var idString = "id"; - var attendees = "attendees"; - var record = "record"; - eventDict[meeting][idString] = info.id; - eventDict[meeting][attendees] = info.participants; - eventDict[meeting][record] = info.conversationProperties.audiorecording === "on" ? "true" : "false"; - return eventDict; - }; - return TranscriptionServiceRecognizer; -}(Exports_3.ServiceRecognizerBase)); -exports.TranscriptionServiceRecognizer = TranscriptionServiceRecognizer; + } + } else if (typeof arg === 'number') { + statusCodes.add(arg) + } else if (typeof arg === 'object') { + if (Array.isArray(arg) || arg instanceof Set) { + arg.forEach(code => statusCodes.add(code)) + } else { + if (headers) { + throw new Error('Cannot set headers twice.') + } + headers = arg + } + } else { + throw new Error(`Unknown type: ${typeof arg}`) + } + }) + if (!method) method = 'GET' + if (statusCodes.size === 0) { + statusCodes.add(200) + } + + return mkrequest(statusCodes, method, encoding, headers, baseurl) +} /***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { +/* 187 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DetailedSpeechPhrase = void 0; -var Exports_1 = __webpack_require__(53); -var DetailedSpeechPhrase = /** @class */ (function () { - function DetailedSpeechPhrase(json) { - this.privDetailedSpeechPhrase = JSON.parse(json); - this.privDetailedSpeechPhrase.RecognitionStatus = Exports_1.RecognitionStatus[this.privDetailedSpeechPhrase.RecognitionStatus]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RestConfigBase = void 0; +class RestConfigBase { + static get requestOptions() { + return RestConfigBase.privDefaultRequestOptions; } - DetailedSpeechPhrase.fromJSON = function (json) { - return new DetailedSpeechPhrase(json); - }; - DetailedSpeechPhrase.prototype.getJsonWithCorrectedOffsets = function (baseOffset) { - if (!!this.privDetailedSpeechPhrase.NBest) { - var firstWordOffset = void 0; - for (var _i = 0, _a = this.privDetailedSpeechPhrase.NBest; _i < _a.length; _i++) { - var phrase = _a[_i]; - if (!!phrase.Words && !!phrase.Words[0]) { - firstWordOffset = phrase.Words[0].Offset; - break; + static get configParams() { + return RestConfigBase.privDefaultParams; + } + static get restErrors() { + return RestConfigBase.privRestErrors; + } +} +exports.RestConfigBase = RestConfigBase; +RestConfigBase.privDefaultRequestOptions = { + headers: { + Accept: "application/json", + }, + ignoreCache: false, + timeout: 10000, +}; +RestConfigBase.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.", +}; +RestConfigBase.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", +}; + + + +/***/ }), +/* 188 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechConnectionMessage = void 0; +const Exports_js_1 = __webpack_require__(4); +const HeaderNames_js_1 = __webpack_require__(59); +class SpeechConnectionMessage extends Exports_js_1.ConnectionMessage { + constructor(messageType, path, requestId, contentType, body, streamId, additionalHeaders, id) { + if (!path) { + throw new Exports_js_1.ArgumentNullError("path"); + } + if (!requestId) { + throw new Exports_js_1.ArgumentNullError("requestId"); + } + const headers = {}; + headers[HeaderNames_js_1.HeaderNames.Path] = path; + headers[HeaderNames_js_1.HeaderNames.RequestId] = requestId; + headers[HeaderNames_js_1.HeaderNames.RequestTimestamp] = new Date().toISOString(); + if (contentType) { + headers[HeaderNames_js_1.HeaderNames.ContentType] = contentType; + } + if (streamId) { + headers[HeaderNames_js_1.HeaderNames.RequestStreamId] = streamId; + } + if (additionalHeaders) { + for (const headerName in additionalHeaders) { + if (headerName) { + headers[headerName] = additionalHeaders[headerName]; } } - if (!!firstWordOffset && firstWordOffset < baseOffset) { - var offset = baseOffset - firstWordOffset; - for (var _b = 0, _c = this.privDetailedSpeechPhrase.NBest; _b < _c.length; _b++) { - var details = _c[_b]; - if (!!details.Words) { - for (var _d = 0, _e = details.Words; _d < _e.length; _d++) { - var word = _e[_d]; - word.Offset += offset; - } + } + if (id) { + super(messageType, body, headers, id); + } + else { + super(messageType, body, headers); + } + this.privPath = path; + this.privRequestId = requestId; + this.privContentType = contentType; + this.privStreamId = streamId; + this.privAdditionalHeaders = additionalHeaders; + } + 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(message) { + let path = null; + let requestId = null; + let contentType = null; + // let requestTimestamp = null; + let streamId = null; + const additionalHeaders = {}; + if (message.headers) { + for (const headerName in message.headers) { + if (headerName) { + if (headerName.toLowerCase() === HeaderNames_js_1.HeaderNames.Path.toLowerCase()) { + path = message.headers[headerName]; + } + else if (headerName.toLowerCase() === HeaderNames_js_1.HeaderNames.RequestId.toLowerCase()) { + requestId = message.headers[headerName]; + // } else if (headerName.toLowerCase() === HeaderNames.RequestTimestamp.toLowerCase()) { + // requestTimestamp = message.headers[headerName]; + } + else if (headerName.toLowerCase() === HeaderNames_js_1.HeaderNames.ContentType.toLowerCase()) { + contentType = message.headers[headerName]; + } + else if (headerName.toLowerCase() === HeaderNames_js_1.HeaderNames.RequestStreamId.toLowerCase()) { + streamId = message.headers[headerName]; + } + else { + additionalHeaders[headerName] = message.headers[headerName]; } } } } - return JSON.stringify(this.privDetailedSpeechPhrase); - }; - Object.defineProperty(DetailedSpeechPhrase.prototype, "RecognitionStatus", { - get: function () { - return this.privDetailedSpeechPhrase.RecognitionStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DetailedSpeechPhrase.prototype, "NBest", { - get: function () { - return this.privDetailedSpeechPhrase.NBest; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DetailedSpeechPhrase.prototype, "Duration", { - get: function () { - return this.privDetailedSpeechPhrase.Duration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DetailedSpeechPhrase.prototype, "Offset", { - get: function () { - return this.privDetailedSpeechPhrase.Offset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DetailedSpeechPhrase.prototype, "Language", { - get: function () { - return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Language; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DetailedSpeechPhrase.prototype, "LanguageDetectionConfidence", { - get: function () { - return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Confidence; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DetailedSpeechPhrase.prototype, "Text", { - get: function () { - return !!this.privDetailedSpeechPhrase.NBest && this.privDetailedSpeechPhrase.NBest[0] ? this.privDetailedSpeechPhrase.NBest[0].Display : this.privDetailedSpeechPhrase.DisplayText; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DetailedSpeechPhrase.prototype, "SpeakerId", { - get: function () { - return this.privDetailedSpeechPhrase.SpeakerId; - }, - enumerable: false, - configurable: true - }); - return DetailedSpeechPhrase; -}()); -exports.DetailedSpeechPhrase = DetailedSpeechPhrase; + return new SpeechConnectionMessage(message.messageType, path, requestId, contentType, message.body, streamId, additionalHeaders, message.id); + } +} +exports.SpeechConnectionMessage = SpeechConnectionMessage; /***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { +/* 189 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SimpleSpeechPhrase = void 0; -var Exports_1 = __webpack_require__(53); -var SimpleSpeechPhrase = /** @class */ (function () { - function SimpleSpeechPhrase(json) { - this.privSimpleSpeechPhrase = JSON.parse(json); - this.privSimpleSpeechPhrase.RecognitionStatus = Exports_1.RecognitionStatus[this.privSimpleSpeechPhrase.RecognitionStatus]; - } - SimpleSpeechPhrase.fromJSON = function (json) { - return new SimpleSpeechPhrase(json); - }; - Object.defineProperty(SimpleSpeechPhrase.prototype, "RecognitionStatus", { - get: function () { - return this.privSimpleSpeechPhrase.RecognitionStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SimpleSpeechPhrase.prototype, "DisplayText", { - get: function () { - return this.privSimpleSpeechPhrase.DisplayText; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SimpleSpeechPhrase.prototype, "Offset", { - get: function () { - return this.privSimpleSpeechPhrase.Offset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SimpleSpeechPhrase.prototype, "Duration", { - get: function () { - return this.privSimpleSpeechPhrase.Duration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SimpleSpeechPhrase.prototype, "Language", { - get: function () { - return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Language; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SimpleSpeechPhrase.prototype, "LanguageDetectionConfidence", { - get: function () { - return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Confidence; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SimpleSpeechPhrase.prototype, "SpeakerId", { - get: function () { - return this.privSimpleSpeechPhrase.SpeakerId; - }, - enumerable: false, - configurable: true - }); - return SimpleSpeechPhrase; -}()); -exports.SimpleSpeechPhrase = SimpleSpeechPhrase; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SegmentationMode = void 0; +/** + * The segmentation mode. + */ +var SegmentationMode; +(function (SegmentationMode) { + SegmentationMode["Normal"] = "Normal"; + SegmentationMode["Disabled"] = "Disabled"; + SegmentationMode["Custom"] = "Custom"; + SegmentationMode["Semantic"] = "Semantic"; +})(SegmentationMode = exports.SegmentationMode || (exports.SegmentationMode = {})); /***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { +/* 190 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AddedLmIntent = void 0; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NextAction = void 0; +/** + * The action to take on success + */ +var NextAction; +(function (NextAction) { + NextAction["None"] = "None"; + NextAction["Synthesize"] = "Synthesize"; +})(NextAction = exports.NextAction || (exports.NextAction = {})); + + + +/***/ }), +/* 191 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Mode = void 0; +/** + * Result type + */ +var Mode; +(function (Mode) { + Mode["None"] = "None"; + Mode["Always"] = "Always"; +})(Mode = exports.Mode || (exports.Mode = {})); + + + +/***/ }), +/* 192 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LanguageIdDetectionPriority = exports.LanguageIdDetectionMode = void 0; +/** + * The enum that represents which mode will language detection take place + * There is only detectAtAudioStart mode for now as language detection models are not trained for different modes + * This enum can be extended in future to support different modes + */ +var LanguageIdDetectionMode; +(function (LanguageIdDetectionMode) { + LanguageIdDetectionMode["DetectAtAudioStart"] = "DetectAtAudioStart"; + LanguageIdDetectionMode["DetectContinuous"] = "DetectContinuous"; + LanguageIdDetectionMode["DetectSegments"] = "DetectSegments"; +})(LanguageIdDetectionMode = exports.LanguageIdDetectionMode || (exports.LanguageIdDetectionMode = {})); /** - * @class AddedLmIntent + * The language id detection mode, setting this will load the detection setting of MaxAudioDuration and MaxSpeechDuration + * If the maxAudioDuration and maxSpeechDuration is set in the speech.context, then this detection mode will be ignored */ -// tslint:disable-next-line:max-classes-per-file -var AddedLmIntent = /** @class */ (function () { +var LanguageIdDetectionPriority; +(function (LanguageIdDetectionPriority) { /** - * Creates and initializes an instance of this class. - * @constructor - * @param modelImpl - The model. - * @param intentName - The intent name. + * default, Service decides the best mode to use. */ - function AddedLmIntent(modelImpl, intentName) { - this.modelImpl = modelImpl; - this.intentName = intentName; - } - return AddedLmIntent; -}()); -exports.AddedLmIntent = AddedLmIntent; + LanguageIdDetectionPriority["Auto"] = "Auto"; + /** + * Offers lower latency via a trade-off of accuracy. + */ + LanguageIdDetectionPriority["PrioritizeLatency"] = "PrioritizeLatency"; + /** + * Offers higher accuracy via a trade-off of latency. + */ + LanguageIdDetectionPriority["PrioritizeAccuracy"] = "PrioritizeAccuracy"; +})(LanguageIdDetectionPriority = exports.LanguageIdDetectionPriority || (exports.LanguageIdDetectionPriority = {})); /***/ }), -/* 195 */ -/***/ (function(module, exports, __webpack_require__) { +/* 193 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IntentServiceRecognizer = void 0; -var Exports_1 = __webpack_require__(4); -var Exports_2 = __webpack_require__(61); -var Exports_3 = __webpack_require__(53); -// tslint:disable-next-line:max-classes-per-file -var IntentServiceRecognizer = /** @class */ (function (_super) { - __extends(IntentServiceRecognizer, _super); - function IntentServiceRecognizer(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) { - var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, recognizer) || this; - _this.privIntentRecognizer = recognizer; - _this.privIntentDataSent = false; - return _this; - } - IntentServiceRecognizer.prototype.setIntents = function (addedIntents, umbrellaIntent) { - this.privAddedLmIntents = addedIntents; - this.privUmbrellaIntent = umbrellaIntent; - this.privIntentDataSent = true; - }; - IntentServiceRecognizer.prototype.processTypeSpecificMessages = function (connectionMessage) { - return __awaiter(this, void 0, void 0, function () { - var result, ev, processed, resultProps, speechHypothesis, simple, sendEvent, intentResponse, addedIntent, intentId, reason, properties; - var _this = this; - return __generator(this, function (_a) { - processed = false; - resultProps = new Exports_2.PropertyCollection(); - if (connectionMessage.messageType === Exports_1.MessageType.Text) { - resultProps.setProperty(Exports_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody); - } - switch (connectionMessage.path.toLowerCase()) { - case "speech.hypothesis": - speechHypothesis = Exports_3.SpeechHypothesis.fromJSON(connectionMessage.textBody); - result = new Exports_2.IntentRecognitionResult(undefined, this.privRequestSession.requestId, Exports_2.ResultReason.RecognizingIntent, speechHypothesis.Text, speechHypothesis.Duration, speechHypothesis.Offset + this.privRequestSession.currentTurnAudioOffset, speechHypothesis.Language, speechHypothesis.LanguageDetectionConfidence, undefined, connectionMessage.textBody, resultProps); - this.privRequestSession.onHypothesis(result.offset); - ev = new Exports_2.IntentRecognitionEventArgs(result, speechHypothesis.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId); - if (!!this.privIntentRecognizer.recognizing) { - try { - this.privIntentRecognizer.recognizing(this.privIntentRecognizer, ev); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - processed = true; - break; - case "speech.phrase": - simple = Exports_3.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody); - result = new Exports_2.IntentRecognitionResult(undefined, this.privRequestSession.requestId, Exports_3.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus), simple.DisplayText, simple.Duration, simple.Offset + this.privRequestSession.currentTurnAudioOffset, simple.Language, simple.LanguageDetectionConfidence, undefined, connectionMessage.textBody, resultProps); - ev = new Exports_2.IntentRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId); - sendEvent = function () { - if (!!_this.privIntentRecognizer.recognized) { - try { - _this.privIntentRecognizer.recognized(_this.privIntentRecognizer, ev); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - // report result to promise. - if (!!_this.privSuccessCallback) { - try { - _this.privSuccessCallback(result); - } - catch (e) { - if (!!_this.privErrorCallback) { - _this.privErrorCallback(e); - } - } - // Only invoke the call back once. - // and if it's successful don't invoke the - // error after that. - _this.privSuccessCallback = undefined; - _this.privErrorCallback = undefined; - } - }; - // If intent data was sent, the terminal result for this recognizer is an intent being found. - // If no intent data was sent, the terminal event is speech recognition being successful. - if (false === this.privIntentDataSent || Exports_2.ResultReason.NoMatch === ev.result.reason) { - // Advance the buffers. - this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration); - sendEvent(); - } - else { - // Squirrel away the args, when the response event arrives it will build upon them - // and then return - this.privPendingIntentArgs = ev; - } - processed = true; - break; - case "response": - // Response from LUIS - ev = this.privPendingIntentArgs; - this.privPendingIntentArgs = undefined; - if (undefined === ev) { - if ("" === connectionMessage.textBody) { - // This condition happens if there is nothing but silence in the - // audio sent to the service. - return [2 /*return*/]; - } - // Odd... Not sure this can happen - ev = new Exports_2.IntentRecognitionEventArgs(new Exports_2.IntentRecognitionResult(), 0 /*TODO*/, this.privRequestSession.sessionId); - } - intentResponse = Exports_3.IntentResponse.fromJSON(connectionMessage.textBody); - addedIntent = this.privAddedLmIntents[intentResponse.topScoringIntent.intent]; - if (this.privUmbrellaIntent !== undefined) { - addedIntent = this.privUmbrellaIntent; - } - if (null !== intentResponse && addedIntent !== undefined) { - intentId = addedIntent.intentName === undefined ? intentResponse.topScoringIntent.intent : addedIntent.intentName; - reason = ev.result.reason; - if (undefined !== intentId) { - reason = Exports_2.ResultReason.RecognizedIntent; - } - properties = (undefined !== ev.result.properties) ? - ev.result.properties : new Exports_2.PropertyCollection(); - properties.setProperty(Exports_2.PropertyId.LanguageUnderstandingServiceResponse_JsonResult, connectionMessage.textBody); - ev = new Exports_2.IntentRecognitionEventArgs(new Exports_2.IntentRecognitionResult(intentId, ev.result.resultId, reason, ev.result.text, ev.result.duration, ev.result.offset, undefined, undefined, ev.result.errorDetails, ev.result.json, properties), ev.offset, ev.sessionId); - } - this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration); - if (!!this.privIntentRecognizer.recognized) { - try { - this.privIntentRecognizer.recognized(this.privIntentRecognizer, ev); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - // report result to promise. - if (!!this.privSuccessCallback) { - try { - this.privSuccessCallback(ev.result); - } - catch (e) { - if (!!this.privErrorCallback) { - this.privErrorCallback(e); - } - } - // Only invoke the call back once. - // and if it's successful don't invoke the - // error after that. - this.privSuccessCallback = undefined; - this.privErrorCallback = undefined; - } - processed = true; - break; - default: - break; - } - return [2 /*return*/, processed]; - }); - }); - }; - // Cancels recognition. - IntentServiceRecognizer.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) { - var properties = new Exports_2.PropertyCollection(); - properties.setProperty(Exports_3.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[errorCode]); - if (!!this.privIntentRecognizer.canceled) { - var cancelEvent = new Exports_2.IntentRecognitionCanceledEventArgs(cancellationReason, error, errorCode, undefined, undefined, sessionId); - try { - this.privIntentRecognizer.canceled(this.privIntentRecognizer, cancelEvent); - /* tslint:disable:no-empty */ - } - catch (_a) { } - } - if (!!this.privSuccessCallback) { - var result = new Exports_2.IntentRecognitionResult(undefined, // Intent Id - requestId, Exports_2.ResultReason.Canceled, undefined, // Text - undefined, // Duration - undefined, // Offset - undefined, // Language - undefined, // LanguageDetectionConfidence - error, undefined, // Json - properties); - try { - this.privSuccessCallback(result); - this.privSuccessCallback = undefined; - /* tslint:disable:no-empty */ - } - catch (_b) { } - } - }; - return IntentServiceRecognizer; -}(Exports_3.ServiceRecognizerBase)); -exports.IntentServiceRecognizer = IntentServiceRecognizer; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NextAction = void 0; +/** + * The action to take on successful language detection + */ +var NextAction; +(function (NextAction) { + NextAction["Recognize"] = "Recognize"; + NextAction["None"] = "None"; +})(NextAction = exports.NextAction || (exports.NextAction = {})); + + + +/***/ }), +/* 194 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OnUnknownAction = void 0; +/** + * An enum that defines actions that can be taken on unknown language detection + */ +var OnUnknownAction; +(function (OnUnknownAction) { + OnUnknownAction["RecognizeWithDefaultLanguage"] = "RecognizeWithDefaultLanguage"; + OnUnknownAction["None"] = "None"; +})(OnUnknownAction = exports.OnUnknownAction || (exports.OnUnknownAction = {})); + + + +/***/ }), +/* 195 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ResultType = void 0; +/** + * The result type enum + */ +var ResultType; +(function (ResultType) { + ResultType["Auto"] = "Auto"; + ResultType["StableFragment"] = "StableFragment"; + ResultType["Hypothesis"] = "Hypothesis"; + ResultType["None"] = "None"; +})(ResultType = exports.ResultType || (exports.ResultType = {})); /***/ }), /* 196 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -// response -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IntentResponse = void 0; -var IntentResponse = /** @class */ (function () { - function IntentResponse(json) { - this.privIntentResponse = JSON.parse(json); - } - IntentResponse.fromJSON = function (json) { - return new IntentResponse(json); - }; - Object.defineProperty(IntentResponse.prototype, "query", { - get: function () { - return this.privIntentResponse.query; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(IntentResponse.prototype, "topScoringIntent", { - get: function () { - return this.privIntentResponse.topScoringIntent; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(IntentResponse.prototype, "entities", { - get: function () { - return this.privIntentResponse.entities; - }, - enumerable: false, - configurable: true - }); - return IntentResponse; -}()); -exports.IntentResponse = IntentResponse; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PhraseResultOutputType = void 0; +/** + * The phrase result output type + */ +var PhraseResultOutputType; +(function (PhraseResultOutputType) { + PhraseResultOutputType["Always"] = "Always"; + PhraseResultOutputType["None"] = "None"; +})(PhraseResultOutputType = exports.PhraseResultOutputType || (exports.PhraseResultOutputType = {})); /***/ }), /* 197 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RequestSession = void 0; -var Exports_1 = __webpack_require__(4); -var RecognitionEvents_1 = __webpack_require__(171); -var ServiceTelemetryListener_Internal_1 = __webpack_require__(198); -var RequestSession = /** @class */ (function () { - function RequestSession(audioSourceId) { - var _this = this; - this.privIsDisposed = false; - this.privDetachables = new Array(); - this.privIsAudioNodeDetached = false; - this.privIsRecognizing = false; - this.privIsSpeechEnded = false; - this.privTurnStartAudioOffset = 0; - this.privLastRecoOffset = 0; - this.privHypothesisReceived = false; - this.privBytesSent = 0; - this.privRecogNumber = 0; - this.privInTurn = false; - this.privConnectionAttempts = 0; - this.onPreConnectionStart = function (authFetchEventId, connectionId) { - _this.privAuthFetchEventId = authFetchEventId; - _this.privSessionId = connectionId; - _this.onEvent(new RecognitionEvents_1.ConnectingToServiceEvent(_this.privRequestId, _this.privAuthFetchEventId, _this.privSessionId)); - }; - this.onSpeechContext = function () { - _this.privRequestId = Exports_1.createNoDashGuid(); - }; - this.onServiceTurnStartResponse = function () { - if (!!_this.privTurnDeferral && !!_this.privInTurn) { - // What? How are we starting a turn with another not done? - _this.privTurnDeferral.reject("Another turn started before current completed."); - // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited - /* tslint:disable:no-empty */ - _this.privTurnDeferral.promise.then().catch(function () { }); - } - _this.privInTurn = true; - _this.privTurnDeferral = new Exports_1.Deferred(); - }; - this.getTelemetry = function () { - if (_this.privServiceTelemetryListener.hasTelemetry) { - return _this.privServiceTelemetryListener.getTelemetry(); - } - else { - return null; - } - }; - this.onEvent = function (event) { - if (!!_this.privServiceTelemetryListener) { - _this.privServiceTelemetryListener.onEvent(event); - } - Exports_1.Events.instance.onEvent(event); - }; - this.privAudioSourceId = audioSourceId; - this.privRequestId = Exports_1.createNoDashGuid(); - this.privAudioNodeId = Exports_1.createNoDashGuid(); - this.privTurnDeferral = new Exports_1.Deferred(); - // We're not in a turn, so resolve. - this.privTurnDeferral.resolve(); - } - Object.defineProperty(RequestSession.prototype, "sessionId", { - get: function () { - return this.privSessionId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "requestId", { - get: function () { - return this.privRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "audioNodeId", { - get: function () { - return this.privAudioNodeId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "turnCompletionPromise", { - get: function () { - return this.privTurnDeferral.promise; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "isSpeechEnded", { - get: function () { - return this.privIsSpeechEnded; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "isRecognizing", { - get: function () { - return this.privIsRecognizing; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "currentTurnAudioOffset", { - get: function () { - return this.privTurnStartAudioOffset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "recogNumber", { - get: function () { - return this.privRecogNumber; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "numConnectionAttempts", { - get: function () { - return this.privConnectionAttempts; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RequestSession.prototype, "bytesSent", { - // The number of bytes sent for the current connection. - // Counter is reset to 0 each time a connection is established. - get: function () { - return this.privBytesSent; - }, - enumerable: false, - configurable: true - }); - RequestSession.prototype.listenForServiceTelemetry = function (eventSource) { - if (!!this.privServiceTelemetryListener) { - this.privDetachables.push(eventSource.attachListener(this.privServiceTelemetryListener)); - } - }; - RequestSession.prototype.startNewRecognition = function () { - this.privIsSpeechEnded = false; - this.privIsRecognizing = true; - this.privTurnStartAudioOffset = 0; - this.privLastRecoOffset = 0; - this.privRecogNumber++; - this.privServiceTelemetryListener = new ServiceTelemetryListener_Internal_1.ServiceTelemetryListener(this.privRequestId, this.privAudioSourceId, this.privAudioNodeId); - this.onEvent(new RecognitionEvents_1.RecognitionTriggeredEvent(this.requestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId)); - }; - RequestSession.prototype.onAudioSourceAttachCompleted = function (audioNode, isError, error) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privAudioNode = audioNode; - this.privIsAudioNodeDetached = false; - if (!isError) return [3 /*break*/, 2]; - return [4 /*yield*/, this.onComplete()]; - case 1: - _a.sent(); - return [3 /*break*/, 3]; - case 2: - this.onEvent(new RecognitionEvents_1.ListeningStartedEvent(this.privRequestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId)); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - RequestSession.prototype.onAuthCompleted = function (isError, error) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!isError) return [3 /*break*/, 2]; - return [4 /*yield*/, this.onComplete()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - RequestSession.prototype.onConnectionEstablishCompleted = function (statusCode, reason) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(statusCode === 200)) return [3 /*break*/, 1]; - this.onEvent(new RecognitionEvents_1.RecognitionStartedEvent(this.requestId, this.privAudioSourceId, this.privAudioNodeId, this.privAuthFetchEventId, this.privSessionId)); - if (!!this.privAudioNode) { - this.privAudioNode.replay(); - } - this.privTurnStartAudioOffset = this.privLastRecoOffset; - this.privBytesSent = 0; - return [2 /*return*/]; - case 1: - if (!(statusCode === 403)) return [3 /*break*/, 3]; - return [4 /*yield*/, this.onComplete()]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - RequestSession.prototype.onServiceTurnEndResponse = function (continuousRecognition) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privTurnDeferral.resolve(); - if (!(!continuousRecognition || this.isSpeechEnded)) return [3 /*break*/, 2]; - return [4 /*yield*/, this.onComplete()]; - case 1: - _a.sent(); - this.privInTurn = false; - return [3 /*break*/, 3]; - case 2: - // Start a new request set. - this.privTurnStartAudioOffset = this.privLastRecoOffset; - this.privAudioNode.replay(); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - RequestSession.prototype.onHypothesis = function (offset) { - if (!this.privHypothesisReceived) { - this.privHypothesisReceived = true; - this.privServiceTelemetryListener.hypothesisReceived(this.privAudioNode.findTimeAtOffset(offset)); - } - }; - RequestSession.prototype.onPhraseRecognized = function (offset) { - this.privServiceTelemetryListener.phraseReceived(this.privAudioNode.findTimeAtOffset(offset)); - this.onServiceRecognized(offset); - }; - RequestSession.prototype.onServiceRecognized = function (offset) { - this.privLastRecoOffset = offset; - this.privHypothesisReceived = false; - this.privAudioNode.shrinkBuffers(offset); - this.privConnectionAttempts = 0; - }; - RequestSession.prototype.onAudioSent = function (bytesSent) { - this.privBytesSent += bytesSent; - }; - RequestSession.prototype.onRetryConnection = function () { - this.privConnectionAttempts++; - }; - RequestSession.prototype.dispose = function (error) { - var _a; - return __awaiter(this, void 0, void 0, function () { - var _i, _b, detachable; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - if (!!this.privIsDisposed) return [3 /*break*/, 5]; - // we should have completed by now. If we did not its an unknown error. - this.privIsDisposed = true; - _i = 0, _b = this.privDetachables; - _c.label = 1; - case 1: - if (!(_i < _b.length)) return [3 /*break*/, 4]; - detachable = _b[_i]; - return [4 /*yield*/, detachable.detach()]; - case 2: - _c.sent(); - _c.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: - (_a = this.privServiceTelemetryListener) === null || _a === void 0 ? void 0 : _a.dispose(); - this.privIsRecognizing = false; - _c.label = 5; - case 5: return [2 /*return*/]; - } - }); - }); - }; - RequestSession.prototype.onStopRecognizing = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.onComplete()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - // Should be called with the audioNode for this session has indicated that it is out of speech. - RequestSession.prototype.onSpeechEnded = function () { - this.privIsSpeechEnded = true; - }; - RequestSession.prototype.onComplete = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!!this.privIsRecognizing) return [3 /*break*/, 2]; - this.privIsRecognizing = false; - return [4 /*yield*/, this.detachAudioNode()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - RequestSession.prototype.detachAudioNode = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!this.privIsAudioNodeDetached) return [3 /*break*/, 2]; - this.privIsAudioNodeDetached = true; - if (!this.privAudioNode) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privAudioNode.detach()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - return RequestSession; -}()); -exports.RequestSession = RequestSession; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NextAction = void 0; +/** + * The action enum when speech recognition return a final phrase result + */ +var NextAction; +(function (NextAction) { + NextAction["None"] = "None"; + NextAction["Translate"] = "Translate"; +})(NextAction = exports.NextAction || (exports.NextAction = {})); /***/ }), /* 198 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ServiceTelemetryListener = void 0; -// tslint:disable:max-classes-per-file -var Exports_1 = __webpack_require__(4); -var RecognitionEvents_1 = __webpack_require__(171); -var ServiceTelemetryListener = /** @class */ (function () { - function ServiceTelemetryListener(requestId, audioSourceId, audioNodeId) { - var _this = this; - this.privIsDisposed = false; - this.privListeningTriggerMetric = null; - this.privMicMetric = null; - this.privConnectionEstablishMetric = null; - this.onEvent = function (e) { - if (_this.privIsDisposed) { - return; - } - if (e instanceof RecognitionEvents_1.RecognitionTriggeredEvent && e.requestId === _this.privRequestId) { - _this.privListeningTriggerMetric = { - End: e.eventTime, - Name: "ListeningTrigger", - Start: e.eventTime, - }; - } - if (e instanceof Exports_1.AudioStreamNodeAttachingEvent && e.audioSourceId === _this.privAudioSourceId && e.audioNodeId === _this.privAudioNodeId) { - _this.privMicStartTime = e.eventTime; - } - if (e instanceof Exports_1.AudioStreamNodeAttachedEvent && e.audioSourceId === _this.privAudioSourceId && e.audioNodeId === _this.privAudioNodeId) { - _this.privMicStartTime = e.eventTime; - } - if (e instanceof Exports_1.AudioSourceErrorEvent && e.audioSourceId === _this.privAudioSourceId) { - if (!_this.privMicMetric) { - _this.privMicMetric = { - End: e.eventTime, - Error: e.error, - Name: "Microphone", - Start: _this.privMicStartTime, - }; - } - } - if (e instanceof Exports_1.AudioStreamNodeErrorEvent && e.audioSourceId === _this.privAudioSourceId && e.audioNodeId === _this.privAudioNodeId) { - if (!_this.privMicMetric) { - _this.privMicMetric = { - End: e.eventTime, - Error: e.error, - Name: "Microphone", - Start: _this.privMicStartTime, - }; - } - } - if (e instanceof Exports_1.AudioStreamNodeDetachedEvent && e.audioSourceId === _this.privAudioSourceId && e.audioNodeId === _this.privAudioNodeId) { - if (!_this.privMicMetric) { - _this.privMicMetric = { - End: e.eventTime, - Name: "Microphone", - Start: _this.privMicStartTime, - }; - } - } - if (e instanceof RecognitionEvents_1.ConnectingToServiceEvent && e.requestId === _this.privRequestId) { - _this.privConnectionId = e.sessionId; - } - if (e instanceof Exports_1.ConnectionStartEvent && e.connectionId === _this.privConnectionId) { - _this.privConnectionStartTime = e.eventTime; - } - if (e instanceof Exports_1.ConnectionEstablishedEvent && e.connectionId === _this.privConnectionId) { - if (!_this.privConnectionEstablishMetric) { - _this.privConnectionEstablishMetric = { - End: e.eventTime, - Id: _this.privConnectionId, - Name: "Connection", - Start: _this.privConnectionStartTime, - }; - } - } - if (e instanceof Exports_1.ConnectionEstablishErrorEvent && e.connectionId === _this.privConnectionId) { - if (!_this.privConnectionEstablishMetric) { - _this.privConnectionEstablishMetric = { - End: e.eventTime, - Error: _this.getConnectionError(e.statusCode), - Id: _this.privConnectionId, - Name: "Connection", - Start: _this.privConnectionStartTime, - }; - } - } - if (e instanceof Exports_1.ConnectionMessageReceivedEvent && e.connectionId === _this.privConnectionId) { - if (e.message && e.message.headers && e.message.headers.path) { - if (!_this.privReceivedMessages[e.message.headers.path]) { - _this.privReceivedMessages[e.message.headers.path] = new Array(); - } - var maxMessagesToSend = 50; - if (_this.privReceivedMessages[e.message.headers.path].length < maxMessagesToSend) { - _this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime); - } - } - } - }; - this.getTelemetry = function () { - var metrics = new Array(); - if (_this.privListeningTriggerMetric) { - metrics.push(_this.privListeningTriggerMetric); - } - if (_this.privMicMetric) { - metrics.push(_this.privMicMetric); - } - if (_this.privConnectionEstablishMetric) { - metrics.push(_this.privConnectionEstablishMetric); - } - if (_this.privPhraseLatencies.length > 0) { - metrics.push({ - PhraseLatencyMs: _this.privPhraseLatencies, - }); - } - if (_this.privHypothesisLatencies.length > 0) { - metrics.push({ - FirstHypothesisLatencyMs: _this.privHypothesisLatencies, - }); - } - var telemetry = { - Metrics: metrics, - ReceivedMessages: _this.privReceivedMessages, - }; - var json = JSON.stringify(telemetry); - // We dont want to send the same telemetry again. So clean those out. - _this.privReceivedMessages = {}; - _this.privListeningTriggerMetric = null; - _this.privMicMetric = null; - _this.privConnectionEstablishMetric = null; - _this.privPhraseLatencies = []; - _this.privHypothesisLatencies = []; - return json; - }; - this.dispose = function () { - _this.privIsDisposed = true; - }; - this.getConnectionError = function (statusCode) { - /* - -- Websocket status codes -- - NormalClosure = 1000, - EndpointUnavailable = 1001, - ProtocolError = 1002, - InvalidMessageType = 1003, - Empty = 1005, - InvalidPayloadData = 1007, - PolicyViolation = 1008, - MessageTooBig = 1009, - MandatoryExtension = 1010, - InternalServerError = 1011 - */ - switch (statusCode) { - case 400: - case 1002: - case 1003: - case 1005: - case 1007: - case 1008: - case 1009: return "BadRequest"; - case 401: return "Unauthorized"; - case 403: return "Forbidden"; - case 503: - case 1001: return "ServerUnavailable"; - case 500: - case 1011: return "ServerError"; - case 408: - case 504: return "Timeout"; - default: return "statuscode:" + statusCode.toString(); - } - }; - this.privRequestId = requestId; - this.privAudioSourceId = audioSourceId; - this.privAudioNodeId = audioNodeId; - this.privReceivedMessages = {}; - this.privPhraseLatencies = []; - this.privHypothesisLatencies = []; - } - ServiceTelemetryListener.prototype.phraseReceived = function (audioReceivedTime) { - if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it. - this.privPhraseLatencies.push(Date.now() - audioReceivedTime); - } - }; - ServiceTelemetryListener.prototype.hypothesisReceived = function (audioReceivedTime) { - if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it. - this.privHypothesisLatencies.push(Date.now() - audioReceivedTime); - } - }; - Object.defineProperty(ServiceTelemetryListener.prototype, "hasTelemetry", { - // Determines if there are any telemetry events to send to the service. - get: function () { - return (Object.keys(this.privReceivedMessages).length !== 0 || - this.privListeningTriggerMetric !== null || - this.privMicMetric !== null || - this.privConnectionEstablishMetric !== null || - this.privPhraseLatencies.length !== 0 || - this.privHypothesisLatencies.length !== 0); - }, - enumerable: false, - configurable: true - }); - return ServiceTelemetryListener; -}()); -exports.ServiceTelemetryListener = ServiceTelemetryListener; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InteractivePunctuationMode = void 0; +/** + * The interactive punctuation mode. + */ +var InteractivePunctuationMode; +(function (InteractivePunctuationMode) { + InteractivePunctuationMode["None"] = "None"; + InteractivePunctuationMode["Implicit"] = "Implicit"; + InteractivePunctuationMode["Explicit"] = "Explicit"; + InteractivePunctuationMode["Intelligent"] = "Intelligent"; +})(InteractivePunctuationMode = exports.InteractivePunctuationMode || (exports.InteractivePunctuationMode = {})); /***/ }), /* 199 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeechContext = void 0; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationPunctuationMode = void 0; /** - * Represents the JSON used in the speech.context message sent to the speech service. - * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object. + * The conversation punctuation mode. */ -var SpeechContext = /** @class */ (function () { - function SpeechContext(dynamicGrammar) { - this.privContext = {}; - this.privDynamicGrammar = dynamicGrammar; - } +var ConversationPunctuationMode; +(function (ConversationPunctuationMode) { + ConversationPunctuationMode["None"] = "None"; + ConversationPunctuationMode["Intelligent"] = "Intelligent"; + ConversationPunctuationMode["Implicit"] = "Implicit"; + ConversationPunctuationMode["Explicit"] = "Explicit"; +})(ConversationPunctuationMode = exports.ConversationPunctuationMode || (exports.ConversationPunctuationMode = {})); + + + +/***/ }), +/* 200 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DictationPunctuationMode = void 0; +/** + * The dictation punctuation mode. + */ +var DictationPunctuationMode; +(function (DictationPunctuationMode) { + DictationPunctuationMode["None"] = "None"; + DictationPunctuationMode["Intelligent"] = "Intelligent"; + DictationPunctuationMode["Implicit"] = "Implicit"; + DictationPunctuationMode["Explicit"] = "Explicit"; +})(DictationPunctuationMode = exports.DictationPunctuationMode || (exports.DictationPunctuationMode = {})); + + + +/***/ }), +/* 201 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DisfluencyMode = void 0; +/** + * Disfluency handling options. + */ +var DisfluencyMode; +(function (DisfluencyMode) { /** - * Adds a section to the speech.context object. - * @param sectionName Name of the section to add. - * @param value JSON serializable object that represents the value. + * The Microsoft Speech Service does not remove disfluencies from all results. */ - SpeechContext.prototype.setSection = function (sectionName, value) { - this.privContext[sectionName] = value; - }; + DisfluencyMode["Raw"] = "Raw"; /** - * @Internal - * This is only used by pronunciation assessment config. - * Do not use externally, object returned will change without warning or notice. + * The Microsoft Speech Service removes disfluencies from all results. */ - SpeechContext.prototype.setPronunciationAssessmentParams = function (params) { - if (this.privContext.phraseDetection === undefined) { - this.privContext.phraseDetection = { - enrichment: { - pronunciationAssessment: {} + DisfluencyMode["Removed"] = "Removed"; + /** + * The Microsoft Speech Service tags disfluencies in the phrase result. + */ + DisfluencyMode["Labeled"] = "Labeled"; +})(DisfluencyMode = exports.DisfluencyMode || (exports.DisfluencyMode = {})); + + + +/***/ }), +/* 202 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationServiceRecognizer = void 0; +const Exports_js_1 = __webpack_require__(85); +const Exports_js_2 = __webpack_require__(2); +class ConversationServiceRecognizer extends Exports_js_2.ServiceRecognizerBase { + constructor(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) { + super(authentication, connectionFactory, audioSource, recognizerConfig, recognizer); + this.handleSpeechPhraseMessage = async (textBody) => this.handleSpeechPhrase(textBody); + this.handleSpeechHypothesisMessage = (textBody) => this.handleSpeechHypothesis(textBody); + } + processTypeSpecificMessages(connectionMessage) { + void connectionMessage; + return; + } + handleRecognizedCallback(result, offset, sessionId) { + void result; + void offset; + void sessionId; + return; + } + handleRecognizingCallback(result, duration, sessionId) { + void result; + void duration; + void sessionId; + return; + } + async processSpeechMessages(connectionMessage) { + let processed = false; + switch (connectionMessage.path.toLowerCase()) { + case "speech.hypothesis": + case "speech.fragment": + if (!!this.handleSpeechHypothesisMessage) { + this.handleSpeechHypothesisMessage(connectionMessage.textBody); } - }; - } - this.privContext.phraseDetection.enrichment.pronunciationAssessment = JSON.parse(params); - if (this.privContext.phraseOutput === undefined) { - this.privContext.phraseOutput = { - detailed: { - options: [] - }, - format: {} - }; + processed = true; + break; + case "speech.phrase": + if (!!this.handleSpeechPhraseMessage) { + await this.handleSpeechPhraseMessage(connectionMessage.textBody); + } + processed = true; + break; + default: + break; } - this.privContext.phraseOutput.format = "Detailed"; - this.privContext.phraseOutput.detailed.options.push("PronunciationAssessment"); - if (this.privContext.phraseOutput.detailed.options.indexOf("WordTimings") === -1) { - this.privContext.phraseOutput.detailed.options.push("WordTimings"); + return processed; + } + cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) { + // Implementing to allow inheritance + void sessionId; + void requestId; + void cancellationReason; + void errorCode; + void error; + } + async handleSpeechPhrase(textBody) { + const simple = Exports_js_2.SimpleSpeechPhrase.fromJSON(textBody, this.privRequestSession.currentTurnAudioOffset); + const resultReason = Exports_js_2.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus); + let result; + const resultProps = new Exports_js_1.PropertyCollection(); + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, textBody); + this.privRequestSession.onPhraseRecognized(simple.Offset + simple.Duration); + if (Exports_js_1.ResultReason.Canceled === resultReason) { + const cancelReason = Exports_js_2.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus); + const cancellationErrorCode = Exports_js_2.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus); + await this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_js_2.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode)); } - if (this.privContext.phraseOutput.detailed.options.indexOf("SNR") === -1) { - this.privContext.phraseOutput.detailed.options.push("SNR"); + else { + if (simple.RecognitionStatus !== Exports_js_2.RecognitionStatus.EndOfDictation) { + if (this.privRecognizerConfig.parameters.getProperty(Exports_js_2.OutputFormatPropertyName) === Exports_js_1.OutputFormat[Exports_js_1.OutputFormat.Simple]) { + result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset, simple.Language, simple.LanguageDetectionConfidence, simple.SpeakerId, undefined, simple.asJson(), resultProps); + } + else { + const detailed = Exports_js_2.DetailedSpeechPhrase.fromJSON(textBody, this.privRequestSession.currentTurnAudioOffset); + result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, detailed.Text, detailed.Duration, detailed.Offset, detailed.Language, detailed.LanguageDetectionConfidence, detailed.SpeakerId, undefined, detailed.asJson(), resultProps); + } + this.handleRecognizedCallback(result, result.offset, this.privRequestSession.sessionId); + } } - }; - SpeechContext.prototype.toJSON = function () { - var dgi = this.privDynamicGrammar.generateGrammarObject(); - this.setSection("dgi", dgi); - var ret = JSON.stringify(this.privContext); - return ret; - }; - return SpeechContext; -}()); -exports.SpeechContext = SpeechContext; + } + handleSpeechHypothesis(textBody) { + const hypothesis = Exports_js_2.SpeechHypothesis.fromJSON(textBody, this.privRequestSession.currentTurnAudioOffset); + const resultProps = new Exports_js_1.PropertyCollection(); + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, textBody); + const result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_js_1.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, hypothesis.Offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, hypothesis.SpeakerId, undefined, hypothesis.asJson(), resultProps); + this.privRequestSession.onHypothesis(hypothesis.Offset); + this.handleRecognizingCallback(result, hypothesis.Duration, this.privRequestSession.sessionId); + } +} +exports.ConversationServiceRecognizer = ConversationServiceRecognizer; /***/ }), -/* 200 */ -/***/ (function(module, exports, __webpack_require__) { +/* 203 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DynamicGrammarBuilder = void 0; -/** - * Responsible for building the object to be sent to the speech service to support dynamic grammars. - * @class DynamicGrammarBuilder - */ -var DynamicGrammarBuilder = /** @class */ (function () { - function DynamicGrammarBuilder() { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RecognizerConfig = exports.SpeechResultFormat = void 0; +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(85); +const Exports_js_2 = __webpack_require__(2); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +var SpeechResultFormat; +(function (SpeechResultFormat) { + SpeechResultFormat[SpeechResultFormat["Simple"] = 0] = "Simple"; + SpeechResultFormat[SpeechResultFormat["Detailed"] = 1] = "Detailed"; +})(SpeechResultFormat = exports.SpeechResultFormat || (exports.SpeechResultFormat = {})); +class RecognizerConfig { + constructor(speechServiceConfig, parameters) { + this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new Exports_js_2.SpeechServiceConfig(new Exports_js_2.Context(null)); + this.privParameters = parameters; + this.privMaxRetryCount = parseInt(parameters.getProperty("SPEECH-Error-MaxRetryCount", "4"), 10); + this.privLanguageIdMode = parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_LanguageIdMode, undefined); + this.privEnableSpeakerId = false; } - // Adds one more reference phrases to the dynamic grammar to send. - // All added phrases are generic phrases. - DynamicGrammarBuilder.prototype.addPhrase = function (phrase) { - if (!this.privPhrases) { - this.privPhrases = []; - } - if (phrase instanceof Array) { - this.privPhrases = this.privPhrases.concat(phrase); - } - else { - this.privPhrases.push(phrase); - } - }; - // Clears all phrases stored in the current object. - DynamicGrammarBuilder.prototype.clearPhrases = function () { - this.privPhrases = undefined; - }; - // Adds one or more reference grammars to the current grammar. - DynamicGrammarBuilder.prototype.addReferenceGrammar = function (grammar) { - if (!this.privGrammars) { - this.privGrammars = []; - } - if (grammar instanceof Array) { - this.privGrammars = this.privGrammars.concat(grammar); - } - else { - this.privGrammars.push(grammar); - } - }; - // clears all grammars stored on the recognizer. - DynamicGrammarBuilder.prototype.clearGrammars = function () { - this.privGrammars = undefined; - }; - // Generates an object that represents the dynamic grammar used by the Speech Service. - // This is done by building an object with the correct layout based on the phrases and reference grammars added to this instance - // of a DynamicGrammarBuilder - DynamicGrammarBuilder.prototype.generateGrammarObject = function () { - if (this.privGrammars === undefined && this.privPhrases === undefined) { - return undefined; - } - var retObj = {}; - retObj.ReferenceGrammars = this.privGrammars; - if (undefined !== this.privPhrases && 0 !== this.privPhrases.length) { - var retPhrases_1 = []; - this.privPhrases.forEach(function (value, index, array) { - retPhrases_1.push({ - Text: value, - }); - }); - retObj.Groups = [{ Type: "Generic", Items: retPhrases_1 }]; + get parameters() { + return this.privParameters; + } + get recognitionMode() { + return this.privRecognitionMode; + } + set recognitionMode(value) { + this.privRecognitionMode = value; + this.privRecognitionActivityTimeout = value === PhraseDetectionContext_js_1.RecognitionMode.Interactive ? 8000 : 25000; + this.privSpeechServiceConfig.Recognition = PhraseDetectionContext_js_1.RecognitionMode[value]; + } + get SpeechServiceConfig() { + return this.privSpeechServiceConfig; + } + get recognitionActivityTimeout() { + return this.privRecognitionActivityTimeout; + } + get isContinuousRecognition() { + return this.privRecognitionMode !== PhraseDetectionContext_js_1.RecognitionMode.Interactive; + } + get languageIdMode() { + return this.privLanguageIdMode; + } + get autoDetectSourceLanguages() { + return this.parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, undefined); + } + get recognitionEndpointVersion() { + return this.parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "2"); + } + set recognitionEndpointVersion(version) { + this.parameters.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, version); + } + get sourceLanguageModels() { + const models = []; + let modelsExist = false; + if (this.autoDetectSourceLanguages !== undefined) { + for (const language of this.autoDetectSourceLanguages.split(",")) { + const customProperty = language + Exports_js_1.PropertyId.SpeechServiceConnection_EndpointId.toString(); + const modelId = this.parameters.getProperty(customProperty, undefined); + if (modelId !== undefined) { + models.push({ language, endpoint: modelId }); + modelsExist = true; + } + else { + models.push({ language, endpoint: "" }); + } + } } - return retObj; - }; - return DynamicGrammarBuilder; -}()); -exports.DynamicGrammarBuilder = DynamicGrammarBuilder; + return modelsExist ? models : undefined; + } + get maxRetryCount() { + return this.privMaxRetryCount; + } + get isSpeakerDiarizationEnabled() { + return this.privEnableSpeakerId; + } + set isSpeakerDiarizationEnabled(value) { + this.privEnableSpeakerId = value; + } +} +exports.RecognizerConfig = RecognizerConfig; /***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { +/* 204 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { +/* 205 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DialogServiceAdapter = void 0; -var Exports_1 = __webpack_require__(2); -var DialogEvents_1 = __webpack_require__(27); -var Exports_2 = __webpack_require__(4); -var AudioOutputFormat_1 = __webpack_require__(74); -var Exports_3 = __webpack_require__(61); -var DialogServiceTurnStateManager_1 = __webpack_require__(203); -var Exports_4 = __webpack_require__(53); -var ActivityResponsePayload_1 = __webpack_require__(205); -var SpeechConnectionMessage_Internal_1 = __webpack_require__(173); -var DialogServiceAdapter = /** @class */ (function (_super) { - __extends(DialogServiceAdapter, _super); - function DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector) { - var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector) || this; - _this.sendAgentConfig = function (connection) { - if (_this.agentConfig && !_this.agentConfigSent) { - if (_this.privRecognizerConfig - .parameters - .getProperty(Exports_3.PropertyId.Conversation_DialogType) === Exports_3.DialogServiceConfig.DialogTypes.CustomCommands) { - var config = _this.agentConfig.get(); - config.botInfo.commandsCulture = _this.privRecognizerConfig.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-us"); - _this.agentConfig.set(config); - } - _this.onEvent(new DialogEvents_1.SendingAgentContextMessageEvent(_this.agentConfig)); - var agentConfigJson = _this.agentConfig.toJsonString(); - // guard against sending this multiple times on one connection - _this.agentConfigSent = true; - return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "agent.config", _this.privRequestSession.requestId, "application/json", agentConfigJson)); - } - return; - }; - _this.sendAgentContext = function (connection) { - var guid = Exports_2.createGuid(); - var speechActivityTemplate = _this.privDialogServiceConnector.properties.getProperty(Exports_3.PropertyId.Conversation_Speech_Activity_Template); - var agentContext = { - channelData: "", - context: { - interactionId: guid - }, - messagePayload: typeof speechActivityTemplate === undefined ? undefined : speechActivityTemplate, - version: 0.5 - }; - var agentContextJson = JSON.stringify(agentContext); - return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "speech.agent.context", _this.privRequestSession.requestId, "application/json", agentContextJson)); - }; - _this.handleResponseMessage = function (responseMessage) { - // "response" messages can contain either "message" (activity) or "MessageStatus" data. Fire the appropriate - // event according to the message type that's specified. - var responsePayload = JSON.parse(responseMessage.textBody); - switch (responsePayload.messageType.toLowerCase()) { - case "message": - var responseRequestId = responseMessage.requestId.toUpperCase(); - var activityPayload = ActivityResponsePayload_1.ActivityPayloadResponse.fromJSON(responseMessage.textBody); - var turn = _this.privTurnStateManager.GetTurn(responseRequestId); - // update the conversation Id - if (activityPayload.conversationId) { - var updateAgentConfig = _this.agentConfig.get(); - updateAgentConfig.botInfo.conversationId = activityPayload.conversationId; - _this.agentConfig.set(updateAgentConfig); - } - var pullAudioOutputStream = turn.processActivityPayload(activityPayload, AudioOutputFormat_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(_this.privDialogServiceConnector.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined))); - var activity = new Exports_3.ActivityReceivedEventArgs(activityPayload.messagePayload, pullAudioOutputStream); - if (!!_this.privDialogServiceConnector.activityReceived) { - try { - _this.privDialogServiceConnector.activityReceived(_this.privDialogServiceConnector, activity); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - break; - case "messagestatus": - if (!!_this.privDialogServiceConnector.turnStatusReceived) { - try { - _this.privDialogServiceConnector.turnStatusReceived(_this.privDialogServiceConnector, new Exports_3.TurnStatusReceivedEventArgs(responseMessage.textBody)); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebsocketMessageFormatter = void 0; +const Exports_js_1 = __webpack_require__(4); +const CRLF = "\r\n"; +class WebsocketMessageFormatter { + toConnectionMessage(message) { + const deferral = new Exports_js_1.Deferred(); + try { + if (message.messageType === Exports_js_1.MessageType.Text) { + const textMessage = message.textContent; + let headers = {}; + let body = null; + if (textMessage) { + const headerBodySplit = textMessage.split("\r\n\r\n"); + if (headerBodySplit && headerBodySplit.length > 0) { + headers = this.parseHeaders(headerBodySplit[0]); + if (headerBodySplit.length > 1) { + body = headerBodySplit[1]; } } - break; - default: - Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent("Unexpected response of type " + responsePayload.messageType + ". Ignoring.")); - break; - } - }; - _this.privEvents = new Exports_2.EventSource(); - _this.privDialogServiceConnector = dialogServiceConnector; - _this.receiveMessageOverride = _this.receiveDialogMessageOverride; - _this.privTurnStateManager = new DialogServiceTurnStateManager_1.DialogServiceTurnStateManager(); - _this.recognizeOverride = _this.listenOnce; - _this.postConnectImplOverride = _this.dialogConnectImpl; - _this.configConnectionOverride = _this.configConnection; - _this.disconnectOverride = _this.privDisconnect; - _this.privDialogAudioSource = audioSource; - _this.agentConfigSent = false; - _this.privLastResult = null; - _this.connectionEvents.attach(function (connectionEvent) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - if (connectionEvent.name === "ConnectionClosedEvent") { - this.terminateMessageLoop = true; - } - return [2 /*return*/]; - }); - }); }); - return _this; - } - DialogServiceAdapter.prototype.sendMessage = function (message) { - return __awaiter(this, void 0, void 0, function () { - var interactionGuid, requestId, agentMessage, agentMessageJson, connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - interactionGuid = Exports_2.createGuid(); - requestId = Exports_2.createNoDashGuid(); - agentMessage = { - context: { - interactionId: interactionGuid - }, - messagePayload: JSON.parse(message), - version: 0.5 - }; - agentMessageJson = JSON.stringify(agentMessage); - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [4 /*yield*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "agent", requestId, "application/json", agentMessageJson))]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - DialogServiceAdapter.prototype.privDisconnect = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.NoError, "Disconnecting")]; - case 1: - _a.sent(); - this.terminateMessageLoop = true; - this.agentConfigSent = false; - return [2 /*return*/]; } - }); - }); - }; - DialogServiceAdapter.prototype.processTypeSpecificMessages = function (connectionMessage) { - return __awaiter(this, void 0, void 0, function () { - var resultProps, result, processed, speechPhrase, args, hypothesis, offset, ev, keyword, event_1, audioRequestId, turn; - return __generator(this, function (_a) { - resultProps = new Exports_3.PropertyCollection(); - if (connectionMessage.messageType === Exports_2.MessageType.Text) { - resultProps.setProperty(Exports_3.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody); + deferral.resolve(new Exports_js_1.ConnectionMessage(message.messageType, body, headers, message.id)); + } + else if (message.messageType === Exports_js_1.MessageType.Binary) { + const binaryMessage = message.binaryContent; + let headers = {}; + let body = null; + if (!binaryMessage || binaryMessage.byteLength < 2) { + throw new Error("Invalid binary message format. Header length missing."); } - switch (connectionMessage.path.toLowerCase()) { - case "speech.phrase": - speechPhrase = Exports_4.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody); - this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + speechPhrase.Offset + speechPhrase.Duration); - if (speechPhrase.RecognitionStatus !== Exports_4.RecognitionStatus.TooManyRequests && speechPhrase.RecognitionStatus !== Exports_4.RecognitionStatus.Error) { - args = this.fireEventForResult(speechPhrase, resultProps); - this.privLastResult = args.result; - if (!!this.privDialogServiceConnector.recognized) { - try { - this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, args); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - } - processed = true; - break; - case "speech.hypothesis": - hypothesis = Exports_4.SpeechHypothesis.fromJSON(connectionMessage.textBody); - offset = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset; - result = new Exports_3.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_3.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, undefined, undefined, connectionMessage.textBody, resultProps); - this.privRequestSession.onHypothesis(offset); - ev = new Exports_3.SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId); - if (!!this.privDialogServiceConnector.recognizing) { - try { - this.privDialogServiceConnector.recognizing(this.privDialogServiceConnector, ev); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - processed = true; - break; - case "speech.keyword": - keyword = Exports_4.SpeechKeyword.fromJSON(connectionMessage.textBody); - result = new Exports_3.SpeechRecognitionResult(this.privRequestSession.requestId, keyword.Status === "Accepted" ? Exports_3.ResultReason.RecognizedKeyword : Exports_3.ResultReason.NoMatch, keyword.Text, keyword.Duration, keyword.Offset, undefined, undefined, undefined, undefined, connectionMessage.textBody, resultProps); - if (keyword.Status !== "Accepted") { - this.privLastResult = result; - } - event_1 = new Exports_3.SpeechRecognitionEventArgs(result, result.duration, result.resultId); - if (!!this.privDialogServiceConnector.recognized) { - try { - this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, event_1); - /* tslint:disable:no-empty */ - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - processed = true; - break; - case "audio": - { - audioRequestId = connectionMessage.requestId.toUpperCase(); - turn = this.privTurnStateManager.GetTurn(audioRequestId); - try { - // Empty binary message signals end of stream. - if (!connectionMessage.binaryBody) { - turn.endAudioStream(); - } - else { - turn.audioStream.write(connectionMessage.binaryBody); - } - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - processed = true; - break; - case "response": - { - this.handleResponseMessage(connectionMessage); - } - processed = true; - break; - default: - break; + const dataView = new DataView(binaryMessage); + const headerLength = dataView.getInt16(0); + if (binaryMessage.byteLength < headerLength + 2) { + throw new Error("Invalid binary message format. Header content missing."); } - return [2 /*return*/, processed]; - }); - }); - }; - // Cancels recognition. - DialogServiceAdapter.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) { - return __awaiter(this, void 0, void 0, function () { - var properties, cancelEvent, result; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.terminateMessageLoop = true; - if (!!!this.privRequestSession.isRecognizing) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privRequestSession.onStopRecognizing()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - if (!!this.privDialogServiceConnector.canceled) { - properties = new Exports_3.PropertyCollection(); - properties.setProperty(Exports_4.CancellationErrorCodePropertyName, Exports_3.CancellationErrorCode[errorCode]); - cancelEvent = new Exports_3.SpeechRecognitionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId); - try { - this.privDialogServiceConnector.canceled(this.privDialogServiceConnector, cancelEvent); - /* tslint:disable:no-empty */ - } - catch (_b) { } - if (!!this.privSuccessCallback) { - result = new Exports_3.SpeechRecognitionResult(undefined, // ResultId - Exports_3.ResultReason.Canceled, undefined, // Text - undefined, // Duration - undefined, // Offset - undefined, // Language - undefined, // Language Detection Confidence - undefined, // Speaker Id - error, undefined, // Json - properties); - try { - this.privSuccessCallback(result); - this.privSuccessCallback = undefined; - /* tslint:disable:no-empty */ - } - catch (_c) { } - } - } - return [2 /*return*/]; + let headersString = ""; + for (let i = 0; i < headerLength; i++) { + headersString += String.fromCharCode((dataView).getInt8(i + 2)); } - }); - }); - }; - DialogServiceAdapter.prototype.listenOnce = function (recoMode, successCallback, errorCallback) { - return __awaiter(this, void 0, void 0, function () { - var conPromise, preAudioPromise, node, format, deviceInfo, audioNode, error_1, sessionStartEventArgs, audioSendPromise; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privRecognizerConfig.recognitionMode = recoMode; - this.privSuccessCallback = successCallback; - this.privErrorCallback = errorCallback; - this.privRequestSession.startNewRecognition(); - this.privRequestSession.listenForServiceTelemetry(this.privDialogAudioSource.events); - this.privRecognizerConfig.parameters.setProperty(Exports_3.PropertyId.Speech_SessionId, this.privRequestSession.sessionId); - conPromise = this.connectImpl(); - preAudioPromise = this.sendPreAudioMessages(); - return [4 /*yield*/, this.privDialogAudioSource.attach(this.privRequestSession.audioNodeId)]; - case 1: - node = _a.sent(); - return [4 /*yield*/, this.privDialogAudioSource.format]; - case 2: - format = _a.sent(); - return [4 /*yield*/, this.privDialogAudioSource.deviceInfo]; - case 3: - deviceInfo = _a.sent(); - audioNode = new Exports_1.ReplayableAudioNode(node, format.avgBytesPerSec); - return [4 /*yield*/, this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false)]; - case 4: - _a.sent(); - this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo }; - _a.label = 5; - case 5: - _a.trys.push([5, 8, , 10]); - return [4 /*yield*/, conPromise]; - case 6: - _a.sent(); - return [4 /*yield*/, preAudioPromise]; - case 7: - _a.sent(); - return [3 /*break*/, 10]; - case 8: - error_1 = _a.sent(); - return [4 /*yield*/, this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.ConnectionFailure, error_1)]; - case 9: - _a.sent(); - return [2 /*return*/, Promise.resolve()]; - case 10: - sessionStartEventArgs = new Exports_3.SessionEventArgs(this.privRequestSession.sessionId); - if (!!this.privRecognizer.sessionStarted) { - this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs); - } - audioSendPromise = this.sendAudio(audioNode); - // /* tslint:disable:no-empty */ - audioSendPromise.then(function () { }, function (error) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.RuntimeError, error)]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); }); - return [2 /*return*/]; + headers = this.parseHeaders(headersString); + if (binaryMessage.byteLength > headerLength + 2) { + body = binaryMessage.slice(2 + headerLength); } - }); - }); - }; - // Establishes a websocket connection to the end point. - DialogServiceAdapter.prototype.dialogConnectImpl = function (connection) { - this.privConnectionLoop = this.startMessageLoop(); - return connection; - }; - DialogServiceAdapter.prototype.receiveDialogMessageOverride = function () { - var _this = this; - // we won't rely on the cascading promises of the connection since we want to continually be available to receive messages - var communicationCustodian = new Exports_2.Deferred(); - var loop = function () { return __awaiter(_this, void 0, void 0, function () { - var isDisposed, terminateMessageLoop, connection, message, connectionMessage, _a, turnRequestId, audioSessionReqId, speechStartDetected, speechStartEventArgs, json, speechStopDetected, speechStopEventArgs, turnEndRequestId, audioSessionReqId, sessionStopEventArgs, ret, error_2; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 12, , 13]); - isDisposed = this.isDisposed(); - terminateMessageLoop = (!this.isDisposed() && this.terminateMessageLoop); - if (isDisposed || terminateMessageLoop) { - // We're done. - communicationCustodian.resolve(undefined); - return [2 /*return*/]; - } - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _b.sent(); - return [4 /*yield*/, connection.read()]; - case 2: - message = _b.sent(); - if (!message) { - return [2 /*return*/, loop()]; - } - connectionMessage = SpeechConnectionMessage_Internal_1.SpeechConnectionMessage.fromConnectionMessage(message); - _a = connectionMessage.path.toLowerCase(); - switch (_a) { - case "turn.start": return [3 /*break*/, 3]; - case "speech.startdetected": return [3 /*break*/, 4]; - case "speech.enddetected": return [3 /*break*/, 5]; - case "turn.end": return [3 /*break*/, 6]; - } - return [3 /*break*/, 10]; - case 3: - { - turnRequestId = connectionMessage.requestId.toUpperCase(); - audioSessionReqId = this.privRequestSession.requestId.toUpperCase(); - // turn started by the service - if (turnRequestId !== audioSessionReqId) { - this.privTurnStateManager.StartTurn(turnRequestId); - } - else { - this.privRequestSession.onServiceTurnStartResponse(); - } - } - return [3 /*break*/, 11]; - case 4: - speechStartDetected = Exports_4.SpeechDetected.fromJSON(connectionMessage.textBody); - speechStartEventArgs = new Exports_3.RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId); - if (!!this.privRecognizer.speechStartDetected) { - this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs); - } - return [3 /*break*/, 11]; - case 5: - json = void 0; - if (connectionMessage.textBody.length > 0) { - json = connectionMessage.textBody; - } - else { - // If the request was empty, the JSON returned is empty. - json = "{ Offset: 0 }"; - } - speechStopDetected = Exports_4.SpeechDetected.fromJSON(json); - this.privRequestSession.onServiceRecognized(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset); - speechStopEventArgs = new Exports_3.RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId); - if (!!this.privRecognizer.speechEndDetected) { - this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs); - } - return [3 /*break*/, 11]; - case 6: - turnEndRequestId = connectionMessage.requestId.toUpperCase(); - audioSessionReqId = this.privRequestSession.requestId.toUpperCase(); - if (!(turnEndRequestId !== audioSessionReqId)) return [3 /*break*/, 7]; - this.privTurnStateManager.CompleteTurn(turnEndRequestId); - return [3 /*break*/, 9]; - case 7: - sessionStopEventArgs = new Exports_3.SessionEventArgs(this.privRequestSession.sessionId); - return [4 /*yield*/, this.privRequestSession.onServiceTurnEndResponse(false)]; - case 8: - _b.sent(); - if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) { - if (!!this.privRecognizer.sessionStopped) { - this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs); - } - } - // report result to promise. - if (!!this.privSuccessCallback && this.privLastResult) { - try { - this.privSuccessCallback(this.privLastResult); - this.privLastResult = null; - } - catch (e) { - if (!!this.privErrorCallback) { - this.privErrorCallback(e); - } - } - // Only invoke the call back once. - // and if it's successful don't invoke the - // error after that. - this.privSuccessCallback = undefined; - this.privErrorCallback = undefined; - } - _b.label = 9; - case 9: return [3 /*break*/, 11]; - case 10: - if (!this.processTypeSpecificMessages(connectionMessage)) { - if (!!this.serviceEvents) { - this.serviceEvents.onEvent(new Exports_2.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody)); - } - } - _b.label = 11; - case 11: - ret = loop(); - return [2 /*return*/, ret]; - case 12: - error_2 = _b.sent(); - this.terminateMessageLoop = true; - communicationCustodian.resolve(); - return [3 /*break*/, 13]; - case 13: return [2 /*return*/]; + deferral.resolve(new Exports_js_1.ConnectionMessage(message.messageType, body, headers, message.id)); + } + } + catch (e) { + deferral.reject(`Error formatting the message. Error: ${e}`); + } + return deferral.promise; + } + fromConnectionMessage(message) { + const deferral = new Exports_js_1.Deferred(); + try { + if (message.messageType === Exports_js_1.MessageType.Text) { + const payload = `${this.makeHeaders(message)}${CRLF}${message.textBody ? message.textBody : ""}`; + deferral.resolve(new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Text, payload, message.id)); + } + else if (message.messageType === Exports_js_1.MessageType.Binary) { + const headersString = this.makeHeaders(message); + const content = message.binaryBody; + const headerBuffer = this.stringToArrayBuffer(headersString); + const headerInt8Array = new Int8Array(headerBuffer); + const headerLength = headerInt8Array.byteLength; + const payloadInt8Array = new Int8Array(2 + headerLength + (content ? content.byteLength : 0)); + payloadInt8Array[0] = ((headerLength >> 8) & 0xff); + payloadInt8Array[1] = headerLength & 0xff; + payloadInt8Array.set(headerInt8Array, 2); + if (content) { + const bodyInt8Array = new Int8Array(content); + payloadInt8Array.set(bodyInt8Array, 2 + headerLength); + } + const payload = payloadInt8Array.buffer; + deferral.resolve(new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Binary, payload, message.id)); + } + } + catch (e) { + deferral.reject(`Error formatting the message. ${e}`); + } + return deferral.promise; + } + makeHeaders(message) { + let headersString = ""; + if (message.headers) { + for (const header in message.headers) { + if (header) { + headersString += `${header}: ${message.headers[header]}${CRLF}`; } - }); - }); }; - loop().catch(function (reason) { - Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason)); - }); - return communicationCustodian.promise; - }; - DialogServiceAdapter.prototype.startMessageLoop = function () { - return __awaiter(this, void 0, void 0, function () { - var error_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.terminateMessageLoop = false; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 5]); - return [4 /*yield*/, this.receiveDialogMessageOverride()]; - case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: - error_3 = _a.sent(); - return [4 /*yield*/, this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.RuntimeError, error_3)]; - case 4: - _a.sent(); - return [3 /*break*/, 5]; - case 5: return [2 /*return*/, Promise.resolve()]; + } + } + return headersString; + } + parseHeaders(headersString) { + const headers = {}; + if (headersString) { + const headerMatches = headersString.match(/[^\r\n]+/g); + if (headers) { + for (const header of headerMatches) { + if (header) { + const separatorIndex = header.indexOf(":"); + const headerName = separatorIndex > 0 ? header.substr(0, separatorIndex).trim().toLowerCase() : header; + const headerValue = separatorIndex > 0 && header.length > (separatorIndex + 1) ? + header.substr(separatorIndex + 1).trim() : + ""; + headers[headerName] = headerValue; + } } - }); - }); - }; - // Takes an established websocket connection to the endpoint and sends speech configuration information. - DialogServiceAdapter.prototype.configConnection = function (connection) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.terminateMessageLoop) { - this.terminateMessageLoop = false; - return [2 /*return*/, Promise.reject("Connection to service terminated.")]; + } + } + return headers; + } + stringToArrayBuffer(str) { + const buffer = new ArrayBuffer(str.length); + const view = new DataView(buffer); + for (let i = 0; i < str.length; i++) { + view.setUint8(i, str.charCodeAt(i)); + } + return buffer; + } +} +exports.WebsocketMessageFormatter = WebsocketMessageFormatter; + + + +/***/ }), +/* 206 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechConnectionFactory = void 0; +const Exports_js_1 = __webpack_require__(66); +const Exports_js_2 = __webpack_require__(2); +const Exports_js_3 = __webpack_require__(85); +const ConnectionFactoryBase_js_1 = __webpack_require__(135); +const Exports_js_4 = __webpack_require__(2); +const HeaderNames_js_1 = __webpack_require__(59); +const QueryParameterNames_js_1 = __webpack_require__(136); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +class SpeechConnectionFactory extends ConnectionFactoryBase_js_1.ConnectionFactoryBase { + constructor() { + super(...arguments); + this.interactiveRelativeUri = "/speech/recognition/interactive/cognitiveservices/v1"; + this.conversationRelativeUri = "/speech/recognition/conversation/cognitiveservices/v1"; + this.dictationRelativeUri = "/speech/recognition/dictation/cognitiveservices/v1"; + this.universalUri = "/stt/speech/universal/v"; + } + async create(config, authInfo, connectionId) { + let endpoint = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Endpoint, undefined); + const region = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Region, undefined); + const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region); + const host = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".stt.speech" + hostSuffix); + const queryParams = {}; + const endpointId = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_EndpointId, undefined); + const language = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, undefined); + // The multichannel reliable-reconnect protocol expects a bare v2 URL: the service omits + // continuation headers when "format"/"language" query params are present, so drop them + // here and let the language travel inside speech.config / speech.context instead. + const multiChannelReconnect = config.parameters.getProperty(Exports_js_3.PropertyId.Speech_EnableMultiChannelProcessing, "false").toLowerCase() === "true"; + if (endpointId) { + if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId) === -1) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId; + } + } + else if (language && !multiChannelReconnect) { + if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.Language) === -1) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.Language] = language; + } + } + if (!multiChannelReconnect && (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.Format) === -1)) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.Format] = config.parameters.getProperty(Exports_js_2.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]).toLowerCase(); + } + if (config.autoDetectSourceLanguages !== undefined) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.EnableLanguageId] = "true"; + } + this.setCommonUrlParams(config, queryParams, endpoint); + if (!!endpoint) { + const endpointUrl = new URL(endpoint); + const pathName = endpointUrl.pathname; + if (pathName === "" || pathName === "/") { + // We need to generate the path, and we need to check for a redirect. + endpointUrl.pathname = this.universalUri + config.recognitionEndpointVersion; + endpoint = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString()); + } + } + if (!endpoint) { + switch (config.recognitionMode) { + case PhraseDetectionContext_js_1.RecognitionMode.Conversation: + if (config.parameters.getProperty(Exports_js_2.ForceDictationPropertyName, "false") === "true") { + endpoint = host + this.dictationRelativeUri; + } + else { + if (config.recognitionEndpointVersion !== undefined && parseInt(config.recognitionEndpointVersion, 10) > 1) { + endpoint = `${host}${this.universalUri}${config.recognitionEndpointVersion}`; + } + else { + endpoint = host + this.conversationRelativeUri; } - return [4 /*yield*/, this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize())]; - case 1: - _a.sent(); - return [4 /*yield*/, this.sendAgentConfig(connection)]; - case 2: - _a.sent(); - return [2 /*return*/, connection]; + } + break; + case PhraseDetectionContext_js_1.RecognitionMode.Dictation: + endpoint = host + this.dictationRelativeUri; + break; + default: + if (config.recognitionEndpointVersion !== undefined && parseInt(config.recognitionEndpointVersion, 10) > 1) { + endpoint = `${host}${this.universalUri}${config.recognitionEndpointVersion}`; + } + else { + endpoint = host + this.interactiveRelativeUri; // default is interactive + } + break; + } + } + const headers = {}; + if (authInfo.token !== undefined && authInfo.token !== "") { + headers[authInfo.headerName] = authInfo.token; + } + headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId; + headers.connectionId = connectionId; + const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; + const webSocketConnection = new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_4.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); + // Set the value of SpeechServiceConnection_Url to webSocketConnection.uri (and not to `endpoint`), since this value is the final + // URI that was used to make the connection (including query parameters). + const uri = webSocketConnection.uri; + config.parameters.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Url, uri); + return webSocketConnection; + } +} +exports.SpeechConnectionFactory = SpeechConnectionFactory; + + + +/***/ }), +/* 207 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationTranscriberConnectionFactory = void 0; +const Exports_js_1 = __webpack_require__(66); +const Exports_js_2 = __webpack_require__(85); +const Exports_js_3 = __webpack_require__(2); +const ConnectionFactoryBase_js_1 = __webpack_require__(135); +const Exports_js_4 = __webpack_require__(2); +const HeaderNames_js_1 = __webpack_require__(59); +const QueryParameterNames_js_1 = __webpack_require__(136); +class ConversationTranscriberConnectionFactory extends ConnectionFactoryBase_js_1.ConnectionFactoryBase { + constructor() { + super(...arguments); + this.universalUri = "/stt/speech/universal/v2"; + this.conversationRelativeUriV1 = "/speech/recognition/conversation/cognitiveservices/v1"; + } + async create(config, authInfo, connectionId) { + let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); + const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, undefined); + const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region); + const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".stt.speech" + hostSuffix); + const queryParams = {}; + const endpointId = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, undefined); + const language = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, undefined); + if (endpointId) { + if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId) === -1) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId; + } + } + else if (language) { + if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.Language) === -1) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.Language] = language; + } + } + if (config.autoDetectSourceLanguages !== undefined) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.EnableLanguageId] = "true"; + } + const apiVersion = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, undefined); + if (apiVersion === "1") { + endpoint = `${host}${this.universalUri}`; + } + else { + this.setV2UrlParams(config, queryParams, endpoint); + if (!!endpoint) { + const endpointUrl = new URL(endpoint); + const pathName = endpointUrl.pathname; + if (pathName === "" || pathName === "/") { + // We need to generate the path, and we need to check for a redirect. + endpointUrl.pathname = this.universalUri; + endpoint = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString()); } - }); + } + if (!endpoint) { + endpoint = `${host}${this.conversationRelativeUriV1}`; + } + } + const headers = {}; + if (authInfo.token !== undefined && authInfo.token !== "") { + headers[authInfo.headerName] = authInfo.token; + } + headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId; + const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; + const webSocketConnection = new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_4.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); + // Set the value of SpeechServiceConnection_Url to webSocketConnection.uri (and not to `endpoint`), since this value is the final + // URI that was used to make the connection (including query parameters). + const uri = webSocketConnection.uri; + config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, uri); + return webSocketConnection; + } + setV2UrlParams(config, queryParams, endpoint) { + const propertyIdToParameterMap = new Map([ + [Exports_js_2.PropertyId.Speech_SegmentationSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.SegmentationSilenceTimeoutMs], + [Exports_js_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, QueryParameterNames_js_1.QueryParameterNames.EnableAudioLogging], + [Exports_js_2.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.EndSilenceTimeoutMs], + [Exports_js_2.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.InitialSilenceTimeoutMs], + [Exports_js_2.PropertyId.SpeechServiceResponse_ProfanityOption, QueryParameterNames_js_1.QueryParameterNames.Profanity], + [Exports_js_2.PropertyId.SpeechServiceResponse_StablePartialResultThreshold, QueryParameterNames_js_1.QueryParameterNames.StableIntermediateThreshold], + ]); + propertyIdToParameterMap.forEach((parameterName, propertyId) => { + this.setUrlParameter(propertyId, parameterName, config, queryParams, endpoint); }); - }; - DialogServiceAdapter.prototype.sendPreAudioMessages = function () { - return __awaiter(this, void 0, void 0, function () { - var connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - this.addKeywordContextData(); - return [4 /*yield*/, this.sendSpeechContext(connection)]; - case 2: - _a.sent(); - return [4 /*yield*/, this.sendAgentContext(connection)]; - case 3: - _a.sent(); - return [4 /*yield*/, this.sendWaveHeader(connection)]; - case 4: - _a.sent(); - return [2 /*return*/]; - } - }); + const serviceProperties = JSON.parse(config.parameters.getProperty(Exports_js_3.ServicePropertiesPropertyName, "{}")); + Object.keys(serviceProperties).forEach((value) => { + queryParams[value] = serviceProperties[value]; }); - }; - DialogServiceAdapter.prototype.fireEventForResult = function (serviceResult, properties) { - var resultReason = Exports_4.EnumTranslation.implTranslateRecognitionResult(serviceResult.RecognitionStatus); - var offset = serviceResult.Offset + this.privRequestSession.currentTurnAudioOffset; - var result = new Exports_3.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, serviceResult.DisplayText, serviceResult.Duration, offset, serviceResult.Language, serviceResult.LanguageDetectionConfidence, undefined, undefined, JSON.stringify(serviceResult), properties); - var ev = new Exports_3.SpeechRecognitionEventArgs(result, offset, this.privRequestSession.sessionId); - return ev; - }; - DialogServiceAdapter.prototype.onEvent = function (event) { - this.privEvents.onEvent(event); - Exports_2.Events.instance.onEvent(event); - }; - DialogServiceAdapter.prototype.addKeywordContextData = function () { - var keywordPropertyValue = this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect"); - if (keywordPropertyValue === undefined) { - return; + } +} +exports.ConversationTranscriberConnectionFactory = ConversationTranscriberConnectionFactory; + + + +/***/ }), +/* 208 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranscriberConnectionFactory = void 0; +const Exports_js_1 = __webpack_require__(66); +const Exports_js_2 = __webpack_require__(85); +const ConnectionFactoryBase_js_1 = __webpack_require__(135); +const Exports_js_3 = __webpack_require__(2); +const HeaderNames_js_1 = __webpack_require__(59); +const QueryParameterNames_js_1 = __webpack_require__(136); +class TranscriberConnectionFactory extends ConnectionFactoryBase_js_1.ConnectionFactoryBase { + constructor() { + super(...arguments); + this.multiaudioRelativeUri = "/speech/recognition/multiaudio"; + } + create(config, authInfo, connectionId) { + let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); + const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, "centralus"); + const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region); + const hostDefault = "wss://transcribe." + region + ".cts.speech" + hostSuffix + this.multiaudioRelativeUri; + const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, hostDefault); + const queryParams = {}; + this.setQueryParams(queryParams, config, endpoint); + if (!endpoint) { + endpoint = host; } - var keywordOffsetPropertyValue = this.privRecognizerConfig.parameters - .getProperty("SPEECH-KeywordsToDetect-Offsets"); - var keywordDurationPropertyValue = this.privRecognizerConfig.parameters - .getProperty("SPEECH-KeywordsToDetect-Durations"); - var keywords = keywordPropertyValue.split(";"); - var keywordOffsets = keywordOffsetPropertyValue === undefined ? [] : keywordOffsetPropertyValue.split(";"); - var keywordDurations = keywordDurationPropertyValue === undefined ? [] : keywordDurationPropertyValue.split(";"); - var keywordDefinitionArray = []; - for (var i = 0; i < keywords.length; i++) { - var definition = {}; - definition.text = keywords[i]; - if (i < keywordOffsets.length) { - definition.offset = Number(keywordOffsets[i]); - } - if (i < keywordDurations.length) { - definition.duration = Number(keywordDurations[i]); + const headers = {}; + if (authInfo.token !== undefined && authInfo.token !== "") { + headers[authInfo.headerName] = authInfo.token; + } + headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId; + config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, endpoint); + const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; + return Promise.resolve(new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId)); + } + setQueryParams(queryParams, config, endpointUrl) { + const endpointId = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, undefined); + const language = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, undefined); + if (endpointId && !(QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId in queryParams)) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId; + } + if (language && !(QueryParameterNames_js_1.QueryParameterNames.Language in queryParams)) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.Language] = language; + } + const wordLevelTimings = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "false").toLowerCase() === "true"; + const detailed = config.parameters.getProperty(Exports_js_3.OutputFormatPropertyName, Exports_js_2.OutputFormat[Exports_js_2.OutputFormat.Simple]) !== Exports_js_2.OutputFormat[Exports_js_2.OutputFormat.Simple]; + if (wordLevelTimings || detailed) { + queryParams[QueryParameterNames_js_1.QueryParameterNames.Format] = Exports_js_2.OutputFormat[Exports_js_2.OutputFormat.Detailed].toLowerCase(); + } + this.setCommonUrlParams(config, queryParams, endpointUrl); + } +} +exports.TranscriberConnectionFactory = TranscriberConnectionFactory; + + + +/***/ }), +/* 209 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranslationConnectionFactory = void 0; +const Exports_js_1 = __webpack_require__(66); +const StringUtils_js_1 = __webpack_require__(210); +const Exports_js_2 = __webpack_require__(85); +const ConnectionFactoryBase_js_1 = __webpack_require__(135); +const Exports_js_3 = __webpack_require__(2); +const HeaderNames_js_1 = __webpack_require__(59); +const QueryParameterNames_js_1 = __webpack_require__(136); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +class TranslationConnectionFactory extends ConnectionFactoryBase_js_1.ConnectionFactoryBase { + constructor() { + super(...arguments); + this.universalUri = "/stt/speech/universal/v2"; + this.translationV1Uri = "/speech/translation/cognitiveservices/v1"; + } + async create(config, authInfo, connectionId) { + let endpoint = this.getEndpointUrl(config); + const queryParams = {}; + // Determine if we're using V1 or V2 endpoint + this.setQueryParams(queryParams, config, endpoint); + if (!!endpoint) { + const endpointUrl = new URL(endpoint); + const pathName = endpointUrl.pathname; + if (pathName === "" || pathName === "/") { + // We need to generate the path, and we need to check for a redirect. + endpointUrl.pathname = this.universalUri; + endpoint = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString()); + } + } + const headers = {}; + if (authInfo.token !== undefined && authInfo.token !== "") { + headers[authInfo.headerName] = authInfo.token; + } + headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId; + config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, endpoint); + const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; + const webSocketConnection = new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); + return webSocketConnection; + } + getEndpointUrl(config, returnRegionPlaceholder) { + const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region); + const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region); + // First check for an explicitly specified endpoint + let endpointUrl = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); + // If an explicit endpoint is provided, use it + if (endpointUrl) { + if (returnRegionPlaceholder === true) { + return endpointUrl; + } + return StringUtils_js_1.StringUtils.formatString(endpointUrl, { region }); + } + // Check if V1 endpoint is explicitly requested + const forceV1Endpoint = config.parameters.getProperty("SPEECH-ForceV1Endpoint", "false") === "true"; + if (forceV1Endpoint) { + // Use V1 endpoint with s2s.speech host + const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://{region}.s2s.speech" + hostSuffix); + endpointUrl = host + this.translationV1Uri; + } + else { + // Default to V2 endpoint with stt.speech host + const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://{region}.stt.speech" + hostSuffix); + endpointUrl = host + this.universalUri; + } + if (returnRegionPlaceholder === true) { + return endpointUrl; + } + return StringUtils_js_1.StringUtils.formatString(endpointUrl, { region }); + } + setQueryParams(queryParams, config, endpointUrl) { + // Common parameters for both V1 and V2 endpoints + queryParams.from = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage); + queryParams.to = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationToLanguages); + queryParams.scenario = config.recognitionMode === PhraseDetectionContext_js_1.RecognitionMode.Interactive ? "interactive" : + config.recognitionMode === PhraseDetectionContext_js_1.RecognitionMode.Conversation ? "conversation" : ""; + // Set common parameters + this.setCommonUrlParams(config, queryParams, endpointUrl); + this.setUrlParameter(Exports_js_2.PropertyId.SpeechServiceResponse_TranslationRequestStablePartialResult, QueryParameterNames_js_1.QueryParameterNames.StableTranslation, config, queryParams, endpointUrl); + // Handle translation voice if specified + const translationVoice = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationVoice, undefined); + if (translationVoice !== undefined) { + queryParams.voice = translationVoice; + queryParams.features = "requireVoice"; + } + } +} +exports.TranslationConnectionFactory = TranslationConnectionFactory; + + + +/***/ }), +/* 210 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StringUtils = void 0; +/** + * String helper functions + */ +class StringUtils { + /** + * Formats a string by replacing the named {keys} in the string with the values contained in the replacement dictionary. + * @param format The format string that contains the parts to replace surrounded by {}. For example: "wss://{region}.cts.speech.microsoft.com". + * If your string needs to contain a { or } you can use the {{ and }} escape sequences respectively. + * @param replacements The dictionary of replacements. If a replacement is not found, it is replaced with an empty string + * @returns The formatted string. If you pass in a null or undefined format string, an empty string will be returned + */ + static formatString(format, replacements) { + if (!format) { + return ""; + } + if (!replacements) { + return format; + } + let formatted = ""; + let key = ""; + const appendToFormatted = (str) => { + formatted += str; + }; + const appendToKey = (str) => { + key += str; + }; + let appendFunc = appendToFormatted; + for (let i = 0; i < format.length; i++) { + const c = format[i]; + const next = i + 1 < format.length ? format[i + 1] : ""; + switch (c) { + case "{": + if (next === "{") { + appendFunc("{"); + i++; + } + else { + appendFunc = appendToKey; + } + break; + case "}": + if (next === "}") { + appendFunc("}"); + i++; + } + else { + if (replacements.hasOwnProperty(key)) { + formatted += replacements[key]; + } + appendFunc = appendToFormatted; + key = ""; + } + break; + default: + appendFunc(c); + break; } - keywordDefinitionArray.push(definition); } - this.speechContext.setSection("invocationSource", "VoiceActivationWithKeyword"); - this.speechContext.setSection("keywordDetection", [{ - clientDetectedKeywords: keywordDefinitionArray, - onReject: { action: "EndOfTurn" }, - type: "startTrigger" - }]); - }; - return DialogServiceAdapter; -}(Exports_4.ServiceRecognizerBase)); -exports.DialogServiceAdapter = DialogServiceAdapter; + return formatted; + } +} +exports.StringUtils = StringUtils; /***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { +/* 211 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DialogServiceTurnStateManager = void 0; -var Error_1 = __webpack_require__(25); -var DialogServiceTurnState_1 = __webpack_require__(204); -var DialogServiceTurnStateManager = /** @class */ (function () { - function DialogServiceTurnStateManager() { - this.privTurnMap = new Map(); - return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.EnumTranslation = void 0; +const Exports_js_1 = __webpack_require__(85); +const Exports_js_2 = __webpack_require__(2); +class EnumTranslation { + static implTranslateRecognitionResult(recognitionStatus, expectEndOfDictation = false) { + let reason = Exports_js_1.ResultReason.Canceled; + switch (recognitionStatus) { + case Exports_js_2.RecognitionStatus.Success: + reason = Exports_js_1.ResultReason.RecognizedSpeech; + break; + case Exports_js_2.RecognitionStatus.EndOfDictation: + // If we need the result in EndOfDictation (typically some session level result), + // translate into RecognizedSpeech, otherwise NoMatch + reason = expectEndOfDictation ? Exports_js_1.ResultReason.RecognizedSpeech : Exports_js_1.ResultReason.NoMatch; + break; + case Exports_js_2.RecognitionStatus.NoMatch: + case Exports_js_2.RecognitionStatus.InitialSilenceTimeout: + case Exports_js_2.RecognitionStatus.BabbleTimeout: + reason = Exports_js_1.ResultReason.NoMatch; + break; + case Exports_js_2.RecognitionStatus.Error: + case Exports_js_2.RecognitionStatus.BadRequest: + case Exports_js_2.RecognitionStatus.Forbidden: + default: + reason = Exports_js_1.ResultReason.Canceled; + break; + } + return reason; } - DialogServiceTurnStateManager.prototype.StartTurn = function (id) { - if (this.privTurnMap.has(id)) { - throw new Error_1.InvalidOperationError("Service error: There is already a turn with id:" + id); + static implTranslateCancelResult(recognitionStatus) { + let reason = Exports_js_1.CancellationReason.EndOfStream; + switch (recognitionStatus) { + case Exports_js_2.RecognitionStatus.Success: + case Exports_js_2.RecognitionStatus.EndOfDictation: + case Exports_js_2.RecognitionStatus.NoMatch: + reason = Exports_js_1.CancellationReason.EndOfStream; + break; + case Exports_js_2.RecognitionStatus.InitialSilenceTimeout: + case Exports_js_2.RecognitionStatus.BabbleTimeout: + case Exports_js_2.RecognitionStatus.Error: + case Exports_js_2.RecognitionStatus.BadRequest: + case Exports_js_2.RecognitionStatus.Forbidden: + default: + reason = Exports_js_1.CancellationReason.Error; + break; } - var turnState = new DialogServiceTurnState_1.DialogServiceTurnState(this, id); - this.privTurnMap.set(id, turnState); - return this.privTurnMap.get(id); - }; - DialogServiceTurnStateManager.prototype.GetTurn = function (id) { - return this.privTurnMap.get(id); - }; - DialogServiceTurnStateManager.prototype.CompleteTurn = function (id) { - if (!this.privTurnMap.has(id)) { - throw new Error_1.InvalidOperationError("Service error: Received turn end for an unknown turn id:" + id); + return reason; + } + static implTranslateCancelErrorCode(recognitionStatus) { + let reason = Exports_js_1.CancellationErrorCode.NoError; + switch (recognitionStatus) { + case Exports_js_2.RecognitionStatus.Error: + reason = Exports_js_1.CancellationErrorCode.ServiceError; + break; + case Exports_js_2.RecognitionStatus.TooManyRequests: + reason = Exports_js_1.CancellationErrorCode.TooManyRequests; + break; + case Exports_js_2.RecognitionStatus.BadRequest: + reason = Exports_js_1.CancellationErrorCode.BadRequestParameters; + break; + case Exports_js_2.RecognitionStatus.Forbidden: + reason = Exports_js_1.CancellationErrorCode.Forbidden; + break; + default: + reason = Exports_js_1.CancellationErrorCode.NoError; + break; } - var turnState = this.privTurnMap.get(id); - turnState.complete(); - this.privTurnMap.delete(id); - return turnState; - }; - return DialogServiceTurnStateManager; -}()); -exports.DialogServiceTurnStateManager = DialogServiceTurnStateManager; + return reason; + } + static implTranslateErrorDetails(cancellationErrorCode) { + let errorDetails = "The speech service encountered an internal error and could not continue."; + switch (cancellationErrorCode) { + case Exports_js_1.CancellationErrorCode.Forbidden: + errorDetails = "The recognizer is using a free subscription that ran out of quota."; + break; + case Exports_js_1.CancellationErrorCode.BadRequestParameters: + errorDetails = "Invalid parameter or unsupported audio format in the request."; + break; + case Exports_js_1.CancellationErrorCode.TooManyRequests: + errorDetails = "The number of parallel requests exceeded the number of allowed concurrent transcriptions."; + break; + default: + break; + } + return errorDetails; + } +} +exports.EnumTranslation = EnumTranslation; + + + +/***/ }), +/* 212 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RecognitionStatus = exports.SynthesisStatus = void 0; +/** + * @class SynthesisStatus + * @private + */ +var SynthesisStatus; +(function (SynthesisStatus) { + /** + * The response contains valid audio data. + * @member SynthesisStatus.Success + */ + SynthesisStatus[SynthesisStatus["Success"] = 0] = "Success"; + /** + * Indicates the end of audio data. No valid audio data is included in the message. + * @member SynthesisStatus.SynthesisEnd + */ + SynthesisStatus[SynthesisStatus["SynthesisEnd"] = 1] = "SynthesisEnd"; + /** + * Indicates an error occurred during synthesis data processing. + * @member SynthesisStatus.Error + */ + SynthesisStatus[SynthesisStatus["Error"] = 2] = "Error"; +})(SynthesisStatus = exports.SynthesisStatus || (exports.SynthesisStatus = {})); +var RecognitionStatus; +(function (RecognitionStatus) { + RecognitionStatus[RecognitionStatus["Success"] = 0] = "Success"; + RecognitionStatus[RecognitionStatus["NoMatch"] = 1] = "NoMatch"; + RecognitionStatus[RecognitionStatus["InitialSilenceTimeout"] = 2] = "InitialSilenceTimeout"; + RecognitionStatus[RecognitionStatus["BabbleTimeout"] = 3] = "BabbleTimeout"; + RecognitionStatus[RecognitionStatus["Error"] = 4] = "Error"; + RecognitionStatus[RecognitionStatus["EndOfDictation"] = 5] = "EndOfDictation"; + RecognitionStatus[RecognitionStatus["TooManyRequests"] = 6] = "TooManyRequests"; + RecognitionStatus[RecognitionStatus["BadRequest"] = 7] = "BadRequest"; + RecognitionStatus[RecognitionStatus["Forbidden"] = 8] = "Forbidden"; +})(RecognitionStatus = exports.RecognitionStatus || (exports.RecognitionStatus = {})); /***/ }), -/* 204 */ -/***/ (function(module, exports, __webpack_require__) { +/* 213 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DialogServiceTurnState = void 0; -var AudioOutputFormat_1 = __webpack_require__(74); -var AudioOutputStream_1 = __webpack_require__(73); -var ActivityResponsePayload_1 = __webpack_require__(205); -var DialogServiceTurnState = /** @class */ (function () { - function DialogServiceTurnState(manager, requestId) { - this.privRequestId = requestId; - this.privIsCompleted = false; - this.privAudioStream = null; - this.privTurnManager = manager; - this.resetTurnEndTimeout(); - // tslint:disable-next-line:no-console - // console.info("DialogServiceTurnState debugturn start:" + this.privRequestId); - } - Object.defineProperty(DialogServiceTurnState.prototype, "audioStream", { - get: function () { - // Called when is needed to stream. - this.resetTurnEndTimeout(); - return this.privAudioStream; - }, - enumerable: false, - configurable: true - }); - DialogServiceTurnState.prototype.processActivityPayload = function (payload, audioFormat) { - if (payload.messageDataStreamType === ActivityResponsePayload_1.MessageDataStreamType.TextToSpeechAudio) { - this.privAudioStream = AudioOutputStream_1.AudioOutputStream.createPullStream(); - this.privAudioStream.format = (audioFormat !== undefined) ? audioFormat : AudioOutputFormat_1.AudioOutputFormatImpl.getDefaultOutputFormat(); - // tslint:disable-next-line:no-console - // console.info("Audio start debugturn:" + this.privRequestId); - } - return this.privAudioStream; - }; - DialogServiceTurnState.prototype.endAudioStream = function () { - if (this.privAudioStream !== null && !this.privAudioStream.isClosed) { - this.privAudioStream.close(); - } - }; - DialogServiceTurnState.prototype.complete = function () { - if (this.privTimeoutToken !== undefined) { - clearTimeout(this.privTimeoutToken); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranslationSynthesisEnd = void 0; +const Exports_js_1 = __webpack_require__(2); +class TranslationSynthesisEnd { + constructor(json) { + this.privSynthesisEnd = JSON.parse(json); + if (!!this.privSynthesisEnd.SynthesisStatus) { + this.privSynthesisEnd.SynthesisStatus = Exports_js_1.SynthesisStatus[this.privSynthesisEnd.SynthesisStatus]; } - this.endAudioStream(); - }; - DialogServiceTurnState.prototype.resetTurnEndTimeout = function () { - var _this = this; - if (this.privTimeoutToken !== undefined) { - clearTimeout(this.privTimeoutToken); + if (!!this.privSynthesisEnd.Status) { + this.privSynthesisEnd.SynthesisStatus = Exports_js_1.SynthesisStatus[this.privSynthesisEnd.Status]; } - // tslint:disable-next-line:no-console - // console.info("Timeout reset debugturn:" + this.privRequestId); - this.privTimeoutToken = setTimeout(function () { - // tslint:disable-next-line:no-console - // console.info("Timeout complete debugturn:" + this.privRequestId); - _this.privTurnManager.CompleteTurn(_this.privRequestId); - return; - }, 2000); - }; - return DialogServiceTurnState; -}()); -exports.DialogServiceTurnState = DialogServiceTurnState; - - - -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -// response -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MessageDataStreamType = exports.ActivityPayloadResponse = void 0; -var ActivityPayloadResponse = /** @class */ (function () { - function ActivityPayloadResponse(json) { - this.privActivityResponse = JSON.parse(json); } - ActivityPayloadResponse.fromJSON = function (json) { - return new ActivityPayloadResponse(json); - }; - Object.defineProperty(ActivityPayloadResponse.prototype, "conversationId", { - get: function () { - return this.privActivityResponse.conversationId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ActivityPayloadResponse.prototype, "messageDataStreamType", { - get: function () { - return this.privActivityResponse.messageDataStreamType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ActivityPayloadResponse.prototype, "messagePayload", { - get: function () { - return this.privActivityResponse.messagePayload; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ActivityPayloadResponse.prototype, "version", { - get: function () { - return this.privActivityResponse.version; - }, - enumerable: false, - configurable: true - }); - return ActivityPayloadResponse; -}()); -exports.ActivityPayloadResponse = ActivityPayloadResponse; -var MessageDataStreamType; -(function (MessageDataStreamType) { - MessageDataStreamType[MessageDataStreamType["None"] = 0] = "None"; - MessageDataStreamType[MessageDataStreamType["TextToSpeechAudio"] = 1] = "TextToSpeechAudio"; -})(MessageDataStreamType = exports.MessageDataStreamType || (exports.MessageDataStreamType = {})); + static fromJSON(json) { + return new TranslationSynthesisEnd(json); + } + get SynthesisStatus() { + return this.privSynthesisEnd.SynthesisStatus; + } + get FailureReason() { + return this.privSynthesisEnd.FailureReason; + } +} +exports.TranslationSynthesisEnd = TranslationSynthesisEnd; /***/ }), -/* 206 */ -/***/ (function(module, exports, __webpack_require__) { +/* 214 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AgentConfig = void 0; -/** - * Represents the JSON used in the agent.config message sent to the speech service. - */ -var AgentConfig = /** @class */ (function () { - function AgentConfig() { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranslationHypothesis = void 0; +const Contracts_js_1 = __webpack_require__(70); +const TranslationStatus_js_1 = __webpack_require__(53); +class TranslationHypothesis { + constructor(hypothesis, baseOffset) { + this.privTranslationHypothesis = hypothesis; + this.privTranslationHypothesis.Offset += baseOffset; + this.privTranslationHypothesis.Translation.TranslationStatus = this.mapTranslationStatus(this.privTranslationHypothesis.Translation.TranslationStatus); } - AgentConfig.prototype.toJsonString = function () { - return JSON.stringify(this.iPrivConfig); - }; - AgentConfig.prototype.get = function () { - return this.iPrivConfig; - }; - /** - * Setter for the agent.config object. - * @param value a JSON serializable object. - */ - AgentConfig.prototype.set = function (value) { - this.iPrivConfig = value; - }; - return AgentConfig; -}()); -exports.AgentConfig = AgentConfig; + static fromJSON(json, baseOffset) { + return new TranslationHypothesis(JSON.parse(json), baseOffset); + } + static fromTranslationResponse(translationHypothesis, baseOffset) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(translationHypothesis, "translationHypothesis"); + const hypothesis = translationHypothesis.SpeechHypothesis; + translationHypothesis.SpeechHypothesis = undefined; + hypothesis.Translation = translationHypothesis; + return new TranslationHypothesis(hypothesis, baseOffset); + } + get Duration() { + return this.privTranslationHypothesis.Duration; + } + get Offset() { + return this.privTranslationHypothesis.Offset; + } + get Text() { + return this.privTranslationHypothesis.Text; + } + get Translation() { + return this.privTranslationHypothesis.Translation; + } + get Language() { + return this.privTranslationHypothesis.PrimaryLanguage?.Language; + } + asJson() { + const jsonObj = { ...this.privTranslationHypothesis }; + // Convert the enum value to its string representation for serialization purposes. + return jsonObj.Translation !== undefined ? JSON.stringify({ + ...jsonObj, + TranslationStatus: TranslationStatus_js_1.TranslationStatus[jsonObj.Translation.TranslationStatus] + }) : JSON.stringify(jsonObj); + } + mapTranslationStatus(status) { + if (typeof status === "string") { + return TranslationStatus_js_1.TranslationStatus[status]; + } + else if (typeof status === "number") { + return status; + } + } +} +exports.TranslationHypothesis = TranslationHypothesis; /***/ }), -/* 207 */ -/***/ (function(module, exports, __webpack_require__) { +/* 215 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -var ConversationManager_1 = __webpack_require__(208); -Object.defineProperty(exports, "ConversationManager", { enumerable: true, get: function () { return ConversationManager_1.ConversationManager; } }); -var ConversationConnectionConfig_1 = __webpack_require__(209); -Object.defineProperty(exports, "ConversationConnectionConfig", { enumerable: true, get: function () { return ConversationConnectionConfig_1.ConversationConnectionConfig; } }); -var ConversationTranslatorRecognizer_1 = __webpack_require__(211); -Object.defineProperty(exports, "ConversationRecognizerFactory", { enumerable: true, get: function () { return ConversationTranslatorRecognizer_1.ConversationRecognizerFactory; } }); -var TranscriberRecognizer_1 = __webpack_require__(223); -Object.defineProperty(exports, "TranscriberRecognizer", { enumerable: true, get: function () { return TranscriberRecognizer_1.TranscriberRecognizer; } }); -var ConversationTranslatorEventArgs_1 = __webpack_require__(217); -Object.defineProperty(exports, "ConversationReceivedTranslationEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.ConversationReceivedTranslationEventArgs; } }); -Object.defineProperty(exports, "LockRoomEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.LockRoomEventArgs; } }); -Object.defineProperty(exports, "MuteAllEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.MuteAllEventArgs; } }); -Object.defineProperty(exports, "ParticipantAttributeEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs; } }); -Object.defineProperty(exports, "ParticipantEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.ParticipantEventArgs; } }); -Object.defineProperty(exports, "ParticipantsListEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.ParticipantsListEventArgs; } }); -var ConversationTranslatorInterfaces_1 = __webpack_require__(218); -Object.defineProperty(exports, "ConversationTranslatorCommandTypes", { enumerable: true, get: function () { return ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes; } }); -Object.defineProperty(exports, "ConversationTranslatorMessageTypes", { enumerable: true, get: function () { return ConversationTranslatorInterfaces_1.ConversationTranslatorMessageTypes; } }); -Object.defineProperty(exports, "InternalParticipants", { enumerable: true, get: function () { return ConversationTranslatorInterfaces_1.InternalParticipants; } }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranslationPhrase = void 0; +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_1 = __webpack_require__(2); +const TranslationStatus_js_1 = __webpack_require__(53); +class TranslationPhrase { + constructor(phrase, baseOffset) { + this.privTranslationPhrase = phrase; + this.privTranslationPhrase.Offset += baseOffset; + this.privTranslationPhrase.RecognitionStatus = this.mapRecognitionStatus(this.privTranslationPhrase.RecognitionStatus); + if (this.privTranslationPhrase.Translation !== undefined) { + this.privTranslationPhrase.Translation.TranslationStatus = this.mapTranslationStatus(this.privTranslationPhrase.Translation.TranslationStatus); + } + } + static fromJSON(json, baseOffset) { + return new TranslationPhrase(JSON.parse(json), baseOffset); + } + static fromTranslationResponse(translationResponse, baseOffset) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(translationResponse, "translationResponse"); + const phrase = translationResponse.SpeechPhrase; + translationResponse.SpeechPhrase = undefined; + phrase.Translation = translationResponse; + phrase.Text = phrase.DisplayText; + return new TranslationPhrase(phrase, baseOffset); + } + get RecognitionStatus() { + return this.privTranslationPhrase.RecognitionStatus; + } + get Offset() { + return this.privTranslationPhrase.Offset; + } + get Duration() { + return this.privTranslationPhrase.Duration; + } + get Text() { + return this.privTranslationPhrase.Text; + } + get Language() { + return this.privTranslationPhrase.PrimaryLanguage?.Language; + } + get Confidence() { + return this.privTranslationPhrase.PrimaryLanguage?.Confidence; + } + get Translation() { + return this.privTranslationPhrase.Translation; + } + asJson() { + const jsonObj = { ...this.privTranslationPhrase }; + // Convert the enum values to their string representations for serialization + const serializedObj = { + ...jsonObj, + RecognitionStatus: Exports_js_1.RecognitionStatus[jsonObj.RecognitionStatus] + }; + if (jsonObj.Translation) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + serializedObj.Translation = { + ...jsonObj.Translation, + TranslationStatus: TranslationStatus_js_1.TranslationStatus[jsonObj.Translation.TranslationStatus] + }; + } + return JSON.stringify(serializedObj); + } + mapRecognitionStatus(status) { + if (typeof status === "string") { + return Exports_js_1.RecognitionStatus[status]; + } + else if (typeof status === "number") { + return status; + } + } + mapTranslationStatus(status) { + if (typeof status === "string") { + return TranslationStatus_js_1.TranslationStatus[status]; + } + else if (typeof status === "number") { + return status; + } + } +} +exports.TranslationPhrase = TranslationPhrase; /***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { +/* 216 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationManager = void 0; -var Exports_1 = __webpack_require__(2); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); -var ConversationConnectionConfig_1 = __webpack_require__(209); -var ConversationManager = /** @class */ (function () { - function ConversationManager() { - // - this.privRequestParams = ConversationConnectionConfig_1.ConversationConnectionConfig.configParams; - this.privErrors = ConversationConnectionConfig_1.ConversationConnectionConfig.restErrors; - this.privHost = ConversationConnectionConfig_1.ConversationConnectionConfig.host; - this.privApiVersion = ConversationConnectionConfig_1.ConversationConnectionConfig.apiVersion; - this.privRestPath = ConversationConnectionConfig_1.ConversationConnectionConfig.restPath; - this.privRestAdapter = new Exports_1.RestMessageAdapter({}); - } - /** - * Make a POST request to the Conversation Manager service endpoint to create or join a conversation. - * @param args - * @param conversationCode - * @param callback - * @param errorCallback - */ - ConversationManager.prototype.createOrJoin = function (args, conversationCode, cb, err) { - var _this = this; - try { - Contracts_1.Contracts.throwIfNullOrUndefined(args, "args"); - var languageCode = args.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage, ConversationConnectionConfig_1.ConversationConnectionConfig.defaultLanguageCode); - var nickname = args.getProperty(Exports_2.PropertyId.ConversationTranslator_Name, "conversation_host"); - var endpointHost = args.getProperty(Exports_2.PropertyId.ConversationTranslator_Host, this.privHost); - var correlationId = args.getProperty(Exports_2.PropertyId.ConversationTranslator_CorrelationId); - var subscriptionKey = args.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Key); - var subscriptionRegion = args.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region); - var authToken = args.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token); - Contracts_1.Contracts.throwIfNullOrWhitespace(languageCode, "languageCode"); - Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, "nickname"); - Contracts_1.Contracts.throwIfNullOrWhitespace(endpointHost, "endpointHost"); - var queryParams = {}; - queryParams[this.privRequestParams.apiVersion] = this.privApiVersion; - queryParams[this.privRequestParams.languageCode] = languageCode; - queryParams[this.privRequestParams.nickname] = nickname; - var headers = {}; - if (correlationId) { - headers[this.privRequestParams.correlationId] = correlationId; - } - headers[this.privRequestParams.clientAppId] = ConversationConnectionConfig_1.ConversationConnectionConfig.clientAppId; - if (conversationCode !== undefined) { - queryParams[this.privRequestParams.roomId] = conversationCode; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranslationServiceRecognizer = void 0; +const Exports_js_1 = __webpack_require__(4); +const Exports_js_2 = __webpack_require__(85); +const Exports_js_3 = __webpack_require__(2); +// eslint-disable-next-line max-classes-per-file +class TranslationServiceRecognizer extends Exports_js_3.ConversationServiceRecognizer { + constructor(authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer) { + super(authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer); + this.privTranslationRecognizer = translationRecognizer; + this.connectionEvents.attach((connectionEvent) => { + if (connectionEvent.name === "ConnectionEstablishedEvent") { + this.privTranslationRecognizer.onConnection(); } - else { - Contracts_1.Contracts.throwIfNullOrUndefined(subscriptionRegion, this.privErrors.authInvalidSubscriptionRegion); - headers[this.privRequestParams.subscriptionRegion] = subscriptionRegion; - if (subscriptionKey) { - headers[this.privRequestParams.subscriptionKey] = subscriptionKey; - } - else if (authToken) { - headers[this.privRequestParams.authorization] = "Bearer " + authToken; - } - else { - Contracts_1.Contracts.throwIfNullOrUndefined(subscriptionKey, this.privErrors.authInvalidSubscriptionKey); - } + }); + } + async processTypeSpecificMessages(connectionMessage) { + const resultProps = new Exports_js_2.PropertyCollection(); + let processed = await this.processSpeechMessages(connectionMessage); + if (processed) { + return true; + } + const handleTranslationPhrase = async (translatedPhrase) => { + resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_JsonResult, translatedPhrase.asJson()); + const phraseLatencyMs = this.privRequestSession.onPhraseRecognized(translatedPhrase.Offset + translatedPhrase.Duration); + if (phraseLatencyMs > 0) { + resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RecognitionLatencyMs, phraseLatencyMs.toString()); } - var config = {}; - config.headers = headers; - this.privRestAdapter.options = config; - var endpoint = "https://" + endpointHost + this.privRestPath; - // TODO: support a proxy and certificate validation - this.privRestAdapter.request(Exports_1.RestRequestType.Post, endpoint, queryParams, null).then(function (response) { - var requestId = Exports_1.RestMessageAdapter.extractHeaderValue(_this.privRequestParams.requestId, response.headers); - if (!response.ok) { - if (!!err) { - // get the error - var errorMessage = _this.privErrors.invalidCreateJoinConversationResponse.replace("{status}", response.status.toString()); - var errMessageRaw = void 0; - try { - errMessageRaw = JSON.parse(response.data); - errorMessage += " [" + errMessageRaw.error.code + ": " + errMessageRaw.error.message + "]"; - } - catch (e) { - errorMessage += " [" + response.data + "]"; - } - if (requestId) { - errorMessage += " " + requestId; - } - err(errorMessage); + if (translatedPhrase.RecognitionStatus === Exports_js_3.RecognitionStatus.Success) { + // OK, the recognition was successful. How'd the translation do? + const result = this.fireEventForResult(translatedPhrase, resultProps); + if (!!this.privTranslationRecognizer.recognized) { + try { + this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, result); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. } - return; - } - var conversation = JSON.parse(response.data); - if (conversation) { - conversation.requestId = requestId; } - if (!!cb) { + // report result to promise. + if (!!this.privSuccessCallback) { try { - cb(conversation); + this.privSuccessCallback(result.result); } catch (e) { - if (!!err) { - err(e); + if (!!this.privErrorCallback) { + this.privErrorCallback(e); } } - cb = undefined; + // Only invoke the call back once. + // and if it's successful don't invoke the + // error after that. + this.privSuccessCallback = undefined; + this.privErrorCallback = undefined; } - /* tslint:disable:no-empty */ - }).catch(function (e) { }); - } - catch (error) { - if (!!err) { - if (error instanceof Error) { - var typedError = error; - err(typedError.name + ": " + typedError.message); + } + else { + const reason = Exports_js_3.EnumTranslation.implTranslateRecognitionResult(translatedPhrase.RecognitionStatus); + const result = new Exports_js_2.TranslationRecognitionResult(undefined, this.privRequestSession.requestId, reason, translatedPhrase.Text, translatedPhrase.Duration, translatedPhrase.Offset, translatedPhrase.Language, translatedPhrase.Confidence, undefined, translatedPhrase.asJson(), resultProps); + if (reason === Exports_js_2.ResultReason.Canceled) { + const cancelReason = Exports_js_3.EnumTranslation.implTranslateCancelResult(translatedPhrase.RecognitionStatus); + const cancellationErrorCode = Exports_js_3.EnumTranslation.implTranslateCancelErrorCode(translatedPhrase.RecognitionStatus); + await this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_js_3.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode)); } else { - err(error); + if (translatedPhrase.RecognitionStatus !== Exports_js_3.RecognitionStatus.EndOfDictation) { + const ev = new Exports_js_2.TranslationRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId); + if (!!this.privTranslationRecognizer.recognized) { + try { + this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, ev); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + // report result to promise. + if (!!this.privSuccessCallback) { + try { + this.privSuccessCallback(result); + } + catch (e) { + if (!!this.privErrorCallback) { + this.privErrorCallback(e); + } + } + // Only invoke the call back once. + // and if it's successful don't invoke the + // error after that. + this.privSuccessCallback = undefined; + this.privErrorCallback = undefined; + } + } + } + processed = true; + } + }; + const handleTranslationHypothesis = (hypothesis) => { + resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_JsonResult, hypothesis.asJson()); + const hypothesisLatencyMs = this.privRequestSession.onHypothesis(hypothesis.Offset); + if (hypothesisLatencyMs > 0) { + resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RecognitionLatencyMs, hypothesisLatencyMs.toString()); + } + const result = this.fireEventForResult(hypothesis, resultProps); + if (!!this.privTranslationRecognizer.recognizing) { + try { + this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer, result); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. } } + processed = true; + }; + if (connectionMessage.messageType === Exports_js_1.MessageType.Text) { + resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody); } - }; - /** - * Make a DELETE request to the Conversation Manager service endpoint to leave the conversation. - * @param args - * @param sessionToken - * @param callback - */ - ConversationManager.prototype.leave = function (args, sessionToken) { - var _this = this; - return new Promise(function (resolve, reject) { - try { - Contracts_1.Contracts.throwIfNullOrUndefined(args, _this.privErrors.invalidArgs.replace("{arg}", "config")); - Contracts_1.Contracts.throwIfNullOrWhitespace(sessionToken, _this.privErrors.invalidArgs.replace("{arg}", "token")); - var endpointHost = args.getProperty(Exports_2.PropertyId.ConversationTranslator_Host, _this.privHost); - var correlationId = args.getProperty(Exports_2.PropertyId.ConversationTranslator_CorrelationId); - var queryParams = {}; - queryParams[_this.privRequestParams.apiVersion] = _this.privApiVersion; - queryParams[_this.privRequestParams.sessionToken] = sessionToken; - var headers = {}; - if (correlationId) { - headers[_this.privRequestParams.correlationId] = correlationId; + switch (connectionMessage.path.toLowerCase()) { + case "translation.hypothesis": + handleTranslationHypothesis(Exports_js_3.TranslationHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset)); + break; + case "translation.response": + const phrase = JSON.parse(connectionMessage.textBody); + if (!!phrase.SpeechPhrase) { + await handleTranslationPhrase(Exports_js_3.TranslationPhrase.fromTranslationResponse(phrase, this.privRequestSession.currentTurnAudioOffset)); } - var config = {}; - config.headers = headers; - _this.privRestAdapter.options = config; - var endpoint = "https://" + endpointHost + _this.privRestPath; - // TODO: support a proxy and certificate validation - _this.privRestAdapter.request(Exports_1.RestRequestType.Delete, endpoint, queryParams, null).then(function (response) { - if (!response.ok) { - // ignore errors on delete + else { + const hypothesis = JSON.parse(connectionMessage.textBody); + if (!!hypothesis.SpeechHypothesis) { + handleTranslationHypothesis(Exports_js_3.TranslationHypothesis.fromTranslationResponse(hypothesis, this.privRequestSession.currentTurnAudioOffset)); } - resolve(); - /* tslint:disable:no-empty */ - }).catch(function (e) { }); + } + break; + case "translation.phrase": + await handleTranslationPhrase(Exports_js_3.TranslationPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset)); + break; + case "translation.synthesis": + case "audio": + this.sendSynthesisAudio(connectionMessage.binaryBody, this.privRequestSession.sessionId); + processed = true; + break; + case "audio.end": + case "translation.synthesis.end": + const synthEnd = Exports_js_3.TranslationSynthesisEnd.fromJSON(connectionMessage.textBody); + switch (synthEnd.SynthesisStatus) { + case Exports_js_3.SynthesisStatus.Error: + if (!!this.privTranslationRecognizer.synthesizing) { + const result = new Exports_js_2.TranslationSynthesisResult(Exports_js_2.ResultReason.Canceled, undefined); + const retEvent = new Exports_js_2.TranslationSynthesisEventArgs(result, this.privRequestSession.sessionId); + try { + this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + if (!!this.privTranslationRecognizer.canceled) { + // And raise a canceled event to send the rich(er) error message back. + const canceledResult = new Exports_js_2.TranslationRecognitionCanceledEventArgs(this.privRequestSession.sessionId, Exports_js_2.CancellationReason.Error, synthEnd.FailureReason, Exports_js_2.CancellationErrorCode.ServiceError, null); + try { + this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, canceledResult); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + break; + case Exports_js_3.SynthesisStatus.Success: + this.sendSynthesisAudio(undefined, this.privRequestSession.sessionId); + break; + default: + break; + } + processed = true; + break; + default: + break; + } + return processed; + } + // Cancels recognition. + cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) { + const properties = new Exports_js_2.PropertyCollection(); + properties.setProperty(Exports_js_3.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[errorCode]); + if (!!this.privTranslationRecognizer.canceled) { + const cancelEvent = new Exports_js_2.TranslationRecognitionCanceledEventArgs(sessionId, cancellationReason, error, errorCode, undefined); + try { + this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, cancelEvent); + /* eslint-disable no-empty */ + } + catch { } + } + if (!!this.privSuccessCallback) { + const result = new Exports_js_2.TranslationRecognitionResult(undefined, // Translations + requestId, Exports_js_2.ResultReason.Canceled, undefined, // Text + undefined, // Druation + undefined, // Offset + undefined, // Language + undefined, // LanguageDetectionConfidence + error, undefined, // Json + properties); + try { + this.privSuccessCallback(result); + /* eslint-disable no-empty */ + this.privSuccessCallback = undefined; + } + catch { } + } + } + handleRecognizingCallback(result, offset, sessionId) { + try { + const ev = new Exports_js_2.TranslationRecognitionEventArgs(Exports_js_2.TranslationRecognitionResult.fromSpeechRecognitionResult(result), offset, sessionId); + this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer, ev); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + handleRecognizedCallback(result, offset, sessionId) { + try { + const ev = new Exports_js_2.TranslationRecognitionEventArgs(Exports_js_2.TranslationRecognitionResult.fromSpeechRecognitionResult(result), offset, sessionId); + this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, ev); + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + fireEventForResult(serviceResult, properties) { + let translations; + if (undefined !== serviceResult.Translation.Translations) { + translations = new Exports_js_2.Translations(); + for (const translation of serviceResult.Translation.Translations) { + translations.set(translation.Language, translation.Text || translation.DisplayText); + } + } + let resultReason; + let confidence; + if (serviceResult instanceof Exports_js_3.TranslationPhrase) { + if (!!serviceResult.Translation && serviceResult.Translation.TranslationStatus === Exports_js_1.TranslationStatus.Success) { + resultReason = Exports_js_2.ResultReason.TranslatedSpeech; + } + else { + resultReason = Exports_js_2.ResultReason.RecognizedSpeech; + } + confidence = serviceResult.Confidence; + } + else { + resultReason = Exports_js_2.ResultReason.TranslatingSpeech; + } + const language = serviceResult.Language; + const result = new Exports_js_2.TranslationRecognitionResult(translations, this.privRequestSession.requestId, resultReason, serviceResult.Text, serviceResult.Duration, serviceResult.Offset, language, confidence, serviceResult.Translation.FailureReason, serviceResult.asJson(), properties); + const ev = new Exports_js_2.TranslationRecognitionEventArgs(result, serviceResult.Offset, this.privRequestSession.sessionId); + return ev; + } + sendSynthesisAudio(audio, sessionId) { + const reason = (undefined === audio) ? Exports_js_2.ResultReason.SynthesizingAudioCompleted : Exports_js_2.ResultReason.SynthesizingAudio; + const result = new Exports_js_2.TranslationSynthesisResult(reason, audio); + const retEvent = new Exports_js_2.TranslationSynthesisEventArgs(result, sessionId); + if (!!this.privTranslationRecognizer.synthesizing) { + try { + this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent); + /* eslint-disable no-empty */ } catch (error) { - if (error instanceof Error) { - var typedError = error; - reject(typedError.name + ": " + typedError.message); - } - else { - reject(error); - } + // Not going to let errors in the event handler + // trip things up. } - }); - }; - return ConversationManager; -}()); -exports.ConversationManager = ConversationManager; + } + } +} +exports.TranslationServiceRecognizer = TranslationServiceRecognizer; /***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { +/* 217 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationConnectionConfig = void 0; -var RestConfigBase_1 = __webpack_require__(210); -var ConversationConnectionConfig = /** @class */ (function (_super) { - __extends(ConversationConnectionConfig, _super); - function ConversationConnectionConfig() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(ConversationConnectionConfig, "host", { - get: function () { - return ConversationConnectionConfig.privHost; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationConnectionConfig, "apiVersion", { - get: function () { - return ConversationConnectionConfig.privApiVersion; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationConnectionConfig, "clientAppId", { - get: function () { - return ConversationConnectionConfig.privClientAppId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationConnectionConfig, "defaultLanguageCode", { - get: function () { - return ConversationConnectionConfig.privDefaultLanguageCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationConnectionConfig, "restPath", { - get: function () { - return ConversationConnectionConfig.privRestPath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationConnectionConfig, "webSocketPath", { - get: function () { - return ConversationConnectionConfig.privWebSocketPath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationConnectionConfig, "speechHost", { - get: function () { - return ConversationConnectionConfig.privSpeechHost; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationConnectionConfig, "speechPath", { - get: function () { - return ConversationConnectionConfig.privSpeechPath; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationConnectionConfig, "transcriptionEventKeys", { - get: function () { - return ConversationConnectionConfig.privTranscriptionEventKeys; - }, - enumerable: false, - configurable: true - }); - ConversationConnectionConfig.privHost = "dev.microsofttranslator.com"; - ConversationConnectionConfig.privRestPath = "/capito/room"; - ConversationConnectionConfig.privApiVersion = "2.0"; - ConversationConnectionConfig.privDefaultLanguageCode = "en-US"; - ConversationConnectionConfig.privClientAppId = "FC539C22-1767-4F1F-84BC-B4D811114F15"; - ConversationConnectionConfig.privWebSocketPath = "/capito/translate"; - ConversationConnectionConfig.privSpeechHost = "{region}.s2s.speech.microsoft.com"; - ConversationConnectionConfig.privSpeechPath = "/speech/translation/cognitiveservices/v1"; - ConversationConnectionConfig.privTranscriptionEventKeys = ["iCalUid", "callId", "organizer", "FLAC", "MTUri", "DifferentiateGuestSpeakers", "audiorecording", "Threadid", "OrganizerMri", "OrganizerTenantId", "UserToken"]; - return ConversationConnectionConfig; -}(RestConfigBase_1.RestConfigBase)); -exports.ConversationConnectionConfig = ConversationConnectionConfig; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechDetected = void 0; +class SpeechDetected { + constructor(json, baseOffset) { + this.privSpeechStartDetected = JSON.parse(json); + this.privSpeechStartDetected.Offset += baseOffset; + } + static fromJSON(json, baseOffset) { + return new SpeechDetected(json, baseOffset); + } + get Offset() { + return this.privSpeechStartDetected.Offset; + } +} +exports.SpeechDetected = SpeechDetected; /***/ }), -/* 210 */ -/***/ (function(module, exports, __webpack_require__) { +/* 218 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RestConfigBase = void 0; -var RestConfigBase = /** @class */ (function () { - function RestConfigBase() { - } - Object.defineProperty(RestConfigBase, "requestOptions", { - get: function () { - return RestConfigBase.privDefaultRequestOptions; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RestConfigBase, "configParams", { - get: function () { - return RestConfigBase.privDefaultParams; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(RestConfigBase, "restErrors", { - get: function () { - return RestConfigBase.privRestErrors; - }, - enumerable: false, - configurable: true - }); - RestConfigBase.privDefaultRequestOptions = { - headers: { - Accept: "application/json", - }, - ignoreCache: false, - timeout: 10000, - }; - RestConfigBase.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.", - }; - RestConfigBase.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", - }; - return RestConfigBase; -}()); -exports.RestConfigBase = RestConfigBase; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechHypothesis = void 0; +class SpeechHypothesis { + constructor(json, baseOffset) { + this.privSpeechHypothesis = JSON.parse(json); + this.updateOffset(baseOffset); + } + static fromJSON(json, baseOffset) { + return new SpeechHypothesis(json, baseOffset); + } + updateOffset(baseOffset) { + this.privSpeechHypothesis.Offset += baseOffset; + } + asJson() { + return JSON.stringify(this.privSpeechHypothesis); + } + get Text() { + return this.privSpeechHypothesis.Text; + } + get Offset() { + return this.privSpeechHypothesis.Offset; + } + get Duration() { + return this.privSpeechHypothesis.Duration; + } + get Language() { + return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Language; + } + get LanguageDetectionConfidence() { + return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Confidence; + } + get SpeakerId() { + return this.privSpeechHypothesis.SpeakerId; + } +} +exports.SpeechHypothesis = SpeechHypothesis; /***/ }), -/* 211 */ -/***/ (function(module, exports, __webpack_require__) { +/* 219 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechKeyword = void 0; +class SpeechKeyword { + constructor(json, baseOffset) { + this.privSpeechKeyword = JSON.parse(json); + this.privSpeechKeyword.Offset += baseOffset; } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranslatorRecognizer = exports.ConversationRecognizerFactory = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -var ConversationConnectionFactory_1 = __webpack_require__(212); -var ConversationServiceAdapter_1 = __webpack_require__(215); -var ConversationRecognizerFactory = /** @class */ (function () { - function ConversationRecognizerFactory() { - } - ConversationRecognizerFactory.fromConfig = function (conversation, speechConfig, audioConfig) { - return new ConversationTranslatorRecognizer(conversation, speechConfig, audioConfig); - }; - return ConversationRecognizerFactory; -}()); -exports.ConversationRecognizerFactory = ConversationRecognizerFactory; -/** - * Sends messages to the Conversation Translator websocket and listens for incoming events containing websocket messages. - * Based off the recognizers in the SDK folder. - */ -// tslint:disable-next-line:max-classes-per-file -var ConversationTranslatorRecognizer = /** @class */ (function (_super) { - __extends(ConversationTranslatorRecognizer, _super); - function ConversationTranslatorRecognizer(conversation, speechConfig, audioConfig) { - var _this = this; - var serviceConfigImpl = speechConfig; - Contracts_1.Contracts.throwIfNull(serviceConfigImpl, "speechConfig"); - var conversationImpl = conversation; - Contracts_1.Contracts.throwIfNull(conversationImpl, "conversationImpl"); - _this = _super.call(this, audioConfig, serviceConfigImpl.properties, new ConversationConnectionFactory_1.ConversationConnectionFactory()) || this; - _this.privConversation = conversationImpl; - _this.privIsDisposed = false; - _this.privProperties = serviceConfigImpl.properties.clone(); - _this.privConnection = Exports_3.Connection.fromRecognizer(_this); - _this.privSetTimeout = (typeof (Blob) !== "undefined" && typeof (Worker) !== "undefined") ? Exports_2.Timeout.setTimeout : setTimeout; - _this.privClearTimeout = (typeof (Blob) !== "undefined" && typeof (Worker) !== "undefined") ? Exports_2.Timeout.clearTimeout : clearTimeout; - return _this; - } - Object.defineProperty(ConversationTranslatorRecognizer.prototype, "connected", { - set: function (cb) { - this.privConnection.connected = cb; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationTranslatorRecognizer.prototype, "disconnected", { - set: function (cb) { - this.privConnection.disconnected = cb; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationTranslatorRecognizer.prototype, "speechRecognitionLanguage", { - /** - * Return the speech language used by the recognizer - */ - get: function () { - return this.privSpeechRecognitionLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationTranslatorRecognizer.prototype, "properties", { - /** - * Return the properties for the recognizer - */ - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - ConversationTranslatorRecognizer.prototype.isDisposed = function () { - return this.privIsDisposed; - }; - /** - * Connect to the recognizer - * @param token - */ - ConversationTranslatorRecognizer.prototype.connect = function (token, cb, err) { - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token"); - this.privReco.conversationTranslatorToken = token; - this.resetConversationTimeout(); - this.privReco.connectAsync(cb, err); - } - catch (error) { - if (!!err) { - if (error instanceof Error) { - var typedError = error; - err(typedError.name + ": " + typedError.message); - } - else { - err(error); - } - } - } - }; - /** - * Disconnect from the recognizer - */ - ConversationTranslatorRecognizer.prototype.disconnect = function (cb, err) { - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - if (this.privTimeoutToken !== undefined) { - this.privClearTimeout(this.privTimeoutToken); - } - this.privReco.disconnect().then(function () { - if (!!cb) { - cb(); - } - }, function (error) { - if (!!err) { - err(error); + static fromJSON(json, baseOffset) { + return new SpeechKeyword(json, baseOffset); + } + get Status() { + return this.privSpeechKeyword.Status; + } + get Text() { + return this.privSpeechKeyword.Text; + } + get Offset() { + return this.privSpeechKeyword.Offset; + } + get Duration() { + return this.privSpeechKeyword.Duration; + } + asJson() { + return JSON.stringify(this.privSpeechKeyword); + } +} +exports.SpeechKeyword = SpeechKeyword; + + + +/***/ }), +/* 220 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechServiceRecognizer = void 0; +const Exports_js_1 = __webpack_require__(85); +const Exports_js_2 = __webpack_require__(2); +// eslint-disable-next-line max-classes-per-file +class SpeechServiceRecognizer extends Exports_js_2.ServiceRecognizerBase { + constructor(authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer) { + super(authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer); + this.privSpeechRecognizer = speechRecognizer; + } + async processTypeSpecificMessages(connectionMessage) { + let result; + const resultProps = new Exports_js_1.PropertyCollection(); + let processed = false; + switch (connectionMessage.path.toLowerCase()) { + case "speech.hypothesis": + case "speech.fragment": + const hypothesis = Exports_js_2.SpeechHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, hypothesis.asJson()); + const hypothesisLatencyMs = this.privRequestSession.onHypothesis(hypothesis.Offset); + if (hypothesisLatencyMs > 0) { + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RecognitionLatencyMs, hypothesisLatencyMs.toString()); + } + result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_js_1.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, hypothesis.Offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, undefined, // Speaker Id + undefined, hypothesis.asJson(), resultProps); + const ev = new Exports_js_1.SpeechRecognitionEventArgs(result, hypothesis.Offset, this.privRequestSession.sessionId); + if (!!this.privSpeechRecognizer.recognizing) { + try { + this.privSpeechRecognizer.recognizing(this.privSpeechRecognizer, ev); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - }); - } - catch (error) { - if (!!err) { - if (error instanceof Error) { - var typedError = error; - err(typedError.name + ": " + typedError.message); + processed = true; + break; + case "speech.phrase": + const simple = Exports_js_2.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, simple.asJson()); + const resultReason = Exports_js_2.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus, this.privExpectContentAssessmentResponse); + const phraseLatencyMs = this.privRequestSession.onPhraseRecognized(simple.Offset + simple.Duration); + if (phraseLatencyMs > 0) { + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RecognitionLatencyMs, phraseLatencyMs.toString()); + } + if (Exports_js_1.ResultReason.Canceled === resultReason) { + const cancelReason = Exports_js_2.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus); + const cancellationErrorCode = Exports_js_2.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus); + await this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_js_2.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode)); } else { - err(error); + // Don't event / return an EndOfDictation message. + if (simple.RecognitionStatus === Exports_js_2.RecognitionStatus.EndOfDictation) { + break; + } + if (this.privRecognizerConfig.parameters.getProperty(Exports_js_2.OutputFormatPropertyName) === Exports_js_1.OutputFormat[Exports_js_1.OutputFormat.Simple]) { + result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset, simple.Language, simple.LanguageDetectionConfidence, undefined, // Speaker Id + undefined, simple.asJson(), resultProps, simple.Channel); + } + else { + const detailed = Exports_js_2.DetailedSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, detailed.asJson()); + result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, detailed.RecognitionStatus === Exports_js_2.RecognitionStatus.Success ? detailed.NBest[0].Display : "", detailed.Duration, detailed.Offset, detailed.Language, detailed.LanguageDetectionConfidence, undefined, // Speaker Id + undefined, detailed.asJson(), resultProps, detailed.Channel); + } + const event = new Exports_js_1.SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId); + if (!!this.privSpeechRecognizer.recognized) { + try { + this.privSpeechRecognizer.recognized(this.privSpeechRecognizer, event); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + if (!!this.privSuccessCallback) { + try { + this.privSuccessCallback(result); + } + catch (e) { + if (!!this.privErrorCallback) { + this.privErrorCallback(e); + } + } + // Only invoke the call back once. + // and if it's successful don't invoke the + // error after that. + this.privSuccessCallback = undefined; + this.privErrorCallback = undefined; + } } - } - // Destroy the recognizer. - this.dispose(true).catch(function (reason) { - Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason)); - }); + processed = true; + break; + default: + break; } - }; - /** - * Send the mute all participants command to the websocket - * @param conversationId - * @param participantId - * @param isMuted - */ - ConversationTranslatorRecognizer.prototype.sendRequest = function (command, cb, err) { - try { - Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed); - this.sendMessage(command, cb, err); + return processed; + } + // Cancels recognition. + cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) { + const properties = new Exports_js_1.PropertyCollection(); + properties.setProperty(Exports_js_2.CancellationErrorCodePropertyName, Exports_js_1.CancellationErrorCode[errorCode]); + if (!!this.privSpeechRecognizer.canceled) { + const cancelEvent = new Exports_js_1.SpeechRecognitionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId); + try { + this.privSpeechRecognizer.canceled(this.privSpeechRecognizer, cancelEvent); + /* eslint-disable no-empty */ + } + catch { } } - catch (error) { - if (!!err) { - if (error instanceof Error) { - var typedError = error; - err(typedError.name + ": " + typedError.message); - } - else { - err(error); - } + if (!!this.privSuccessCallback) { + const result = new Exports_js_1.SpeechRecognitionResult(requestId, Exports_js_1.ResultReason.Canceled, undefined, // Text + undefined, // Duration + undefined, // Offset + undefined, // Language + undefined, // Language Detection Confidence + undefined, // Speaker Id + error, undefined, // Json + properties); + try { + this.privSuccessCallback(result); + this.privSuccessCallback = undefined; + /* eslint-disable no-empty */ } - // Destroy the recognizer. - this.dispose(true).catch(function (reason) { - Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason)); - }); + catch { } } - }; - /** - * Close and dispose the recognizer - */ - ConversationTranslatorRecognizer.prototype.close = function () { - var _a, _b; - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - if (!!this.privIsDisposed) return [3 /*break*/, 2]; - (_a = this.privConnection) === null || _a === void 0 ? void 0 : _a.closeConnection(); - (_b = this.privConnection) === null || _b === void 0 ? void 0 : _b.close(); - this.privConnection = undefined; - return [4 /*yield*/, this.dispose(true)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: return [2 /*return*/]; + } +} +exports.SpeechServiceRecognizer = SpeechServiceRecognizer; + + + +/***/ }), +/* 221 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationTranscriptionServiceRecognizer = void 0; +const Exports_js_1 = __webpack_require__(85); +const Exports_js_2 = __webpack_require__(2); +const SpeakerDiarization_js_1 = __webpack_require__(222); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +// eslint-disable-next-line max-classes-per-file +class ConversationTranscriptionServiceRecognizer extends Exports_js_2.ServiceRecognizerBase { + constructor(authentication, connectionFactory, audioSource, recognizerConfig, conversationTranscriber) { + super(authentication, connectionFactory, audioSource, recognizerConfig, conversationTranscriber); + this.privConversationTranscriber = conversationTranscriber; + this.setSpeakerDiarizationJson(); + } + setSpeakerDiarizationJson() { + if (this.privEnableSpeakerId) { + const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {}; + phraseDetection.mode = PhraseDetectionContext_js_1.RecognitionMode.Conversation; + const speakerDiarization = {}; + speakerDiarization.mode = SpeakerDiarization_js_1.SpeakerDiarizationMode.Anonymous; + speakerDiarization.audioSessionId = this.privDiarizationSessionId; + speakerDiarization.audioOffsetMs = 0; + speakerDiarization.diarizeIntermediates = this.privRecognizerConfig.parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_DiarizeIntermediateResults, "false") === "true"; + phraseDetection.speakerDiarization = speakerDiarization; + this.privSpeechContext.getContext().phraseDetection = phraseDetection; + } + } + async processTypeSpecificMessages(connectionMessage) { + let result; + const resultProps = new Exports_js_1.PropertyCollection(); + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody); + let processed = false; + switch (connectionMessage.path.toLowerCase()) { + case "speech.hypothesis": + case "speech.fragment": + const hypothesis = Exports_js_2.SpeechHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + const hypothesisLatencyMs = this.privRequestSession.onHypothesis(hypothesis.Offset); + if (hypothesisLatencyMs > 0) { + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RecognitionLatencyMs, hypothesisLatencyMs.toString()); + } + result = new Exports_js_1.ConversationTranscriptionResult(this.privRequestSession.requestId, Exports_js_1.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, hypothesis.Offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, hypothesis.SpeakerId, undefined, hypothesis.asJson(), resultProps); + const ev = new Exports_js_1.ConversationTranscriptionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId); + if (!!this.privConversationTranscriber.transcribing) { + try { + this.privConversationTranscriber.transcribing(this.privConversationTranscriber, ev); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - }); - }); - }; - /** - * Dispose the recognizer - * @param disposing - */ - ConversationTranslatorRecognizer.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privIsDisposed) { - return [2 /*return*/]; - } - if (!disposing) return [3 /*break*/, 2]; - if (this.privTimeoutToken !== undefined) { - this.privClearTimeout(this.privTimeoutToken); - } - this.privIsDisposed = true; - if (!!this.privConnection) { - this.privConnection.closeConnection(); - this.privConnection.close(); - this.privConnection = undefined; - } - return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; + processed = true; + break; + case "speech.phrase": + const simple = Exports_js_2.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + const resultReason = Exports_js_2.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus); + const phraseLatencyMs = this.privRequestSession.onPhraseRecognized(simple.Offset + simple.Duration); + if (phraseLatencyMs > 0) { + resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RecognitionLatencyMs, phraseLatencyMs.toString()); + } + if (Exports_js_1.ResultReason.Canceled === resultReason) { + const cancelReason = Exports_js_2.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus); + const cancellationErrorCode = Exports_js_2.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus); + await this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_js_2.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode)); } - }); - }); - }; - /** - * Create the config for the recognizer - * @param speechConfig - */ - ConversationTranslatorRecognizer.prototype.createRecognizerConfig = function (speechConfig) { - return new Exports_1.RecognizerConfig(speechConfig, this.privProperties); - }; - /** - * Create the service recognizer. - * The audio source is redundnant here but is required by the implementation. - * @param authentication - * @param connectionFactory - * @param audioConfig - * @param recognizerConfig - */ - ConversationTranslatorRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) { - var audioSource = audioConfig; - return new ConversationServiceAdapter_1.ConversationServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this); - }; - ConversationTranslatorRecognizer.prototype.sendMessage = function (msg, cb, err) { - var withAsync = this.privReco; - function PromiseToEmptyCallback(promise, cb, err) { - if (!!promise) { - promise.then(function (result) { - try { - if (!!cb) { - cb(); + else { + if (!(this.privRequestSession.isSpeechEnded && resultReason === Exports_js_1.ResultReason.NoMatch && simple.RecognitionStatus !== Exports_js_2.RecognitionStatus.InitialSilenceTimeout)) { + if (this.privRecognizerConfig.parameters.getProperty(Exports_js_2.OutputFormatPropertyName) === Exports_js_1.OutputFormat[Exports_js_1.OutputFormat.Simple]) { + result = new Exports_js_1.ConversationTranscriptionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset, simple.Language, simple.LanguageDetectionConfidence, simple.SpeakerId, undefined, simple.asJson(), resultProps); } - } - catch (e) { - if (!!err) { - err("'Unhandled error on promise callback: " + e + "'"); + else { + const detailed = Exports_js_2.DetailedSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + result = new Exports_js_1.ConversationTranscriptionResult(this.privRequestSession.requestId, resultReason, detailed.RecognitionStatus === Exports_js_2.RecognitionStatus.Success ? detailed.NBest[0].Display : undefined, detailed.Duration, detailed.Offset, detailed.Language, detailed.LanguageDetectionConfidence, simple.SpeakerId, undefined, detailed.asJson(), resultProps); } - } - }, function (reason) { - try { - if (!!err) { - err(reason); + const event = new Exports_js_1.ConversationTranscriptionEventArgs(result, result.offset, this.privRequestSession.sessionId); + if (!!this.privConversationTranscriber.transcribed) { + try { + this.privConversationTranscriber.transcribed(this.privConversationTranscriber, event); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - /* tslint:disable:no-empty */ - } - catch (error) { } - }); - } - else { - if (!!err) { - err("Null promise"); } - } + processed = true; + break; + default: + break; } - PromiseToEmptyCallback(withAsync.sendMessageAsync(msg), cb, err); - this.resetConversationTimeout(); - }; - ConversationTranslatorRecognizer.prototype.resetConversationTimeout = function () { - var _this = this; - if (this.privTimeoutToken !== undefined) { - this.privClearTimeout(this.privTimeoutToken); + return processed; + } + // Cancels recognition. + cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) { + const properties = new Exports_js_1.PropertyCollection(); + properties.setProperty(Exports_js_2.CancellationErrorCodePropertyName, Exports_js_1.CancellationErrorCode[errorCode]); + if (!!this.privConversationTranscriber.canceled) { + const cancelEvent = new Exports_js_1.ConversationTranscriptionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId); + try { + this.privConversationTranscriber.canceled(this.privConversationTranscriber, cancelEvent); + /* eslint-disable no-empty */ + } + catch { } } - this.privTimeoutToken = this.privSetTimeout(function () { - _this.sendRequest(_this.privConversation.getKeepAlive()); - }, 60000); - }; - return ConversationTranslatorRecognizer; -}(Exports_3.Recognizer)); -exports.ConversationTranslatorRecognizer = ConversationTranslatorRecognizer; + } +} +exports.ConversationTranscriptionServiceRecognizer = ConversationTranscriptionServiceRecognizer; + + + +/***/ }), +/* 222 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IdentityProvider = exports.SpeakerDiarizationMode = void 0; +/** + * The speaker diarization mode + */ +var SpeakerDiarizationMode; +(function (SpeakerDiarizationMode) { + SpeakerDiarizationMode["None"] = "None"; + SpeakerDiarizationMode["Identity"] = "Identity"; + SpeakerDiarizationMode["Anonymous"] = "Anonymous"; +})(SpeakerDiarizationMode = exports.SpeakerDiarizationMode || (exports.SpeakerDiarizationMode = {})); +/** + * The identity provider + */ +var IdentityProvider; +(function (IdentityProvider) { + IdentityProvider["CallCenter"] = "CallCenter"; +})(IdentityProvider = exports.IdentityProvider || (exports.IdentityProvider = {})); /***/ }), -/* 212 */ -/***/ (function(module, exports, __webpack_require__) { +/* 223 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationConnectionFactory = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_3 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -var ConversationConnectionConfig_1 = __webpack_require__(209); -var ConversationWebsocketMessageFormatter_1 = __webpack_require__(213); -/** - * Create a connection to the Conversation Translator websocket for sending instant messages and commands, and for receiving translated messages. - * The conversation must already have been started or joined. - */ -var ConversationConnectionFactory = /** @class */ (function (_super) { - __extends(ConversationConnectionFactory, _super); - function ConversationConnectionFactory() { - return _super !== null && _super.apply(this, arguments) || this; - } - ConversationConnectionFactory.prototype.create = function (config, authInfo, connectionId) { - var endpointHost = config.parameters.getProperty(Exports_3.PropertyId.ConversationTranslator_Host, ConversationConnectionConfig_1.ConversationConnectionConfig.host); - var correlationId = config.parameters.getProperty(Exports_3.PropertyId.ConversationTranslator_CorrelationId, Exports_2.createGuid()); - var endpoint = "wss://" + endpointHost + ConversationConnectionConfig_1.ConversationConnectionConfig.webSocketPath; - var token = config.parameters.getProperty(Exports_3.PropertyId.ConversationTranslator_Token, undefined); - Contracts_1.Contracts.throwIfNullOrUndefined(token, "token"); - var queryParams = {}; - queryParams[ConversationConnectionConfig_1.ConversationConnectionConfig.configParams.apiVersion] = ConversationConnectionConfig_1.ConversationConnectionConfig.apiVersion; - queryParams[ConversationConnectionConfig_1.ConversationConnectionConfig.configParams.token] = token; - queryParams[ConversationConnectionConfig_1.ConversationConnectionConfig.configParams.correlationId] = correlationId; - var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true"; - return new Exports_1.WebsocketConnection(endpoint, queryParams, {}, new ConversationWebsocketMessageFormatter_1.ConversationWebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId); - }; - return ConversationConnectionFactory; -}(ConnectionFactoryBase_1.ConnectionFactoryBase)); -exports.ConversationConnectionFactory = ConversationConnectionFactory; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranscriptionServiceRecognizer = void 0; +const Exports_js_1 = __webpack_require__(4); +const Exports_js_2 = __webpack_require__(85); +const Exports_js_3 = __webpack_require__(2); +const SpeechConnectionMessage_Internal_js_1 = __webpack_require__(188); +// eslint-disable-next-line max-classes-per-file +class TranscriptionServiceRecognizer extends Exports_js_3.ConversationServiceRecognizer { + constructor(authentication, connectionFactory, audioSource, recognizerConfig, transcriber) { + super(authentication, connectionFactory, audioSource, recognizerConfig, transcriber); + this.privTranscriberRecognizer = transcriber; + this.sendPrePayloadJSONOverride = (connection) => this.sendTranscriptionStartJSON(connection); + if (this.privRecognizerConfig.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps) === "true") { + this.privSpeechContext.setWordLevelTimings(); + } + } + async sendMeetingSpeechEventAsync(info, command) { + if (!!this.privRequestSession.isRecognizing) { + const connection = await this.fetchConnection(); + await this.sendSpeechEvent(connection, this.createMeetingSpeechEventPayload(info, command)); + } + } + processTypeSpecificMessages(connectionMessage) { + return this.processSpeechMessages(connectionMessage); + } + handleRecognizedCallback(result, offset, sessionId) { + try { + const event = new Exports_js_2.SpeechRecognitionEventArgs(result, offset, sessionId); + this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer, event); + if (!!this.privSuccessCallback) { + try { + this.privSuccessCallback(result); + } + catch (e) { + if (!!this.privErrorCallback) { + this.privErrorCallback(e); + } + } + // Only invoke the call back once. + // and if it's successful don't invoke the + // error after that. + this.privSuccessCallback = undefined; + this.privErrorCallback = undefined; + } + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + handleRecognizingCallback(result, duration, sessionId) { + try { + const ev = new Exports_js_2.SpeechRecognitionEventArgs(result, duration, sessionId); + this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer, ev); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + // Cancels recognition. + cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) { + const properties = new Exports_js_2.PropertyCollection(); + properties.setProperty(Exports_js_3.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[errorCode]); + if (!!this.privTranscriberRecognizer.canceled) { + const cancelEvent = new Exports_js_2.MeetingTranscriptionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId); + try { + this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer, cancelEvent); + /* eslint-disable no-empty */ + } + catch { } + } + if (!!this.privSuccessCallback) { + const result = new Exports_js_2.SpeechRecognitionResult(requestId, Exports_js_2.ResultReason.Canceled, undefined, // Text + undefined, // Duration + undefined, // Offset + undefined, // Language + undefined, // Language Detection Confidence + undefined, // Speaker Id + error, undefined, // Json + properties); + try { + this.privSuccessCallback(result); + this.privSuccessCallback = undefined; + /* eslint-disable no-empty */ + } + catch { } + } + } + // Encapsulated for derived service recognizers that need to send additional JSON + async sendTranscriptionStartJSON(connection) { + await this.sendSpeechContext(connection, true); + const info = this.privTranscriberRecognizer.getMeetingInfo(); + const payload = this.createMeetingSpeechEventPayload(info, "start"); + await this.sendSpeechEvent(connection, payload); + await this.sendWaveHeader(connection); + return; + } + sendSpeechEvent(connection, payload) { + const speechEventJson = JSON.stringify(payload); + if (speechEventJson) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "speech.event", this.privRequestSession.requestId, "application/json", speechEventJson)); + } + return; + } + createMeetingSpeechEventPayload(info, command) { + const eventDict = { id: "meeting", name: command, meeting: info.meetingProperties }; + eventDict.meeting.id = info.id; + eventDict.meeting.attendees = info.participants; + return eventDict; + } +} +exports.TranscriptionServiceRecognizer = TranscriptionServiceRecognizer; /***/ }), -/* 213 */ -/***/ (function(module, exports, __webpack_require__) { +/* 224 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationWebsocketMessageFormatter = void 0; -var Exports_1 = __webpack_require__(4); -var ConversationConnectionMessage_1 = __webpack_require__(214); -/** - * Based off WebsocketMessageFormatter. The messages for Conversation Translator have some variations from the Speech messages. - */ -var ConversationWebsocketMessageFormatter = /** @class */ (function () { - function ConversationWebsocketMessageFormatter() { - /** - * Format incoming messages: text (speech partial/final, IM) or binary (tts) - */ - this.toConnectionMessage = function (message) { - var deferral = new Exports_1.Deferred(); - try { - if (message.messageType === Exports_1.MessageType.Text) { - var incomingMessage = new ConversationConnectionMessage_1.ConversationConnectionMessage(message.messageType, message.textContent, {}, message.id); - deferral.resolve(incomingMessage); - } - else if (message.messageType === Exports_1.MessageType.Binary) { - deferral.resolve(new ConversationConnectionMessage_1.ConversationConnectionMessage(message.messageType, message.binaryContent, undefined, message.id)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DetailedSpeechPhrase = void 0; +const Exports_js_1 = __webpack_require__(2); +class DetailedSpeechPhrase { + constructor(json, baseOffset) { + this.privDetailedSpeechPhrase = JSON.parse(json); + this.privDetailedSpeechPhrase.RecognitionStatus = this.mapRecognitionStatus(this.privDetailedSpeechPhrase.RecognitionStatus); + this.updateOffsets(baseOffset); + } + static fromJSON(json, baseOffset) { + return new DetailedSpeechPhrase(json, baseOffset); + } + updateOffsets(baseOffset) { + this.privDetailedSpeechPhrase.Offset += baseOffset; + if (!!this.privDetailedSpeechPhrase.NBest) { + for (const phrase of this.privDetailedSpeechPhrase.NBest) { + if (!!phrase.Words) { + for (const word of phrase.Words) { + word.Offset += baseOffset; + } } - } - catch (e) { - deferral.reject("Error formatting the message. Error: " + e); - } - return deferral.promise; - }; - /** - * Format outgoing messages: text (commands or IM) - */ - this.fromConnectionMessage = function (message) { - var deferral = new Exports_1.Deferred(); - try { - if (message.messageType === Exports_1.MessageType.Text) { - var payload = "" + (message.textBody ? message.textBody : ""); - deferral.resolve(new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Text, payload, message.id)); + if (!!phrase.DisplayWords) { + for (const word of phrase.DisplayWords) { + word.Offset += baseOffset; + } } } - catch (e) { - deferral.reject("Error formatting the message. " + e); - } - return deferral.promise; - }; + } + } + asJson() { + const jsonObj = { ...this.privDetailedSpeechPhrase }; + // Convert the enum value to its string representation for serialization purposes. + return JSON.stringify({ + ...jsonObj, + RecognitionStatus: Exports_js_1.RecognitionStatus[jsonObj.RecognitionStatus] + }); + } + get RecognitionStatus() { + return this.privDetailedSpeechPhrase.RecognitionStatus; + } + get NBest() { + return this.privDetailedSpeechPhrase.NBest; } - return ConversationWebsocketMessageFormatter; -}()); -exports.ConversationWebsocketMessageFormatter = ConversationWebsocketMessageFormatter; + get Duration() { + return this.privDetailedSpeechPhrase.Duration; + } + get Offset() { + return this.privDetailedSpeechPhrase.Offset; + } + get Language() { + return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Language; + } + get LanguageDetectionConfidence() { + return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Confidence; + } + get Text() { + if (!!this.privDetailedSpeechPhrase.NBest && this.privDetailedSpeechPhrase.NBest[0]) { + return this.privDetailedSpeechPhrase.NBest[0].Display || this.privDetailedSpeechPhrase.NBest[0].DisplayText; + } + return this.privDetailedSpeechPhrase.DisplayText; + } + get SpeakerId() { + return this.privDetailedSpeechPhrase.SpeakerId; + } + get Channel() { + return this.privDetailedSpeechPhrase.Channel === undefined ? 0 : this.privDetailedSpeechPhrase.Channel; + } + mapRecognitionStatus(status) { + if (typeof status === "string") { + return Exports_js_1.RecognitionStatus[status]; + } + else if (typeof status === "number") { + return status; + } + } +} +exports.DetailedSpeechPhrase = DetailedSpeechPhrase; /***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { +/* 225 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationConnectionMessage = void 0; -var Exports_1 = __webpack_require__(4); -var ConversationConnectionMessage = /** @class */ (function (_super) { - __extends(ConversationConnectionMessage, _super); - function ConversationConnectionMessage(messageType, body, headers, id) { - var _this = _super.call(this, messageType, body, headers, id) || this; - var json = JSON.parse(_this.textBody); - if (json.type !== undefined) { - _this.privConversationMessageType = json.type; - } - return _this; - } - Object.defineProperty(ConversationConnectionMessage.prototype, "conversationMessageType", { - get: function () { - return this.privConversationMessageType; - }, - enumerable: false, - configurable: true - }); - return ConversationConnectionMessage; -}(Exports_1.ConnectionMessage)); -exports.ConversationConnectionMessage = ConversationConnectionMessage; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SimpleSpeechPhrase = void 0; +const Exports_js_1 = __webpack_require__(2); +class SimpleSpeechPhrase { + constructor(json, baseOffset = 0) { + this.privSimpleSpeechPhrase = JSON.parse(json); + this.privSimpleSpeechPhrase.RecognitionStatus = this.mapRecognitionStatus(this.privSimpleSpeechPhrase.RecognitionStatus); // RecognitionStatus[this.privSimpleSpeechPhrase.RecognitionStatus as unknown as keyof typeof RecognitionStatus]; + this.updateOffset(baseOffset); + } + static fromJSON(json, baseOffset) { + return new SimpleSpeechPhrase(json, baseOffset); + } + updateOffset(baseOffset) { + this.privSimpleSpeechPhrase.Offset += baseOffset; + } + asJson() { + const jsonObj = { ...this.privSimpleSpeechPhrase }; + // Convert the enum value to its string representation for serialization purposes. + return JSON.stringify({ + ...jsonObj, + RecognitionStatus: Exports_js_1.RecognitionStatus[jsonObj.RecognitionStatus] + }); + } + get RecognitionStatus() { + return this.privSimpleSpeechPhrase.RecognitionStatus; + } + get DisplayText() { + return this.privSimpleSpeechPhrase.DisplayText; + } + get Offset() { + return this.privSimpleSpeechPhrase.Offset; + } + get Duration() { + return this.privSimpleSpeechPhrase.Duration; + } + get Language() { + return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Language; + } + get LanguageDetectionConfidence() { + return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Confidence; + } + get SpeakerId() { + return this.privSimpleSpeechPhrase.SpeakerId; + } + get Channel() { + return this.privSimpleSpeechPhrase.Channel === undefined ? 0 : this.privSimpleSpeechPhrase.Channel; + } + mapRecognitionStatus(status) { + if (typeof status === "string") { + return Exports_js_1.RecognitionStatus[status]; + } + else if (typeof status === "number") { + return status; + } + } +} +exports.SimpleSpeechPhrase = SimpleSpeechPhrase; /***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { +/* 226 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RequestSession = void 0; +const Exports_js_1 = __webpack_require__(4); +const RecognitionEvents_js_1 = __webpack_require__(64); +const ServiceTelemetryListener_Internal_js_1 = __webpack_require__(227); +class RequestSession { + constructor(audioSourceId) { + this.privIsDisposed = false; + this.privDetachables = new Array(); + this.privIsAudioNodeDetached = false; + this.privIsRecognizing = false; + this.privIsSpeechEnded = false; + this.privTurnStartAudioOffset = 0; + this.privLastRecoOffset = 0; + this.privHypothesisReceived = false; + this.privBytesSent = 0; + this.privRecognitionBytesSent = 0; + this.privRecogNumber = 0; + this.privInTurn = false; + this.privConnectionAttempts = 0; + this.privAudioSourceId = audioSourceId; + this.privRequestId = (0, Exports_js_1.createNoDashGuid)(); + this.privAudioNodeId = (0, Exports_js_1.createNoDashGuid)(); + this.privTurnDeferral = new Exports_js_1.Deferred(); + // We're not in a turn, so resolve. + this.privTurnDeferral.resolve(); } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationServiceAdapter = void 0; -var Exports_1 = __webpack_require__(4); -var Exports_2 = __webpack_require__(61); -var Exports_3 = __webpack_require__(53); -var ConversationConnectionMessage_1 = __webpack_require__(214); -var ConversationRequestSession_1 = __webpack_require__(216); -var ConversationTranslatorEventArgs_1 = __webpack_require__(217); -var ConversationTranslatorInterfaces_1 = __webpack_require__(218); -var Exports_4 = __webpack_require__(219); -/*** - * The service adapter handles sending and receiving messages to the Conversation Translator websocket. - */ -var ConversationServiceAdapter = /** @class */ (function (_super) { - __extends(ConversationServiceAdapter, _super); - function ConversationServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, conversationServiceConnector) { - var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, conversationServiceConnector) || this; - _this.privLastPartialUtteranceId = ""; - _this.noOp = function () { - // operation not supported - }; - _this.privConversationServiceConnector = conversationServiceConnector; - _this.privConversationAuthentication = authentication; - _this.receiveMessageOverride = _this.receiveConversationMessageOverride; - _this.recognizeOverride = _this.noOp; - _this.postConnectImplOverride = _this.conversationConnectImpl; - _this.configConnectionOverride = _this.configConnection; - _this.disconnectOverride = _this.privDisconnect; - _this.privConversationRequestSession = new ConversationRequestSession_1.ConversationRequestSession(Exports_1.createNoDashGuid()); - _this.privConversationConnectionFactory = connectionFactory; - _this.privConversationIsDisposed = false; - return _this; - } - ConversationServiceAdapter.prototype.isDisposed = function () { - return _super.prototype.isDisposed.call(this) || this.privConversationIsDisposed; - }; - ConversationServiceAdapter.prototype.dispose = function (reason) { - return __awaiter(this, void 0, void 0, function () { - var connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privConversationIsDisposed = true; - if (!this.privConnectionConfigPromise) return [3 /*break*/, 3]; - return [4 /*yield*/, this.privConnectionConfigPromise]; - case 1: - connection = _a.sent(); - return [4 /*yield*/, connection.dispose(reason)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [4 /*yield*/, _super.prototype.dispose.call(this, reason)]; - case 4: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - ConversationServiceAdapter.prototype.sendMessage = function (message) { - return __awaiter(this, void 0, void 0, function () { - var connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [2 /*return*/, connection.send(new ConversationConnectionMessage_1.ConversationConnectionMessage(Exports_1.MessageType.Text, message))]; - } - }); - }); - }; - ConversationServiceAdapter.prototype.sendMessageAsync = function (message) { - return __awaiter(this, void 0, void 0, function () { - var sink, connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - sink = new Exports_1.Deferred(); - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [4 /*yield*/, connection.send(new ConversationConnectionMessage_1.ConversationConnectionMessage(Exports_1.MessageType.Text, message))]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - ConversationServiceAdapter.prototype.privDisconnect = function () { - if (this.terminateMessageLoop) { - return; + get sessionId() { + return this.privSessionId; + } + get requestId() { + return this.privRequestId; + } + get audioNodeId() { + return this.privAudioNodeId; + } + get turnCompletionPromise() { + return this.privTurnDeferral.promise; + } + get isSpeechEnded() { + return this.privIsSpeechEnded; + } + get isRecognizing() { + return this.privIsRecognizing; + } + get currentTurnAudioOffset() { + return this.privTurnStartAudioOffset; + } + get recogNumber() { + return this.privRecogNumber; + } + get numConnectionAttempts() { + return this.privConnectionAttempts; + } + // The number of bytes sent for the current connection. + // Counter is reset to 0 each time a connection is established. + get bytesSent() { + return this.privBytesSent; + } + // The number of bytes sent for the current recognition. + // Counter is reset to 0 each time recognition is started. + get recognitionBytesSent() { + return this.privRecognitionBytesSent; + } + listenForServiceTelemetry(eventSource) { + if (!!this.privServiceTelemetryListener) { + this.privDetachables.push(eventSource.attachListener(this.privServiceTelemetryListener)); } - this.cancelRecognition(this.privConversationRequestSession.sessionId, this.privConversationRequestSession.requestId, Exports_2.CancellationReason.Error, Exports_2.CancellationErrorCode.NoError, "Disconnecting"); - this.terminateMessageLoop = true; - return Promise.resolve(); - }; - ConversationServiceAdapter.prototype.processTypeSpecificMessages = function (connectionMessage, successCallback, errorCallBack) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, true]; - }); - }); - }; - // Cancels recognition. - ConversationServiceAdapter.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) { - this.terminateMessageLoop = true; - var cancelEvent = new Exports_2.ConversationTranslationCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId); - try { - if (!!this.privConversationServiceConnector.canceled) { - this.privConversationServiceConnector.canceled(this.privConversationServiceConnector, cancelEvent); + } + startNewRecognition() { + this.privRecognitionBytesSent = 0; + this.privIsSpeechEnded = false; + this.privIsRecognizing = true; + this.privTurnStartAudioOffset = 0; + this.privLastRecoOffset = 0; + this.privRecogNumber++; + this.privServiceTelemetryListener = new ServiceTelemetryListener_Internal_js_1.ServiceTelemetryListener(this.privRequestId, this.privAudioSourceId, this.privAudioNodeId); + this.onEvent(new RecognitionEvents_js_1.RecognitionTriggeredEvent(this.requestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId)); + } + async onAudioSourceAttachCompleted(audioNode, isError) { + this.privAudioNode = audioNode; + this.privIsAudioNodeDetached = false; + if (isError) { + await this.onComplete(); + } + else { + this.onEvent(new RecognitionEvents_js_1.ListeningStartedEvent(this.privRequestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId)); + } + } + onPreConnectionStart(authFetchEventId, connectionId) { + this.privAuthFetchEventId = authFetchEventId; + this.privSessionId = connectionId; + this.onEvent(new RecognitionEvents_js_1.ConnectingToServiceEvent(this.privRequestId, this.privAuthFetchEventId, this.privSessionId)); + } + async onAuthCompleted(isError) { + if (isError) { + await this.onComplete(); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async onConnectionEstablishCompleted(statusCode, reason) { + if (statusCode === 200) { + this.onEvent(new RecognitionEvents_js_1.RecognitionStartedEvent(this.requestId, this.privAudioSourceId, this.privAudioNodeId, this.privAuthFetchEventId, this.privSessionId)); + if (!!this.privAudioNode) { + this.privAudioNode.replay(); } + this.privTurnStartAudioOffset = this.privLastRecoOffset; + this.privBytesSent = 0; + return; + } + else if (statusCode === 403) { + await this.onComplete(); } - catch (_a) { - // continue on error + } + async onServiceTurnEndResponse(continuousRecognition) { + this.privTurnDeferral.resolve(); + if (!continuousRecognition || this.isSpeechEnded) { + await this.onComplete(); + this.privInTurn = false; + } + else { + // Start a new request set. + this.privTurnStartAudioOffset = this.privLastRecoOffset; + this.privAudioNode.replay(); + } + } + onSpeechContext() { + this.privRequestId = (0, Exports_js_1.createNoDashGuid)(); + } + onServiceTurnStartResponse() { + if (!!this.privTurnDeferral && !!this.privInTurn) { + // What? How are we starting a turn with another not done? + this.privTurnDeferral.reject("Another turn started before current completed."); + // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.privTurnDeferral.promise.then().catch(() => { }); + } + this.privInTurn = true; + this.privTurnDeferral = new Exports_js_1.Deferred(); + } + onHypothesis(offset) { + const audioReceivedTime = this.privAudioNode.findTimeAtOffset(offset); + if (!this.privHypothesisReceived) { + this.privHypothesisReceived = true; + this.privServiceTelemetryListener.hypothesisReceived(audioReceivedTime); } - }; + return audioReceivedTime > 0 ? Date.now() - audioReceivedTime : 0; + } + onPhraseRecognized(offset) { + const audioReceivedTime = this.privAudioNode.findTimeAtOffset(offset); + this.privServiceTelemetryListener.phraseReceived(audioReceivedTime); + this.onServiceRecognized(offset); + return audioReceivedTime > 0 ? Date.now() - audioReceivedTime : 0; + } + onServiceRecognized(offset) { + this.privLastRecoOffset = offset; + this.privHypothesisReceived = false; + this.privAudioNode.shrinkBuffers(offset); + this.privConnectionAttempts = 0; + } /** - * Establishes a websocket connection to the end point. + * The service has acknowledged audio up to `offset` (session-absolute, 100ns ticks); trim + * the replay buffer to that point so a reconnect resends only unacknowledged audio + * (shrinkBuffers is monotonic). */ - ConversationServiceAdapter.prototype.conversationConnectImpl = function (connection) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - this.privConnectionLoop = this.startMessageLoop(); - return [2 /*return*/, connection]; - }); - }); - }; - /** - * Process incoming websocket messages - */ - ConversationServiceAdapter.prototype.receiveConversationMessageOverride = function () { - return __awaiter(this, void 0, void 0, function () { - var communicationCustodian, connection, message, sessionId, sendFinal, commandPayload_1, participantsPayload, participantsResult, joinParticipantPayload, joiningParticipant, leavingParticipant, disconnectParticipant, token, speechPayload, speechResult, textPayload, textResult, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.isDisposed() || this.terminateMessageLoop) { - return [2 /*return*/, Promise.resolve()]; - } - communicationCustodian = new Exports_1.Deferred(); - _a.label = 1; - case 1: - _a.trys.push([1, 4, , 5]); - return [4 /*yield*/, this.fetchConnection()]; - case 2: - connection = _a.sent(); - return [4 /*yield*/, connection.read()]; - case 3: - message = _a.sent(); - if (this.isDisposed() || this.terminateMessageLoop) { - // We're done. - communicationCustodian.resolve(); - return [2 /*return*/, Promise.resolve()]; - } - if (!message) { - return [2 /*return*/, this.receiveConversationMessageOverride()]; - } - sessionId = this.privConversationRequestSession.sessionId; - sendFinal = false; - try { - switch (message.conversationMessageType.toLowerCase()) { - case "info": - case "participant_command": - case "command": - commandPayload_1 = Exports_4.CommandResponsePayload.fromJSON(message.textBody); - switch (commandPayload_1.command.toLowerCase()) { - /** - * 'ParticpantList' is the first message sent to the user after the websocket connection has opened. - * The consuming client must wait for this message to arrive - * before starting to send their own data. - */ - case "participantlist": - participantsPayload = Exports_4.ParticipantsListPayloadResponse.fromJSON(message.textBody); - participantsResult = participantsPayload.participants.map(function (p) { - var participant = { - avatar: p.avatar, - displayName: p.nickname, - id: p.participantId, - isHost: p.ishost, - isMuted: p.ismuted, - isUsingTts: p.usetts, - preferredLanguage: p.locale - }; - return participant; - }); - if (!!this.privConversationServiceConnector.participantsListReceived) { - this.privConversationServiceConnector.participantsListReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantsListEventArgs(participantsPayload.roomid, participantsPayload.token, participantsPayload.translateTo, participantsPayload.profanityFilter, participantsPayload.roomProfanityFilter, participantsPayload.roomLocked, participantsPayload.muteAll, participantsResult, sessionId)); - } - break; - /** - * 'SetTranslateToLanguages' represents the list of languages being used in the Conversation by all users(?). - * This is sent at the start of the Conversation - */ - case "settranslatetolanguages": - if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) { - this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.setTranslateToLanguages, commandPayload_1.value, sessionId)); - } - break; - /** - * 'SetProfanityFiltering' lets the client set the level of profanity filtering. - * If sent by the participant the setting will effect only their own profanity level. - * If sent by the host, the setting will effect all participants including the host. - * Note: the profanity filters differ from Speech Service (?): 'marked', 'raw', 'removed', 'tagged' - */ - case "setprofanityfiltering": - if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) { - this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.setProfanityFiltering, commandPayload_1.value, sessionId)); - } - break; - /** - * 'SetMute' is sent if the participant has been muted by the host. - * Check the 'participantId' to determine if the current user has been muted. - */ - case "setmute": - if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) { - this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.setMute, commandPayload_1.value, sessionId)); - } - break; - /** - * 'SetMuteAll' is sent if the Conversation has been muted by the host. - */ - case "setmuteall": - if (!!this.privConversationServiceConnector.muteAllCommandReceived) { - this.privConversationServiceConnector.muteAllCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.MuteAllEventArgs(commandPayload_1.value, sessionId)); - } - break; - /** - * 'RoomExpirationWarning' is sent towards the end of the Conversation session to give a timeout warning. - */ - case "roomexpirationwarning": - if (!!this.privConversationServiceConnector.conversationExpiration) { - this.privConversationServiceConnector.conversationExpiration(this.privConversationServiceConnector, new Exports_2.ConversationExpirationEventArgs(commandPayload_1.value, this.privConversationRequestSession.sessionId)); - } - break; - /** - * 'SetUseTts' is sent as a confirmation if the user requests TTS to be turned on or off. - */ - case "setusetts": - if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) { - this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.setUseTTS, commandPayload_1.value, sessionId)); - } - break; - /** - * 'SetLockState' is set if the host has locked or unlocked the Conversation. - */ - case "setlockstate": - if (!!this.privConversationServiceConnector.lockRoomCommandReceived) { - this.privConversationServiceConnector.lockRoomCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.LockRoomEventArgs(commandPayload_1.value, sessionId)); - } - break; - /** - * 'ChangeNickname' is received if a user changes their display name. - * Any cached particpiants list should be updated to reflect the display name. - */ - case "changenickname": - if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) { - this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.changeNickname, commandPayload_1.nickname, sessionId)); - } - break; - /** - * 'JoinSession' is sent when a user joins the Conversation. - */ - case "joinsession": - joinParticipantPayload = Exports_4.ParticipantPayloadResponse.fromJSON(message.textBody); - joiningParticipant = { - avatar: joinParticipantPayload.avatar, - displayName: joinParticipantPayload.nickname, - id: joinParticipantPayload.participantId, - isHost: joinParticipantPayload.ishost, - isMuted: joinParticipantPayload.ismuted, - isUsingTts: joinParticipantPayload.usetts, - preferredLanguage: joinParticipantPayload.locale, - }; - if (!!this.privConversationServiceConnector.participantJoinCommandReceived) { - this.privConversationServiceConnector.participantJoinCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantEventArgs(joiningParticipant, sessionId)); - } - break; - /** - * 'LeaveSession' is sent when a user leaves the Conversation'. - */ - case "leavesession": - leavingParticipant = { - id: commandPayload_1.participantId - }; - if (!!this.privConversationServiceConnector.participantLeaveCommandReceived) { - this.privConversationServiceConnector.participantLeaveCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantEventArgs(leavingParticipant, sessionId)); - } - break; - /** - * 'DisconnectSession' is sent when a user is disconnected from the session (e.g. network problem). - * Check the 'ParticipantId' to check whether the message is for the current user. - */ - case "disconnectsession": - disconnectParticipant = { - id: commandPayload_1.participantId - }; - break; - case "token": - token = new Exports_3.CognitiveTokenAuthentication(function (authFetchEventId) { - var authorizationToken = commandPayload_1.token; - return Promise.resolve(authorizationToken); - }, function (authFetchEventId) { - var authorizationToken = commandPayload_1.token; - return Promise.resolve(authorizationToken); - }); - this.authentication = token; - break; - /** - * Message not recognized. - */ - default: - break; - } - break; - /** - * 'partial' (or 'hypothesis') represents a unfinalized speech message. - */ - case "partial": - /** - * 'final' (or 'phrase') represents a finalized speech message. - */ - case "final": - speechPayload = Exports_4.SpeechResponsePayload.fromJSON(message.textBody); - speechResult = new Exports_2.ConversationTranslationResult(speechPayload.participantId, this.getTranslations(speechPayload.translations), speechPayload.language, undefined, undefined, speechPayload.recognition, undefined, undefined, message.textBody, undefined); - if (speechPayload.isFinal) { - // check the length, sometimes empty finals are returned - if (speechResult.text !== undefined && speechResult.text.length > 0) { - sendFinal = true; - } - else if (speechPayload.id === this.privLastPartialUtteranceId) { - // send final as normal. We had a non-empty partial for this same utterance - // so sending the empty final is important - sendFinal = true; - } - else { - // suppress unneeded final - } - if (sendFinal) { - if (!!this.privConversationServiceConnector.translationReceived) { - this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_1.ConversationTranslatorMessageTypes.final, speechResult, sessionId)); - } - } - } - else if (speechResult.text !== undefined) { - this.privLastPartialUtteranceId = speechPayload.id; - if (!!this.privConversationServiceConnector.translationReceived) { - this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_1.ConversationTranslatorMessageTypes.partial, speechResult, sessionId)); - } - } - break; - /** - * "translated_message" is a text message or instant message (IM). - */ - case "translated_message": - textPayload = Exports_4.TextResponsePayload.fromJSON(message.textBody); - textResult = new Exports_2.ConversationTranslationResult(textPayload.participantId, this.getTranslations(textPayload.translations), textPayload.language, undefined, undefined, textPayload.originalText, undefined, undefined, undefined, message.textBody, undefined); - if (!!this.privConversationServiceConnector.translationReceived) { - this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_1.ConversationTranslatorMessageTypes.instantMessage, textResult, sessionId)); - } - break; - default: - // ignore any unsupported message types - break; - } - } - catch (e) { - // continue - } - return [2 /*return*/, this.receiveConversationMessageOverride()]; - case 4: - e_1 = _a.sent(); - this.terminateMessageLoop = true; - return [3 /*break*/, 5]; - case 5: return [2 /*return*/, communicationCustodian.promise]; - } - }); - }); - }; - ConversationServiceAdapter.prototype.startMessageLoop = function () { - return __awaiter(this, void 0, void 0, function () { - var messageRetrievalPromise, r, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.isDisposed()) { - return [2 /*return*/, Promise.resolve()]; - } - this.terminateMessageLoop = false; - messageRetrievalPromise = this.receiveConversationMessageOverride(); - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, messageRetrievalPromise]; - case 2: - r = _a.sent(); - return [2 /*return*/, r]; - case 3: - error_1 = _a.sent(); - this.cancelRecognition(this.privRequestSession ? this.privRequestSession.sessionId : "", this.privRequestSession ? this.privRequestSession.requestId : "", Exports_2.CancellationReason.Error, Exports_2.CancellationErrorCode.RuntimeError, error_1); - return [2 /*return*/, null]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - // Takes an established websocket connection to the endpoint - ConversationServiceAdapter.prototype.configConnection = function () { - var _this = this; - if (this.isDisposed()) { - return Promise.resolve(undefined); - } - if (this.privConnectionConfigPromise) { - return this.privConnectionConfigPromise.then(function (connection) { - if (connection.state() === Exports_1.ConnectionState.Disconnected) { - _this.privConnectionId = null; - _this.privConnectionConfigPromise = null; - return _this.configConnection(); - } - return _this.privConnectionConfigPromise; - }, function (error) { - _this.privConnectionId = null; - _this.privConnectionConfigPromise = null; - return _this.configConnection(); - }); + onServiceAcknowledgedAudio(offset) { + if (!!this.privAudioNode) { + this.privAudioNode.shrinkBuffers(offset); + } + } + onAudioSent(bytesSent) { + this.privBytesSent += bytesSent; + this.privRecognitionBytesSent += bytesSent; + } + onRetryConnection() { + this.privConnectionAttempts++; + } + async dispose() { + if (!this.privIsDisposed) { + // we should have completed by now. If we did not its an unknown error. + this.privIsDisposed = true; + for (const detachable of this.privDetachables) { + await detachable.detach(); + } + if (!!this.privServiceTelemetryListener) { + this.privServiceTelemetryListener.dispose(); + } + this.privIsRecognizing = false; + } + } + getTelemetry() { + if (this.privServiceTelemetryListener.hasTelemetry) { + return this.privServiceTelemetryListener.getTelemetry(); + } + else { + return null; } - if (this.terminateMessageLoop) { - return Promise.resolve(undefined); + } + async onStopRecognizing() { + await this.onComplete(); + } + // Should be called with the audioNode for this session has indicated that it is out of speech. + onSpeechEnded() { + this.privIsSpeechEnded = true; + } + onEvent(event) { + if (!!this.privServiceTelemetryListener) { + this.privServiceTelemetryListener.onEvent(event); } - this.privConnectionConfigPromise = this.connectImpl().then(function (connection) { - return connection; - }); - return this.privConnectionConfigPromise; - }; - ConversationServiceAdapter.prototype.getTranslations = function (serviceResultTranslations) { - var translations; - if (undefined !== serviceResultTranslations) { - translations = new Exports_2.Translations(); - for (var _i = 0, serviceResultTranslations_1 = serviceResultTranslations; _i < serviceResultTranslations_1.length; _i++) { - var translation = serviceResultTranslations_1[_i]; - translations.set(translation.lang, translation.translation); + Exports_js_1.Events.instance.onEvent(event); + } + async onComplete() { + if (!!this.privIsRecognizing) { + this.privIsRecognizing = false; + await this.detachAudioNode(); + } + } + async detachAudioNode() { + if (!this.privIsAudioNodeDetached) { + this.privIsAudioNodeDetached = true; + if (this.privAudioNode) { + await this.privAudioNode.detach(); } } - return translations; - }; - return ConversationServiceAdapter; -}(Exports_3.ServiceRecognizerBase)); -exports.ConversationServiceAdapter = ConversationServiceAdapter; + } +} +exports.RequestSession = RequestSession; /***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { +/* 227 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationRequestSession = void 0; -var Exports_1 = __webpack_require__(4); -/** - * Placeholder class for the Conversation Request Session. Based off RequestSession. - * TODO: define what telemetry is required. - */ -var ConversationRequestSession = /** @class */ (function () { - function ConversationRequestSession(sessionId) { - var _this = this; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServiceTelemetryListener = void 0; +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(4); +const RecognitionEvents_js_1 = __webpack_require__(64); +class ServiceTelemetryListener { + constructor(requestId, audioSourceId, audioNodeId) { this.privIsDisposed = false; - this.privDetachables = new Array(); - this.onPreConnectionStart = function (authFetchEventId, connectionId) { - _this.privSessionId = connectionId; - }; - this.onAuthCompleted = function (isError, error) { - if (isError) { - _this.onComplete(); + this.privListeningTriggerMetric = null; + this.privMicMetric = null; + this.privConnectionEstablishMetric = null; + this.privRequestId = requestId; + this.privAudioSourceId = audioSourceId; + this.privAudioNodeId = audioNodeId; + this.privReceivedMessages = {}; + this.privPhraseLatencies = []; + this.privHypothesisLatencies = []; + } + phraseReceived(audioReceivedTime) { + if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it. + this.privPhraseLatencies.push(Date.now() - audioReceivedTime); + } + } + hypothesisReceived(audioReceivedTime) { + if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it. + this.privHypothesisLatencies.push(Date.now() - audioReceivedTime); + } + } + onEvent(e) { + if (this.privIsDisposed) { + return; + } + if (e instanceof RecognitionEvents_js_1.RecognitionTriggeredEvent && e.requestId === this.privRequestId) { + this.privListeningTriggerMetric = { + End: e.eventTime, + Name: "ListeningTrigger", + Start: e.eventTime, + }; + } + if (e instanceof Exports_js_1.AudioStreamNodeAttachingEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) { + this.privMicStartTime = e.eventTime; + } + if (e instanceof Exports_js_1.AudioStreamNodeAttachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) { + this.privMicStartTime = e.eventTime; + } + if (e instanceof Exports_js_1.AudioSourceErrorEvent && e.audioSourceId === this.privAudioSourceId) { + if (!this.privMicMetric) { + this.privMicMetric = { + End: e.eventTime, + Error: e.error, + Name: "Microphone", + Start: this.privMicStartTime, + }; } - }; - this.onConnectionEstablishCompleted = function (statusCode, reason) { - if (statusCode === 200) { - return; + } + if (e instanceof Exports_js_1.AudioStreamNodeErrorEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) { + if (!this.privMicMetric) { + this.privMicMetric = { + End: e.eventTime, + Error: e.error, + Name: "Microphone", + Start: this.privMicStartTime, + }; } - else if (statusCode === 403) { - _this.onComplete(); + } + if (e instanceof Exports_js_1.AudioStreamNodeDetachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) { + if (!this.privMicMetric) { + this.privMicMetric = { + End: e.eventTime, + Name: "Microphone", + Start: this.privMicStartTime, + }; } - }; - this.onServiceTurnEndResponse = function (continuousRecognition) { - if (!continuousRecognition) { - _this.onComplete(); + } + if (e instanceof RecognitionEvents_js_1.ConnectingToServiceEvent && e.requestId === this.privRequestId) { + this.privConnectionId = e.sessionId; + } + if (e instanceof Exports_js_1.ConnectionStartEvent && e.connectionId === this.privConnectionId) { + this.privConnectionStartTime = e.eventTime; + } + if (e instanceof Exports_js_1.ConnectionEstablishedEvent && e.connectionId === this.privConnectionId) { + if (!this.privConnectionEstablishMetric) { + this.privConnectionEstablishMetric = { + End: e.eventTime, + Id: this.privConnectionId, + Name: "Connection", + Start: this.privConnectionStartTime, + }; } - else { - _this.privRequestId = Exports_1.createNoDashGuid(); + } + if (e instanceof Exports_js_1.ConnectionEstablishErrorEvent && e.connectionId === this.privConnectionId) { + if (!this.privConnectionEstablishMetric) { + this.privConnectionEstablishMetric = { + End: e.eventTime, + Error: this.getConnectionError(e.statusCode), + Id: this.privConnectionId, + Name: "Connection", + Start: this.privConnectionStartTime, + }; } - }; - this.onComplete = function () { - // - }; - this.privSessionId = sessionId; - this.privRequestId = Exports_1.createNoDashGuid(); - this.privRequestCompletionDeferral = new Exports_1.Deferred(); - } - Object.defineProperty(ConversationRequestSession.prototype, "sessionId", { - get: function () { - return this.privSessionId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationRequestSession.prototype, "requestId", { - get: function () { - return this.privRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationRequestSession.prototype, "completionPromise", { - get: function () { - return this.privRequestCompletionDeferral.promise; - }, - enumerable: false, - configurable: true - }); - ConversationRequestSession.prototype.dispose = function (error) { - return __awaiter(this, void 0, void 0, function () { - var _i, _a, detachable; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!!this.privIsDisposed) return [3 /*break*/, 4]; - // we should have completed by now. If we did not its an unknown error. - this.privIsDisposed = true; - _i = 0, _a = this.privDetachables; - _b.label = 1; - case 1: - if (!(_i < _a.length)) return [3 /*break*/, 4]; - detachable = _a[_i]; - return [4 /*yield*/, detachable.detach()]; - case 2: - _b.sent(); - _b.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: return [2 /*return*/]; + } + if (e instanceof Exports_js_1.ConnectionMessageReceivedEvent && e.connectionId === this.privConnectionId) { + if (e.message && e.message.headers && e.message.headers.path) { + if (!this.privReceivedMessages[e.message.headers.path]) { + this.privReceivedMessages[e.message.headers.path] = new Array(); } + const maxMessagesToSend = 50; + if (this.privReceivedMessages[e.message.headers.path].length < maxMessagesToSend) { + this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime); + } + } + } + } + getTelemetry() { + const metrics = new Array(); + if (this.privListeningTriggerMetric) { + metrics.push(this.privListeningTriggerMetric); + } + if (this.privMicMetric) { + metrics.push(this.privMicMetric); + } + if (this.privConnectionEstablishMetric) { + metrics.push(this.privConnectionEstablishMetric); + } + if (this.privPhraseLatencies.length > 0) { + metrics.push({ + PhraseLatencyMs: this.privPhraseLatencies, }); - }); - }; - return ConversationRequestSession; -}()); -exports.ConversationRequestSession = ConversationRequestSession; - - - -/***/ }), -/* 217 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationReceivedTranslationEventArgs = exports.ParticipantsListEventArgs = exports.ParticipantAttributeEventArgs = exports.ParticipantEventArgs = exports.LockRoomEventArgs = exports.MuteAllEventArgs = void 0; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -var Exports_1 = __webpack_require__(61); -var MuteAllEventArgs = /** @class */ (function (_super) { - __extends(MuteAllEventArgs, _super); - function MuteAllEventArgs(isMuted, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privIsMuted = isMuted; - return _this; - } - Object.defineProperty(MuteAllEventArgs.prototype, "isMuted", { - get: function () { - return this.privIsMuted; - }, - enumerable: false, - configurable: true - }); - return MuteAllEventArgs; -}(Exports_1.SessionEventArgs)); -exports.MuteAllEventArgs = MuteAllEventArgs; -// tslint:disable-next-line: max-classes-per-file -var LockRoomEventArgs = /** @class */ (function (_super) { - __extends(LockRoomEventArgs, _super); - function LockRoomEventArgs(isLocked, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privIsLocked = isLocked; - return _this; - } - Object.defineProperty(LockRoomEventArgs.prototype, "isMuted", { - get: function () { - return this.privIsLocked; - }, - enumerable: false, - configurable: true - }); - return LockRoomEventArgs; -}(Exports_1.SessionEventArgs)); -exports.LockRoomEventArgs = LockRoomEventArgs; -// tslint:disable-next-line: max-classes-per-file -var ParticipantEventArgs = /** @class */ (function (_super) { - __extends(ParticipantEventArgs, _super); - function ParticipantEventArgs(participant, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privParticipant = participant; - return _this; - } - Object.defineProperty(ParticipantEventArgs.prototype, "participant", { - get: function () { - return this.privParticipant; - }, - enumerable: false, - configurable: true - }); - return ParticipantEventArgs; -}(Exports_1.SessionEventArgs)); -exports.ParticipantEventArgs = ParticipantEventArgs; -// tslint:disable-next-line: max-classes-per-file -var ParticipantAttributeEventArgs = /** @class */ (function (_super) { - __extends(ParticipantAttributeEventArgs, _super); - function ParticipantAttributeEventArgs(participantId, key, value, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privKey = key; - _this.privValue = value; - _this.privParticipantId = participantId; - return _this; - } - Object.defineProperty(ParticipantAttributeEventArgs.prototype, "value", { - get: function () { - return this.privValue; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantAttributeEventArgs.prototype, "key", { - get: function () { - return this.privKey; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantAttributeEventArgs.prototype, "id", { - get: function () { - return this.privParticipantId; - }, - enumerable: false, - configurable: true - }); - return ParticipantAttributeEventArgs; -}(Exports_1.SessionEventArgs)); -exports.ParticipantAttributeEventArgs = ParticipantAttributeEventArgs; -// tslint:disable-next-line: max-classes-per-file -var ParticipantsListEventArgs = /** @class */ (function (_super) { - __extends(ParticipantsListEventArgs, _super); - function ParticipantsListEventArgs(conversationId, token, translateTo, profanityFilter, roomProfanityFilter, isRoomLocked, isMuteAll, participants, sessionId) { - var _this = _super.call(this, sessionId) || this; - _this.privRoomId = conversationId; - _this.privSessionToken = token; - _this.privTranslateTo = translateTo; - _this.privProfanityFilter = profanityFilter; - _this.privRoomProfanityFilter = roomProfanityFilter; - _this.privIsRoomLocked = isRoomLocked; - _this.privIsRoomLocked = isMuteAll; - _this.privParticipants = participants; - return _this; - } - Object.defineProperty(ParticipantsListEventArgs.prototype, "sessionToken", { - get: function () { - return this.privSessionToken; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListEventArgs.prototype, "conversationId", { - get: function () { - return this.privRoomId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListEventArgs.prototype, "translateTo", { - get: function () { - return this.privTranslateTo; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListEventArgs.prototype, "profanityFilter", { - get: function () { - return this.privProfanityFilter; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListEventArgs.prototype, "roomProfanityFilter", { - get: function () { - return this.privRoomProfanityFilter; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListEventArgs.prototype, "isRoomLocked", { - get: function () { - return this.privIsRoomLocked; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListEventArgs.prototype, "isMuteAll", { - get: function () { - return this.privIsMuteAll; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListEventArgs.prototype, "participants", { - get: function () { - return this.privParticipants; - }, - enumerable: false, - configurable: true - }); - return ParticipantsListEventArgs; -}(Exports_1.SessionEventArgs)); -exports.ParticipantsListEventArgs = ParticipantsListEventArgs; -// tslint:disable-next-line: max-classes-per-file -var ConversationReceivedTranslationEventArgs = /** @class */ (function () { - function ConversationReceivedTranslationEventArgs(command, payload, sessionId) { - this.privPayload = payload; - this.privCommand = command; - this.privSessionId = sessionId; + } + if (this.privHypothesisLatencies.length > 0) { + metrics.push({ + FirstHypothesisLatencyMs: this.privHypothesisLatencies, + }); + } + const telemetry = { + Metrics: metrics, + ReceivedMessages: this.privReceivedMessages, + }; + const json = JSON.stringify(telemetry); + // We dont want to send the same telemetry again. So clean those out. + this.privReceivedMessages = {}; + this.privListeningTriggerMetric = null; + this.privMicMetric = null; + this.privConnectionEstablishMetric = null; + this.privPhraseLatencies = []; + this.privHypothesisLatencies = []; + return json; + } + // Determines if there are any telemetry events to send to the service. + get hasTelemetry() { + return (Object.keys(this.privReceivedMessages).length !== 0 || + this.privListeningTriggerMetric !== null || + this.privMicMetric !== null || + this.privConnectionEstablishMetric !== null || + this.privPhraseLatencies.length !== 0 || + this.privHypothesisLatencies.length !== 0); + } + dispose() { + this.privIsDisposed = true; } - Object.defineProperty(ConversationReceivedTranslationEventArgs.prototype, "payload", { - get: function () { - return this.privPayload; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationReceivedTranslationEventArgs.prototype, "command", { - get: function () { - return this.privCommand; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ConversationReceivedTranslationEventArgs.prototype, "sessionId", { - get: function () { - return this.privSessionId; - }, - enumerable: false, - configurable: true - }); - return ConversationReceivedTranslationEventArgs; -}()); -exports.ConversationReceivedTranslationEventArgs = ConversationReceivedTranslationEventArgs; + getConnectionError(statusCode) { + /* + -- Websocket status codes -- + NormalClosure = 1000, + EndpointUnavailable = 1001, + ProtocolError = 1002, + InvalidMessageType = 1003, + Empty = 1005, + InvalidPayloadData = 1007, + PolicyViolation = 1008, + MessageTooBig = 1009, + MandatoryExtension = 1010, + InternalServerError = 1011 + */ + switch (statusCode) { + case 400: + case 1002: + case 1003: + case 1005: + case 1007: + case 1008: + case 1009: return "BadRequest"; + case 401: return "Unauthorized"; + case 403: return "Forbidden"; + case 503: + case 1001: return "ServerUnavailable"; + case 500: + case 1011: return "ServerError"; + case 408: + case 504: return "Timeout"; + default: return "statuscode:" + statusCode.toString(); + } + } +} +exports.ServiceTelemetryListener = ServiceTelemetryListener; /***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { +/* 228 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConversationTranslatorCommandTypes = exports.ConversationTranslatorMessageTypes = exports.InternalParticipants = void 0; -/** Users participating in the conversation */ -var InternalParticipants = /** @class */ (function () { - function InternalParticipants(participants, meId) { - if (participants === void 0) { participants = []; } - this.participants = participants; - this.meId = meId; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechContext = void 0; +const PhraseDetectionContext_js_1 = __webpack_require__(116); +const PhraseOutput_js_1 = __webpack_require__(229); +/** + * Represents the JSON used in the speech.context message sent to the speech service. + * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object. + */ +class SpeechContext { + constructor(dynamicGrammar) { + this.privContext = {}; + this.privDynamicGrammar = dynamicGrammar; + } + getContext() { + return this.privContext; } /** - * Add or update a participant - * @param value + * @Internal + * This is only used by pronunciation assessment config. + * Do not use externally, object returned will change without warning or notice. */ - InternalParticipants.prototype.addOrUpdateParticipant = function (value) { - if (value === undefined) { - return; + setPronunciationAssessmentParams(params, isSpeakerDiarizationEnabled = false) { + if (this.privContext.phraseDetection === undefined) { + this.privContext.phraseDetection = { + enrichment: { + pronunciationAssessment: {} + } + }; } - var exists = this.getParticipantIndex(value.id); - if (exists > -1) { - this.participants.splice(exists, 1, value); + if (this.privContext.phraseDetection.enrichment === undefined) { + this.privContext.phraseDetection.enrichment = { + pronunciationAssessment: {} + }; } - else { - this.participants.push(value); + this.privContext.phraseDetection.enrichment.pronunciationAssessment = JSON.parse(params) || {}; + if (isSpeakerDiarizationEnabled) { + this.privContext.phraseDetection.mode = PhraseDetectionContext_js_1.RecognitionMode.Conversation; } - // ensure it was added ok - return this.getParticipant(value.id); - }; - /** - * Find the participant's position in the participants list. - * @param id - */ - InternalParticipants.prototype.getParticipantIndex = function (id) { - return this.participants.findIndex(function (p) { return p.id === id; }); - }; - /** - * Find the participant by id. - * @param id - */ - InternalParticipants.prototype.getParticipant = function (id) { - return this.participants.find(function (p) { return p.id === id; }); - }; - /*** - * Remove a participant from the participants list. - */ - InternalParticipants.prototype.deleteParticipant = function (id) { - this.participants = this.participants.filter(function (p) { return p.id !== id; }); - }; - Object.defineProperty(InternalParticipants.prototype, "host", { - /*** - * Helper to return the conversation host. - */ - get: function () { - return this.participants.find(function (p) { return p.isHost === true; }); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InternalParticipants.prototype, "me", { - /** - * Helper to return the current user. - */ - get: function () { - return this.getParticipant(this.meId); - }, - enumerable: false, - configurable: true - }); - return InternalParticipants; -}()); -exports.InternalParticipants = InternalParticipants; -/** - * List of command message types - */ -exports.ConversationTranslatorMessageTypes = { - command: "command", - final: "final", - info: "info", - instantMessage: "instant_message", - keepAlive: "keep_alive", - partial: "partial", - participantCommand: "participant_command", - translatedMessage: "translated_message" -}; -/** - * List of command types - */ -exports.ConversationTranslatorCommandTypes = { - changeNickname: "ChangeNickname", - disconnectSession: "DisconnectSession", - ejectParticipant: "EjectParticipant", - instant_message: "instant_message", - joinSession: "JoinSession", - leaveSession: "LeaveSession", - participantList: "ParticipantList", - roomExpirationWarning: "RoomExpirationWarning", - setLockState: "SetLockState", - setMute: "SetMute", - setMuteAll: "SetMuteAll", - setProfanityFiltering: "SetProfanityFiltering", - setTranslateToLanguages: "SetTranslateToLanguages", - setUseTTS: "SetUseTTS" -}; - - - -/***/ }), -/* 219 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var CommandResponsePayload_1 = __webpack_require__(220); -Object.defineProperty(exports, "CommandResponsePayload", { enumerable: true, get: function () { return CommandResponsePayload_1.CommandResponsePayload; } }); -var ParticipantResponsePayload_1 = __webpack_require__(221); -Object.defineProperty(exports, "ParticipantsListPayloadResponse", { enumerable: true, get: function () { return ParticipantResponsePayload_1.ParticipantsListPayloadResponse; } }); -Object.defineProperty(exports, "ParticipantPayloadResponse", { enumerable: true, get: function () { return ParticipantResponsePayload_1.ParticipantPayloadResponse; } }); -var TranslationResponsePayload_1 = __webpack_require__(222); -Object.defineProperty(exports, "SpeechResponsePayload", { enumerable: true, get: function () { return TranslationResponsePayload_1.SpeechResponsePayload; } }); -Object.defineProperty(exports, "TextResponsePayload", { enumerable: true, get: function () { return TranslationResponsePayload_1.TextResponsePayload; } }); - - - -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CommandResponsePayload = void 0; -var CommandResponsePayload = /** @class */ (function () { - function CommandResponsePayload(json) { - this.privCommandResponse = JSON.parse(json); - } - CommandResponsePayload.fromJSON = function (json) { - return new CommandResponsePayload(json); - }; - Object.defineProperty(CommandResponsePayload.prototype, "type", { - get: function () { - return this.privCommandResponse.type; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CommandResponsePayload.prototype, "command", { - get: function () { - return this.privCommandResponse.command; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CommandResponsePayload.prototype, "id", { - get: function () { - return this.privCommandResponse.id; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CommandResponsePayload.prototype, "nickname", { - get: function () { - return this.privCommandResponse.nickname; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CommandResponsePayload.prototype, "participantId", { - get: function () { - return this.privCommandResponse.participantId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CommandResponsePayload.prototype, "roomid", { - get: function () { - return this.privCommandResponse.roomid; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CommandResponsePayload.prototype, "value", { - get: function () { - return this.privCommandResponse.value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CommandResponsePayload.prototype, "token", { - get: function () { - return this.privCommandResponse.token; - }, - enumerable: false, - configurable: true - }); - return CommandResponsePayload; -}()); -exports.CommandResponsePayload = CommandResponsePayload; - - - -/***/ }), -/* 221 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ParticipantPayloadResponse = exports.ParticipantsListPayloadResponse = void 0; -var ParticipantsListPayloadResponse = /** @class */ (function () { - function ParticipantsListPayloadResponse(json) { - this.privParticipantsPayloadResponse = JSON.parse(json); - } - ParticipantsListPayloadResponse.fromJSON = function (json) { - return new ParticipantsListPayloadResponse(json); - }; - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "roomid", { - get: function () { - return this.privParticipantsPayloadResponse.roomid; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "id", { - get: function () { - return this.privParticipantsPayloadResponse.id; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "command", { - get: function () { - return this.privParticipantsPayloadResponse.command; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "participants", { - get: function () { - return this.privParticipantsPayloadResponse.participants; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "token", { - get: function () { - return this.privParticipantsPayloadResponse.token; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "translateTo", { - get: function () { - return this.privParticipantsPayloadResponse.translateTo; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "profanityFilter", { - get: function () { - return this.privParticipantsPayloadResponse.profanityFilter; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "roomProfanityFilter", { - get: function () { - return this.privParticipantsPayloadResponse.roomProfanityFilter; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "roomLocked", { - get: function () { - return this.privParticipantsPayloadResponse.roomLocked; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "muteAll", { - get: function () { - return this.privParticipantsPayloadResponse.muteAll; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantsListPayloadResponse.prototype, "type", { - get: function () { - return this.privParticipantsPayloadResponse.type; - }, - enumerable: false, - configurable: true - }); - return ParticipantsListPayloadResponse; -}()); -exports.ParticipantsListPayloadResponse = ParticipantsListPayloadResponse; -// tslint:disable-next-line: max-classes-per-file -var ParticipantPayloadResponse = /** @class */ (function () { - function ParticipantPayloadResponse(json) { - this.privParticipantPayloadResponse = JSON.parse(json); - } - ParticipantPayloadResponse.fromJSON = function (json) { - return new ParticipantPayloadResponse(json); - }; - Object.defineProperty(ParticipantPayloadResponse.prototype, "nickname", { - get: function () { - return this.privParticipantPayloadResponse.nickname; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantPayloadResponse.prototype, "locale", { - get: function () { - return this.privParticipantPayloadResponse.locale; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantPayloadResponse.prototype, "usetts", { - get: function () { - return this.privParticipantPayloadResponse.usetts; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantPayloadResponse.prototype, "ismuted", { - get: function () { - return this.privParticipantPayloadResponse.ismuted; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantPayloadResponse.prototype, "ishost", { - get: function () { - return this.privParticipantPayloadResponse.ishost; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantPayloadResponse.prototype, "participantId", { - get: function () { - return this.privParticipantPayloadResponse.participantId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ParticipantPayloadResponse.prototype, "avatar", { - get: function () { - return this.privParticipantPayloadResponse.avatar; - }, - enumerable: false, - configurable: true - }); - return ParticipantPayloadResponse; -}()); -exports.ParticipantPayloadResponse = ParticipantPayloadResponse; + this.setWordLevelTimings(); + this.privContext.phraseOutput.detailed.options.push(PhraseOutput_js_1.PhraseOption.PronunciationAssessment); + if (this.privContext.phraseOutput.detailed.options.indexOf(PhraseOutput_js_1.PhraseOption.SNR) === -1) { + this.privContext.phraseOutput.detailed.options.push(PhraseOutput_js_1.PhraseOption.SNR); + } + } + setDetailedOutputFormat() { + if (this.privContext.phraseOutput === undefined) { + this.privContext.phraseOutput = { + detailed: { + options: [] + } + }; + } + if (this.privContext.phraseOutput.detailed === undefined) { + this.privContext.phraseOutput.detailed = { + options: [] + }; + } + this.privContext.phraseOutput.format = PhraseOutput_js_1.OutputFormat.Detailed; + } + setWordLevelTimings() { + if (this.privContext.phraseOutput === undefined) { + this.privContext.phraseOutput = { + detailed: { + options: [] + } + }; + } + if (this.privContext.phraseOutput.detailed === undefined) { + this.privContext.phraseOutput.detailed = { + options: [] + }; + } + this.privContext.phraseOutput.format = PhraseOutput_js_1.OutputFormat.Detailed; + if (this.privContext.phraseOutput.detailed.options.indexOf(PhraseOutput_js_1.PhraseOption.WordTimings) === -1) { + this.privContext.phraseOutput.detailed.options.push(PhraseOutput_js_1.PhraseOption.WordTimings); + } + } + setSpeakerDiarizationAudioOffsetMs(audioOffsetMs) { + this.privContext.phraseDetection.speakerDiarization.audioOffsetMs = audioOffsetMs; + } + toJSON() { + const dgi = this.privDynamicGrammar.generateGrammarObject(); + this.privContext.dgi = dgi; + const ret = JSON.stringify(this.privContext); + return ret; + } +} +exports.SpeechContext = SpeechContext; /***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { +/* 229 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TextResponsePayload = exports.SpeechResponsePayload = void 0; -var SpeechResponsePayload = /** @class */ (function () { - function SpeechResponsePayload(json) { - this.privSpeechResponse = JSON.parse(json); - } - SpeechResponsePayload.fromJSON = function (json) { - return new SpeechResponsePayload(json); - }; - Object.defineProperty(SpeechResponsePayload.prototype, "recognition", { - get: function () { - return this.privSpeechResponse.recognition; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "translations", { - get: function () { - return this.privSpeechResponse.translations; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "id", { - get: function () { - return this.privSpeechResponse.id; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "language", { - get: function () { - return this.privSpeechResponse.language; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "nickname", { - get: function () { - return this.privSpeechResponse.nickname; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "participantId", { - get: function () { - return this.privSpeechResponse.participantId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "roomid", { - get: function () { - return this.privSpeechResponse.roomid; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "timestamp", { - get: function () { - return this.privSpeechResponse.timestamp; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "type", { - get: function () { - return this.privSpeechResponse.type; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeechResponsePayload.prototype, "isFinal", { - get: function () { - return this.privSpeechResponse.type === "final"; - }, - enumerable: false, - configurable: true - }); - return SpeechResponsePayload; -}()); -exports.SpeechResponsePayload = SpeechResponsePayload; -// tslint:disable-next-line: max-classes-per-file -var TextResponsePayload = /** @class */ (function () { - function TextResponsePayload(json) { - this.privTextResponse = JSON.parse(json); - } - TextResponsePayload.fromJSON = function (json) { - return new TextResponsePayload(json); - }; - Object.defineProperty(TextResponsePayload.prototype, "originalText", { - get: function () { - return this.privTextResponse.originalText; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextResponsePayload.prototype, "translations", { - get: function () { - return this.privTextResponse.translations; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextResponsePayload.prototype, "id", { - get: function () { - return this.privTextResponse.id; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextResponsePayload.prototype, "language", { - get: function () { - return this.privTextResponse.language; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextResponsePayload.prototype, "nickname", { - get: function () { - return this.privTextResponse.nickname; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextResponsePayload.prototype, "participantId", { - get: function () { - return this.privTextResponse.participantId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextResponsePayload.prototype, "roomid", { - get: function () { - return this.privTextResponse.roomid; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextResponsePayload.prototype, "timestamp", { - get: function () { - return this.privTextResponse.timestamp; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextResponsePayload.prototype, "type", { - get: function () { - return this.privTextResponse.type; - }, - enumerable: false, - configurable: true - }); - return TextResponsePayload; -}()); -exports.TextResponsePayload = TextResponsePayload; +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TentativePhraseResultsOption = exports.OutputFormat = exports.PhraseExtension = exports.PhraseOption = void 0; +/** + * The detailed output options. + */ +var PhraseOption; +(function (PhraseOption) { + PhraseOption["WordTimings"] = "WordTimings"; + PhraseOption["SNR"] = "SNR"; + PhraseOption["Pronunciation"] = "Pronunciation"; + PhraseOption["WordPronunciation"] = "WordPronunciation"; + PhraseOption["WordConfidence"] = "WordConfidence"; + PhraseOption["Words"] = "Words"; + PhraseOption["Sentiment"] = "Sentiment"; + PhraseOption["PronunciationAssessment"] = "PronunciationAssessment"; + PhraseOption["ContentAssessment"] = "ContentAssessment"; + PhraseOption["PhraseAMScore"] = "PhraseAMScore"; + PhraseOption["PhraseLMScore"] = "PhraseLMScore"; + PhraseOption["WordAMScore"] = "WordAMScore"; + PhraseOption["WordLMScore"] = "WordLMScore"; + PhraseOption["RuleTree"] = "RuleTree"; + PhraseOption["NBestTimings"] = "NBestTimings"; + PhraseOption["DecoderDiagnostics"] = "DecoderDiagnostics"; + PhraseOption["DisplayWordTimings"] = "DisplayWordTimings"; + PhraseOption["DisplayWords"] = "DisplayWords"; +})(PhraseOption = exports.PhraseOption || (exports.PhraseOption = {})); +/** + * The detailed output extensions. + */ +var PhraseExtension; +(function (PhraseExtension) { + PhraseExtension["Graph"] = "Graph"; + PhraseExtension["Corrections"] = "Corrections"; + PhraseExtension["Sentiment"] = "Sentiment"; +})(PhraseExtension = exports.PhraseExtension || (exports.PhraseExtension = {})); +/** + * The Recognition modes + */ +var OutputFormat; +(function (OutputFormat) { + OutputFormat["Simple"] = "Simple"; + OutputFormat["Detailed"] = "Detailed"; +})(OutputFormat = exports.OutputFormat || (exports.OutputFormat = {})); +/** + * The Tentative Phrase Results option + */ +var TentativePhraseResultsOption; +(function (TentativePhraseResultsOption) { + TentativePhraseResultsOption["None"] = "None"; + TentativePhraseResultsOption["Always"] = "Always"; +})(TentativePhraseResultsOption = exports.TentativePhraseResultsOption || (exports.TentativePhraseResultsOption = {})); /***/ }), -/* 223 */ -/***/ (function(module, exports, __webpack_require__) { +/* 230 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReconnectContinuationState = void 0; +const HeaderNames_js_1 = __webpack_require__(59); +/** + * Tracks the per-turn state required by the reliable reconnect protocol. + * + * The service issues a continuation token, per-stream resume offsets and a service tag on its + * responses. When a turn is interrupted before "turn.end", the client echoes these values back + * in the next "speech.context" so the service can suppress duplicate results, correct media + * offsets and correlate the reconnected turn. + * + * Intentionally dependency-free so it can be unit tested in isolation. + */ +class ReconnectContinuationState { + constructor(defaultStreamId = "1") { + this.privDefaultStreamId = defaultStreamId; } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TranscriberRecognizer = void 0; -var Exports_1 = __webpack_require__(4); -var Contracts_1 = __webpack_require__(63); -var Exports_2 = __webpack_require__(61); -var Exports_3 = __webpack_require__(53); -var TranscriberRecognizer = /** @class */ (function (_super) { - __extends(TranscriberRecognizer, _super); /** - * TranscriberRecognizer constructor. - * @constructor - * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer + * The stream id used for the single logical audio stream the SDK currently sends. */ - function TranscriberRecognizer(speechTranslationConfig, audioConfig) { - var _this = this; - var speechTranslationConfigImpl = speechTranslationConfig; - Contracts_1.Contracts.throwIfNull(speechTranslationConfigImpl, "speechTranslationConfig"); - Contracts_1.Contracts.throwIfNullOrWhitespace(speechTranslationConfigImpl.speechRecognitionLanguage, Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage]); - _this = _super.call(this, audioConfig, speechTranslationConfigImpl.properties, new Exports_3.TranscriberConnectionFactory()) || this; - _this.privDisposedRecognizer = false; - return _this; - } - TranscriberRecognizer.prototype.getConversationInfo = function () { - Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation, "Conversation"); - return this.privConversation.conversationInfo; - }; - Object.defineProperty(TranscriberRecognizer.prototype, "authorizationToken", { - get: function () { - return this.properties.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token); - }, - set: function (token) { - Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token"); - this.properties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, token); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranscriberRecognizer.prototype, "conversation", { - set: function (c) { - Contracts_1.Contracts.throwIfNullOrUndefined(c, "Conversation"); - this.privConversation = c; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranscriberRecognizer.prototype, "speechRecognitionLanguage", { - get: function () { - Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); - return this.properties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TranscriberRecognizer.prototype, "properties", { - get: function () { - return this.privProperties; - }, - enumerable: false, - configurable: true - }); - TranscriberRecognizer.prototype.startContinuousRecognitionAsync = function (cb, err) { - Exports_1.marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(Exports_3.RecognitionMode.Conversation), cb, err); - }; - TranscriberRecognizer.prototype.stopContinuousRecognitionAsync = function (cb, err) { - Exports_1.marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err); - }; - TranscriberRecognizer.prototype.close = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!this.privDisposedRecognizer) return [3 /*break*/, 2]; - return [4 /*yield*/, this.dispose(true)]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - // Push async join/leave conversation message via serviceRecognizer - TranscriberRecognizer.prototype.pushConversationEvent = function (conversationInfo, command) { - return __awaiter(this, void 0, void 0, function () { - var reco; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - reco = (this.privReco); - Contracts_1.Contracts.throwIfNullOrUndefined(reco, "serviceRecognizer"); - return [4 /*yield*/, reco.sendSpeechEventAsync(conversationInfo, command)]; - case 1: - _a.sent(); - return [2 /*return*/]; + get defaultStreamId() { + return this.privDefaultStreamId; + } + /** + * The session-absolute resume offset (100ns ticks) most recently acknowledged by the + * service, or undefined if none has arrived. Used both to populate the outgoing + * continuation block and to trim the replay buffer. + */ + get streamOffset() { + return this.privStreamOffset; + } + /** + * True when the continuation block must be emitted. The block is emitted whenever any of + * the three signals is present (token, service tag or stream offset). The signals persist + * for the whole session, so the block keeps being + * emitted on reconnects and subsequent turns once the first turn.start has been seen. + */ + get hasPendingContinuation() { + return this.privToken !== undefined + || this.privServiceTag !== undefined + || this.privStreamOffset !== undefined; + } + /** + * Resets all state. Called when a brand new recognition (session) starts. + */ + reset() { + this.privToken = undefined; + this.privServiceTag = undefined; + this.privStreamOffset = undefined; + } + /** + * A turn has started ("turn.start"). The service tag arrives in the turn.start body (under + * "$.context.serviceTag"), not a header. The tag is stored unconditionally + * (empty string when absent) and the token/offset are NOT cleared: the offset is + * session-global and the token persists until the service issues a new one. + */ + onTurnStart(serviceTag) { + this.privServiceTag = serviceTag ?? ""; + } + /** + * Captures the reliable-reconnect headers (continuation token and stream resume offset) + * from an inbound message. Header names are case-insensitive, so matching is too. The + * service tag is not a header; it comes from the turn.start body via onTurnStart(). + * + * The per-stream offset header is turn-relative. It is rebased onto the session-absolute + * timeline using `turnStartOffset` + * (RequestSession.currentTurnAudioOffset) - the same base used to rebase every other + * service offset - so the stored offset stays in the same frame as results and replay. + */ + updateFromHeaders(headers, turnStartOffset = 0) { + if (!headers) { + return; + } + const tokenHeader = HeaderNames_js_1.HeaderNames.ContinuationToken.toLowerCase(); + const offsetHeader = HeaderNames_js_1.HeaderNames.ContinuationAudioStreamOffset.toLowerCase(); + for (const headerName in headers) { + if (!headerName) { + continue; + } + const lowerName = headerName.toLowerCase(); + const value = headers[headerName]; + if (lowerName === tokenHeader) { + this.privToken = value; + } + else if (lowerName === offsetHeader) { + const relativeOffset = parseInt(value, 10); + if (!isNaN(relativeOffset)) { + // Rebase onto the session-absolute timeline and store only when it advances, + // so an out-of-order offset never regresses the resume position. + const absoluteOffset = turnStartOffset + relativeOffset; + if (this.privStreamOffset === undefined || absoluteOffset > this.privStreamOffset) { + this.privStreamOffset = absoluteOffset; + } } - }); - }); - }; - TranscriberRecognizer.prototype.connectCallbacks = function (transcriber) { - this.canceled = function (s, e) { - if (!!transcriber.canceled) { - transcriber.canceled(transcriber, e); - } - }; - this.conversationCanceled = function (s, e) { - if (!!transcriber.conversationCanceled) { - transcriber.conversationCanceled(transcriber, e); - } - }; - this.recognizing = function (s, e) { - if (!!transcriber.transcribing) { - transcriber.transcribing(transcriber, e); - } - }; - this.recognized = function (s, e) { - if (!!transcriber.transcribed) { - transcriber.transcribed(transcriber, e); - } - }; - this.conversationStarted = function (s, e) { - if (!!transcriber.conversationStarted) { - transcriber.conversationStarted(transcriber, e); - } - }; - this.conversationStopped = function (s, e) { - if (!!transcriber.conversationStopped) { - transcriber.conversationStopped(transcriber, e); - } - }; - this.sessionStarted = function (s, e) { - if (!!transcriber.sessionStarted) { - transcriber.sessionStarted(transcriber, e); - } - }; - this.sessionStopped = function (s, e) { - if (!!transcriber.sessionStopped) { - transcriber.sessionStopped(transcriber, e); } - }; - }; - TranscriberRecognizer.prototype.disconnectCallbacks = function () { - this.canceled = undefined; - this.recognizing = undefined; - this.recognized = undefined; - this.sessionStarted = undefined; - this.sessionStopped = undefined; - this.conversationCanceled = undefined; - this.conversationStarted = undefined; - this.conversationStopped = undefined; - }; + } + } /** - * Disposes any resources held by the object. - * @member ConversationTranscriber.prototype.dispose - * @function - * @public - * @param {boolean} disposing - true if disposing the object. + * Builds the "$.audio.streams" metadata section. This is always sent when the feature is + * enabled and is the prerequisite for the service to return continuation headers. */ - TranscriberRecognizer.prototype.dispose = function (disposing) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privDisposedRecognizer) { - return [2 /*return*/]; - } - if (!disposing) return [3 /*break*/, 2]; - this.privDisposedRecognizer = true; - return [4 /*yield*/, this.implRecognizerStop()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)]; - case 3: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - TranscriberRecognizer.prototype.createRecognizerConfig = function (speechConfig) { - return new Exports_3.RecognizerConfig(speechConfig, this.properties); - }; - TranscriberRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) { - var configImpl = audioConfig; - return new Exports_3.TranscriptionServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this); - }; - return TranscriberRecognizer; -}(Exports_2.Recognizer)); -exports.TranscriberRecognizer = TranscriberRecognizer; - - - -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesisAudioMetadata = exports.MetadataType = void 0; -var MetadataType; -(function (MetadataType) { - MetadataType["WordBoundary"] = "WordBoundary"; - MetadataType["Bookmark"] = "Bookmark"; - MetadataType["Viseme"] = "Viseme"; -})(MetadataType = exports.MetadataType || (exports.MetadataType = {})); -var SynthesisAudioMetadata = /** @class */ (function () { - function SynthesisAudioMetadata(json) { - this.privSynthesisAudioMetadata = JSON.parse(json); + buildAudioStreamsMetadata() { + const streams = {}; + // The stream is opted in with "":null (not an empty object); only the null marker + // enables the continuation contract service-side. + streams[this.privDefaultStreamId] = null; + return { streams }; } - SynthesisAudioMetadata.fromJSON = function (json) { - return new SynthesisAudioMetadata(json); - }; - Object.defineProperty(SynthesisAudioMetadata.prototype, "Metadata", { - get: function () { - return this.privSynthesisAudioMetadata.Metadata; - }, - enumerable: false, - configurable: true - }); - return SynthesisAudioMetadata; -}()); -exports.SynthesisAudioMetadata = SynthesisAudioMetadata; + /** + * Builds the "$.continuation" section to resume an aborted turn, or undefined when this + * is a fresh turn (and therefore must not carry a continuation). + */ + buildContinuationContext() { + if (!this.hasPendingContinuation) { + return undefined; + } + // Always emit "token" and "previousServiceTag" (defaulting to "") and add the + // audio stream offset only when one is known. + const continuation = { + previousServiceTag: this.privServiceTag ?? "", + token: this.privToken ?? "" + }; + if (this.privStreamOffset !== undefined) { + continuation.audio = { + streams: { [this.privDefaultStreamId]: { offset: this.privStreamOffset } } + }; + } + return continuation; + } +} +exports.ReconnectContinuationState = ReconnectContinuationState; /***/ }), -/* 225 */ -/***/ (function(module, exports, __webpack_require__) { +/* 231 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DynamicGrammarBuilder = void 0; +const Group_js_1 = __webpack_require__(232); +/** + * Responsible for building the object to be sent to the speech service to support dynamic grammars. + * @class DynamicGrammarBuilder + */ +class DynamicGrammarBuilder { + constructor() { + this.privWeight = 1.0; } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesisTurn = void 0; -var Exports_1 = __webpack_require__(4); -var AudioOutputStream_1 = __webpack_require__(73); -var SynthesisAdapterBase_1 = __webpack_require__(226); -var SynthesisEvents_1 = __webpack_require__(227); -var SynthesisTurn = /** @class */ (function () { - function SynthesisTurn() { - var _this = this; - this.privIsDisposed = false; - this.privIsSynthesizing = false; - this.privIsSynthesisEnded = false; - this.privBytesReceived = 0; - this.privInTurn = false; - this.privTextOffset = 0; - this.privNextSearchTextIndex = 0; - this.onPreConnectionStart = function (authFetchEventId, connectionId) { - _this.privAuthFetchEventId = authFetchEventId; - _this.onEvent(new SynthesisEvents_1.ConnectingToSynthesisServiceEvent(_this.privRequestId, _this.privAuthFetchEventId)); - }; - this.onAuthCompleted = function (isError, error) { - if (isError) { - _this.onComplete(); - } - }; - this.onConnectionEstablishCompleted = function (statusCode, reason) { - if (statusCode === 200) { - _this.onEvent(new SynthesisEvents_1.SynthesisStartedEvent(_this.requestId, _this.privAuthFetchEventId)); - _this.privBytesReceived = 0; - return; - } - else if (statusCode === 403) { - _this.onComplete(); - } - }; - this.onServiceResponseMessage = function (responseJson) { - var response = JSON.parse(responseJson); - _this.streamId = response.audio.streamId; - }; - this.onServiceTurnEndResponse = function () { - _this.privInTurn = false; - _this.privTurnDeferral.resolve(); - _this.onComplete(); - }; - this.onServiceTurnStartResponse = function () { - if (!!_this.privTurnDeferral && !!_this.privInTurn) { - // What? How are we starting a turn with another not done? - _this.privTurnDeferral.reject("Another turn started before current completed."); - // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited - /* tslint:disable:no-empty */ - _this.privTurnDeferral.promise.then().catch(function () { }); - } - _this.privInTurn = true; - _this.privTurnDeferral = new Exports_1.Deferred(); - }; - this.dispose = function (error) { - if (!_this.privIsDisposed) { - // we should have completed by now. If we did not its an unknown error. - _this.privIsDisposed = true; - } - }; - this.onEvent = function (event) { - Exports_1.Events.instance.onEvent(event); - }; - this.onComplete = function () { - if (_this.privIsSynthesizing) { - _this.privIsSynthesizing = false; - _this.privIsSynthesisEnded = true; - _this.privAudioOutputStream.close(); - _this.privInTurn = false; - if (_this.privTurnAudioDestination !== undefined) { - _this.privTurnAudioDestination.close(); - _this.privTurnAudioDestination = undefined; - } - } - }; - this.privRequestId = Exports_1.createNoDashGuid(); - this.privTurnDeferral = new Exports_1.Deferred(); - // We're not in a turn, so resolve. - this.privTurnDeferral.resolve(); + // Adds one more reference phrases to the dynamic grammar to send. + // All added phrases are generic phrases. + addPhrase(phrase) { + if (!this.privPhrases) { + this.privPhrases = []; + } + if (phrase instanceof Array) { + this.privPhrases = this.privPhrases.concat(phrase); + } + else { + this.privPhrases.push(phrase); + } } - Object.defineProperty(SynthesisTurn.prototype, "requestId", { - get: function () { - return this.privRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisTurn.prototype, "streamId", { - get: function () { - return this.privStreamId; - }, - set: function (value) { - this.privStreamId = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisTurn.prototype, "audioOutputFormat", { - get: function () { - return this.privAudioOutputFormat; - }, - set: function (format) { - this.privAudioOutputFormat = format; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisTurn.prototype, "turnCompletionPromise", { - get: function () { - return this.privTurnDeferral.promise; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisTurn.prototype, "isSynthesisEnded", { - get: function () { - return this.privIsSynthesisEnded; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisTurn.prototype, "isSynthesizing", { - get: function () { - return this.privIsSynthesizing; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisTurn.prototype, "currentTextOffset", { - get: function () { - return this.privTextOffset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisTurn.prototype, "bytesReceived", { - // The number of bytes received for current turn - get: function () { - return this.privBytesReceived; - }, - enumerable: false, - configurable: true - }); - SynthesisTurn.prototype.getAllReceivedAudio = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!this.privReceivedAudio) { - return [2 /*return*/, Promise.resolve(this.privReceivedAudio)]; - } - if (!this.privIsSynthesisEnded) { - return [2 /*return*/, null]; - } - return [4 /*yield*/, this.readAllAudioFromStream()]; - case 1: - _a.sent(); - return [2 /*return*/, Promise.resolve(this.privReceivedAudio)]; - } - }); - }); - }; - SynthesisTurn.prototype.getAllReceivedAudioWithHeader = function () { - return __awaiter(this, void 0, void 0, function () { - var audio; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!this.privReceivedAudioWithHeader) { - return [2 /*return*/, this.privReceivedAudioWithHeader]; - } - if (!this.privIsSynthesisEnded) { - return [2 /*return*/, null]; - } - if (!this.audioOutputFormat.hasHeader) return [3 /*break*/, 2]; - return [4 /*yield*/, this.getAllReceivedAudio()]; - case 1: - audio = _a.sent(); - this.privReceivedAudioWithHeader = SynthesisAdapterBase_1.SynthesisAdapterBase.addHeader(audio, this.audioOutputFormat); - return [2 /*return*/, this.privReceivedAudioWithHeader]; - case 2: return [2 /*return*/, this.getAllReceivedAudio()]; - } - }); - }); - }; - SynthesisTurn.prototype.startNewSynthesis = function (requestId, rawText, isSSML, audioDestination) { - this.privIsSynthesisEnded = false; - this.privIsSynthesizing = true; - this.privRequestId = requestId; - this.privRawText = rawText; - this.privIsSSML = isSSML; - this.privAudioOutputStream = new AudioOutputStream_1.PullAudioOutputStreamImpl(); - this.privAudioOutputStream.format = this.privAudioOutputFormat; - this.privReceivedAudio = null; - this.privReceivedAudioWithHeader = null; - this.privBytesReceived = 0; - this.privTextOffset = 0; - this.privNextSearchTextIndex = 0; - this.privPartialVisemeAnimation = ""; - if (audioDestination !== undefined) { - this.privTurnAudioDestination = audioDestination; - this.privTurnAudioDestination.format = this.privAudioOutputFormat; + // Clears all phrases stored in the current object. + clearPhrases() { + this.privPhrases = undefined; + } + // Adds one or more reference grammars to the current grammar. + addReferenceGrammar(grammar) { + if (!this.privGrammars) { + this.privGrammars = []; } - this.onEvent(new SynthesisEvents_1.SynthesisTriggeredEvent(this.requestId, undefined, audioDestination === undefined ? undefined : audioDestination.id())); - }; - SynthesisTurn.prototype.onAudioChunkReceived = function (data) { - if (this.isSynthesizing) { - this.privAudioOutputStream.write(data); - this.privBytesReceived += data.byteLength; - if (this.privTurnAudioDestination !== undefined) { - this.privTurnAudioDestination.write(data); - } + if (grammar instanceof Array) { + this.privGrammars = this.privGrammars.concat(grammar); } - }; - SynthesisTurn.prototype.onWordBoundaryEvent = function (text) { - this.updateTextOffset(text); - }; - SynthesisTurn.prototype.onVisemeMetadataReceived = function (metadata) { - if (metadata.Data.AnimationChunk !== undefined) { - this.privPartialVisemeAnimation += metadata.Data.AnimationChunk; + else { + this.privGrammars.push(grammar); } - }; - SynthesisTurn.prototype.onStopSynthesizing = function () { - this.onComplete(); - }; - /** - * Gets the viseme animation string (merged from animation chunk), and clears the internal - * partial animation. - */ - SynthesisTurn.prototype.getAndClearVisemeAnimation = function () { - var animation = this.privPartialVisemeAnimation; - this.privPartialVisemeAnimation = ""; - return animation; - }; - SynthesisTurn.prototype.updateTextOffset = function (text) { - if (this.privTextOffset >= 0) { - this.privTextOffset = this.privRawText.indexOf(text, this.privNextSearchTextIndex); - if (this.privTextOffset >= 0) { - this.privNextSearchTextIndex = this.privTextOffset + text.length; - } - if (this.privIsSSML) { - if (this.privRawText.indexOf("<", this.privTextOffset + 1) > this.privRawText.indexOf(">", this.privTextOffset + 1)) { - this.updateTextOffset(text); - } - } + } + // clears all grammars stored on the recognizer. + clearGrammars() { + this.privGrammars = undefined; + } + // Sets the weight for the dynamic grammar. + setWeight(weight) { + this.privWeight = weight; + } + // Generates an object that represents the dynamic grammar used by the Speech Service. + // This is done by building an object with the correct layout based on the phrases and reference grammars added to this instance + // of a DynamicGrammarBuilder + generateGrammarObject() { + if (this.privGrammars === undefined && this.privPhrases === undefined) { + return undefined; } - }; - SynthesisTurn.prototype.readAllAudioFromStream = function () { - return __awaiter(this, void 0, void 0, function () { - var e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.privIsSynthesisEnded) return [3 /*break*/, 4]; - this.privReceivedAudio = new ArrayBuffer(this.bytesReceived); - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, this.privAudioOutputStream.read(this.privReceivedAudio)]; - case 2: - _a.sent(); - return [3 /*break*/, 4]; - case 3: - e_1 = _a.sent(); - this.privReceivedAudio = new ArrayBuffer(0); - return [3 /*break*/, 4]; - case 4: return [2 /*return*/]; - } + const retObj = {}; + retObj.referenceGrammars = this.privGrammars; + if (undefined !== this.privPhrases && 0 !== this.privPhrases.length) { + const retPhrases = []; + this.privPhrases.forEach((value) => { + retPhrases.push({ + text: value, + }); }); - }); - }; - return SynthesisTurn; -}()); -exports.SynthesisTurn = SynthesisTurn; + retObj.groups = [{ type: Group_js_1.GroupType.Generic, items: retPhrases }]; + retObj.bias = this.privWeight; + } + return retObj; + } +} +exports.DynamicGrammarBuilder = DynamicGrammarBuilder; /***/ }), -/* 226 */ -/***/ (function(module, exports, __webpack_require__) { +/* 232 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE.md file in the project root for full license information. +// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SubstringMatchType = exports.GroupType = void 0; +/** + * Represents the type of the Intent. + */ +var GroupType; +(function (GroupType) { + GroupType["IntentText"] = "IntentText"; + GroupType["IntentEntity"] = "IntentEntity"; + GroupType["Generic"] = "Generic"; + GroupType["People"] = "People"; + GroupType["Place"] = "Place"; + GroupType["DynamicEntity"] = "DynamicEntity"; +})(GroupType = exports.GroupType || (exports.GroupType = {})); +/** + * Represents the type of the substring match. + */ +var SubstringMatchType; +(function (SubstringMatchType) { + SubstringMatchType["None"] = "None"; + SubstringMatchType["LeftRooted"] = "LeftRooted"; + SubstringMatchType["PartialName"] = "PartialName"; + SubstringMatchType["MiddleOfSentence"] = "MiddleOfSentence"; +})(SubstringMatchType = exports.SubstringMatchType || (exports.SubstringMatchType = {})); + + + +/***/ }), +/* 233 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesisAdapterBase = void 0; -var Exports_1 = __webpack_require__(4); -var Exports_2 = __webpack_require__(61); -var Exports_3 = __webpack_require__(53); -var SpeechConnectionMessage_Internal_1 = __webpack_require__(173); -var SynthesisAdapterBase = /** @class */ (function () { - function SynthesisAdapterBase(authentication, connectionFactory, synthesizerConfig, speechSynthesizer, audioDestination) { - var _this = this; - this.speakOverride = undefined; - this.receiveMessageOverride = undefined; - this.connectImplOverride = undefined; - this.configConnectionOverride = undefined; - this.sendSynthesisContext = function (connection) { - var synthesisContextJson = _this.synthesisContext.toJSON(); - if (synthesisContextJson) { - return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_1.MessageType.Text, "synthesis.context", _this.privSynthesisTurn.requestId, "application/json", synthesisContextJson)); - } - return; - }; - this.sendSpeechServiceConfig = function (connection, SpeechServiceConfigJson) { - if (SpeechServiceConfigJson) { - return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_1.MessageType.Text, "speech.config", _this.privSynthesisTurn.requestId, "application/json", SpeechServiceConfigJson)); - } - }; - this.sendSsmlMessage = function (connection, ssml, requestId) { - return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_1.MessageType.Text, "ssml", requestId, "application/ssml+xml", ssml)); - }; - if (!authentication) { - throw new Exports_1.ArgumentNullError("authentication"); - } - if (!connectionFactory) { - throw new Exports_1.ArgumentNullError("connectionFactory"); - } - if (!synthesizerConfig) { - throw new Exports_1.ArgumentNullError("synthesizerConfig"); - } - this.privAuthentication = authentication; - this.privConnectionFactory = connectionFactory; - this.privSynthesizerConfig = synthesizerConfig; - this.privIsDisposed = false; - this.privSpeechSynthesizer = speechSynthesizer; - this.privSessionAudioDestination = audioDestination; - this.privSynthesisTurn = new Exports_3.SynthesisTurn(); - this.privConnectionEvents = new Exports_1.EventSource(); - this.privServiceEvents = new Exports_1.EventSource(); - this.privSynthesisContext = new Exports_3.SynthesisContext(this.privSpeechSynthesizer); - this.privAgentConfig = new Exports_3.AgentConfig(); - this.connectionEvents.attach(function (connectionEvent) { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DialogServiceAdapter = void 0; +const Exports_js_1 = __webpack_require__(66); +const DialogEvents_js_1 = __webpack_require__(34); +const Exports_js_2 = __webpack_require__(4); +const AudioOutputFormat_js_1 = __webpack_require__(91); +const Exports_js_3 = __webpack_require__(85); +const DialogServiceTurnStateManager_js_1 = __webpack_require__(234); +const Exports_js_4 = __webpack_require__(2); +const ActivityResponsePayload_js_1 = __webpack_require__(236); +const InvocationSource_js_1 = __webpack_require__(237); +const KeywordDetection_js_1 = __webpack_require__(238); +const SpeechConnectionMessage_Internal_js_1 = __webpack_require__(188); +class DialogServiceAdapter extends Exports_js_4.ServiceRecognizerBase { + constructor(authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector) { + super(authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector); + this.privEvents = new Exports_js_2.EventSource(); + this.privDialogServiceConnector = dialogServiceConnector; + this.receiveMessageOverride = () => this.receiveDialogMessageOverride(); + this.privTurnStateManager = new DialogServiceTurnStateManager_js_1.DialogServiceTurnStateManager(); + this.recognizeOverride = + (recoMode, successCallback, errorCallback) => this.listenOnce(recoMode, successCallback, errorCallback); + this.postConnectImplOverride = (connection) => this.dialogConnectImpl(connection); + this.configConnectionOverride = (connection) => this.configConnection(connection); + this.disconnectOverride = () => this.privDisconnect(); + this.privDialogAudioSource = audioSource; + this.agentConfigSent = false; + this.privLastResult = null; + this.connectionEvents.attach((connectionEvent) => { if (connectionEvent.name === "ConnectionClosedEvent") { - var connectionClosedEvent = connectionEvent; - if (connectionClosedEvent.statusCode !== 1000) { - _this.cancelSynthesisLocal(Exports_2.CancellationReason.Error, connectionClosedEvent.statusCode === 1007 ? Exports_2.CancellationErrorCode.BadRequestParameters : Exports_2.CancellationErrorCode.ConnectionFailure, connectionClosedEvent.reason + " websocket error code: " + connectionClosedEvent.statusCode); - } + this.terminateMessageLoop = true; } }); } - Object.defineProperty(SynthesisAdapterBase.prototype, "synthesisContext", { - get: function () { - return this.privSynthesisContext; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisAdapterBase.prototype, "agentConfig", { - get: function () { - return this.privAgentConfig; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisAdapterBase.prototype, "connectionEvents", { - get: function () { - return this.privConnectionEvents; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisAdapterBase.prototype, "serviceEvents", { - get: function () { - return this.privServiceEvents; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisAdapterBase.prototype, "activityTemplate", { - get: function () { return this.privActivityTemplate; }, - set: function (messagePayload) { this.privActivityTemplate = messagePayload; }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisAdapterBase.prototype, "audioOutputFormat", { - set: function (format) { - this.privAudioOutputFormat = format; - this.privSynthesisTurn.audioOutputFormat = format; - if (this.privSessionAudioDestination !== undefined) { - this.privSessionAudioDestination.format = format; - } - if (this.synthesisContext !== undefined) { - this.synthesisContext.audioOutputFormat = format; - } - }, - enumerable: false, - configurable: true - }); - SynthesisAdapterBase.addHeader = function (audio, format) { - if (!format.hasHeader) { - return audio; - } - format.updateHeader(audio.byteLength); - var tmp = new Uint8Array(audio.byteLength + format.header.byteLength); - tmp.set(new Uint8Array(format.header), 0); - tmp.set(new Uint8Array(audio), format.header.byteLength); - return tmp.buffer; - }; - SynthesisAdapterBase.prototype.isDisposed = function () { - return this.privIsDisposed; - }; - SynthesisAdapterBase.prototype.dispose = function (reason) { - return __awaiter(this, void 0, void 0, function () { - var connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privIsDisposed = true; - if (this.privSessionAudioDestination !== undefined) { - this.privSessionAudioDestination.close(); + async sendMessage(message) { + const interactionGuid = (0, Exports_js_2.createGuid)(); + const requestId = (0, Exports_js_2.createNoDashGuid)(); + const agentMessage = { + context: { + interactionId: interactionGuid + }, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + messagePayload: JSON.parse(message), + version: 0.5 + }; + const agentMessageJson = JSON.stringify(agentMessage); + const connection = await this.fetchConnection(); + await connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "agent", requestId, "application/json", agentMessageJson)); + } + async privDisconnect() { + await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.NoError, "Disconnecting"); + this.terminateMessageLoop = true; + this.agentConfigSent = false; + return; + } + processTypeSpecificMessages(connectionMessage) { + const resultProps = new Exports_js_3.PropertyCollection(); + if (connectionMessage.messageType === Exports_js_2.MessageType.Text) { + resultProps.setProperty(Exports_js_3.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody); + } + let result; + let processed; + switch (connectionMessage.path.toLowerCase()) { + case "speech.phrase": + const speechPhrase = Exports_js_4.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + this.privRequestSession.onPhraseRecognized(speechPhrase.Offset + speechPhrase.Duration); + if (speechPhrase.RecognitionStatus !== Exports_js_4.RecognitionStatus.TooManyRequests && speechPhrase.RecognitionStatus !== Exports_js_4.RecognitionStatus.Error) { + const args = this.fireEventForResult(speechPhrase, resultProps); + this.privLastResult = args.result; + if (!!this.privDialogServiceConnector.recognized) { + try { + this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, args); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. } - if (!this.privConnectionConfigurationPromise) return [3 /*break*/, 3]; - return [4 /*yield*/, this.privConnectionConfigurationPromise]; - case 1: - connection = _a.sent(); - return [4 /*yield*/, connection.dispose(reason)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; + } } - }); - }); - }; - SynthesisAdapterBase.prototype.connect = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.connectImpl()]; - case 1: - _a.sent(); - return [2 /*return*/]; + processed = true; + break; + case "speech.hypothesis": + const hypothesis = Exports_js_4.SpeechHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + result = new Exports_js_3.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_js_3.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, hypothesis.Offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, undefined, undefined, hypothesis.asJson(), resultProps); + this.privRequestSession.onHypothesis(hypothesis.Offset); + const ev = new Exports_js_3.SpeechRecognitionEventArgs(result, hypothesis.Offset, this.privRequestSession.sessionId); + if (!!this.privDialogServiceConnector.recognizing) { + try { + this.privDialogServiceConnector.recognizing(this.privDialogServiceConnector, ev); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - }); - }); - }; - SynthesisAdapterBase.prototype.sendNetworkMessage = function (path, payload) { - return __awaiter(this, void 0, void 0, function () { - var type, contentType, connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - type = typeof payload === "string" ? Exports_1.MessageType.Text : Exports_1.MessageType.Binary; - contentType = typeof payload === "string" ? "application/json" : ""; - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _a.sent(); - return [2 /*return*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(type, path, this.privSynthesisTurn.requestId, contentType, payload))]; + processed = true; + break; + case "speech.keyword": + const keyword = Exports_js_4.SpeechKeyword.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + result = new Exports_js_3.SpeechRecognitionResult(this.privRequestSession.requestId, keyword.Status === "Accepted" ? Exports_js_3.ResultReason.RecognizedKeyword : Exports_js_3.ResultReason.NoMatch, keyword.Text, keyword.Duration, keyword.Offset, undefined, undefined, undefined, undefined, keyword.asJson(), resultProps); + if (keyword.Status !== "Accepted") { + this.privLastResult = result; + } + const event = new Exports_js_3.SpeechRecognitionEventArgs(result, result.duration, result.resultId); + if (!!this.privDialogServiceConnector.recognized) { + try { + this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, event); + /* eslint-disable no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - }); - }); - }; - SynthesisAdapterBase.prototype.Speak = function (text, isSSML, requestId, successCallback, errorCallBack, audioDestination) { - return __awaiter(this, void 0, void 0, function () { - var ssml, connection, synthesisStartEventArgs, messageRetrievalPromise, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (isSSML) { - ssml = text; + processed = true; + break; + case "audio": + { + const audioRequestId = connectionMessage.requestId.toUpperCase(); + const turn = this.privTurnStateManager.GetTurn(audioRequestId); + try { + // Empty binary message signals end of stream. + if (!connectionMessage.binaryBody) { + turn.endAudioStream(); } else { - ssml = this.privSpeechSynthesizer.buildSsml(text); - } - if (this.speakOverride !== undefined) { - return [2 /*return*/, this.speakOverride(ssml, requestId, successCallback, errorCallBack)]; + turn.audioStream.write(connectionMessage.binaryBody); } - this.privSuccessCallback = successCallback; - this.privErrorCallback = errorCallBack; - this.privSynthesisTurn.startNewSynthesis(requestId, text, isSSML, audioDestination); - _a.label = 1; - case 1: - _a.trys.push([1, 6, , 7]); - return [4 /*yield*/, this.connectImpl()]; - case 2: - _a.sent(); - return [4 /*yield*/, this.fetchConnection()]; - case 3: - connection = _a.sent(); - return [4 /*yield*/, this.sendSynthesisContext(connection)]; - case 4: - _a.sent(); - return [4 /*yield*/, this.sendSsmlMessage(connection, ssml, requestId)]; - case 5: - _a.sent(); - synthesisStartEventArgs = new Exports_2.SpeechSynthesisEventArgs(new Exports_2.SpeechSynthesisResult(requestId, Exports_2.ResultReason.SynthesizingAudioStarted)); - if (!!this.privSpeechSynthesizer.synthesisStarted) { - this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer, synthesisStartEventArgs); - } - messageRetrievalPromise = this.receiveMessage(); - return [3 /*break*/, 7]; - case 6: - e_1 = _a.sent(); - this.cancelSynthesisLocal(Exports_2.CancellationReason.Error, Exports_2.CancellationErrorCode.ConnectionFailure, e_1); - return [2 /*return*/, Promise.reject(e_1)]; - case 7: return [2 /*return*/]; + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - }); - }); - }; - // Cancels synthesis. - SynthesisAdapterBase.prototype.cancelSynthesis = function (requestId, cancellationReason, errorCode, error) { - var properties = new Exports_2.PropertyCollection(); - properties.setProperty(Exports_3.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[errorCode]); - var result = new Exports_2.SpeechSynthesisResult(requestId, Exports_2.ResultReason.Canceled, undefined, error, properties); - if (!!this.privSpeechSynthesizer.SynthesisCanceled) { - var cancelEvent = new Exports_2.SpeechSynthesisEventArgs(result); - try { - this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer, cancelEvent); - /* tslint:disable:no-empty */ - } - catch (_a) { } + processed = true; + break; + case "response": + { + this.handleResponseMessage(connectionMessage); + } + processed = true; + break; + default: + break; } - if (!!this.privSuccessCallback) { + const defferal = new Exports_js_2.Deferred(); + defferal.resolve(processed); + return defferal.promise; + } + // Cancels recognition. + async cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) { + this.terminateMessageLoop = true; + if (!!this.privRequestSession.isRecognizing) { + await this.privRequestSession.onStopRecognizing(); + } + if (!!this.privDialogServiceConnector.canceled) { + const properties = new Exports_js_3.PropertyCollection(); + properties.setProperty(Exports_js_4.CancellationErrorCodePropertyName, Exports_js_3.CancellationErrorCode[errorCode]); + const cancelEvent = new Exports_js_3.SpeechRecognitionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId); try { - this.privSuccessCallback(result); - /* tslint:disable:no-empty */ - } - catch (_b) { } + this.privDialogServiceConnector.canceled(this.privDialogServiceConnector, cancelEvent); + /* eslint-disable no-empty */ + } + catch { } + if (!!this.privSuccessCallback) { + const result = new Exports_js_3.SpeechRecognitionResult(undefined, // ResultId + Exports_js_3.ResultReason.Canceled, undefined, // Text + undefined, // Duration + undefined, // Offset + undefined, // Language + undefined, // Language Detection Confidence + undefined, // Speaker Id + error, undefined, // Json + properties); + try { + this.privSuccessCallback(result); + this.privSuccessCallback = undefined; + /* eslint-disable no-empty */ + } + catch { } + } + } + } + async listenOnce(recoMode, successCallback, errorCallback) { + this.privRecognizerConfig.recognitionMode = recoMode; + this.privSuccessCallback = successCallback; + this.privErrorCallback = errorCallback; + this.privRequestSession.startNewRecognition(); + this.privRequestSession.listenForServiceTelemetry(this.privDialogAudioSource.events); + this.privRecognizerConfig.parameters.setProperty(Exports_js_3.PropertyId.Speech_SessionId, this.privRequestSession.sessionId); + // Start the connection to the service. The promise this will create is stored and will be used by configureConnection(). + const conPromise = this.connectImpl(); + const preAudioPromise = this.sendPreAudioMessages(); + const node = await this.privDialogAudioSource.attach(this.privRequestSession.audioNodeId); + const format = await this.privDialogAudioSource.format; + const deviceInfo = await this.privDialogAudioSource.deviceInfo; + const audioNode = new Exports_js_1.ReplayableAudioNode(node, format.avgBytesPerSec); + await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false); + this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo }; + try { + await conPromise; + await preAudioPromise; } - }; - // Cancels synthesis. - SynthesisAdapterBase.prototype.cancelSynthesisLocal = function (cancellationReason, errorCode, error) { - if (!!this.privSynthesisTurn.isSynthesizing) { - this.privSynthesisTurn.onStopSynthesizing(); - this.cancelSynthesis(this.privSynthesisTurn.requestId, cancellationReason, errorCode, error); + catch (error) { + await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.ConnectionFailure, error); + return Promise.resolve(); } - }; - SynthesisAdapterBase.prototype.processTypeSpecificMessages = function (connectionMessage, successCallback, errorCallBack) { - return true; - }; - SynthesisAdapterBase.prototype.receiveMessage = function () { - return __awaiter(this, void 0, void 0, function () { - var connection, message, connectionMessage, _a, audioWithHeader, ev, metadataList, _i, metadataList_1, metadata, wordBoundaryEventArgs, bookmarkEventArgs, visemeEventArgs, result, audioBuffer, error_1, e_2; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 14, , 15]); - return [4 /*yield*/, this.fetchConnection()]; - case 1: - connection = _b.sent(); - return [4 /*yield*/, connection.read()]; - case 2: - message = _b.sent(); - if (this.receiveMessageOverride !== undefined) { - return [2 /*return*/, this.receiveMessageOverride()]; - } - if (this.privIsDisposed) { - // We're done. - return [2 /*return*/]; - } - // indicates we are draining the queue and it came with no message; - if (!message) { - if (!this.privSynthesisTurn.isSynthesizing) { - return [2 /*return*/]; + const sessionStartEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId); + if (!!this.privRecognizer.sessionStarted) { + this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs); + } + const audioSendPromise = this.sendAudio(audioNode); + // /* eslint-disable no-empty */ + audioSendPromise.then(() => { }, async (error) => { + await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.RuntimeError, error); + }); + } + // Establishes a websocket connection to the end point. + dialogConnectImpl(connection) { + this.privConnectionLoop = this.startMessageLoop(); + return connection; + } + receiveDialogMessageOverride() { + // we won't rely on the cascading promises of the connection since we want to continually be available to receive messages + const communicationCustodian = new Exports_js_2.Deferred(); + const loop = async () => { + try { + const isDisposed = this.isDisposed(); + const terminateMessageLoop = (!this.isDisposed() && this.terminateMessageLoop); + if (isDisposed || terminateMessageLoop) { + // We're done. + communicationCustodian.resolve(undefined); + return; + } + const connection = await this.fetchConnection(); + const message = await connection.read(); + if (!message) { + return loop(); + } + const connectionMessage = SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage.fromConnectionMessage(message); + switch (connectionMessage.path.toLowerCase()) { + case "turn.start": + { + const turnRequestId = connectionMessage.requestId.toUpperCase(); + const audioSessionReqId = this.privRequestSession.requestId.toUpperCase(); + // turn started by the service + if (turnRequestId !== audioSessionReqId) { + this.privTurnStateManager.StartTurn(turnRequestId); } else { - return [2 /*return*/, this.receiveMessage()]; - } - } - this.privServiceHasSentMessage = true; - connectionMessage = SpeechConnectionMessage_Internal_1.SpeechConnectionMessage.fromConnectionMessage(message); - if (!(connectionMessage.requestId.toLowerCase() === this.privSynthesisTurn.requestId.toLowerCase())) return [3 /*break*/, 13]; - _a = connectionMessage.path.toLowerCase(); - switch (_a) { - case "turn.start": return [3 /*break*/, 3]; - case "response": return [3 /*break*/, 4]; - case "audio": return [3 /*break*/, 5]; - case "audio.metadata": return [3 /*break*/, 6]; - case "turn.end": return [3 /*break*/, 7]; - } - return [3 /*break*/, 12]; - case 3: - this.privSynthesisTurn.onServiceTurnStartResponse(); - return [3 /*break*/, 13]; - case 4: - this.privSynthesisTurn.onServiceResponseMessage(connectionMessage.textBody); - return [3 /*break*/, 13]; - case 5: - if (this.privSynthesisTurn.streamId.toLowerCase() === connectionMessage.streamId.toLowerCase() - && !!connectionMessage.binaryBody) { - this.privSynthesisTurn.onAudioChunkReceived(connectionMessage.binaryBody); - if (!!this.privSpeechSynthesizer.synthesizing) { - try { - audioWithHeader = SynthesisAdapterBase.addHeader(connectionMessage.binaryBody, this.privSynthesisTurn.audioOutputFormat); - ev = new Exports_2.SpeechSynthesisEventArgs(new Exports_2.SpeechSynthesisResult(this.privSynthesisTurn.requestId, Exports_2.ResultReason.SynthesizingAudio, audioWithHeader)); - this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer, ev); - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - if (this.privSessionAudioDestination !== undefined) { - this.privSessionAudioDestination.write(connectionMessage.binaryBody); + this.privRequestSession.onServiceTurnStartResponse(); } } - return [3 /*break*/, 13]; - case 6: - metadataList = Exports_3.SynthesisAudioMetadata.fromJSON(connectionMessage.textBody).Metadata; - for (_i = 0, metadataList_1 = metadataList; _i < metadataList_1.length; _i++) { - metadata = metadataList_1[_i]; - switch (metadata.Type) { - case Exports_3.MetadataType.WordBoundary: - this.privSynthesisTurn.onWordBoundaryEvent(metadata.Data.text.Text); - wordBoundaryEventArgs = new Exports_2.SpeechSynthesisWordBoundaryEventArgs(metadata.Data.Offset, metadata.Data.text.Text, metadata.Data.text.Length, this.privSynthesisTurn.currentTextOffset); - if (!!this.privSpeechSynthesizer.wordBoundary) { - try { - this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer, wordBoundaryEventArgs); - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - break; - case Exports_3.MetadataType.Bookmark: - bookmarkEventArgs = new Exports_2.SpeechSynthesisBookmarkEventArgs(metadata.Data.Offset, metadata.Data.Bookmark); - if (!!this.privSpeechSynthesizer.bookmarkReached) { - try { - this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer, bookmarkEventArgs); - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - break; - case Exports_3.MetadataType.Viseme: - this.privSynthesisTurn.onVisemeMetadataReceived(metadata); - if (metadata.Data.IsLastAnimation) { - visemeEventArgs = new Exports_2.SpeechSynthesisVisemeEventArgs(metadata.Data.Offset, metadata.Data.VisemeId, this.privSynthesisTurn.getAndClearVisemeAnimation()); - if (!!this.privSpeechSynthesizer.visemeReceived) { - try { - this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer, visemeEventArgs); - } - catch (error) { - // Not going to let errors in the event handler - // trip things up. - } - } - } - break; - } + break; + case "speech.startdetected": + const speechStartDetected = Exports_js_4.SpeechDetected.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset); + const speechStartEventArgs = new Exports_js_3.RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId); + if (!!this.privRecognizer.speechStartDetected) { + this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs); } - return [3 /*break*/, 13]; - case 7: - this.privSynthesisTurn.onServiceTurnEndResponse(); - result = void 0; - _b.label = 8; - case 8: - _b.trys.push([8, 10, , 11]); - return [4 /*yield*/, this.privSynthesisTurn.getAllReceivedAudioWithHeader()]; - case 9: - audioBuffer = _b.sent(); - result = new Exports_2.SpeechSynthesisResult(this.privSynthesisTurn.requestId, Exports_2.ResultReason.SynthesizingAudioCompleted, audioBuffer); - if (!!this.privSuccessCallback) { - this.privSuccessCallback(result); + break; + case "speech.enddetected": + let json; + if (connectionMessage.textBody.length > 0) { + json = connectionMessage.textBody; } - return [3 /*break*/, 11]; - case 10: - error_1 = _b.sent(); - if (!!this.privErrorCallback) { - this.privErrorCallback(error_1); + else { + // If the request was empty, the JSON returned is empty. + json = "{ Offset: 0 }"; } - return [3 /*break*/, 11]; - case 11: - if (this.privSpeechSynthesizer.synthesisCompleted) { - try { - this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer, new Exports_2.SpeechSynthesisEventArgs(result)); - } - catch (e) { - // Not going to let errors in the event handler - // trip things up. - } + const speechStopDetected = Exports_js_4.SpeechDetected.fromJSON(json, this.privRequestSession.currentTurnAudioOffset); + this.privRequestSession.onServiceRecognized(speechStopDetected.Offset); + const speechStopEventArgs = new Exports_js_3.RecognitionEventArgs(speechStopDetected.Offset, this.privRequestSession.sessionId); + if (!!this.privRecognizer.speechEndDetected) { + this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs); } - return [3 /*break*/, 13]; - case 12: - if (!this.processTypeSpecificMessages(connectionMessage)) { - // here are some messages that the derived class has not processed, dispatch them to connect class - if (!!this.privServiceEvents) { - this.serviceEvents.onEvent(new Exports_1.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody)); + break; + case "turn.end": + { + const turnEndRequestId = connectionMessage.requestId.toUpperCase(); + const audioSessionReqId = this.privRequestSession.requestId.toUpperCase(); + // turn started by the service + if (turnEndRequestId !== audioSessionReqId) { + this.privTurnStateManager.CompleteTurn(turnEndRequestId); } - } - _b.label = 13; - case 13: return [2 /*return*/, this.receiveMessage()]; - case 14: - e_2 = _b.sent(); - return [3 /*break*/, 15]; - case 15: return [2 /*return*/]; - } - }); - }); - }; - SynthesisAdapterBase.prototype.connectImpl = function (isUnAuthorized) { - var _this = this; - if (isUnAuthorized === void 0) { isUnAuthorized = false; } - if (this.privConnectionPromise) { - return this.privConnectionPromise.then(function (connection) { - if (connection.state() === Exports_1.ConnectionState.Disconnected) { - _this.privConnectionId = null; - _this.privConnectionPromise = null; - _this.privServiceHasSentMessage = false; - return _this.connectImpl(); - } - return _this.privConnectionPromise; - }, function (error) { - _this.privConnectionId = null; - _this.privConnectionPromise = null; - _this.privServiceHasSentMessage = false; - return _this.connectImpl(); - }); - } - this.privAuthFetchEventId = Exports_1.createNoDashGuid(); - this.privConnectionId = Exports_1.createNoDashGuid(); - this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId); - var authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId); - this.privConnectionPromise = authPromise.then(function (result) { return __awaiter(_this, void 0, void 0, function () { - var connection, response; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privSynthesisTurn.onAuthCompleted(false)]; - case 1: - _a.sent(); - connection = this.privConnectionFactory.create(this.privSynthesizerConfig, result, this.privConnectionId); - // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away, - // it'll stop sending events. - connection.events.attach(function (event) { - _this.connectionEvents.onEvent(event); - }); - return [4 /*yield*/, connection.open()]; - case 2: - response = _a.sent(); - if (!(response.statusCode === 200)) return [3 /*break*/, 4]; - return [4 /*yield*/, this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode)]; - case 3: - _a.sent(); - return [2 /*return*/, Promise.resolve(connection)]; - case 4: - if (!(response.statusCode === 403 && !isUnAuthorized)) return [3 /*break*/, 5]; - return [2 /*return*/, this.connectImpl(true)]; - case 5: return [4 /*yield*/, this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode, response.reason)]; - case 6: - _a.sent(); - return [2 /*return*/, Promise.reject("Unable to contact server. StatusCode: " + response.statusCode + ", " + this.privSynthesizerConfig.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint) + " Reason: " + response.reason)]; - } - }); - }); }, function (error) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.privSynthesisTurn.onAuthCompleted(true, error)]; - case 1: - _a.sent(); - throw new Error(error); - } - }); - }); }); - // Attach an empty handler to allow the promise to run in the background while - // other startup events happen. It'll eventually be awaited on. - this.privConnectionPromise.catch(function () { }); - return this.privConnectionPromise; - }; - SynthesisAdapterBase.prototype.fetchConnection = function () { - return __awaiter(this, void 0, void 0, function () { - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.privConnectionConfigurationPromise) { - return [2 /*return*/, this.privConnectionConfigurationPromise.then(function (connection) { - if (connection.state() === Exports_1.ConnectionState.Disconnected) { - _this.privConnectionId = null; - _this.privConnectionConfigurationPromise = null; - _this.privServiceHasSentMessage = false; - return _this.fetchConnection(); + else { + // Audio session turn + const sessionStopEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId); + await this.privRequestSession.onServiceTurnEndResponse(false); + if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) { + if (!!this.privRecognizer.sessionStopped) { + this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs); + } + } + // report result to promise. + if (!!this.privSuccessCallback && this.privLastResult) { + try { + this.privSuccessCallback(this.privLastResult); + this.privLastResult = null; + } + catch (e) { + if (!!this.privErrorCallback) { + this.privErrorCallback(e); + } } - return _this.privConnectionConfigurationPromise; - }, function (error) { - _this.privConnectionId = null; - _this.privConnectionConfigurationPromise = null; - _this.privServiceHasSentMessage = false; - return _this.fetchConnection(); - })]; + // Only invoke the call back once. + // and if it's successful don't invoke the + // error after that. + this.privSuccessCallback = undefined; + this.privErrorCallback = undefined; + } + } + } + break; + default: + try { + const processed = await this.processTypeSpecificMessages(connectionMessage); + if (!processed) { + if (!!this.serviceEvents) { + this.serviceEvents.onEvent(new Exports_js_2.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody)); + } + } + } + catch (e) { + // } - this.privConnectionConfigurationPromise = this.configureConnection(); - return [4 /*yield*/, this.privConnectionConfigurationPromise]; - case 1: return [2 /*return*/, _a.sent()]; } - }); + const ret = loop(); + return ret; + } + catch (error) { + this.terminateMessageLoop = true; + communicationCustodian.resolve(); + } + }; + loop().catch((reason) => { + Exports_js_2.Events.instance.onEvent(new Exports_js_2.BackgroundEvent(reason)); }); - }; + return communicationCustodian.promise; + } + async startMessageLoop() { + this.terminateMessageLoop = false; + try { + await this.receiveDialogMessageOverride(); + } + catch (error) { + await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.RuntimeError, error); + } + return Promise.resolve(); + } // Takes an established websocket connection to the endpoint and sends speech configuration information. - SynthesisAdapterBase.prototype.configureConnection = function () { - return __awaiter(this, void 0, void 0, function () { - var connection; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.connectImpl()]; - case 1: - connection = _a.sent(); - if (this.configConnectionOverride !== undefined) { - return [2 /*return*/, this.configConnectionOverride(connection)]; - } - return [4 /*yield*/, this.sendSpeechServiceConfig(connection, this.privSynthesizerConfig.SpeechServiceConfig.serialize())]; - case 2: - _a.sent(); - return [2 /*return*/, connection]; + async configConnection(connection) { + if (this.terminateMessageLoop) { + this.terminateMessageLoop = false; + return Promise.reject("Connection to service terminated."); + } + await this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize()); + await this.sendAgentConfig(connection); + return connection; + } + async sendPreAudioMessages() { + const connection = await this.fetchConnection(); + this.addKeywordContextData(); + await this.sendSpeechContext(connection, true); + await this.sendAgentContext(connection); + await this.sendWaveHeader(connection); + } + sendAgentConfig(connection) { + if (this.agentConfig && !this.agentConfigSent) { + if (this.privRecognizerConfig + .parameters + .getProperty(Exports_js_3.PropertyId.Conversation_DialogType) === Exports_js_3.DialogServiceConfig.DialogTypes.CustomCommands) { + const config = this.agentConfig.get(); + config.botInfo.commandsCulture = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-us"); + this.agentConfig.set(config); + } + this.onEvent(new DialogEvents_js_1.SendingAgentContextMessageEvent(this.agentConfig)); + const agentConfigJson = this.agentConfig.toJsonString(); + // guard against sending this multiple times on one connection + this.agentConfigSent = true; + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "agent.config", this.privRequestSession.requestId, "application/json", agentConfigJson)); + } + return; + } + sendAgentContext(connection) { + const guid = (0, Exports_js_2.createGuid)(); + const speechActivityTemplate = this.privDialogServiceConnector.properties.getProperty(Exports_js_3.PropertyId.Conversation_Speech_Activity_Template); + const agentContext = { + channelData: "", + context: { + interactionId: guid + }, + messagePayload: typeof speechActivityTemplate === undefined ? undefined : speechActivityTemplate, + version: 0.5 + }; + const agentContextJson = JSON.stringify(agentContext); + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speech.agent.context", this.privRequestSession.requestId, "application/json", agentContextJson)); + } + fireEventForResult(serviceResult, properties) { + const resultReason = Exports_js_4.EnumTranslation.implTranslateRecognitionResult(serviceResult.RecognitionStatus); + const result = new Exports_js_3.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, serviceResult.DisplayText, serviceResult.Duration, serviceResult.Offset, serviceResult.Language, serviceResult.LanguageDetectionConfidence, undefined, undefined, serviceResult.asJson(), properties); + const ev = new Exports_js_3.SpeechRecognitionEventArgs(result, serviceResult.Offset, this.privRequestSession.sessionId); + return ev; + } + handleResponseMessage(responseMessage) { + // "response" messages can contain either "message" (activity) or "MessageStatus" data. Fire the appropriate + // event according to the message type that's specified. + const responsePayload = JSON.parse(responseMessage.textBody); + switch (responsePayload.messageType.toLowerCase()) { + case "message": + const responseRequestId = responseMessage.requestId.toUpperCase(); + const activityPayload = ActivityResponsePayload_js_1.ActivityPayloadResponse.fromJSON(responseMessage.textBody); + const turn = this.privTurnStateManager.GetTurn(responseRequestId); + // update the conversation Id + if (activityPayload.conversationId) { + const updateAgentConfig = this.agentConfig.get(); + updateAgentConfig.botInfo.conversationId = activityPayload.conversationId; + this.agentConfig.set(updateAgentConfig); + } + const pullAudioOutputStream = turn.processActivityPayload(activityPayload, AudioOutputFormat_js_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(this.privDialogServiceConnector.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined))); + const activity = new Exports_js_3.ActivityReceivedEventArgs(activityPayload.messagePayload, pullAudioOutputStream); + if (!!this.privDialogServiceConnector.activityReceived) { + try { + this.privDialogServiceConnector.activityReceived(this.privDialogServiceConnector, activity); + /* eslint-disable-next-line no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - }); - }); - }; - SynthesisAdapterBase.telemetryDataEnabled = true; - return SynthesisAdapterBase; -}()); -exports.SynthesisAdapterBase = SynthesisAdapterBase; + break; + case "messagestatus": + if (!!this.privDialogServiceConnector.turnStatusReceived) { + try { + this.privDialogServiceConnector.turnStatusReceived(this.privDialogServiceConnector, new Exports_js_3.TurnStatusReceivedEventArgs(responseMessage.textBody)); + /* eslint-disable-next-line no-empty */ + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + break; + default: + Exports_js_2.Events.instance.onEvent(new Exports_js_2.BackgroundEvent(`Unexpected response of type ${responsePayload.messageType}. Ignoring.`)); + break; + } + } + onEvent(event) { + this.privEvents.onEvent(event); + Exports_js_2.Events.instance.onEvent(event); + } + addKeywordContextData() { + const keywordPropertyValue = this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect"); + if (keywordPropertyValue === undefined) { + return; + } + const keywordOffsetPropertyValue = this.privRecognizerConfig.parameters + .getProperty("SPEECH-KeywordsToDetect-Offsets"); + const keywordDurationPropertyValue = this.privRecognizerConfig.parameters + .getProperty("SPEECH-KeywordsToDetect-Durations"); + const keywords = keywordPropertyValue.split(";"); + const keywordOffsets = keywordOffsetPropertyValue === undefined ? [] : keywordOffsetPropertyValue.split(";"); + const keywordDurations = keywordDurationPropertyValue === undefined ? [] : keywordDurationPropertyValue.split(";"); + const keywordDefinitionArray = []; + for (let i = 0; i < keywords.length; i++) { + const definition = { + text: keywords[i] + }; + if (i < keywordOffsets.length) { + definition.startOffset = Number(keywordOffsets[i]); + } + if (i < keywordDurations.length) { + definition.duration = Number(keywordDurations[i]); + } + keywordDefinitionArray.push(definition); + } + this.speechContext.getContext().invocationSource = InvocationSource_js_1.InvocationSource.VoiceActivationWithKeyword; + this.speechContext.getContext().keywordDetection = [{ + clientDetectedKeywords: keywordDefinitionArray, + onReject: { action: KeywordDetection_js_1.OnRejectAction.EndOfTurn }, + type: KeywordDetection_js_1.KeywordDetectionType.StartTrigger + }]; + } +} +exports.DialogServiceAdapter = DialogServiceAdapter; /***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { +/* 234 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesisStartedEvent = exports.ConnectingToSynthesisServiceEvent = exports.SynthesisTriggeredEvent = exports.SpeechSynthesisEvent = void 0; -// tslint:disable:max-classes-per-file -var Exports_1 = __webpack_require__(4); -var SpeechSynthesisEvent = /** @class */ (function (_super) { - __extends(SpeechSynthesisEvent, _super); - function SpeechSynthesisEvent(eventName, requestId, eventType) { - if (eventType === void 0) { eventType = Exports_1.EventType.Info; } - var _this = _super.call(this, eventName, eventType) || this; - _this.privRequestId = requestId; - return _this; - } - Object.defineProperty(SpeechSynthesisEvent.prototype, "requestId", { - get: function () { - return this.privRequestId; - }, - enumerable: false, - configurable: true - }); - return SpeechSynthesisEvent; -}(Exports_1.PlatformEvent)); -exports.SpeechSynthesisEvent = SpeechSynthesisEvent; -var SynthesisTriggeredEvent = /** @class */ (function (_super) { - __extends(SynthesisTriggeredEvent, _super); - function SynthesisTriggeredEvent(requestId, sessionAudioDestinationId, turnAudioDestinationId) { - var _this = _super.call(this, "SynthesisTriggeredEvent", requestId) || this; - _this.privSessionAudioDestinationId = sessionAudioDestinationId; - _this.privTurnAudioDestinationId = turnAudioDestinationId; - return _this; - } - Object.defineProperty(SynthesisTriggeredEvent.prototype, "audioSessionDestinationId", { - get: function () { - return this.privSessionAudioDestinationId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesisTriggeredEvent.prototype, "audioTurnDestinationId", { - get: function () { - return this.privTurnAudioDestinationId; - }, - enumerable: false, - configurable: true - }); - return SynthesisTriggeredEvent; -}(SpeechSynthesisEvent)); -exports.SynthesisTriggeredEvent = SynthesisTriggeredEvent; -var ConnectingToSynthesisServiceEvent = /** @class */ (function (_super) { - __extends(ConnectingToSynthesisServiceEvent, _super); - function ConnectingToSynthesisServiceEvent(requestId, authFetchEventId) { - var _this = _super.call(this, "ConnectingToSynthesisServiceEvent", requestId) || this; - _this.privAuthFetchEventId = authFetchEventId; - return _this; - } - Object.defineProperty(ConnectingToSynthesisServiceEvent.prototype, "authFetchEventId", { - get: function () { - return this.privAuthFetchEventId; - }, - enumerable: false, - configurable: true - }); - return ConnectingToSynthesisServiceEvent; -}(SpeechSynthesisEvent)); -exports.ConnectingToSynthesisServiceEvent = ConnectingToSynthesisServiceEvent; -var SynthesisStartedEvent = /** @class */ (function (_super) { - __extends(SynthesisStartedEvent, _super); - function SynthesisStartedEvent(requestId, authFetchEventId) { - var _this = _super.call(this, "SynthesisStartedEvent", requestId) || this; - _this.privAuthFetchEventId = authFetchEventId; - return _this; - } - Object.defineProperty(SynthesisStartedEvent.prototype, "authFetchEventId", { - get: function () { - return this.privAuthFetchEventId; - }, - enumerable: false, - configurable: true - }); - return SynthesisStartedEvent; -}(SpeechSynthesisEvent)); -exports.SynthesisStartedEvent = SynthesisStartedEvent; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DialogServiceTurnStateManager = void 0; +const Error_js_1 = __webpack_require__(31); +const DialogServiceTurnState_js_1 = __webpack_require__(235); +class DialogServiceTurnStateManager { + constructor() { + this.privTurnMap = new Map(); + return; + } + StartTurn(id) { + if (this.privTurnMap.has(id)) { + throw new Error_js_1.InvalidOperationError("Service error: There is already a turn with id:" + id); + } + const turnState = new DialogServiceTurnState_js_1.DialogServiceTurnState(this, id); + this.privTurnMap.set(id, turnState); + return this.privTurnMap.get(id); + } + GetTurn(id) { + return this.privTurnMap.get(id); + } + CompleteTurn(id) { + if (!this.privTurnMap.has(id)) { + throw new Error_js_1.InvalidOperationError("Service error: Received turn end for an unknown turn id:" + id); + } + const turnState = this.privTurnMap.get(id); + turnState.complete(); + this.privTurnMap.delete(id); + return turnState; + } +} +exports.DialogServiceTurnStateManager = DialogServiceTurnStateManager; /***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { +/* 235 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesisRestAdapter = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -var HeaderNames_1 = __webpack_require__(55); -/** - * Implements methods for speaker recognition classes, sending requests to endpoint - * and parsing response into expected format - * @class SynthesisRestAdapter - */ -var SynthesisRestAdapter = /** @class */ (function () { - function SynthesisRestAdapter(config) { - var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); - if (!endpoint) { - var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, "westus"); - var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region); - endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "https://" + region + ".tts.speech" + hostSuffix); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DialogServiceTurnState = void 0; +const AudioOutputFormat_js_1 = __webpack_require__(91); +const AudioOutputStream_js_1 = __webpack_require__(90); +const ActivityResponsePayload_js_1 = __webpack_require__(236); +class DialogServiceTurnState { + constructor(manager, requestId) { + this.privRequestId = requestId; + this.privIsCompleted = false; + this.privAudioStream = null; + this.privTurnManager = manager; + this.resetTurnEndTimeout(); + } + get audioStream() { + // Called when is needed to stream. + this.resetTurnEndTimeout(); + return this.privAudioStream; + } + processActivityPayload(payload, audioFormat) { + if (payload.messageDataStreamType === ActivityResponsePayload_js_1.MessageDataStreamType.TextToSpeechAudio) { + this.privAudioStream = AudioOutputStream_js_1.AudioOutputStream.createPullStream(); + this.privAudioStream.format = (audioFormat !== undefined) ? audioFormat : AudioOutputFormat_js_1.AudioOutputFormatImpl.getDefaultOutputFormat(); + } + return this.privAudioStream; + } + endAudioStream() { + if (this.privAudioStream !== null && !this.privAudioStream.isClosed) { + this.privAudioStream.close(); } - this.privUri = endpoint + "/cognitiveservices/voices/list"; - var options = Exports_1.RestConfigBase.requestOptions; - options.headers[Exports_1.RestConfigBase.configParams.subscriptionKey] = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, undefined); - this.privRestAdapter = new Exports_1.RestMessageAdapter(options); } - /** - * Sends list voices request to endpoint. - * @function - * @public - * @param connectionId - guid for connectionId - * @returns {Promise} rest response to status request - */ - SynthesisRestAdapter.prototype.getVoicesList = function (connectionId) { - this.privRestAdapter.setHeaders(HeaderNames_1.HeaderNames.ConnectionId, connectionId); - return this.privRestAdapter.request(Exports_1.RestRequestType.Get, this.privUri); - }; - return SynthesisRestAdapter; -}()); -exports.SynthesisRestAdapter = SynthesisRestAdapter; + complete() { + if (this.privTimeoutToken !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + clearTimeout(this.privTimeoutToken); + } + this.endAudioStream(); + } + resetTurnEndTimeout() { + if (this.privTimeoutToken !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + clearTimeout(this.privTimeoutToken); + } + this.privTimeoutToken = setTimeout(() => { + this.privTurnManager.CompleteTurn(this.privRequestId); + return; + }, 2000); + } +} +exports.DialogServiceTurnState = DialogServiceTurnState; /***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { +/* 236 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesizerConfig = exports.SynthesisServiceType = void 0; -var Exports_1 = __webpack_require__(53); -var SynthesisServiceType; -(function (SynthesisServiceType) { - SynthesisServiceType[SynthesisServiceType["Standard"] = 0] = "Standard"; - SynthesisServiceType[SynthesisServiceType["Custom"] = 1] = "Custom"; -})(SynthesisServiceType = exports.SynthesisServiceType || (exports.SynthesisServiceType = {})); -var SynthesizerConfig = /** @class */ (function () { - function SynthesizerConfig(speechServiceConfig, parameters) { - this.privSynthesisServiceType = SynthesisServiceType.Standard; - this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new Exports_1.SpeechServiceConfig(new Exports_1.Context(null)); - this.privParameters = parameters; +// response +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MessageDataStreamType = exports.ActivityPayloadResponse = void 0; +class ActivityPayloadResponse { + constructor(json) { + this.privActivityResponse = JSON.parse(json); } - Object.defineProperty(SynthesizerConfig.prototype, "parameters", { - get: function () { - return this.privParameters; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesizerConfig.prototype, "synthesisServiceType", { - get: function () { - return this.privSynthesisServiceType; - }, - set: function (value) { - this.privSynthesisServiceType = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SynthesizerConfig.prototype, "SpeechServiceConfig", { - get: function () { - return this.privSpeechServiceConfig; - }, - enumerable: false, - configurable: true - }); - return SynthesizerConfig; -}()); -exports.SynthesizerConfig = SynthesizerConfig; + static fromJSON(json) { + return new ActivityPayloadResponse(json); + } + get conversationId() { + return this.privActivityResponse.conversationId; + } + get messageDataStreamType() { + return this.privActivityResponse.messageDataStreamType; + } + get messagePayload() { + return this.privActivityResponse.messagePayload; + } + get version() { + return this.privActivityResponse.version; + } +} +exports.ActivityPayloadResponse = ActivityPayloadResponse; +var MessageDataStreamType; +(function (MessageDataStreamType) { + MessageDataStreamType[MessageDataStreamType["None"] = 0] = "None"; + MessageDataStreamType[MessageDataStreamType["TextToSpeechAudio"] = 1] = "TextToSpeechAudio"; +})(MessageDataStreamType = exports.MessageDataStreamType || (exports.MessageDataStreamType = {})); /***/ }), -/* 230 */ -/***/ (function(module, exports, __webpack_require__) { +/* 237 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InvocationSource = void 0; +/** + * Represents the source of speech recognition invocation. + */ +var InvocationSource; +(function (InvocationSource) { + /** + * No invocation source specified. + */ + InvocationSource["None"] = "None"; + /** + * Voice activation with a keyword. + */ + InvocationSource["VoiceActivationWithKeyword"] = "VoiceActivationWithKeyword"; +})(InvocationSource = exports.InvocationSource || (exports.InvocationSource = {})); + + + +/***/ }), +/* 238 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OnRejectAction = exports.KeywordDetectionType = void 0; +/** + * Represents the type of keyword detection. + */ +var KeywordDetectionType; +(function (KeywordDetectionType) { + /** + * Triggered at the start of input. + */ + KeywordDetectionType["StartTrigger"] = "StartTrigger"; +})(KeywordDetectionType = exports.KeywordDetectionType || (exports.KeywordDetectionType = {})); +/** + * The action to take when a keyword is rejected. + */ +var OnRejectAction; +(function (OnRejectAction) { + /** + * End the current turn. + */ + OnRejectAction["EndOfTurn"] = "EndOfTurn"; + /** + * Continue processing. + */ + OnRejectAction["Continue"] = "Continue"; +})(OnRejectAction = exports.OnRejectAction || (exports.OnRejectAction = {})); + + + +/***/ }), +/* 239 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SynthesisContext = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AgentConfig = void 0; /** - * Represents the JSON used in the synthesis.context message sent to the speech service. - * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object. + * Represents the JSON used in the agent.config message sent to the speech service. */ -var SynthesisContext = /** @class */ (function () { - function SynthesisContext(speechSynthesizer) { - this.privContext = {}; - this.privSpeechSynthesizer = speechSynthesizer; +class AgentConfig { + toJsonString() { + return JSON.stringify(this.iPrivConfig); + } + get() { + return this.iPrivConfig; } /** - * Adds a section to the synthesis.context object. - * @param sectionName Name of the section to add. - * @param value JSON serializable object that represents the value. + * Setter for the agent.config object. + * @param value a JSON serializable object. */ - SynthesisContext.prototype.setSection = function (sectionName, value) { - this.privContext[sectionName] = value; - }; - Object.defineProperty(SynthesisContext.prototype, "audioOutputFormat", { - /** - * Sets the audio output format for synthesis context generation. - * @param format {AudioOutputFormatImpl} the output format - */ - set: function (format) { - this.privAudioOutputFormat = format; - }, - enumerable: false, - configurable: true - }); - SynthesisContext.prototype.toJSON = function () { - var synthesisSection = this.buildSynthesisContext(); - this.setSection("synthesis", synthesisSection); - return JSON.stringify(this.privContext); - }; - SynthesisContext.prototype.buildSynthesisContext = function () { - return { - audio: { - metadataOptions: { - bookmarkEnabled: (!!this.privSpeechSynthesizer.bookmarkReached), - sentenceBoundaryEnabled: false, - visemeEnabled: (!!this.privSpeechSynthesizer.visemeReceived), - wordBoundaryEnabled: (!!this.privSpeechSynthesizer.wordBoundary), - }, - outputFormat: this.privAudioOutputFormat.requestAudioFormatString, - }, - language: { - autoDetection: this.privSpeechSynthesizer.autoDetectSourceLanguage - } - }; - }; - return SynthesisContext; -}()); -exports.SynthesisContext = SynthesisContext; + set(value) { + this.iPrivConfig = value; + } +} +exports.AgentConfig = AgentConfig; /***/ }), -/* 231 */ -/***/ (function(module, exports, __webpack_require__) { +/* 240 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeakerRecognitionConfig = void 0; -var Exports_1 = __webpack_require__(53); -var SpeakerRecognitionConfig = /** @class */ (function () { - function SpeakerRecognitionConfig(context, parameters) { - this.privContext = context ? context : new Exports_1.Context(null); - this.privParameters = parameters; - } - Object.defineProperty(SpeakerRecognitionConfig.prototype, "parameters", { - get: function () { - return this.privParameters; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(SpeakerRecognitionConfig.prototype, "Context", { - get: function () { - return this.privContext; - }, - enumerable: false, - configurable: true - }); - return SpeakerRecognitionConfig; -}()); -exports.SpeakerRecognitionConfig = SpeakerRecognitionConfig; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InternalParticipants = exports.TranscriberRecognizer = exports.ConversationConnectionConfig = void 0; +var ConversationConnectionConfig_js_1 = __webpack_require__(241); +Object.defineProperty(exports, "ConversationConnectionConfig", ({ enumerable: true, get: function () { return ConversationConnectionConfig_js_1.ConversationConnectionConfig; } })); +var TranscriberRecognizer_js_1 = __webpack_require__(242); +Object.defineProperty(exports, "TranscriberRecognizer", ({ enumerable: true, get: function () { return TranscriberRecognizer_js_1.TranscriberRecognizer; } })); +var InternalParticipants_js_1 = __webpack_require__(243); +Object.defineProperty(exports, "InternalParticipants", ({ enumerable: true, get: function () { return InternalParticipants_js_1.InternalParticipants; } })); /***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { +/* 241 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationConnectionConfig = void 0; +const RestConfigBase_js_1 = __webpack_require__(187); +class ConversationConnectionConfig extends RestConfigBase_js_1.RestConfigBase { + static get defaultLanguageCode() { + return ConversationConnectionConfig.privDefaultLanguageCode; } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpeakerIdMessageAdapter = void 0; -var Exports_1 = __webpack_require__(2); -var Exports_2 = __webpack_require__(61); -var ConnectionFactoryBase_1 = __webpack_require__(123); -/** - * Implements methods for speaker recognition classes, sending requests to endpoint - * and parsing response into expected format - * @class SpeakerIdMessageAdapter - */ -var SpeakerIdMessageAdapter = /** @class */ (function () { - function SpeakerIdMessageAdapter(config) { - var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); - if (!endpoint) { - var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, "westus"); - var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region); - endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "https://" + region + ".api.cognitive" + hostSuffix); - } - this.privUri = endpoint + "/speaker-recognition/{mode}/{dependency}/profiles"; - var options = Exports_1.RestConfigBase.requestOptions; - options.headers[Exports_1.RestConfigBase.configParams.subscriptionKey] = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, undefined); - this.privApiVersion = config.parameters.getProperty(Exports_2.PropertyId.SpeakerRecognition_Api_Version, "2021-09-05"); - this.privRestAdapter = new Exports_1.RestMessageAdapter(options); + static get transcriptionEventKeys() { + return ConversationConnectionConfig.privTranscriptionEventKeys; } - /** - * Sends create profile request to endpoint. - * @function - * @param {VoiceProfileType} profileType - type of voice profile to create. - * @param {string} lang - language/locale of voice profile - * @public - * @returns {Promise} promised rest response containing id of created profile. - */ - SpeakerIdMessageAdapter.prototype.createProfile = function (profileType, lang) { - var uri = this.getOperationUri(profileType); - return this.privRestAdapter.request(Exports_1.RestRequestType.Post, uri, this.getQueryParams(), { locale: lang }); - }; - /** - * Sends create enrollment request to endpoint. - * @function - * @param {VoiceProfile} profileType - voice profile for which to create new enrollment. - * @param {IAudioSource} audioSource - audioSource from which to pull data to send - * @public - * @returns {Promise} rest response to enrollment request. - */ - SpeakerIdMessageAdapter.prototype.createEnrollment = function (profile, audioSource) { - var _this = this; - var uri = this.getOperationUri(profile.profileType) + "/" + profile.profileId + "/enrollments"; - return audioSource.blob.then(function (result) { - return _this.privRestAdapter.request(Exports_1.RestRequestType.File, uri, _this.getQueryParams({ ignoreMinLength: "true" }), null, result); - }); - }; - /** - * Sends verification request to endpoint. - * @function - * @param {SpeakerVerificationModel} model - voice model to verify against. - * @param {IAudioSource} audioSource - audioSource from which to pull data to send - * @public - * @returns {Promise} rest response to enrollment request. - */ - SpeakerIdMessageAdapter.prototype.verifySpeaker = function (model, audioSource) { - return __awaiter(this, void 0, void 0, function () { - var uri, result, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - uri = this.getOperationUri(model.voiceProfile.profileType) + "/" + model.voiceProfile.profileId + ":verify"; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, audioSource.blob]; - case 2: - result = _a.sent(); - return [2 /*return*/, this.privRestAdapter.request(Exports_1.RestRequestType.File, uri, this.getQueryParams({ ignoreMinLength: "true" }), null, result)]; - case 3: - e_1 = _a.sent(); - return [2 /*return*/, Promise.resolve({ data: e_1 })]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - /** - * Sends identification request to endpoint. - * @function - * @param {SpeakerIdentificationModel} model - voice profiles against which to identify. - * @param {IAudioSource} audioSource - audioSource from which to pull data to send - * @public - * @returns {Promise} rest response to enrollment request. - */ - SpeakerIdMessageAdapter.prototype.identifySpeaker = function (model, audioSource) { - return __awaiter(this, void 0, void 0, function () { - var uri, result, e_2; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - uri = this.getOperationUri(Exports_2.VoiceProfileType.TextIndependentIdentification) + ":identifySingleSpeaker"; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, audioSource.blob]; - case 2: - result = _a.sent(); - return [2 /*return*/, this.privRestAdapter.request(Exports_1.RestRequestType.File, uri, this.getQueryParams({ profileIds: model.voiceProfileIds, ignoreMinLength: "true" }), null, result)]; - case 3: - e_2 = _a.sent(); - return [2 /*return*/, Promise.resolve({ data: e_2 })]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - /** - * Sends profile status request to endpoint. - * @function - * @param {VoiceProfile} profile - voice profile to check. - * @public - * @returns {Promise} rest response to status request - */ - SpeakerIdMessageAdapter.prototype.getProfileStatus = function (profile) { - var uri = this.getOperationUri(profile.profileType) + "/" + profile.profileId; - return this.privRestAdapter.request(Exports_1.RestRequestType.Get, uri, this.getQueryParams()); - }; - /** - * Sends get all profiles request to endpoint. - * @function - * @param {VoiceProfileType} profileType - type of profiles to return list of - * @public - * @returns {Promise} promised rest response containing all profiles - */ - SpeakerIdMessageAdapter.prototype.getProfiles = function (profileType) { - var uri = this.getOperationUri(profileType); - return this.privRestAdapter.request(Exports_1.RestRequestType.Get, uri, this.getQueryParams()); - }; - /** - * Sends get activation/auth phrases request to endpoint. - * @function - * @param {VoiceProfileType} profileType - type of profiles to return phrases for - * @param {string} lang - language/locale of voice profile - * @public - * @returns {Promise} promised rest response containing list of valid phrases - */ - SpeakerIdMessageAdapter.prototype.getPhrases = function (profileType, lang) { - var uri = ("" + this.getOperationUri(profileType)).replace("profiles", "phrases") + "/" + lang; - return this.privRestAdapter.request(Exports_1.RestRequestType.Get, uri, this.getQueryParams()); - }; - /** - * Sends delete profile request to endpoint. - * @function - * @param {VoiceProfile} profile - voice profile to delete. - * @public - * @returns {Promise} rest response to deletion request - */ - SpeakerIdMessageAdapter.prototype.deleteProfile = function (profile) { - var uri = this.getOperationUri(profile.profileType) + "/" + profile.profileId; - return this.privRestAdapter.request(Exports_1.RestRequestType.Delete, uri, this.getQueryParams()); - }; - /** - * Sends reset profile request to endpoint. - * @function - * @param {VoiceProfile} profile - voice profile to reset enrollments for. - * @public - * @returns {Promise} rest response to reset request - */ - SpeakerIdMessageAdapter.prototype.resetProfile = function (profile) { - var uri = this.getOperationUri(profile.profileType) + "/" + profile.profileId + ":reset"; - return this.privRestAdapter.request(Exports_1.RestRequestType.Post, uri, this.getQueryParams()); - }; - SpeakerIdMessageAdapter.prototype.getOperationUri = function (profileType) { - var mode = profileType === Exports_2.VoiceProfileType.TextIndependentIdentification ? "identification" : "verification"; - var dependency = profileType === Exports_2.VoiceProfileType.TextDependentVerification ? "text-dependent" : "text-independent"; - return this.privUri.replace("{mode}", mode).replace("{dependency}", dependency); - }; - SpeakerIdMessageAdapter.prototype.getQueryParams = function (params) { - if (params === void 0) { params = {}; } - params[Exports_1.RestConfigBase.configParams.apiVersion] = this.privApiVersion; - return params; - }; - return SpeakerIdMessageAdapter; -}()); -exports.SpeakerIdMessageAdapter = SpeakerIdMessageAdapter; +} +exports.ConversationConnectionConfig = ConversationConnectionConfig; +ConversationConnectionConfig.privDefaultLanguageCode = "en-US"; +ConversationConnectionConfig.privTranscriptionEventKeys = ["iCalUid", "callId", "organizer", "FLAC", "MTUri", "DifferentiateGuestSpeakers", "audiorecording", "Threadid", "OrganizerMri", "OrganizerTenantId", "UserToken"]; /***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { +/* 242 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TranscriberRecognizer = void 0; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; +const Exports_js_1 = __webpack_require__(4); +const Contracts_js_1 = __webpack_require__(70); +const Exports_js_2 = __webpack_require__(85); +const Exports_js_3 = __webpack_require__(2); +const PhraseDetectionContext_js_1 = __webpack_require__(116); +class TranscriberRecognizer extends Exports_js_2.Recognizer { + /** + * TranscriberRecognizer constructor. + * @constructor + * @param {SpeechTranslationConfig} speechTranslationConfig - Non-audio configuration associated with the recognizer + * @param {AudioConfig} audioConfig - An audio configuration associated with the recognizer + */ + constructor(speechTranslationConfig, audioConfig) { + const speechTranslationConfigImpl = speechTranslationConfig; + Contracts_js_1.Contracts.throwIfNull(speechTranslationConfigImpl, "speechTranslationConfig"); + const audioConfigImpl = audioConfig; + Contracts_js_1.Contracts.throwIfNull(audioConfigImpl, "audioConfigImpl"); + Contracts_js_1.Contracts.throwIfNullOrWhitespace(speechTranslationConfigImpl.speechRecognitionLanguage, Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage]); + super(audioConfig, speechTranslationConfigImpl.properties, new Exports_js_3.TranscriberConnectionFactory()); + this.privDisposedRecognizer = false; + } + get speechRecognitionLanguage() { + Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer); + return this.properties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage); + } + get properties() { + return this.privProperties; + } + get authorizationToken() { + return this.properties.getProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token); + } + set authorizationToken(token) { + Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token"); + this.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, token); + } + set meeting(m) { + Contracts_js_1.Contracts.throwIfNullOrUndefined(m, "Meeting"); + this.privMeeting = m; + } + getMeetingInfo() { + Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privMeeting, "Meeting"); + return this.privMeeting.meetingInfo; + } + startContinuousRecognitionAsync(cb, err) { + (0, Exports_js_1.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(PhraseDetectionContext_js_1.RecognitionMode.Conversation), cb, err); + } + stopContinuousRecognitionAsync(cb, err) { + (0, Exports_js_1.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(), cb, err); + } + async close() { + if (!this.privDisposedRecognizer) { + await this.dispose(true); + } + } + // Push async join/leave meeting message via serviceRecognizer + async pushMeetingEvent(meetingInfo, command) { + const reco = (this.privReco); + Contracts_js_1.Contracts.throwIfNullOrUndefined(reco, "serviceRecognizer"); + await reco.sendMeetingSpeechEventAsync(meetingInfo, command); + } + async enforceAudioGating() { + const audioConfigImpl = this.audioConfig; + const format = await audioConfigImpl.format; + const channels = format.channels; + if (channels === 1) { + if (this.properties.getProperty("f0f5debc-f8c9-4892-ac4b-90a7ab359fd2", "false").toLowerCase() !== "true") { + throw new Error("Single channel audio configuration for MeetingTranscriber is currently under private preview, please contact diarizationrequest@microsoft.com for more details"); } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + else if (channels !== 8) { + throw new Error(`Unsupported audio configuration: Detected ${channels}-channel audio`); + } + return; } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FileAudioSource = void 0; -var Exports_1 = __webpack_require__(53); -var Exports_2 = __webpack_require__(4); -var AudioStreamFormat_1 = __webpack_require__(72); -var FileAudioSource = /** @class */ (function () { - function FileAudioSource(file, filename, audioSourceId) { - var _this = this; - this.privStreams = {}; - this.privHeaderEnd = 44; - this.turnOn = function () { - if (_this.privFilename.lastIndexOf(".wav") !== _this.privFilename.length - 4) { - var errorMsg = _this.privFilename + " is not supported. Only WAVE files are allowed at the moment."; - _this.onEvent(new Exports_2.AudioSourceErrorEvent(errorMsg, "")); - return Promise.reject(errorMsg); - } - _this.onEvent(new Exports_2.AudioSourceInitializingEvent(_this.privId)); // no stream id - _this.onEvent(new Exports_2.AudioSourceReadyEvent(_this.privId)); - return; - }; - this.id = function () { - return _this.privId; - }; - this.attach = function (audioNodeId) { return __awaiter(_this, void 0, void 0, function () { - var stream; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.onEvent(new Exports_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId)); - return [4 /*yield*/, this.upload(audioNodeId)]; - case 1: - stream = _a.sent(); - this.onEvent(new Exports_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId)); - return [2 /*return*/, Promise.resolve({ - detach: function () { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - stream.readEnded(); - delete this.privStreams[audioNodeId]; - this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId)); - return [4 /*yield*/, this.turnOff()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); }, - id: function () { - return audioNodeId; - }, - read: function () { - return stream.read(); - }, - })]; - } - }); - }); }; - this.detach = function (audioNodeId) { - if (audioNodeId && _this.privStreams[audioNodeId]) { - _this.privStreams[audioNodeId].close(); - delete _this.privStreams[audioNodeId]; - _this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(_this.privId, audioNodeId)); + connectMeetingCallbacks(transcriber) { + this.canceled = (s, e) => { + if (!!transcriber.canceled) { + transcriber.canceled(transcriber, e); } }; - this.turnOff = function () { - for (var streamId in _this.privStreams) { - if (streamId) { - var stream = _this.privStreams[streamId]; - if (stream && !stream.isClosed) { - stream.close(); - } - } + this.recognizing = (s, e) => { + if (!!transcriber.transcribing) { + transcriber.transcribing(transcriber, e); } - _this.onEvent(new Exports_2.AudioSourceOffEvent(_this.privId)); // no stream now - return Promise.resolve(); }; - this.onEvent = function (event) { - _this.privEvents.onEvent(event); - Exports_2.Events.instance.onEvent(event); - }; - this.privId = audioSourceId ? audioSourceId : Exports_2.createNoDashGuid(); - this.privEvents = new Exports_2.EventSource(); - this.privSource = file; - if (typeof window !== "undefined" && typeof Blob !== "undefined" && this.privSource instanceof Blob) { - this.privFilename = file.name; - } - else { - this.privFilename = filename || "unknown.wav"; - } - // Read the header. - this.privAudioFormatPromise = this.readHeader(); - } - Object.defineProperty(FileAudioSource.prototype, "format", { - get: function () { - return this.privAudioFormatPromise; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FileAudioSource.prototype, "blob", { - get: function () { - return Promise.resolve(this.privSource); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FileAudioSource.prototype, "events", { - get: function () { - return this.privEvents; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FileAudioSource.prototype, "deviceInfo", { - get: function () { - return this.privAudioFormatPromise.then(function (result) { - return Promise.resolve({ - bitspersample: result.bitsPerSample, - channelcount: result.channels, - connectivity: Exports_1.connectivity.Unknown, - manufacturer: "Speech SDK", - model: "File", - samplerate: result.samplesPerSec, - type: Exports_1.type.File, - }); - }); - }, - enumerable: false, - configurable: true - }); - FileAudioSource.prototype.readHeader = function () { - var _this = this; - // Read the wave header. - var maxHeaderSize = 512; - var header = this.privSource.slice(0, maxHeaderSize); - var headerResult = new Exports_2.Deferred(); - var processHeader = function (header) { - var view = new DataView(header); - var getWord = function (index) { - return String.fromCharCode(view.getUint8(index), view.getUint8(index + 1), view.getUint8(index + 2), view.getUint8(index + 3)); - }; - // RIFF 4 bytes. - if ("RIFF" !== getWord(0)) { - headerResult.reject("Invalid WAV header in file, RIFF was not found"); - return; + this.recognized = (s, e) => { + if (!!transcriber.transcribed) { + transcriber.transcribed(transcriber, e); } - // length, 4 bytes - // RIFF Type & fmt 8 bytes - if ("WAVE" !== getWord(8) || "fmt " !== getWord(12)) { - headerResult.reject("Invalid WAV header in file, WAVEfmt was not found"); - return; + }; + this.sessionStarted = (s, e) => { + if (!!transcriber.sessionStarted) { + transcriber.sessionStarted(transcriber, e); } - var formatSize = view.getInt32(16, true); - var channelCount = view.getUint16(22, true); - var sampleRate = view.getUint32(24, true); - var bitsPerSample = view.getUint16(34, true); - // Confirm if header is 44 bytes long. - var pos = 36 + Math.max(formatSize - 16, 0); - for (; getWord(pos) !== "data"; pos += 2) { - if (pos > maxHeaderSize - 8) { - headerResult.reject("Invalid WAV header in file, data block was not found"); - return; - } + }; + this.sessionStopped = (s, e) => { + if (!!transcriber.sessionStopped) { + transcriber.sessionStopped(transcriber, e); } - _this.privHeaderEnd = pos + 8; - headerResult.resolve(AudioStreamFormat_1.AudioStreamFormat.getWaveFormatPCM(sampleRate, bitsPerSample, channelCount)); }; - if (typeof window !== "undefined" && typeof Blob !== "undefined" && header instanceof Blob) { - var reader = new FileReader(); - reader.onload = function (event) { - var header = event.target.result; - processHeader(header); - }; - reader.readAsArrayBuffer(header); + } + disconnectCallbacks() { + this.canceled = undefined; + this.recognizing = undefined; + this.recognized = undefined; + this.sessionStarted = undefined; + this.sessionStopped = undefined; + } + /** + * Disposes any resources held by the object. + * @member ConversationTranscriber.prototype.dispose + * @function + * @public + * @param {boolean} disposing - true if disposing the object. + */ + async dispose(disposing) { + if (this.privDisposedRecognizer) { + return; } - else { - var h = header; - processHeader(h.buffer.slice(h.byteOffset, h.byteOffset + h.byteLength)); + if (disposing) { + this.privDisposedRecognizer = true; + await this.implRecognizerStop(); } - return headerResult.promise; - }; - FileAudioSource.prototype.upload = function (audioNodeId) { - return __awaiter(this, void 0, void 0, function () { - var onerror, format, stream_1, chunk, processFile_1, reader, c, e_1; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - onerror = function (error) { - var errorMsg = "Error occurred while processing '" + _this.privFilename + "'. " + error; - _this.onEvent(new Exports_2.AudioStreamNodeErrorEvent(_this.privId, audioNodeId, errorMsg)); - throw new Error(errorMsg); - }; - _a.label = 1; - case 1: - _a.trys.push([1, 4, , 5]); - return [4 /*yield*/, this.turnOn()]; - case 2: - _a.sent(); - return [4 /*yield*/, this.privAudioFormatPromise]; - case 3: - format = _a.sent(); - stream_1 = new Exports_2.ChunkedArrayBufferStream(format.avgBytesPerSec / 10, audioNodeId); - this.privStreams[audioNodeId] = stream_1; - chunk = this.privSource.slice(this.privHeaderEnd); - processFile_1 = function (buff) { - if (stream_1.isClosed) { - return; // output stream was closed (somebody called TurnOff). We're done here. - } - stream_1.writeStreamChunk({ - buffer: buff, - isEnd: false, - timeReceived: Date.now(), - }); - stream_1.close(); - }; - if (typeof window !== "undefined" && typeof Blob !== "undefined" && chunk instanceof Blob) { - reader = new FileReader(); - reader.onerror = function (ev) { onerror(ev.toString()); }; - reader.onload = function (event) { - var fileBuffer = event.target.result; - processFile_1(fileBuffer); - }; - reader.readAsArrayBuffer(chunk); - } - else { - c = chunk; - processFile_1(c.buffer.slice(c.byteOffset, c.byteOffset + c.byteLength)); - } - return [2 /*return*/, stream_1]; - case 4: - e_1 = _a.sent(); - onerror(e_1); - return [3 /*break*/, 5]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - return FileAudioSource; -}()); -exports.FileAudioSource = FileAudioSource; + await super.dispose(disposing); + } + createRecognizerConfig(speechConfig) { + return new Exports_js_3.RecognizerConfig(speechConfig, this.properties); + } + createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) { + const configImpl = audioConfig; + return new Exports_js_3.TranscriptionServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this); + } +} +exports.TranscriberRecognizer = TranscriberRecognizer; /***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { +/* 243 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PcmRecorder = void 0; -var Exports_1 = __webpack_require__(4); -var PcmRecorder = /** @class */ (function () { - function PcmRecorder(stopInputOnRelease) { - var _this = this; - this.record = function (context, mediaStream, outputStream) { - var desiredSampleRate = 16000; - var waveStreamEncoder = new Exports_1.RiffPcmEncoder(context.sampleRate, desiredSampleRate); - var needHeader = true; - var micInput = context.createMediaStreamSource(mediaStream); - if (!_this.privSpeechProcessorScript) { - var workletScript = "class SP extends AudioWorkletProcessor {\n constructor(options) {\n super(options);\n }\n process(inputs, outputs) {\n const input = inputs[0];\n const output = [];\n for (let channel = 0; channel < input.length; channel += 1) {\n output[channel] = input[channel];\n }\n this.port.postMessage(output[0]);\n return true;\n }\n }\n registerProcessor('speech-processor', SP);"; // tslint:disable-line:max-line-length - var blob = new Blob([workletScript], { type: "application/javascript; charset=utf-8" }); - _this.privSpeechProcessorScript = URL.createObjectURL(blob); - } - var attachScriptProcessor = function () { - var scriptNode = (function () { - var bufferSize = 0; - try { - return context.createScriptProcessor(bufferSize, 1, 1); - } - catch (error) { - // Webkit (<= version 31) requires a valid bufferSize. - bufferSize = 2048; - var audioSampleRate = context.sampleRate; - while (bufferSize < 16384 && audioSampleRate >= (2 * desiredSampleRate)) { - bufferSize <<= 1; - audioSampleRate >>= 1; - } - return context.createScriptProcessor(bufferSize, 1, 1); - } - })(); - scriptNode.onaudioprocess = function (event) { - var inputFrame = event.inputBuffer.getChannelData(0); - if (outputStream && !outputStream.isClosed) { - var waveFrame = waveStreamEncoder.encode(inputFrame); - if (!!waveFrame) { - outputStream.writeStreamChunk({ - buffer: waveFrame, - isEnd: false, - timeReceived: Date.now(), - }); - needHeader = false; - } - } - }; - micInput.connect(scriptNode); - scriptNode.connect(context.destination); - _this.privMediaResources = { - scriptProcessorNode: scriptNode, - source: micInput, - stream: mediaStream, - }; - }; - // https://webaudio.github.io/web-audio-api/#audioworklet - // Using AudioWorklet to improve audio quality and avoid audio glitches due to blocking the UI thread - if (!!_this.privSpeechProcessorScript && !!context.audioWorklet) { - context.audioWorklet - .addModule(_this.privSpeechProcessorScript) - .then(function () { - var workletNode = new AudioWorkletNode(context, "speech-processor"); - workletNode.port.onmessage = function (ev) { - var inputFrame = ev.data; - if (outputStream && !outputStream.isClosed) { - var waveFrame = waveStreamEncoder.encode(inputFrame); - if (!!waveFrame) { - outputStream.writeStreamChunk({ - buffer: waveFrame, - isEnd: false, - timeReceived: Date.now(), - }); - needHeader = false; - } - } - }; - micInput.connect(workletNode); - workletNode.connect(context.destination); - _this.privMediaResources = { - scriptProcessorNode: workletNode, - source: micInput, - stream: mediaStream, - }; - }) - .catch(function () { - attachScriptProcessor(); - }); - } - else { - try { - attachScriptProcessor(); - } - catch (err) { - throw new Error("Unable to start audio worklet node for PCMRecorder: " + err); - } - } - }; - this.releaseMediaResources = function (context) { - if (_this.privMediaResources) { - if (_this.privMediaResources.scriptProcessorNode) { - _this.privMediaResources.scriptProcessorNode.disconnect(context.destination); - _this.privMediaResources.scriptProcessorNode = null; - } - if (_this.privMediaResources.source) { - _this.privMediaResources.source.disconnect(); - if (_this.privStopInputOnRelease) { - _this.privMediaResources.stream.getTracks().forEach(function (track) { return track.stop(); }); - } - _this.privMediaResources.source = null; - } - } - }; - this.privStopInputOnRelease = stopInputOnRelease; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InternalParticipants = void 0; +/** Users participating in the meeting */ +class InternalParticipants { + constructor(participants = []) { + this.participants = participants; } - PcmRecorder.prototype.setWorkletUrl = function (url) { - this.privSpeechProcessorScript = url; - }; - return PcmRecorder; -}()); -exports.PcmRecorder = PcmRecorder; + /** + * Add or update a participant + * @param value + */ + addOrUpdateParticipant(value) { + if (value === undefined) { + return; + } + const exists = this.getParticipantIndex(value.id); + if (exists > -1) { + this.participants.splice(exists, 1, value); + } + else { + this.participants.push(value); + } + // ensure it was added ok + return this.getParticipant(value.id); + } + /** + * Find the participant's position in the participants list. + * @param id + */ + getParticipantIndex(id) { + return this.participants.findIndex((p) => p.id === id); + } + /** + * Find the participant by id. + * @param id + */ + getParticipant(id) { + return this.participants.find((p) => p.id === id); + } + /** + * Remove a participant from the participants list. + */ + deleteParticipant(id) { + this.participants = this.participants.filter((p) => p.id !== id); + } +} +exports.InternalParticipants = InternalParticipants; /***/ }), -/* 235 */ -/***/ (function(module, exports, __webpack_require__) { +/* 244 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SynthesisAudioMetadata = exports.MetadataType = void 0; +var MetadataType; +(function (MetadataType) { + MetadataType["WordBoundary"] = "WordBoundary"; + MetadataType["Bookmark"] = "Bookmark"; + MetadataType["Viseme"] = "Viseme"; + MetadataType["SentenceBoundary"] = "SentenceBoundary"; + MetadataType["SessionEnd"] = "SessionEnd"; + MetadataType["AvatarSignal"] = "TalkingAvatarSignal"; +})(MetadataType = exports.MetadataType || (exports.MetadataType = {})); +class SynthesisAudioMetadata { + constructor(json) { + this.privSynthesisAudioMetadata = JSON.parse(json); } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.WebsocketConnection = void 0; -var Exports_1 = __webpack_require__(4); -var WebsocketMessageAdapter_1 = __webpack_require__(236); -var WebsocketConnection = /** @class */ (function () { - function WebsocketConnection(uri, queryParameters, headers, messageFormatter, proxyInfo, enableCompression, connectionId) { - var _this = this; - if (enableCompression === void 0) { enableCompression = false; } - this.privIsDisposed = false; - this.isDisposed = function () { - return _this.privIsDisposed; - }; - this.state = function () { - return _this.privConnectionMessageAdapter.state; - }; - this.open = function () { - return _this.privConnectionMessageAdapter.open(); - }; - this.send = function (message) { - return _this.privConnectionMessageAdapter.send(message); - }; - this.read = function () { - return _this.privConnectionMessageAdapter.read(); - }; - if (!uri) { - throw new Exports_1.ArgumentNullError("uri"); - } - if (!messageFormatter) { - throw new Exports_1.ArgumentNullError("messageFormatter"); - } - this.privMessageFormatter = messageFormatter; - var queryParams = ""; - var i = 0; - if (queryParameters) { - for (var paramName in queryParameters) { - if (paramName) { - queryParams += ((i === 0) && (uri.indexOf("?") === -1)) ? "?" : "&"; - var val = encodeURIComponent(queryParameters[paramName]); - queryParams += paramName + "=" + val; - i++; - } - } - } - if (headers) { - for (var headerName in headers) { - if (headerName) { - queryParams += ((i === 0) && (uri.indexOf("?") === -1)) ? "?" : "&"; - var val = encodeURIComponent(headers[headerName]); - queryParams += headerName + "=" + val; - i++; - } - } - } - this.privUri = uri + queryParams; - this.privId = connectionId ? connectionId : Exports_1.createNoDashGuid(); - this.privConnectionMessageAdapter = new WebsocketMessageAdapter_1.WebsocketMessageAdapter(this.privUri, this.id, this.privMessageFormatter, proxyInfo, headers, enableCompression); - } - WebsocketConnection.prototype.dispose = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.privIsDisposed = true; - if (!this.privConnectionMessageAdapter) return [3 /*break*/, 2]; - return [4 /*yield*/, this.privConnectionMessageAdapter.close()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - Object.defineProperty(WebsocketConnection.prototype, "id", { - get: function () { - return this.privId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(WebsocketConnection.prototype, "events", { - get: function () { - return this.privConnectionMessageAdapter.events; - }, - enumerable: false, - configurable: true - }); - return WebsocketConnection; -}()); -exports.WebsocketConnection = WebsocketConnection; + static fromJSON(json) { + return new SynthesisAudioMetadata(json); + } + get Metadata() { + return this.privSynthesisAudioMetadata.Metadata; + } +} +exports.SynthesisAudioMetadata = SynthesisAudioMetadata; /***/ }), -/* 236 */ -/***/ (function(module, exports, __webpack_require__) { +/* 245 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SynthesisTurn = void 0; +const Exports_js_1 = __webpack_require__(4); +const AudioOutputStream_js_1 = __webpack_require__(90); +const Exports_js_2 = __webpack_require__(85); +const SynthesisAudioMetadata_js_1 = __webpack_require__(244); +const SynthesisEvents_js_1 = __webpack_require__(246); +class SynthesisTurn { + constructor() { + this.privIsDisposed = false; + this.privIsSynthesizing = false; + this.privIsSynthesisEnded = false; + this.privBytesReceived = 0; + this.privInTurn = false; + this.privTextOffset = 0; + this.privNextSearchTextIndex = 0; + this.privSentenceOffset = 0; + this.privNextSearchSentenceIndex = 0; + // Latency tracking + this.privSynthesisStartTime = 0; + this.privConnectionLatency = -1; + this.privNetworkLatency = -1; + this.privFirstByteLatency = -1; + this.privServiceLatency = -1; + this.privRequestId = (0, Exports_js_1.createNoDashGuid)(); + this.privTurnDeferral = new Exports_js_1.Deferred(); + // We're not in a turn, so resolve. + this.privTurnDeferral.resolve(); } -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.WebsocketMessageAdapter = void 0; -var HeaderNames_1 = __webpack_require__(55); -var Exports_1 = __webpack_require__(4); -// Node.JS specific web socket / browser support. -var ws_1 = __importDefault(__webpack_require__(237)); -var CertChecks_1 = __webpack_require__(238); -var WebsocketMessageAdapter = /** @class */ (function () { - function WebsocketMessageAdapter(uri, connectionId, messageFormatter, proxyInfo, headers, enableCompression) { - var _this = this; - this.open = function () { - if (_this.privConnectionState === Exports_1.ConnectionState.Disconnected) { - return Promise.reject("Cannot open a connection that is in " + _this.privConnectionState + " state"); - } - if (_this.privConnectionEstablishDeferral) { - return _this.privConnectionEstablishDeferral.promise; - } - _this.privConnectionEstablishDeferral = new Exports_1.Deferred(); - _this.privCertificateValidatedDeferral = new Exports_1.Deferred(); - _this.privConnectionState = Exports_1.ConnectionState.Connecting; - try { - if (typeof WebSocket !== "undefined" && !WebsocketMessageAdapter.forceNpmWebSocket) { - // Browser handles cert checks. - _this.privCertificateValidatedDeferral.resolve(); - _this.privWebsocketClient = new WebSocket(_this.privUri); - } - else { - var options = { headers: _this.privHeaders, perMessageDeflate: _this.privEnableCompression }; - // The ocsp library will handle validation for us and fail the connection if needed. - _this.privCertificateValidatedDeferral.resolve(); - var checkAgent = new CertChecks_1.CertCheckAgent(_this.proxyInfo); - options.agent = checkAgent.GetAgent(); - // Workaround for https://github.com/microsoft/cognitive-services-speech-sdk-js/issues/465 - // Which is root caused by https://github.com/TooTallNate/node-agent-base/issues/61 - var uri = new URL(_this.privUri); - var protocol = uri.protocol; - if ((protocol === null || protocol === void 0 ? void 0 : protocol.toLocaleLowerCase()) === "wss:") { - protocol = "https:"; - } - else if ((protocol === null || protocol === void 0 ? void 0 : protocol.toLocaleLowerCase()) === "ws:") { - protocol = "http:"; - } - options.agent.protocol = protocol; - _this.privWebsocketClient = new ws_1.default(_this.privUri, options); + get requestId() { + return this.privRequestId; + } + get streamId() { + return this.privStreamId; + } + set streamId(value) { + this.privStreamId = value; + } + get audioOutputFormat() { + return this.privAudioOutputFormat; + } + set audioOutputFormat(format) { + this.privAudioOutputFormat = format; + } + 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; + } + // The number of bytes received for current turn + get bytesReceived() { + return this.privBytesReceived; + } + get audioDuration() { + return this.privAudioDuration; + } + get extraProperties() { + if (!!this.privWebRTCSDP) { + const properties = new Exports_js_2.PropertyCollection(); + properties.setProperty(Exports_js_2.PropertyId.TalkingAvatarService_WebRTC_SDP, this.privWebRTCSDP); + return properties; + } + return undefined; + } + async getAllReceivedAudio() { + if (!!this.privReceivedAudio) { + return Promise.resolve(this.privReceivedAudio); + } + if (!this.privIsSynthesisEnded) { + return null; + } + await this.readAllAudioFromStream(); + return Promise.resolve(this.privReceivedAudio); + } + async getAllReceivedAudioWithHeader() { + if (!!this.privReceivedAudioWithHeader) { + return this.privReceivedAudioWithHeader; + } + if (!this.privIsSynthesisEnded) { + return null; + } + if (this.audioOutputFormat.hasHeader) { + const audio = await this.getAllReceivedAudio(); + this.privReceivedAudioWithHeader = this.audioOutputFormat.addHeader(audio); + return this.privReceivedAudioWithHeader; + } + else { + return this.getAllReceivedAudio(); + } + } + startNewSynthesis(requestId, rawText, isSSML, audioDestination) { + this.privIsSynthesisEnded = false; + this.privIsSynthesizing = true; + this.privRequestId = requestId; + this.privRawText = rawText; + this.privIsSSML = isSSML; + this.privAudioOutputStream = new AudioOutputStream_js_1.PullAudioOutputStreamImpl(); + this.privAudioOutputStream.format = this.privAudioOutputFormat; + this.privReceivedAudio = null; + this.privReceivedAudioWithHeader = null; + this.privBytesReceived = 0; + this.privTextOffset = 0; + this.privNextSearchTextIndex = 0; + this.privSentenceOffset = 0; + this.privNextSearchSentenceIndex = 0; + this.privPartialVisemeAnimation = ""; + this.privWebRTCSDP = ""; + // Reset latency tracking for this synthesis request + this.privSynthesisStartTime = Date.now(); + this.privConnectionLatency = -1; + this.privNetworkLatency = -1; + this.privFirstByteLatency = -1; + this.privServiceLatency = -1; + if (audioDestination !== undefined) { + this.privTurnAudioDestination = audioDestination; + this.privTurnAudioDestination.format = this.privAudioOutputFormat; + } + this.onEvent(new SynthesisEvents_js_1.SynthesisTriggeredEvent(this.requestId, undefined, audioDestination === undefined ? undefined : audioDestination.id())); + } + onPreConnectionStart(authFetchEventId) { + this.privAuthFetchEventId = authFetchEventId; + this.onEvent(new SynthesisEvents_js_1.ConnectingToSynthesisServiceEvent(this.privRequestId, this.privAuthFetchEventId)); + } + onAuthCompleted(isError) { + if (isError) { + this.onComplete(); + } + } + onConnectionEstablishCompleted(statusCode) { + if (statusCode === 200) { + this.privConnectionLatency = Date.now() - this.privSynthesisStartTime; + this.onEvent(new SynthesisEvents_js_1.SynthesisStartedEvent(this.requestId, this.privAuthFetchEventId)); + this.privBytesReceived = 0; + return; + } + else if (statusCode === 403) { + this.onComplete(); + } + } + onServiceResponseMessage(responseJson) { + const response = JSON.parse(responseJson); + this.streamId = response.audio.streamId; + } + onServiceTurnEndResponse() { + this.privInTurn = false; + this.privTurnDeferral.resolve(); + this.onComplete(); + } + onServiceTurnStartResponse(responseJson) { + if (!!this.privTurnDeferral && !!this.privInTurn) { + // What? How are we starting a turn with another not done? + this.privTurnDeferral.reject("Another turn started before current completed."); + // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.privTurnDeferral.promise.then().catch(() => { }); + } + this.privInTurn = true; + this.privTurnDeferral = new Exports_js_1.Deferred(); + // If connection was reused, onConnectionEstablishCompleted was never called; treat as 0. + if (this.privConnectionLatency < 0) { + this.privConnectionLatency = 0; + } + this.privNetworkLatency = Date.now() - this.privSynthesisStartTime - this.privConnectionLatency; + const response = JSON.parse(responseJson); + if (!!response.webrtc) { + this.privWebRTCSDP = response.webrtc.connectionString; + } + } + onAudioChunkReceived(data) { + if (this.isSynthesizing) { + if (this.privFirstByteLatency < 0) { + this.privFirstByteLatency = Date.now() - this.privSynthesisStartTime; + if (this.privNetworkLatency >= 0) { + this.privServiceLatency = this.privFirstByteLatency - this.privConnectionLatency - this.privNetworkLatency; } - _this.privWebsocketClient.binaryType = "arraybuffer"; - _this.privReceivingMessageQueue = new Exports_1.Queue(); - _this.privDisconnectDeferral = new Exports_1.Deferred(); - _this.privSendMessageQueue = new Exports_1.Queue(); - _this.processSendQueue().catch(function (reason) { - Exports_1.Events.instance.onEvent(new Exports_1.BackgroundEvent(reason)); - }); } - catch (error) { - _this.privConnectionEstablishDeferral.resolve(new Exports_1.ConnectionOpenResponse(500, error)); - return _this.privConnectionEstablishDeferral.promise; - } - _this.onEvent(new Exports_1.ConnectionStartEvent(_this.privConnectionId, _this.privUri)); - _this.privWebsocketClient.onopen = function (e) { - _this.privCertificateValidatedDeferral.promise.then(function () { - _this.privConnectionState = Exports_1.ConnectionState.Connected; - _this.onEvent(new Exports_1.ConnectionEstablishedEvent(_this.privConnectionId)); - _this.privConnectionEstablishDeferral.resolve(new Exports_1.ConnectionOpenResponse(200, "")); - }, function (error) { - _this.privConnectionEstablishDeferral.reject(error); - }); - }; - _this.privWebsocketClient.onerror = function (e) { - _this.onEvent(new Exports_1.ConnectionErrorEvent(_this.privConnectionId, e.message, e.type)); - _this.privLastErrorReceived = e.message; - }; - _this.privWebsocketClient.onclose = function (e) { - if (_this.privConnectionState === Exports_1.ConnectionState.Connecting) { - _this.privConnectionState = Exports_1.ConnectionState.Disconnected; - // this.onEvent(new ConnectionEstablishErrorEvent(this.connectionId, e.code, e.reason)); - _this.privConnectionEstablishDeferral.resolve(new Exports_1.ConnectionOpenResponse(e.code, e.reason + " " + _this.privLastErrorReceived)); - } - else { - _this.privConnectionState = Exports_1.ConnectionState.Disconnected; - _this.privWebsocketClient = null; - _this.onEvent(new Exports_1.ConnectionClosedEvent(_this.privConnectionId, e.code, e.reason)); - } - _this.onClose(e.code, e.reason).catch(function (reason) { - Exports_1.Events.instance.onEvent(new Exports_1.BackgroundEvent(reason)); - }); - }; - _this.privWebsocketClient.onmessage = function (e) { - var networkReceivedTime = new Date().toISOString(); - if (_this.privConnectionState === Exports_1.ConnectionState.Connected) { - var deferred_1 = new Exports_1.Deferred(); - // let id = ++this.idCounter; - _this.privReceivingMessageQueue.enqueueFromPromise(deferred_1.promise); - if (e.data instanceof ArrayBuffer) { - var rawMessage = new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Binary, e.data); - _this.privMessageFormatter - .toConnectionMessage(rawMessage) - .then(function (connectionMessage) { - _this.onEvent(new Exports_1.ConnectionMessageReceivedEvent(_this.privConnectionId, networkReceivedTime, connectionMessage)); - deferred_1.resolve(connectionMessage); - }, function (error) { - // TODO: Events for these ? - deferred_1.reject("Invalid binary message format. Error: " + error); - }); - } - else { - var rawMessage = new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Text, e.data); - _this.privMessageFormatter - .toConnectionMessage(rawMessage) - .then(function (connectionMessage) { - _this.onEvent(new Exports_1.ConnectionMessageReceivedEvent(_this.privConnectionId, networkReceivedTime, connectionMessage)); - deferred_1.resolve(connectionMessage); - }, function (error) { - // TODO: Events for these ? - deferred_1.reject("Invalid text message format. Error: " + error); - }); + this.privAudioOutputStream.write(data); + this.privBytesReceived += data.byteLength; + if (this.privTurnAudioDestination !== undefined) { + this.privTurnAudioDestination.write(data); + } + } + } + onTextBoundaryEvent(metadata) { + this.updateTextOffset(metadata.Data.text.Text, metadata.Type); + } + onVisemeMetadataReceived(metadata) { + if (metadata.Data.AnimationChunk !== undefined) { + this.privPartialVisemeAnimation += metadata.Data.AnimationChunk; + } + } + onSessionEnd(metadata) { + this.privAudioDuration = metadata.Data.Offset; + } + async constructSynthesisResult() { + const finishLatency = Date.now() - this.privSynthesisStartTime; + const audioBuffer = await this.getAllReceivedAudioWithHeader(); + const properties = new Exports_js_2.PropertyCollection(); + if (!!this.privWebRTCSDP) { + properties.setProperty(Exports_js_2.PropertyId.TalkingAvatarService_WebRTC_SDP, this.privWebRTCSDP); + } + properties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_SynthesisFirstByteLatencyMs, String(Math.max(0, this.privFirstByteLatency))); + properties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_SynthesisFinishLatencyMs, String(finishLatency)); + properties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_SynthesisConnectionLatencyMs, String(Math.max(0, this.privConnectionLatency))); + properties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_SynthesisNetworkLatencyMs, String(Math.max(0, this.privNetworkLatency))); + properties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_SynthesisServiceLatencyMs, String(Math.max(0, this.privServiceLatency))); + return new Exports_js_2.SpeechSynthesisResult(this.requestId, Exports_js_2.ResultReason.SynthesizingAudioCompleted, audioBuffer, undefined, properties, this.audioDuration); + } + dispose() { + if (!this.privIsDisposed) { + // we should have completed by now. If we did not its an unknown error. + this.privIsDisposed = true; + } + } + onStopSynthesizing() { + this.onComplete(); + } + /** + * Gets the viseme animation string (merged from animation chunk), and clears the internal + * partial animation. + */ + getAndClearVisemeAnimation() { + const animation = this.privPartialVisemeAnimation; + this.privPartialVisemeAnimation = ""; + return animation; + } + onEvent(event) { + Exports_js_1.Events.instance.onEvent(event); + } + /** + * Check if the text is an XML(SSML) tag + * @param text + * @private + */ + static isXmlTag(text) { + return text.length >= 2 && text[0] === "<" && text[text.length - 1] === ">"; + } + updateTextOffset(text, type) { + if (type === SynthesisAudioMetadata_js_1.MetadataType.WordBoundary) { + this.privTextOffset = this.privRawText.indexOf(text, this.privNextSearchTextIndex); + if (this.privTextOffset >= 0) { + this.privNextSearchTextIndex = this.privTextOffset + text.length; + if (this.privIsSSML) { + if (this.withinXmlTag(this.privTextOffset) && !SynthesisTurn.isXmlTag(text)) { + this.updateTextOffset(text, type); } } - }; - return _this.privConnectionEstablishDeferral.promise; - }; - this.send = function (message) { - if (_this.privConnectionState !== Exports_1.ConnectionState.Connected) { - return Promise.reject("Cannot send on connection that is in " + Exports_1.ConnectionState[_this.privConnectionState] + " state"); - } - var messageSendStatusDeferral = new Exports_1.Deferred(); - var messageSendDeferral = new Exports_1.Deferred(); - _this.privSendMessageQueue.enqueueFromPromise(messageSendDeferral.promise); - _this.privMessageFormatter - .fromConnectionMessage(message) - .then(function (rawMessage) { - messageSendDeferral.resolve({ - Message: message, - RawWebsocketMessage: rawMessage, - sendStatusDeferral: messageSendStatusDeferral, - }); - }, function (error) { - messageSendDeferral.reject("Error formatting the message. " + error); - }); - return messageSendStatusDeferral.promise; - }; - this.read = function () { - if (_this.privConnectionState !== Exports_1.ConnectionState.Connected) { - return Promise.reject("Cannot read on connection that is in " + _this.privConnectionState + " state"); } - return _this.privReceivingMessageQueue.dequeue(); - }; - this.close = function (reason) { - if (_this.privWebsocketClient) { - if (_this.privConnectionState !== Exports_1.ConnectionState.Disconnected) { - _this.privWebsocketClient.close(1000, reason ? reason : "Normal closure by client"); + } + else { + this.privSentenceOffset = this.privRawText.indexOf(text, this.privNextSearchSentenceIndex); + if (this.privSentenceOffset >= 0) { + this.privNextSearchSentenceIndex = this.privSentenceOffset + text.length; + if (this.privIsSSML) { + if (this.withinXmlTag(this.privSentenceOffset) && !SynthesisTurn.isXmlTag(text)) { + this.updateTextOffset(text, type); + } } } - else { - return Promise.resolve(); + } + } + onComplete() { + if (this.privIsSynthesizing) { + this.privIsSynthesizing = false; + this.privIsSynthesisEnded = true; + this.privAudioOutputStream.close(); + this.privInTurn = false; + if (this.privTurnAudioDestination !== undefined) { + this.privTurnAudioDestination.close(); + this.privTurnAudioDestination = undefined; } - return _this.privDisconnectDeferral.promise; - }; - this.sendRawMessage = function (sendItem) { + } + } + async readAllAudioFromStream() { + if (this.privIsSynthesisEnded) { + this.privReceivedAudio = new ArrayBuffer(this.bytesReceived); try { - // indicates we are draining the queue and it came with no message; - if (!sendItem) { - return Promise.resolve(); - } - _this.onEvent(new Exports_1.ConnectionMessageSentEvent(_this.privConnectionId, new Date().toISOString(), sendItem.Message)); - // add a check for the ws readystate in order to stop the red console error 'WebSocket is already in CLOSING or CLOSED state' appearing - if (_this.isWebsocketOpen) { - _this.privWebsocketClient.send(sendItem.RawWebsocketMessage.payload); - } - else { - return Promise.reject("websocket send error: Websocket not ready " + _this.privConnectionId + " " + sendItem.Message.id + " " + new Error().stack); - } - return Promise.resolve(); + await this.privAudioOutputStream.read(this.privReceivedAudio); } catch (e) { - return Promise.reject("websocket send error: " + e); + this.privReceivedAudio = new ArrayBuffer(0); } - }; - this.onEvent = function (event) { - _this.privConnectionEvents.onEvent(event); - Exports_1.Events.instance.onEvent(event); - }; - if (!uri) { - throw new Exports_1.ArgumentNullError("uri"); - } - if (!messageFormatter) { - throw new Exports_1.ArgumentNullError("messageFormatter"); } - this.proxyInfo = proxyInfo; - this.privConnectionEvents = new Exports_1.EventSource(); - this.privConnectionId = connectionId; - this.privMessageFormatter = messageFormatter; - this.privConnectionState = Exports_1.ConnectionState.None; - this.privUri = uri; - this.privHeaders = headers; - this.privEnableCompression = enableCompression; - // Add the connection ID to the headers - this.privHeaders[HeaderNames_1.HeaderNames.ConnectionId] = this.privConnectionId; - this.privLastErrorReceived = ""; } - Object.defineProperty(WebsocketMessageAdapter.prototype, "state", { - get: function () { - return this.privConnectionState; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(WebsocketMessageAdapter.prototype, "events", { - get: function () { - return this.privConnectionEvents; - }, - enumerable: false, - configurable: true - }); - WebsocketMessageAdapter.prototype.onClose = function (code, reason) { - return __awaiter(this, void 0, void 0, function () { - var closeReason; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - closeReason = "Connection closed. " + code + ": " + reason; - this.privConnectionState = Exports_1.ConnectionState.Disconnected; - this.privDisconnectDeferral.resolve(); - return [4 /*yield*/, this.privReceivingMessageQueue.drainAndDispose(function (pendingReceiveItem) { - // TODO: Events for these ? - // Logger.instance.onEvent(new LoggingEvent(LogType.Warning, null, `Failed to process received message. Reason: ${closeReason}, Message: ${JSON.stringify(pendingReceiveItem)}`)); - }, closeReason)]; - case 1: - _a.sent(); - return [4 /*yield*/, this.privSendMessageQueue.drainAndDispose(function (pendingSendItem) { - pendingSendItem.sendStatusDeferral.reject(closeReason); - }, closeReason)]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - WebsocketMessageAdapter.prototype.processSendQueue = function () { - return __awaiter(this, void 0, void 0, function () { - var itemToSend, sendItem, sendError_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (false) {} - itemToSend = this.privSendMessageQueue.dequeue(); - return [4 /*yield*/, itemToSend]; - case 1: - sendItem = _a.sent(); - // indicates we are draining the queue and it came with no message; - if (!sendItem) { - return [2 /*return*/]; - } - _a.label = 2; - case 2: - _a.trys.push([2, 4, , 5]); - return [4 /*yield*/, this.sendRawMessage(sendItem)]; - case 3: - _a.sent(); - sendItem.sendStatusDeferral.resolve(); - return [3 /*break*/, 5]; - case 4: - sendError_1 = _a.sent(); - sendItem.sendStatusDeferral.reject(sendError_1); - return [3 /*break*/, 5]; - case 5: return [3 /*break*/, 0]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - Object.defineProperty(WebsocketMessageAdapter.prototype, "isWebsocketOpen", { - get: function () { - return this.privWebsocketClient && this.privWebsocketClient.readyState === this.privWebsocketClient.OPEN; - }, - enumerable: false, - configurable: true - }); - WebsocketMessageAdapter.forceNpmWebSocket = false; - return WebsocketMessageAdapter; -}()); -exports.WebsocketMessageAdapter = WebsocketMessageAdapter; + /** + * Check if current idx is in XML(SSML) tag + * @param idx + * @private + */ + withinXmlTag(idx) { + return this.privRawText.indexOf("<", idx + 1) > this.privRawText.indexOf(">", idx + 1); + } +} +exports.SynthesisTurn = SynthesisTurn; + + + +/***/ }), +/* 246 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SynthesisStartedEvent = exports.ConnectingToSynthesisServiceEvent = exports.SynthesisTriggeredEvent = exports.SpeechSynthesisEvent = void 0; +/* eslint-disable max-classes-per-file */ +const Exports_js_1 = __webpack_require__(4); +class SpeechSynthesisEvent extends Exports_js_1.PlatformEvent { + constructor(eventName, requestId, eventType = Exports_js_1.EventType.Info) { + super(eventName, eventType); + this.privRequestId = requestId; + } + get requestId() { + return this.privRequestId; + } +} +exports.SpeechSynthesisEvent = SpeechSynthesisEvent; +class SynthesisTriggeredEvent extends SpeechSynthesisEvent { + constructor(requestId, sessionAudioDestinationId, turnAudioDestinationId) { + super("SynthesisTriggeredEvent", requestId); + this.privSessionAudioDestinationId = sessionAudioDestinationId; + this.privTurnAudioDestinationId = turnAudioDestinationId; + } + get audioSessionDestinationId() { + return this.privSessionAudioDestinationId; + } + get audioTurnDestinationId() { + return this.privTurnAudioDestinationId; + } +} +exports.SynthesisTriggeredEvent = SynthesisTriggeredEvent; +class ConnectingToSynthesisServiceEvent extends SpeechSynthesisEvent { + constructor(requestId, authFetchEventId) { + super("ConnectingToSynthesisServiceEvent", requestId); + this.privAuthFetchEventId = authFetchEventId; + } + get authFetchEventId() { + return this.privAuthFetchEventId; + } +} +exports.ConnectingToSynthesisServiceEvent = ConnectingToSynthesisServiceEvent; +class SynthesisStartedEvent extends SpeechSynthesisEvent { + constructor(requestId, authFetchEventId) { + super("SynthesisStartedEvent", requestId); + this.privAuthFetchEventId = authFetchEventId; + } + get authFetchEventId() { + return this.privAuthFetchEventId; + } +} +exports.SynthesisStartedEvent = SynthesisStartedEvent; -/***/ }), -/* 237 */ -/***/ (function(module, exports) { -/* (ignored) */ /***/ }), -/* 238 */ -/***/ (function(module, exports, __webpack_require__) { +/* 247 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* WEBPACK VAR INJECTION */(function(process, Buffer) { + // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SynthesisAdapterBase = void 0; +const Exports_js_1 = __webpack_require__(4); +const Exports_js_2 = __webpack_require__(85); +const Exports_js_3 = __webpack_require__(2); +const SpeechConnectionMessage_Internal_js_1 = __webpack_require__(188); +class SynthesisAdapterBase { + constructor(authentication, connectionFactory, synthesizerConfig, audioDestination) { + this.speakOverride = undefined; + this.receiveMessageOverride = undefined; + this.connectImplOverride = undefined; + this.configConnectionOverride = undefined; + // A promise for a configured connection. + // Do not consume directly, call fetchConnection instead. + this.privConnectionConfigurationPromise = undefined; + if (!authentication) { + throw new Exports_js_1.ArgumentNullError("authentication"); + } + if (!connectionFactory) { + throw new Exports_js_1.ArgumentNullError("connectionFactory"); + } + if (!synthesizerConfig) { + throw new Exports_js_1.ArgumentNullError("synthesizerConfig"); + } + this.privAuthentication = authentication; + this.privConnectionFactory = connectionFactory; + this.privSynthesizerConfig = synthesizerConfig; + this.privIsDisposed = false; + this.privSessionAudioDestination = audioDestination; + this.privSynthesisTurn = new Exports_js_3.SynthesisTurn(); + this.privConnectionEvents = new Exports_js_1.EventSource(); + this.privServiceEvents = new Exports_js_1.EventSource(); + this.privSynthesisContext = new Exports_js_3.SynthesisContext(); + this.privAgentConfig = new Exports_js_3.AgentConfig(); + this.connectionEvents.attach((connectionEvent) => { + if (connectionEvent.name === "ConnectionClosedEvent") { + const connectionClosedEvent = connectionEvent; + if (connectionClosedEvent.statusCode !== 1000) { + this.cancelSynthesisLocal(Exports_js_2.CancellationReason.Error, connectionClosedEvent.statusCode === 1007 ? Exports_js_2.CancellationErrorCode.BadRequestParameters : Exports_js_2.CancellationErrorCode.ConnectionFailure, `${connectionClosedEvent.reason} websocket error code: ${connectionClosedEvent.statusCode}`); + } } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + }); } -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CertCheckAgent = void 0; -var tls = __importStar(__webpack_require__(240)); -var parse = __importStar(__webpack_require__(241)); -var ocsp = __importStar(__webpack_require__(244)); -var Exports_1 = __webpack_require__(4); -var agent_base_1 = __importDefault(__webpack_require__(245)); -// @ts-ignore -var async_disk_cache_1 = __importDefault(__webpack_require__(246)); -var https_proxy_agent_1 = __importDefault(__webpack_require__(247)); -var net = __importStar(__webpack_require__(248)); -var OCSPEvents_1 = __webpack_require__(49); -var CertCheckAgent = /** @class */ (function () { - function CertCheckAgent(proxyInfo) { - if (!!proxyInfo) { - this.privProxyInfo = proxyInfo; - } - // Initialize this here to allow tests to set the env variable before the cache is constructed. - if (!CertCheckAgent.privDiskCache) { - CertCheckAgent.privDiskCache = new async_disk_cache_1.default("microsoft-cognitiveservices-speech-sdk-cache", { supportBuffer: true, location: (typeof process !== "undefined" && !!process.env.SPEECH_OCSP_CACHE_ROOT) ? process.env.SPEECH_OCSP_CACHE_ROOT : undefined }); - } - } - // Test hook to force the disk cache to be recreated. - CertCheckAgent.forceReinitDiskCache = function () { - CertCheckAgent.privDiskCache = undefined; - CertCheckAgent.privMemCache = {}; - }; - CertCheckAgent.prototype.GetAgent = function (disableStapling) { - var agent = new agent_base_1.default.Agent(this.CreateConnection); - if (this.privProxyInfo !== undefined && - this.privProxyInfo.HostName !== undefined && - this.privProxyInfo.Port > 0) { - var proxyName = "privProxyInfo"; - agent[proxyName] = this.privProxyInfo; + get synthesizerConfig() { + return this.privSynthesizerConfig; + } + get synthesisContext() { + return this.privSynthesisContext; + } + get agentConfig() { + return this.privAgentConfig; + } + get connectionEvents() { + return this.privConnectionEvents; + } + get serviceEvents() { + return this.privServiceEvents; + } + set activityTemplate(messagePayload) { + this.privActivityTemplate = messagePayload; + } + get activityTemplate() { + return this.privActivityTemplate; + } + set audioOutputFormat(format) { + this.privAudioOutputFormat = format; + this.privSynthesisTurn.audioOutputFormat = format; + if (this.privSessionAudioDestination !== undefined) { + this.privSessionAudioDestination.format = format; } - return agent; - }; - CertCheckAgent.GetProxyAgent = function (proxyInfo) { - var httpProxyOptions = { - host: proxyInfo.HostName, - port: proxyInfo.Port, - }; - if (!!proxyInfo.UserName) { - httpProxyOptions.headers = { - "Proxy-Authentication": "Basic " + new Buffer(proxyInfo.UserName + ":" + (proxyInfo.Password === undefined) ? "" : proxyInfo.Password).toString("base64"), - }; + if (this.synthesisContext !== undefined) { + this.synthesisContext.audioOutputFormat = format; + } + } + isDisposed() { + return this.privIsDisposed; + } + async dispose(reason) { + this.privIsDisposed = true; + if (this.privSessionAudioDestination !== undefined) { + this.privSessionAudioDestination.close(); + } + if (this.privConnectionConfigurationPromise !== undefined) { + try { + const connection = await this.privConnectionConfigurationPromise; + await connection.dispose(reason); + } + catch { + // Connection was never successfully established, nothing to dispose + } + } + } + async connect() { + await this.connectImpl(); + } + async sendNetworkMessage(path, payload) { + const type = typeof payload === "string" ? Exports_js_1.MessageType.Text : Exports_js_1.MessageType.Binary; + const contentType = typeof payload === "string" ? "application/json" : ""; + const connection = await this.fetchConnection(); + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(type, path, this.privSynthesisTurn.requestId, contentType, payload)); + } + async Speak(text, isSSML, requestId, successCallback, errorCallBack, audioDestination) { + let ssml; + if (isSSML) { + ssml = text; } else { - httpProxyOptions.headers = {}; + ssml = this.privSynthesizer.buildSsml(text); } - httpProxyOptions.headers.requestOCSP = "true"; - var httpProxyAgent = new https_proxy_agent_1.default(httpProxyOptions); - return httpProxyAgent; - }; - CertCheckAgent.OCSPCheck = function (socketPromise, proxyInfo) { - return __awaiter(this, void 0, void 0, function () { - var ocspRequest, stapling, resolved, socket, tlsSocket; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - resolved = false; - return [4 /*yield*/, socketPromise]; - case 1: - socket = _a.sent(); - socket.cork(); - tlsSocket = socket; - return [2 /*return*/, new Promise(function (resolve, reject) { - socket.on("OCSPResponse", function (data) { - if (!!data) { - _this.onEvent(new Exports_1.OCSPStapleReceivedEvent()); - stapling = data; - } - }); - socket.on("error", function (error) { - if (!resolved) { - resolved = true; - socket.destroy(); - reject(error); - } - }); - tlsSocket.on("secure", function () { return __awaiter(_this, void 0, void 0, function () { - var peer, issuer, sig, cacheEntry, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - peer = tlsSocket.getPeerCertificate(true); - _a.label = 1; - case 1: - _a.trys.push([1, 6, , 7]); - return [4 /*yield*/, this.GetIssuer(peer)]; - case 2: - issuer = _a.sent(); - // We always need a request to verify the response. - ocspRequest = ocsp.request.generate(peer.raw, issuer.raw); - sig = ocspRequest.id.toString("hex"); - if (!!stapling) return [3 /*break*/, 4]; - return [4 /*yield*/, CertCheckAgent.GetResponseFromCache(sig, ocspRequest, proxyInfo)]; - case 3: - cacheEntry = _a.sent(); - stapling = cacheEntry; - _a.label = 4; - case 4: return [4 /*yield*/, this.VerifyOCSPResponse(stapling, ocspRequest, proxyInfo)]; - case 5: - _a.sent(); - socket.uncork(); - resolved = true; - resolve(socket); - return [3 /*break*/, 7]; - case 6: - e_1 = _a.sent(); - socket.destroy(); - resolved = true; - reject(e_1); - return [3 /*break*/, 7]; - case 7: return [2 /*return*/]; - } - }); - }); }); - })]; - } - }); - }); - }; - CertCheckAgent.GetIssuer = function (peer) { - if (peer.issuerCertificate) { - return Promise.resolve(peer.issuerCertificate); - } - return new Promise(function (resolve, reject) { - var ocspAgent = new ocsp.Agent({}); - ocspAgent.fetchIssuer(peer, null, function (error, value) { - if (!!error) { - reject(error); + if (this.speakOverride !== undefined) { + return this.speakOverride(ssml, requestId, successCallback, errorCallBack); + } + this.privSuccessCallback = successCallback; + this.privErrorCallback = errorCallBack; + this.privSynthesisTurn.startNewSynthesis(requestId, text, isSSML, audioDestination); + try { + const connection = await this.fetchConnection(); + await this.sendSynthesisContext(connection); + await this.sendSsmlMessage(connection, ssml, requestId); + this.onSynthesisStarted(requestId); + void this.receiveMessage(); + } + catch (e) { + this.cancelSynthesisLocal(Exports_js_2.CancellationReason.Error, Exports_js_2.CancellationErrorCode.ConnectionFailure, e); + return Promise.reject(e); + } + } + async stopSpeaking() { + const connection = await this.fetchConnection(); + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "synthesis.control", this.privSynthesisTurn.requestId, "application/json", JSON.stringify({ + action: "stop" + }))); + } + /** + * Performs text streaming synthesis using a SpeechSynthesisRequest. + * Text pieces are sent over WebSocket as they arrive via the request's input stream. + */ + async SpeakStream(request, requestId, successCallback, errorCallBack, audioDestination) { + this.privSuccessCallback = successCallback; + this.privErrorCallback = errorCallBack; + this.privSynthesisTurn.startNewSynthesis(requestId, "", false, audioDestination); + try { + const connection = await this.fetchConnection(); + // Send synthesis.context with streaming input section embedded + await this.sendStreamingSynthesisContext(connection, request, requestId); + this.onSynthesisStarted(requestId); + // Set up text piece callback - each piece is sent as a text.piece message + request.onTextPiece = (text) => { + this.sendTextPiece(connection, text, requestId).catch((e) => { + this.cancelSynthesisLocal(Exports_js_2.CancellationReason.Error, Exports_js_2.CancellationErrorCode.ConnectionFailure, e); + }); + }; + // Set up close callback - sends the finish signal + request.onClose = () => { + this.sendTextStreamEnd(connection, requestId).catch((e) => { + this.cancelSynthesisLocal(Exports_js_2.CancellationReason.Error, Exports_js_2.CancellationErrorCode.ConnectionFailure, e); + }); + }; + void this.receiveMessage(); + } + catch (e) { + this.cancelSynthesisLocal(Exports_js_2.CancellationReason.Error, Exports_js_2.CancellationErrorCode.ConnectionFailure, e); + return Promise.reject(e); + } + } + // Cancels synthesis. + cancelSynthesis(requestId, _cancellationReason, errorCode, error) { + const properties = new Exports_js_2.PropertyCollection(); + properties.setProperty(Exports_js_3.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[errorCode]); + const result = new Exports_js_2.SpeechSynthesisResult(requestId, Exports_js_2.ResultReason.Canceled, undefined, error, properties); + this.onSynthesisCancelled(result); + if (!!this.privSuccessCallback) { + try { + this.privSuccessCallback(result); + /* eslint-disable no-empty */ + } + catch { } + } + } + // Cancels synthesis. + cancelSynthesisLocal(cancellationReason, errorCode, error) { + if (!!this.privSynthesisTurn.isSynthesizing) { + this.privSynthesisTurn.onStopSynthesizing(); + this.cancelSynthesis(this.privSynthesisTurn.requestId, cancellationReason, errorCode, error); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + processTypeSpecificMessages(_connectionMessage) { + return true; + } + async receiveMessage() { + try { + const connection = await this.fetchConnection(); + const message = await connection.read(); + if (this.receiveMessageOverride !== undefined) { + return this.receiveMessageOverride(); + } + if (this.privIsDisposed) { + // We're done. + return; + } + // indicates we are draining the queue and it came with no message; + if (!message) { + if (!this.privSynthesisTurn.isSynthesizing) { return; } - resolve(value); - }); - }); - }; - CertCheckAgent.GetResponseFromCache = function (signature, ocspRequest, proxyInfo) { - return __awaiter(this, void 0, void 0, function () { - var cachedResponse, diskCacheResponse, error_1, cachedOcspResponse, tbsData, cachedStartTime, cachedNextTime, minUpdate; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - cachedResponse = CertCheckAgent.privMemCache[signature]; - if (!!cachedResponse) { - this.onEvent(new Exports_1.OCSPMemoryCacheHitEvent(signature)); - } - if (!!cachedResponse) return [3 /*break*/, 4]; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, CertCheckAgent.privDiskCache.get(signature)]; - case 2: - diskCacheResponse = _a.sent(); - if (!!diskCacheResponse.isCached) { - CertCheckAgent.onEvent(new Exports_1.OCSPDiskCacheHitEvent(signature)); - CertCheckAgent.StoreMemoryCacheEntry(signature, diskCacheResponse.value); - cachedResponse = diskCacheResponse.value; + else { + return this.receiveMessage(); + } + } + const connectionMessage = SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage.fromConnectionMessage(message); + if (connectionMessage.requestId.toLowerCase() === this.privSynthesisTurn.requestId.toLowerCase()) { + switch (connectionMessage.path.toLowerCase()) { + case "turn.start": + this.privSynthesisTurn.onServiceTurnStartResponse(connectionMessage.textBody); + break; + case "response": + this.privSynthesisTurn.onServiceResponseMessage(connectionMessage.textBody); + break; + case "audio": + if (this.privSynthesisTurn.streamId.toLowerCase() === connectionMessage.streamId.toLowerCase() + && !!connectionMessage.binaryBody) { + this.privSynthesisTurn.onAudioChunkReceived(connectionMessage.binaryBody); + this.onSynthesizing(connectionMessage.binaryBody); + if (this.privSessionAudioDestination !== undefined) { + this.privSessionAudioDestination.write(connectionMessage.binaryBody); + } } - return [3 /*break*/, 4]; - case 3: - error_1 = _a.sent(); - cachedResponse = null; - return [3 /*break*/, 4]; - case 4: - if (!cachedResponse) { - return [2 /*return*/, cachedResponse]; + break; + case "audio.metadata": + const metadataList = Exports_js_3.SynthesisAudioMetadata.fromJSON(connectionMessage.textBody).Metadata; + for (const metadata of metadataList) { + switch (metadata.Type) { + case Exports_js_3.MetadataType.WordBoundary: + case Exports_js_3.MetadataType.SentenceBoundary: + this.privSynthesisTurn.onTextBoundaryEvent(metadata); + const wordBoundaryEventArgs = new Exports_js_2.SpeechSynthesisWordBoundaryEventArgs(metadata.Data.Offset, metadata.Data.Duration, metadata.Data.text.Text, metadata.Data.text.Length, metadata.Type === Exports_js_3.MetadataType.WordBoundary + ? this.privSynthesisTurn.currentTextOffset : this.privSynthesisTurn.currentSentenceOffset, metadata.Data.text.BoundaryType); + this.onWordBoundary(wordBoundaryEventArgs); + break; + case Exports_js_3.MetadataType.Bookmark: + const bookmarkEventArgs = new Exports_js_2.SpeechSynthesisBookmarkEventArgs(metadata.Data.Offset, metadata.Data.Bookmark); + this.onBookmarkReached(bookmarkEventArgs); + break; + case Exports_js_3.MetadataType.Viseme: + this.privSynthesisTurn.onVisemeMetadataReceived(metadata); + if (metadata.Data.IsLastAnimation) { + const visemeEventArgs = new Exports_js_2.SpeechSynthesisVisemeEventArgs(metadata.Data.Offset, metadata.Data.VisemeId, this.privSynthesisTurn.getAndClearVisemeAnimation()); + this.onVisemeReceived(visemeEventArgs); + } + break; + case Exports_js_3.MetadataType.AvatarSignal: + this.onAvatarEvent(metadata); + break; + case Exports_js_3.MetadataType.SessionEnd: + this.privSynthesisTurn.onSessionEnd(metadata); + break; + } } + break; + case "turn.end": + this.privSynthesisTurn.onServiceTurnEndResponse(); + let result; try { - cachedOcspResponse = ocsp.utils.parseResponse(cachedResponse); - tbsData = cachedOcspResponse.value.tbsResponseData; - if (tbsData.responses.length < 1) { - this.onEvent(new Exports_1.OCSPCacheFetchErrorEvent(signature, "Not enough data in cached response")); - return [2 /*return*/]; - } - cachedStartTime = tbsData.responses[0].thisUpdate; - cachedNextTime = tbsData.responses[0].nextUpdate; - if (cachedNextTime < (Date.now() + this.testTimeOffset - 60000)) { - // Cached entry has expired. - this.onEvent(new Exports_1.OCSPCacheEntryExpiredEvent(signature, cachedNextTime)); - cachedResponse = null; - } - else { - minUpdate = Math.min(24 * 60 * 60 * 1000, (cachedNextTime - cachedStartTime) / 2); - if ((cachedNextTime - (Date.now() + this.testTimeOffset)) < minUpdate) { - this.onEvent(new Exports_1.OCSPCacheEntryNeedsRefreshEvent(signature, cachedStartTime, cachedNextTime)); - this.UpdateCache(ocspRequest, proxyInfo).catch(function (error) { - // Well, not much we can do here. - _this.onEvent(new OCSPEvents_1.OCSPCacheUpdateErrorEvent(signature, error.toString())); - }); - } - else { - this.onEvent(new Exports_1.OCSPCacheHitEvent(signature, cachedStartTime, cachedNextTime)); - } + result = await this.privSynthesisTurn.constructSynthesisResult(); + this.onSynthesisCompleted(result); + if (!!this.privSuccessCallback) { + this.privSuccessCallback(result); } } catch (error) { - this.onEvent(new Exports_1.OCSPCacheFetchErrorEvent(signature, error)); - cachedResponse = null; + if (!!this.privErrorCallback) { + this.privErrorCallback(error); + } } - if (!cachedResponse) { - this.onEvent(new Exports_1.OCSPCacheMissEvent(signature)); + break; + default: + if (!this.processTypeSpecificMessages(connectionMessage)) { + // here are some messages that the derived class has not processed, dispatch them to connect class + if (!!this.privServiceEvents) { + this.serviceEvents.onEvent(new Exports_js_1.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody)); + } } - return [2 /*return*/, cachedResponse]; - } - }); - }); - }; - CertCheckAgent.VerifyOCSPResponse = function (cacheValue, ocspRequest, proxyInfo) { - return __awaiter(this, void 0, void 0, function () { - var ocspResponse, sig; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - ocspResponse = cacheValue; - sig = ocspRequest.certID.toString("hex"); - if (!!ocspResponse) return [3 /*break*/, 2]; - return [4 /*yield*/, CertCheckAgent.GetOCSPResponse(ocspRequest, proxyInfo)]; - case 1: - ocspResponse = _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/, new Promise(function (resolve, reject) { - ocsp.verify({ request: ocspRequest, response: ocspResponse }, function (error, result) { - if (!!error) { - CertCheckAgent.onEvent(new Exports_1.OCSPVerificationFailedEvent(ocspRequest.id.toString("hex"), error)); - // Bad Cached Value? One more try without the cache. - if (!!cacheValue) { - _this.VerifyOCSPResponse(null, ocspRequest, proxyInfo).then(function () { - resolve(); - }, function (error) { - reject(error); - }); - } - else { - reject(error); - } - } - else { - if (!cacheValue) { - CertCheckAgent.StoreCacheEntry(ocspRequest.id.toString("hex"), ocspResponse); - } - resolve(); - } - }); - })]; - } - }); - }); - }; - CertCheckAgent.UpdateCache = function (req, proxyInfo) { - return __awaiter(this, void 0, void 0, function () { - var signature, rawResponse; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - signature = req.id.toString("hex"); - this.onEvent(new Exports_1.OCSPCacheUpdateNeededEvent(signature)); - return [4 /*yield*/, this.GetOCSPResponse(req, proxyInfo)]; - case 1: - rawResponse = _a.sent(); - this.StoreCacheEntry(signature, rawResponse); - this.onEvent(new Exports_1.OCSPCacheUpdateCompleteEvent(req.id.toString("hex"))); - return [2 /*return*/]; - } - }); - }); - }; - CertCheckAgent.StoreCacheEntry = function (sig, rawResponse) { - this.StoreMemoryCacheEntry(sig, rawResponse); - this.StoreDiskCacheEntry(sig, rawResponse); - }; - CertCheckAgent.StoreMemoryCacheEntry = function (sig, rawResponse) { - this.privMemCache[sig] = rawResponse; - this.onEvent(new Exports_1.OCSPMemoryCacheStoreEvent(sig)); - }; - CertCheckAgent.StoreDiskCacheEntry = function (sig, rawResponse) { - var _this = this; - this.privDiskCache.set(sig, rawResponse).then(function () { - _this.onEvent(new Exports_1.OCSPDiskCacheStoreEvent(sig)); - }); - }; - CertCheckAgent.GetOCSPResponse = function (req, proxyInfo) { - var _this = this; - var ocspMethod = "1.3.6.1.5.5.7.48.1"; - var options = {}; - if (!!proxyInfo) { - var agent = CertCheckAgent.GetProxyAgent(proxyInfo); - options.agent = agent; - } - return new Promise(function (resolve, reject) { - ocsp.utils.getAuthorityInfo(req.cert, ocspMethod, function (error, uri) { - if (error) { - reject(error); - return; } - var parsedUri = parse.default(uri); - parsedUri.path = parsedUri.pathname; - options = __assign(__assign({}, options), parsedUri); - ocsp.utils.getResponse(options, req.data, function (error, raw) { - if (error) { - reject(error); - return; - } - _this.onEvent(new Exports_1.OCSPResponseRetrievedEvent(req.certID.toString("hex"))); - resolve(raw); - }); - }); - }); - }; - CertCheckAgent.prototype.CreateConnection = function (request, options) { - var enableOCSP = (typeof process !== "undefined" && process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0" && process.env.SPEECH_CONDUCT_OCSP_CHECK !== "0") && options.secureEndpoint; - var socketPromise; - options = __assign(__assign({}, options), { - requestOCSP: !CertCheckAgent.forceDisableOCSPStapling, - servername: options.host - }); - if (!!this.privProxyInfo) { - var httpProxyAgent = CertCheckAgent.GetProxyAgent(this.privProxyInfo); - var baseAgent_1 = httpProxyAgent; - socketPromise = new Promise(function (resolve, reject) { - baseAgent_1.callback(request, options, function (error, socket) { - if (!!error) { - reject(error); - } - else { - resolve(socket); - } - }); - }); - } - else { - if (!!options.secureEndpoint) { - socketPromise = Promise.resolve(tls.connect(options)); } - else { - socketPromise = Promise.resolve(net.connect(options)); - } - } - if (!!enableOCSP) { - return CertCheckAgent.OCSPCheck(socketPromise, this.privProxyInfo); - } - else { - return socketPromise; - } - }; - // Test hook to enable forcing expiration / refresh to happen. - CertCheckAgent.testTimeOffset = 0; - // Test hook to disable stapling for cache testing. - CertCheckAgent.forceDisableOCSPStapling = false; - // An in memory cache for recived responses. - CertCheckAgent.privMemCache = {}; - CertCheckAgent.onEvent = function (event) { - Exports_1.Events.instance.onEvent(event); - }; - return CertCheckAgent; -}()); -exports.CertCheckAgent = CertCheckAgent; - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(239), __webpack_require__(67).Buffer)) - -/***/ }), -/* 239 */ -/***/ (function(module, exports) { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; + return this.receiveMessage(); } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); + catch (e) { + // TODO: What goes here? } } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); + sendSynthesisContext(connection) { + this.setSynthesisContextSynthesisSection(); + const synthesisContextJson = this.synthesisContext.toJSON(); + if (synthesisContextJson) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "synthesis.context", this.privSynthesisTurn.requestId, "application/json", synthesisContextJson)); } + return; } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { + setSpeechConfigSynthesisSection() { return; } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; + connectImpl(isUnAuthorized = false) { + if (this.privConnectionPromise != null) { + return this.privConnectionPromise.then((connection) => { + if (connection.state() === Exports_js_1.ConnectionState.Disconnected) { + this.privConnectionId = null; + this.privConnectionPromise = null; + return this.connectImpl(); + } + return this.privConnectionPromise; + }, () => { + this.privConnectionId = null; + this.privConnectionPromise = null; + return this.connectImpl(); + }); + } + this.privAuthFetchEventId = (0, Exports_js_1.createNoDashGuid)(); + this.privConnectionId = (0, Exports_js_1.createNoDashGuid)(); + this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId); + const authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId); + this.privConnectionPromise = authPromise.then(async (result) => { + this.privSynthesisTurn.onAuthCompleted(false); + const connection = await this.privConnectionFactory.create(this.privSynthesizerConfig, result, this.privConnectionId); + // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away, + // it'll stop sending events. + connection.events.attach((event) => { + this.connectionEvents.onEvent(event); + }); + const response = await connection.open(); + if (response.statusCode === 200) { + this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode); + return Promise.resolve(connection); + } + else if (response.statusCode === 403 && !isUnAuthorized) { + return this.connectImpl(true); + } + else { + this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode); + return Promise.reject(`Unable to contact server. StatusCode: ${response.statusCode}, + ${this.privSynthesizerConfig.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url)} Reason: ${response.reason}`); + } + }, (error) => { + this.privSynthesisTurn.onAuthCompleted(true); + throw new Error(error); + }); + // Attach an empty handler to allow the promise to run in the background while + // other startup events happen. It'll eventually be awaited on. + // eslint-disable-next-line @typescript-eslint/no-empty-function + this.privConnectionPromise.catch(() => { }); + return this.privConnectionPromise; } - if (queue.length) { - drainQueue(); + sendSpeechServiceConfig(connection, SpeechServiceConfigJson) { + if (SpeechServiceConfigJson) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "speech.config", this.privSynthesisTurn.requestId, "application/json", SpeechServiceConfigJson)); + } } -} - -function drainQueue() { - if (draining) { - return; + sendSsmlMessage(connection, ssml, requestId) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "ssml", requestId, "application/ssml+xml", ssml)); } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } + /** + * Sends the synthesis.context message for text streaming mode. + * Includes the standard audio/language sections plus an input section + * with bidirectionalStreamingMode, voice name, and per-request properties. + */ + async sendStreamingSynthesisContext(connection, request, requestId) { + // Build the standard synthesis context first + this.setSynthesisContextSynthesisSection(); + // Build the streaming input section + const inputSection = { + bidirectionalStreamingMode: true, + }; + // Add voice name and language from synthesizer properties + const voiceName = this.privSynthesizerConfig.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice, ""); + const language = this.privSynthesizerConfig.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage, "en-US"); + if (voiceName) { + inputSection.voiceName = voiceName; + } + inputSection.language = language; + // Add per-request voice properties + const pitch = request.properties.getProperty(Exports_js_2.PropertyId.SpeechSynthesisRequest_Pitch, undefined); + const rate = request.properties.getProperty(Exports_js_2.PropertyId.SpeechSynthesisRequest_Rate, undefined); + const volume = request.properties.getProperty(Exports_js_2.PropertyId.SpeechSynthesisRequest_Volume, undefined); + const style = request.properties.getProperty(Exports_js_2.PropertyId.SpeechSynthesisRequest_Style, undefined); + const temperature = request.properties.getProperty(Exports_js_2.PropertyId.SpeechSynthesisRequest_Temperature, undefined); + const customLexiconUrl = request.properties.getProperty(Exports_js_2.PropertyId.SpeechSynthesisRequest_CustomLexiconUrl, undefined); + const preferLocales = request.properties.getProperty(Exports_js_2.PropertyId.SpeechSynthesisRequest_PreferLocales, undefined); + if (pitch !== undefined) { + inputSection.pitch = pitch; + } + if (rate !== undefined) { + inputSection.rate = rate; + } + if (volume !== undefined) { + inputSection.volume = volume; + } + if (style !== undefined) { + inputSection.style = style; + } + if (temperature !== undefined) { + inputSection.temperature = temperature; + } + if (customLexiconUrl !== undefined) { + inputSection.customLexiconUrl = customLexiconUrl; + } + if (preferLocales !== undefined) { + inputSection.preferLocales = preferLocales; + } + // Add the input section to the synthesis context + const existingSynthesis = this.privSynthesisContext.getSection("synthesis") ?? {}; + this.privSynthesisContext.setSection("synthesis", { + ...existingSynthesis, + input: inputSection, + }); + const synthesisContextJson = this.privSynthesisContext.toJSON(); + if (synthesisContextJson) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "synthesis.context", requestId, "application/json", synthesisContextJson)); } - queueIndex = -1; - len = queue.length; } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } + /** + * Sends a text piece for streaming synthesis. + * Path: text.piece, Content-Type: text/plain, Body: raw text + */ + async sendTextPiece(connection, text, requestId) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "text.piece", requestId, "text/plain", text)); } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + /** + * Sends the end-of-stream signal for text streaming synthesis. + * Path: text.end, Content-Type: text/plain, Body: empty + */ + async sendTextStreamEnd(connection, requestId) { + return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "text.end", requestId, "text/plain", "")); } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - -/***/ }), -/* 240 */ -/***/ (function(module, exports) { - -/* (ignored) */ - -/***/ }), -/* 241 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) { - -var required = __webpack_require__(242) - , qs = __webpack_require__(243) - , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\// - , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i - , windowsDriveLetter = /^[a-zA-Z]:/ - , whitespace = '[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]' - , left = new RegExp('^'+ whitespace +'+'); - -/** - * Trim a given string. - * - * @param {String} str String to trim. - * @public - */ -function trimLeft(str) { - return (str ? str : '').toString().replace(left, ''); -} - -/** - * These are the parse rules for the URL parser, it informs the parser - * about: - * - * 0. The char it Needs to parse, if it's a string it should be done using - * indexOf, RegExp using exec and NaN means set as current value. - * 1. The property we should set when parsing this value. - * 2. Indication if it's backwards or forward parsing, when set as number it's - * the value of extra chars that should be split off. - * 3. Inherit from location if non existing in the parser. - * 4. `toLowerCase` the resulting value. - */ -var rules = [ - ['#', 'hash'], // Extract from the back. - ['?', 'query'], // Extract from the back. - function sanitize(address, url) { // Sanitize what is left of the address - return isSpecial(url.protocol) ? address.replace(/\\/g, '/') : address; - }, - ['/', 'pathname'], // Extract from the back. - ['@', 'auth', 1], // Extract from the front. - [NaN, 'host', undefined, 1, 1], // Set left over value. - [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. - [NaN, 'hostname', undefined, 1, 1] // Set left over. -]; - -/** - * These properties should not be copied or inherited from. This is only needed - * for all non blob URL's as a blob URL does not include a hash, only the - * origin. - * - * @type {Object} - * @private - */ -var ignore = { hash: 1, query: 1 }; - -/** - * The location object differs when your code is loaded through a normal page, - * Worker or through a worker using a blob. And with the blobble begins the - * trouble as the location object will contain the URL of the blob, not the - * location of the page where our code is loaded in. The actual origin is - * encoded in the `pathname` so we can thankfully generate a good "default" - * location from it so we can generate proper relative URL's again. - * - * @param {Object|String} loc Optional default location object. - * @returns {Object} lolcation object. - * @public - */ -function lolcation(loc) { - var globalVar; - - if (typeof window !== 'undefined') globalVar = window; - else if (typeof global !== 'undefined') globalVar = global; - else if (typeof self !== 'undefined') globalVar = self; - else globalVar = {}; - - var location = globalVar.location || {}; - loc = loc || location; - - var finaldestination = {} - , type = typeof loc - , key; - - if ('blob:' === loc.protocol) { - finaldestination = new Url(unescape(loc.pathname), {}); - } else if ('string' === type) { - finaldestination = new Url(loc, {}); - for (key in ignore) delete finaldestination[key]; - } else if ('object' === type) { - for (key in loc) { - if (key in ignore) continue; - finaldestination[key] = loc[key]; + async fetchConnection() { + if (this.privConnectionConfigurationPromise !== undefined) { + return this.privConnectionConfigurationPromise.then((connection) => { + if (connection.state() === Exports_js_1.ConnectionState.Disconnected) { + this.privConnectionId = null; + this.privConnectionConfigurationPromise = undefined; + return this.fetchConnection(); + } + return this.privConnectionConfigurationPromise; + }, () => { + this.privConnectionId = null; + this.privConnectionConfigurationPromise = undefined; + return this.fetchConnection(); + }); + } + this.privConnectionConfigurationPromise = this.configureConnection(); + return await this.privConnectionConfigurationPromise; } - - if (finaldestination.slashes === undefined) { - finaldestination.slashes = slashes.test(loc.href); + // Takes an established websocket connection to the endpoint and sends speech configuration information. + async configureConnection() { + const connection = await this.connectImpl(); + if (this.configConnectionOverride !== undefined) { + return this.configConnectionOverride(connection); + } + this.setSpeechConfigSynthesisSection(); + await this.sendSpeechServiceConfig(connection, this.privSynthesizerConfig.SpeechServiceConfig.serialize()); + return connection; } - } - - return finaldestination; -} - -/** - * Check whether a protocol scheme is special. - * - * @param {String} The protocol scheme of the URL - * @return {Boolean} `true` if the protocol scheme is special, else `false` - * @private - */ -function isSpecial(scheme) { - return ( - scheme === 'file:' || - scheme === 'ftp:' || - scheme === 'http:' || - scheme === 'https:' || - scheme === 'ws:' || - scheme === 'wss:' - ); -} - -/** - * @typedef ProtocolExtract - * @type Object - * @property {String} protocol Protocol matched in the URL, in lowercase. - * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. - * @property {String} rest Rest of the URL that is not part of the protocol. - */ - -/** - * Extract protocol information from a URL with/without double slash ("//"). - * - * @param {String} address URL we want to extract from. - * @param {Object} location - * @return {ProtocolExtract} Extracted information. - * @private - */ -function extractProtocol(address, location) { - address = trimLeft(address); - location = location || {}; - - var match = protocolre.exec(address); - var protocol = match[1] ? match[1].toLowerCase() : ''; - var forwardSlashes = !!match[2]; - var otherSlashes = !!match[3]; - var slashesCount = 0; - var rest; - - if (forwardSlashes) { - if (otherSlashes) { - rest = match[2] + match[3] + match[4]; - slashesCount = match[2].length + match[3].length; - } else { - rest = match[2] + match[4]; - slashesCount = match[2].length; + onAvatarEvent(_metadata) { + return; } - } else { - if (otherSlashes) { - rest = match[3] + match[4]; - slashesCount = match[3].length; - } else { - rest = match[4] + onSynthesisStarted(_requestId) { + return; } - } - - if (protocol === 'file:') { - if (slashesCount >= 2) { - rest = rest.slice(2); + onSynthesizing(_audio) { + return; } - } else if (isSpecial(protocol)) { - rest = match[4]; - } else if (protocol) { - if (forwardSlashes) { - rest = rest.slice(2); + onSynthesisCancelled(_result) { + return; } - } else if (slashesCount >= 2 && isSpecial(location.protocol)) { - rest = match[4]; - } - - return { - protocol: protocol, - slashes: forwardSlashes || isSpecial(protocol), - slashesCount: slashesCount, - rest: rest - }; -} - -/** - * Resolve a relative URL pathname against a base URL pathname. - * - * @param {String} relative Pathname of the relative URL. - * @param {String} base Pathname of the base URL. - * @return {String} Resolved pathname. - * @private - */ -function resolve(relative, base) { - if (relative === '') return base; - - var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) - , i = path.length - , last = path[i - 1] - , unshift = false - , up = 0; - - while (i--) { - if (path[i] === '.') { - path.splice(i, 1); - } else if (path[i] === '..') { - path.splice(i, 1); - up++; - } else if (up) { - if (i === 0) unshift = true; - path.splice(i, 1); - up--; + onSynthesisCompleted(_result) { + return; } - } - - if (unshift) path.unshift(''); - if (last === '.' || last === '..') path.push(''); - - return path.join('/'); -} - -/** - * The actual URL instance. Instead of returning an object we've opted-in to - * create an actual constructor as it's much more memory efficient and - * faster and it pleases my OCD. - * - * It is worth noting that we should not use `URL` as class name to prevent - * clashes with the global URL instance that got introduced in browsers. - * - * @constructor - * @param {String} address URL we want to parse. - * @param {Object|String} [location] Location defaults for relative paths. - * @param {Boolean|Function} [parser] Parser for the query string. - * @private - */ -function Url(address, location, parser) { - address = trimLeft(address); - - if (!(this instanceof Url)) { - return new Url(address, location, parser); - } - - var relative, extracted, parse, instruction, index, key - , instructions = rules.slice() - , type = typeof location - , url = this - , i = 0; - - // - // The following if statements allows this module two have compatibility with - // 2 different API: - // - // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments - // where the boolean indicates that the query string should also be parsed. - // - // 2. The `URL` interface of the browser which accepts a URL, object as - // arguments. The supplied object will be used as default values / fall-back - // for relative paths. - // - if ('object' !== type && 'string' !== type) { - parser = location; - location = null; - } - - if (parser && 'function' !== typeof parser) parser = qs.parse; - - location = lolcation(location); - - // - // Extract protocol information before running the instructions. - // - extracted = extractProtocol(address || '', location); - relative = !extracted.protocol && !extracted.slashes; - url.slashes = extracted.slashes || relative && location.slashes; - url.protocol = extracted.protocol || location.protocol || ''; - address = extracted.rest; - - // - // When the authority component is absent the URL starts with a path - // component. - // - if ( - extracted.protocol === 'file:' && ( - extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) || - (!extracted.slashes && - (extracted.protocol || - extracted.slashesCount < 2 || - !isSpecial(url.protocol))) - ) { - instructions[3] = [/(.*)/, 'pathname']; - } - - for (; i < instructions.length; i++) { - instruction = instructions[i]; - - if (typeof instruction === 'function') { - address = instruction(address, url); - continue; + onWordBoundary(_wordBoundaryEventArgs) { + return; } - - parse = instruction[0]; - key = instruction[1]; - - if (parse !== parse) { - url[key] = address; - } else if ('string' === typeof parse) { - if (~(index = address.indexOf(parse))) { - if ('number' === typeof instruction[2]) { - url[key] = address.slice(0, index); - address = address.slice(index + instruction[2]); - } else { - url[key] = address.slice(index); - address = address.slice(0, index); - } - } - } else if ((index = parse.exec(address))) { - url[key] = index[1]; - address = address.slice(0, index.index); + onVisemeReceived(_visemeEventArgs) { + return; } - - url[key] = url[key] || ( - relative && instruction[3] ? location[key] || '' : '' - ); - - // - // Hostname, host and protocol should be lowercased so they can be used to - // create a proper `origin`. - // - if (instruction[4]) url[key] = url[key].toLowerCase(); - } - - // - // Also parse the supplied query string in to an object. If we're supplied - // with a custom parser as function use that instead of the default build-in - // parser. - // - if (parser) url.query = parser(url.query); - - // - // If the URL is relative, resolve the pathname against the base URL. - // - if ( - relative - && location.slashes - && url.pathname.charAt(0) !== '/' - && (url.pathname !== '' || location.pathname !== '') - ) { - url.pathname = resolve(url.pathname, location.pathname); - } - - // - // Default to a / for pathname if none exists. This normalizes the URL - // to always have a / - // - if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) { - url.pathname = '/' + url.pathname; - } - - // - // We should not add port numbers if they are already the default port number - // for a given protocol. As the host also contains the port number we're going - // override it with the hostname which contains no port number. - // - if (!required(url.port, url.protocol)) { - url.host = url.hostname; - url.port = ''; - } - - // - // Parse down the `auth` for the username and password. - // - url.username = url.password = ''; - if (url.auth) { - instruction = url.auth.split(':'); - url.username = instruction[0] || ''; - url.password = instruction[1] || ''; - } - - url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host - ? url.protocol +'//'+ url.host - : 'null'; - - // - // The href is just the compiled result. - // - url.href = url.toString(); -} - -/** - * This is convenience method for changing properties in the URL instance to - * insure that they all propagate correctly. - * - * @param {String} part Property we need to adjust. - * @param {Mixed} value The newly assigned value. - * @param {Boolean|Function} fn When setting the query, it will be the function - * used to parse the query. - * When setting the protocol, double slash will be - * removed from the final url if it is true. - * @returns {URL} URL instance for chaining. - * @public - */ -function set(part, value, fn) { - var url = this; - - switch (part) { - case 'query': - if ('string' === typeof value && value.length) { - value = (fn || qs.parse)(value); - } - - url[part] = value; - break; - - case 'port': - url[part] = value; - - if (!required(value, url.protocol)) { - url.host = url.hostname; - url[part] = ''; - } else if (value) { - url.host = url.hostname +':'+ value; - } - - break; - - case 'hostname': - url[part] = value; - - if (url.port) value += ':'+ url.port; - url.host = value; - break; - - case 'host': - url[part] = value; - - if (/:\d+$/.test(value)) { - value = value.split(':'); - url.port = value.pop(); - url.hostname = value.join(':'); - } else { - url.hostname = value; - url.port = ''; - } - - break; - - case 'protocol': - url.protocol = value.toLowerCase(); - url.slashes = !fn; - break; - - case 'pathname': - case 'hash': - if (value) { - var char = part === 'pathname' ? '/' : '#'; - url[part] = value.charAt(0) !== char ? char + value : value; - } else { - url[part] = value; - } - break; - - default: - url[part] = value; - } - - for (var i = 0; i < rules.length; i++) { - var ins = rules[i]; - - if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); - } - - url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host - ? url.protocol +'//'+ url.host - : 'null'; - - url.href = url.toString(); - - return url; -} - -/** - * Transform the properties back in to a valid and full URL string. - * - * @param {Function} stringify Optional query stringify function. - * @returns {String} Compiled version of the URL. - * @public - */ -function toString(stringify) { - if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; - - var query - , url = this - , protocol = url.protocol; - - if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; - - var result = protocol + (url.slashes || isSpecial(url.protocol) ? '//' : ''); - - if (url.username) { - result += url.username; - if (url.password) result += ':'+ url.password; - result += '@'; - } - - result += url.host + url.pathname; - - query = 'object' === typeof url.query ? stringify(url.query) : url.query; - if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; - - if (url.hash) result += url.hash; - - return result; -} - -Url.prototype = { set: set, toString: toString }; - -// -// Expose the URL parser and some additional properties that might be useful for -// others or testing. -// -Url.extractProtocol = extractProtocol; -Url.location = lolcation; -Url.trimLeft = trimLeft; -Url.qs = qs; - -module.exports = Url; - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(68))) - -/***/ }), -/* 242 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/** - * Check if we're required to add a port number. - * - * @see https://url.spec.whatwg.org/#default-port - * @param {Number|String} port Port number we need to check - * @param {String} protocol Protocol we need to check against. - * @returns {Boolean} Is it a default port for the given protocol - * @api private - */ -module.exports = function required(port, protocol) { - protocol = protocol.split(':')[0]; - port = +port; - - if (!port) return false; - - switch (protocol) { - case 'http': - case 'ws': - return port !== 80; - - case 'https': - case 'wss': - return port !== 443; - - case 'ftp': - return port !== 21; - - case 'gopher': - return port !== 70; - - case 'file': - return false; - } - - return port !== 0; -}; - - -/***/ }), -/* 243 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var has = Object.prototype.hasOwnProperty - , undef; - -/** - * Decode a URI encoded string. - * - * @param {String} input The URI encoded string. - * @returns {String|Null} The decoded string. - * @api private - */ -function decode(input) { - try { - return decodeURIComponent(input.replace(/\+/g, ' ')); - } catch (e) { - return null; - } -} - -/** - * Attempts to encode a given input. - * - * @param {String} input The string that needs to be encoded. - * @returns {String|Null} The encoded string. - * @api private - */ -function encode(input) { - try { - return encodeURIComponent(input); - } catch (e) { - return null; - } -} - -/** - * Simple query string parser. - * - * @param {String} query The query string that needs to be parsed. - * @returns {Object} - * @api public - */ -function querystring(query) { - var parser = /([^=?#&]+)=?([^&]*)/g - , result = {} - , part; - - while (part = parser.exec(query)) { - var key = decode(part[1]) - , value = decode(part[2]); - - // - // Prevent overriding of existing properties. This ensures that build-in - // methods like `toString` or __proto__ are not overriden by malicious - // querystrings. - // - // In the case if failed decoding, we want to omit the key/value pairs - // from the result. - // - if (key === null || value === null || key in result) continue; - result[key] = value; - } - - return result; -} - -/** - * Transform a query string to an object. - * - * @param {Object} obj Object that should be transformed. - * @param {String} prefix Optional prefix. - * @returns {String} - * @api public - */ -function querystringify(obj, prefix) { - prefix = prefix || ''; - - var pairs = [] - , value - , key; - - // - // Optionally prefix with a '?' if needed - // - if ('string' !== typeof prefix) prefix = '?'; - - for (key in obj) { - if (has.call(obj, key)) { - value = obj[key]; - - // - // Edge cases where we actually want to encode the value to an empty - // string instead of the stringified value. - // - if (!value && (value === null || value === undef || isNaN(value))) { - value = ''; - } - - key = encode(key); - value = encode(value); - - // - // If we failed to encode the strings, we should bail out as we don't - // want to add invalid strings to the query. - // - if (key === null || value === null) continue; - pairs.push(key +'='+ value); + onBookmarkReached(_bookmarkEventArgs) { + return; } - } - - return pairs.length ? prefix + pairs.join('&') : ''; } +exports.SynthesisAdapterBase = SynthesisAdapterBase; +SynthesisAdapterBase.telemetryDataEnabled = true; -// -// Expose the module. -// -exports.stringify = querystringify; -exports.parse = querystring; - - -/***/ }), -/* 244 */ -/***/ (function(module, exports) { - -/* (ignored) */ - -/***/ }), -/* 245 */ -/***/ (function(module, exports) { -/* (ignored) */ /***/ }), -/* 246 */ -/***/ (function(module, exports) { - -/* (ignored) */ +/* 248 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -/***/ }), -/* 247 */ -/***/ (function(module, exports) { +"use strict"; -/* (ignored) */ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AvatarSynthesisAdapter = void 0; +const Exports_js_1 = __webpack_require__(85); +const Exports_js_2 = __webpack_require__(2); +class AvatarSynthesisAdapter extends Exports_js_2.SynthesisAdapterBase { + constructor(authentication, connectionFactory, synthesizerConfig, avatarSynthesizer, avatarConfig) { + super(authentication, connectionFactory, synthesizerConfig, undefined); + this.privAvatarSynthesizer = avatarSynthesizer; + this.privSynthesizer = avatarSynthesizer; + this.privAvatarConfig = avatarConfig; + } + setSynthesisContextSynthesisSection() { + this.privSynthesisContext.setSynthesisSection(undefined); + } + setSpeechConfigSynthesisSection() { + const talkingAvatarConfig = { + background: { + color: this.privAvatarConfig.backgroundColor, + image: { + url: this.privAvatarConfig.backgroundImage?.toString(), + } + }, + character: this.privAvatarConfig.character, + customized: this.privAvatarConfig.customized, + photoAvatarBaseModel: this.privAvatarConfig.photoAvatarBaseModel, + style: this.privAvatarConfig.style, + useBuiltInVoice: this.privAvatarConfig.useBuiltInVoice, + }; + // Add scene configuration if provided + if (this.privAvatarConfig.scene) { + talkingAvatarConfig.scene = { + amplitude: this.privAvatarConfig.scene.amplitude, + positionX: this.privAvatarConfig.scene.positionX, + positionY: this.privAvatarConfig.scene.positionY, + rotationX: this.privAvatarConfig.scene.rotationX, + rotationY: this.privAvatarConfig.scene.rotationY, + rotationZ: this.privAvatarConfig.scene.rotationZ, + zoom: this.privAvatarConfig.scene.zoom, + }; + } + this.privSynthesizerConfig.synthesisVideoSection = { + format: { + bitrate: this.privAvatarConfig.videoFormat?.bitrate, + codec: this.privAvatarConfig.videoFormat?.codec, + crop: { + bottomRight: { + x: this.privAvatarConfig.videoFormat?.cropRange?.bottomRight?.x, + y: this.privAvatarConfig.videoFormat?.cropRange?.bottomRight?.y, + }, + topLeft: { + x: this.privAvatarConfig.videoFormat?.cropRange?.topLeft?.x, + y: this.privAvatarConfig.videoFormat?.cropRange?.topLeft?.y, + }, + }, + resolution: { + height: this.privAvatarConfig.videoFormat?.height, + width: this.privAvatarConfig.videoFormat?.width, + }, + }, + protocol: { + name: "WebRTC", + webrtcConfig: { + clientDescription: btoa(this.privSynthesizerConfig.parameters.getProperty(Exports_js_1.PropertyId.TalkingAvatarService_WebRTC_SDP)), + iceServers: this.privAvatarConfig.remoteIceServers ?? this.privAvatarSynthesizer.iceServers, + }, + }, + talkingAvatar: talkingAvatarConfig, + }; + } + onAvatarEvent(metadata) { + if (!!this.privAvatarSynthesizer.avatarEventReceived) { + const avatarEventArgs = new Exports_js_1.AvatarEventArgs(metadata.Data.Offset, metadata.Data.Name); + try { + this.privAvatarSynthesizer.avatarEventReceived(this.privAvatarSynthesizer, avatarEventArgs); + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } + } + } +} +exports.AvatarSynthesisAdapter = AvatarSynthesisAdapter; -/***/ }), -/* 248 */ -/***/ (function(module, exports) { -/* (ignored) */ /***/ }), /* 249 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ReplayableAudioNode = void 0; -var ReplayableAudioNode = /** @class */ (function () { - function ReplayableAudioNode(audioSource, bytesPerSecond) { - var _this = this; - this.privBuffers = []; - this.privReplayOffset = 0; - this.privLastShrinkOffset = 0; - this.privBufferStartOffset = 0; - this.privBufferSerial = 0; - this.privBufferedBytes = 0; - this.privReplay = false; - this.privLastChunkAcquiredTime = 0; - this.id = function () { - return _this.privAudioNode.id(); - }; - this.privAudioNode = audioSource; - this.privBytesPerSecond = bytesPerSecond; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpeechSynthesisAdapter = void 0; +const Exports_js_1 = __webpack_require__(85); +const Exports_js_2 = __webpack_require__(2); +class SpeechSynthesisAdapter extends Exports_js_2.SynthesisAdapterBase { + constructor(authentication, connectionFactory, synthesizerConfig, speechSynthesizer, audioDestination) { + super(authentication, connectionFactory, synthesizerConfig, audioDestination); + this.privSpeechSynthesizer = speechSynthesizer; + this.privSynthesizer = speechSynthesizer; } - // Reads and returns the next chunk of audio buffer. - // If replay of existing buffers are needed, read() will first seek and replay - // existing content, and upoin completion it will read new content from the underlying - // audio node, saving that content into the replayable buffers. - ReplayableAudioNode.prototype.read = function () { - var _this = this; - // if there is a replay request to honor. - if (!!this.privReplay && this.privBuffers.length !== 0) { - // Find the start point in the buffers. - // Offsets are in 100ns increments. - // So how many bytes do we need to seek to get the right offset? - var offsetToSeek = this.privReplayOffset - this.privBufferStartOffset; - var bytesToSeek = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7); - if (0 !== (bytesToSeek % 2)) { - bytesToSeek++; - } - var i = 0; - while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) { - bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength; + setSynthesisContextSynthesisSection() { + this.privSynthesisContext.setSynthesisSection(this.privSpeechSynthesizer); + } + onSynthesisStarted(requestId) { + const synthesisStartEventArgs = new Exports_js_1.SpeechSynthesisEventArgs(new Exports_js_1.SpeechSynthesisResult(requestId, Exports_js_1.ResultReason.SynthesizingAudioStarted)); + if (!!this.privSpeechSynthesizer.synthesisStarted) { + this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer, synthesisStartEventArgs); + } + } + onSynthesizing(audio) { + if (!!this.privSpeechSynthesizer.synthesizing) { + try { + const audioWithHeader = this.privSynthesisTurn.audioOutputFormat.addHeader(audio); + const ev = new Exports_js_1.SpeechSynthesisEventArgs(new Exports_js_1.SpeechSynthesisResult(this.privSynthesisTurn.requestId, Exports_js_1.ResultReason.SynthesizingAudio, audioWithHeader)); + this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer, ev); } - if (i < this.privBuffers.length) { - var retVal = this.privBuffers[i].chunk.buffer.slice(bytesToSeek); - this.privReplayOffset += (retVal.byteLength / this.privBytesPerSecond) * 1e+7; - // If we've reached the end of the buffers, stop replaying. - if (i === this.privBuffers.length - 1) { - this.privReplay = false; - } - return Promise.resolve({ - buffer: retVal, - isEnd: false, - timeReceived: this.privBuffers[i].chunk.timeReceived, - }); + catch (error) { + // Not going to let errors in the event handler + // trip things up. } } - return this.privAudioNode.read() - .then(function (result) { - if (result && result.buffer) { - _this.privBuffers.push(new BufferEntry(result, _this.privBufferSerial++, _this.privBufferedBytes)); - _this.privBufferedBytes += result.buffer.byteLength; + } + onSynthesisCancelled(result) { + if (!!this.privSpeechSynthesizer.SynthesisCanceled) { + const cancelEvent = new Exports_js_1.SpeechSynthesisEventArgs(result); + try { + this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer, cancelEvent); + /* eslint-disable no-empty */ } - return result; - }); - }; - ReplayableAudioNode.prototype.detach = function () { - this.privBuffers = undefined; - return this.privAudioNode.detach(); - }; - ReplayableAudioNode.prototype.replay = function () { - if (this.privBuffers && 0 !== this.privBuffers.length) { - this.privReplay = true; - this.privReplayOffset = this.privLastShrinkOffset; + catch { } } - }; - // Shrinks the existing audio buffers to start at the new offset, or at the - // beginning of the buffer closest to the requested offset. - // A replay request will start from the last shrink point. - ReplayableAudioNode.prototype.shrinkBuffers = function (offset) { - if (this.privBuffers === undefined || this.privBuffers.length === 0) { - return; + } + onSynthesisCompleted(result) { + if (this.privSpeechSynthesizer.synthesisCompleted) { + try { + this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer, new Exports_js_1.SpeechSynthesisEventArgs(result)); + } + catch (e) { + // Not going to let errors in the event handler + // trip things up. + } } - this.privLastShrinkOffset = offset; - // Find the start point in the buffers. - // Offsets are in 100ns increments. - // So how many bytes do we need to seek to get the right offset? - var offsetToSeek = offset - this.privBufferStartOffset; - var bytesToSeek = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7); - var i = 0; - while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) { - bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength; + } + onWordBoundary(wordBoundaryEventArgs) { + if (!!this.privSpeechSynthesizer.wordBoundary) { + try { + this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer, wordBoundaryEventArgs); + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - this.privBufferStartOffset = Math.round(offset - ((bytesToSeek / this.privBytesPerSecond) * 1e+7)); - this.privBuffers = this.privBuffers.slice(i); - }; - // Finds the time a buffer of audio was first seen by offset. - ReplayableAudioNode.prototype.findTimeAtOffset = function (offset) { - if (offset < this.privBufferStartOffset || this.privBuffers === undefined) { - return 0; + } + onVisemeReceived(visemeEventArgs) { + if (!!this.privSpeechSynthesizer.visemeReceived) { + try { + this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer, visemeEventArgs); + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. + } } - for (var _i = 0, _a = this.privBuffers; _i < _a.length; _i++) { - var value = _a[_i]; - var startOffset = (value.byteOffset / this.privBytesPerSecond) * 1e7; - var endOffset = startOffset + ((value.chunk.buffer.byteLength / this.privBytesPerSecond) * 1e7); - if (offset >= startOffset && offset <= endOffset) { - return value.chunk.timeReceived; + } + onBookmarkReached(bookmarkEventArgs) { + if (!!this.privSpeechSynthesizer.bookmarkReached) { + try { + this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer, bookmarkEventArgs); + } + catch (error) { + // Not going to let errors in the event handler + // trip things up. } } - return 0; - }; - return ReplayableAudioNode; -}()); -exports.ReplayableAudioNode = ReplayableAudioNode; -// Primary use of this class is to help debugging problems with the replay -// code. If the memory cost of alloc / dealloc gets too much, drop it and just use -// the ArrayBuffer directly. -// tslint:disable-next-line:max-classes-per-file -var BufferEntry = /** @class */ (function () { - function BufferEntry(chunk, serial, byteOffset) { - this.chunk = chunk; - this.serial = serial; - this.byteOffset = byteOffset; } - return BufferEntry; -}()); +} +exports.SpeechSynthesisAdapter = SpeechSynthesisAdapter; /***/ }), /* 250 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProxyInfo = void 0; -var Exports_1 = __webpack_require__(61); -var ProxyInfo = /** @class */ (function () { - function ProxyInfo(proxyHostName, proxyPort, proxyUserName, proxyPassword) { - this.privProxyHostName = proxyHostName; - this.privProxyPort = proxyPort; - this.privProxyUserName = proxyUserName; - this.privProxyPassword = proxyPassword; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SynthesisRestAdapter = void 0; +const Exports_js_1 = __webpack_require__(66); +const Exports_js_2 = __webpack_require__(85); +const ConnectionFactoryBase_js_1 = __webpack_require__(135); +const HeaderNames_js_1 = __webpack_require__(59); +/** + * Implements methods for speech synthesis classes, sending requests to endpoint + * and parsing response into expected format + * @class SynthesisRestAdapter + */ +class SynthesisRestAdapter { + constructor(config, authentication) { + let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, undefined); + this.privIsCustomEndpoint = !!endpoint; + if (!endpoint) { + const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, "westus"); + const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region); + endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, `https://${region}.tts.speech${hostSuffix}`); + } + this.privEndpoint = endpoint; + const options = Exports_js_1.RestConfigBase.requestOptions; + this.privRestAdapter = new Exports_js_1.RestMessageAdapter(options); + this.privAuthentication = authentication; } - ProxyInfo.fromParameters = function (parameters) { - return new ProxyInfo(parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyHostName), parseInt(parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyPort), 10), parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyUserName), parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyPassword)); - }; - ProxyInfo.fromRecognizerConfig = function (config) { - return this.fromParameters(config.parameters); - }; - Object.defineProperty(ProxyInfo.prototype, "HostName", { - get: function () { - return this.privProxyHostName; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ProxyInfo.prototype, "Port", { - get: function () { - return this.privProxyPort; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ProxyInfo.prototype, "UserName", { - get: function () { - return this.privProxyUserName; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ProxyInfo.prototype, "Password", { - get: function () { - return this.privProxyPassword; - }, - enumerable: false, - configurable: true - }); - return ProxyInfo; -}()); -exports.ProxyInfo = ProxyInfo; + /** + * Sends list voices request to endpoint. + * @function + * @public + * @param connectionId - guid for connectionId + * @returns {Promise} rest response to status request + */ + async getVoicesList(connectionId) { + const uri = await this.getVoicesListUri(); + this.privRestAdapter.setHeaders(HeaderNames_js_1.HeaderNames.ConnectionId, connectionId); + const authInfo = await this.privAuthentication.fetch(connectionId); + this.privRestAdapter.setHeaders(authInfo.headerName, authInfo.token); + return this.privRestAdapter.request(Exports_js_1.RestRequestType.Get, uri); + } + /** + * Builds (and caches) the voices/list URI. When the caller supplied a custom endpoint with no path + * (e.g. a custom-domain or private-link host via fromEndpoint), the host may not serve the voices/list + * route directly and AAD token auth requires the regional host with the ocp-apim-custom-domain-name + * query parameter. In that case we resolve the service redirect (which is exposed on the synthesis + * route) to discover the regional host and custom-domain parameter, then retarget it to the + * voices/list path, keeping the http(s) scheme for this REST call. + */ + async getVoicesListUri() { + if (this.privUri !== undefined) { + return this.privUri; + } + const voicesPath = "/cognitiveservices/voices/list"; + const endpointUrl = new URL(this.privEndpoint); + const pathName = endpointUrl.pathname; + const hasNoPath = pathName === "" || pathName === "/"; + if (this.privIsCustomEndpoint && hasNoPath) { + // The redirect handler is exposed on the synthesis route. Resolving it returns the regional + // host together with the Ocp-Apim-Custom-Domain-Name parameter (or, when no redirect applies, + // falls back to the original host). We then point the resolved URL at the voices/list path. + endpointUrl.pathname = "/tts/cognitiveservices/websocket/v1"; + const resolved = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString(), false); + const resolvedUrl = new URL(resolved); + resolvedUrl.pathname = voicesPath; + resolvedUrl.searchParams.delete("GenerateRedirectResponse"); + this.privUri = resolvedUrl.toString(); + } + else if (hasNoPath) { + endpointUrl.pathname = voicesPath; + this.privUri = endpointUrl.toString(); + } + else { + // The endpoint already carries a path; preserve the legacy behavior of appending the voices route. + this.privUri = `${this.privEndpoint}${voicesPath}`; + } + return this.privUri; + } +} +exports.SynthesisRestAdapter = SynthesisRestAdapter; /***/ }), /* 251 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SynthesizerConfig = exports.SynthesisServiceType = void 0; +const Exports_js_1 = __webpack_require__(2); +var SynthesisServiceType; +(function (SynthesisServiceType) { + SynthesisServiceType[SynthesisServiceType["Standard"] = 0] = "Standard"; + SynthesisServiceType[SynthesisServiceType["Custom"] = 1] = "Custom"; +})(SynthesisServiceType = exports.SynthesisServiceType || (exports.SynthesisServiceType = {})); +class SynthesizerConfig { + constructor(speechServiceConfig, parameters) { + this.privSynthesisServiceType = SynthesisServiceType.Standard; + this.avatarEnabled = false; + this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new Exports_js_1.SpeechServiceConfig(new Exports_js_1.Context(null)); + this.privParameters = parameters; } -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RestMessageAdapter = exports.RestRequestType = void 0; -var Exports_1 = __webpack_require__(4); -var bent_1 = __importDefault(__webpack_require__(252)); -var RestRequestType; -(function (RestRequestType) { - RestRequestType["Get"] = "GET"; - RestRequestType["Post"] = "POST"; - RestRequestType["Delete"] = "DELETE"; - RestRequestType["File"] = "file"; -})(RestRequestType = exports.RestRequestType || (exports.RestRequestType = {})); -// accept rest operations via request method and return abstracted objects from server response -var RestMessageAdapter = /** @class */ (function () { - function RestMessageAdapter(configParams) { - if (!configParams) { - throw new Exports_1.ArgumentNullError("configParams"); - } - this.privHeaders = configParams.headers; - this.privIgnoreCache = configParams.ignoreCache; + get parameters() { + return this.privParameters; } - RestMessageAdapter.extractHeaderValue = function (headerKey, headers) { - var headerValue = ""; - try { - var arr = headers.trim().split(/[\r\n]+/); - var headerMap_1 = {}; - arr.forEach(function (line) { - var parts = line.split(": "); - var header = parts.shift().toLowerCase(); - var value = parts.join(": "); - headerMap_1[header] = value; - }); - headerValue = headerMap_1[headerKey.toLowerCase()]; - } - catch (e) { - // ignore the error - } - return headerValue; - }; - Object.defineProperty(RestMessageAdapter.prototype, "options", { - set: function (configParams) { - this.privHeaders = configParams.headers; - this.privIgnoreCache = configParams.ignoreCache; - }, - enumerable: false, - configurable: true - }); - RestMessageAdapter.prototype.setHeaders = function (key, value) { - this.privHeaders[key] = value; - }; - RestMessageAdapter.prototype.request = function (method, uri, queryParams, body, binaryBody) { - var _this = this; - if (queryParams === void 0) { queryParams = {}; } - if (body === void 0) { body = null; } - if (binaryBody === void 0) { binaryBody = null; } - var responseReceivedDeferral = new Exports_1.Deferred(); - var requestCommand = method === RestRequestType.File ? "POST" : method; - var handleRestResponse = function (data, j) { - if (j === void 0) { j = {}; } - var d = data; - return { - data: JSON.stringify(j), - headers: JSON.stringify(data.headers), - json: j, - ok: data.statusCode >= 200 && data.statusCode < 300, - status: data.statusCode, - statusText: j.error ? j.error.message : d.statusText ? d.statusText : d.statusMessage - }; - }; - var blobToArrayBuffer = function (blob) { - var reader = new FileReader(); - reader.readAsArrayBuffer(blob); - return new Promise(function (resolve) { - reader.onloadend = function () { - resolve(reader.result); - }; - }); - }; - var send = function (postData) { - var sendRequest = bent_1.default(uri, requestCommand, _this.privHeaders, 200, 201, 202, 204, 400, 401, 402, 403, 404); - var params = _this.queryParams(queryParams) === "" ? "" : "?" + _this.queryParams(queryParams); - sendRequest(params, postData).then(function (data) { return __awaiter(_this, void 0, void 0, function () { - var j, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!(method === RestRequestType.Delete || data.statusCode === 204)) return [3 /*break*/, 1]; - // No JSON from Delete and reset (204) operations - responseReceivedDeferral.resolve(handleRestResponse(data)); - return [3 /*break*/, 4]; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, data.json()]; - case 2: - j = _b.sent(); - responseReceivedDeferral.resolve(handleRestResponse(data, j)); - return [3 /*break*/, 4]; - case 3: - _a = _b.sent(); - responseReceivedDeferral.resolve(handleRestResponse(data)); - return [3 /*break*/, 4]; - case 4: return [2 /*return*/]; - } - }); - }); }).catch(function (error) { - responseReceivedDeferral.reject(error); - }); + get synthesisServiceType() { + return this.privSynthesisServiceType; + } + set synthesisServiceType(value) { + this.privSynthesisServiceType = value; + } + set synthesisVideoSection(value) { + this.privSpeechServiceConfig.Context.synthesis = { + video: value }; - if (this.privIgnoreCache) { - this.privHeaders["Cache-Control"] = "no-cache"; + } + get SpeechServiceConfig() { + return this.privSpeechServiceConfig; + } + setContextFromJson(contextJson) { + const context = JSON.parse(contextJson); + if (context.system) { + this.privSpeechServiceConfig.Context.system = context.system; } - if (method === RestRequestType.File && binaryBody) { - var contentType = "multipart/form-data"; - this.privHeaders["content-type"] = contentType; - this.privHeaders["Content-Type"] = contentType; - if (typeof (Blob) !== "undefined" && binaryBody instanceof Blob) { - blobToArrayBuffer(binaryBody).then(function (res) { - send(res); - }).catch(function (error) { - responseReceivedDeferral.reject(error); - }); - } - else { - send(binaryBody); - } + if (context.os) { + this.privSpeechServiceConfig.Context.os = context.os; } - else { - if (method === RestRequestType.Post && body) { - this.privHeaders["content-type"] = "application/json"; - this.privHeaders["Content-Type"] = "application/json"; - } - send(body); + if (context.audio) { + this.privSpeechServiceConfig.Context.audio = context.audio; } - return responseReceivedDeferral.promise; - }; - RestMessageAdapter.prototype.withQuery = function (url, params) { - if (params === void 0) { params = {}; } - var queryString = this.queryParams(params); - return queryString ? url + (url.indexOf("?") === -1 ? "?" : "&") + queryString : url; - }; - RestMessageAdapter.prototype.queryParams = function (params) { - if (params === void 0) { params = {}; } - return Object.keys(params) - .map(function (k) { return encodeURIComponent(k) + "=" + encodeURIComponent(params[k]); }) - .join("&"); - }; - return RestMessageAdapter; -}()); -exports.RestMessageAdapter = RestMessageAdapter; + if (context.synthesis) { + this.privSpeechServiceConfig.Context.synthesis = context.synthesis; + } + } +} +exports.SynthesizerConfig = SynthesizerConfig; /***/ }), /* 252 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* global fetch, btoa, Headers */ -const core = __webpack_require__(253) - -class StatusError extends Error { - constructor (res, ...params) { - super(...params) - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, StatusError) +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SynthesisContext = void 0; +const Exports_js_1 = __webpack_require__(85); +/** + * Represents the JSON used in the synthesis.context message sent to the speech service. + * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object. + */ +class SynthesisContext { + constructor() { + this.privContext = {}; } - - this.name = 'StatusError' - this.message = res.statusMessage - this.statusCode = res.status - this.res = res - this.json = res.json.bind(res) - this.text = res.text.bind(res) - this.arrayBuffer = res.arrayBuffer.bind(res) - let buffer - const get = () => { - if (!buffer) buffer = this.arrayBuffer() - return buffer + /** + * Adds a section to the synthesis.context object. + * @param sectionName Name of the section to add. + * @param value JSON serializable object that represents the value. + */ + setSection(sectionName, value) { + this.privContext[sectionName] = value; } - Object.defineProperty(this, 'responseBody', { get }) - // match Node.js headers object - this.headers = {} - for (const [key, value] of res.headers.entries()) { - this.headers[key.toLowerCase()] = value + /** + * Sets the audio output format for synthesis context generation. + * @param format {AudioOutputFormatImpl} the output format + */ + set audioOutputFormat(format) { + this.privAudioOutputFormat = format; } - } -} - -const mkrequest = (statusCodes, method, encoding, headers, baseurl) => async (_url, body, _headers = {}) => { - _url = baseurl + (_url || '') - let parsed = new URL(_url) - - if (!headers) headers = {} - if (parsed.username) { - headers.Authorization = 'Basic ' + btoa(parsed.username + ':' + parsed.password) - parsed = new URL(parsed.protocol + '//' + parsed.host + parsed.pathname + parsed.search) - } - if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') { - throw new Error(`Unknown protocol, ${parsed.protocol}`) - } - - if (body) { - if (body instanceof ArrayBuffer || - ArrayBuffer.isView(body) || - typeof body === 'string' - ) { - // noop - } else if (typeof body === 'object') { - body = JSON.stringify(body) - headers['Content-Type'] = 'application/json' - } else { - throw new Error('Unknown body type.') + toJSON() { + return JSON.stringify(this.privContext); + } + /** + * Gets a previously set section by name. + * @param sectionName Name of the section to retrieve. + */ + getSection(sectionName) { + return this.privContext[sectionName]; + } + setSynthesisSection(speechSynthesizer) { + const synthesisSection = this.buildSynthesisContext(speechSynthesizer); + this.setSection("synthesis", synthesisSection); + } + buildSynthesisContext(speechSynthesizer) { + return { + audio: { + metadataOptions: { + bookmarkEnabled: (!!speechSynthesizer?.bookmarkReached), + punctuationBoundaryEnabled: speechSynthesizer?.properties.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RequestPunctuationBoundary, (!!speechSynthesizer?.wordBoundary)), + sentenceBoundaryEnabled: speechSynthesizer?.properties.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RequestSentenceBoundary, false), + sessionEndEnabled: true, + visemeEnabled: (!!speechSynthesizer?.visemeReceived), + wordBoundaryEnabled: speechSynthesizer?.properties.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RequestWordBoundary, (!!speechSynthesizer?.wordBoundary)), + }, + outputFormat: this.privAudioOutputFormat.requestAudioFormatString, + }, + language: { + autoDetection: speechSynthesizer?.autoDetectSourceLanguage + } + }; } - } - - _headers = new Headers({ ...(headers || {}), ..._headers }) - - const resp = await fetch(parsed, { method, headers: _headers, body }) - resp.statusCode = resp.status - - if (!statusCodes.has(resp.status)) { - throw new StatusError(resp) - } - - if (encoding === 'json') return resp.json() - else if (encoding === 'buffer') return resp.arrayBuffer() - else if (encoding === 'string') return resp.text() - else return resp } +exports.SynthesisContext = SynthesisContext; -module.exports = core(mkrequest) /***/ }), /* 253 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { "use strict"; -const encodings = new Set(['json', 'buffer', 'string']) +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.type = exports.connectivity = exports.Device = exports.OS = exports.System = exports.Context = exports.SpeechServiceConfig = void 0; +/* eslint-disable max-classes-per-file */ +// The config is serialized and sent as the Speech.Config +class SpeechServiceConfig { + constructor(context) { + this.context = context; + } + serialize() { + return JSON.stringify(this, (key, value) => { + if (value && typeof value === "object" && !Array.isArray(value)) { + const replacement = {}; + for (const k in value) { + if (Object.hasOwnProperty.call(value, k)) { + // SeparateChannelProcessing must keep its PascalCase form to match the + // server-side (case-sensitive) multichannel/continuation contract. + const outKey = k === "SeparateChannelProcessing" ? k : (k && k.charAt(0).toLowerCase() + k.substring(1)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + replacement[outKey] = value[k]; + } + } + return replacement; + } + return value; + }); + } + get Context() { + return this.context; + } + get Recognition() { + return this.recognition; + } + set Recognition(value) { + this.recognition = value.toLowerCase(); + } +} +exports.SpeechServiceConfig = SpeechServiceConfig; +class Context { + constructor(os) { + this.system = new System(); + this.os = os; + } +} +exports.Context = Context; +class System { + constructor() { + // Note: below will be patched for official builds. + const SPEECHSDK_CLIENTSDK_VERSION = "1.51.0"; + this.name = "SpeechSDK"; + this.version = SPEECHSDK_CLIENTSDK_VERSION; + this.build = "JavaScript"; + this.lang = "JavaScript"; + } +} +exports.System = System; +class OS { + constructor(platform, name, version) { + this.platform = platform; + this.name = name; + this.version = version; + } +} +exports.OS = OS; +class Device { + constructor(manufacturer, model, version) { + this.manufacturer = manufacturer; + this.model = model; + this.version = version; + } +} +exports.Device = Device; +var connectivity; +(function (connectivity) { + connectivity["Bluetooth"] = "Bluetooth"; + connectivity["Wired"] = "Wired"; + connectivity["WiFi"] = "WiFi"; + connectivity["Cellular"] = "Cellular"; + connectivity["InBuilt"] = "InBuilt"; + connectivity["Unknown"] = "Unknown"; +})(connectivity = exports.connectivity || (exports.connectivity = {})); +var type; +(function (type) { + type["Phone"] = "Phone"; + type["Speaker"] = "Speaker"; + type["Car"] = "Car"; + type["Headset"] = "Headset"; + type["Thermostat"] = "Thermostat"; + type["Microphones"] = "Microphones"; + type["Deskphone"] = "Deskphone"; + type["RemoteControl"] = "RemoteControl"; + type["Unknown"] = "Unknown"; + type["File"] = "File"; + type["Stream"] = "Stream"; +})(type = exports.type || (exports.type = {})); -module.exports = mkrequest => (...args) => { - const statusCodes = new Set() - let method - let encoding - let headers - let baseurl = '' - args.forEach(arg => { - if (typeof arg === 'string') { - if (arg.toUpperCase() === arg) { - if (method) { - const msg = `Can't set method to ${arg}, already set to ${method}.` - throw new Error(msg) - } else { - method = arg - } - } else if (arg.startsWith('http:') || arg.startsWith('https:')) { - baseurl = arg - } else { - if (encodings.has(arg)) { - encoding = arg - } else { - throw new Error(`Unknown encoding, ${arg}`) - } - } - } else if (typeof arg === 'number') { - statusCodes.add(arg) - } else if (typeof arg === 'object') { - if (Array.isArray(arg) || arg instanceof Set) { - arg.forEach(code => statusCodes.add(code)) - } else { - if (headers) { - throw new Error('Cannot set headers twice.') - } - headers = arg - } - } else { - throw new Error(`Unknown type: ${typeof arg}`) - } - }) - if (!method) method = 'GET' - if (statusCodes.size === 0) { - statusCodes.add(200) - } +/***/ }) +/******/ ]); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +// This entry needs to be wrapped in an IIFE because it needs to be in strict mode. +(() => { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _distrib_lib_microsoft_cognitiveservices_speech_sdk_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var _distrib_lib_microsoft_cognitiveservices_speech_sdk_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_distrib_lib_microsoft_cognitiveservices_speech_sdk_js__WEBPACK_IMPORTED_MODULE_0__); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. - return mkrequest(statusCodes, method, encoding, headers, baseurl) -} +window.SpeechSDK = _distrib_lib_microsoft_cognitiveservices_speech_sdk_js__WEBPACK_IMPORTED_MODULE_0__; -/***/ }) -/******/ ]); +})(); + +/******/ })() +; //# sourceMappingURL=microsoft.cognitiveservices.speech.sdk.bundle.js.map \ No newline at end of file diff --git a/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/speech.js b/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/speech.js index a6632ceb..d8c06bc1 100644 --- a/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/speech.js +++ b/src/components/BootstrapBlazor.AzureSpeech/wwwroot/js/speech.js @@ -1,4 +1,4 @@ -import "./microsoft.cognitiveservices.speech.sdk.bundle.js"; +import "./microsoft.cognitiveservices.speech.sdk.bundle-min.js"; var recognizer = undefined; var synthesizer = undefined; @@ -16,7 +16,7 @@ export function bb_azure_speech_recognizeOnce(obj, method, token, region, recogn recognizer.recognizeOnceAsync(function (successfulResult) { recognizer.close(); recognizer = undefined; - obj.invokeMethodAsync(method, "Finished", successfulResult.privText); + obj.invokeMethodAsync(method, "Finished", successfulResult.text); }, function (err) { recognizer = undefined; obj.invokeMethodAsync(method, "Error", err);