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+BACD,OAAO,IAAIZ,GACP9Q,EAAe2R,MACf,EACA,KACA,IACA,GACA,EACAD,EACA,iCACA,GACR,IAAK,gCACD,OAAO,IAAIZ,GACP9Q,EAAe2R,MACf,EACA,KACA,IACA,GACA,EACAD,EACAA,GACA,GACR,IAAK,kCACD,OAAO,IAAIZ,GACP9Q,EAAe4R,IACf,EACA,KACA,KACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,mCACD,OAAO,IAAIZ,GACP9Q,EAAe4R,IACf,EACA,KACA,MACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,kCACD,OAAO,IAAIZ,GACP9Q,EAAe4R,IACf,EACA,KACA,KACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,kCACD,OAAO,IAAIZ,GACP9Q,EAAe4R,IACf,EACA,KACA,KACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,kCACD,OAAO,IAAIZ,GACP9Q,EAAe4R,IACf,EACA,KACA,MACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,mCACD,OAAO,IAAIZ,GACP9Q,EAAe4R,IACf,EACA,KACA,MACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,gCACD,OAAO,IAAIZ,GACP9Q,EAAe6R,UACf,EACA,KACA,KACA,EACA,GACAH,EACAA,GACA,GAER,IAAK,2BACD,OAAO,IAAIZ,GACP9Q,EAAeuC,IACf,EACA,IACA,KACA,EACA,GACAmP,EACA,2BACA,GACR,IAAK,4BACD,OAAO,IAAIZ,GACP9Q,EAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,4BACD,OAAO,IAAIZ,GACP9Q,EAAe0C,MACf,EACA,IACA,IACA,EACA,EACAgP,EACA,4BACA,GACR,IAAK,2BACD,OAAO,IAAIZ,GACP9Q,EAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,2BACD,OAAO,IAAIZ,GACP9Q,EAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,0BACD,OAAO,IAAIZ,GACP9Q,EAAeuC,IACf,EACA,IACA,KACA,EACA,GACAmP,EACA,2BACA,GACR,IAAK,4BACD,OAAO,IAAIZ,GACP9Q,EAAe8R,SACf,EACA,KACA,KACA,EACA,GACAJ,EACAA,GACA,GACR,IAAK,4BACD,OAAO,IAAIZ,GACP9Q,EAAe8R,SACf,EACA,KACA,KACA,EACA,GACAJ,EACAA,GACA,GACR,IAAK,2BACD,OAAO,IAAIZ,GACP9Q,EAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,4BACD,OAAO,IAAIZ,GACP9Q,EAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,kCACD,OAAO,IAAIZ,GACP9Q,EAAe4R,IACf,EACA,KACA,MACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,mCACD,OAAO,IAAIZ,GACP9Q,EAAe4R,IACf,EACA,KACA,MACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,4BACD,OAAO,IAAIZ,GACP9Q,EAAe8R,SACf,EACA,KACA,KACA,EACA,GACAJ,EACAA,GACA,GACR,IAAK,6BACD,OAAO,IAAIZ,GACP9Q,EAAe+R,UACf,EACA,KACA,IACA,EACA,GACAL,EACAA,GACA,GACR,IAAK,6BACD,OAAO,IAAIZ,GACP9Q,EAAe+R,UACf,EACA,KACA,IACA,EACA,GACAL,EACAA,GACA,GACR,IAAK,gCACD,OAAO,IAAIZ,GACP9Q,EAAe6R,UACf,EACA,KACA,KACA,EACA,GACAH,EACAA,GACA,GACR,IAAK,0BACD,OAAO,IAAIZ,GACP9Q,EAAeyC,KACf,EACA,IACA,IACA,EACA,EACAiP,EACAA,GACA,GACR,IAAK,2BACD,OAAO,IAAIZ,GACP9Q,EAAeyC,KACf,EACA,IACA,IACA,EACA,EACAiP,EACA,2BACA,GAER,QACI,OAAO,IAAIZ,GACP9Q,EAAeuC,IACf,EACA,KACA,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A,EACA,GACAF,EACAA,GACA,GACR,IAAK,gCACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAe6R,UACf,EACA,KACA,KACA,EACA,GACAH,EACAA,GACA,GAER,IAAK,2BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAeuC,IACf,EACA,IACA,KACA,EACA,GACAmP,EACA,2BACA,GACR,IAAK,4BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,4BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAe0C,MACf,EACA,IACA,IACA,EACA,EACAgP,EACA,4BACA,GACR,IAAK,2BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,2BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,0BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAeuC,IACf,EACA,IACA,KACA,EACA,GACAmP,EACA,2BACA,GACR,IAAK,4BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAe8R,SACf,EACA,KACA,KACA,EACA,GACAJ,EACAA,GACA,GACR,IAAK,4BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAe8R,SACf,EACA,KACA,KACA,EACA,GACAJ,EACAA,GACA,GACR,IAAK,2BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,4BACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAeuC,IACf,EACA,KACA,KACA,EACA,GACAmP,EACA,4BACA,GACR,IAAK,kCACD,OAAO,IAAIZ,EACP8zD,EAAA5kE,eAAe4R,IACf,EACA,KACA,MACA,EACA,GACAF,EACAA,GACA,GACR,IAAK,m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AAA4R,GAAAnO,EAAA,OAAStrE,OAAAA,eAAAA,EAAAA,qCAAAA,CAAAyxE,YAAA,EAAAvuE,IAAA,kBAAAu2E,GAAA3R,kCAAkC,IAC3C,IAAA4R,GAAApO,EAAA,OAAStrE,OAAAA,eAAAA,EAAAA,gCAAAA,CAAAyxE,YAAA,EAAAvuE,IAAA,kBAAAw2E,GAAA5Q,6BAA6B,IACtC,IAAA6Q,GAAArO,EAAA,OAAStrE,OAAAA,eAAAA,EAAAA,gCAAAA,CAAAyxE,YAAA,EAAAvuE,IAAA,kBAAAy2E,GAAA3P,6BAA6B,G","sources":["../node_modules/memoize-one/dist/memoize-one.esm.js","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Guid.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/PlatformEvent.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/PropertyId.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/RecognizerConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Promise.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Error.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/EventSource.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Events.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/RiffPcmEncoder.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/PCMRecorder.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/AudioSourceEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/List.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Queue.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/AudioStreamFormat.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Stream.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/ChunkedArrayBufferStream.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/MicAudioSource.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/FileAudioSource.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/Contracts.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/PullAudioInputStreamCallback.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/ConnectionMessage.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/IConnection.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/CancellationReason.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/CancellationErrorCodes.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ResultReason.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechSynthesisOutputFormat.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/AudioInputStream.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/ConnectionEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechSynthesisEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechSynthesisResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/PropertyCollection.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechSynthesisWordBoundaryEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechSynthesisBookmarkEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechSynthesisVisemeEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/AudioOutputFormat.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/AudioOutputStream.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SynthesisEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SynthesisTurn.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SynthesisContext.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/AgentConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/Exports.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SynthesisAudioMetadata.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/HeaderNames.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SpeechConnectionMessage.Internal.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SynthesisAdapterBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/BackgroundError.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/SpeakerAudioDestination.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/PushAudioOutputStreamCallback.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/OutputFormat.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ProfanityOption.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/RecognitionEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/AudioFileWriter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/AudioConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/KeywordRecognitionModel.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SessionEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/RecognitionEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/IntentRecognitionEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/RecognitionResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechRecognitionResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/IntentRecognitionResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/LanguageUnderstandingModel.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechRecognitionEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/CancellationEventArgsBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechRecognitionCanceledEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/TranslationRecognitionEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/TranslationSynthesisEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/TranslationRecognitionResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/TranslationSynthesisResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechTranslationConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/ReplayableAudioNode.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Timeout.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/ServiceTelemetryListener.Internal.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/RequestSession.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/DynamicGrammarBuilder.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SpeechContext.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SpeechDetected.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/ServiceRecognizerBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/IAuthentication.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/CognitiveSubscriptionKeyAuthentication.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/CognitiveTokenAuthentication.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/Recognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/ConnectionOpenResponse.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/RawWebsocketMessage.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/OCSPEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/CertChecks.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/WebsocketMessageAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/WebsocketConnection.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/ProxyInfo.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/QueryParameterNames.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/ConnectionFactoryBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/WebsocketMessageFormatter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SpeechConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SpeechHypothesis.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/Enums.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SimpleSpeechPhrase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/EnumTranslation.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/DetailedSpeechPhrase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SpeechServiceRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/IntentConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/AddedLmIntent.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/IntentRecognitionCanceledEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/IntentResponse.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/IntentServiceRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/VoiceProfileType.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/TranslationStatus.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/IntentRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/TranslationConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/TranslationRecognitionCanceledEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/Translations.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/TranslationHypothesis.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/TranslationPhrase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/TranslationSynthesisEnd.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/TranslationServiceRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/NoMatchReason.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/ActivityResponsePayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/TranslationRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/NoMatchDetails.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/CancellationDetailsBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/CancellationDetails.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ConnectionEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ServiceEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ConnectionMessage.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ConnectionMessageEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/Connection.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/PhraseListGrammar.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/DialogServiceConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/BotFrameworkConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/CustomCommandsConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/DialogConnectorFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/DialogEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ActivityReceivedEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/TurnStatusPayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/TurnStatusReceivedEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/DialogServiceTurnState.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/DialogServiceTurnStateManager.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SpeechKeyword.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/DialogServiceAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ServicePropertyChannel.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/DialogServiceConnector.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/BaseAudioPlayer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/VoiceProfile.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/VoiceProfileEnrollmentResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/VoiceProfileResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/VoiceProfileAuthorizationPhraseResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SpeakerRecognitionConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/RestConfigBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/RestMessageAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SpeakerIdMessageAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeakerRecognitionResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/VoiceProfileClient.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeakerIdentificationModel.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeakerVerificationModel.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeakerRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/AutoDetectSourceLanguageConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/AutoDetectSourceLanguageResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SourceLanguageConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationConnectionConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationTranslatorInterfaces.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationUtils.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationManager.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationConnectionMessage.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationWebsocketMessageFormatter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ConversationTranslationCanceledEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ConversationExpirationEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ConversationTranslationResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationRequestSession.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationTranslatorEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/ServiceMessages/src/common.speech/Transcription/ServiceMessages/CommandResponsePayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/ServiceMessages/src/common.speech/Transcription/ServiceMessages/ParticipantResponsePayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/ServiceMessages/src/common.speech/Transcription/ServiceMessages/TranslationResponsePayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationServiceAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ParticipantChangedReason.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/ConversationTranslatorRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ConversationParticipantsChangedEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ConversationTranslationEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/IParticipant.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/Conversation.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ConversationCommon.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ConversationTranslator.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/TranscriberConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/ConversationTranscriptionCanceledEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/TranscriptionServiceRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/Transcription/src/common.speech/Transcription/TranscriberRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SynthesizerConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Transcription/src/sdk/Transcription/ConversationTranscriber.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/SpeechSynthesisConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/PronunciationAssessmentGradingSystem.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/PronunciationAssessmentGranularity.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/SpeechSynthesizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/PronunciationAssessmentConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/src/sdk/PronunciationAssessmentResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/microsoft.cognitiveservices.speech.sdk.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.browser/src/common.browser/ConsoleLoggingListener.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/microsoft.cognitiveservices.speech.sdk.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/CertChecks.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/ConsoleLoggingListener.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/Exports.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/FileAudioSource.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/MicAudioSource.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/PCMRecorder.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/ProxyInfo.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/ReplayableAudioNode.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/RestConfigBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/RestMessageAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/WebsocketConnection.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/src/common.browser/WebsocketMessageAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/AddedLmIntent.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/AgentConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/CognitiveSubscriptionKeyAuthentication.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/CognitiveTokenAuthentication.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/ConnectionFactoryBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/DialogConnectorFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/DialogServiceAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/DialogServiceTurnState.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/DialogServiceTurnStateManager.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/DynamicGrammarBuilder.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/EnumTranslation.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/Exports.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/HeaderNames.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/IAuthentication.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/IntentConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/IntentServiceRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/QueryParameterNames.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/RecognitionEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/RecognizerConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/RequestSession.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/ActivityResponsePayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/DetailedSpeechPhrase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/Enums.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/IntentResponse.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SimpleSpeechPhrase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SpeechDetected.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SpeechHypothesis.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SpeechKeyword.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/SynthesisAudioMetadata.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/TranslationHypothesis.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/TranslationPhrase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/TranslationSynthesisEnd.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/src/common.speech/ServiceMessages/TurnStatusPayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/ServiceRecognizerBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/ServiceTelemetryListener.Internal.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SpeakerIdMessageAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SpeakerRecognitionConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SpeechConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SpeechConnectionMessage.Internal.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SpeechContext.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SpeechServiceRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SpeechSynthesisConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SynthesisAdapterBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SynthesisContext.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SynthesisEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SynthesisTurn.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/SynthesizerConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/TranscriberConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/TranscriptionServiceRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationConnectionConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationConnectionMessage.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationManager.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationRequestSession.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationServiceAdapter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationTranslatorEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationTranslatorInterfaces.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationTranslatorRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationUtils.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/ConversationWebsocketMessageFormatter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/Exports.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/src/common.speech/Transcription/ServiceMessages/CommandResponsePayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/src/common.speech/Transcription/ServiceMessages/Exports.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/src/common.speech/Transcription/ServiceMessages/ParticipantResponsePayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/src/common.speech/Transcription/ServiceMessages/TranslationResponsePayload.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/src/common.speech/Transcription/TranscriberRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/TranslationConnectionFactory.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/TranslationServiceRecognizer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/TranslationStatus.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/src/common.speech/WebsocketMessageFormatter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/AudioSourceEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/BackgroundError.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/ChunkedArrayBufferStream.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/ConnectionEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/ConnectionMessage.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/ConnectionOpenResponse.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/DialogEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/Error.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/EventSource.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/Events.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/Exports.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/Guid.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/IConnection.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/List.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/OCSPEvents.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/PlatformEvent.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/Promise.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/Queue.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/RawWebsocketMessage.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/RiffPcmEncoder.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/Stream.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/src/common/Timeout.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/ActivityReceivedEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/AudioConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/AudioFileWriter.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/AudioInputStream.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/AudioOutputFormat.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/AudioOutputStream.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/AudioStreamFormat.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/BaseAudioPlayer.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/PullAudioInputStreamCallback.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/PushAudioOutputStreamCallback.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/src/sdk/Audio/SpeakerAudioDestination.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/AutoDetectSourceLanguageConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/AutoDetectSourceLanguageResult.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/BotFrameworkConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/CancellationDetails.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/CancellationDetailsBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/CancellationErrorCodes.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/CancellationEventArgsBase.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/CancellationReason.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/Connection.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/ConnectionEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/ConnectionMessage.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/ConnectionMessageEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/Contracts.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/ConversationTranscriptionCanceledEventArgs.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/CustomCommandsConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/DialogServiceConfig.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/DialogServiceConnector.ts","../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/src/sdk/Exports.ts"],"sourcesContent":["var safeIsNaN = Number.isNaN ||\n function ponyfill(value) {\n return typeof value === 'number' && value !== value;\n };\nfunction isEqual(first, second) {\n if (first === second) {\n return true;\n }\n if (safeIsNaN(first) && safeIsNaN(second)) {\n return true;\n }\n return false;\n}\nfunction areInputsEqual(newInputs, lastInputs) {\n if (newInputs.length !== lastInputs.length) {\n return false;\n }\n for (var i = 0; i < newInputs.length; i++) {\n if (!isEqual(newInputs[i], lastInputs[i])) {\n return false;\n }\n }\n return true;\n}\n\nfunction memoizeOne(resultFn, isEqual) {\n if (isEqual === void 0) { isEqual = areInputsEqual; }\n var cache = null;\n function memoized() {\n var newArgs = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n newArgs[_i] = arguments[_i];\n }\n if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) {\n return cache.lastResult;\n }\n var lastResult = resultFn.apply(this, newArgs);\n cache = {\n lastResult: lastResult,\n lastArgs: newArgs,\n lastThis: this,\n };\n return lastResult;\n }\n memoized.clear = function clear() {\n cache = null;\n };\n return memoized;\n}\n\nexport { memoizeOne as default };\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { v4 as uuid } from \"uuid\";\r\n\r\nconst createGuid: () => string = (): string => {\r\n return uuid();\r\n};\r\n\r\nconst createNoDashGuid: () => string = (): string => {\r\n return createGuid().replace(new RegExp(\"-\", \"g\"), \"\").toUpperCase();\r\n};\r\n\r\nexport { createGuid, createNoDashGuid };\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { createNoDashGuid } from \"./Guid\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\n\r\nexport enum EventType {\r\n Debug,\r\n Info,\r\n Warning,\r\n Error,\r\n}\r\n\r\nexport class PlatformEvent {\r\n private privName: string;\r\n private privEventId: string;\r\n private privEventTime: string;\r\n private privEventType: EventType;\r\n private privMetadata: IStringDictionary;\r\n\r\n constructor(eventName: string, eventType: EventType) {\r\n this.privName = eventName;\r\n this.privEventId = createNoDashGuid();\r\n this.privEventTime = new Date().toISOString();\r\n this.privEventType = eventType;\r\n this.privMetadata = { };\r\n }\r\n\r\n public get name(): string {\r\n return this.privName;\r\n }\r\n\r\n public get eventId(): string {\r\n return this.privEventId;\r\n }\r\n\r\n public get eventTime(): string {\r\n return this.privEventTime;\r\n }\r\n\r\n public get eventType(): EventType {\r\n return this.privEventType;\r\n }\r\n\r\n public get metadata(): IStringDictionary {\r\n return this.privMetadata;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines speech property ids.\r\n * @class PropertyId\r\n */\r\nexport enum PropertyId {\r\n\r\n /**\r\n * The Cognitive Services Speech Service subscription Key. If you are using an intent recognizer, you need to specify\r\n * to specify the LUIS endpoint key for your particular LUIS app. Under normal circumstances, you shouldn't\r\n * have to use this property directly.\r\n * Instead, use [[SpeechConfig.fromSubscription]].\r\n * @member PropertyId.SpeechServiceConnection_Key\r\n */\r\n SpeechServiceConnection_Key = 0,\r\n\r\n /**\r\n * The Cognitive Services Speech Service endpoint (url). Under normal circumstances, you shouldn't\r\n * have to use this property directly.\r\n * Instead, use [[SpeechConfig.fromEndpoint]].\r\n * NOTE: This endpoint is not the same as the endpoint used to obtain an access token.\r\n * @member PropertyId.SpeechServiceConnection_Endpoint\r\n */\r\n SpeechServiceConnection_Endpoint,\r\n\r\n /**\r\n * The Cognitive Services Speech Service region. Under normal circumstances, you shouldn't have to\r\n * use this property directly.\r\n * Instead, use [[SpeechConfig.fromSubscription]], [[SpeechConfig.fromEndpoint]], [[SpeechConfig.fromAuthorizationToken]].\r\n * @member PropertyId.SpeechServiceConnection_Region\r\n */\r\n SpeechServiceConnection_Region,\r\n\r\n /**\r\n * The Cognitive Services Speech Service authorization token (aka access token). Under normal circumstances,\r\n * you shouldn't have to use this property directly.\r\n * Instead, use [[SpeechConfig.fromAuthorizationToken]], [[SpeechRecognizer.authorizationToken]],\r\n * [[IntentRecognizer.authorizationToken]], [[TranslationRecognizer.authorizationToken]], [[SpeakerRecognizer.authorizationToken]].\r\n * @member PropertyId.SpeechServiceAuthorization_Token\r\n */\r\n SpeechServiceAuthorization_Token,\r\n\r\n /**\r\n * The Cognitive Services Speech Service authorization type. Currently unused.\r\n * @member PropertyId.SpeechServiceAuthorization_Type\r\n */\r\n SpeechServiceAuthorization_Type,\r\n\r\n /**\r\n * The Cognitive Services Speech Service endpoint id. Under normal circumstances, you shouldn't\r\n * have to use this property directly.\r\n * Instead, use [[SpeechConfig.endpointId]].\r\n * NOTE: The endpoint id is available in the Speech Portal, listed under Endpoint Details.\r\n * @member PropertyId.SpeechServiceConnection_EndpointId\r\n */\r\n SpeechServiceConnection_EndpointId,\r\n\r\n /**\r\n * The list of comma separated languages (BCP-47 format) used as target translation languages. Under normal circumstances,\r\n * you shouldn't have to use this property directly.\r\n * Instead use [[SpeechTranslationConfig.addTargetLanguage]],\r\n * [[SpeechTranslationConfig.targetLanguages]], [[TranslationRecognizer.targetLanguages]].\r\n * @member PropertyId.SpeechServiceConnection_TranslationToLanguages\r\n */\r\n SpeechServiceConnection_TranslationToLanguages,\r\n\r\n /**\r\n * The name of the Cognitive Service Text to Speech Service Voice. Under normal circumstances, you shouldn't have to use this\r\n * property directly.\r\n * Instead, use [[SpeechTranslationConfig.voiceName]].\r\n * NOTE: Valid voice names can be found here.\r\n * @member PropertyId.SpeechServiceConnection_TranslationVoice\r\n */\r\n SpeechServiceConnection_TranslationVoice,\r\n\r\n /**\r\n * Translation features.\r\n * @member PropertyId.SpeechServiceConnection_TranslationFeatures\r\n */\r\n SpeechServiceConnection_TranslationFeatures,\r\n\r\n /**\r\n * The Language Understanding Service Region. Under normal circumstances, you shouldn't have to use this property directly.\r\n * Instead, use [[LanguageUnderstandingModel]].\r\n * @member PropertyId.SpeechServiceConnection_IntentRegion\r\n */\r\n SpeechServiceConnection_IntentRegion,\r\n\r\n /**\r\n * The host name of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments.\r\n * You shouldn't have to use this property directly.\r\n * Instead use .\r\n * Added in version 1.4.0.\r\n */\r\n SpeechServiceConnection_ProxyHostName,\r\n\r\n /**\r\n * The port of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments.\r\n * You shouldn't have to use this property directly.\r\n * Instead use .\r\n * Added in version 1.4.0.\r\n */\r\n SpeechServiceConnection_ProxyPort,\r\n\r\n /**\r\n * The user name of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments.\r\n * You shouldn't have to use this property directly.\r\n * Instead use .\r\n * Added in version 1.4.0.\r\n */\r\n SpeechServiceConnection_ProxyUserName,\r\n\r\n /**\r\n * The password of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments.\r\n * You shouldn't have to use this property directly.\r\n * Instead use .\r\n * Added in version 1.4.0.\r\n */\r\n SpeechServiceConnection_ProxyPassword,\r\n\r\n /**\r\n * The Cognitive Services Speech Service recognition Mode. Can be \"INTERACTIVE\", \"CONVERSATION\", \"DICTATION\".\r\n * This property is intended to be read-only. The SDK is using it internally.\r\n * @member PropertyId.SpeechServiceConnection_RecoMode\r\n */\r\n SpeechServiceConnection_RecoMode,\r\n\r\n /**\r\n * The spoken language to be recognized (in BCP-47 format). Under normal circumstances, you shouldn't have to use this property\r\n * directly.\r\n * Instead, use [[SpeechConfig.speechRecognitionLanguage]].\r\n * @member PropertyId.SpeechServiceConnection_RecoLanguage\r\n */\r\n SpeechServiceConnection_RecoLanguage,\r\n\r\n /**\r\n * The session id. This id is a universally unique identifier (aka UUID) representing a specific binding of an audio input stream\r\n * and the underlying speech recognition instance to which it is bound. Under normal circumstances, you shouldn't have to use this\r\n * property directly.\r\n * Instead use [[SessionEventArgs.sessionId]].\r\n * @member PropertyId.Speech_SessionId\r\n */\r\n Speech_SessionId,\r\n\r\n /**\r\n * The spoken language to be synthesized (e.g. en-US)\r\n * @member PropertyId.SpeechServiceConnection_SynthLanguage\r\n */\r\n SpeechServiceConnection_SynthLanguage,\r\n\r\n /**\r\n * The name of the TTS voice to be used for speech synthesis\r\n * @member PropertyId.SpeechServiceConnection_SynthVoice\r\n */\r\n SpeechServiceConnection_SynthVoice,\r\n\r\n /**\r\n * The string to specify TTS output audio format\r\n * @member PropertyId.SpeechServiceConnection_SynthOutputFormat\r\n */\r\n SpeechServiceConnection_SynthOutputFormat,\r\n\r\n /**\r\n * The list of comma separated languages used as possible source languages\r\n * Added in version 1.13.0\r\n * @member PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages\r\n */\r\n SpeechServiceConnection_AutoDetectSourceLanguages,\r\n\r\n /**\r\n * The requested Cognitive Services Speech Service response output format (simple or detailed). Under normal circumstances, you shouldn't have\r\n * to use this property directly.\r\n * Instead use [[SpeechConfig.outputFormat]].\r\n * @member PropertyId.SpeechServiceResponse_RequestDetailedResultTrueFalse\r\n */\r\n SpeechServiceResponse_RequestDetailedResultTrueFalse,\r\n\r\n /**\r\n * The requested Cognitive Services Speech Service response output profanity level. Currently unused.\r\n * @member PropertyId.SpeechServiceResponse_RequestProfanityFilterTrueFalse\r\n */\r\n SpeechServiceResponse_RequestProfanityFilterTrueFalse,\r\n\r\n /**\r\n * The Cognitive Services Speech Service response output (in JSON format). This property is available on recognition result objects only.\r\n * @member PropertyId.SpeechServiceResponse_JsonResult\r\n */\r\n SpeechServiceResponse_JsonResult,\r\n\r\n /**\r\n * The Cognitive Services Speech Service error details (in JSON format). Under normal circumstances, you shouldn't have to\r\n * use this property directly. Instead use [[CancellationDetails.errorDetails]].\r\n * @member PropertyId.SpeechServiceResponse_JsonErrorDetails\r\n */\r\n SpeechServiceResponse_JsonErrorDetails,\r\n\r\n /**\r\n * The cancellation reason. Currently unused.\r\n * @member PropertyId.CancellationDetails_Reason\r\n */\r\n CancellationDetails_Reason,\r\n\r\n /**\r\n * The cancellation text. Currently unused.\r\n * @member PropertyId.CancellationDetails_ReasonText\r\n */\r\n CancellationDetails_ReasonText,\r\n\r\n /**\r\n * The Cancellation detailed text. Currently unused.\r\n * @member PropertyId.CancellationDetails_ReasonDetailedText\r\n */\r\n CancellationDetails_ReasonDetailedText,\r\n\r\n /**\r\n * The Language Understanding Service response output (in JSON format). Available via [[IntentRecognitionResult]]\r\n * @member PropertyId.LanguageUnderstandingServiceResponse_JsonResult\r\n */\r\n LanguageUnderstandingServiceResponse_JsonResult,\r\n\r\n /**\r\n * The URL string built from speech configuration.\r\n * This property is intended to be read-only. The SDK is using it internally.\r\n * NOTE: Added in version 1.7.0.\r\n */\r\n SpeechServiceConnection_Url,\r\n\r\n /**\r\n * The initial silence timeout value (in milliseconds) used by the service.\r\n * Added in version 1.7.0\r\n */\r\n SpeechServiceConnection_InitialSilenceTimeoutMs,\r\n\r\n /**\r\n * The end silence timeout value (in milliseconds) used by the service.\r\n * Added in version 1.7.0\r\n */\r\n SpeechServiceConnection_EndSilenceTimeoutMs,\r\n\r\n /**\r\n * A boolean value specifying whether audio logging is enabled in the service or not.\r\n * Added in version 1.7.0\r\n */\r\n SpeechServiceConnection_EnableAudioLogging,\r\n\r\n /**\r\n * The requested Cognitive Services Speech Service response output profanity setting.\r\n * Allowed values are \"masked\", \"removed\", and \"raw\".\r\n * Added in version 1.7.0.\r\n */\r\n SpeechServiceResponse_ProfanityOption,\r\n\r\n /**\r\n * A string value specifying which post processing option should be used by service.\r\n * Allowed values are \"TrueText\".\r\n * Added in version 1.7.0\r\n */\r\n SpeechServiceResponse_PostProcessingOption,\r\n\r\n /**\r\n * A boolean value specifying whether to include word-level timestamps in the response result.\r\n * Added in version 1.7.0\r\n */\r\n SpeechServiceResponse_RequestWordLevelTimestamps,\r\n\r\n /**\r\n * The number of times a word has to be in partial results to be returned.\r\n * Added in version 1.7.0\r\n */\r\n SpeechServiceResponse_StablePartialResultThreshold,\r\n\r\n /**\r\n * A string value specifying the output format option in the response result. Internal use only.\r\n * Added in version 1.7.0.\r\n */\r\n SpeechServiceResponse_OutputFormatOption,\r\n\r\n /**\r\n * A boolean value to request for stabilizing translation partial results by omitting words in the end.\r\n * Added in version 1.7.0.\r\n */\r\n SpeechServiceResponse_TranslationRequestStablePartialResult,\r\n\r\n /**\r\n * Identifier used to connect to the backend service.\r\n * @member PropertyId.Conversation_ApplicationId\r\n */\r\n Conversation_ApplicationId,\r\n\r\n /**\r\n * Type of dialog backend to connect to.\r\n * @member PropertyId.Conversation_DialogType\r\n */\r\n Conversation_DialogType,\r\n\r\n /**\r\n * Silence timeout for listening\r\n * @member PropertyId.Conversation_Initial_Silence_Timeout\r\n */\r\n Conversation_Initial_Silence_Timeout,\r\n\r\n /**\r\n * From Id to add to speech recognition activities.\r\n * @member PropertyId.Conversation_From_Id\r\n */\r\n Conversation_From_Id,\r\n\r\n /**\r\n * ConversationId for the session.\r\n * @member PropertyId.Conversation_Conversation_Id\r\n */\r\n Conversation_Conversation_Id,\r\n\r\n /**\r\n * Comma separated list of custom voice deployment ids.\r\n * @member PropertyId.Conversation_Custom_Voice_Deployment_Ids\r\n */\r\n Conversation_Custom_Voice_Deployment_Ids,\r\n\r\n /**\r\n * Speech activity template, stamp properties from the template on the activity generated by the service for speech.\r\n * @member PropertyId.Conversation_Speech_Activity_Template\r\n * Added in version 1.10.0.\r\n */\r\n Conversation_Speech_Activity_Template,\r\n\r\n /**\r\n * Enables or disables the receipt of turn status messages as obtained on the turnStatusReceived event.\r\n * @member PropertyId.Conversation_Request_Bot_Status_Messages\r\n * Added in version 1.15.0.\r\n */\r\n Conversation_Request_Bot_Status_Messages,\r\n\r\n /**\r\n * Specifies the connection ID to be provided in the Agent configuration message, e.g. a Direct Line token for\r\n * channel authentication.\r\n * Added in version 1.15.1.\r\n */\r\n Conversation_Agent_Connection_Id,\r\n\r\n /**\r\n * The Cognitive Services Speech Service host (url). Under normal circumstances, you shouldn't have to use this property directly.\r\n * Instead, use [[SpeechConfig.fromHost]].\r\n */\r\n SpeechServiceConnection_Host,\r\n\r\n /**\r\n * Set the host for service calls to the Conversation Translator REST management and websocket calls.\r\n */\r\n ConversationTranslator_Host,\r\n\r\n /**\r\n * Optionally set the the host's display name.\r\n * Used when joining a conversation.\r\n */\r\n ConversationTranslator_Name,\r\n\r\n /**\r\n * Optionally set a value for the X-CorrelationId request header.\r\n * Used for troubleshooting errors in the server logs. It should be a valid guid.\r\n */\r\n ConversationTranslator_CorrelationId,\r\n\r\n /**\r\n * Set the conversation token to be sent to the speech service. This enables the\r\n * service to service call from the speech service to the Conversation Translator service for relaying\r\n * recognitions. For internal use.\r\n */\r\n ConversationTranslator_Token,\r\n\r\n /**\r\n * The reference text of the audio for pronunciation evaluation.\r\n * For this and the following pronunciation assessment parameters, see\r\n * https://docs.microsoft.com/azure/cognitive-services/speech-service/rest-speech-to-text#pronunciation-assessment-parameters for details.\r\n * Under normal circumstances, you shouldn't have to use this property directly.\r\n * Added in version 1.15.0\r\n */\r\n PronunciationAssessment_ReferenceText,\r\n\r\n /**\r\n * The point system for pronunciation score calibration (FivePoint or HundredMark).\r\n * Under normal circumstances, you shouldn't have to use this property directly.\r\n * Added in version 1.15.0\r\n */\r\n PronunciationAssessment_GradingSystem,\r\n\r\n /**\r\n * The pronunciation evaluation granularity (Phoneme, Word, or FullText).\r\n * Under normal circumstances, you shouldn't have to use this property directly.\r\n * Added in version 1.15.0\r\n */\r\n PronunciationAssessment_Granularity,\r\n\r\n /**\r\n * Defines if enable miscue calculation.\r\n * With this enabled, the pronounced words will be compared to the reference text,\r\n * and will be marked with omission/insertion based on the comparison. The default setting is False.\r\n * Under normal circumstances, you shouldn't have to use this property directly.\r\n * Added in version 1.15.0\r\n */\r\n PronunciationAssessment_EnableMiscue,\r\n\r\n /**\r\n * The json string of pronunciation assessment parameters\r\n * Under normal circumstances, you shouldn't have to use this property directly.\r\n * Added in version 1.15.0\r\n */\r\n PronunciationAssessment_Json,\r\n\r\n /**\r\n * Pronunciation assessment parameters.\r\n * This property is intended to be read-only. The SDK is using it internally.\r\n * Added in version 1.15.0\r\n */\r\n PronunciationAssessment_Params\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { PropertyCollection, PropertyId } from \"../sdk/Exports\";\r\n\r\nexport enum RecognitionMode {\r\n Interactive,\r\n Conversation,\r\n Dictation,\r\n}\r\n\r\nexport enum SpeechResultFormat {\r\n Simple,\r\n Detailed,\r\n}\r\n\r\nexport class RecognizerConfig {\r\n private privRecognitionMode: RecognitionMode = RecognitionMode.Interactive;\r\n private privSpeechServiceConfig: SpeechServiceConfig;\r\n private privRecognitionActivityTimeout: number;\r\n private privParameters: PropertyCollection;\r\n private privMaxRetryCount: number;\r\n\r\n constructor(\r\n speechServiceConfig: SpeechServiceConfig,\r\n parameters: PropertyCollection) {\r\n this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new SpeechServiceConfig(new Context(null));\r\n this.privParameters = parameters;\r\n this.privMaxRetryCount = parseInt(parameters.getProperty(\"SPEECH-Error-MaxRetryCount\", \"4\"), 10);\r\n }\r\n\r\n public get parameters(): PropertyCollection {\r\n return this.privParameters;\r\n }\r\n\r\n public get recognitionMode(): RecognitionMode {\r\n return this.privRecognitionMode;\r\n }\r\n\r\n public set recognitionMode(value: RecognitionMode) {\r\n this.privRecognitionMode = value;\r\n this.privRecognitionActivityTimeout = value === RecognitionMode.Interactive ? 8000 : 25000;\r\n this.privSpeechServiceConfig.Recognition = RecognitionMode[value];\r\n }\r\n\r\n public get SpeechServiceConfig(): SpeechServiceConfig {\r\n return this.privSpeechServiceConfig;\r\n }\r\n\r\n public get recognitionActivityTimeout(): number {\r\n return this.privRecognitionActivityTimeout;\r\n }\r\n\r\n public get isContinuousRecognition(): boolean {\r\n return this.privRecognitionMode !== RecognitionMode.Interactive;\r\n }\r\n\r\n public get autoDetectSourceLanguages(): string {\r\n return this.parameters.getProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, undefined);\r\n }\r\n\r\n public get maxRetryCount(): number {\r\n return this.privMaxRetryCount;\r\n }\r\n}\r\n\r\n// The config is serialized and sent as the Speech.Config\r\nexport class SpeechServiceConfig {\r\n private context: Context;\r\n private recognition: string;\r\n\r\n constructor(context: Context) {\r\n this.context = context;\r\n }\r\n\r\n public serialize = (): string => {\r\n return JSON.stringify(this, (key: any, value: any): any => {\r\n if (value && typeof value === \"object\") {\r\n const replacement: any = {};\r\n for (const k in value) {\r\n if (Object.hasOwnProperty.call(value, k)) {\r\n replacement[k && k.charAt(0).toLowerCase() + k.substring(1)] = value[k];\r\n }\r\n }\r\n return replacement;\r\n }\r\n return value;\r\n });\r\n }\r\n\r\n public get Context(): Context {\r\n return this.context;\r\n }\r\n\r\n public get Recognition(): string {\r\n return this.recognition;\r\n }\r\n\r\n public set Recognition(value: string) {\r\n this.recognition = value.toLowerCase();\r\n }\r\n}\r\n\r\nexport class Context {\r\n public system: System;\r\n public os: OS;\r\n public audio: ISpeechConfigAudio;\r\n\r\n constructor(os: OS) {\r\n this.system = new System();\r\n this.os = os;\r\n }\r\n}\r\n\r\nexport class System {\r\n public name: string;\r\n public version: string;\r\n public build: string;\r\n public lang: string;\r\n\r\n constructor() {\r\n // Note: below will be patched for official builds.\r\n const SPEECHSDK_CLIENTSDK_VERSION = \"1.17.0\";\r\n\r\n this.name = \"SpeechSDK\";\r\n this.version = SPEECHSDK_CLIENTSDK_VERSION;\r\n this.build = \"JavaScript\";\r\n this.lang = \"JavaScript\";\r\n }\r\n}\r\n\r\nexport class OS {\r\n public platform: string;\r\n public name: string;\r\n public version: string;\r\n\r\n constructor(platform: string, name: string, version: string) {\r\n this.platform = platform;\r\n this.name = name;\r\n this.version = version;\r\n }\r\n}\r\n\r\nexport class Device {\r\n public manufacturer: string;\r\n public model: string;\r\n public version: string;\r\n\r\n constructor(manufacturer: string, model: string, version: string) {\r\n this.manufacturer = manufacturer;\r\n this.model = model;\r\n this.version = version;\r\n }\r\n}\r\n\r\nexport interface ISpeechConfigAudio {\r\n source?: ISpeechConfigAudioDevice;\r\n playback?: ISpeechConfigAudioDevice;\r\n}\r\n\r\nexport interface ISpeechConfigAudioDevice {\r\n manufacturer: string;\r\n model: string;\r\n connectivity: connectivity;\r\n type: type;\r\n samplerate: number;\r\n bitspersample: number;\r\n channelcount: number;\r\n}\r\n\r\nexport enum connectivity {\r\n Bluetooth = \"Bluetooth\",\r\n Wired = \"Wired\",\r\n WiFi = \"WiFi\",\r\n Cellular = \"Cellular\",\r\n InBuilt = \"InBuilt\",\r\n Unknown = \"Unknown\",\r\n}\r\n\r\nexport enum type {\r\n Phone = \"Phone\",\r\n Speaker = \"Speaker\",\r\n Car = \"Car\",\r\n Headset = \"Headset\",\r\n Thermostat = \"Thermostat\",\r\n Microphones = \"Microphones\",\r\n Deskphone = \"Deskphone\",\r\n RemoteControl = \"RemoteControl\",\r\n Unknown = \"Unknown\",\r\n File = \"File\",\r\n Stream = \"Stream\",\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { ArgumentNullError } from \"./Error\";\r\n\r\nexport enum PromiseState {\r\n None,\r\n Resolved,\r\n Rejected,\r\n}\r\n\r\nexport interface IDeferred {\r\n readonly promise: Promise;\r\n\r\n resolve(result: T): IDeferred;\r\n\r\n reject(error: string): IDeferred;\r\n}\r\n\r\nexport class PromiseResult {\r\n protected privIsCompleted: boolean;\r\n protected privIsError: boolean;\r\n protected privError: string;\r\n protected privResult: T;\r\n\r\n public constructor(promiseResultEventSource: PromiseResultEventSource) {\r\n promiseResultEventSource.on((result: T) => {\r\n if (!this.privIsCompleted) {\r\n this.privIsCompleted = true;\r\n this.privIsError = false;\r\n this.privResult = result;\r\n }\r\n }, (error: string) => {\r\n if (!this.privIsCompleted) {\r\n this.privIsCompleted = true;\r\n this.privIsError = true;\r\n this.privError = error;\r\n }\r\n });\r\n }\r\n\r\n public get isCompleted(): boolean {\r\n return this.privIsCompleted;\r\n }\r\n\r\n public get isError(): boolean {\r\n return this.privIsError;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n\r\n public get result(): T {\r\n return this.privResult;\r\n }\r\n\r\n public throwIfError = (): void => {\r\n if (this.isError) {\r\n throw this.error;\r\n }\r\n }\r\n}\r\n\r\nexport class PromiseResultEventSource {\r\n\r\n private privOnSetResult: (result: T) => void;\r\n private privOnSetError: (error: string) => void;\r\n\r\n public setResult = (result: T): void => {\r\n this.privOnSetResult(result);\r\n }\r\n\r\n public setError = (error: string): void => {\r\n this.privOnSetError(error);\r\n }\r\n\r\n public on = (onSetResult: (result: T) => void, onSetError: (error: string) => void): void => {\r\n this.privOnSetResult = onSetResult;\r\n this.privOnSetError = onSetError;\r\n }\r\n}\r\n\r\nexport class Deferred implements IDeferred {\r\n private privPromise: Promise;\r\n private privResolve: (value?: T | PromiseLike) => void;\r\n private privReject: (reason?: any) => void;\r\n\r\n public constructor() {\r\n this.privPromise = new Promise((resolve: (value: T) => void, reject: (reason: any) => void) => {\r\n this.privResolve = resolve;\r\n this.privReject = reject;\r\n });\r\n }\r\n\r\n public get promise(): Promise {\r\n return this.privPromise;\r\n }\r\n\r\n public resolve = (result: T | Promise): Deferred => {\r\n this.privResolve(result);\r\n return this;\r\n }\r\n\r\n public reject = (error: string): Deferred => {\r\n this.privReject(error);\r\n return this;\r\n }\r\n}\r\n\r\nexport class Sink {\r\n private privState: PromiseState = PromiseState.None;\r\n private privPromiseResult: PromiseResult = null;\r\n private privPromiseResultEvents: PromiseResultEventSource = null;\r\n\r\n private privSuccessHandlers: ((result: T) => void)[] = [];\r\n private privErrorHandlers: ((e: string) => void)[] = [];\r\n\r\n public constructor() {\r\n this.privPromiseResultEvents = new PromiseResultEventSource();\r\n this.privPromiseResult = new PromiseResult(this.privPromiseResultEvents);\r\n }\r\n\r\n public get state(): PromiseState {\r\n return this.privState;\r\n }\r\n\r\n public get result(): PromiseResult {\r\n return this.privPromiseResult;\r\n }\r\n\r\n public resolve = (result: T): void => {\r\n if (this.privState !== PromiseState.None) {\r\n throw new Error(\"'Cannot resolve a completed promise'\");\r\n }\r\n\r\n this.privState = PromiseState.Resolved;\r\n this.privPromiseResultEvents.setResult(result);\r\n\r\n for (let i = 0; i < this.privSuccessHandlers.length; i++) {\r\n this.executeSuccessCallback(result, this.privSuccessHandlers[i], this.privErrorHandlers[i]);\r\n }\r\n\r\n this.detachHandlers();\r\n }\r\n\r\n public reject = (error: string): void => {\r\n if (this.privState !== PromiseState.None) {\r\n throw new Error(\"'Cannot reject a completed promise'\");\r\n }\r\n\r\n this.privState = PromiseState.Rejected;\r\n this.privPromiseResultEvents.setError(error);\r\n\r\n for (const errorHandler of this.privErrorHandlers) {\r\n this.executeErrorCallback(error, errorHandler);\r\n }\r\n\r\n this.detachHandlers();\r\n }\r\n\r\n public on = (\r\n successCallback: (result: T) => void,\r\n errorCallback: (error: string) => void): void => {\r\n\r\n if (successCallback == null) {\r\n successCallback = (r: T) => { return; };\r\n }\r\n\r\n if (this.privState === PromiseState.None) {\r\n this.privSuccessHandlers.push(successCallback);\r\n this.privErrorHandlers.push(errorCallback);\r\n } else {\r\n if (this.privState === PromiseState.Resolved) {\r\n this.executeSuccessCallback(this.privPromiseResult.result, successCallback, errorCallback);\r\n } else if (this.privState === PromiseState.Rejected) {\r\n this.executeErrorCallback(this.privPromiseResult.error, errorCallback);\r\n }\r\n\r\n this.detachHandlers();\r\n }\r\n }\r\n\r\n private executeSuccessCallback = (result: T, successCallback: (result: T) => void, errorCallback: (error: string) => void): void => {\r\n try {\r\n successCallback(result);\r\n } catch (e) {\r\n this.executeErrorCallback(`'Unhandled callback error: ${e}'`, errorCallback);\r\n }\r\n }\r\n\r\n private executeErrorCallback = (error: string, errorCallback: (error: string) => void): void => {\r\n if (errorCallback) {\r\n try {\r\n errorCallback(error);\r\n } catch (e) {\r\n throw new Error(`'Unhandled callback error: ${e}. InnerError: ${error}'`);\r\n }\r\n } else {\r\n throw new Error(`'Unhandled error: ${error}'`);\r\n }\r\n }\r\n\r\n private detachHandlers = (): void => {\r\n this.privErrorHandlers = [];\r\n this.privSuccessHandlers = [];\r\n }\r\n}\r\n\r\nexport function marshalPromiseToCallbacks(\r\n promise: Promise,\r\n cb?: (value: T) => void,\r\n err?: (error: string) => void): void {\r\n promise.then((val: T): void => {\r\n try {\r\n if (!!cb) {\r\n cb(val);\r\n }\r\n } catch (error) {\r\n if (!!err) {\r\n try {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n /* tslint:disable:no-empty */\r\n } catch (error) { }\r\n }\r\n }\r\n }, (error: any): void => {\r\n if (!!err) {\r\n try {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n /* tslint:disable:no-empty */\r\n } catch (error) { }\r\n }\r\n });\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\n/**\r\n * The error that is thrown when an argument passed in is null.\r\n *\r\n * @export\r\n * @class ArgumentNullError\r\n * @extends {Error}\r\n */\r\nexport class ArgumentNullError extends Error {\r\n\r\n /**\r\n * Creates an instance of ArgumentNullError.\r\n *\r\n * @param {string} argumentName - Name of the argument that is null\r\n *\r\n * @memberOf ArgumentNullError\r\n */\r\n public constructor(argumentName: string) {\r\n super(argumentName);\r\n this.name = \"ArgumentNull\";\r\n this.message = argumentName;\r\n }\r\n}\r\n\r\n/**\r\n * The error that is thrown when an invalid operation is performed in the code.\r\n *\r\n * @export\r\n * @class InvalidOperationError\r\n * @extends {Error}\r\n */\r\nexport class InvalidOperationError extends Error {\r\n\r\n /**\r\n * Creates an instance of InvalidOperationError.\r\n *\r\n * @param {string} error - The error\r\n *\r\n * @memberOf InvalidOperationError\r\n */\r\n public constructor(error: string) {\r\n super(error);\r\n this.name = \"InvalidOperation\";\r\n this.message = error;\r\n }\r\n}\r\n\r\n/**\r\n * The error that is thrown when an object is disposed.\r\n *\r\n * @export\r\n * @class ObjectDisposedError\r\n * @extends {Error}\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class ObjectDisposedError extends Error {\r\n\r\n /**\r\n * Creates an instance of ObjectDisposedError.\r\n *\r\n * @param {string} objectName - The object that is disposed\r\n * @param {string} error - The error\r\n *\r\n * @memberOf ObjectDisposedError\r\n */\r\n public constructor(objectName: string, error?: string) {\r\n super(error);\r\n this.name = objectName + \"ObjectDisposed\";\r\n this.message = error;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ObjectDisposedError } from \"./Error\";\r\nimport { createNoDashGuid } from \"./Guid\";\r\nimport { IDetachable } from \"./IDetachable\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\nimport { IEventListener, IEventSource } from \"./IEventSource\";\r\nimport { PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class EventSource implements IEventSource {\r\n private privEventListeners: IStringDictionary<(event: TEvent) => void> = {};\r\n private privMetadata: IStringDictionary;\r\n private privIsDisposed: boolean = false;\r\n\r\n constructor(metadata?: IStringDictionary) {\r\n this.privMetadata = metadata;\r\n }\r\n\r\n public onEvent = (event: TEvent): void => {\r\n if (this.isDisposed()) {\r\n throw (new ObjectDisposedError(\"EventSource\"));\r\n }\r\n\r\n if (this.metadata) {\r\n for (const paramName in this.metadata) {\r\n if (paramName) {\r\n if (event.metadata) {\r\n if (!event.metadata[paramName]) {\r\n event.metadata[paramName] = this.metadata[paramName];\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n for (const eventId in this.privEventListeners) {\r\n if (eventId && this.privEventListeners[eventId]) {\r\n this.privEventListeners[eventId](event);\r\n }\r\n }\r\n }\r\n\r\n public attach = (onEventCallback: (event: TEvent) => void): IDetachable => {\r\n const id = createNoDashGuid();\r\n this.privEventListeners[id] = onEventCallback;\r\n return {\r\n detach: () => {\r\n delete this.privEventListeners[id];\r\n return Promise.resolve();\r\n },\r\n };\r\n }\r\n\r\n public attachListener = (listener: IEventListener): IDetachable => {\r\n return this.attach(listener.onEvent);\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public dispose = (): void => {\r\n this.privEventListeners = null;\r\n this.privIsDisposed = true;\r\n }\r\n\r\n public get metadata(): IStringDictionary {\r\n return this.privMetadata;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ArgumentNullError } from \"./Error\";\r\nimport { EventSource } from \"./EventSource\";\r\nimport { IEventSource } from \"./IEventSource\";\r\nimport { PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class Events {\r\n private static privInstance: IEventSource = new EventSource();\r\n\r\n public static setEventSource = (eventSource: IEventSource): void => {\r\n if (!eventSource) {\r\n throw new ArgumentNullError(\"eventSource\");\r\n }\r\n\r\n Events.privInstance = eventSource;\r\n }\r\n\r\n public static get instance(): IEventSource {\r\n return Events.privInstance;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport class RiffPcmEncoder {\r\n\r\n private privActualSampleRate: number;\r\n private privDesiredSampleRate: number;\r\n\r\n public constructor(actualSampleRate: number, desiredSampleRate: number) {\r\n this.privActualSampleRate = actualSampleRate;\r\n this.privDesiredSampleRate = desiredSampleRate;\r\n }\r\n\r\n public encode = (\r\n actualAudioFrame: Float32Array): ArrayBuffer => {\r\n\r\n const audioFrame = this.downSampleAudioFrame(actualAudioFrame, this.privActualSampleRate, this.privDesiredSampleRate);\r\n\r\n if (!audioFrame) {\r\n return null;\r\n }\r\n\r\n const audioLength = audioFrame.length * 2;\r\n\r\n const buffer = new ArrayBuffer(audioLength);\r\n const view = new DataView(buffer);\r\n this.floatTo16BitPCM(view, 0, audioFrame);\r\n\r\n return buffer;\r\n }\r\n\r\n private setString = (view: DataView, offset: number, str: string): void => {\r\n for (let i = 0; i < str.length; i++) {\r\n view.setUint8(offset + i, str.charCodeAt(i));\r\n }\r\n }\r\n\r\n private floatTo16BitPCM = (view: DataView, offset: number, input: Float32Array): void => {\r\n for (let i = 0; i < input.length; i++ , offset += 2) {\r\n const s = Math.max(-1, Math.min(1, input[i]));\r\n view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);\r\n }\r\n }\r\n\r\n private downSampleAudioFrame = (\r\n srcFrame: Float32Array,\r\n srcRate: number,\r\n dstRate: number): Float32Array => {\r\n\r\n if (dstRate === srcRate || dstRate > srcRate) {\r\n return srcFrame;\r\n }\r\n\r\n const ratio = srcRate / dstRate;\r\n const dstLength = Math.round(srcFrame.length / ratio);\r\n const dstFrame = new Float32Array(dstLength);\r\n let srcOffset = 0;\r\n let dstOffset = 0;\r\n while (dstOffset < dstLength) {\r\n const nextSrcOffset = Math.round((dstOffset + 1) * ratio);\r\n let accum = 0;\r\n let count = 0;\r\n while (srcOffset < nextSrcOffset && srcOffset < srcFrame.length) {\r\n accum += srcFrame[srcOffset++];\r\n count++;\r\n }\r\n dstFrame[dstOffset++] = accum / count;\r\n }\r\n\r\n return dstFrame;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RiffPcmEncoder, Stream } from \"../common/Exports\";\r\nimport { IRecorder } from \"./IRecorder\";\r\n\r\nexport class PcmRecorder implements IRecorder {\r\n private privMediaResources: IMediaResources;\r\n private privSpeechProcessorScript: string; // speech-processor.js Url\r\n\r\n public record = (context: AudioContext, mediaStream: MediaStream, outputStream: Stream): void => {\r\n const desiredSampleRate = 16000;\r\n\r\n const scriptNode = (() => {\r\n let bufferSize = 0;\r\n try {\r\n return context.createScriptProcessor(bufferSize, 1, 1);\r\n } catch (error) {\r\n // Webkit (<= version 31) requires a valid bufferSize.\r\n bufferSize = 2048;\r\n let audioSampleRate = context.sampleRate;\r\n while (bufferSize < 16384 && audioSampleRate >= (2 * desiredSampleRate)) {\r\n bufferSize <<= 1;\r\n audioSampleRate >>= 1;\r\n }\r\n return context.createScriptProcessor(bufferSize, 1, 1);\r\n }\r\n })();\r\n\r\n const waveStreamEncoder = new RiffPcmEncoder(context.sampleRate, desiredSampleRate);\r\n let needHeader: boolean = true;\r\n const that = this;\r\n scriptNode.onaudioprocess = (event: AudioProcessingEvent) => {\r\n const inputFrame = event.inputBuffer.getChannelData(0);\r\n\r\n if (outputStream && !outputStream.isClosed) {\r\n const waveFrame = waveStreamEncoder.encode(inputFrame);\r\n if (!!waveFrame) {\r\n outputStream.writeStreamChunk({\r\n buffer: waveFrame,\r\n isEnd: false,\r\n timeReceived: Date.now(),\r\n });\r\n needHeader = false;\r\n }\r\n }\r\n };\r\n\r\n const micInput = context.createMediaStreamSource(mediaStream);\r\n\r\n // https://webaudio.github.io/web-audio-api/#audioworklet\r\n // Using AudioWorklet to improve audio quality and avoid audio glitches due to blocking the UI thread\r\n\r\n if (!!this.privSpeechProcessorScript && !!context.audioWorklet) {\r\n context.audioWorklet\r\n .addModule(this.privSpeechProcessorScript)\r\n .then(() => {\r\n const workletNode = new AudioWorkletNode(context, \"speech-processor\");\r\n workletNode.port.onmessage = (ev: MessageEvent) => {\r\n const inputFrame: Float32Array = ev.data as Float32Array;\r\n\r\n if (outputStream && !outputStream.isClosed) {\r\n const waveFrame = waveStreamEncoder.encode(inputFrame);\r\n if (!!waveFrame) {\r\n outputStream.writeStreamChunk({\r\n buffer: waveFrame,\r\n isEnd: false,\r\n timeReceived: Date.now(),\r\n });\r\n needHeader = false;\r\n }\r\n }\r\n };\r\n micInput.connect(workletNode);\r\n workletNode.connect(context.destination);\r\n this.privMediaResources = {\r\n scriptProcessorNode: workletNode,\r\n source: micInput,\r\n stream: mediaStream,\r\n };\r\n })\r\n .catch(() => {\r\n micInput.connect(scriptNode);\r\n scriptNode.connect(context.destination);\r\n this.privMediaResources = {\r\n scriptProcessorNode: scriptNode,\r\n source: micInput,\r\n stream: mediaStream,\r\n };\r\n });\r\n } else {\r\n micInput.connect(scriptNode);\r\n scriptNode.connect(context.destination);\r\n this.privMediaResources = {\r\n scriptProcessorNode: scriptNode,\r\n source: micInput,\r\n stream: mediaStream,\r\n };\r\n }\r\n }\r\n\r\n public releaseMediaResources = (context: AudioContext): void => {\r\n if (this.privMediaResources) {\r\n if (this.privMediaResources.scriptProcessorNode) {\r\n this.privMediaResources.scriptProcessorNode.disconnect(context.destination);\r\n this.privMediaResources.scriptProcessorNode = null;\r\n }\r\n if (this.privMediaResources.source) {\r\n this.privMediaResources.source.disconnect();\r\n this.privMediaResources.stream.getTracks().forEach((track: any) => track.stop());\r\n this.privMediaResources.source = null;\r\n }\r\n }\r\n }\r\n\r\n public setWorkletUrl(url: string): void {\r\n this.privSpeechProcessorScript = url;\r\n }\r\n}\r\n\r\ninterface IMediaResources {\r\n source: MediaStreamAudioSourceNode;\r\n scriptProcessorNode: ScriptProcessorNode | AudioWorkletNode;\r\n stream: MediaStream;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { EventType, PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class AudioSourceEvent extends PlatformEvent {\r\n private privAudioSourceId: string;\r\n\r\n constructor(eventName: string, audioSourceId: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n this.privAudioSourceId = audioSourceId;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n}\r\n\r\nexport class AudioSourceInitializingEvent extends AudioSourceEvent {\r\n constructor(audioSourceId: string) {\r\n super(\"AudioSourceInitializingEvent\", audioSourceId);\r\n }\r\n}\r\n\r\nexport class AudioSourceReadyEvent extends AudioSourceEvent {\r\n constructor(audioSourceId: string) {\r\n super(\"AudioSourceReadyEvent\", audioSourceId);\r\n }\r\n}\r\n\r\nexport class AudioSourceOffEvent extends AudioSourceEvent {\r\n constructor(audioSourceId: string) {\r\n super(\"AudioSourceOffEvent\", audioSourceId);\r\n }\r\n}\r\n\r\nexport class AudioSourceErrorEvent extends AudioSourceEvent {\r\n private privError: string;\r\n\r\n constructor(audioSourceId: string, error: string) {\r\n super(\"AudioSourceErrorEvent\", audioSourceId, EventType.Error);\r\n this.privError = error;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeEvent extends AudioSourceEvent {\r\n private privAudioNodeId: string;\r\n\r\n constructor(eventName: string, audioSourceId: string, audioNodeId: string) {\r\n super(eventName, audioSourceId);\r\n this.privAudioNodeId = audioNodeId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeAttachingEvent extends AudioStreamNodeEvent {\r\n constructor(audioSourceId: string, audioNodeId: string) {\r\n super(\"AudioStreamNodeAttachingEvent\", audioSourceId, audioNodeId);\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeAttachedEvent extends AudioStreamNodeEvent {\r\n constructor(audioSourceId: string, audioNodeId: string) {\r\n super(\"AudioStreamNodeAttachedEvent\", audioSourceId, audioNodeId);\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeDetachedEvent extends AudioStreamNodeEvent {\r\n constructor(audioSourceId: string, audioNodeId: string) {\r\n super(\"AudioStreamNodeDetachedEvent\", audioSourceId, audioNodeId);\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeErrorEvent extends AudioStreamNodeEvent {\r\n private privError: string;\r\n\r\n constructor(audioSourceId: string, audioNodeId: string, error: string) {\r\n super(\"AudioStreamNodeErrorEvent\", audioSourceId, audioNodeId);\r\n this.privError = error;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ObjectDisposedError } from \"./Error\";\r\nimport { IDetachable } from \"./IDetachable\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\nimport { IDisposable } from \"./IDisposable\";\r\n\r\nexport interface IList extends IDisposable {\r\n get(itemIndex: number): TItem;\r\n first(): TItem;\r\n last(): TItem;\r\n\r\n add(item: TItem): void;\r\n insertAt(index: number, item: TItem): void;\r\n\r\n removeFirst(): TItem;\r\n removeLast(): TItem;\r\n removeAt(index: number): TItem;\r\n remove(index: number, count: number): TItem[];\r\n clear(): void;\r\n\r\n length(): number;\r\n\r\n onAdded(addedCallback: () => void): IDetachable;\r\n onRemoved(removedCallback: () => void): IDetachable;\r\n onDisposed(disposedCallback: () => void): IDetachable;\r\n\r\n join(seperator?: string): string;\r\n\r\n toArray(): TItem[];\r\n\r\n any(callback?: (item: TItem, index: number) => boolean): boolean;\r\n all(callback: (item: TItem) => boolean): boolean;\r\n forEach(callback: (item: TItem, index: number) => void): void;\r\n select(callback: (item: TItem, index: number) => T2): List;\r\n where(callback: (item: TItem, index: number) => boolean): List;\r\n orderBy(compareFn: (a: TItem, b: TItem) => number): List;\r\n orderByDesc(compareFn: (a: TItem, b: TItem) => number): List;\r\n clone(): List;\r\n concat(list: List): List;\r\n concatArray(array: TItem[]): List;\r\n}\r\n\r\nexport class List implements IList {\r\n private privList: TItem[];\r\n private privSubscriptionIdCounter: number = 0;\r\n private privAddSubscriptions: IStringDictionary<() => void> = {};\r\n private privRemoveSubscriptions: IStringDictionary<() => void> = {};\r\n private privDisposedSubscriptions: IStringDictionary<() => void> = {};\r\n private privDisposeReason: string = null;\r\n\r\n public constructor(list?: TItem[]) {\r\n this.privList = [];\r\n // copy the list rather than taking as is.\r\n if (list) {\r\n for (const item of list) {\r\n this.privList.push(item);\r\n }\r\n }\r\n }\r\n\r\n public get = (itemIndex: number): TItem => {\r\n this.throwIfDisposed();\r\n return this.privList[itemIndex];\r\n }\r\n\r\n public first = (): TItem => {\r\n return this.get(0);\r\n }\r\n\r\n public last = (): TItem => {\r\n return this.get(this.length() - 1);\r\n }\r\n\r\n public add = (item: TItem): void => {\r\n this.throwIfDisposed();\r\n this.insertAt(this.privList.length, item);\r\n }\r\n\r\n public insertAt = (index: number, item: TItem): void => {\r\n this.throwIfDisposed();\r\n if (index === 0) {\r\n this.privList.unshift(item);\r\n } else if (index === this.privList.length) {\r\n this.privList.push(item);\r\n } else {\r\n this.privList.splice(index, 0, item);\r\n }\r\n this.triggerSubscriptions(this.privAddSubscriptions);\r\n }\r\n\r\n public removeFirst = (): TItem => {\r\n this.throwIfDisposed();\r\n return this.removeAt(0);\r\n }\r\n\r\n public removeLast = (): TItem => {\r\n this.throwIfDisposed();\r\n return this.removeAt(this.length() - 1);\r\n }\r\n\r\n public removeAt = (index: number): TItem => {\r\n this.throwIfDisposed();\r\n return this.remove(index, 1)[0];\r\n }\r\n\r\n public remove = (index: number, count: number): TItem[] => {\r\n this.throwIfDisposed();\r\n const removedElements = this.privList.splice(index, count);\r\n this.triggerSubscriptions(this.privRemoveSubscriptions);\r\n return removedElements;\r\n }\r\n\r\n public clear = (): void => {\r\n this.throwIfDisposed();\r\n this.remove(0, this.length());\r\n }\r\n\r\n public length = (): number => {\r\n this.throwIfDisposed();\r\n return this.privList.length;\r\n }\r\n\r\n public onAdded = (addedCallback: () => void): IDetachable => {\r\n this.throwIfDisposed();\r\n const subscriptionId = this.privSubscriptionIdCounter++;\r\n\r\n this.privAddSubscriptions[subscriptionId] = addedCallback;\r\n\r\n return {\r\n detach: () => {\r\n delete this.privAddSubscriptions[subscriptionId];\r\n return Promise.resolve();\r\n },\r\n };\r\n }\r\n\r\n public onRemoved = (removedCallback: () => void): IDetachable => {\r\n this.throwIfDisposed();\r\n const subscriptionId = this.privSubscriptionIdCounter++;\r\n\r\n this.privRemoveSubscriptions[subscriptionId] = removedCallback;\r\n\r\n return {\r\n detach: () => {\r\n delete this.privRemoveSubscriptions[subscriptionId];\r\n return Promise.resolve();\r\n },\r\n };\r\n }\r\n\r\n public onDisposed = (disposedCallback: () => void): IDetachable => {\r\n this.throwIfDisposed();\r\n const subscriptionId = this.privSubscriptionIdCounter++;\r\n\r\n this.privDisposedSubscriptions[subscriptionId] = disposedCallback;\r\n\r\n return {\r\n detach: () => {\r\n delete this.privDisposedSubscriptions[subscriptionId];\r\n return Promise.resolve();\r\n },\r\n };\r\n }\r\n\r\n public join = (seperator?: string): string => {\r\n this.throwIfDisposed();\r\n return this.privList.join(seperator);\r\n }\r\n\r\n public toArray = (): TItem[] => {\r\n const cloneCopy = Array();\r\n this.privList.forEach((val: TItem) => {\r\n cloneCopy.push(val);\r\n });\r\n return cloneCopy;\r\n }\r\n\r\n public any = (callback?: (item: TItem, index: number) => boolean): boolean => {\r\n this.throwIfDisposed();\r\n if (callback) {\r\n return this.where(callback).length() > 0;\r\n } else {\r\n return this.length() > 0;\r\n }\r\n }\r\n\r\n public all = (callback: (item: TItem) => boolean): boolean => {\r\n this.throwIfDisposed();\r\n return this.where(callback).length() === this.length();\r\n }\r\n\r\n public forEach = (callback: (item: TItem, index: number) => void): void => {\r\n this.throwIfDisposed();\r\n for (let i = 0; i < this.length(); i++) {\r\n callback(this.privList[i], i);\r\n }\r\n }\r\n\r\n public select = (callback: (item: TItem, index: number) => T2): List => {\r\n this.throwIfDisposed();\r\n const selectList: T2[] = [];\r\n for (let i = 0; i < this.privList.length; i++) {\r\n selectList.push(callback(this.privList[i], i));\r\n }\r\n\r\n return new List(selectList);\r\n }\r\n\r\n public where = (callback: (item: TItem, index: number) => boolean): List => {\r\n this.throwIfDisposed();\r\n const filteredList = new List();\r\n for (let i = 0; i < this.privList.length; i++) {\r\n if (callback(this.privList[i], i)) {\r\n filteredList.add(this.privList[i]);\r\n }\r\n }\r\n return filteredList;\r\n }\r\n\r\n public orderBy = (compareFn: (a: TItem, b: TItem) => number): List => {\r\n this.throwIfDisposed();\r\n const clonedArray = this.toArray();\r\n const orderedArray = clonedArray.sort(compareFn);\r\n return new List(orderedArray);\r\n }\r\n\r\n public orderByDesc = (compareFn: (a: TItem, b: TItem) => number): List => {\r\n this.throwIfDisposed();\r\n return this.orderBy((a: TItem, b: TItem) => compareFn(b, a));\r\n }\r\n\r\n public clone = (): List => {\r\n this.throwIfDisposed();\r\n return new List(this.toArray());\r\n }\r\n\r\n public concat = (list: List): List => {\r\n this.throwIfDisposed();\r\n return new List(this.privList.concat(list.toArray()));\r\n }\r\n\r\n public concatArray = (array: TItem[]): List => {\r\n this.throwIfDisposed();\r\n return new List(this.privList.concat(array));\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privList == null;\r\n }\r\n\r\n public dispose = (reason?: string): void => {\r\n if (!this.isDisposed()) {\r\n this.privDisposeReason = reason;\r\n this.privList = null;\r\n this.privAddSubscriptions = null;\r\n this.privRemoveSubscriptions = null;\r\n this.triggerSubscriptions(this.privDisposedSubscriptions);\r\n }\r\n }\r\n\r\n private throwIfDisposed = (): void => {\r\n if (this.isDisposed()) {\r\n throw new ObjectDisposedError(\"List\", this.privDisposeReason);\r\n }\r\n }\r\n\r\n private triggerSubscriptions = (subscriptions: IStringDictionary<() => void>): void => {\r\n if (subscriptions) {\r\n for (const subscriptionId in subscriptions) {\r\n if (subscriptionId) {\r\n subscriptions[subscriptionId]();\r\n }\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError, ObjectDisposedError } from \"./Error\";\r\nimport { IDetachable } from \"./IDetachable\";\r\nimport { IDisposable } from \"./IDisposable\";\r\nimport { List } from \"./List\";\r\nimport {\r\n Deferred,\r\n} from \"./Promise\";\r\nexport interface IQueue extends IDisposable {\r\n enqueue(item: TItem): void;\r\n enqueueFromPromise(promise: Promise): void;\r\n dequeue(): Promise;\r\n peek(): Promise;\r\n length(): number;\r\n}\r\n\r\nenum SubscriberType {\r\n Dequeue,\r\n Peek,\r\n}\r\n\r\nexport class Queue implements IQueue {\r\n private privPromiseStore: List> = new List>();\r\n private privList: List;\r\n private privDetachables: IDetachable[];\r\n private privSubscribers: List<{ type: SubscriberType, deferral: Deferred }>;\r\n private privIsDrainInProgress: boolean = false;\r\n private privIsDisposing: boolean = false;\r\n private privDisposeReason: string = null;\r\n\r\n public constructor(list?: List) {\r\n this.privList = list ? list : new List();\r\n this.privDetachables = [];\r\n this.privSubscribers = new List<{ type: SubscriberType, deferral: Deferred }>();\r\n this.privDetachables.push(this.privList.onAdded(this.drain));\r\n }\r\n\r\n public enqueue = (item: TItem): void => {\r\n this.throwIfDispose();\r\n this.enqueueFromPromise(new Promise((resolve: (value: TItem) => void, reject: (reason: any) => void) => { resolve(item); }));\r\n }\r\n\r\n public enqueueFromPromise = (promise: Promise): void => {\r\n this.throwIfDispose();\r\n promise.then((val: TItem): void => {\r\n this.privList.add(val);\r\n /* tslint:disable:no-empty */\r\n }, (error: string): void => { });\r\n }\r\n\r\n public dequeue = (): Promise => {\r\n this.throwIfDispose();\r\n const deferredSubscriber = new Deferred();\r\n\r\n if (this.privSubscribers) {\r\n this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Dequeue });\r\n this.drain();\r\n }\r\n\r\n return deferredSubscriber.promise;\r\n }\r\n\r\n public peek = (): Promise => {\r\n this.throwIfDispose();\r\n const deferredSubscriber = new Deferred();\r\n\r\n const subs = this.privSubscribers;\r\n if (subs) {\r\n this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Peek });\r\n this.drain();\r\n }\r\n\r\n return deferredSubscriber.promise;\r\n }\r\n\r\n public length = (): number => {\r\n this.throwIfDispose();\r\n return this.privList.length();\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privSubscribers == null;\r\n }\r\n\r\n public async drainAndDispose(pendingItemProcessor: (pendingItemInQueue: TItem) => void, reason?: string): Promise {\r\n if (!this.isDisposed() && !this.privIsDisposing) {\r\n this.privDisposeReason = reason;\r\n this.privIsDisposing = true;\r\n\r\n const subs = this.privSubscribers;\r\n if (subs) {\r\n while (subs.length() > 0) {\r\n const subscriber = subs.removeFirst();\r\n // TODO: this needs work (Resolve(null) instead?).\r\n subscriber.deferral.resolve(undefined);\r\n // subscriber.deferral.reject(\"Disposed\");\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privSubscribers === subs) {\r\n this.privSubscribers = subs;\r\n }\r\n }\r\n\r\n for (const detachable of this.privDetachables) {\r\n await detachable.detach();\r\n }\r\n\r\n if (this.privPromiseStore.length() > 0 && pendingItemProcessor) {\r\n const promiseArray: Promise[] = [];\r\n\r\n this.privPromiseStore.toArray().forEach((wrapper: Promise) => {\r\n promiseArray.push(wrapper);\r\n });\r\n return Promise.all(promiseArray).finally(() => {\r\n this.privSubscribers = null;\r\n this.privList.forEach((item: TItem, index: number): void => {\r\n pendingItemProcessor(item);\r\n });\r\n this.privList = null;\r\n return;\r\n }).then();\r\n } else {\r\n this.privSubscribers = null;\r\n this.privList = null;\r\n }\r\n }\r\n }\r\n\r\n public async dispose(reason?: string): Promise {\r\n await this.drainAndDispose(null, reason);\r\n }\r\n\r\n private drain = (): void => {\r\n if (!this.privIsDrainInProgress && !this.privIsDisposing) {\r\n this.privIsDrainInProgress = true;\r\n\r\n const subs = this.privSubscribers;\r\n const lists = this.privList;\r\n if (subs && lists) {\r\n while (lists.length() > 0 && subs.length() > 0 && !this.privIsDisposing) {\r\n const subscriber = subs.removeFirst();\r\n if (subscriber.type === SubscriberType.Peek) {\r\n subscriber.deferral.resolve(lists.first());\r\n } else {\r\n const dequeuedItem = lists.removeFirst();\r\n subscriber.deferral.resolve(dequeuedItem);\r\n }\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privSubscribers === subs) {\r\n this.privSubscribers = subs;\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privList === lists) {\r\n this.privList = lists;\r\n }\r\n }\r\n\r\n this.privIsDrainInProgress = false;\r\n }\r\n }\r\n\r\n private throwIfDispose = (): void => {\r\n if (this.isDisposed()) {\r\n if (this.privDisposeReason) {\r\n throw new InvalidOperationError(this.privDisposeReason);\r\n }\r\n\r\n throw new ObjectDisposedError(\"Queue\");\r\n } else if (this.privIsDisposing) {\r\n throw new InvalidOperationError(\"Queue disposing\");\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport enum AudioFormatTag {\r\n PCM = 1,\r\n MuLaw,\r\n Siren,\r\n MP3,\r\n SILKSkype,\r\n OGG_OPUS,\r\n WEBM_OPUS,\r\n ALaw,\r\n}\r\n\r\n/**\r\n * Represents audio stream format used for custom audio input configurations.\r\n * @class AudioStreamFormat\r\n */\r\nexport abstract class AudioStreamFormat {\r\n /**\r\n * Creates an audio stream format object representing the default audio stream\r\n * format (16KHz 16bit mono PCM).\r\n * @member AudioStreamFormat.getDefaultInputFormat\r\n * @function\r\n * @public\r\n * @returns {AudioStreamFormat} The audio stream format being created.\r\n */\r\n public static getDefaultInputFormat(): AudioStreamFormat {\r\n return AudioStreamFormatImpl.getDefaultInputFormat();\r\n }\r\n\r\n /**\r\n * Creates an audio stream format object with the specified pcm waveformat characteristics.\r\n * @member AudioStreamFormat.getWaveFormatPCM\r\n * @function\r\n * @public\r\n * @param {number} samplesPerSecond - Sample rate, in samples per second (Hertz).\r\n * @param {number} bitsPerSample - Bits per sample, typically 16.\r\n * @param {number} channels - Number of channels in the waveform-audio data. Monaural data\r\n * uses one channel and stereo data uses two channels.\r\n * @returns {AudioStreamFormat} The audio stream format being created.\r\n */\r\n public static getWaveFormatPCM(samplesPerSecond: number, bitsPerSample: number, channels: number): AudioStreamFormat {\r\n return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels);\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioStreamFormat.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * @private\r\n * @class AudioStreamFormatImpl\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class AudioStreamFormatImpl extends AudioStreamFormat {\r\n protected privHeader: ArrayBuffer;\r\n\r\n /**\r\n * Creates an instance with the given values.\r\n * @constructor\r\n * @param {number} samplesPerSec - Samples per second.\r\n * @param {number} bitsPerSample - Bits per sample.\r\n * @param {number} channels - Number of channels.\r\n * @param {AudioFormatTag} format - Audio format (PCM, alaw or mulaw).\r\n */\r\n public constructor(samplesPerSec: number = 16000, bitsPerSample: number = 16, channels: number = 1, format: AudioFormatTag = AudioFormatTag.PCM) {\r\n super();\r\n /* 1 for PCM; 6 for alaw; 7 for mulaw */\r\n switch (format) {\r\n case AudioFormatTag.PCM:\r\n this.formatTag = 1;\r\n break;\r\n case AudioFormatTag.ALaw:\r\n this.formatTag = 6;\r\n break;\r\n case AudioFormatTag.MuLaw:\r\n this.formatTag = 7;\r\n break;\r\n default:\r\n }\r\n this.bitsPerSample = bitsPerSample;\r\n this.samplesPerSec = samplesPerSec;\r\n this.channels = channels;\r\n this.avgBytesPerSec = this.samplesPerSec * this.channels * (this.bitsPerSample / 8);\r\n this.blockAlign = this.channels * Math.max(this.bitsPerSample, 8);\r\n\r\n this.privHeader = new ArrayBuffer(44);\r\n\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView\r\n const view = new DataView(this.privHeader);\r\n\r\n /* RIFF identifier */\r\n this.setString(view, 0, \"RIFF\");\r\n /* file length */\r\n view.setUint32(4, 0, true);\r\n /* RIFF type & Format */\r\n this.setString(view, 8, \"WAVEfmt \");\r\n /* format chunk length */\r\n view.setUint32(16, 16, true);\r\n /* audio format */\r\n view.setUint16(20, this.formatTag, true);\r\n /* channel count */\r\n view.setUint16(22, this.channels, true);\r\n /* sample rate */\r\n view.setUint32(24, this.samplesPerSec, true);\r\n /* byte rate (sample rate * block align) */\r\n view.setUint32(28, this.avgBytesPerSec, true);\r\n /* block align (channel count * bytes per sample) */\r\n view.setUint16(32, this.channels * (this.bitsPerSample / 8), true);\r\n /* bits per sample */\r\n view.setUint16(34, this.bitsPerSample, true);\r\n /* data chunk identifier */\r\n this.setString(view, 36, \"data\");\r\n /* data chunk length */\r\n view.setUint32(40, 0, true);\r\n }\r\n\r\n /**\r\n * Retrieves the default input format.\r\n * @member AudioStreamFormatImpl.getDefaultInputFormat\r\n * @function\r\n * @public\r\n * @returns {AudioStreamFormatImpl} The default input format.\r\n */\r\n public static getDefaultInputFormat(): AudioStreamFormatImpl {\r\n return new AudioStreamFormatImpl();\r\n }\r\n\r\n /**\r\n * Creates an audio context appropriate to current browser\r\n * @member AudioStreamFormatImpl.getAudioContext\r\n * @function\r\n * @public\r\n * @returns {AudioContext} An audio context instance\r\n */\r\n public static getAudioContext(sampleRate?: number): AudioContext {\r\n // Workaround for Speech SDK bug in Safari.\r\n const AudioContext = (window as any).AudioContext // our preferred impl\r\n || (window as any).webkitAudioContext // fallback, mostly when on Safari\r\n || false; // could not find.\r\n\r\n // https://developer.mozilla.org/en-US/docs/Web/API/AudioContext\r\n if (!!AudioContext) {\r\n if (sampleRate !== undefined && navigator.mediaDevices.getSupportedConstraints().sampleRate) {\r\n return new AudioContext({ sampleRate });\r\n } else {\r\n return new AudioContext();\r\n }\r\n } else {\r\n throw new Error(\"Browser does not support Web Audio API (AudioContext is not available).\");\r\n }\r\n }\r\n\r\n /**\r\n * Closes the configuration object.\r\n * @member AudioStreamFormatImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void { return; }\r\n\r\n /**\r\n * The format of the audio, valid values: 1 (PCM)\r\n * @member AudioStreamFormatImpl.prototype.formatTag\r\n * @function\r\n * @public\r\n */\r\n public formatTag: number;\r\n\r\n /**\r\n * The number of channels, valid values: 1 (Mono).\r\n * @member AudioStreamFormatImpl.prototype.channels\r\n * @function\r\n * @public\r\n */\r\n public channels: number;\r\n\r\n /**\r\n * The sample rate, valid values: 16000.\r\n * @member AudioStreamFormatImpl.prototype.samplesPerSec\r\n * @function\r\n * @public\r\n */\r\n public samplesPerSec: number;\r\n\r\n /**\r\n * The bits per sample, valid values: 16\r\n * @member AudioStreamFormatImpl.prototype.b\r\n * @function\r\n * @public\r\n */\r\n public bitsPerSample: number;\r\n\r\n /**\r\n * Average bytes per second, usually calculated as nSamplesPerSec * nChannels * ceil(wBitsPerSample, 8).\r\n * @member AudioStreamFormatImpl.prototype.avgBytesPerSec\r\n * @function\r\n * @public\r\n */\r\n public avgBytesPerSec: number;\r\n\r\n /**\r\n * The size of a single frame, valid values: nChannels * ceil(wBitsPerSample, 8).\r\n * @member AudioStreamFormatImpl.prototype.blockAlign\r\n * @function\r\n * @public\r\n */\r\n public blockAlign: number;\r\n\r\n public get header(): ArrayBuffer {\r\n return this.privHeader;\r\n }\r\n\r\n protected setString = (view: DataView, offset: number, str: string): void => {\r\n for (let i = 0; i < str.length; i++) {\r\n view.setUint8(offset + i, str.charCodeAt(i));\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError } from \"./Error\";\r\nimport { createNoDashGuid } from \"./Guid\";\r\nimport { Queue } from \"./Queue\";\r\n\r\nexport interface IStreamChunk {\r\n isEnd: boolean;\r\n buffer: TBuffer;\r\n timeReceived: number;\r\n}\r\n\r\nexport class Stream {\r\n private privId: string;\r\n private privIsWriteEnded: boolean = false;\r\n private privIsReadEnded: boolean = false;\r\n private privReaderQueue: Queue>;\r\n\r\n public constructor(streamId?: string) {\r\n this.privId = streamId ? streamId : createNoDashGuid();\r\n this.privReaderQueue = new Queue>();\r\n }\r\n\r\n public get isClosed(): boolean {\r\n return this.privIsWriteEnded;\r\n }\r\n\r\n public get isReadEnded(): boolean {\r\n return this.privIsReadEnded;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n\r\n public close(): void {\r\n if (!this.privIsWriteEnded) {\r\n this.writeStreamChunk({\r\n buffer: null,\r\n isEnd: true,\r\n timeReceived: Date.now(),\r\n });\r\n this.privIsWriteEnded = true;\r\n }\r\n }\r\n\r\n public writeStreamChunk(streamChunk: IStreamChunk): void {\r\n this.throwIfClosed();\r\n if (!this.privReaderQueue.isDisposed()) {\r\n try {\r\n this.privReaderQueue.enqueue(streamChunk);\r\n } catch (e) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n\r\n public read = (): Promise> => {\r\n if (this.privIsReadEnded) {\r\n throw new InvalidOperationError(\"Stream read has already finished\");\r\n }\r\n\r\n return this.privReaderQueue\r\n .dequeue()\r\n .then(async (streamChunk: IStreamChunk) => {\r\n if (streamChunk === undefined || streamChunk.isEnd) {\r\n await this.privReaderQueue.dispose(\"End of stream reached\");\r\n }\r\n\r\n return streamChunk;\r\n });\r\n }\r\n public readEnded = (): void => {\r\n if (!this.privIsReadEnded) {\r\n this.privIsReadEnded = true;\r\n this.privReaderQueue = new Queue>();\r\n }\r\n }\r\n\r\n private throwIfClosed = (): void => {\r\n if (this.privIsWriteEnded) {\r\n throw new InvalidOperationError(\"Stream closed\");\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IStreamChunk, Stream } from \"./Exports\";\r\n\r\nexport class ChunkedArrayBufferStream extends Stream {\r\n private privTargetChunkSize: number;\r\n private privNextBufferToWrite: ArrayBuffer;\r\n private privNextBufferStartTime: number;\r\n private privNextBufferReadyBytes: number;\r\n\r\n constructor(targetChunkSize: number, streamId?: string) {\r\n super(streamId);\r\n this.privTargetChunkSize = targetChunkSize;\r\n this.privNextBufferReadyBytes = 0;\r\n }\r\n\r\n public writeStreamChunk(chunk: IStreamChunk): void {\r\n // No pending write, and the buffer is the right size so write it.\r\n if (chunk.isEnd ||\r\n (0 === this.privNextBufferReadyBytes && chunk.buffer.byteLength === this.privTargetChunkSize)) {\r\n super.writeStreamChunk(chunk);\r\n return;\r\n }\r\n\r\n let bytesCopiedFromBuffer: number = 0;\r\n\r\n while (bytesCopiedFromBuffer < chunk.buffer.byteLength) {\r\n // Fill the next buffer.\r\n if (undefined === this.privNextBufferToWrite) {\r\n this.privNextBufferToWrite = new ArrayBuffer(this.privTargetChunkSize);\r\n this.privNextBufferStartTime = chunk.timeReceived;\r\n }\r\n\r\n // Find out how many bytes we can copy into the read buffer.\r\n const bytesToCopy: number = Math.min(chunk.buffer.byteLength - bytesCopiedFromBuffer, this.privTargetChunkSize - this.privNextBufferReadyBytes);\r\n const targetView: Uint8Array = new Uint8Array(this.privNextBufferToWrite);\r\n const sourceView: Uint8Array = new Uint8Array(chunk.buffer.slice(bytesCopiedFromBuffer, bytesToCopy + bytesCopiedFromBuffer));\r\n\r\n targetView.set(sourceView, this.privNextBufferReadyBytes);\r\n this.privNextBufferReadyBytes += bytesToCopy;\r\n bytesCopiedFromBuffer += bytesToCopy;\r\n\r\n // Are we ready to write?\r\n if (this.privNextBufferReadyBytes === this.privTargetChunkSize) {\r\n super.writeStreamChunk({\r\n buffer: this.privNextBufferToWrite,\r\n isEnd: false,\r\n timeReceived: this.privNextBufferStartTime,\r\n });\r\n this.privNextBufferReadyBytes = 0;\r\n this.privNextBufferToWrite = undefined;\r\n }\r\n }\r\n }\r\n\r\n public close(): void {\r\n // Send whatever is pending, then close the base class.\r\n if (0 !== this.privNextBufferReadyBytes && !this.isClosed) {\r\n super.writeStreamChunk({\r\n buffer: this.privNextBufferToWrite.slice(0, this.privNextBufferReadyBytes),\r\n isEnd: false,\r\n timeReceived: this.privNextBufferStartTime,\r\n });\r\n }\r\n\r\n super.close();\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n connectivity,\r\n ISpeechConfigAudioDevice,\r\n type\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n AudioSourceErrorEvent,\r\n AudioSourceEvent,\r\n AudioSourceInitializingEvent,\r\n AudioSourceOffEvent,\r\n AudioSourceReadyEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n AudioStreamNodeErrorEvent,\r\n ChunkedArrayBufferStream,\r\n createNoDashGuid,\r\n Deferred,\r\n Events,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IStringDictionary,\r\n Stream,\r\n} from \"../common/Exports\";\r\nimport {\r\n AudioStreamFormat,\r\n AudioStreamFormatImpl,\r\n} from \"../sdk/Audio/AudioStreamFormat\";\r\nimport { IRecorder } from \"./IRecorder\";\r\n\r\n// Extending the default definition with browser specific definitions for backward compatibility\r\ninterface INavigator extends Navigator {\r\n webkitGetUserMedia?: (constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback) => void;\r\n mozGetUserMedia?: (constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback) => void;\r\n msGetUserMedia?: (constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback) => void;\r\n}\r\n\r\nexport const AudioWorkletSourceURLPropertyName = \"MICROPHONE-WorkletSourceUrl\";\r\n\r\nexport class MicAudioSource implements IAudioSource {\r\n\r\n private static readonly AUDIOFORMAT: AudioStreamFormatImpl = AudioStreamFormat.getDefaultInputFormat() as AudioStreamFormatImpl;\r\n\r\n private privStreams: IStringDictionary> = {};\r\n\r\n private privId: string;\r\n\r\n private privEvents: EventSource;\r\n\r\n private privInitializeDeferral: Deferred;\r\n\r\n private privMediaStream: MediaStream;\r\n\r\n private privContext: AudioContext;\r\n\r\n private privMicrophoneLabel: string;\r\n\r\n private privOutputChunkSize: number;\r\n\r\n public constructor(\r\n private readonly privRecorder: IRecorder,\r\n private readonly deviceId?: string,\r\n audioSourceId?: string,\r\n mediaStream?: MediaStream\r\n ) {\r\n\r\n this.privOutputChunkSize = MicAudioSource.AUDIOFORMAT.avgBytesPerSec / 10;\r\n this.privId = audioSourceId ? audioSourceId : createNoDashGuid();\r\n this.privEvents = new EventSource();\r\n this.privMediaStream = mediaStream || null;\r\n }\r\n\r\n public get format(): Promise {\r\n return Promise.resolve(MicAudioSource.AUDIOFORMAT);\r\n }\r\n\r\n public get blob(): Promise {\r\n return Promise.reject(\"Not implemented for Mic input\");\r\n }\r\n\r\n public turnOn = (): Promise => {\r\n if (this.privInitializeDeferral) {\r\n return this.privInitializeDeferral.promise;\r\n }\r\n\r\n this.privInitializeDeferral = new Deferred();\r\n\r\n try {\r\n this.createAudioContext();\r\n } catch (error) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n this.privInitializeDeferral.reject(typedError.name + \": \" + typedError.message);\r\n } else {\r\n this.privInitializeDeferral.reject(error);\r\n }\r\n return this.privInitializeDeferral.promise;\r\n }\r\n\r\n const nav = window.navigator as INavigator;\r\n\r\n let getUserMedia = (\r\n nav.getUserMedia ||\r\n nav.webkitGetUserMedia ||\r\n nav.mozGetUserMedia ||\r\n nav.msGetUserMedia\r\n );\r\n\r\n if (!!nav.mediaDevices) {\r\n getUserMedia = (constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void => {\r\n nav.mediaDevices\r\n .getUserMedia(constraints)\r\n .then(successCallback)\r\n .catch(errorCallback);\r\n };\r\n }\r\n\r\n if (!getUserMedia) {\r\n const errorMsg = \"Browser does not support getUserMedia.\";\r\n this.privInitializeDeferral.reject(errorMsg);\r\n this.onEvent(new AudioSourceErrorEvent(errorMsg, \"\")); // mic initialized error - no streamid at this point\r\n } else {\r\n const next = () => {\r\n this.onEvent(new AudioSourceInitializingEvent(this.privId)); // no stream id\r\n if (this.privMediaStream && this.privMediaStream.active) {\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n this.privInitializeDeferral.resolve();\r\n } else {\r\n getUserMedia(\r\n { audio: this.deviceId ? { deviceId: this.deviceId } : true, video: false },\r\n (mediaStream: MediaStream) => {\r\n this.privMediaStream = mediaStream;\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n this.privInitializeDeferral.resolve();\r\n }, (error: MediaStreamError) => {\r\n const errorMsg = `Error occurred during microphone initialization: ${error}`;\r\n this.privInitializeDeferral.reject(errorMsg);\r\n this.onEvent(new AudioSourceErrorEvent(this.privId, errorMsg));\r\n });\r\n }\r\n };\r\n\r\n if (this.privContext.state === \"suspended\") {\r\n // NOTE: On iOS, the Web Audio API requires sounds to be triggered from an explicit user action.\r\n // https://github.com/WebAudio/web-audio-api/issues/790\r\n this.privContext.resume()\r\n .then(next)\r\n .catch((reason: any) => {\r\n this.privInitializeDeferral.reject(`Failed to initialize audio context: ${reason}`);\r\n });\r\n } else {\r\n next();\r\n }\r\n }\r\n\r\n return this.privInitializeDeferral.promise;\r\n }\r\n\r\n public id = (): string => {\r\n return this.privId;\r\n }\r\n\r\n public attach = (audioNodeId: string): Promise => {\r\n this.onEvent(new AudioStreamNodeAttachingEvent(this.privId, audioNodeId));\r\n\r\n return this.listen(audioNodeId).then(\r\n (stream: Stream) => {\r\n this.onEvent(new AudioStreamNodeAttachedEvent(this.privId, audioNodeId));\r\n return {\r\n detach: async () => {\r\n stream.readEnded();\r\n delete this.privStreams[audioNodeId];\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n return this.turnOff();\r\n },\r\n id: () => {\r\n return audioNodeId;\r\n },\r\n read: () => {\r\n return stream.read();\r\n },\r\n };\r\n });\r\n }\r\n\r\n public detach = (audioNodeId: string): void => {\r\n if (audioNodeId && this.privStreams[audioNodeId]) {\r\n this.privStreams[audioNodeId].close();\r\n delete this.privStreams[audioNodeId];\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n }\r\n }\r\n\r\n public async turnOff(): Promise {\r\n for (const streamId in this.privStreams) {\r\n if (streamId) {\r\n const stream = this.privStreams[streamId];\r\n if (stream) {\r\n stream.close();\r\n }\r\n }\r\n }\r\n\r\n this.onEvent(new AudioSourceOffEvent(this.privId)); // no stream now\r\n if (this.privInitializeDeferral) {\r\n // Correctly handle when browser forces mic off before turnOn() completes\r\n await this.privInitializeDeferral;\r\n this.privInitializeDeferral = null;\r\n }\r\n\r\n await this.destroyAudioContext();\r\n\r\n return;\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privEvents;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return this.getMicrophoneLabel().then((label: string) => {\r\n return {\r\n bitspersample: MicAudioSource.AUDIOFORMAT.bitsPerSample,\r\n channelcount: MicAudioSource.AUDIOFORMAT.channels,\r\n connectivity: connectivity.Unknown,\r\n manufacturer: \"Speech SDK\",\r\n model: label,\r\n samplerate: MicAudioSource.AUDIOFORMAT.samplesPerSec,\r\n type: type.Microphones,\r\n };\r\n });\r\n }\r\n\r\n public setProperty(name: string, value: string): void {\r\n if (name === AudioWorkletSourceURLPropertyName) {\r\n this.privRecorder.setWorkletUrl(value);\r\n } else {\r\n throw new Error(\"Property '\" + name + \"' is not supported on Microphone.\");\r\n }\r\n }\r\n\r\n private getMicrophoneLabel(): Promise {\r\n const defaultMicrophoneName: string = \"microphone\";\r\n\r\n // If we did this already, return the value.\r\n if (this.privMicrophoneLabel !== undefined) {\r\n return Promise.resolve(this.privMicrophoneLabel);\r\n }\r\n\r\n // If the stream isn't currently running, we can't query devices because security.\r\n if (this.privMediaStream === undefined || !this.privMediaStream.active) {\r\n return Promise.resolve(defaultMicrophoneName);\r\n }\r\n\r\n // Setup a default\r\n this.privMicrophoneLabel = defaultMicrophoneName;\r\n\r\n // Get the id of the device running the audio track.\r\n const microphoneDeviceId: string = this.privMediaStream.getTracks()[0].getSettings().deviceId;\r\n\r\n // If the browser doesn't support getting the device ID, set a default and return.\r\n if (undefined === microphoneDeviceId) {\r\n return Promise.resolve(this.privMicrophoneLabel);\r\n }\r\n\r\n const deferred: Deferred = new Deferred();\r\n\r\n // Enumerate the media devices.\r\n navigator.mediaDevices.enumerateDevices().then((devices: MediaDeviceInfo[]) => {\r\n for (const device of devices) {\r\n if (device.deviceId === microphoneDeviceId) {\r\n // Found the device\r\n this.privMicrophoneLabel = device.label;\r\n break;\r\n }\r\n }\r\n deferred.resolve(this.privMicrophoneLabel);\r\n }, () => deferred.resolve(this.privMicrophoneLabel));\r\n\r\n return deferred.promise;\r\n }\r\n\r\n private listen = async (audioNodeId: string): Promise> => {\r\n await this.turnOn();\r\n const stream = new ChunkedArrayBufferStream(this.privOutputChunkSize, audioNodeId);\r\n this.privStreams[audioNodeId] = stream;\r\n try {\r\n this.privRecorder.record(this.privContext, this.privMediaStream, stream);\r\n } catch (error) {\r\n this.onEvent(new AudioStreamNodeErrorEvent(this.privId, audioNodeId, error));\r\n throw error;\r\n }\r\n const result: Stream = stream;\r\n return result;\r\n }\r\n\r\n private onEvent = (event: AudioSourceEvent): void => {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private createAudioContext = (): void => {\r\n if (!!this.privContext) {\r\n return;\r\n }\r\n\r\n this.privContext = AudioStreamFormatImpl.getAudioContext(MicAudioSource.AUDIOFORMAT.samplesPerSec);\r\n }\r\n\r\n private async destroyAudioContext(): Promise {\r\n if (!this.privContext) {\r\n return;\r\n }\r\n\r\n this.privRecorder.releaseMediaResources(this.privContext);\r\n\r\n // This pattern brought to you by a bug in the TypeScript compiler where it\r\n // confuses the (\"close\" in this.privContext) with this.privContext always being null as the alternate.\r\n // https://github.com/Microsoft/TypeScript/issues/11498\r\n let hasClose: boolean = false;\r\n if (\"close\" in this.privContext) {\r\n hasClose = true;\r\n }\r\n\r\n if (hasClose) {\r\n await this.privContext.close();\r\n this.privContext = null;\r\n } else if (null !== this.privContext && this.privContext.state === \"running\") {\r\n // Suspend actually takes a callback, but analogous to the\r\n // resume method, it'll be only fired if suspend is called\r\n // in a direct response to a user action. The later is not always\r\n // the case, as TurnOff is also called, when we receive an\r\n // end-of-speech message from the service. So, doing a best effort\r\n // fire-and-forget here.\r\n await this.privContext.suspend();\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n connectivity,\r\n ISpeechConfigAudioDevice,\r\n type,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n AudioSourceErrorEvent,\r\n AudioSourceEvent,\r\n AudioSourceInitializingEvent,\r\n AudioSourceOffEvent,\r\n AudioSourceReadyEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n AudioStreamNodeErrorEvent,\r\n ChunkedArrayBufferStream,\r\n createNoDashGuid,\r\n Deferred,\r\n Events,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IStreamChunk,\r\n IStringDictionary,\r\n Stream,\r\n} from \"../common/Exports\";\r\nimport { AudioStreamFormat, AudioStreamFormatImpl } from \"../sdk/Audio/AudioStreamFormat\";\r\n\r\nexport class FileAudioSource implements IAudioSource {\r\n\r\n private privAudioFormatPromise: Promise;\r\n\r\n private privStreams: IStringDictionary> = {};\r\n\r\n private privId: string;\r\n\r\n private privEvents: EventSource;\r\n\r\n private privSource: Blob | Buffer;\r\n\r\n private privFilename: string;\r\n\r\n private privHeaderEnd: number = 44;\r\n\r\n public constructor(file: File | Buffer, filename?: string, audioSourceId?: string) {\r\n this.privId = audioSourceId ? audioSourceId : createNoDashGuid();\r\n this.privEvents = new EventSource();\r\n this.privSource = file;\r\n if (typeof window !== \"undefined\" && typeof Blob !== \"undefined\" && this.privSource instanceof Blob) {\r\n this.privFilename = (file as File).name;\r\n } else {\r\n this.privFilename = filename || \"unknown.wav\";\r\n }\r\n\r\n // Read the header.\r\n this.privAudioFormatPromise = this.readHeader();\r\n }\r\n\r\n public get format(): Promise {\r\n return this.privAudioFormatPromise;\r\n }\r\n\r\n public get blob(): Promise {\r\n return Promise.resolve(this.privSource);\r\n }\r\n\r\n public turnOn = (): Promise => {\r\n if (this.privFilename.lastIndexOf(\".wav\") !== this.privFilename.length - 4) {\r\n const errorMsg = this.privFilename + \" is not supported. Only WAVE files are allowed at the moment.\";\r\n this.onEvent(new AudioSourceErrorEvent(errorMsg, \"\"));\r\n return Promise.reject(errorMsg);\r\n }\r\n\r\n this.onEvent(new AudioSourceInitializingEvent(this.privId)); // no stream id\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n return;\r\n }\r\n\r\n public id = (): string => {\r\n return this.privId;\r\n }\r\n\r\n public attach = async (audioNodeId: string): Promise => {\r\n this.onEvent(new AudioStreamNodeAttachingEvent(this.privId, audioNodeId));\r\n\r\n const stream: Stream = await this.upload(audioNodeId);\r\n\r\n this.onEvent(new AudioStreamNodeAttachedEvent(this.privId, audioNodeId));\r\n return Promise.resolve({\r\n detach: async (): Promise => {\r\n stream.readEnded();\r\n delete this.privStreams[audioNodeId];\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n await this.turnOff();\r\n },\r\n id: () => {\r\n return audioNodeId;\r\n },\r\n read: (): Promise> => {\r\n return stream.read();\r\n },\r\n });\r\n }\r\n\r\n public detach = (audioNodeId: string): void => {\r\n if (audioNodeId && this.privStreams[audioNodeId]) {\r\n this.privStreams[audioNodeId].close();\r\n delete this.privStreams[audioNodeId];\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n }\r\n }\r\n\r\n public turnOff = (): Promise => {\r\n for (const streamId in this.privStreams) {\r\n if (streamId) {\r\n const stream = this.privStreams[streamId];\r\n if (stream && !stream.isClosed) {\r\n stream.close();\r\n }\r\n }\r\n }\r\n\r\n this.onEvent(new AudioSourceOffEvent(this.privId)); // no stream now\r\n return Promise.resolve();\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privEvents;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return this.privAudioFormatPromise.then((result: AudioStreamFormatImpl) => {\r\n return Promise.resolve({\r\n bitspersample: result.bitsPerSample,\r\n channelcount: result.channels,\r\n connectivity: connectivity.Unknown,\r\n manufacturer: \"Speech SDK\",\r\n model: \"File\",\r\n samplerate: result.samplesPerSec,\r\n type: type.File,\r\n });\r\n });\r\n }\r\n\r\n private readHeader(): Promise {\r\n // Read the wave header.\r\n const maxHeaderSize: number = 512;\r\n const header: Blob | Buffer = this.privSource.slice(0, maxHeaderSize);\r\n\r\n const headerResult: Deferred = new Deferred();\r\n\r\n const processHeader = (header: ArrayBuffer): void => {\r\n const view: DataView = new DataView(header);\r\n\r\n const getWord = (index: number): string => {\r\n return String.fromCharCode(view.getUint8(index), view.getUint8(index + 1), view.getUint8(index + 2), view.getUint8(index + 3));\r\n };\r\n\r\n // RIFF 4 bytes.\r\n if (\"RIFF\" !== getWord(0)) {\r\n headerResult.reject(\"Invalid WAV header in file, RIFF was not found\");\r\n return;\r\n }\r\n\r\n // length, 4 bytes\r\n // RIFF Type & fmt 8 bytes\r\n if (\"WAVE\" !== getWord(8) || \"fmt \" !== getWord(12)) {\r\n headerResult.reject(\"Invalid WAV header in file, WAVEfmt was not found\");\r\n return;\r\n }\r\n\r\n const formatSize: number = view.getInt32(16, true);\r\n const channelCount: number = view.getUint16(22, true);\r\n const sampleRate: number = view.getUint32(24, true);\r\n const bitsPerSample: number = view.getUint16(34, true);\r\n // Confirm if header is 44 bytes long.\r\n let pos: number = 36 + Math.max(formatSize - 16, 0);\r\n for (; getWord(pos) !== \"data\"; pos += 2) {\r\n if (pos > maxHeaderSize - 8) {\r\n headerResult.reject(\"Invalid WAV header in file, data block was not found\");\r\n return;\r\n }\r\n }\r\n this.privHeaderEnd = pos + 8;\r\n headerResult.resolve(AudioStreamFormat.getWaveFormatPCM(sampleRate, bitsPerSample, channelCount) as AudioStreamFormatImpl);\r\n };\r\n\r\n if (typeof window !== \"undefined\" && typeof Blob !== \"undefined\" && header instanceof Blob) {\r\n const reader: FileReader = new FileReader();\r\n\r\n reader.onload = (event: Event) => {\r\n const header: ArrayBuffer = (event.target as FileReader).result as ArrayBuffer;\r\n processHeader(header);\r\n };\r\n\r\n reader.readAsArrayBuffer(header);\r\n } else {\r\n const h: Buffer = header as Buffer;\r\n processHeader(h.buffer.slice(h.byteOffset, h.byteOffset + h.byteLength));\r\n }\r\n return headerResult.promise;\r\n }\r\n\r\n private async upload(audioNodeId: string): Promise> {\r\n const onerror = (error: string) => {\r\n const errorMsg = `Error occurred while processing '${this.privFilename}'. ${error}`;\r\n this.onEvent(new AudioStreamNodeErrorEvent(this.privId, audioNodeId, errorMsg));\r\n throw new Error(errorMsg);\r\n };\r\n\r\n try {\r\n await this.turnOn();\r\n\r\n const format: AudioStreamFormatImpl = await this.privAudioFormatPromise;\r\n const stream = new ChunkedArrayBufferStream(format.avgBytesPerSec / 10, audioNodeId);\r\n\r\n this.privStreams[audioNodeId] = stream;\r\n const chunk: Blob | Buffer = this.privSource.slice(this.privHeaderEnd);\r\n\r\n const processFile = (buff: ArrayBuffer): void => {\r\n if (stream.isClosed) {\r\n return; // output stream was closed (somebody called TurnOff). We're done here.\r\n }\r\n\r\n stream.writeStreamChunk({\r\n buffer: buff,\r\n isEnd: false,\r\n timeReceived: Date.now(),\r\n });\r\n stream.close();\r\n };\r\n\r\n if (typeof window !== \"undefined\" && typeof Blob !== \"undefined\" && chunk instanceof Blob) {\r\n const reader: FileReader = new FileReader();\r\n reader.onerror = (ev: ProgressEvent) => { onerror(ev.toString()); };\r\n\r\n reader.onload = (event: Event) => {\r\n const fileBuffer: ArrayBuffer = (event.target as FileReader).result as ArrayBuffer;\r\n processFile(fileBuffer);\r\n };\r\n\r\n reader.readAsArrayBuffer(chunk);\r\n } else {\r\n const c: Buffer = chunk as Buffer;\r\n processFile(c.buffer.slice(c.byteOffset, c.byteOffset + c.byteLength));\r\n }\r\n\r\n return stream;\r\n } catch (e) {\r\n onerror(e);\r\n }\r\n }\r\n\r\n private onEvent = (event: AudioSourceEvent): void => {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * @class Contracts\r\n * @private\r\n */\r\nexport class Contracts {\r\n public static throwIfNullOrUndefined(param: any, name: string): void {\r\n if (param === undefined || param === null) {\r\n throw new Error(\"throwIfNullOrUndefined:\" + name);\r\n }\r\n }\r\n\r\n public static throwIfNull(param: any, name: string): void {\r\n if (param === null) {\r\n throw new Error(\"throwIfNull:\" + name);\r\n }\r\n }\r\n\r\n public static throwIfNullOrWhitespace(param: string, name: string): void {\r\n Contracts.throwIfNullOrUndefined(param, name);\r\n\r\n if ((\"\" + param).trim().length < 1) {\r\n throw new Error(\"throwIfNullOrWhitespace:\" + name);\r\n }\r\n }\r\n\r\n public static throwIfDisposed(isDisposed: boolean): void {\r\n if (isDisposed) {\r\n throw new Error(\"the object is already disposed\");\r\n }\r\n }\r\n\r\n public static throwIfArrayEmptyOrWhitespace(array: string[], name: string): void {\r\n Contracts.throwIfNullOrUndefined(array, name);\r\n\r\n if (array.length === 0) {\r\n throw new Error(\"throwIfArrayEmptyOrWhitespace:\" + name);\r\n }\r\n\r\n for (const item of array) {\r\n Contracts.throwIfNullOrWhitespace(item, name);\r\n }\r\n }\r\n\r\n public static throwIfFileDoesNotExist(param: any, name: string): void {\r\n Contracts.throwIfNullOrWhitespace(param, name);\r\n\r\n // TODO check for file existence.\r\n }\r\n\r\n public static throwIfNotUndefined(param: any, name: string): void {\r\n if (param !== undefined) {\r\n throw new Error(\"throwIfNotUndefined:\" + name);\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n /**\r\n * An abstract base class that defines callback methods (read() and close()) for\r\n * custom audio input streams).\r\n * @class PullAudioInputStreamCallback\r\n */\r\nexport abstract class PullAudioInputStreamCallback {\r\n\r\n /**\r\n * Reads data from audio input stream into the data buffer. The maximal number of bytes\r\n * to be read is determined by the size of dataBuffer.\r\n * @member PullAudioInputStreamCallback.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The byte array to store the read data.\r\n * @returns {number} the number of bytes have been read.\r\n */\r\n public abstract read(dataBuffer: ArrayBuffer): number;\r\n\r\n /**\r\n * Closes the audio input stream.\r\n * @member PullAudioInputStreamCallback.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError } from \"./Error\";\r\nimport { createNoDashGuid } from \"./Guid\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\n\r\nexport enum MessageType {\r\n Text,\r\n Binary,\r\n}\r\n\r\nexport class ConnectionMessage {\r\n\r\n private privMessageType: MessageType;\r\n private privHeaders: IStringDictionary;\r\n private privBody: any = null;\r\n private privSize: number;\r\n\r\n private privId: string;\r\n\r\n public constructor(\r\n messageType: MessageType,\r\n body: any,\r\n headers?: IStringDictionary,\r\n id?: string) {\r\n\r\n if (messageType === MessageType.Text && body && !(typeof (body) === \"string\")) {\r\n throw new InvalidOperationError(\"Payload must be a string\");\r\n }\r\n\r\n if (messageType === MessageType.Binary && body && !(body instanceof ArrayBuffer)) {\r\n throw new InvalidOperationError(\"Payload must be ArrayBuffer\");\r\n }\r\n\r\n this.privMessageType = messageType;\r\n this.privBody = body;\r\n this.privHeaders = headers ? headers : {};\r\n this.privId = id ? id : createNoDashGuid();\r\n switch (this.messageType) {\r\n case MessageType.Binary:\r\n this.privSize = this.binaryBody !== null ? this.binaryBody.byteLength : 0;\r\n break;\r\n case MessageType.Text:\r\n this.privSize = this.textBody.length;\r\n }\r\n }\r\n\r\n public get messageType(): MessageType {\r\n return this.privMessageType;\r\n }\r\n\r\n public get headers(): IStringDictionary {\r\n return this.privHeaders;\r\n }\r\n\r\n public get body(): any {\r\n return this.privBody;\r\n }\r\n\r\n public get textBody(): string {\r\n if (this.privMessageType === MessageType.Binary) {\r\n throw new InvalidOperationError(\"Not supported for binary message\");\r\n }\r\n\r\n return this.privBody as string;\r\n }\r\n\r\n public get binaryBody(): ArrayBuffer {\r\n if (this.privMessageType === MessageType.Text) {\r\n throw new InvalidOperationError(\"Not supported for text message\");\r\n }\r\n\r\n return this.privBody;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ConnectionEvent } from \"./ConnectionEvents\";\r\nimport { ConnectionMessage } from \"./ConnectionMessage\";\r\nimport { ConnectionOpenResponse } from \"./ConnectionOpenResponse\";\r\nimport { EventSource } from \"./EventSource\";\r\n\r\nexport enum ConnectionState {\r\n None,\r\n Connected,\r\n Connecting,\r\n Disconnected,\r\n}\r\n\r\nexport interface IConnection {\r\n id: string;\r\n state(): ConnectionState;\r\n open(): Promise;\r\n send(message: ConnectionMessage): Promise;\r\n read(): Promise;\r\n events: EventSource;\r\n dispose(disposing?: string): Promise;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the possible reasons a recognition result might be canceled.\r\n * @class CancellationReason\r\n */\r\nexport enum CancellationReason {\r\n /**\r\n * Indicates that an error occurred during speech recognition.\r\n * @member CancellationReason.Error\r\n */\r\n Error,\r\n\r\n /**\r\n * Indicates that the end of the audio stream was reached.\r\n * @member CancellationReason.EndOfStream\r\n */\r\n EndOfStream,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines error code in case that CancellationReason is Error.\r\n * Added in version 1.1.0.\r\n */\r\nexport enum CancellationErrorCode {\r\n /**\r\n * Indicates that no error occurred during speech recognition.\r\n */\r\n NoError,\r\n\r\n /**\r\n * Indicates an authentication error.\r\n */\r\n AuthenticationFailure,\r\n\r\n /**\r\n * Indicates that one or more recognition parameters are invalid.\r\n */\r\n BadRequestParameters,\r\n\r\n /**\r\n * Indicates that the number of parallel requests exceeded the number of allowed\r\n * concurrent transcriptions for the subscription.\r\n */\r\n TooManyRequests,\r\n\r\n /**\r\n * Indicates a connection error.\r\n */\r\n ConnectionFailure,\r\n\r\n /**\r\n * Indicates a time-out error when waiting for response from service.\r\n */\r\n ServiceTimeout,\r\n\r\n /**\r\n * Indicates that an error is returned by the service.\r\n */\r\n ServiceError,\r\n\r\n /**\r\n * Indicates an unexpected runtime error.\r\n */\r\n RuntimeError,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the possible reasons a recognition result might be generated.\r\n * @class ResultReason\r\n */\r\nexport enum ResultReason {\r\n /**\r\n * Indicates speech could not be recognized. More details\r\n * can be found in the NoMatchDetails object.\r\n * @member ResultReason.NoMatch\r\n */\r\n NoMatch,\r\n\r\n /**\r\n * Indicates that the recognition was canceled. More details\r\n * can be found using the CancellationDetails object.\r\n * @member ResultReason.Canceled\r\n */\r\n Canceled,\r\n\r\n /**\r\n * Indicates the speech result contains hypothesis text.\r\n * @member ResultReason.RecognizedSpeech\r\n */\r\n RecognizingSpeech,\r\n\r\n /**\r\n * Indicates the speech result contains final text that has been recognized.\r\n * Speech Recognition is now complete for this phrase.\r\n * @member ResultReason.RecognizedSpeech\r\n */\r\n RecognizedSpeech,\r\n\r\n /**\r\n * Indicates the speech result contains a finalized acceptance of a provided keyword.\r\n * Speech recognition will continue unless otherwise configured.\r\n * @member ResultReason.RecognizedKeyword\r\n */\r\n RecognizedKeyword,\r\n\r\n /**\r\n * Indicates the intent result contains hypothesis text and intent.\r\n * @member ResultReason.RecognizingIntent\r\n */\r\n RecognizingIntent,\r\n\r\n /**\r\n * Indicates the intent result contains final text and intent.\r\n * Speech Recognition and Intent determination are now complete for this phrase.\r\n * @member ResultReason.RecognizedIntent\r\n */\r\n RecognizedIntent,\r\n\r\n /**\r\n * Indicates the translation result contains hypothesis text and its translation(s).\r\n * @member ResultReason.TranslatingSpeech\r\n */\r\n TranslatingSpeech,\r\n\r\n /**\r\n * Indicates the translation result contains final text and corresponding translation(s).\r\n * Speech Recognition and Translation are now complete for this phrase.\r\n * @member ResultReason.TranslatedSpeech\r\n */\r\n TranslatedSpeech,\r\n\r\n /**\r\n * Indicates the synthesized audio result contains a non-zero amount of audio data\r\n * @member ResultReason.SynthesizingAudio\r\n */\r\n SynthesizingAudio,\r\n\r\n /**\r\n * Indicates the synthesized audio is now complete for this phrase.\r\n * @member ResultReason.SynthesizingAudioCompleted\r\n */\r\n SynthesizingAudioCompleted,\r\n\r\n /**\r\n * Indicates the speech synthesis is now started\r\n * @member ResultReason.SynthesizingAudioStarted\r\n */\r\n SynthesizingAudioStarted,\r\n\r\n /**\r\n * Indicates the voice profile is being enrolled and customers need to send more audio to create a voice profile.\r\n * @member ResultReason.EnrollingVoiceProfile\r\n */\r\n EnrollingVoiceProfile,\r\n\r\n /**\r\n * Indicates the voice profile has been enrolled.\r\n * @member ResultReason.EnrolledVoiceProfile\r\n */\r\n EnrolledVoiceProfile,\r\n\r\n /**\r\n * Indicates successful identification of some speakers.\r\n * @member ResultReason.RecognizedSpeakers\r\n */\r\n RecognizedSpeakers,\r\n\r\n /**\r\n * Indicates successfully verified one speaker.\r\n * @member ResultReason.RecognizedSpeaker\r\n */\r\n RecognizedSpeaker,\r\n\r\n /**\r\n * Indicates a voice profile has been reset successfully.\r\n * @member ResultReason.ResetVoiceProfile\r\n */\r\n ResetVoiceProfile,\r\n\r\n /**\r\n * Indicates a voice profile has been deleted successfully.\r\n * @member ResultReason.DeletedVoiceProfile\r\n */\r\n DeletedVoiceProfile,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Define speech synthesis audio output formats.\r\n * @enum SpeechSynthesisOutputFormat\r\n * Updated in version 1.17.0\r\n */\r\nexport enum SpeechSynthesisOutputFormat {\r\n /**\r\n * raw-8khz-8bit-mono-mulaw\r\n * @member SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw,\r\n */\r\n Raw8Khz8BitMonoMULaw,\r\n\r\n /**\r\n * riff-16khz-16kbps-mono-siren\r\n * @note Unsupported by the service. Do not use this value.\r\n * @member SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren\r\n */\r\n Riff16Khz16KbpsMonoSiren ,\r\n\r\n /**\r\n * audio-16khz-16kbps-mono-siren\r\n * @note Unsupported by the service. Do not use this value.\r\n * @member SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren\r\n */\r\n Audio16Khz16KbpsMonoSiren,\r\n\r\n /**\r\n * audio-16khz-32kbitrate-mono-mp3\r\n * @member SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3\r\n */\r\n Audio16Khz32KBitRateMonoMp3,\r\n\r\n /**\r\n * audio-16khz-128kbitrate-mono-mp3\r\n * @member SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3\r\n */\r\n Audio16Khz128KBitRateMonoMp3,\r\n\r\n /**\r\n * audio-16khz-64kbitrate-mono-mp3\r\n * @member SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3\r\n */\r\n Audio16Khz64KBitRateMonoMp3,\r\n\r\n /**\r\n * audio-24khz-48kbitrate-mono-mp3\r\n * @member SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3\r\n */\r\n Audio24Khz48KBitRateMonoMp3,\r\n\r\n /**\r\n * audio-24khz-96kbitrate-mono-mp3\r\n * @member SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3\r\n */\r\n Audio24Khz96KBitRateMonoMp3,\r\n\r\n /**\r\n * audio-24khz-160kbitrate-mono-mp3\r\n * @member SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3\r\n */\r\n Audio24Khz160KBitRateMonoMp3,\r\n\r\n /**\r\n * raw-16khz-16bit-mono-truesilk\r\n * @member SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk\r\n */\r\n Raw16Khz16BitMonoTrueSilk,\r\n\r\n /**\r\n * riff-16khz-16bit-mono-pcm\r\n * @member SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm\r\n */\r\n Riff16Khz16BitMonoPcm,\r\n\r\n /**\r\n * riff-8khz-16bit-mono-pcm\r\n * @member SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm\r\n */\r\n Riff8Khz16BitMonoPcm,\r\n\r\n /**\r\n * riff-24khz-16bit-mono-pcm\r\n * @member SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm\r\n */\r\n Riff24Khz16BitMonoPcm,\r\n\r\n /**\r\n * riff-8khz-8bit-mono-mulaw\r\n * @member SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw\r\n */\r\n Riff8Khz8BitMonoMULaw,\r\n\r\n /**\r\n * raw-16khz-16bit-mono-pcm\r\n * @member SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm\r\n */\r\n Raw16Khz16BitMonoPcm,\r\n\r\n /**\r\n * raw-24khz-16bit-mono-pcm\r\n * @member SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm\r\n */\r\n Raw24Khz16BitMonoPcm,\r\n\r\n /**\r\n * raw-8khz-16bit-mono-pcm\r\n * @member SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm\r\n */\r\n Raw8Khz16BitMonoPcm,\r\n\r\n /**\r\n * ogg-16khz-16bit-mono-opus\r\n * @member SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus\r\n */\r\n Ogg16Khz16BitMonoOpus,\r\n\r\n /**\r\n * ogg-24khz-16bit-mono-opus\r\n * @member SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus\r\n */\r\n Ogg24Khz16BitMonoOpus,\r\n\r\n /**\r\n * raw-48khz-16bit-mono-pcm\r\n * @member SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm\r\n */\r\n Raw48Khz16BitMonoPcm,\r\n\r\n /**\r\n * riff-48khz-16bit-mono-pcm\r\n * @member SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm\r\n */\r\n\r\n Riff48Khz16BitMonoPcm,\r\n /**\r\n * audio-48khz-96kbitrate-mono-mp3\r\n * @member SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3\r\n */\r\n Audio48Khz96KBitRateMonoMp3,\r\n\r\n /**\r\n * audio-48khz-192kbitrate-mono-mp3\r\n * @member SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3\r\n */\r\n Audio48Khz192KBitRateMonoMp3,\r\n\r\n /**\r\n * ogg-48khz-16bit-mono-opus\r\n * Added in version 1.16.0\r\n * @member SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus\r\n */\r\n Ogg48Khz16BitMonoOpus,\r\n\r\n /**\r\n * webm-16khz-16bit-mono-opus\r\n * Added in version 1.16.0\r\n * @member SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus\r\n */\r\n Webm16Khz16BitMonoOpus,\r\n\r\n /**\r\n * webm-24khz-16bit-mono-opus\r\n * Added in version 1.16.0\r\n * @member SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus\r\n */\r\n Webm24Khz16BitMonoOpus,\r\n\r\n /**\r\n * raw-24khz-16bit-mono-truesilk\r\n * Added in version 1.17.0\r\n * @member SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk\r\n */\r\n Raw24Khz16BitMonoTrueSilk,\r\n\r\n /**\r\n * raw-8khz-8bit-mono-alaw\r\n * Added in version 1.17.0\r\n * @member SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw\r\n */\r\n Raw8Khz8BitMonoALaw,\r\n\r\n /**\r\n * riff-8khz-8bit-mono-alaw\r\n * Added in version 1.17.0\r\n * @member SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw\r\n */\r\n Riff8Khz8BitMonoALaw,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n connectivity,\r\n ISpeechConfigAudioDevice,\r\n type,\r\n} from \"../../common.speech/Exports\";\r\nimport {\r\n AudioSourceEvent,\r\n AudioSourceInitializingEvent,\r\n AudioSourceReadyEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n ChunkedArrayBufferStream,\r\n Deferred,\r\n Events,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IStreamChunk,\r\n Stream,\r\n} from \"../../common/Exports\";\r\nimport { createNoDashGuid } from \"../../common/Guid\";\r\nimport { AudioStreamFormat, PullAudioInputStreamCallback } from \"../Exports\";\r\nimport { AudioStreamFormatImpl } from \"./AudioStreamFormat\";\r\n\r\n/**\r\n * Represents audio input stream used for custom audio input configurations.\r\n * @class AudioInputStream\r\n */\r\nexport abstract class AudioInputStream {\r\n\r\n /**\r\n * Creates and initializes an instance.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Creates a memory backed PushAudioInputStream with the specified audio format.\r\n * @member AudioInputStream.createPushStream\r\n * @function\r\n * @public\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be\r\n * written to the push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM).\r\n * @returns {PushAudioInputStream} The audio input stream being created.\r\n */\r\n public static createPushStream(format?: AudioStreamFormat): PushAudioInputStream {\r\n return PushAudioInputStream.create(format);\r\n }\r\n\r\n /**\r\n * Creates a PullAudioInputStream that delegates to the specified callback interface for read()\r\n * and close() methods.\r\n * @member AudioInputStream.createPullStream\r\n * @function\r\n * @public\r\n * @param {PullAudioInputStreamCallback} callback - The custom audio input object, derived from\r\n * PullAudioInputStreamCallback\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be returned from\r\n * the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).\r\n * @returns {PullAudioInputStream} The audio input stream being created.\r\n */\r\n public static createPullStream(callback: PullAudioInputStreamCallback, format?: AudioStreamFormat): PullAudioInputStream {\r\n return PullAudioInputStream.create(callback, format);\r\n // throw new Error(\"Oops\");\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioInputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio input stream used for custom audio input configurations.\r\n * @class PushAudioInputStream\r\n */\r\nexport abstract class PushAudioInputStream extends AudioInputStream {\r\n\r\n /**\r\n * Creates a memory backed PushAudioInputStream with the specified audio format.\r\n * @member PushAudioInputStream.create\r\n * @function\r\n * @public\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be written to the\r\n * push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM).\r\n * @returns {PushAudioInputStream} The push audio input stream being created.\r\n */\r\n public static create(format?: AudioStreamFormat): PushAudioInputStream {\r\n return new PushAudioInputStreamImpl(format);\r\n }\r\n\r\n /**\r\n * Writes the audio data specified by making an internal copy of the data.\r\n * @member PushAudioInputStream.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.\r\n */\r\n public abstract write(dataBuffer: ArrayBuffer): void;\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PushAudioInputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio input stream used for custom audio input configurations.\r\n * @private\r\n * @class PushAudioInputStreamImpl\r\n */\r\nexport class PushAudioInputStreamImpl extends PushAudioInputStream implements IAudioSource {\r\n\r\n private privFormat: AudioStreamFormatImpl;\r\n private privId: string;\r\n private privEvents: EventSource;\r\n private privStream: Stream;\r\n\r\n /**\r\n * Creates and initalizes an instance with the given values.\r\n * @constructor\r\n * @param {AudioStreamFormat} format - The audio stream format.\r\n */\r\n public constructor(format?: AudioStreamFormat) {\r\n super();\r\n if (format === undefined) {\r\n this.privFormat = AudioStreamFormatImpl.getDefaultInputFormat();\r\n } else {\r\n this.privFormat = format as AudioStreamFormatImpl;\r\n }\r\n this.privEvents = new EventSource();\r\n this.privId = createNoDashGuid();\r\n this.privStream = new ChunkedArrayBufferStream(this.privFormat.avgBytesPerSec / 10);\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): Promise {\r\n return Promise.resolve(this.privFormat);\r\n }\r\n\r\n /**\r\n * Writes the audio data specified by making an internal copy of the data.\r\n * @member PushAudioInputStreamImpl.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.\r\n */\r\n public write(dataBuffer: ArrayBuffer): void {\r\n this.privStream.writeStreamChunk({\r\n buffer: dataBuffer,\r\n isEnd: false,\r\n timeReceived: Date.now()\r\n });\r\n }\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PushAudioInputStreamImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n this.privStream.close();\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n public get blob(): Promise {\r\n return this.attach(\"id\").then((audioNode: IAudioStreamNode) => {\r\n const data: ArrayBuffer[] = [];\r\n let bufferData = Buffer.from(\"\");\r\n const readCycle = (): Promise => {\r\n return audioNode.read().then((audioStreamChunk: IStreamChunk) => {\r\n if (!audioStreamChunk || audioStreamChunk.isEnd) {\r\n if (typeof (XMLHttpRequest) !== \"undefined\" && typeof (Blob) !== \"undefined\") {\r\n return Promise.resolve(new Blob(data));\r\n } else {\r\n return Promise.resolve(Buffer.from(bufferData));\r\n }\r\n } else {\r\n if (typeof (Blob) !== \"undefined\") {\r\n data.push(audioStreamChunk.buffer);\r\n } else {\r\n bufferData = Buffer.concat([bufferData, this.toBuffer(audioStreamChunk.buffer)]);\r\n }\r\n return readCycle();\r\n }\r\n });\r\n };\r\n return readCycle();\r\n });\r\n }\r\n\r\n public turnOn(): Promise {\r\n this.onEvent(new AudioSourceInitializingEvent(this.privId)); // no stream id\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n return;\r\n }\r\n\r\n public async attach(audioNodeId: string): Promise {\r\n this.onEvent(new AudioStreamNodeAttachingEvent(this.privId, audioNodeId));\r\n\r\n await this.turnOn();\r\n const stream = this.privStream;\r\n this.onEvent(new AudioStreamNodeAttachedEvent(this.privId, audioNodeId));\r\n return {\r\n detach: async () => {\r\n stream.readEnded();\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n return this.turnOff();\r\n },\r\n id: () => {\r\n return audioNodeId;\r\n },\r\n read: () => {\r\n return stream.read();\r\n },\r\n };\r\n }\r\n\r\n public detach(audioNodeId: string): void {\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n }\r\n\r\n public turnOff(): Promise {\r\n return;\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privEvents;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return Promise.resolve({\r\n bitspersample: this.privFormat.bitsPerSample,\r\n channelcount: this.privFormat.channels,\r\n connectivity: connectivity.Unknown,\r\n manufacturer: \"Speech SDK\",\r\n model: \"PushStream\",\r\n samplerate: this.privFormat.samplesPerSec,\r\n type: type.Stream,\r\n });\r\n }\r\n\r\n private onEvent = (event: AudioSourceEvent): void => {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private toBuffer(arrayBuffer: ArrayBuffer): Buffer {\r\n const buf: Buffer = Buffer.alloc(arrayBuffer.byteLength);\r\n const view: Uint8Array = new Uint8Array(arrayBuffer);\r\n for (let i = 0; i < buf.length; ++i) {\r\n buf[i] = view[i];\r\n }\r\n return buf;\r\n }\r\n}\r\n\r\n/*\r\n * Represents audio input stream used for custom audio input configurations.\r\n * @class PullAudioInputStream\r\n */\r\nexport abstract class PullAudioInputStream extends AudioInputStream {\r\n /**\r\n * Creates and initializes and instance.\r\n * @constructor\r\n */\r\n protected constructor() { super(); }\r\n\r\n /**\r\n * Creates a PullAudioInputStream that delegates to the specified callback interface for\r\n * read() and close() methods, using the default format (16 kHz 16bit mono PCM).\r\n * @member PullAudioInputStream.create\r\n * @function\r\n * @public\r\n * @param {PullAudioInputStreamCallback} callback - The custom audio input object,\r\n * derived from PullAudioInputStreamCustomCallback\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be\r\n * returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).\r\n * @returns {PullAudioInputStream} The push audio input stream being created.\r\n */\r\n public static create(callback: PullAudioInputStreamCallback, format?: AudioStreamFormat): PullAudioInputStream {\r\n return new PullAudioInputStreamImpl(callback, format as AudioStreamFormatImpl);\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member PullAudioInputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n\r\n}\r\n\r\n/**\r\n * Represents audio input stream used for custom audio input configurations.\r\n * @private\r\n * @class PullAudioInputStreamImpl\r\n */\r\nexport class PullAudioInputStreamImpl extends PullAudioInputStream implements IAudioSource {\r\n\r\n private privCallback: PullAudioInputStreamCallback;\r\n private privFormat: AudioStreamFormatImpl;\r\n private privId: string;\r\n private privEvents: EventSource;\r\n private privIsClosed: boolean;\r\n private privBufferSize: number;\r\n\r\n /**\r\n * Creates a PullAudioInputStream that delegates to the specified callback interface for\r\n * read() and close() methods, using the default format (16 kHz 16bit mono PCM).\r\n * @constructor\r\n * @param {PullAudioInputStreamCallback} callback - The custom audio input object,\r\n * derived from PullAudioInputStreamCustomCallback\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be\r\n * returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).\r\n */\r\n public constructor(callback: PullAudioInputStreamCallback, format?: AudioStreamFormatImpl) {\r\n super();\r\n if (undefined === format) {\r\n this.privFormat = AudioStreamFormat.getDefaultInputFormat() as AudioStreamFormatImpl;\r\n } else {\r\n this.privFormat = format;\r\n }\r\n this.privEvents = new EventSource();\r\n this.privId = createNoDashGuid();\r\n this.privCallback = callback;\r\n this.privIsClosed = false;\r\n this.privBufferSize = this.privFormat.avgBytesPerSec / 10;\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): Promise {\r\n return Promise.resolve(this.privFormat);\r\n }\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioInputStreamImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n this.privIsClosed = true;\r\n this.privCallback.close();\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n public get blob(): Promise {\r\n return Promise.reject(\"Not implemented\");\r\n }\r\n\r\n public turnOn(): Promise {\r\n this.onEvent(new AudioSourceInitializingEvent(this.privId)); // no stream id\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n return;\r\n }\r\n\r\n public async attach(audioNodeId: string): Promise {\r\n this.onEvent(new AudioStreamNodeAttachingEvent(this.privId, audioNodeId));\r\n\r\n await this.turnOn();\r\n this.onEvent(new AudioStreamNodeAttachedEvent(this.privId, audioNodeId));\r\n return {\r\n detach: () => {\r\n this.privCallback.close();\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n return this.turnOff();\r\n },\r\n id: () => {\r\n return audioNodeId;\r\n },\r\n read: (): Promise> => {\r\n let totalBytes: number = 0;\r\n let transmitBuff: ArrayBuffer;\r\n // Until we have the minimum number of bytes to send in a transmission, keep asking for more.\r\n while (totalBytes < this.privBufferSize) {\r\n // Sizing the read buffer to the delta between the perfect size and what's left means we won't ever get too much\r\n // data back.\r\n const readBuff: ArrayBuffer = new ArrayBuffer(this.privBufferSize - totalBytes);\r\n const pulledBytes: number = this.privCallback.read(readBuff);\r\n // If there is no return buffer yet defined, set the return buffer to the that was just populated.\r\n // This was, if we have enough data there's no copy penalty, but if we don't we have a buffer that's the\r\n // preferred size allocated.\r\n if (undefined === transmitBuff) {\r\n transmitBuff = readBuff;\r\n } else {\r\n // Not the first bite at the apple, so fill the return buffer with the data we got back.\r\n const intView: Int8Array = new Int8Array(transmitBuff);\r\n intView.set(new Int8Array(readBuff), totalBytes);\r\n }\r\n // If there are no bytes to read, just break out and be done.\r\n if (0 === pulledBytes) {\r\n break;\r\n }\r\n totalBytes += pulledBytes;\r\n }\r\n return Promise.resolve>({\r\n buffer: transmitBuff.slice(0, totalBytes),\r\n isEnd: this.privIsClosed || totalBytes === 0,\r\n timeReceived: Date.now(),\r\n });\r\n },\r\n };\r\n }\r\n\r\n public detach(audioNodeId: string): void {\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n }\r\n\r\n public turnOff(): Promise {\r\n return;\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privEvents;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return Promise.resolve({\r\n bitspersample: this.privFormat.bitsPerSample,\r\n channelcount: this.privFormat.channels,\r\n connectivity: connectivity.Unknown,\r\n manufacturer: \"Speech SDK\",\r\n model: \"PullStream\",\r\n samplerate: this.privFormat.samplesPerSec,\r\n type: type.Stream,\r\n });\r\n }\r\n\r\n private onEvent = (event: AudioSourceEvent): void => {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { ConnectionMessage } from \"./ConnectionMessage\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\nimport { EventType, PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class ServiceEvent extends PlatformEvent {\r\n private privJsonResult: string;\r\n\r\n constructor(eventName: string, jsonstring: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n this.privJsonResult = jsonstring;\r\n }\r\n\r\n public get jsonString(): string {\r\n return this.privJsonResult;\r\n }\r\n}\r\n\r\nexport class ConnectionEvent extends PlatformEvent {\r\n private privConnectionId: string;\r\n\r\n constructor(eventName: string, connectionId: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n this.privConnectionId = connectionId;\r\n }\r\n\r\n public get connectionId(): string {\r\n return this.privConnectionId;\r\n }\r\n}\r\n\r\nexport class ConnectionStartEvent extends ConnectionEvent {\r\n private privUri: string;\r\n private privHeaders: IStringDictionary;\r\n\r\n constructor(connectionId: string, uri: string, headers?: IStringDictionary) {\r\n super(\"ConnectionStartEvent\", connectionId);\r\n this.privUri = uri;\r\n this.privHeaders = headers;\r\n }\r\n\r\n public get uri(): string {\r\n return this.privUri;\r\n }\r\n\r\n public get headers(): IStringDictionary {\r\n return this.privHeaders;\r\n }\r\n}\r\n\r\nexport class ConnectionEstablishedEvent extends ConnectionEvent {\r\n constructor(connectionId: string, metadata?: IStringDictionary) {\r\n super(\"ConnectionEstablishedEvent\", connectionId);\r\n }\r\n}\r\n\r\nexport class ConnectionClosedEvent extends ConnectionEvent {\r\n private privReason: string;\r\n private privStatusCode: number;\r\n\r\n constructor(connectionId: string, statusCode: number, reason: string) {\r\n super(\"ConnectionClosedEvent\", connectionId, EventType.Debug);\r\n this.privReason = reason;\r\n this.privStatusCode = statusCode;\r\n }\r\n\r\n public get reason(): string {\r\n return this.privReason;\r\n }\r\n\r\n public get statusCode(): number {\r\n return this.privStatusCode;\r\n }\r\n}\r\n\r\nexport class ConnectionErrorEvent extends ConnectionEvent {\r\n private readonly privMessage: string;\r\n private readonly privType: string;\r\n\r\n constructor(connectionId: string, message: string, type: string) {\r\n super(\"ConnectionErrorEvent\", connectionId, EventType.Debug);\r\n this.privMessage = message;\r\n this.privType = type;\r\n }\r\n\r\n public get message(): string {\r\n return this.privMessage;\r\n }\r\n\r\n public get type(): string {\r\n return this.privType;\r\n }\r\n}\r\n\r\nexport class ConnectionEstablishErrorEvent extends ConnectionEvent {\r\n private privStatusCode: number;\r\n private privReason: string;\r\n\r\n constructor(connectionId: string, statuscode: number, reason: string) {\r\n super(\"ConnectionEstablishErrorEvent\", connectionId, EventType.Error);\r\n this.privStatusCode = statuscode;\r\n this.privReason = reason;\r\n }\r\n\r\n public get reason(): string {\r\n return this.privReason;\r\n }\r\n\r\n public get statusCode(): number {\r\n return this.privStatusCode;\r\n }\r\n}\r\n\r\nexport class ConnectionMessageReceivedEvent extends ConnectionEvent {\r\n private privNetworkReceivedTime: string;\r\n private privMessage: ConnectionMessage;\r\n\r\n constructor(connectionId: string, networkReceivedTimeISO: string, message: ConnectionMessage) {\r\n super(\"ConnectionMessageReceivedEvent\", connectionId);\r\n this.privNetworkReceivedTime = networkReceivedTimeISO;\r\n this.privMessage = message;\r\n }\r\n\r\n public get networkReceivedTime(): string {\r\n return this.privNetworkReceivedTime;\r\n }\r\n\r\n public get message(): ConnectionMessage {\r\n return this.privMessage;\r\n }\r\n}\r\n\r\nexport class ConnectionMessageSentEvent extends ConnectionEvent {\r\n private privNetworkSentTime: string;\r\n private privMessage: ConnectionMessage;\r\n\r\n constructor(connectionId: string, networkSentTimeISO: string, message: ConnectionMessage) {\r\n super(\"ConnectionMessageSentEvent\", connectionId);\r\n this.privNetworkSentTime = networkSentTimeISO;\r\n this.privMessage = message;\r\n }\r\n\r\n public get networkSentTime(): string {\r\n return this.privNetworkSentTime;\r\n }\r\n\r\n public get message(): ConnectionMessage {\r\n return this.privMessage;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { SpeechSynthesisResult } from \"./Exports\";\r\n\r\n/**\r\n * Defines contents of speech synthesis events.\r\n * @class SpeechSynthesisEventArgs\r\n * Added in version 1.11.0\r\n */\r\nexport class SpeechSynthesisEventArgs {\r\n private readonly privResult: SpeechSynthesisResult;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {SpeechSynthesisResult} result - The speech synthesis result.\r\n */\r\n public constructor(result: SpeechSynthesisResult) {\r\n this.privResult = result;\r\n }\r\n\r\n /**\r\n * Specifies the synthesis result.\r\n * @member SpeechSynthesisEventArgs.prototype.result\r\n * @function\r\n * @public\r\n * @returns {SpeechSynthesisResult} the synthesis result.\r\n */\r\n public get result(): SpeechSynthesisResult {\r\n return this.privResult;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection, ResultReason } from \"./Exports\";\r\n\r\n/**\r\n * Defines result of speech synthesis.\r\n * @class SpeechSynthesisResult\r\n * Added in version 1.11.0\r\n */\r\nexport class SpeechSynthesisResult {\r\n private privResultId: string;\r\n private privReason: ResultReason;\r\n private privAudioData: ArrayBuffer;\r\n private privErrorDetails: string;\r\n private privProperties: PropertyCollection;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {string} resultId - The result id.\r\n * @param {ResultReason} reason - The reason.\r\n * @param {number} audioData - The offset into the stream.\r\n * @param {string} errorDetails - Error details, if provided.\r\n * @param {PropertyCollection} properties - Additional properties, if provided.\r\n */\r\n constructor(resultId?: string, reason?: ResultReason, audioData?: ArrayBuffer,\r\n errorDetails?: string, properties?: PropertyCollection) {\r\n this.privResultId = resultId;\r\n this.privReason = reason;\r\n this.privAudioData = audioData;\r\n this.privErrorDetails = errorDetails;\r\n this.privProperties = properties;\r\n }\r\n\r\n /**\r\n * Specifies the result identifier.\r\n * @member SpeechSynthesisResult.prototype.resultId\r\n * @function\r\n * @public\r\n * @returns {string} Specifies the result identifier.\r\n */\r\n public get resultId(): string {\r\n return this.privResultId;\r\n }\r\n\r\n /**\r\n * Specifies status of the result.\r\n * @member SpeechSynthesisResult.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {ResultReason} Specifies status of the result.\r\n */\r\n public get reason(): ResultReason {\r\n return this.privReason;\r\n }\r\n\r\n /**\r\n * The synthesized audio data\r\n * @member SpeechSynthesisResult.prototype.audioData\r\n * @function\r\n * @public\r\n * @returns {ArrayBuffer} The synthesized audio data.\r\n */\r\n public get audioData(): ArrayBuffer {\r\n return this.privAudioData;\r\n }\r\n\r\n /**\r\n * In case of an unsuccessful synthesis, provides details of the occurred error.\r\n * @member SpeechSynthesisResult.prototype.errorDetails\r\n * @function\r\n * @public\r\n * @returns {string} a brief description of an error.\r\n */\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n\r\n /**\r\n * The set of properties exposed in the result.\r\n * @member SpeechSynthesisResult.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The set of properties exposed in the result.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyId } from \"./Exports\";\r\n\r\n/**\r\n * Represents collection of properties and their values.\r\n * @class PropertyCollection\r\n */\r\nexport class PropertyCollection {\r\n private privKeys: string[] = [] as string[];\r\n private privValues: string[] = [] as string[];\r\n\r\n /**\r\n * Returns the property value in type String. The parameter must have the same type as String.\r\n * Currently only String, int and bool are allowed.\r\n * If the name is not available, the specified defaultValue is returned.\r\n * @member PropertyCollection.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {string} key - The parameter name.\r\n * @param {string} def - The default value which is returned if the parameter\r\n * is not available in the collection.\r\n * @returns {string} value of the parameter.\r\n */\r\n public getProperty(key: PropertyId | string, def?: string): string {\r\n let keyToUse: string;\r\n\r\n if (typeof key === \"string\") {\r\n keyToUse = key;\r\n } else {\r\n keyToUse = PropertyId[key];\r\n }\r\n\r\n for (let n = 0; n < this.privKeys.length; n++) {\r\n if (this.privKeys[n] === keyToUse) {\r\n return this.privValues[n];\r\n }\r\n }\r\n\r\n return def;\r\n }\r\n\r\n /**\r\n * Sets the String value of the parameter specified by name.\r\n * @member PropertyCollection.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {string} key - The parameter name.\r\n * @param {string} value - The value of the parameter.\r\n */\r\n public setProperty(key: string | PropertyId, value: string): void {\r\n let keyToUse: string;\r\n\r\n if (typeof key === \"string\") {\r\n keyToUse = key;\r\n } else {\r\n keyToUse = PropertyId[key];\r\n }\r\n\r\n for (let n = 0; n < this.privKeys.length; n++) {\r\n if (this.privKeys[n] === keyToUse) {\r\n this.privValues[n] = value;\r\n return;\r\n }\r\n }\r\n\r\n this.privKeys.push(keyToUse);\r\n this.privValues.push(value);\r\n }\r\n\r\n /**\r\n * Clones the collection.\r\n * @member PropertyCollection.prototype.clone\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} A copy of the collection.\r\n */\r\n public clone(): PropertyCollection {\r\n const clonedMap = new PropertyCollection();\r\n\r\n for (let n = 0; n < this.privKeys.length; n++) {\r\n clonedMap.privKeys.push(this.privKeys[n]);\r\n clonedMap.privValues.push(this.privValues[n]);\r\n }\r\n\r\n return clonedMap;\r\n }\r\n\r\n /**\r\n * Merges this set of properties into another, no overwrites.\r\n * @member PropertyCollection.prototype.mergeTo\r\n * @function\r\n * @public\r\n * @param {PropertyCollection} The collection to merge into.\r\n */\r\n public mergeTo(destinationCollection: PropertyCollection): void {\r\n this.privKeys.forEach((key: string | PropertyId) => {\r\n if (destinationCollection.getProperty(key, undefined) === undefined) {\r\n const value = this.getProperty(key);\r\n destinationCollection.setProperty(key, value);\r\n }\r\n });\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines contents of speech synthesis word boundary event.\r\n * @class SpeechSynthesisWordBoundaryEventArgs\r\n * Added in version 1.11.0\r\n */\r\nexport class SpeechSynthesisWordBoundaryEventArgs {\r\n private privAudioOffset: number;\r\n private privText: string;\r\n private privWordLength: number;\r\n private privTextOffset: number;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {number} audioOffset - The audio offset.\r\n * @param {string} text - The text.\r\n * @param {number} wordLength - The length of the word.\r\n * @param {number} textOffset - The text offset.\r\n */\r\n public constructor(audioOffset: number, text: string, wordLength: number, textOffset: number) {\r\n this.privAudioOffset = audioOffset;\r\n this.privText = text;\r\n this.privWordLength = wordLength;\r\n this.privTextOffset = textOffset;\r\n }\r\n\r\n /**\r\n * Specifies the audio offset.\r\n * @member SpeechSynthesisWordBoundaryEventArgs.prototype.audioOffset\r\n * @function\r\n * @public\r\n * @returns {number} the audio offset.\r\n */\r\n public get audioOffset(): number {\r\n return this.privAudioOffset;\r\n }\r\n\r\n /**\r\n * Specifies the text of the word boundary event.\r\n * @member SpeechSynthesisWordBoundaryEventArgs.prototype.text\r\n * @function\r\n * @public\r\n * @returns {string} the text.\r\n */\r\n public get text(): string {\r\n return this.privText;\r\n }\r\n\r\n /**\r\n * Specifies the word length\r\n * @member SpeechSynthesisWordBoundaryEventArgs.prototype.wordLength\r\n * @function\r\n * @public\r\n * @returns {number} the word length\r\n */\r\n public get wordLength(): number {\r\n return this.privWordLength;\r\n }\r\n\r\n /**\r\n * Specifies the text offset.\r\n * @member SpeechSynthesisWordBoundaryEventArgs.prototype.textOffset\r\n * @function\r\n * @public\r\n * @returns {number} the text offset.\r\n */\r\n public get textOffset(): number {\r\n return this.privTextOffset;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines contents of speech synthesis bookmark event.\r\n * @class SpeechSynthesisBookmarkEventArgs\r\n * Added in version 1.16.0\r\n */\r\nexport class SpeechSynthesisBookmarkEventArgs {\r\n private privAudioOffset: number;\r\n private privText: string;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {number} audioOffset - The audio offset.\r\n * @param {string} text - The bookmark text.\r\n */\r\n public constructor(audioOffset: number, text: string) {\r\n this.privAudioOffset = audioOffset;\r\n this.privText = text;\r\n }\r\n\r\n /**\r\n * Specifies the audio offset.\r\n * @member SpeechSynthesisBookmarkEventArgs.prototype.audioOffset\r\n * @function\r\n * @public\r\n * @returns {number} the audio offset.\r\n */\r\n public get audioOffset(): number {\r\n return this.privAudioOffset;\r\n }\r\n\r\n /**\r\n * Specifies the bookmark.\r\n * @member SpeechSynthesisBookmarkEventArgs.prototype.text\r\n * @function\r\n * @public\r\n * @returns {string} the bookmark text.\r\n */\r\n public get text(): string {\r\n return this.privText;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines contents of speech synthesis viseme event.\r\n * @class SpeechSynthesisVisemeEventArgs\r\n * Added in version 1.16.0\r\n */\r\nexport class SpeechSynthesisVisemeEventArgs {\r\n private privAudioOffset: number;\r\n private privVisemeId: number;\r\n private privAnimation: string;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {number} audioOffset - The audio offset.\r\n * @param {number} visemeId - The viseme ID.\r\n * @param {string} animation - The animation, could be in svg or other format.\r\n */\r\n public constructor(audioOffset: number, visemeId: number, animation: string) {\r\n this.privAudioOffset = audioOffset;\r\n this.privVisemeId = visemeId;\r\n this.privAnimation = animation;\r\n }\r\n\r\n /**\r\n * Specifies the audio offset.\r\n * @member SpeechSynthesisVisemeEventArgs.prototype.audioOffset\r\n * @function\r\n * @public\r\n * @returns {number} the audio offset.\r\n */\r\n public get audioOffset(): number {\r\n return this.privAudioOffset;\r\n }\r\n\r\n /**\r\n * Specifies the viseme ID.\r\n * @member SpeechSynthesisVisemeEventArgs.prototype.visemeId\r\n * @function\r\n * @public\r\n * @returns {number} the viseme ID.\r\n */\r\n public get visemeId(): number {\r\n return this.privVisemeId;\r\n }\r\n\r\n /**\r\n * Specifies the animation.\r\n * @member SpeechSynthesisVisemeEventArgs.prototype.animation\r\n * @function\r\n * @public\r\n * @returns {string} the animation, could be in svg or other format.\r\n */\r\n public get animation(): string {\r\n return this.privAnimation;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { INumberDictionary } from \"../../common/Exports\";\r\nimport { SpeechSynthesisOutputFormat } from \"../SpeechSynthesisOutputFormat\";\r\nimport { AudioFormatTag, AudioStreamFormatImpl } from \"./AudioStreamFormat\";\r\n\r\n/**\r\n * @private\r\n * @class AudioOutputFormatImpl\r\n * Updated in version 1.17.0\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class AudioOutputFormatImpl extends AudioStreamFormatImpl {\r\n public static SpeechSynthesisOutputFormatToString: INumberDictionary = {\r\n [SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw]: \"raw-8khz-8bit-mono-mulaw\",\r\n [SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren]: \"riff-16khz-16kbps-mono-siren\",\r\n [SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren]: \"audio-16khz-16kbps-mono-siren\",\r\n [SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3]: \"audio-16khz-32kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3]: \"audio-16khz-128kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3]: \"audio-16khz-64kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3]: \"audio-24khz-48kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3]: \"audio-24khz-96kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3]: \"audio-24khz-160kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk]: \"raw-16khz-16bit-mono-truesilk\",\r\n [SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm]: \"riff-16khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm]: \"riff-8khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm]: \"riff-24khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw]: \"riff-8khz-8bit-mono-mulaw\",\r\n [SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm]: \"raw-16khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm]: \"raw-24khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm]: \"raw-8khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus]: \"ogg-16khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus]: \"ogg-24khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm]: \"raw-48khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm]: \"riff-48khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3]: \"audio-48khz-96kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3]: \"audio-48khz-192kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus]: \"ogg-48khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus]: \"webm-16khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus]: \"webm-24khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk]: \"raw-24khz-16bit-mono-truesilk\",\r\n [SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw]: \"raw-8khz-8bit-mono-alaw\",\r\n [SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw]: \"riff-8khz-8bit-mono-alaw\",\r\n };\r\n private priAudioFormatString: string;\r\n /**\r\n * audio format string for synthesis request, which may differ from priAudioFormatString.\r\n * e.g. for riff format, we will request raw format and add a header in SDK side.\r\n */\r\n private readonly priRequestAudioFormatString: string;\r\n private readonly priHasHeader: boolean;\r\n\r\n /**\r\n * Creates an instance with the given values.\r\n * @constructor\r\n * @param formatTag\r\n * @param {number} channels - Number of channels.\r\n * @param {number} samplesPerSec - Samples per second.\r\n * @param {number} avgBytesPerSec - Average bytes per second.\r\n * @param {number} blockAlign - Block alignment.\r\n * @param {number} bitsPerSample - Bits per sample.\r\n * @param {string} audioFormatString - Audio format string\r\n * @param {string} requestAudioFormatString - Audio format string sent to service.\r\n * @param {boolean} hasHeader - If the format has header or not.\r\n */\r\n public constructor(formatTag: AudioFormatTag,\r\n channels: number,\r\n samplesPerSec: number,\r\n avgBytesPerSec: number,\r\n blockAlign: number,\r\n bitsPerSample: number,\r\n audioFormatString: string,\r\n requestAudioFormatString: string,\r\n hasHeader: boolean) {\r\n super(samplesPerSec, bitsPerSample, channels, formatTag);\r\n this.formatTag = formatTag;\r\n this.avgBytesPerSec = avgBytesPerSec;\r\n this.blockAlign = blockAlign;\r\n this.priAudioFormatString = audioFormatString;\r\n this.priRequestAudioFormatString = requestAudioFormatString;\r\n this.priHasHeader = hasHeader;\r\n }\r\n\r\n public static fromSpeechSynthesisOutputFormat(speechSynthesisOutputFormat?: SpeechSynthesisOutputFormat): AudioOutputFormatImpl {\r\n if (speechSynthesisOutputFormat === undefined) {\r\n return AudioOutputFormatImpl.getDefaultOutputFormat();\r\n }\r\n return AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(\r\n AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString[speechSynthesisOutputFormat]);\r\n }\r\n\r\n public static fromSpeechSynthesisOutputFormatString(speechSynthesisOutputFormatString: string): AudioOutputFormatImpl {\r\n switch (speechSynthesisOutputFormatString) {\r\n case \"raw-8khz-8bit-mono-mulaw\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MuLaw,\r\n 1,\r\n 8000,\r\n 8000,\r\n 1,\r\n 8,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"riff-16khz-16kbps-mono-siren\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.Siren,\r\n 1,\r\n 16000,\r\n 2000,\r\n 40,\r\n 0,\r\n speechSynthesisOutputFormatString,\r\n \"audio-16khz-16kbps-mono-siren\",\r\n true);\r\n case \"audio-16khz-16kbps-mono-siren\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.Siren,\r\n 1,\r\n 16000,\r\n 2000,\r\n 40,\r\n 0,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-16khz-32kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 16000,\r\n 32 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-16khz-128kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 16000,\r\n 128 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-16khz-64kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 16000,\r\n 64 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-24khz-48kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 24000,\r\n 48 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-24khz-96kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 24000,\r\n 96 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-24khz-160kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 24000,\r\n 160 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"raw-16khz-16bit-mono-truesilk\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.SILKSkype,\r\n 1,\r\n 16000,\r\n 32000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n\r\n case \"riff-8khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 8000,\r\n 16000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-8khz-16bit-mono-pcm\",\r\n true);\r\n case \"riff-24khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 24000,\r\n 48000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-24khz-16bit-mono-pcm\",\r\n true);\r\n case \"riff-8khz-8bit-mono-mulaw\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MuLaw,\r\n 1,\r\n 8000,\r\n 8000,\r\n 1,\r\n 8,\r\n speechSynthesisOutputFormatString,\r\n \"raw-8khz-8bit-mono-mulaw\",\r\n true);\r\n case \"raw-16khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 16000,\r\n 32000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-16khz-16bit-mono-pcm\",\r\n false);\r\n case \"raw-24khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 24000,\r\n 48000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-24khz-16bit-mono-pcm\",\r\n false);\r\n case \"raw-8khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 8000,\r\n 16000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-8khz-16bit-mono-pcm\",\r\n false);\r\n case \"ogg-16khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.OGG_OPUS,\r\n 1,\r\n 16000,\r\n 8192,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"ogg-24khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.OGG_OPUS,\r\n 1,\r\n 24000,\r\n 8192,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"raw-48khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 48000,\r\n 96000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-48khz-16bit-mono-pcm\",\r\n false);\r\n case \"riff-48khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 48000,\r\n 96000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-48khz-16bit-mono-pcm\",\r\n true);\r\n case \"audio-48khz-96kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 48000,\r\n 96 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-48khz-192kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 48000,\r\n 192 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"ogg-48khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.OGG_OPUS,\r\n 1,\r\n 48000,\r\n 12000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"webm-16khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.WEBM_OPUS,\r\n 1,\r\n 16000,\r\n 8000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"webm-24khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.WEBM_OPUS,\r\n 1,\r\n 24000,\r\n 8000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"raw-24khz-16bit-mono-truesilk\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.SILKSkype,\r\n 1,\r\n 24000,\r\n 48000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"raw-8khz-8bit-mono-alaw\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.ALaw,\r\n 1,\r\n 8000,\r\n 8000,\r\n 1,\r\n 8,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"riff-8khz-8bit-mono-alaw\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.ALaw,\r\n 1,\r\n 8000,\r\n 8000,\r\n 1,\r\n 8,\r\n speechSynthesisOutputFormatString,\r\n \"raw-8khz-8bit-mono-alaw\",\r\n true);\r\n case \"riff-16khz-16bit-mono-pcm\":\r\n default:\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 16000,\r\n 32000,\r\n 2,\r\n 16,\r\n \"riff-16khz-16bit-mono-pcm\",\r\n \"raw-16khz-16bit-mono-pcm\",\r\n true);\r\n }\r\n }\r\n\r\n public static getDefaultOutputFormat(): AudioOutputFormatImpl {\r\n return AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(\r\n (typeof window !== \"undefined\") ? \"audio-24khz-48kbitrate-mono-mp3\" : \"riff-16khz-16bit-mono-pcm\");\r\n }\r\n\r\n /**\r\n * The format tag of the audio\r\n * @AudioFormatTag AudioOutputFormatImpl.prototype.formatTag\r\n * @function\r\n * @public\r\n */\r\n public formatTag: AudioFormatTag;\r\n\r\n /**\r\n * Specifies if this audio output format has a header\r\n * @boolean AudioOutputFormatImpl.prototype.hasHeader\r\n * @function\r\n * @public\r\n */\r\n public get hasHeader(): boolean {\r\n return this.priHasHeader;\r\n }\r\n\r\n /**\r\n * Specifies the header of this format\r\n * @ArrayBuffer AudioOutputFormatImpl.prototype.header\r\n * @function\r\n * @public\r\n */\r\n public get header(): ArrayBuffer {\r\n if (this.hasHeader) {\r\n return this.privHeader;\r\n }\r\n return undefined;\r\n }\r\n\r\n /**\r\n * Updates the header based on the audio length\r\n * @member AudioOutputFormatImpl.updateHeader\r\n * @function\r\n * @public\r\n * @param {number} audioLength - the audio length\r\n */\r\n public updateHeader(audioLength: number): void {\r\n if (this.priHasHeader) {\r\n const view = new DataView(this.privHeader);\r\n view.setUint32(40, audioLength, true);\r\n }\r\n }\r\n\r\n /**\r\n * Specifies the audio format string to be sent to the service\r\n * @string AudioOutputFormatImpl.prototype.requestAudioFormatString\r\n * @function\r\n * @public\r\n */\r\n public get requestAudioFormatString(): string {\r\n return this.priRequestAudioFormatString;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n IAudioDestination,\r\n IStreamChunk,\r\n Stream,\r\n} from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n AudioStreamFormat,\r\n PushAudioOutputStreamCallback\r\n} from \"../Exports\";\r\nimport { AudioOutputFormatImpl } from \"./AudioOutputFormat\";\r\n\r\n/**\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @class AudioOutputStream\r\n */\r\nexport abstract class AudioOutputStream {\r\n\r\n /**\r\n * Creates and initializes an instance.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Sets the format of the AudioOutputStream\r\n * Note: the format is set by the synthesizer before writing. Do not set it before passing it to AudioConfig\r\n * @member AudioOutputStream.prototype.format\r\n */\r\n public abstract set format(format: AudioStreamFormat);\r\n\r\n /**\r\n * Creates a memory backed PullAudioOutputStream with the specified audio format.\r\n * @member AudioOutputStream.createPullStream\r\n * @function\r\n * @public\r\n * @returns {PullAudioOutputStream} The audio output stream being created.\r\n */\r\n public static createPullStream(): PullAudioOutputStream {\r\n return PullAudioOutputStream.create();\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio output stream used for custom audio output configurations.\r\n * @class PullAudioOutputStream\r\n */\r\nexport abstract class PullAudioOutputStream extends AudioOutputStream {\r\n\r\n /**\r\n * Creates a memory backed PullAudioOutputStream with the specified audio format.\r\n * @member PullAudioOutputStream.create\r\n * @function\r\n * @public\r\n * @returns {PullAudioOutputStream} The push audio output stream being created.\r\n */\r\n public static create(): PullAudioOutputStream {\r\n return new PullAudioOutputStreamImpl();\r\n }\r\n\r\n /**\r\n * Reads audio data from the internal buffer.\r\n * @member PullAudioOutputStream.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.\r\n * @returns {Promise} Audio buffer length has been read.\r\n */\r\n public abstract read(dataBuffer: ArrayBuffer): Promise;\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio output stream used for custom audio output configurations.\r\n * @private\r\n * @class PullAudioOutputStreamImpl\r\n */\r\nexport class PullAudioOutputStreamImpl extends PullAudioOutputStream implements IAudioDestination {\r\n private privFormat: AudioOutputFormatImpl;\r\n private privId: string;\r\n private privStream: Stream;\r\n private privLastChunkView: Int8Array;\r\n\r\n /**\r\n * Creates and initializes an instance with the given values.\r\n * @constructor\r\n */\r\n public constructor() {\r\n super();\r\n this.privId = createNoDashGuid();\r\n this.privStream = new Stream();\r\n }\r\n\r\n /**\r\n * Sets the format information to the stream. For internal use only.\r\n * @param {AudioStreamFormat} format - the format to be set.\r\n */\r\n public set format(format: AudioStreamFormat) {\r\n if (format === undefined || format === null) {\r\n this.privFormat = AudioOutputFormatImpl.getDefaultOutputFormat();\r\n }\r\n this.privFormat = format as AudioOutputFormatImpl;\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): AudioStreamFormat {\r\n return this.privFormat;\r\n }\r\n\r\n /**\r\n * Checks if the stream is closed\r\n * @member PullAudioOutputStreamImpl.prototype.isClosed\r\n * @property\r\n * @public\r\n */\r\n public get isClosed(): boolean {\r\n return this.privStream.isClosed;\r\n }\r\n\r\n /**\r\n * Gets the id of the stream\r\n * @member PullAudioOutputStreamImpl.prototype.id\r\n * @property\r\n * @public\r\n */\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n /**\r\n * Reads audio data from the internal buffer.\r\n * @member PullAudioOutputStreamImpl.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.\r\n * @returns {Promise} - Audio buffer length has been read.\r\n */\r\n public async read(dataBuffer: ArrayBuffer): Promise {\r\n const intView: Int8Array = new Int8Array(dataBuffer);\r\n let totalBytes: number = 0;\r\n\r\n if (this.privLastChunkView !== undefined) {\r\n if (this.privLastChunkView.length > dataBuffer.byteLength) {\r\n intView.set(this.privLastChunkView.slice(0, dataBuffer.byteLength));\r\n this.privLastChunkView = this.privLastChunkView.slice(dataBuffer.byteLength);\r\n return Promise.resolve(dataBuffer.byteLength);\r\n }\r\n intView.set(this.privLastChunkView);\r\n totalBytes = this.privLastChunkView.length;\r\n this.privLastChunkView = undefined;\r\n }\r\n\r\n // Until we have the minimum number of bytes to send in a transmission, keep asking for more.\r\n while (totalBytes < dataBuffer.byteLength && !this.privStream.isReadEnded) {\r\n const chunk: IStreamChunk = await this.privStream.read();\r\n if (chunk !== undefined && !chunk.isEnd) {\r\n let tmpBuffer: ArrayBuffer;\r\n if (chunk.buffer.byteLength > dataBuffer.byteLength - totalBytes) {\r\n tmpBuffer = chunk.buffer.slice(0, dataBuffer.byteLength - totalBytes);\r\n this.privLastChunkView = new Int8Array(chunk.buffer.slice(dataBuffer.byteLength - totalBytes));\r\n } else {\r\n tmpBuffer = chunk.buffer;\r\n }\r\n intView.set(new Int8Array(tmpBuffer), totalBytes);\r\n totalBytes += tmpBuffer.byteLength;\r\n } else {\r\n await this.privStream.readEnded();\r\n }\r\n }\r\n return totalBytes;\r\n }\r\n\r\n /**\r\n * Writes the audio data specified by making an internal copy of the data.\r\n * @member PullAudioOutputStreamImpl.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.\r\n */\r\n public write(dataBuffer: ArrayBuffer): void {\r\n Contracts.throwIfNullOrUndefined(this.privStream, \"must set format before writing\");\r\n this.privStream.writeStreamChunk({\r\n buffer: dataBuffer,\r\n isEnd: false,\r\n timeReceived: Date.now()\r\n });\r\n }\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioOutputStreamImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n this.privStream.close();\r\n }\r\n}\r\n\r\n/*\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @class PushAudioOutputStream\r\n */\r\nexport abstract class PushAudioOutputStream extends AudioOutputStream {\r\n /**\r\n * Creates and initializes and instance.\r\n * @constructor\r\n */\r\n protected constructor() { super(); }\r\n\r\n /**\r\n * Creates a PushAudioOutputStream that delegates to the specified callback interface for\r\n * write() and close() methods.\r\n * @member PushAudioOutputStream.create\r\n * @function\r\n * @public\r\n * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,\r\n * derived from PushAudioOutputStreamCallback\r\n * @returns {PushAudioOutputStream} The push audio output stream being created.\r\n */\r\n public static create(callback: PushAudioOutputStreamCallback): PushAudioOutputStream {\r\n return new PushAudioOutputStreamImpl(callback);\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member PushAudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n\r\n}\r\n\r\n/**\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @private\r\n * @class PushAudioOutputStreamImpl\r\n */\r\nexport class PushAudioOutputStreamImpl extends PushAudioOutputStream implements IAudioDestination {\r\n private readonly privId: string;\r\n private privCallback: PushAudioOutputStreamCallback;\r\n\r\n /**\r\n * Creates a PushAudioOutputStream that delegates to the specified callback interface for\r\n * read() and close() methods.\r\n * @constructor\r\n * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,\r\n * derived from PushAudioOutputStreamCallback\r\n */\r\n public constructor(callback: PushAudioOutputStreamCallback) {\r\n super();\r\n this.privId = createNoDashGuid();\r\n this.privCallback = callback;\r\n }\r\n\r\n // tslint:disable-next-line:no-empty\r\n public set format(format: AudioStreamFormat) { }\r\n\r\n public write(buffer: ArrayBuffer): void {\r\n if (!!this.privCallback.write) {\r\n this.privCallback.write(buffer);\r\n }\r\n }\r\n\r\n public close(): void {\r\n if (!!this.privCallback.close) {\r\n this.privCallback.close();\r\n }\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { EventType, PlatformEvent } from \"../common/Exports\";\r\n\r\nexport class SpeechSynthesisEvent extends PlatformEvent {\r\n private privRequestId: string;\r\n\r\n constructor(eventName: string, requestId: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n\r\n this.privRequestId = requestId;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n}\r\n\r\nexport class SynthesisTriggeredEvent extends SpeechSynthesisEvent {\r\n private privSessionAudioDestinationId: string;\r\n private privTurnAudioDestinationId: string;\r\n\r\n constructor(requestId: string, sessionAudioDestinationId: string, turnAudioDestinationId: string) {\r\n super(\"SynthesisTriggeredEvent\", requestId);\r\n\r\n this.privSessionAudioDestinationId = sessionAudioDestinationId;\r\n this.privTurnAudioDestinationId = turnAudioDestinationId;\r\n }\r\n\r\n public get audioSessionDestinationId(): string {\r\n return this.privSessionAudioDestinationId;\r\n }\r\n\r\n public get audioTurnDestinationId(): string {\r\n return this.privTurnAudioDestinationId;\r\n }\r\n}\r\n\r\nexport class ConnectingToSynthesisServiceEvent extends SpeechSynthesisEvent {\r\n private privAuthFetchEventId: string;\r\n\r\n constructor(requestId: string, authFetchEventId: string) {\r\n super(\"ConnectingToSynthesisServiceEvent\", requestId);\r\n this.privAuthFetchEventId = authFetchEventId;\r\n }\r\n\r\n public get authFetchEventId(): string {\r\n return this.privAuthFetchEventId;\r\n }\r\n}\r\n\r\nexport class SynthesisStartedEvent extends SpeechSynthesisEvent {\r\n private privAuthFetchEventId: string;\r\n\r\n constructor(requestId: string, authFetchEventId: string) {\r\n super(\"SynthesisStartedEvent\", requestId);\r\n\r\n this.privAuthFetchEventId = authFetchEventId;\r\n }\r\n\r\n public get authFetchEventId(): string {\r\n return this.privAuthFetchEventId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n Events, IAudioDestination\r\n} from \"../common/Exports\";\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport { PullAudioOutputStreamImpl } from \"../sdk/Audio/AudioOutputStream\";\r\nimport { ISynthesisMetadata } from \"./ServiceMessages/SynthesisAudioMetadata\";\r\nimport { SynthesisAdapterBase } from \"./SynthesisAdapterBase\";\r\nimport {\r\n ConnectingToSynthesisServiceEvent,\r\n SpeechSynthesisEvent,\r\n SynthesisStartedEvent,\r\n SynthesisTriggeredEvent,\r\n} from \"./SynthesisEvents\";\r\n\r\nexport interface ISynthesisResponseContext {\r\n serviceTag: string;\r\n}\r\n\r\nexport interface ISynthesisResponseAudio {\r\n type: string;\r\n streamId: string;\r\n}\r\n\r\nexport interface ISynthesisResponse {\r\n context: ISynthesisResponseContext;\r\n audio: ISynthesisResponseAudio;\r\n}\r\n\r\nexport class SynthesisTurn {\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get streamId(): string {\r\n return this.privStreamId;\r\n }\r\n\r\n public set streamId(value: string) {\r\n this.privStreamId = value;\r\n }\r\n\r\n public get audioOutputFormat(): AudioOutputFormatImpl {\r\n return this.privAudioOutputFormat;\r\n }\r\n\r\n public set audioOutputFormat(format: AudioOutputFormatImpl) {\r\n this.privAudioOutputFormat = format;\r\n }\r\n\r\n public get turnCompletionPromise(): Promise {\r\n return this.privTurnDeferral.promise;\r\n }\r\n\r\n public get isSynthesisEnded(): boolean {\r\n return this.privIsSynthesisEnded;\r\n }\r\n\r\n public get isSynthesizing(): boolean {\r\n return this.privIsSynthesizing;\r\n }\r\n\r\n public get currentTextOffset(): number {\r\n return this.privTextOffset;\r\n }\r\n\r\n // The number of bytes received for current turn\r\n public get bytesReceived(): number {\r\n return this.privBytesReceived;\r\n }\r\n\r\n private privIsDisposed: boolean = false;\r\n private privAuthFetchEventId: string;\r\n private privIsSynthesizing: boolean = false;\r\n private privIsSynthesisEnded: boolean = false;\r\n private privBytesReceived: number = 0;\r\n private privRequestId: string;\r\n private privStreamId: string;\r\n private privTurnDeferral: Deferred;\r\n private privInTurn: boolean = false;\r\n private privAudioOutputFormat: AudioOutputFormatImpl;\r\n private privAudioOutputStream: PullAudioOutputStreamImpl;\r\n private privReceivedAudio: ArrayBuffer;\r\n private privReceivedAudioWithHeader: ArrayBuffer;\r\n private privTextOffset: number = 0;\r\n private privNextSearchTextIndex: number = 0;\r\n private privPartialVisemeAnimation: string;\r\n private privRawText: string;\r\n private privIsSSML: boolean;\r\n private privTurnAudioDestination: IAudioDestination;\r\n\r\n constructor() {\r\n this.privRequestId = createNoDashGuid();\r\n this.privTurnDeferral = new Deferred();\r\n\r\n // We're not in a turn, so resolve.\r\n this.privTurnDeferral.resolve();\r\n }\r\n\r\n public async getAllReceivedAudio(): Promise {\r\n if (!!this.privReceivedAudio) {\r\n return Promise.resolve(this.privReceivedAudio);\r\n }\r\n if (!this.privIsSynthesisEnded) {\r\n return null;\r\n }\r\n await this.readAllAudioFromStream();\r\n return Promise.resolve(this.privReceivedAudio);\r\n }\r\n\r\n public async getAllReceivedAudioWithHeader(): Promise {\r\n if (!!this.privReceivedAudioWithHeader) {\r\n return this.privReceivedAudioWithHeader;\r\n }\r\n if (!this.privIsSynthesisEnded) {\r\n return null;\r\n }\r\n if (this.audioOutputFormat.hasHeader) {\r\n const audio: ArrayBuffer = await this.getAllReceivedAudio();\r\n this.privReceivedAudioWithHeader = SynthesisAdapterBase.addHeader(audio, this.audioOutputFormat);\r\n return this.privReceivedAudioWithHeader;\r\n } else {\r\n return this.getAllReceivedAudio();\r\n }\r\n }\r\n\r\n public startNewSynthesis(requestId: string, rawText: string, isSSML: boolean, audioDestination?: IAudioDestination): void {\r\n this.privIsSynthesisEnded = false;\r\n this.privIsSynthesizing = true;\r\n this.privRequestId = requestId;\r\n this.privRawText = rawText;\r\n this.privIsSSML = isSSML;\r\n this.privAudioOutputStream = new PullAudioOutputStreamImpl();\r\n this.privAudioOutputStream.format = this.privAudioOutputFormat;\r\n this.privReceivedAudio = null;\r\n this.privReceivedAudioWithHeader = null;\r\n this.privBytesReceived = 0;\r\n this.privTextOffset = 0;\r\n this.privNextSearchTextIndex = 0;\r\n this.privPartialVisemeAnimation = \"\";\r\n if (audioDestination !== undefined) {\r\n this.privTurnAudioDestination = audioDestination;\r\n this.privTurnAudioDestination.format = this.privAudioOutputFormat;\r\n }\r\n this.onEvent(new SynthesisTriggeredEvent(this.requestId, undefined, audioDestination === undefined ? undefined : audioDestination.id()));\r\n }\r\n\r\n public onPreConnectionStart = (authFetchEventId: string, connectionId: string): void => {\r\n this.privAuthFetchEventId = authFetchEventId;\r\n this.onEvent(new ConnectingToSynthesisServiceEvent(this.privRequestId, this.privAuthFetchEventId));\r\n }\r\n\r\n public onAuthCompleted = (isError: boolean, error?: string): void => {\r\n if (isError) {\r\n this.onComplete();\r\n }\r\n }\r\n\r\n public onConnectionEstablishCompleted = (statusCode: number, reason?: string): void => {\r\n if (statusCode === 200) {\r\n this.onEvent(new SynthesisStartedEvent(this.requestId, this.privAuthFetchEventId));\r\n this.privBytesReceived = 0;\r\n return;\r\n } else if (statusCode === 403) {\r\n this.onComplete();\r\n }\r\n }\r\n\r\n public onServiceResponseMessage = (responseJson: string): void => {\r\n const response: ISynthesisResponse = JSON.parse(responseJson);\r\n this.streamId = response.audio.streamId;\r\n }\r\n\r\n public onServiceTurnEndResponse = (): void => {\r\n this.privInTurn = false;\r\n this.privTurnDeferral.resolve();\r\n this.onComplete();\r\n }\r\n\r\n public onServiceTurnStartResponse = (): void => {\r\n if (!!this.privTurnDeferral && !!this.privInTurn) {\r\n // What? How are we starting a turn with another not done?\r\n this.privTurnDeferral.reject(\"Another turn started before current completed.\");\r\n // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited\r\n /* tslint:disable:no-empty */\r\n this.privTurnDeferral.promise.then().catch(() => { });\r\n }\r\n this.privInTurn = true;\r\n this.privTurnDeferral = new Deferred();\r\n }\r\n\r\n public onAudioChunkReceived(data: ArrayBuffer): void {\r\n if (this.isSynthesizing) {\r\n this.privAudioOutputStream.write(data);\r\n this.privBytesReceived += data.byteLength;\r\n if (this.privTurnAudioDestination !== undefined) {\r\n this.privTurnAudioDestination.write(data);\r\n }\r\n }\r\n }\r\n\r\n public onWordBoundaryEvent(text: string): void {\r\n this.updateTextOffset(text);\r\n }\r\n\r\n public onVisemeMetadataReceived(metadata: ISynthesisMetadata): void {\r\n if (metadata.Data.AnimationChunk !== undefined) {\r\n this.privPartialVisemeAnimation += metadata.Data.AnimationChunk;\r\n }\r\n }\r\n\r\n public dispose = (error?: string): void => {\r\n if (!this.privIsDisposed) {\r\n // we should have completed by now. If we did not its an unknown error.\r\n this.privIsDisposed = true;\r\n }\r\n }\r\n\r\n public onStopSynthesizing(): void {\r\n this.onComplete();\r\n }\r\n\r\n /**\r\n * Gets the viseme animation string (merged from animation chunk), and clears the internal\r\n * partial animation.\r\n */\r\n public getAndClearVisemeAnimation(): string {\r\n const animation: string = this.privPartialVisemeAnimation;\r\n this.privPartialVisemeAnimation = \"\";\r\n return animation;\r\n }\r\n\r\n protected onEvent = (event: SpeechSynthesisEvent): void => {\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private updateTextOffset(text: string): void {\r\n if (this.privTextOffset >= 0) {\r\n this.privTextOffset = this.privRawText.indexOf(text, this.privNextSearchTextIndex);\r\n if (this.privTextOffset >= 0) {\r\n this.privNextSearchTextIndex = this.privTextOffset + text.length;\r\n }\r\n if (this.privIsSSML) {\r\n if (this.privRawText.indexOf(\"<\", this.privTextOffset + 1) > this.privRawText.indexOf(\">\", this.privTextOffset + 1)) {\r\n this.updateTextOffset(text);\r\n }\r\n }\r\n }\r\n }\r\n\r\n private onComplete = (): void => {\r\n if (this.privIsSynthesizing) {\r\n this.privIsSynthesizing = false;\r\n this.privIsSynthesisEnded = true;\r\n this.privAudioOutputStream.close();\r\n this.privInTurn = false;\r\n if (this.privTurnAudioDestination !== undefined) {\r\n this.privTurnAudioDestination.close();\r\n this.privTurnAudioDestination = undefined;\r\n }\r\n }\r\n }\r\n\r\n private async readAllAudioFromStream(): Promise {\r\n if (this.privIsSynthesisEnded) {\r\n this.privReceivedAudio = new ArrayBuffer(this.bytesReceived);\r\n try {\r\n await this.privAudioOutputStream.read(this.privReceivedAudio);\r\n } catch (e) {\r\n this.privReceivedAudio = new ArrayBuffer(0);\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport { SpeechSynthesizer } from \"../sdk/Exports\";\r\n\r\n/**\r\n * Represents the JSON used in the synthesis.context message sent to the speech service.\r\n * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object.\r\n */\r\nexport class SynthesisContext {\r\n private privContext: { [section: string]: any } = {};\r\n private privSpeechSynthesizer: SpeechSynthesizer;\r\n private privAudioOutputFormat: AudioOutputFormatImpl;\r\n\r\n constructor(speechSynthesizer: SpeechSynthesizer) {\r\n this.privSpeechSynthesizer = speechSynthesizer;\r\n }\r\n\r\n /**\r\n * Adds a section to the synthesis.context object.\r\n * @param sectionName Name of the section to add.\r\n * @param value JSON serializable object that represents the value.\r\n */\r\n public setSection(sectionName: string, value: any): void {\r\n this.privContext[sectionName] = value;\r\n }\r\n\r\n /**\r\n * Sets the audio output format for synthesis context generation.\r\n * @param format {AudioOutputFormatImpl} the output format\r\n */\r\n public set audioOutputFormat(format: AudioOutputFormatImpl) {\r\n this.privAudioOutputFormat = format;\r\n }\r\n\r\n public toJSON(): string {\r\n\r\n const synthesisSection: ISynthesisSection = this.buildSynthesisContext();\r\n this.setSection(\"synthesis\", synthesisSection);\r\n\r\n return JSON.stringify(this.privContext);\r\n }\r\n\r\n private buildSynthesisContext(): ISynthesisSection {\r\n return {\r\n audio: {\r\n metadataOptions: {\r\n bookmarkEnabled: (!!this.privSpeechSynthesizer.bookmarkReached),\r\n sentenceBoundaryEnabled: false,\r\n visemeEnabled: (!!this.privSpeechSynthesizer.visemeReceived),\r\n wordBoundaryEnabled: (!!this.privSpeechSynthesizer.wordBoundary),\r\n },\r\n outputFormat: this.privAudioOutputFormat.requestAudioFormatString,\r\n },\r\n language: {\r\n autoDetection: this.privSpeechSynthesizer.autoDetectSourceLanguage\r\n }\r\n };\r\n }\r\n}\r\n\r\ninterface ISynthesisSection {\r\n audio: {\r\n outputFormat: string,\r\n metadataOptions: {\r\n bookmarkEnabled: boolean,\r\n wordBoundaryEnabled: boolean,\r\n visemeEnabled: boolean,\r\n sentenceBoundaryEnabled: boolean,\r\n }\r\n };\r\n language: {\r\n autoDetection: boolean\r\n };\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Represents the JSON used in the agent.config message sent to the speech service.\r\n */\r\nexport class AgentConfig {\r\n private iPrivConfig: IAgentConfig;\r\n\r\n public toJsonString(): string {\r\n return JSON.stringify(this.iPrivConfig);\r\n }\r\n\r\n public get(): IAgentConfig {\r\n return this.iPrivConfig;\r\n }\r\n\r\n /**\r\n * Setter for the agent.config object.\r\n * @param value a JSON serializable object.\r\n */\r\n public set(value: IAgentConfig): void {\r\n this.iPrivConfig = value;\r\n }\r\n}\r\n\r\nexport interface IAgentConfig {\r\n botInfo: {\r\n commType: string,\r\n connectionId: string,\r\n conversationId: string,\r\n fromId: string\r\n commandsCulture: string,\r\n ttsAudioFormat: string\r\n };\r\n version: number;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// Make sure not to export internal modules.\r\n//\r\nexport * from \"./CognitiveSubscriptionKeyAuthentication\";\r\nexport * from \"./CognitiveTokenAuthentication\";\r\nexport * from \"./IAuthentication\";\r\nexport * from \"./IConnectionFactory\";\r\nexport * from \"./ISynthesisConnectionFactory\";\r\nexport * from \"./IntentConnectionFactory\";\r\nexport * from \"./RecognitionEvents\";\r\nexport * from \"./ServiceRecognizerBase\";\r\nexport * from \"./RecognizerConfig\";\r\nexport * from \"./SpeechServiceInterfaces\";\r\nexport * from \"./WebsocketMessageFormatter\";\r\nexport * from \"./SpeechConnectionFactory\";\r\nexport * from \"./TranscriberConnectionFactory\";\r\nexport * from \"./TranslationConnectionFactory\";\r\nexport * from \"./SpeechSynthesisConnectionFactory\";\r\nexport * from \"./EnumTranslation\";\r\nexport * from \"./ServiceMessages/Enums\";\r\nexport * from \"./ServiceMessages/TranslationSynthesisEnd\";\r\nexport * from \"./ServiceMessages/TranslationHypothesis\";\r\nexport * from \"./ServiceMessages/TranslationPhrase\";\r\nexport * from \"./TranslationServiceRecognizer\";\r\nexport * from \"./ServiceMessages/SpeechDetected\";\r\nexport * from \"./ServiceMessages/SpeechHypothesis\";\r\nexport * from \"./ServiceMessages/SpeechKeyword\";\r\nexport * from \"./SpeechServiceRecognizer\";\r\nexport * from \"./TranscriptionServiceRecognizer\";\r\nexport * from \"./ServiceMessages/DetailedSpeechPhrase\";\r\nexport * from \"./ServiceMessages/SimpleSpeechPhrase\";\r\nexport * from \"./AddedLmIntent\";\r\nexport * from \"./IntentServiceRecognizer\";\r\nexport * from \"./ServiceMessages/IntentResponse\";\r\nexport * from \"./RequestSession\";\r\nexport * from \"./SpeechContext\";\r\nexport * from \"./DynamicGrammarBuilder\";\r\nexport * from \"./DynamicGrammarInterfaces\";\r\nexport * from \"./DialogServiceAdapter\";\r\nexport * from \"./AgentConfig\";\r\nexport * from \"./Transcription/Exports\";\r\nexport * from \"./ServiceMessages/SynthesisAudioMetadata\";\r\nexport * from \"./SynthesisTurn\";\r\nexport * from \"./SynthesisAdapterBase\";\r\nexport * from \"./SynthesizerConfig\";\r\nexport * from \"./SynthesisContext\";\r\nexport * from \"./SpeakerRecognitionConfig\";\r\nexport * from \"./SpeakerIdMessageAdapter\";\r\n\r\nexport const OutputFormatPropertyName: string = \"OutputFormat\";\r\nexport const CancellationErrorCodePropertyName: string = \"CancellationErrorCode\";\r\nexport const ServicePropertiesPropertyName: string = \"ServiceProperties\";\r\nexport const ForceDictationPropertyName: string = \"ForceDictation\";\r\nexport const AutoDetectSourceLanguagesOpenRangeOptionName: string = \"OpenRange\";\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport enum MetadataType {\r\n WordBoundary = \"WordBoundary\",\r\n Bookmark = \"Bookmark\",\r\n Viseme = \"Viseme\"\r\n}\r\n\r\nexport interface ISynthesisMetadata {\r\n Type: MetadataType;\r\n Data: {\r\n Offset: number;\r\n text: {\r\n Text: string;\r\n Length: number;\r\n };\r\n Bookmark: string;\r\n VisemeId: number;\r\n AnimationChunk: string;\r\n IsLastAnimation: boolean;\r\n };\r\n}\r\n\r\n// audio.metadata\r\nexport interface ISynthesisAudioMetadata {\r\n Metadata: ISynthesisMetadata[];\r\n}\r\n\r\nexport class SynthesisAudioMetadata implements ISynthesisAudioMetadata {\r\n private privSynthesisAudioMetadata: ISynthesisAudioMetadata;\r\n\r\n private constructor(json: string) {\r\n this.privSynthesisAudioMetadata = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SynthesisAudioMetadata {\r\n return new SynthesisAudioMetadata(json);\r\n }\r\n\r\n public get Metadata(): ISynthesisMetadata[] {\r\n return this.privSynthesisAudioMetadata.Metadata;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport class HeaderNames {\r\n public static AuthKey: string = \"Ocp-Apim-Subscription-Key\";\r\n public static ConnectionId: string = \"X-ConnectionId\";\r\n public static ContentType: string = \"Content-Type\";\r\n public static CustomCommandsAppId: string = \"X-CommandsAppId\";\r\n public static Path: string = \"Path\";\r\n public static RequestId: string = \"X-RequestId\";\r\n public static RequestStreamId: string = \"X-StreamId\";\r\n public static RequestTimestamp: string = \"X-Timestamp\";\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ArgumentNullError, ConnectionMessage, IStringDictionary, MessageType } from \"../common/Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\n\r\nexport class SpeechConnectionMessage extends ConnectionMessage {\r\n\r\n private privPath: string;\r\n private privRequestId: string;\r\n private privContentType: string;\r\n private privStreamId: string;\r\n private privAdditionalHeaders: IStringDictionary;\r\n\r\n public constructor(\r\n messageType: MessageType,\r\n path: string,\r\n requestId: string,\r\n contentType: string,\r\n body: any,\r\n streamId?: string,\r\n additionalHeaders?: IStringDictionary,\r\n id?: string) {\r\n\r\n if (!path) {\r\n throw new ArgumentNullError(\"path\");\r\n }\r\n\r\n if (!requestId) {\r\n throw new ArgumentNullError(\"requestId\");\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n headers[HeaderNames.Path] = path;\r\n headers[HeaderNames.RequestId] = requestId;\r\n headers[HeaderNames.RequestTimestamp] = new Date().toISOString();\r\n if (contentType) {\r\n headers[HeaderNames.ContentType] = contentType;\r\n }\r\n\r\n if (streamId) {\r\n headers[HeaderNames.RequestStreamId] = streamId;\r\n }\r\n\r\n if (additionalHeaders) {\r\n for (const headerName in additionalHeaders) {\r\n if (headerName) {\r\n headers[headerName] = additionalHeaders[headerName];\r\n }\r\n\r\n }\r\n }\r\n\r\n if (id) {\r\n super(messageType, body, headers, id);\r\n } else {\r\n super(messageType, body, headers);\r\n }\r\n\r\n this.privPath = path;\r\n this.privRequestId = requestId;\r\n this.privContentType = contentType;\r\n this.privStreamId = streamId;\r\n this.privAdditionalHeaders = additionalHeaders;\r\n }\r\n\r\n public get path(): string {\r\n return this.privPath;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get contentType(): string {\r\n return this.privContentType;\r\n }\r\n\r\n public get streamId(): string {\r\n return this.privStreamId;\r\n }\r\n\r\n public get additionalHeaders(): IStringDictionary {\r\n return this.privAdditionalHeaders;\r\n }\r\n\r\n public static fromConnectionMessage = (message: ConnectionMessage): SpeechConnectionMessage => {\r\n let path = null;\r\n let requestId = null;\r\n let contentType = null;\r\n let requestTimestamp = null;\r\n let streamId = null;\r\n const additionalHeaders: IStringDictionary = {};\r\n\r\n if (message.headers) {\r\n for (const headerName in message.headers) {\r\n if (headerName) {\r\n if (headerName.toLowerCase() === HeaderNames.Path.toLowerCase()) {\r\n path = message.headers[headerName];\r\n } else if (headerName.toLowerCase() === HeaderNames.RequestId.toLowerCase()) {\r\n requestId = message.headers[headerName];\r\n } else if (headerName.toLowerCase() === HeaderNames.RequestTimestamp.toLowerCase()) {\r\n requestTimestamp = message.headers[headerName];\r\n } else if (headerName.toLowerCase() === HeaderNames.ContentType.toLowerCase()) {\r\n contentType = message.headers[headerName];\r\n } else if (headerName.toLowerCase() === HeaderNames.RequestStreamId.toLowerCase()) {\r\n streamId = message.headers[headerName];\r\n } else {\r\n additionalHeaders[headerName] = message.headers[headerName];\r\n }\r\n }\r\n }\r\n }\r\n\r\n return new SpeechConnectionMessage(\r\n message.messageType,\r\n path,\r\n requestId,\r\n contentType,\r\n message.body,\r\n streamId,\r\n additionalHeaders,\r\n message.id);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ArgumentNullError,\r\n ConnectionClosedEvent,\r\n ConnectionEvent,\r\n ConnectionMessage,\r\n ConnectionState,\r\n createNoDashGuid,\r\n EventSource,\r\n IAudioDestination,\r\n IConnection,\r\n IDisposable,\r\n MessageType,\r\n ServiceEvent,\r\n} from \"../common/Exports\";\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechSynthesisBookmarkEventArgs,\r\n SpeechSynthesisEventArgs,\r\n SpeechSynthesisResult,\r\n SpeechSynthesisVisemeEventArgs,\r\n SpeechSynthesisWordBoundaryEventArgs,\r\n SpeechSynthesizer,\r\n} from \"../sdk/Exports\";\r\nimport {\r\n AgentConfig,\r\n CancellationErrorCodePropertyName,\r\n ISynthesisConnectionFactory,\r\n MetadataType,\r\n SynthesisAudioMetadata,\r\n SynthesisContext,\r\n SynthesisTurn,\r\n SynthesizerConfig\r\n} from \"./Exports\";\r\nimport { AuthInfo, IAuthentication } from \"./IAuthentication\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\nexport class SynthesisAdapterBase implements IDisposable {\r\n protected privSynthesisTurn: SynthesisTurn;\r\n protected privConnectionId: string;\r\n protected privSynthesizerConfig: SynthesizerConfig;\r\n protected privSpeechSynthesizer: SpeechSynthesizer;\r\n protected privSuccessCallback: (e: SpeechSynthesisResult) => void;\r\n protected privErrorCallback: (e: string) => void;\r\n\r\n public get synthesisContext(): SynthesisContext {\r\n return this.privSynthesisContext;\r\n }\r\n\r\n public get agentConfig(): AgentConfig {\r\n return this.privAgentConfig;\r\n }\r\n\r\n public get connectionEvents(): EventSource {\r\n return this.privConnectionEvents;\r\n }\r\n\r\n public get serviceEvents(): EventSource {\r\n return this.privServiceEvents;\r\n }\r\n\r\n protected speakOverride: (ssml: string, requestId: string, sc: (e: SpeechSynthesisResult) => void, ec: (e: string) => void) => any = undefined;\r\n\r\n // Called when telemetry data is sent to the service.\r\n // Used for testing Telemetry capture.\r\n public static telemetryData: (json: string) => void;\r\n public static telemetryDataEnabled: boolean = true;\r\n\r\n public set activityTemplate(messagePayload: string) { this.privActivityTemplate = messagePayload; }\r\n public get activityTemplate(): string { return this.privActivityTemplate; }\r\n\r\n protected receiveMessageOverride: () => any = undefined;\r\n\r\n protected connectImplOverride: (isUnAuthorized: boolean) => any = undefined;\r\n\r\n protected configConnectionOverride: (connection: IConnection) => any = undefined;\r\n\r\n public set audioOutputFormat(format: AudioOutputFormatImpl) {\r\n this.privAudioOutputFormat = format;\r\n this.privSynthesisTurn.audioOutputFormat = format;\r\n if (this.privSessionAudioDestination !== undefined) {\r\n this.privSessionAudioDestination.format = format;\r\n }\r\n if (this.synthesisContext !== undefined) {\r\n this.synthesisContext.audioOutputFormat = format;\r\n }\r\n }\r\n private privAuthentication: IAuthentication;\r\n private privConnectionFactory: ISynthesisConnectionFactory;\r\n\r\n // A promise for a configured connection.\r\n // Do not consume directly, call fetchConnection instead.\r\n private privConnectionConfigurationPromise: Promise;\r\n\r\n // A promise for a connection, but one that has not had the speech context sent yet.\r\n // Do not consume directly, call fetchConnection instead.\r\n private privConnectionPromise: Promise;\r\n private privAuthFetchEventId: string;\r\n private privIsDisposed: boolean;\r\n private privConnectionEvents: EventSource;\r\n private privServiceEvents: EventSource;\r\n private privSynthesisContext: SynthesisContext;\r\n private privAgentConfig: AgentConfig;\r\n private privServiceHasSentMessage: boolean;\r\n private privActivityTemplate: string;\r\n private privAudioOutputFormat: AudioOutputFormatImpl;\r\n private privSessionAudioDestination: IAudioDestination;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: ISynthesisConnectionFactory,\r\n synthesizerConfig: SynthesizerConfig,\r\n speechSynthesizer: SpeechSynthesizer,\r\n audioDestination: IAudioDestination) {\r\n\r\n if (!authentication) {\r\n throw new ArgumentNullError(\"authentication\");\r\n }\r\n\r\n if (!connectionFactory) {\r\n throw new ArgumentNullError(\"connectionFactory\");\r\n }\r\n\r\n if (!synthesizerConfig) {\r\n throw new ArgumentNullError(\"synthesizerConfig\");\r\n }\r\n\r\n this.privAuthentication = authentication;\r\n this.privConnectionFactory = connectionFactory;\r\n this.privSynthesizerConfig = synthesizerConfig;\r\n this.privIsDisposed = false;\r\n this.privSpeechSynthesizer = speechSynthesizer;\r\n this.privSessionAudioDestination = audioDestination;\r\n this.privSynthesisTurn = new SynthesisTurn();\r\n this.privConnectionEvents = new EventSource();\r\n this.privServiceEvents = new EventSource();\r\n this.privSynthesisContext = new SynthesisContext(this.privSpeechSynthesizer);\r\n this.privAgentConfig = new AgentConfig();\r\n\r\n this.connectionEvents.attach((connectionEvent: ConnectionEvent): void => {\r\n if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n const connectionClosedEvent = connectionEvent as ConnectionClosedEvent;\r\n if (connectionClosedEvent.statusCode !== 1000) {\r\n this.cancelSynthesisLocal(CancellationReason.Error,\r\n connectionClosedEvent.statusCode === 1007 ? CancellationErrorCode.BadRequestParameters : CancellationErrorCode.ConnectionFailure,\r\n connectionClosedEvent.reason + \" websocket error code: \" + connectionClosedEvent.statusCode);\r\n }\r\n }\r\n });\r\n }\r\n\r\n public static addHeader(audio: ArrayBuffer, format: AudioOutputFormatImpl): ArrayBuffer {\r\n if (!format.hasHeader) {\r\n return audio;\r\n }\r\n format.updateHeader(audio.byteLength);\r\n const tmp = new Uint8Array(audio.byteLength + format.header.byteLength);\r\n tmp.set(new Uint8Array(format.header), 0);\r\n tmp.set(new Uint8Array(audio), format.header.byteLength);\r\n return tmp.buffer;\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public async dispose(reason?: string): Promise {\r\n this.privIsDisposed = true;\r\n if (this.privSessionAudioDestination !== undefined) {\r\n this.privSessionAudioDestination.close();\r\n }\r\n if (this.privConnectionConfigurationPromise) {\r\n const connection: IConnection = await this.privConnectionConfigurationPromise;\r\n await connection.dispose(reason);\r\n }\r\n }\r\n\r\n public async connect(): Promise {\r\n await this.connectImpl();\r\n }\r\n\r\n public async sendNetworkMessage(path: string, payload: string | ArrayBuffer): Promise {\r\n const type: MessageType = typeof payload === \"string\" ? MessageType.Text : MessageType.Binary;\r\n const contentType: string = typeof payload === \"string\" ? \"application/json\" : \"\";\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n return connection.send(new SpeechConnectionMessage(type, path, this.privSynthesisTurn.requestId, contentType, payload));\r\n }\r\n\r\n public async Speak(\r\n text: string,\r\n isSSML: boolean,\r\n requestId: string,\r\n successCallback: (e: SpeechSynthesisResult) => void,\r\n errorCallBack: (e: string) => void,\r\n audioDestination: IAudioDestination,\r\n ): Promise {\r\n\r\n let ssml: string;\r\n\r\n if (isSSML) {\r\n ssml = text;\r\n } else {\r\n ssml = this.privSpeechSynthesizer.buildSsml(text);\r\n }\r\n\r\n if (this.speakOverride !== undefined) {\r\n return this.speakOverride(ssml, requestId, successCallback, errorCallBack);\r\n }\r\n\r\n this.privSuccessCallback = successCallback;\r\n this.privErrorCallback = errorCallBack;\r\n\r\n this.privSynthesisTurn.startNewSynthesis(requestId, text, isSSML, audioDestination);\r\n\r\n try {\r\n await this.connectImpl();\r\n const connection: IConnection = await this.fetchConnection();\r\n await this.sendSynthesisContext(connection);\r\n await this.sendSsmlMessage(connection, ssml, requestId);\r\n const synthesisStartEventArgs: SpeechSynthesisEventArgs = new SpeechSynthesisEventArgs(\r\n new SpeechSynthesisResult(\r\n requestId,\r\n ResultReason.SynthesizingAudioStarted,\r\n )\r\n );\r\n\r\n if (!!this.privSpeechSynthesizer.synthesisStarted) {\r\n this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer, synthesisStartEventArgs);\r\n }\r\n\r\n const messageRetrievalPromise = this.receiveMessage();\r\n } catch (e) {\r\n this.cancelSynthesisLocal(CancellationReason.Error, CancellationErrorCode.ConnectionFailure, e);\r\n return Promise.reject(e);\r\n }\r\n }\r\n\r\n // Cancels synthesis.\r\n protected cancelSynthesis(\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n const result: SpeechSynthesisResult = new SpeechSynthesisResult(\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined,\r\n error,\r\n properties\r\n );\r\n\r\n if (!!this.privSpeechSynthesizer.SynthesisCanceled) {\r\n const cancelEvent: SpeechSynthesisEventArgs = new SpeechSynthesisEventArgs(result);\r\n try {\r\n this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n\r\n // Cancels synthesis.\r\n protected cancelSynthesisLocal(\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n if (!!this.privSynthesisTurn.isSynthesizing) {\r\n this.privSynthesisTurn.onStopSynthesizing();\r\n\r\n this.cancelSynthesis(\r\n this.privSynthesisTurn.requestId,\r\n cancellationReason,\r\n errorCode,\r\n error);\r\n }\r\n }\r\n\r\n protected processTypeSpecificMessages(\r\n connectionMessage: SpeechConnectionMessage,\r\n successCallback?: (e: SpeechSynthesisResult) => void,\r\n errorCallBack?: (e: string) => void): boolean {\r\n return true;\r\n }\r\n\r\n protected async receiveMessage(): Promise {\r\n try {\r\n const connection: IConnection = await this.fetchConnection();\r\n const message: ConnectionMessage = await connection.read();\r\n\r\n if (this.receiveMessageOverride !== undefined) {\r\n return this.receiveMessageOverride();\r\n }\r\n if (this.privIsDisposed) {\r\n // We're done.\r\n return;\r\n }\r\n\r\n // indicates we are draining the queue and it came with no message;\r\n if (!message) {\r\n if (!this.privSynthesisTurn.isSynthesizing) {\r\n return;\r\n } else {\r\n return this.receiveMessage();\r\n }\r\n }\r\n\r\n this.privServiceHasSentMessage = true;\r\n\r\n const connectionMessage = SpeechConnectionMessage.fromConnectionMessage(message);\r\n\r\n if (connectionMessage.requestId.toLowerCase() === this.privSynthesisTurn.requestId.toLowerCase()) {\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"turn.start\":\r\n this.privSynthesisTurn.onServiceTurnStartResponse();\r\n break;\r\n case \"response\":\r\n this.privSynthesisTurn.onServiceResponseMessage(connectionMessage.textBody);\r\n break;\r\n case \"audio\":\r\n if (this.privSynthesisTurn.streamId.toLowerCase() === connectionMessage.streamId.toLowerCase()\r\n && !!connectionMessage.binaryBody) {\r\n this.privSynthesisTurn.onAudioChunkReceived(connectionMessage.binaryBody);\r\n if (!!this.privSpeechSynthesizer.synthesizing) {\r\n try {\r\n const audioWithHeader = SynthesisAdapterBase.addHeader(connectionMessage.binaryBody, this.privSynthesisTurn.audioOutputFormat);\r\n const ev: SpeechSynthesisEventArgs = new SpeechSynthesisEventArgs(\r\n new SpeechSynthesisResult(\r\n this.privSynthesisTurn.requestId,\r\n ResultReason.SynthesizingAudio,\r\n audioWithHeader));\r\n this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer, ev);\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n if (this.privSessionAudioDestination !== undefined) {\r\n this.privSessionAudioDestination.write(connectionMessage.binaryBody);\r\n }\r\n }\r\n break;\r\n case \"audio.metadata\":\r\n const metadataList = SynthesisAudioMetadata.fromJSON(connectionMessage.textBody).Metadata;\r\n for (const metadata of metadataList) {\r\n switch (metadata.Type) {\r\n case MetadataType.WordBoundary:\r\n this.privSynthesisTurn.onWordBoundaryEvent(metadata.Data.text.Text);\r\n\r\n const wordBoundaryEventArgs: SpeechSynthesisWordBoundaryEventArgs = new SpeechSynthesisWordBoundaryEventArgs(\r\n metadata.Data.Offset,\r\n metadata.Data.text.Text,\r\n metadata.Data.text.Length,\r\n this.privSynthesisTurn.currentTextOffset);\r\n\r\n if (!!this.privSpeechSynthesizer.wordBoundary) {\r\n try {\r\n this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer, wordBoundaryEventArgs);\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n case MetadataType.Bookmark:\r\n const bookmarkEventArgs: SpeechSynthesisBookmarkEventArgs = new SpeechSynthesisBookmarkEventArgs(\r\n metadata.Data.Offset,\r\n metadata.Data.Bookmark);\r\n\r\n if (!!this.privSpeechSynthesizer.bookmarkReached) {\r\n try {\r\n this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer, bookmarkEventArgs);\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n case MetadataType.Viseme:\r\n\r\n this.privSynthesisTurn.onVisemeMetadataReceived(metadata);\r\n\r\n if (metadata.Data.IsLastAnimation) {\r\n const visemeEventArgs: SpeechSynthesisVisemeEventArgs = new SpeechSynthesisVisemeEventArgs(\r\n metadata.Data.Offset,\r\n metadata.Data.VisemeId,\r\n this.privSynthesisTurn.getAndClearVisemeAnimation());\r\n\r\n if (!!this.privSpeechSynthesizer.visemeReceived) {\r\n try {\r\n this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer, visemeEventArgs);\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n break;\r\n case \"turn.end\":\r\n this.privSynthesisTurn.onServiceTurnEndResponse();\r\n let result: SpeechSynthesisResult;\r\n try {\r\n const audioBuffer: ArrayBuffer = await this.privSynthesisTurn.getAllReceivedAudioWithHeader();\r\n result = new SpeechSynthesisResult(\r\n this.privSynthesisTurn.requestId,\r\n ResultReason.SynthesizingAudioCompleted,\r\n audioBuffer\r\n );\r\n if (!!this.privSuccessCallback) {\r\n this.privSuccessCallback(result);\r\n }\r\n } catch (error) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(error);\r\n }\r\n }\r\n if (this.privSpeechSynthesizer.synthesisCompleted) {\r\n try {\r\n this.privSpeechSynthesizer.synthesisCompleted(\r\n this.privSpeechSynthesizer,\r\n new SpeechSynthesisEventArgs(result)\r\n );\r\n } catch (e) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n\r\n default:\r\n\r\n if (!this.processTypeSpecificMessages(connectionMessage)) {\r\n // here are some messages that the derived class has not processed, dispatch them to connect class\r\n if (!!this.privServiceEvents) {\r\n this.serviceEvents.onEvent(new ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));\r\n }\r\n }\r\n\r\n }\r\n }\r\n\r\n return this.receiveMessage();\r\n\r\n } catch (e) {\r\n // TODO: What goes here?\r\n }\r\n }\r\n\r\n protected sendSynthesisContext = (connection: IConnection): Promise => {\r\n const synthesisContextJson = this.synthesisContext.toJSON();\r\n\r\n if (synthesisContextJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"synthesis.context\",\r\n this.privSynthesisTurn.requestId,\r\n \"application/json\",\r\n synthesisContextJson));\r\n }\r\n return;\r\n }\r\n\r\n protected connectImpl(isUnAuthorized: boolean = false): Promise {\r\n if (this.privConnectionPromise) {\r\n return this.privConnectionPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.connectImpl();\r\n }\r\n return this.privConnectionPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.connectImpl();\r\n });\r\n }\r\n this.privAuthFetchEventId = createNoDashGuid();\r\n this.privConnectionId = createNoDashGuid();\r\n\r\n this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId);\r\n\r\n const authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId);\r\n\r\n this.privConnectionPromise = authPromise.then(async (result: AuthInfo) => {\r\n await this.privSynthesisTurn.onAuthCompleted(false);\r\n\r\n const connection: IConnection = this.privConnectionFactory.create(this.privSynthesizerConfig, result, this.privConnectionId);\r\n\r\n // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away,\r\n // it'll stop sending events.\r\n connection.events.attach((event: ConnectionEvent) => {\r\n this.connectionEvents.onEvent(event);\r\n });\r\n const response = await connection.open();\r\n if (response.statusCode === 200) {\r\n await this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode);\r\n return Promise.resolve(connection);\r\n } else if (response.statusCode === 403 && !isUnAuthorized) {\r\n return this.connectImpl(true);\r\n } else {\r\n await this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode, response.reason);\r\n return Promise.reject(`Unable to contact server. StatusCode: ${response.statusCode}, ${this.privSynthesizerConfig.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint)} Reason: ${response.reason}`);\r\n }\r\n }, async (error: string): Promise => {\r\n await this.privSynthesisTurn.onAuthCompleted(true, error);\r\n throw new Error(error);\r\n });\r\n\r\n // Attach an empty handler to allow the promise to run in the background while\r\n // other startup events happen. It'll eventually be awaited on.\r\n this.privConnectionPromise.catch(() => { });\r\n\r\n return this.privConnectionPromise;\r\n }\r\n protected sendSpeechServiceConfig = (connection: IConnection, SpeechServiceConfigJson: string): Promise => {\r\n if (SpeechServiceConfigJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.config\",\r\n this.privSynthesisTurn.requestId,\r\n \"application/json\",\r\n SpeechServiceConfigJson));\r\n }\r\n }\r\n\r\n protected sendSsmlMessage = (connection: IConnection, ssml: string, requestId: string): Promise => {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"ssml\",\r\n requestId,\r\n \"application/ssml+xml\",\r\n ssml));\r\n }\r\n\r\n private async fetchConnection(): Promise {\r\n if (this.privConnectionConfigurationPromise) {\r\n return this.privConnectionConfigurationPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigurationPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.fetchConnection();\r\n }\r\n return this.privConnectionConfigurationPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigurationPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.fetchConnection();\r\n });\r\n }\r\n this.privConnectionConfigurationPromise = this.configureConnection();\r\n return await this.privConnectionConfigurationPromise;\r\n }\r\n\r\n // Takes an established websocket connection to the endpoint and sends speech configuration information.\r\n private async configureConnection(): Promise {\r\n const connection: IConnection = await this.connectImpl();\r\n if (this.configConnectionOverride !== undefined) {\r\n return this.configConnectionOverride(connection);\r\n }\r\n await this.sendSpeechServiceConfig(connection, this.privSynthesizerConfig.SpeechServiceConfig.serialize());\r\n return connection;\r\n }\r\n}\r\n","\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n EventType,\r\n PlatformEvent\r\n} from \"./Exports\";\r\n\r\nexport class BackgroundEvent extends PlatformEvent {\r\n private privError: string;\r\n\r\n constructor(error: string) {\r\n super(\"BackgroundEvent\", EventType.Error);\r\n this.privError = error;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { SynthesisAdapterBase } from \"../../common.speech/Exports\";\r\nimport {\r\n BackgroundEvent,\r\n createNoDashGuid,\r\n Events,\r\n IAudioDestination,\r\n INumberDictionary\r\n} from \"../../common/Exports\";\r\nimport { AudioStreamFormat, IPlayer } from \"../Exports\";\r\nimport { AudioOutputFormatImpl } from \"./AudioOutputFormat\";\r\nimport { PullAudioOutputStreamImpl } from \"./AudioOutputStream\";\r\nimport { AudioFormatTag } from \"./AudioStreamFormat\";\r\n\r\nconst MediaDurationPlaceholderSeconds = 60 * 30;\r\n\r\nconst AudioFormatToMimeType: INumberDictionary = {\r\n [AudioFormatTag.PCM]: \"audio/wav\",\r\n [AudioFormatTag.MuLaw]: \"audio/x-wav\",\r\n [AudioFormatTag.MP3]: \"audio/mpeg\",\r\n [AudioFormatTag.OGG_OPUS]: \"audio/ogg\",\r\n [AudioFormatTag.WEBM_OPUS]: \"audio/webm; codecs=opus\",\r\n [AudioFormatTag.ALaw]: \"audio/x-wav\",\r\n};\r\n\r\n/**\r\n * Represents the speaker playback audio destination, which only works in browser.\r\n * Note: the SDK will try to use Media Source Extensions to play audio.\r\n * Mp3 format has better supports on Microsoft Edge, Chrome and Safari (desktop), so, it's better to specify mp3 format for playback.\r\n * @class SpeakerAudioDestination\r\n * Updated in version 1.17.0\r\n */\r\nexport class SpeakerAudioDestination implements IAudioDestination, IPlayer {\r\n private readonly privId: string;\r\n private privFormat: AudioOutputFormatImpl;\r\n private privAudio: HTMLAudioElement;\r\n private privMediaSource: MediaSource;\r\n private privSourceBuffer: SourceBuffer;\r\n private privPlaybackStarted: boolean = false;\r\n private privAudioBuffer: ArrayBuffer[];\r\n private privAppendingToBuffer: boolean = false;\r\n private privMediaSourceOpened: boolean = false;\r\n private privIsClosed: boolean;\r\n private privIsPaused: boolean;\r\n private privAudioOutputStream: PullAudioOutputStreamImpl;\r\n private privBytesReceived: number = 0;\r\n\r\n public constructor(audioDestinationId?: string) {\r\n this.privId = audioDestinationId ? audioDestinationId : createNoDashGuid();\r\n this.privIsPaused = false;\r\n this.privIsClosed = false;\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n public write(buffer: ArrayBuffer, cb?: () => void, err?: (error: string) => void): void {\r\n if (this.privAudioBuffer !== undefined) {\r\n this.privAudioBuffer.push(buffer);\r\n this.updateSourceBuffer().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n } else if (this.privAudioOutputStream !== undefined) {\r\n this.privAudioOutputStream.write(buffer);\r\n this.privBytesReceived += buffer.byteLength;\r\n }\r\n }\r\n\r\n public close(cb?: () => void, err?: (error: string) => void): void {\r\n this.privIsClosed = true;\r\n if (this.privSourceBuffer !== undefined) {\r\n this.handleSourceBufferUpdateEnd().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n } else if (this.privAudioOutputStream !== undefined) {\r\n if ((this.privFormat.formatTag === AudioFormatTag.PCM || this.privFormat.formatTag === AudioFormatTag.MuLaw\r\n || this.privFormat.formatTag === AudioFormatTag.ALaw) && this.privFormat.hasHeader === false) {\r\n // tslint:disable-next-line:no-console\r\n console.warn(`Play back is not supported for raw PCM, mulaw or alaw format without header.`);\r\n if (!!this.onAudioEnd) {\r\n this.onAudioEnd(this);\r\n }\r\n } else {\r\n let receivedAudio = new ArrayBuffer(this.privBytesReceived);\r\n this.privAudioOutputStream.read(receivedAudio).then((_: number): void => {\r\n receivedAudio = SynthesisAdapterBase.addHeader(receivedAudio, this.privFormat);\r\n const audioBlob = new Blob([receivedAudio], { type: AudioFormatToMimeType[this.privFormat.formatTag] });\r\n this.privAudio.src = window.URL.createObjectURL(audioBlob);\r\n this.notifyPlayback().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n }\r\n } else {\r\n // unsupported format, call onAudioEnd directly.\r\n if (!!this.onAudioEnd) {\r\n this.onAudioEnd(this);\r\n }\r\n }\r\n }\r\n\r\n set format(format: AudioStreamFormat) {\r\n if (typeof (AudioContext) !== \"undefined\" || typeof ((window as any).webkitAudioContext) !== \"undefined\") {\r\n this.privFormat = format as AudioOutputFormatImpl;\r\n const mimeType: string = AudioFormatToMimeType[this.privFormat.formatTag];\r\n if (mimeType === undefined) {\r\n // tslint:disable-next-line:no-console\r\n console.warn(\r\n `Unknown mimeType for format ${AudioFormatTag[this.privFormat.formatTag]}; playback is not supported.`);\r\n\r\n } else if (typeof (MediaSource) !== \"undefined\" && MediaSource.isTypeSupported(mimeType)) {\r\n this.privAudio = new Audio();\r\n this.privAudioBuffer = [];\r\n this.privMediaSource = new MediaSource();\r\n this.privAudio.src = URL.createObjectURL(this.privMediaSource);\r\n this.privAudio.load();\r\n this.privMediaSource.onsourceopen = (event: Event): void => {\r\n this.privMediaSourceOpened = true;\r\n this.privMediaSource.duration = MediaDurationPlaceholderSeconds;\r\n this.privSourceBuffer = this.privMediaSource.addSourceBuffer(mimeType);\r\n this.privSourceBuffer.onupdate = (_: Event) => {\r\n this.updateSourceBuffer().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n };\r\n this.privSourceBuffer.onupdateend = (_: Event) => {\r\n this.handleSourceBufferUpdateEnd().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n };\r\n this.privSourceBuffer.onupdatestart = (_: Event) => {\r\n this.privAppendingToBuffer = false;\r\n };\r\n };\r\n this.updateSourceBuffer().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n\r\n } else {\r\n // tslint:disable-next-line:no-console\r\n console.warn(\r\n `Format ${AudioFormatTag[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`);\r\n this.privAudioOutputStream = new PullAudioOutputStreamImpl();\r\n this.privAudioOutputStream.format = this.privFormat;\r\n this.privAudio = new Audio();\r\n }\r\n }\r\n }\r\n\r\n public get isClosed(): boolean {\r\n return this.privIsClosed;\r\n }\r\n\r\n public get currentTime(): number {\r\n if (this.privAudio !== undefined) {\r\n return this.privAudio.currentTime;\r\n }\r\n return -1;\r\n }\r\n\r\n public pause(): void {\r\n if (!this.privIsPaused && this.privAudio !== undefined) {\r\n this.privAudio.pause();\r\n this.privIsPaused = true;\r\n }\r\n }\r\n\r\n public resume(cb?: () => void, err?: (error: string) => void): void {\r\n if (this.privIsPaused && this.privAudio !== undefined) {\r\n this.privAudio.play().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n this.privIsPaused = false;\r\n }\r\n }\r\n\r\n public onAudioStart: (sender: IPlayer) => void;\r\n\r\n public onAudioEnd: (sender: IPlayer) => void;\r\n\r\n public get internalAudio(): HTMLAudioElement {\r\n return this.privAudio;\r\n }\r\n\r\n private async updateSourceBuffer(): Promise {\r\n if (this.privAudioBuffer !== undefined && (this.privAudioBuffer.length > 0) && this.sourceBufferAvailable()) {\r\n this.privAppendingToBuffer = true;\r\n const binary = this.privAudioBuffer.shift();\r\n try {\r\n this.privSourceBuffer.appendBuffer(binary);\r\n } catch (error) {\r\n this.privAudioBuffer.unshift(binary);\r\n // tslint:disable-next-line:no-console\r\n console.log(\r\n \"buffer filled, pausing addition of binaries until space is made\");\r\n return;\r\n }\r\n await this.notifyPlayback();\r\n } else if (this.canEndStream()) {\r\n await this.handleSourceBufferUpdateEnd();\r\n }\r\n }\r\n\r\n private async handleSourceBufferUpdateEnd(): Promise {\r\n if (this.canEndStream() && this.sourceBufferAvailable()) {\r\n this.privMediaSource.endOfStream();\r\n await this.notifyPlayback();\r\n }\r\n }\r\n\r\n private async notifyPlayback(): Promise {\r\n if (!this.privPlaybackStarted && this.privAudio !== undefined) {\r\n this.privPlaybackStarted = true;\r\n if (!!this.onAudioStart) {\r\n this.onAudioStart(this);\r\n }\r\n this.privAudio.onended = (): void => {\r\n if (!!this.onAudioEnd) {\r\n this.onAudioEnd(this);\r\n }\r\n };\r\n if (!this.privIsPaused) {\r\n await this.privAudio.play();\r\n }\r\n }\r\n }\r\n\r\n private canEndStream(): boolean {\r\n return (this.isClosed && this.privSourceBuffer !== undefined && (this.privAudioBuffer.length === 0)\r\n && this.privMediaSourceOpened && !this.privAppendingToBuffer && this.privMediaSource.readyState === \"open\");\r\n }\r\n\r\n private sourceBufferAvailable(): boolean {\r\n return (this.privSourceBuffer !== undefined && !this.privSourceBuffer.updating);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n/**\r\n * An abstract base class that defines callback methods (write() and close()) for\r\n * custom audio output streams).\r\n * @class PushAudioOutputStreamCallback\r\n */\r\nexport abstract class PushAudioOutputStreamCallback {\r\n\r\n /**\r\n * Writes audio data into the data buffer.\r\n * @member PushAudioOutputStreamCallback.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The byte array that stores the audio data to write.\r\n */\r\n public abstract write(dataBuffer: ArrayBuffer): void;\r\n\r\n /**\r\n * Closes the audio output stream.\r\n * @member PushAudioOutputStreamCallback.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Define Speech Recognizer output formats.\r\n * @class OutputFormat\r\n */\r\nexport enum OutputFormat {\r\n /**\r\n * @member OutputFormat.Simple\r\n */\r\n Simple = 0,\r\n\r\n /**\r\n * @member OutputFormat.Detailed\r\n */\r\n Detailed,\r\n}\r\n","// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Profanity option.\r\n * Added in version 1.7.0.\r\n */\r\nexport enum ProfanityOption {\r\n Masked = 0,\r\n Removed = 1,\r\n Raw = 2\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { EventType, PlatformEvent } from \"../common/Exports\";\r\n\r\nexport class SpeechRecognitionEvent extends PlatformEvent {\r\n private privRequestId: string;\r\n private privSessionId: string;\r\n\r\n constructor(eventName: string, requestId: string, sessionId: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n\r\n this.privRequestId = requestId;\r\n this.privSessionId = sessionId;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n}\r\n\r\nexport class RecognitionTriggeredEvent extends SpeechRecognitionEvent {\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n\r\n constructor(requestId: string, sessionId: string, audioSourceId: string, audioNodeId: string) {\r\n super(\"RecognitionTriggeredEvent\", requestId, sessionId);\r\n\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n}\r\n\r\nexport class ListeningStartedEvent extends SpeechRecognitionEvent {\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n\r\n constructor(requestId: string, sessionId: string, audioSourceId: string, audioNodeId: string) {\r\n super(\"ListeningStartedEvent\", requestId, sessionId);\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n}\r\n\r\nexport class ConnectingToServiceEvent extends SpeechRecognitionEvent {\r\n private privAuthFetchEventid: string;\r\n\r\n constructor(requestId: string, authFetchEventid: string, sessionId: string) {\r\n super(\"ConnectingToServiceEvent\", requestId, sessionId);\r\n this.privAuthFetchEventid = authFetchEventid;\r\n }\r\n\r\n public get authFetchEventid(): string {\r\n return this.privAuthFetchEventid;\r\n }\r\n}\r\n\r\nexport class RecognitionStartedEvent extends SpeechRecognitionEvent {\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n private privAuthFetchEventId: string;\r\n\r\n constructor(requestId: string, audioSourceId: string, audioNodeId: string, authFetchEventId: string, sessionId: string) {\r\n super(\"RecognitionStartedEvent\", requestId, sessionId);\r\n\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n this.privAuthFetchEventId = authFetchEventId;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n\r\n public get authFetchEventId(): string {\r\n return this.privAuthFetchEventId;\r\n }\r\n}\r\n\r\nexport enum RecognitionCompletionStatus {\r\n Success,\r\n AudioSourceError,\r\n AudioSourceTimeout,\r\n AuthTokenFetchError,\r\n AuthTokenFetchTimeout,\r\n UnAuthorized,\r\n ConnectTimeout,\r\n ConnectError,\r\n ClientRecognitionActivityTimeout,\r\n UnknownError,\r\n}\r\n\r\nexport class RecognitionEndedEvent extends SpeechRecognitionEvent {\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n private privAuthFetchEventId: string;\r\n private privServiceTag: string;\r\n private privStatus: RecognitionCompletionStatus;\r\n private privError: string;\r\n\r\n constructor(\r\n requestId: string,\r\n audioSourceId: string,\r\n audioNodeId: string,\r\n authFetchEventId: string,\r\n sessionId: string,\r\n serviceTag: string,\r\n status: RecognitionCompletionStatus,\r\n error: string) {\r\n\r\n super(\"RecognitionEndedEvent\", requestId, sessionId, status === RecognitionCompletionStatus.Success ? EventType.Info : EventType.Error);\r\n\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n this.privAuthFetchEventId = authFetchEventId;\r\n this.privStatus = status;\r\n this.privError = error;\r\n this.privServiceTag = serviceTag;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n\r\n public get authFetchEventId(): string {\r\n return this.privAuthFetchEventId;\r\n }\r\n\r\n public get serviceTag(): string {\r\n return this.privServiceTag;\r\n }\r\n\r\n public get status(): RecognitionCompletionStatus {\r\n return this.privStatus;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport * as fs from \"fs\";\r\nimport { IAudioDestination } from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport { AudioStreamFormat } from \"../Exports\";\r\nimport { AudioOutputFormatImpl } from \"./AudioOutputFormat\";\r\n\r\nexport class AudioFileWriter implements IAudioDestination {\r\n private privAudioFormat: AudioOutputFormatImpl;\r\n private privFd: number;\r\n private privId: string;\r\n private privWriteStream: fs.WriteStream;\r\n\r\n public constructor(filename: fs.PathLike) {\r\n Contracts.throwIfNullOrUndefined(fs.openSync, \"\\nFile System access not available, please use Push or PullAudioOutputStream\");\r\n this.privFd = fs.openSync(filename, \"w\");\r\n }\r\n\r\n public set format(format: AudioStreamFormat) {\r\n Contracts.throwIfNotUndefined(this.privAudioFormat, \"format is already set\");\r\n this.privAudioFormat = format as AudioOutputFormatImpl;\r\n let headerOffset: number = 0;\r\n if (this.privAudioFormat.hasHeader) {\r\n headerOffset = this.privAudioFormat.header.byteLength;\r\n }\r\n if (this.privFd !== undefined) {\r\n this.privWriteStream = fs.createWriteStream(\"\", {fd: this.privFd, start: headerOffset, autoClose: false});\r\n }\r\n }\r\n\r\n public write(buffer: ArrayBuffer): void {\r\n Contracts.throwIfNullOrUndefined(this.privAudioFormat, \"must set format before writing.\");\r\n if (this.privWriteStream !== undefined) {\r\n this.privWriteStream.write(new Uint8Array(buffer.slice(0)));\r\n }\r\n }\r\n\r\n public close(): void {\r\n if (this.privFd !== undefined) {\r\n this.privWriteStream.on(\"finish\", () => {\r\n if (this.privAudioFormat.hasHeader) {\r\n this.privAudioFormat.updateHeader(this.privWriteStream.bytesWritten);\r\n fs.writeSync(this.privFd,\r\n new Int8Array(this.privAudioFormat.header),\r\n 0,\r\n this.privAudioFormat.header.byteLength,\r\n 0);\r\n }\r\n fs.closeSync(this.privFd);\r\n this.privFd = undefined;\r\n });\r\n this.privWriteStream.end();\r\n }\r\n }\r\n\r\n public id = (): string => {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { PathLike } from \"fs\";\r\nimport {\r\n FileAudioSource,\r\n MicAudioSource,\r\n PcmRecorder,\r\n} from \"../../common.browser/Exports\";\r\nimport { ISpeechConfigAudioDevice } from \"../../common.speech/Exports\";\r\nimport {\r\n AudioSourceEvent,\r\n Deferred,\r\n EventSource,\r\n IAudioDestination,\r\n IAudioSource,\r\n IAudioStreamNode\r\n} from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n AudioInputStream,\r\n AudioOutputStream,\r\n AudioStreamFormat,\r\n IPlayer,\r\n PropertyCollection,\r\n PropertyId,\r\n PullAudioInputStreamCallback,\r\n PullAudioOutputStream,\r\n PushAudioOutputStream,\r\n PushAudioOutputStreamCallback,\r\n SpeakerAudioDestination\r\n} from \"../Exports\";\r\nimport { AudioFileWriter } from \"./AudioFileWriter\";\r\nimport { PullAudioInputStreamImpl, PushAudioInputStreamImpl } from \"./AudioInputStream\";\r\nimport { PullAudioOutputStreamImpl, PushAudioOutputStreamImpl } from \"./AudioOutputStream\";\r\nimport { AudioStreamFormatImpl } from \"./AudioStreamFormat\";\r\n\r\n/**\r\n * Represents audio input configuration used for specifying what type of input to use (microphone, file, stream).\r\n * @class AudioConfig\r\n * Updated in version 1.11.0\r\n */\r\nexport abstract class AudioConfig {\r\n /**\r\n * Creates an AudioConfig object representing the default microphone on the system.\r\n * @member AudioConfig.fromDefaultMicrophoneInput\r\n * @function\r\n * @public\r\n * @returns {AudioConfig} The audio input configuration being created.\r\n */\r\n public static fromDefaultMicrophoneInput(): AudioConfig {\r\n const pcmRecorder = new PcmRecorder();\r\n return new AudioConfigImpl(new MicAudioSource(pcmRecorder));\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing a microphone with the specified device ID.\r\n * @member AudioConfig.fromMicrophoneInput\r\n * @function\r\n * @public\r\n * @param {string | undefined} deviceId - Specifies the device ID of the microphone to be used.\r\n * Default microphone is used the value is omitted.\r\n * @returns {AudioConfig} The audio input configuration being created.\r\n */\r\n public static fromMicrophoneInput(deviceId?: string): AudioConfig {\r\n const pcmRecorder = new PcmRecorder();\r\n return new AudioConfigImpl(new MicAudioSource(pcmRecorder, deviceId));\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing the specified file.\r\n * @member AudioConfig.fromWavFileInput\r\n * @function\r\n * @public\r\n * @param {File} fileName - Specifies the audio input file. Currently, only WAV / PCM is supported.\r\n * @returns {AudioConfig} The audio input configuration being created.\r\n */\r\n public static fromWavFileInput(file: File | Buffer, name: string = \"unnamedBuffer.wav\"): AudioConfig {\r\n return new AudioConfigImpl(new FileAudioSource(file, name));\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing the specified stream.\r\n * @member AudioConfig.fromStreamInput\r\n * @function\r\n * @public\r\n * @param {AudioInputStream | PullAudioInputStreamCallback | MediaStream} audioStream - Specifies the custom audio input\r\n * stream. Currently, only WAV / PCM is supported.\r\n * @returns {AudioConfig} The audio input configuration being created.\r\n */\r\n public static fromStreamInput(audioStream: AudioInputStream | PullAudioInputStreamCallback\r\n | MediaStream): AudioConfig {\r\n if (audioStream instanceof PullAudioInputStreamCallback) {\r\n return new AudioConfigImpl(new PullAudioInputStreamImpl(audioStream as PullAudioInputStreamCallback));\r\n }\r\n\r\n if (audioStream instanceof AudioInputStream) {\r\n return new AudioConfigImpl(audioStream as PushAudioInputStreamImpl);\r\n }\r\n if (typeof MediaStream !== \"undefined\" && audioStream instanceof MediaStream) {\r\n const pcmRecorder = new PcmRecorder();\r\n return new AudioConfigImpl(new MicAudioSource(pcmRecorder, null, null, audioStream));\r\n }\r\n\r\n throw new Error(\"Not Supported Type\");\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing the default speaker.\r\n * @member AudioConfig.fromDefaultSpeakerOutput\r\n * @function\r\n * @public\r\n * @returns {AudioConfig} The audio output configuration being created.\r\n * Added in version 1.11.0\r\n */\r\n public static fromDefaultSpeakerOutput(): AudioConfig {\r\n return new AudioOutputConfigImpl(new SpeakerAudioDestination());\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing the custom IPlayer object.\r\n * You can use the IPlayer object to control pause, resume, etc.\r\n * @member AudioConfig.fromSpeakerOutput\r\n * @function\r\n * @public\r\n * @param {IPlayer} player - the IPlayer object for playback.\r\n * @returns {AudioConfig} The audio output configuration being created.\r\n * Added in version 1.12.0\r\n */\r\n public static fromSpeakerOutput(player?: IPlayer): AudioConfig {\r\n if (player === undefined) {\r\n return AudioConfig.fromDefaultSpeakerOutput();\r\n }\r\n if (player instanceof SpeakerAudioDestination) {\r\n return new AudioOutputConfigImpl(player as SpeakerAudioDestination);\r\n }\r\n\r\n throw new Error(\"Not Supported Type\");\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing a specified output audio file\r\n * @member AudioConfig.fromAudioFileOutput\r\n * @function\r\n * @public\r\n * @param {PathLike} filename - the filename of the output audio file\r\n * @returns {AudioConfig} The audio output configuration being created.\r\n * Added in version 1.11.0\r\n */\r\n public static fromAudioFileOutput(filename: PathLike): AudioConfig {\r\n return new AudioOutputConfigImpl(new AudioFileWriter(filename));\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing a specified audio output stream\r\n * @member AudioConfig.fromStreamOutput\r\n * @function\r\n * @public\r\n * @param {AudioOutputStream | PushAudioOutputStreamCallback} audioStream - Specifies the custom audio output\r\n * stream.\r\n * @returns {AudioConfig} The audio output configuration being created.\r\n * Added in version 1.11.0\r\n */\r\n public static fromStreamOutput(audioStream: AudioOutputStream | PushAudioOutputStreamCallback): AudioConfig {\r\n if (audioStream instanceof PushAudioOutputStreamCallback) {\r\n return new AudioOutputConfigImpl(new PushAudioOutputStreamImpl(audioStream as PushAudioOutputStreamCallback));\r\n }\r\n\r\n if (audioStream instanceof PushAudioOutputStream) {\r\n return new AudioOutputConfigImpl(audioStream as PushAudioOutputStreamImpl);\r\n }\r\n\r\n if (audioStream instanceof PullAudioOutputStream) {\r\n return new AudioOutputConfigImpl(audioStream as PullAudioOutputStreamImpl);\r\n }\r\n\r\n throw new Error(\"Not Supported Type\");\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioConfig.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n\r\n /**\r\n * Sets an arbitrary property.\r\n * @member SpeechConfig.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to set.\r\n * @param {string} value - The new value of the property.\r\n */\r\n public abstract setProperty(name: string, value: string): void;\r\n\r\n /**\r\n * Returns the current value of an arbitrary property.\r\n * @member SpeechConfig.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to query.\r\n * @param {string} def - The value to return in case the property is not known.\r\n * @returns {string} The current value, or provided default, of the given property.\r\n */\r\n public abstract getProperty(name: string, def?: string): string;\r\n\r\n}\r\n\r\n/**\r\n * Represents audio input stream used for custom audio input configurations.\r\n * @private\r\n * @class AudioConfigImpl\r\n */\r\nexport class AudioConfigImpl extends AudioConfig implements IAudioSource {\r\n private privSource: IAudioSource;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {IAudioSource} source - An audio source.\r\n */\r\n public constructor(source: IAudioSource) {\r\n super();\r\n this.privSource = source;\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): Promise {\r\n return this.privSource.format;\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, err?: (error: string) => void): void {\r\n this.privSource.turnOff().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string) => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.id\r\n * @function\r\n * @public\r\n */\r\n public id(): string {\r\n return this.privSource.id();\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.blob\r\n * @function\r\n * @public\r\n */\r\n public get blob(): Promise {\r\n return this.privSource.blob;\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.turnOn\r\n * @function\r\n * @public\r\n * @returns {Promise} A promise.\r\n */\r\n public turnOn(): Promise {\r\n return this.privSource.turnOn();\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.attach\r\n * @function\r\n * @public\r\n * @param {string} audioNodeId - The audio node id.\r\n * @returns {Promise} A promise.\r\n */\r\n public attach(audioNodeId: string): Promise {\r\n return this.privSource.attach(audioNodeId);\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.detach\r\n * @function\r\n * @public\r\n * @param {string} audioNodeId - The audio node id.\r\n */\r\n public detach(audioNodeId: string): void {\r\n return this.privSource.detach(audioNodeId);\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.turnOff\r\n * @function\r\n * @public\r\n * @returns {Promise} A promise.\r\n */\r\n public turnOff(): Promise {\r\n return this.privSource.turnOff();\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.events\r\n * @function\r\n * @public\r\n * @returns {EventSource} An event source for audio events.\r\n */\r\n public get events(): EventSource {\r\n return this.privSource.events;\r\n }\r\n\r\n public setProperty(name: string, value: string): void {\r\n Contracts.throwIfNull(value, \"value\");\r\n\r\n if (undefined !== this.privSource.setProperty) {\r\n this.privSource.setProperty(name, value);\r\n } else {\r\n throw new Error(\"This AudioConfig instance does not support setting properties.\");\r\n }\r\n\r\n }\r\n\r\n public getProperty(name: string, def?: string): string {\r\n if (undefined !== this.privSource.getProperty) {\r\n return this.privSource.getProperty(name, def);\r\n } else {\r\n throw new Error(\"This AudioConfig instance does not support getting properties.\");\r\n }\r\n\r\n return def;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return this.privSource.deviceInfo;\r\n }\r\n}\r\n\r\nexport class AudioOutputConfigImpl extends AudioConfig implements IAudioDestination {\r\n private privDestination: IAudioDestination;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {IAudioDestination} destination - An audio destination.\r\n */\r\n public constructor(destination: IAudioDestination) {\r\n super();\r\n this.privDestination = destination;\r\n }\r\n\r\n public set format(format: AudioStreamFormat) {\r\n this.privDestination.format = format;\r\n }\r\n\r\n public write(buffer: ArrayBuffer): void {\r\n this.privDestination.write(buffer);\r\n }\r\n\r\n public close(): void {\r\n this.privDestination.close();\r\n }\r\n\r\n public id(): string {\r\n return this.privDestination.id();\r\n }\r\n\r\n public setProperty(name: string, value: string): void {\r\n throw new Error(\"This AudioConfig instance does not support setting properties.\");\r\n }\r\n\r\n public getProperty(name: string, def?: string): string {\r\n throw new Error(\"This AudioConfig instance does not support getting properties.\");\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\n\r\n/**\r\n * Represents a keyword recognition model for recognizing when\r\n * the user says a keyword to initiate further speech recognition.\r\n * @class KeywordRecognitionModel\r\n */\r\nexport class KeywordRecognitionModel {\r\n private privDisposed: boolean = false;\r\n\r\n /**\r\n * Create and initializes a new instance.\r\n * @constructor\r\n */\r\n private constructor() {\r\n }\r\n\r\n /**\r\n * Creates a keyword recognition model using the specified filename.\r\n * @member KeywordRecognitionModel.fromFile\r\n * @function\r\n * @public\r\n * @param {string} fileName - A string that represents file name for the keyword recognition model.\r\n * Note, the file can point to a zip file in which case the model\r\n * will be extracted from the zip.\r\n * @returns {KeywordRecognitionModel} The keyword recognition model being created.\r\n */\r\n public static fromFile(fileName: string): KeywordRecognitionModel {\r\n Contracts.throwIfFileDoesNotExist(fileName, \"fileName\");\r\n\r\n throw new Error(\"Not yet implemented.\");\r\n }\r\n\r\n /**\r\n * Creates a keyword recognition model using the specified filename.\r\n * @member KeywordRecognitionModel.fromStream\r\n * @function\r\n * @public\r\n * @param {string} file - A File that represents file for the keyword recognition model.\r\n * Note, the file can point to a zip file in which case the model will be extracted from the zip.\r\n * @returns {KeywordRecognitionModel} The keyword recognition model being created.\r\n */\r\n public static fromStream(file: File): KeywordRecognitionModel {\r\n Contracts.throwIfNull(file, \"file\");\r\n\r\n throw new Error(\"Not yet implemented.\");\r\n }\r\n\r\n /**\r\n * Dispose of associated resources.\r\n * @member KeywordRecognitionModel.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n if (this.privDisposed) {\r\n return;\r\n }\r\n\r\n this.privDisposed = true;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines content for session events like SessionStarted/Stopped, SoundStarted/Stopped.\r\n * @class SessionEventArgs\r\n */\r\nexport class SessionEventArgs {\r\n private privSessionId: string;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {string} sessionId - The session id.\r\n */\r\n public constructor(sessionId: string) {\r\n this.privSessionId = sessionId;\r\n }\r\n\r\n /**\r\n * Represents the session identifier.\r\n * @member SessionEventArgs.prototype.sessionId\r\n * @function\r\n * @public\r\n * @returns {string} Represents the session identifier.\r\n */\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { SessionEventArgs } from \"./Exports\";\r\n\r\n/**\r\n * Defines payload for session events like Speech Start/End Detected\r\n * @class\r\n */\r\nexport class RecognitionEventArgs extends SessionEventArgs {\r\n private privOffset: number;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {number} offset - The offset.\r\n * @param {string} sessionId - The session id.\r\n */\r\n public constructor(offset: number, sessionId?: string) {\r\n super(sessionId);\r\n\r\n this.privOffset = offset;\r\n }\r\n\r\n /**\r\n * Represents the message offset\r\n * @member RecognitionEventArgs.prototype.offset\r\n * @function\r\n * @public\r\n */\r\n public get offset(): number {\r\n return this.privOffset;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IntentRecognitionResult, RecognitionEventArgs } from \"./Exports\";\r\n\r\n/**\r\n * Intent recognition result event arguments.\r\n * @class\r\n */\r\nexport class IntentRecognitionEventArgs extends RecognitionEventArgs {\r\n private privResult: IntentRecognitionResult;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param result - The result of the intent recognition.\r\n * @param offset - The offset.\r\n * @param sessionId - The session id.\r\n */\r\n public constructor(result: IntentRecognitionResult, offset?: number, sessionId?: string) {\r\n super(offset, sessionId);\r\n\r\n this.privResult = result;\r\n }\r\n\r\n /**\r\n * Represents the intent recognition result.\r\n * @member IntentRecognitionEventArgs.prototype.result\r\n * @function\r\n * @public\r\n * @returns {IntentRecognitionResult} Represents the intent recognition result.\r\n */\r\n public get result(): IntentRecognitionResult {\r\n return this.privResult;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection, ResultReason } from \"./Exports\";\r\n\r\n/**\r\n * Defines result of speech recognition.\r\n * @class RecognitionResult\r\n */\r\nexport class RecognitionResult {\r\n private privResultId: string;\r\n private privReason: ResultReason;\r\n private privText: string;\r\n private privDuration: number;\r\n private privOffset: number;\r\n private privLanguage: string;\r\n private privLanguageDetectionConfidence: string;\r\n private privErrorDetails: string;\r\n private privJson: string;\r\n private privProperties: PropertyCollection;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {string} resultId - The result id.\r\n * @param {ResultReason} reason - The reason.\r\n * @param {string} text - The recognized text.\r\n * @param {number} duration - The duration.\r\n * @param {number} offset - The offset into the stream.\r\n * @param {string} language - Primary Language detected, if provided.\r\n * @param {string} languageDetectionConfidence - Primary Language confidence (\"Unknown,\" \"Low,\" \"Medium,\" \"High\"...), if provided.\r\n * @param {string} errorDetails - Error details, if provided.\r\n * @param {string} json - Additional Json, if provided.\r\n * @param {PropertyCollection} properties - Additional properties, if provided.\r\n */\r\n constructor(resultId?: string, reason?: ResultReason, text?: string, duration?: number,\r\n offset?: number, language?: string, languageDetectionConfidence?: string, errorDetails?: string, json?: string, properties?: PropertyCollection) {\r\n this.privResultId = resultId;\r\n this.privReason = reason;\r\n this.privText = text;\r\n this.privDuration = duration;\r\n this.privOffset = offset;\r\n this.privLanguage = language;\r\n this.privLanguageDetectionConfidence = languageDetectionConfidence;\r\n this.privErrorDetails = errorDetails;\r\n this.privJson = json;\r\n this.privProperties = properties;\r\n }\r\n\r\n /**\r\n * Specifies the result identifier.\r\n * @member RecognitionResult.prototype.resultId\r\n * @function\r\n * @public\r\n * @returns {string} Specifies the result identifier.\r\n */\r\n public get resultId(): string {\r\n return this.privResultId;\r\n }\r\n\r\n /**\r\n * Specifies status of the result.\r\n * @member RecognitionResult.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {ResultReason} Specifies status of the result.\r\n */\r\n public get reason(): ResultReason {\r\n return this.privReason;\r\n }\r\n\r\n /**\r\n * Presents the recognized text in the result.\r\n * @member RecognitionResult.prototype.text\r\n * @function\r\n * @public\r\n * @returns {string} Presents the recognized text in the result.\r\n */\r\n public get text(): string {\r\n return this.privText;\r\n }\r\n\r\n /**\r\n * Duration of recognized speech in 100 nano second incements.\r\n * @member RecognitionResult.prototype.duration\r\n * @function\r\n * @public\r\n * @returns {number} Duration of recognized speech in 100 nano second incements.\r\n */\r\n public get duration(): number {\r\n return this.privDuration;\r\n }\r\n\r\n /**\r\n * Offset of recognized speech in 100 nano second incements.\r\n * @member RecognitionResult.prototype.offset\r\n * @function\r\n * @public\r\n * @returns {number} Offset of recognized speech in 100 nano second incements.\r\n */\r\n public get offset(): number {\r\n return this.privOffset;\r\n }\r\n\r\n /**\r\n * Primary Language detected.\r\n * @member RecognitionResult.prototype.language\r\n * @function\r\n * @public\r\n * @returns {string} language detected.\r\n */\r\n public get language(): string {\r\n return this.privLanguage;\r\n }\r\n\r\n /**\r\n * Primary Language detection confidence (Unknown, Low, Medium, High).\r\n * @member RecognitionResult.prototype.languageDetectionConfidence\r\n * @function\r\n * @public\r\n * @returns {string} detection confidence strength.\r\n */\r\n public get languageDetectionConfidence(): string {\r\n return this.privLanguageDetectionConfidence;\r\n }\r\n\r\n /**\r\n * In case of an unsuccessful recognition, provides details of the occurred error.\r\n * @member RecognitionResult.prototype.errorDetails\r\n * @function\r\n * @public\r\n * @returns {string} a brief description of an error.\r\n */\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n\r\n /**\r\n * A string containing Json serialized recognition result as it was received from the service.\r\n * @member RecognitionResult.prototype.json\r\n * @function\r\n * @private\r\n * @returns {string} Json serialized representation of the result.\r\n */\r\n public get json(): string {\r\n return this.privJson;\r\n }\r\n\r\n /**\r\n * The set of properties exposed in the result.\r\n * @member RecognitionResult.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The set of properties exposed in the result.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection, RecognitionResult, ResultReason } from \"./Exports\";\r\n\r\n/**\r\n * Defines result of speech recognition.\r\n * @class SpeechRecognitionResult\r\n */\r\nexport class SpeechRecognitionResult extends RecognitionResult {\r\n private readonly privSpeakerId: string;\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @public\r\n * @param {string} resultId - The result id.\r\n * @param {ResultReason} reason - The reason.\r\n * @param {string} text - The recognized text.\r\n * @param {number} duration - The duration.\r\n * @param {number} offset - The offset into the stream.\r\n * @param {string} language - Primary Language detected, if provided.\r\n * @param {string} languageDetectionConfidence - Primary Language confidence (\"Unknown,\" \"Low,\" \"Medium,\" \"High\"...), if provided.\r\n * @param {string} speakerId - speaker id for conversation transcription, if provided.\r\n * @param {string} errorDetails - Error details, if provided.\r\n * @param {string} json - Additional Json, if provided.\r\n * @param {PropertyCollection} properties - Additional properties, if provided.\r\n */\r\n public constructor(resultId?: string, reason?: ResultReason, text?: string,\r\n duration?: number, offset?: number, language?: string,\r\n languageDetectionConfidence?: string, speakerId?: string, errorDetails?: string,\r\n json?: string, properties?: PropertyCollection) {\r\n super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties);\r\n this.privSpeakerId = speakerId;\r\n }\r\n\r\n /**\r\n * speaker id from conversation transcription/id scenarios\r\n * @member SpeechRecognitionResult.prototype.speakerId\r\n * @function\r\n * @public\r\n * @returns {string} id of speaker in given result\r\n */\r\n public get speakerId(): string {\r\n return this.privSpeakerId;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection, ResultReason, SpeechRecognitionResult } from \"./Exports\";\r\n\r\n/**\r\n * Intent recognition result.\r\n * @class\r\n */\r\nexport class IntentRecognitionResult extends SpeechRecognitionResult {\r\n private privIntentId: string;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param intentId - The intent id.\r\n * @param resultId - The result id.\r\n * @param reason - The reason.\r\n * @param text - The recognized text.\r\n * @param duration - The duration.\r\n * @param offset - The offset into the stream.\r\n * @param language - Primary Language detected, if provided.\r\n * @param languageDetectionConfidence - Primary Language confidence (\"Unknown,\" \"Low,\" \"Medium,\" \"High\"...), if provided.\r\n * @param errorDetails - Error details, if provided.\r\n * @param json - Additional Json, if provided.\r\n * @param properties - Additional properties, if provided.\r\n */\r\n constructor(intentId?: string, resultId?: string, reason?: ResultReason, text?: string,\r\n duration?: number, offset?: number, language?: string, languageDetectionConfidence?: string,\r\n errorDetails?: string, json?: string, properties?: PropertyCollection) {\r\n super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, undefined, errorDetails, json, properties);\r\n\r\n this.privIntentId = intentId;\r\n }\r\n\r\n /**\r\n * A String that represents the intent identifier being recognized.\r\n * @member IntentRecognitionResult.prototype.intentId\r\n * @function\r\n * @public\r\n * @returns {string} A String that represents the intent identifier being recognized.\r\n */\r\n public get intentId(): string {\r\n return this.privIntentId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\n\r\n/**\r\n * Language understanding model\r\n * @class LanguageUnderstandingModel\r\n */\r\nexport class LanguageUnderstandingModel {\r\n /**\r\n * Creates and initializes a new instance\r\n * @constructor\r\n */\r\n protected constructor() {\r\n }\r\n\r\n /**\r\n * Creates an language understanding model using the specified endpoint.\r\n * @member LanguageUnderstandingModel.fromEndpoint\r\n * @function\r\n * @public\r\n * @param {URL} uri - A String that represents the endpoint of the language understanding model.\r\n * @returns {LanguageUnderstandingModel} The language understanding model being created.\r\n */\r\n public static fromEndpoint(uri: URL): LanguageUnderstandingModel {\r\n Contracts.throwIfNull(uri, \"uri\");\r\n Contracts.throwIfNullOrWhitespace(uri.hostname, \"uri\");\r\n\r\n const langModelImp: LanguageUnderstandingModelImpl = new LanguageUnderstandingModelImpl();\r\n // Need to extract the app ID from the URL.\r\n // URL is in the format: https://.api.cognitive.microsoft.com/luis/v2.0/apps/?subscription-key=&timezoneOffset=-360\r\n\r\n // Start tearing the string apart.\r\n\r\n // region can be extracted from the host name.\r\n const firstDot: number = uri.host.indexOf(\".\");\r\n if (-1 === firstDot) {\r\n throw new Error(\"Could not determine region from endpoint\");\r\n }\r\n langModelImp.region = uri.host.substr(0, firstDot);\r\n\r\n // Now the app ID.\r\n\r\n const lastSegment: number = uri.pathname.lastIndexOf(\"/\") + 1;\r\n if (-1 === lastSegment) {\r\n throw new Error(\"Could not determine appId from endpoint\");\r\n }\r\n\r\n langModelImp.appId = uri.pathname.substr(lastSegment);\r\n\r\n // And finally the key.\r\n langModelImp.subscriptionKey = uri.searchParams.get(\"subscription-key\");\r\n if (undefined === langModelImp.subscriptionKey) {\r\n throw new Error(\"Could not determine subscription key from endpoint\");\r\n }\r\n\r\n return langModelImp;\r\n }\r\n\r\n /**\r\n * Creates an language understanding model using the application id of Language Understanding service.\r\n * @member LanguageUnderstandingModel.fromAppId\r\n * @function\r\n * @public\r\n * @param {string} appId - A String that represents the application id of Language Understanding service.\r\n * @returns {LanguageUnderstandingModel} The language understanding model being created.\r\n */\r\n public static fromAppId(appId: string): LanguageUnderstandingModel {\r\n Contracts.throwIfNullOrWhitespace(appId, \"appId\");\r\n\r\n const langModelImp: LanguageUnderstandingModelImpl = new LanguageUnderstandingModelImpl();\r\n langModelImp.appId = appId;\r\n return langModelImp;\r\n }\r\n\r\n /**\r\n * Creates a language understanding model using hostname, subscription key and application\r\n * id of Language Understanding service.\r\n * @member LanguageUnderstandingModel.fromSubscription\r\n * @function\r\n * @public\r\n * @param {string} subscriptionKey - A String that represents the subscription key of\r\n * Language Understanding service.\r\n * @param {string} appId - A String that represents the application id of Language\r\n * Understanding service.\r\n * @param {LanguageUnderstandingModel} region - A String that represents the region\r\n * of the Language Understanding service (see the region page).\r\n * @returns {LanguageUnderstandingModel} The language understanding model being created.\r\n */\r\n public static fromSubscription(subscriptionKey: string, appId: string, region: string): LanguageUnderstandingModel {\r\n Contracts.throwIfNullOrWhitespace(subscriptionKey, \"subscriptionKey\");\r\n Contracts.throwIfNullOrWhitespace(appId, \"appId\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const langModelImp: LanguageUnderstandingModelImpl = new LanguageUnderstandingModelImpl();\r\n langModelImp.appId = appId;\r\n langModelImp.region = region;\r\n langModelImp.subscriptionKey = subscriptionKey;\r\n return langModelImp;\r\n }\r\n}\r\n\r\n/**\r\n * @private\r\n * @class LanguageUnderstandingModelImpl\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class LanguageUnderstandingModelImpl extends LanguageUnderstandingModel {\r\n public appId: string;\r\n public region: string;\r\n public subscriptionKey: string;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RecognitionEventArgs, SpeechRecognitionResult } from \"./Exports\";\r\n\r\n/**\r\n * Defines contents of speech recognizing/recognized event.\r\n * @class SpeechRecognitionEventArgs\r\n */\r\nexport class SpeechRecognitionEventArgs extends RecognitionEventArgs {\r\n private privResult: SpeechRecognitionResult;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {SpeechRecognitionResult} result - The speech recognition result.\r\n * @param {number} offset - The offset.\r\n * @param {string} sessionId - The session id.\r\n */\r\n public constructor(result: SpeechRecognitionResult, offset?: number, sessionId?: string) {\r\n super(offset, sessionId);\r\n\r\n this.privResult = result;\r\n }\r\n\r\n /**\r\n * Specifies the recognition result.\r\n * @member SpeechRecognitionEventArgs.prototype.result\r\n * @function\r\n * @public\r\n * @returns {SpeechRecognitionResult} the recognition result.\r\n */\r\n public get result(): SpeechRecognitionResult {\r\n return this.privResult;\r\n }\r\n}\r\n\r\n/**\r\n * Defines contents of conversation transcribed/transcribing event.\r\n * @class ConversationTranscriptionEventArgs\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class ConversationTranscriptionEventArgs extends SpeechRecognitionEventArgs {\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationErrorCode,\r\n CancellationEventArgs,\r\n CancellationReason,\r\n RecognitionEventArgs\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Defines content of a CancellationEvent.\r\n * @class CancellationEventArgsBase\r\n */\r\nexport class CancellationEventArgsBase extends RecognitionEventArgs implements CancellationEventArgs {\r\n private privReason: CancellationReason;\r\n private privErrorDetails: string;\r\n private privErrorCode: CancellationErrorCode;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {CancellationReason} reason - The cancellation reason.\r\n * @param {string} errorDetails - Error details, if provided.\r\n * @param {number} offset - The offset.\r\n * @param {string} sessionId - The session id.\r\n */\r\n public constructor(reason: CancellationReason, errorDetails: string,\r\n errorCode: CancellationErrorCode, offset?: number, sessionId?: string) {\r\n super(offset, sessionId);\r\n\r\n this.privReason = reason;\r\n this.privErrorDetails = errorDetails;\r\n this.privErrorCode = errorCode;\r\n }\r\n\r\n /**\r\n * The reason the recognition was canceled.\r\n * @member CancellationEventArgsBase.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {CancellationReason} Specifies the reason canceled.\r\n */\r\n public get reason(): CancellationReason {\r\n return this.privReason;\r\n }\r\n\r\n /**\r\n * The error code in case of an unsuccessful operation.\r\n * @return An error code that represents the error reason.\r\n */\r\n public get errorCode(): CancellationErrorCode {\r\n return this.privErrorCode;\r\n }\r\n\r\n /**\r\n * In case of an unsuccessful operation, provides details of the occurred error.\r\n * @member CancellationEventArgsBase.prototype.errorDetails\r\n * @function\r\n * @public\r\n * @returns {string} A String that represents the error details.\r\n */\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationEventArgsBase,\r\n} from \"./CancellationEventArgsBase\";\r\n\r\nexport class SpeechRecognitionCanceledEventArgs extends CancellationEventArgsBase {\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RecognitionEventArgs, TranslationRecognitionResult } from \"./Exports\";\r\n\r\n/**\r\n * Translation text result event arguments.\r\n * @class TranslationRecognitionEventArgs\r\n */\r\nexport class TranslationRecognitionEventArgs extends RecognitionEventArgs {\r\n private privResult: TranslationRecognitionResult;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {TranslationRecognitionResult} result - The translation recognition result.\r\n * @param {number} offset - The offset.\r\n * @param {string} sessionId - The session id.\r\n */\r\n public constructor(result: TranslationRecognitionResult, offset?: number, sessionId?: string) {\r\n super(offset, sessionId);\r\n\r\n this.privResult = result;\r\n }\r\n\r\n /**\r\n * Specifies the recognition result.\r\n * @member TranslationRecognitionEventArgs.prototype.result\r\n * @function\r\n * @public\r\n * @returns {TranslationRecognitionResult} the recognition result.\r\n */\r\n public get result(): TranslationRecognitionResult {\r\n return this.privResult;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { SessionEventArgs, TranslationSynthesisResult } from \"./Exports\";\r\n\r\n/**\r\n * Translation Synthesis event arguments\r\n * @class TranslationSynthesisEventArgs\r\n */\r\nexport class TranslationSynthesisEventArgs extends SessionEventArgs {\r\n private privResult: TranslationSynthesisResult;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {TranslationSynthesisResult} result - The translation synthesis result.\r\n * @param {string} sessionId - The session id.\r\n */\r\n public constructor(result: TranslationSynthesisResult, sessionId?: string) {\r\n super(sessionId);\r\n\r\n this.privResult = result;\r\n }\r\n\r\n /**\r\n * Specifies the translation synthesis result.\r\n * @member TranslationSynthesisEventArgs.prototype.result\r\n * @function\r\n * @public\r\n * @returns {TranslationSynthesisResult} Specifies the translation synthesis result.\r\n */\r\n public get result(): TranslationSynthesisResult {\r\n return this.privResult;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection, ResultReason, SpeechRecognitionResult, Translations } from \"./Exports\";\r\n\r\n/**\r\n * Translation text result.\r\n * @class TranslationRecognitionResult\r\n */\r\nexport class TranslationRecognitionResult extends SpeechRecognitionResult {\r\n private privTranslations: Translations;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {Translations} translations - The translations.\r\n * @param {string} resultId - The result id.\r\n * @param {ResultReason} reason - The reason.\r\n * @param {string} text - The recognized text.\r\n * @param {number} duration - The duration.\r\n * @param {number} offset - The offset into the stream.\r\n * @param {string} errorDetails - Error details, if provided.\r\n * @param {string} json - Additional Json, if provided.\r\n * @param {PropertyCollection} properties - Additional properties, if provided.\r\n */\r\n public constructor(translations: Translations, resultId?: string, reason?: ResultReason,\r\n text?: string, duration?: number, offset?: number, errorDetails?: string,\r\n json?: string, properties?: PropertyCollection) {\r\n super(resultId, reason, text, duration, offset, undefined, undefined, undefined, errorDetails, json, properties);\r\n\r\n this.privTranslations = translations;\r\n }\r\n\r\n /**\r\n * Presents the translation results. Each item in the dictionary represents\r\n * a translation result in one of target languages, where the key is the name\r\n * of the target language, in BCP-47 format, and the value is the translation\r\n * text in the specified language.\r\n * @member TranslationRecognitionResult.prototype.translations\r\n * @function\r\n * @public\r\n * @returns {Translations} the current translation map that holds all translations requested.\r\n */\r\n public get translations(): Translations {\r\n return this.privTranslations;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ResultReason } from \"./ResultReason\";\r\n\r\n/**\r\n * Defines translation synthesis result, i.e. the voice output of the translated\r\n * text in the target language.\r\n * @class TranslationSynthesisResult\r\n */\r\nexport class TranslationSynthesisResult {\r\n private privReason: ResultReason;\r\n private privAudio: ArrayBuffer;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {ResultReason} reason - The synthesis reason.\r\n * @param {ArrayBuffer} audio - The audio data.\r\n */\r\n constructor(reason: ResultReason, audio: ArrayBuffer) {\r\n this.privReason = reason;\r\n this.privAudio = audio;\r\n }\r\n\r\n /**\r\n * Translated text in the target language.\r\n * @member TranslationSynthesisResult.prototype.audio\r\n * @function\r\n * @public\r\n * @returns {ArrayBuffer} Translated audio in the target language.\r\n */\r\n public get audio(): ArrayBuffer {\r\n return this.privAudio;\r\n }\r\n\r\n /**\r\n * The synthesis status.\r\n * @member TranslationSynthesisResult.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {ResultReason} The synthesis status.\r\n */\r\n public get reason(): ResultReason {\r\n return this.privReason;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ForceDictationPropertyName,\r\n OutputFormatPropertyName,\r\n ServicePropertiesPropertyName\r\n} from \"../common.speech/Exports\";\r\nimport {IStringDictionary} from \"../common/Exports\";\r\nimport {Contracts} from \"./Contracts\";\r\nimport {\r\n OutputFormat,\r\n ProfanityOption,\r\n PropertyCollection,\r\n PropertyId,\r\n ServicePropertyChannel,\r\n SpeechSynthesisOutputFormat,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Speech configuration.\r\n * @class SpeechConfig\r\n */\r\nexport abstract class SpeechConfig {\r\n /**\r\n * Creates and initializes an instance.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Static instance of SpeechConfig returned by passing subscriptionKey and service region.\r\n * Note: Please use your LanguageUnderstanding subscription key in case you want to use the Intent recognizer.\r\n * @member SpeechConfig.fromSubscription\r\n * @function\r\n * @public\r\n * @param {string} subscriptionKey - The subscription key.\r\n * @param {string} region - The region name (see the region page).\r\n * @returns {SpeechConfig} The speech factory\r\n */\r\n public static fromSubscription(subscriptionKey: string, region: string): SpeechConfig {\r\n Contracts.throwIfNullOrWhitespace(subscriptionKey, \"subscriptionKey\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const speechImpl: SpeechConfigImpl = new SpeechConfigImpl();\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_IntentRegion, region);\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n\r\n return speechImpl;\r\n }\r\n\r\n /**\r\n * Creates an instance of the speech config with specified endpoint and subscription key.\r\n * This method is intended only for users who use a non-standard service endpoint or parameters.\r\n * Note: Please use your LanguageUnderstanding subscription key in case you want to use the Intent recognizer.\r\n * Note: The query parameters specified in the endpoint URL are not changed, even if they are set by any other APIs.\r\n * For example, if language is defined in the uri as query parameter \"language=de-DE\", and also set by\r\n * SpeechConfig.speechRecognitionLanguage = \"en-US\", the language setting in uri takes precedence,\r\n * and the effective language is \"de-DE\". Only the parameters that are not specified in the\r\n * endpoint URL can be set by other APIs.\r\n * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the\r\n * fromEndpoint method, and then set authorizationToken=\"token\" on the created SpeechConfig instance to\r\n * use the authorization token.\r\n * @member SpeechConfig.fromEndpoint\r\n * @function\r\n * @public\r\n * @param {URL} endpoint - The service endpoint to connect to.\r\n * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set.\r\n * @returns {SpeechConfig} A speech factory instance.\r\n */\r\n public static fromEndpoint(endpoint: URL, subscriptionKey?: string): SpeechConfig {\r\n Contracts.throwIfNull(endpoint, \"endpoint\");\r\n\r\n const speechImpl: SpeechConfigImpl = new SpeechConfigImpl();\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Endpoint, endpoint.href);\r\n\r\n if (undefined !== subscriptionKey) {\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n }\r\n return speechImpl;\r\n }\r\n\r\n /**\r\n * Creates an instance of the speech config with specified host and subscription key.\r\n * This method is intended only for users who use a non-default service host. Standard resource path will be assumed.\r\n * For services with a non-standard resource path or no path at all, use fromEndpoint instead.\r\n * Note: Query parameters are not allowed in the host URI and must be set by other APIs.\r\n * Note: To use an authorization token with fromHost, use fromHost(URL),\r\n * and then set the AuthorizationToken property on the created SpeechConfig instance.\r\n * Note: Added in version 1.9.0.\r\n * @member SpeechConfig.fromHost\r\n * @function\r\n * @public\r\n * @param {URL} host - The service endpoint to connect to. Format is \"protocol://host:port\" where \":port\" is optional.\r\n * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set.\r\n * @returns {SpeechConfig} A speech factory instance.\r\n */\r\n public static fromHost(hostName: URL, subscriptionKey?: string): SpeechConfig {\r\n Contracts.throwIfNull(hostName, \"hostName\");\r\n\r\n const speechImpl: SpeechConfigImpl = new SpeechConfigImpl();\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Host, hostName.protocol + \"//\" + hostName.hostname + (hostName.port === \"\" ? \"\" : \":\" + hostName.port));\r\n\r\n if (undefined !== subscriptionKey) {\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n }\r\n return speechImpl;\r\n }\r\n\r\n /**\r\n * Creates an instance of the speech factory with specified initial authorization token and region.\r\n * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token\r\n * expires, the caller needs to refresh it by calling this setter with a new valid token.\r\n * Note: Please use a token derived from your LanguageUnderstanding subscription key in case you want\r\n * to use the Intent recognizer. As configuration values are copied when creating a new recognizer,\r\n * the new token value will not apply to recognizers that have already been created. For recognizers\r\n * that have been created before, you need to set authorization token of the corresponding recognizer\r\n * to refresh the token. Otherwise, the recognizers will encounter errors during recognition.\r\n * @member SpeechConfig.fromAuthorizationToken\r\n * @function\r\n * @public\r\n * @param {string} authorizationToken - The initial authorization token.\r\n * @param {string} region - The region name (see the region page).\r\n * @returns {SpeechConfig} A speech factory instance.\r\n */\r\n public static fromAuthorizationToken(authorizationToken: string, region: string): SpeechConfig {\r\n Contracts.throwIfNull(authorizationToken, \"authorizationToken\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const speechImpl: SpeechConfigImpl = new SpeechConfigImpl();\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_IntentRegion, region);\r\n speechImpl.authorizationToken = authorizationToken;\r\n return speechImpl;\r\n }\r\n\r\n /**\r\n * Sets the proxy configuration.\r\n * Only relevant in Node.js environments.\r\n * Added in version 1.4.0.\r\n * @param proxyHostName The host name of the proxy server.\r\n * @param proxyPort The port number of the proxy server.\r\n */\r\n public abstract setProxy(proxyHostName: string, proxyPort: number): void;\r\n\r\n /**\r\n * Sets the proxy configuration.\r\n * Only relevant in Node.js environments.\r\n * Added in version 1.4.0.\r\n * @param proxyHostName The host name of the proxy server, without the protocol scheme (http://)\r\n * @param proxyPort The port number of the proxy server.\r\n * @param proxyUserName The user name of the proxy server.\r\n * @param proxyPassword The password of the proxy server.\r\n */\r\n public abstract setProxy(proxyHostName: string, proxyPort: number, proxyUserName: string, proxyPassword: string): void;\r\n\r\n /**\r\n * Gets the authorization token.\r\n * @member SpeechConfig.prototype.authorizationToken\r\n * @function\r\n * @public\r\n */\r\n public abstract get authorizationToken(): string;\r\n\r\n /**\r\n * Gets/Sets the authorization token.\r\n * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token\r\n * expires, the caller needs to refresh it by calling this setter with a new valid token.\r\n * @member SpeechConfig.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} value - The authorization token.\r\n */\r\n public abstract set authorizationToken(value: string);\r\n\r\n /**\r\n * Returns the configured language.\r\n * @member SpeechConfig.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n */\r\n public abstract get speechRecognitionLanguage(): string;\r\n\r\n /**\r\n * Gets/Sets the input language.\r\n * @member SpeechConfig.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The authorization token.\r\n */\r\n public abstract set speechRecognitionLanguage(value: string);\r\n\r\n /**\r\n * Sets an arbitrary property.\r\n * @member SpeechConfig.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to set.\r\n * @param {string} value - The new value of the property.\r\n */\r\n public abstract setProperty(name: string, value: string): void;\r\n\r\n /**\r\n * Returns the current value of an arbitrary property.\r\n * @member SpeechConfig.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to query.\r\n * @param {string} def - The value to return in case the property is not known.\r\n * @returns {string} The current value, or provided default, of the given property.\r\n */\r\n public abstract getProperty(name: string, def?: string): string;\r\n\r\n /**\r\n * Gets speech recognition output format (simple or detailed).\r\n * Note: This output format is for speech recognition result, use [SpeechConfig.speechSynthesisOutputFormat] to\r\n * get synthesized audio output format.\r\n * @member SpeechConfig.prototype.outputFormat\r\n * @function\r\n * @public\r\n * @returns {OutputFormat} Returns the output format.\r\n */\r\n public abstract get outputFormat(): OutputFormat;\r\n\r\n /**\r\n * Gets/Sets speech recognition output format (simple or detailed).\r\n * Note: This output format is for speech recognition result, use [SpeechConfig.speechSynthesisOutputFormat] to\r\n * set synthesized audio output format.\r\n * @member SpeechConfig.prototype.outputFormat\r\n * @function\r\n * @public\r\n */\r\n public abstract set outputFormat(format: OutputFormat);\r\n\r\n /**\r\n * Gets the endpoint ID of a customized speech model that is used for speech recognition.\r\n * @member SpeechConfig.prototype.endpointId\r\n * @function\r\n * @public\r\n * @return {string} The endpoint ID\r\n */\r\n public abstract get endpointId(): string;\r\n\r\n /**\r\n * Gets/Sets the endpoint ID of a customized speech model that is used for speech recognition.\r\n * @member SpeechConfig.prototype.endpointId\r\n * @function\r\n * @public\r\n * @param {string} value - The endpoint ID\r\n */\r\n public abstract set endpointId(value: string);\r\n\r\n /**\r\n * Closes the configuration.\r\n * @member SpeechConfig.prototype.close\r\n * @function\r\n * @public\r\n */\r\n /* tslint:disable:no-empty */\r\n public close(): void { }\r\n\r\n /**\r\n * @member SpeechConfig.prototype.subscriptionKey\r\n * @function\r\n * @public\r\n * @return {string} The subscription key set on the config.\r\n */\r\n public abstract get subscriptionKey(): string;\r\n\r\n /**\r\n * @member SpeechConfig.prototype.region\r\n * @function\r\n * @public\r\n * @return {region} The region set on the config.\r\n */\r\n public abstract get region(): string;\r\n\r\n /**\r\n * @member SpeechConfig.prototype.setServiceProperty\r\n * @function\r\n * @public\r\n * @param {name} The name of the property.\r\n * @param {value} Value to set.\r\n * @param {channel} The channel used to pass the specified property to service.\r\n * @summary Sets a property value that will be passed to service using the specified channel.\r\n * Added in version 1.7.0.\r\n */\r\n public abstract setServiceProperty(name: string, value: string, channel: ServicePropertyChannel): void;\r\n\r\n /**\r\n * @member SpeechConfig.prototype.setProfanity\r\n * @function\r\n * @public\r\n * @param {profanity} Profanity option to set.\r\n * @summary Sets profanity option.\r\n * Added in version 1.7.0.\r\n */\r\n public abstract setProfanity(profanity: ProfanityOption): void;\r\n\r\n /**\r\n * @member SpeechConfig.prototype.enableAudioLogging\r\n * @function\r\n * @public\r\n * @summary Enable audio logging in service.\r\n * Added in version 1.7.0.\r\n */\r\n public abstract enableAudioLogging(): void;\r\n\r\n /**\r\n * @member SpeechConfig.prototype.requestWordLevelTimestamps\r\n * @function\r\n * @public\r\n * @summary Includes word-level timestamps.\r\n * Added in version 1.7.0.\r\n */\r\n public abstract requestWordLevelTimestamps(): void;\r\n\r\n /**\r\n * @member SpeechConfig.prototype.enableDictation\r\n * @function\r\n * @public\r\n * @summary Enable dictation. Only supported in speech continuous recognition.\r\n * Added in version 1.7.0.\r\n */\r\n public abstract enableDictation(): void;\r\n\r\n /**\r\n * Gets the language of the speech synthesizer.\r\n * @member SpeechConfig.prototype.speechSynthesisLanguage\r\n * @function\r\n * @public\r\n * @returns {string} Returns the speech synthesis language.\r\n * Added in version 1.11.0.\r\n */\r\n public abstract get speechSynthesisLanguage(): string;\r\n\r\n /**\r\n * Sets the language of the speech synthesizer.\r\n * @member SpeechConfig.prototype.speechSynthesisLanguage\r\n * @function\r\n * @public\r\n * Added in version 1.11.0.\r\n */\r\n public abstract set speechSynthesisLanguage(language: string);\r\n\r\n /**\r\n * Gets the voice of the speech synthesizer.\r\n * @member SpeechConfig.prototype.speechSynthesisVoiceName\r\n * @function\r\n * @public\r\n * @returns {string} Returns the speech synthesis voice.\r\n * Added in version 1.11.0.\r\n */\r\n public abstract get speechSynthesisVoiceName(): string;\r\n\r\n /**\r\n * Sets the voice of the speech synthesizer. (see available voices).\r\n * @member SpeechConfig.prototype.speechSynthesisVoiceName\r\n * @function\r\n * @public\r\n * Added in version 1.11.0.\r\n */\r\n public abstract set speechSynthesisVoiceName(voice: string);\r\n\r\n /**\r\n * Gets the speech synthesis output format.\r\n * @member SpeechConfig.prototype.speechSynthesisOutputFormat\r\n * @function\r\n * @public\r\n * @returns {SpeechSynthesisOutputFormat} Returns the speech synthesis output format\r\n * Added in version 1.11.0.\r\n */\r\n public abstract get speechSynthesisOutputFormat(): SpeechSynthesisOutputFormat;\r\n\r\n /**\r\n * Sets the speech synthesis output format (e.g. Riff16Khz16BitMonoPcm).\r\n * @member SpeechConfig.prototype.speechSynthesisOutputFormat\r\n * @function\r\n * @public\r\n * The default format is Audio16Khz64KBitRateMonoMp3 for browser and Riff16Khz16BitMonoPcm for Node.JS\r\n * Added in version 1.11.0.\r\n */\r\n public abstract set speechSynthesisOutputFormat(format: SpeechSynthesisOutputFormat);\r\n}\r\n\r\n/**\r\n * @public\r\n * @class SpeechConfigImpl\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class SpeechConfigImpl extends SpeechConfig {\r\n\r\n private privProperties: PropertyCollection;\r\n\r\n public constructor() {\r\n super();\r\n this.privProperties = new PropertyCollection();\r\n this.speechRecognitionLanguage = \"en-US\"; // Should we have a default?\r\n this.outputFormat = OutputFormat.Simple;\r\n }\r\n\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public get endPoint(): URL {\r\n return new URL(this.privProperties.getProperty(PropertyId.SpeechServiceConnection_Endpoint));\r\n }\r\n\r\n public get subscriptionKey(): string {\r\n return this.privProperties.getProperty(PropertyId.SpeechServiceConnection_Key);\r\n }\r\n\r\n public get region(): string {\r\n return this.privProperties.getProperty(PropertyId.SpeechServiceConnection_Region);\r\n }\r\n\r\n public get authorizationToken(): string {\r\n return this.privProperties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n public set authorizationToken(value: string) {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceAuthorization_Token, value);\r\n }\r\n\r\n public get speechRecognitionLanguage(): string {\r\n return this.privProperties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);\r\n }\r\n\r\n public set speechRecognitionLanguage(value: string) {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceConnection_RecoLanguage, value);\r\n }\r\n\r\n public get autoDetectSourceLanguages(): string {\r\n return this.privProperties.getProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages);\r\n }\r\n\r\n public set autoDetectSourceLanguages(value: string) {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, value);\r\n }\r\n\r\n public get outputFormat(): OutputFormat {\r\n return (OutputFormat as any)[this.privProperties.getProperty(OutputFormatPropertyName, undefined)];\r\n }\r\n\r\n public set outputFormat(value: OutputFormat) {\r\n this.privProperties.setProperty(OutputFormatPropertyName, OutputFormat[value]);\r\n }\r\n\r\n public get endpointId(): string {\r\n return this.privProperties.getProperty(PropertyId.SpeechServiceConnection_EndpointId);\r\n }\r\n\r\n public set endpointId(value: string) {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceConnection_EndpointId, value);\r\n }\r\n\r\n public setProperty(name: string | PropertyId, value: string): void {\r\n Contracts.throwIfNull(value, \"value\");\r\n\r\n this.privProperties.setProperty(name, value);\r\n }\r\n\r\n public getProperty(name: string | PropertyId, def?: string): string {\r\n\r\n return this.privProperties.getProperty(name, def);\r\n }\r\n\r\n public setProxy(proxyHostName: string, proxyPort: number): void;\r\n public setProxy(proxyHostName: string, proxyPort: number, proxyUserName: string, proxyPassword: string): void;\r\n public setProxy(proxyHostName: any, proxyPort: any, proxyUserName?: any, proxyPassword?: any): void {\r\n this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName);\r\n this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyPort], proxyPort);\r\n this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName);\r\n this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword);\r\n }\r\n\r\n public setServiceProperty(name: string, value: string, channel: ServicePropertyChannel): void {\r\n const currentProperties: IStringDictionary = JSON.parse(this.privProperties.getProperty(ServicePropertiesPropertyName, \"{}\"));\r\n\r\n currentProperties[name] = value;\r\n\r\n this.privProperties.setProperty(ServicePropertiesPropertyName, JSON.stringify(currentProperties));\r\n }\r\n\r\n public setProfanity(profanity: ProfanityOption): void {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceResponse_ProfanityOption, ProfanityOption[profanity]);\r\n }\r\n\r\n public enableAudioLogging(): void {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceConnection_EnableAudioLogging, \"true\");\r\n }\r\n public requestWordLevelTimestamps(): void {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, \"true\");\r\n }\r\n public enableDictation(): void {\r\n this.privProperties.setProperty(ForceDictationPropertyName, \"true\");\r\n }\r\n\r\n public clone(): SpeechConfigImpl {\r\n const ret: SpeechConfigImpl = new SpeechConfigImpl();\r\n ret.privProperties = this.privProperties.clone();\r\n return ret;\r\n }\r\n\r\n public get speechSynthesisLanguage(): string {\r\n return this.privProperties.getProperty(PropertyId.SpeechServiceConnection_SynthLanguage);\r\n }\r\n\r\n public set speechSynthesisLanguage(language: string) {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceConnection_SynthLanguage, language);\r\n }\r\n\r\n public get speechSynthesisVoiceName(): string {\r\n return this.privProperties.getProperty(PropertyId.SpeechServiceConnection_SynthVoice);\r\n }\r\n\r\n public set speechSynthesisVoiceName(voice: string) {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceConnection_SynthVoice, voice);\r\n }\r\n\r\n public get speechSynthesisOutputFormat(): SpeechSynthesisOutputFormat {\r\n return (SpeechSynthesisOutputFormat as any)[this.privProperties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)];\r\n }\r\n\r\n public set speechSynthesisOutputFormat(format: SpeechSynthesisOutputFormat) {\r\n this.privProperties.setProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, SpeechSynthesisOutputFormat[format]);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ForceDictationPropertyName,\r\n OutputFormatPropertyName,\r\n ServicePropertiesPropertyName\r\n} from \"../common.speech/Exports\";\r\nimport { IStringDictionary } from \"../common/Exports\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n OutputFormat,\r\n ProfanityOption,\r\n PropertyCollection,\r\n PropertyId,\r\n ServicePropertyChannel,\r\n SpeechConfig, SpeechSynthesisOutputFormat,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Speech translation configuration.\r\n * @class SpeechTranslationConfig\r\n */\r\nexport abstract class SpeechTranslationConfig extends SpeechConfig {\r\n\r\n /**\r\n * Creates an instance of recognizer config.\r\n */\r\n protected constructor() {\r\n super();\r\n }\r\n\r\n /**\r\n * Static instance of SpeechTranslationConfig returned by passing a subscription key and service region.\r\n * @member SpeechTranslationConfig.fromSubscription\r\n * @function\r\n * @public\r\n * @param {string} subscriptionKey - The subscription key.\r\n * @param {string} region - The region name (see the region page).\r\n * @returns {SpeechTranslationConfig} The speech translation config.\r\n */\r\n public static fromSubscription(subscriptionKey: string, region: string): SpeechTranslationConfig {\r\n Contracts.throwIfNullOrWhitespace(subscriptionKey, \"subscriptionKey\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const ret: SpeechTranslationConfigImpl = new SpeechTranslationConfigImpl();\r\n ret.properties.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n ret.properties.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n return ret;\r\n }\r\n\r\n /**\r\n * Static instance of SpeechTranslationConfig returned by passing authorization token and service region.\r\n * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token\r\n * expires, the caller needs to refresh it by setting the property authorizationToken with a new\r\n * valid token. Otherwise, all the recognizers created by this SpeechTranslationConfig instance\r\n * will encounter errors during recognition.\r\n * As configuration values are copied when creating a new recognizer, the new token value will not apply\r\n * to recognizers that have already been created.\r\n * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer\r\n * to refresh the token. Otherwise, the recognizers will encounter errors during recognition.\r\n * @member SpeechTranslationConfig.fromAuthorizationToken\r\n * @function\r\n * @public\r\n * @param {string} authorizationToken - The authorization token.\r\n * @param {string} region - The region name (see the region page).\r\n * @returns {SpeechTranslationConfig} The speech translation config.\r\n */\r\n public static fromAuthorizationToken(authorizationToken: string, region: string): SpeechTranslationConfig {\r\n Contracts.throwIfNullOrWhitespace(authorizationToken, \"authorizationToken\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const ret: SpeechTranslationConfigImpl = new SpeechTranslationConfigImpl();\r\n ret.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, authorizationToken);\r\n ret.properties.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n return ret;\r\n }\r\n\r\n /**\r\n * Creates an instance of the speech config with specified host and subscription key.\r\n * This method is intended only for users who use a non-default service host. Standard resource path will be assumed.\r\n * For services with a non-standard resource path or no path at all, use fromEndpoint instead.\r\n * Note: Query parameters are not allowed in the host URI and must be set by other APIs.\r\n * Note: To use an authorization token with fromHost, use fromHost(URL),\r\n * and then set the AuthorizationToken property on the created SpeechConfig instance.\r\n * Note: Added in version 1.9.0.\r\n * @member SpeechConfig.fromHost\r\n * @function\r\n * @public\r\n * @param {URL} host - The service endpoint to connect to. Format is \"protocol://host:port\" where \":port\" is optional.\r\n * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set.\r\n * @returns {SpeechConfig} A speech factory instance.\r\n */\r\n public static fromHost(hostName: URL, subscriptionKey?: string): SpeechConfig {\r\n Contracts.throwIfNull(hostName, \"hostName\");\r\n\r\n const speechImpl: SpeechTranslationConfigImpl = new SpeechTranslationConfigImpl();\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Host, hostName.protocol + \"//\" + hostName.hostname + (hostName.port === \"\" ? \"\" : \":\" + hostName.port));\r\n\r\n if (undefined !== subscriptionKey) {\r\n speechImpl.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n }\r\n return speechImpl;\r\n }\r\n\r\n /**\r\n * Creates an instance of the speech translation config with specified endpoint and subscription key.\r\n * This method is intended only for users who use a non-standard service endpoint or paramters.\r\n * Note: The query properties specified in the endpoint URL are not changed, even if they are\r\n * set by any other APIs. For example, if language is defined in the uri as query parameter\r\n * \"language=de-DE\", and also set by the speechRecognitionLanguage property, the language\r\n * setting in uri takes precedence, and the effective language is \"de-DE\".\r\n * Only the properties that are not specified in the endpoint URL can be set by other APIs.\r\n * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the\r\n * fromEndpoint method, and then set authorizationToken=\"token\" on the created SpeechConfig instance to\r\n * use the authorization token.\r\n * @member SpeechTranslationConfig.fromEndpoint\r\n * @function\r\n * @public\r\n * @param {URL} endpoint - The service endpoint to connect to.\r\n * @param {string} subscriptionKey - The subscription key.\r\n * @returns {SpeechTranslationConfig} A speech config instance.\r\n */\r\n public static fromEndpoint(endpoint: URL, subscriptionKey: string): SpeechTranslationConfig {\r\n Contracts.throwIfNull(endpoint, \"endpoint\");\r\n Contracts.throwIfNull(subscriptionKey, \"subscriptionKey\");\r\n\r\n const ret: SpeechTranslationConfigImpl = new SpeechTranslationConfigImpl();\r\n ret.properties.setProperty(PropertyId.SpeechServiceConnection_Endpoint, endpoint.href);\r\n ret.properties.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n return ret;\r\n }\r\n\r\n /**\r\n * Gets/Sets the authorization token.\r\n * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token\r\n * expires, the caller needs to refresh it by calling this setter with a new valid token.\r\n * @member SpeechTranslationConfig.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} value - The authorization token.\r\n */\r\n public abstract set authorizationToken(value: string);\r\n\r\n /**\r\n * Gets/Sets the speech recognition language.\r\n * @member SpeechTranslationConfig.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The authorization token.\r\n */\r\n public abstract set speechRecognitionLanguage(value: string);\r\n\r\n /**\r\n * Add a (text) target language to translate into.\r\n * @member SpeechTranslationConfig.prototype.addTargetLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The language such as de-DE\r\n */\r\n public abstract addTargetLanguage(value: string): void;\r\n\r\n /**\r\n * Gets the (text) target language to translate into.\r\n * @member SpeechTranslationConfig.prototype.targetLanguages\r\n * @function\r\n * @public\r\n * @param {string} value - The language such as de-DE\r\n */\r\n public abstract get targetLanguages(): string[];\r\n\r\n /**\r\n * Gets the selected voice name.\r\n * @member SpeechTranslationConfig.prototype.voiceName\r\n * @function\r\n * @public\r\n * @returns {string} The voice name.\r\n */\r\n public abstract get voiceName(): string;\r\n\r\n /**\r\n * Gets/Sets voice of the translated language, enable voice synthesis output.\r\n * @member SpeechTranslationConfig.prototype.voiceName\r\n * @function\r\n * @public\r\n * @param {string} value - The name of the voice.\r\n */\r\n public abstract set voiceName(value: string);\r\n\r\n /**\r\n * Sets a named property as value\r\n * @member SpeechTranslationConfig.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property.\r\n * @param {string} value - The value.\r\n */\r\n public abstract setProperty(name: string, value: string): void;\r\n\r\n /**\r\n * Dispose of associated resources.\r\n * @member SpeechTranslationConfig.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * @private\r\n * @class SpeechTranslationConfigImpl\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class SpeechTranslationConfigImpl extends SpeechTranslationConfig {\r\n\r\n private privSpeechProperties: PropertyCollection;\r\n\r\n public constructor() {\r\n super();\r\n this.privSpeechProperties = new PropertyCollection();\r\n this.outputFormat = OutputFormat.Simple;\r\n }\r\n /**\r\n * Gets/Sets the authorization token.\r\n * If this is set, subscription key is ignored.\r\n * User needs to make sure the provided authorization token is valid and not expired.\r\n * @member SpeechTranslationConfigImpl.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} value - The authorization token.\r\n */\r\n public set authorizationToken(value: string) {\r\n Contracts.throwIfNullOrWhitespace(value, \"value\");\r\n\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceAuthorization_Token, value);\r\n }\r\n\r\n /**\r\n * Sets the speech recognition language.\r\n * @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The authorization token.\r\n */\r\n public set speechRecognitionLanguage(value: string) {\r\n Contracts.throwIfNullOrWhitespace(value, \"value\");\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_RecoLanguage, value);\r\n }\r\n\r\n /**\r\n * Gets the speech recognition language.\r\n * @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @return {string} The speechRecognitionLanguage.\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n return this.privSpeechProperties.getProperty(PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);\r\n }\r\n\r\n /**\r\n * @member SpeechTranslationConfigImpl.prototype.subscriptionKey\r\n * @function\r\n * @public\r\n */\r\n public get subscriptionKey(): string {\r\n return this.privSpeechProperties.getProperty(PropertyId[PropertyId.SpeechServiceConnection_Key]);\r\n }\r\n\r\n /**\r\n * Gets the output format\r\n * @member SpeechTranslationConfigImpl.prototype.outputFormat\r\n * @function\r\n * @public\r\n */\r\n public get outputFormat(): OutputFormat {\r\n return (OutputFormat as any)[this.privSpeechProperties.getProperty(OutputFormatPropertyName, undefined)];\r\n }\r\n\r\n /**\r\n * Gets/Sets the output format\r\n * @member SpeechTranslationConfigImpl.prototype.outputFormat\r\n * @function\r\n * @public\r\n */\r\n public set outputFormat(value: OutputFormat) {\r\n this.privSpeechProperties.setProperty(OutputFormatPropertyName, OutputFormat[value]);\r\n }\r\n\r\n /**\r\n * Gets the endpoint id.\r\n * @member SpeechTranslationConfigImpl.prototype.endpointId\r\n * @function\r\n * @public\r\n */\r\n public get endpointId(): string {\r\n return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_EndpointId);\r\n }\r\n\r\n /**\r\n * Gets/Sets the endpoint id.\r\n * @member SpeechTranslationConfigImpl.prototype.endpointId\r\n * @function\r\n * @public\r\n */\r\n public set endpointId(value: string) {\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_EndpointId, value);\r\n }\r\n\r\n /**\r\n * Add a (text) target language to translate into.\r\n * @member SpeechTranslationConfigImpl.prototype.addTargetLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The language such as de-DE\r\n */\r\n public addTargetLanguage(value: string): void {\r\n Contracts.throwIfNullOrWhitespace(value, \"value\");\r\n\r\n const languages: string[] = this.targetLanguages;\r\n languages.push(value);\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(\",\"));\r\n }\r\n\r\n /**\r\n * Gets the (text) target language to translate into.\r\n * @member SpeechTranslationConfigImpl.prototype.targetLanguages\r\n * @function\r\n * @public\r\n * @param {string} value - The language such as de-DE\r\n */\r\n public get targetLanguages(): string[] {\r\n\r\n if (this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) {\r\n return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages).split(\",\");\r\n } else {\r\n return [];\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Gets the voice name.\r\n * @member SpeechTranslationConfigImpl.prototype.voiceName\r\n * @function\r\n * @public\r\n */\r\n public get voiceName(): string {\r\n return this.getProperty(PropertyId[PropertyId.SpeechServiceConnection_TranslationVoice]);\r\n }\r\n\r\n /**\r\n * Gets/Sets the voice of the translated language, enable voice synthesis output.\r\n * @member SpeechTranslationConfigImpl.prototype.voiceName\r\n * @function\r\n * @public\r\n * @param {string} value - The name of the voice.\r\n */\r\n public set voiceName(value: string) {\r\n Contracts.throwIfNullOrWhitespace(value, \"value\");\r\n\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_TranslationVoice, value);\r\n }\r\n\r\n /**\r\n * Provides the region.\r\n * @member SpeechTranslationConfigImpl.prototype.region\r\n * @function\r\n * @public\r\n * @returns {string} The region.\r\n */\r\n public get region(): string {\r\n return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_Region);\r\n }\r\n\r\n public setProxy(proxyHostName: string, proxyPort: number): void;\r\n public setProxy(proxyHostName: string, proxyPort: number, proxyUserName: string, proxyPassword: string): void;\r\n public setProxy(proxyHostName: any, proxyPort: any, proxyUserName?: any, proxyPassword?: any): void {\r\n this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName);\r\n this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyPort], proxyPort);\r\n this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName);\r\n this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword);\r\n }\r\n\r\n /**\r\n * Gets an arbitrary property value.\r\n * @member SpeechTranslationConfigImpl.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property.\r\n * @param {string} def - The default value of the property in case it is not set.\r\n * @returns {string} The value of the property.\r\n */\r\n public getProperty(name: string, def?: string): string {\r\n return this.privSpeechProperties.getProperty(name, def);\r\n }\r\n\r\n /**\r\n * Gets/Sets an arbitrary property value.\r\n * @member SpeechTranslationConfigImpl.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property.\r\n * @param {string} value - The value of the property.\r\n */\r\n public setProperty(name: string | PropertyId, value: string): void {\r\n this.privSpeechProperties.setProperty(name, value);\r\n }\r\n\r\n /**\r\n * Provides access to custom properties.\r\n * @member SpeechTranslationConfigImpl.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The properties.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privSpeechProperties;\r\n }\r\n\r\n /**\r\n * Dispose of associated resources.\r\n * @member SpeechTranslationConfigImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n return;\r\n }\r\n\r\n public setServiceProperty(name: string, value: string, channel: ServicePropertyChannel): void {\r\n const currentProperties: IStringDictionary = JSON.parse(this.privSpeechProperties.getProperty(ServicePropertiesPropertyName, \"{}\"));\r\n\r\n currentProperties[name] = value;\r\n\r\n this.privSpeechProperties.setProperty(ServicePropertiesPropertyName, JSON.stringify(currentProperties));\r\n }\r\n\r\n public setProfanity(profanity: ProfanityOption): void {\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceResponse_ProfanityOption, ProfanityOption[profanity]);\r\n }\r\n\r\n public enableAudioLogging(): void {\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_EnableAudioLogging, \"true\");\r\n }\r\n public requestWordLevelTimestamps(): void {\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, \"true\");\r\n }\r\n public enableDictation(): void {\r\n this.privSpeechProperties.setProperty(ForceDictationPropertyName, \"true\");\r\n }\r\n\r\n public get speechSynthesisLanguage(): string {\r\n return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_SynthLanguage);\r\n }\r\n\r\n public set speechSynthesisLanguage(language: string) {\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_SynthLanguage, language);\r\n }\r\n\r\n public get speechSynthesisVoiceName(): string {\r\n return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_SynthVoice);\r\n }\r\n\r\n public set speechSynthesisVoiceName(voice: string) {\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_SynthVoice, voice);\r\n }\r\n\r\n public get speechSynthesisOutputFormat(): SpeechSynthesisOutputFormat {\r\n return (SpeechSynthesisOutputFormat as any)[this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)];\r\n }\r\n\r\n public set speechSynthesisOutputFormat(format: SpeechSynthesisOutputFormat) {\r\n this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, SpeechSynthesisOutputFormat[format]);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { AudioStreamFormatImpl } from \"../../src/sdk/Audio/AudioStreamFormat\";\r\nimport {\r\n IAudioStreamNode,\r\n IStreamChunk,\r\n} from \"../common/Exports\";\r\n\r\nexport class ReplayableAudioNode implements IAudioStreamNode {\r\n private privAudioNode: IAudioStreamNode;\r\n private privBytesPerSecond: number;\r\n private privBuffers: BufferEntry[] = [];\r\n private privReplayOffset: number = 0;\r\n private privLastShrinkOffset: number = 0;\r\n private privBufferStartOffset: number = 0;\r\n private privBufferSerial: number = 0;\r\n private privBufferedBytes: number = 0;\r\n private privReplay: boolean = false;\r\n private privLastChunkAcquiredTime: number = 0;\r\n\r\n public constructor(audioSource: IAudioStreamNode, bytesPerSecond: number) {\r\n this.privAudioNode = audioSource;\r\n this.privBytesPerSecond = bytesPerSecond;\r\n }\r\n\r\n public id = (): string => {\r\n return this.privAudioNode.id();\r\n }\r\n\r\n // Reads and returns the next chunk of audio buffer.\r\n // If replay of existing buffers are needed, read() will first seek and replay\r\n // existing content, and upoin completion it will read new content from the underlying\r\n // audio node, saving that content into the replayable buffers.\r\n public read(): Promise> {\r\n // if there is a replay request to honor.\r\n if (!!this.privReplay && this.privBuffers.length !== 0) {\r\n // Find the start point in the buffers.\r\n // Offsets are in 100ns increments.\r\n // So how many bytes do we need to seek to get the right offset?\r\n const offsetToSeek: number = this.privReplayOffset - this.privBufferStartOffset;\r\n\r\n let bytesToSeek: number = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7);\r\n if (0 !== (bytesToSeek % 2)) {\r\n bytesToSeek++;\r\n }\r\n\r\n let i: number = 0;\r\n\r\n while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) {\r\n bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength;\r\n }\r\n\r\n if (i < this.privBuffers.length) {\r\n const retVal: ArrayBuffer = this.privBuffers[i].chunk.buffer.slice(bytesToSeek);\r\n\r\n this.privReplayOffset += (retVal.byteLength / this.privBytesPerSecond) * 1e+7;\r\n\r\n // If we've reached the end of the buffers, stop replaying.\r\n if (i === this.privBuffers.length - 1) {\r\n this.privReplay = false;\r\n }\r\n\r\n return Promise.resolve>({\r\n buffer: retVal,\r\n isEnd: false,\r\n timeReceived: this.privBuffers[i].chunk.timeReceived,\r\n });\r\n }\r\n }\r\n\r\n return this.privAudioNode.read()\r\n .then((result: IStreamChunk) => {\r\n if (result && result.buffer) {\r\n this.privBuffers.push(new BufferEntry(result, this.privBufferSerial++, this.privBufferedBytes));\r\n this.privBufferedBytes += result.buffer.byteLength;\r\n }\r\n return result;\r\n });\r\n }\r\n\r\n public detach(): Promise {\r\n this.privBuffers = undefined;\r\n return this.privAudioNode.detach();\r\n }\r\n\r\n public replay(): void {\r\n if (this.privBuffers && 0 !== this.privBuffers.length) {\r\n this.privReplay = true;\r\n this.privReplayOffset = this.privLastShrinkOffset;\r\n }\r\n }\r\n\r\n // Shrinks the existing audio buffers to start at the new offset, or at the\r\n // beginning of the buffer closest to the requested offset.\r\n // A replay request will start from the last shrink point.\r\n public shrinkBuffers(offset: number): void {\r\n if (this.privBuffers === undefined || this.privBuffers.length === 0) {\r\n return;\r\n }\r\n\r\n this.privLastShrinkOffset = offset;\r\n\r\n // Find the start point in the buffers.\r\n // Offsets are in 100ns increments.\r\n // So how many bytes do we need to seek to get the right offset?\r\n const offsetToSeek: number = offset - this.privBufferStartOffset;\r\n\r\n let bytesToSeek: number = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7);\r\n\r\n let i: number = 0;\r\n\r\n while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) {\r\n bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength;\r\n }\r\n this.privBufferStartOffset = Math.round(offset - ((bytesToSeek / this.privBytesPerSecond) * 1e+7));\r\n this.privBuffers = this.privBuffers.slice(i);\r\n }\r\n\r\n // Finds the time a buffer of audio was first seen by offset.\r\n public findTimeAtOffset(offset: number): number {\r\n if (offset < this.privBufferStartOffset || this.privBuffers === undefined) {\r\n return 0;\r\n }\r\n\r\n for (const value of this.privBuffers) {\r\n const startOffset: number = (value.byteOffset / this.privBytesPerSecond) * 1e7;\r\n const endOffset: number = startOffset + ((value.chunk.buffer.byteLength / this.privBytesPerSecond) * 1e7);\r\n\r\n if (offset >= startOffset && offset <= endOffset) {\r\n return value.chunk.timeReceived;\r\n }\r\n }\r\n\r\n return 0;\r\n }\r\n}\r\n\r\n// Primary use of this class is to help debugging problems with the replay\r\n// code. If the memory cost of alloc / dealloc gets too much, drop it and just use\r\n// the ArrayBuffer directly.\r\n// tslint:disable-next-line:max-classes-per-file\r\nclass BufferEntry {\r\n public chunk: IStreamChunk;\r\n public serial: number;\r\n public byteOffset: number;\r\n\r\n public constructor(chunk: IStreamChunk, serial: number, byteOffset: number) {\r\n this.chunk = chunk;\r\n this.serial = serial;\r\n this.byteOffset = byteOffset;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\ntype TWorkerMessage = ICallNotification | IClearResponse | IErrorNotification | IErrorResponse;\r\n\r\ninterface IClearResponse {\r\n error: null;\r\n id: number;\r\n}\r\n\r\ninterface IErrorNotification {\r\n error: {\r\n message: string;\r\n };\r\n id: null;\r\n result: null;\r\n}\r\n\r\ninterface IErrorResponse {\r\n error: {\r\n message: string;\r\n };\r\n id: number;\r\n result: null;\r\n}\r\n\r\ninterface ICallNotification {\r\n id: null;\r\n method: \"call\";\r\n params: {\r\n timerId: number;\r\n };\r\n}\r\n\r\ninterface ISetNotification {\r\n id: null;\r\n method: \"set\";\r\n params: {\r\n delay: number;\r\n now: number;\r\n timerId: number;\r\n };\r\n}\r\n\r\ninterface IClearRequest {\r\n id: number;\r\n method: \"clear\";\r\n params: {\r\n timerId: number;\r\n };\r\n}\r\n\r\ninterface IWorkerEvent extends Event {\r\n data: TWorkerMessage;\r\n}\r\n\r\ninterface IWorkerTimers {\r\n clearTimeout: (timerId: number) => void;\r\n setTimeout: (func: () => any, delay: number) => number;\r\n}\r\n\r\ndeclare type Func = () => any;\r\n\r\nexport class Timeout {\r\n\r\n private static workerTimers: null | IWorkerTimers = null;\r\n\r\n public static clearTimeout: IWorkerTimers[\"clearTimeout\"] = (timerId) => Timeout.timers().clearTimeout(timerId);\r\n\r\n public static setTimeout: IWorkerTimers[\"setTimeout\"] = (func, delay) => Timeout.timers().setTimeout(func, delay);\r\n\r\n public static load = (url: string) => {\r\n // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.\r\n const scheduledTimeoutFunctions: Map = new Map([[0, () => { }]]); // tslint:disable-line no-empty\r\n const unhandledRequests: Map = new Map();\r\n\r\n const worker = new Worker(url);\r\n\r\n worker.addEventListener(\"message\", ({ data }: IWorkerEvent) => {\r\n if (Timeout.isCallNotification(data)) {\r\n const {\r\n params: { timerId }\r\n } = data;\r\n\r\n const idOrFunc = scheduledTimeoutFunctions.get(timerId);\r\n\r\n if (typeof idOrFunc === \"number\") {\r\n const unhandledTimerId = unhandledRequests.get(idOrFunc);\r\n\r\n if (\r\n unhandledTimerId === undefined ||\r\n unhandledTimerId !== timerId\r\n ) {\r\n throw new Error(\"The timer is in an undefined state.\");\r\n }\r\n } else if (typeof idOrFunc !== \"undefined\") {\r\n idOrFunc();\r\n\r\n // A timeout can be safely deleted because it is only called once.\r\n scheduledTimeoutFunctions.delete(timerId);\r\n } else {\r\n throw new Error(\"The timer is in an undefined state.\");\r\n }\r\n } else if (Timeout.isClearResponse(data)) {\r\n const { id } = data;\r\n\r\n const unhandledTimerId = unhandledRequests.get(id);\r\n\r\n if (unhandledTimerId === undefined) {\r\n throw new Error(\"The timer is in an undefined state.\");\r\n }\r\n\r\n unhandledRequests.delete(id);\r\n\r\n scheduledTimeoutFunctions.delete(unhandledTimerId);\r\n } else {\r\n const {\r\n error: { message }\r\n } = data;\r\n\r\n throw new Error(message);\r\n }\r\n });\r\n\r\n const clearTimeout = (timerId: number) => {\r\n const id = Math.random();\r\n\r\n unhandledRequests.set(id, timerId);\r\n scheduledTimeoutFunctions.set(timerId, id);\r\n\r\n worker.postMessage({\r\n id,\r\n method: \"clear\",\r\n params: { timerId }\r\n } as IClearRequest);\r\n };\r\n\r\n const setTimeout = (func: () => void, delay: number) => {\r\n const timerId = Math.random();\r\n\r\n scheduledTimeoutFunctions.set(timerId, func);\r\n\r\n worker.postMessage({\r\n id: null,\r\n method: \"set\",\r\n params: {\r\n delay,\r\n now: performance.now(),\r\n timerId\r\n }\r\n } as ISetNotification);\r\n\r\n return timerId;\r\n };\r\n\r\n return {\r\n clearTimeout,\r\n setTimeout\r\n };\r\n }\r\n\r\n private static loadWorkerTimers = () => {\r\n const 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\r\n return () => {\r\n if (Timeout.workerTimers !== null) {\r\n return Timeout.workerTimers;\r\n }\r\n\r\n const blob = new Blob([worker], { type: \"application/javascript; charset=utf-8\" });\r\n const url = URL.createObjectURL(blob);\r\n\r\n Timeout.workerTimers = Timeout.load(url);\r\n\r\n // Edge doesn't like the URL to be revoked directly.\r\n Timeout.workerTimers.setTimeout(() => URL.revokeObjectURL(url), 0);\r\n\r\n return Timeout.workerTimers as IWorkerTimers;\r\n };\r\n }\r\n\r\n public static timers: () => IWorkerTimers = Timeout.loadWorkerTimers();\r\n\r\n private static isCallNotification = (message: TWorkerMessage): message is ICallNotification => {\r\n return (message as ICallNotification).method !== undefined && (message as ICallNotification).method === \"call\";\r\n }\r\n\r\n private static isClearResponse = (message: TWorkerMessage): message is IClearResponse => {\r\n return (message as IClearResponse).error === null && typeof message.id === \"number\";\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n AudioSourceErrorEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n AudioStreamNodeErrorEvent,\r\n ConnectionEstablishedEvent,\r\n ConnectionEstablishErrorEvent,\r\n ConnectionMessageReceivedEvent,\r\n ConnectionStartEvent,\r\n IEventListener,\r\n IStringDictionary,\r\n PlatformEvent,\r\n} from \"../common/Exports\";\r\nimport { ConnectingToServiceEvent, RecognitionTriggeredEvent } from \"./RecognitionEvents\";\r\n\r\nexport interface ITelemetry {\r\n Metrics: IMetric[];\r\n ReceivedMessages: IStringDictionary;\r\n}\r\n\r\nexport interface IMetric {\r\n End?: string;\r\n Error?: string;\r\n Id?: string;\r\n Name?: string;\r\n Start?: string;\r\n PhraseLatencyMs?: number[];\r\n FirstHypothesisLatencyMs?: number[];\r\n}\r\n\r\nexport class ServiceTelemetryListener implements IEventListener {\r\n private privIsDisposed: boolean = false;\r\n\r\n private privRequestId: string;\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n\r\n private privListeningTriggerMetric: IMetric = null;\r\n private privMicMetric: IMetric = null;\r\n private privConnectionEstablishMetric: IMetric = null;\r\n\r\n private privMicStartTime: string;\r\n\r\n private privConnectionId: string;\r\n private privConnectionStartTime: string;\r\n\r\n private privReceivedMessages: IStringDictionary;\r\n private privPhraseLatencies: number[];\r\n private privHypothesisLatencies: number[];\r\n\r\n constructor(requestId: string, audioSourceId: string, audioNodeId: string) {\r\n this.privRequestId = requestId;\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n\r\n this.privReceivedMessages = {};\r\n this.privPhraseLatencies = [];\r\n this.privHypothesisLatencies = [];\r\n }\r\n\r\n public phraseReceived(audioReceivedTime: number): void {\r\n if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.\r\n this.privPhraseLatencies.push(Date.now() - audioReceivedTime);\r\n }\r\n }\r\n\r\n public hypothesisReceived(audioReceivedTime: number): void {\r\n if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.\r\n this.privHypothesisLatencies.push(Date.now() - audioReceivedTime);\r\n }\r\n }\r\n\r\n public onEvent = (e: PlatformEvent): void => {\r\n if (this.privIsDisposed) {\r\n return;\r\n }\r\n\r\n if (e instanceof RecognitionTriggeredEvent && e.requestId === this.privRequestId) {\r\n this.privListeningTriggerMetric = {\r\n End: e.eventTime,\r\n Name: \"ListeningTrigger\",\r\n Start: e.eventTime,\r\n };\r\n }\r\n\r\n if (e instanceof AudioStreamNodeAttachingEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n this.privMicStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof AudioStreamNodeAttachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n this.privMicStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof AudioSourceErrorEvent && e.audioSourceId === this.privAudioSourceId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Error: e.error,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof AudioStreamNodeErrorEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Error: e.error,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof AudioStreamNodeDetachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectingToServiceEvent && e.requestId === this.privRequestId) {\r\n this.privConnectionId = e.sessionId;\r\n }\r\n\r\n if (e instanceof ConnectionStartEvent && e.connectionId === this.privConnectionId) {\r\n this.privConnectionStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof ConnectionEstablishedEvent && e.connectionId === this.privConnectionId) {\r\n if (!this.privConnectionEstablishMetric) {\r\n this.privConnectionEstablishMetric = {\r\n End: e.eventTime,\r\n Id: this.privConnectionId,\r\n Name: \"Connection\",\r\n Start: this.privConnectionStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectionEstablishErrorEvent && e.connectionId === this.privConnectionId) {\r\n if (!this.privConnectionEstablishMetric) {\r\n this.privConnectionEstablishMetric = {\r\n End: e.eventTime,\r\n Error: this.getConnectionError(e.statusCode),\r\n Id: this.privConnectionId,\r\n Name: \"Connection\",\r\n Start: this.privConnectionStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectionMessageReceivedEvent && e.connectionId === this.privConnectionId) {\r\n if (e.message && e.message.headers && e.message.headers.path) {\r\n if (!this.privReceivedMessages[e.message.headers.path]) {\r\n this.privReceivedMessages[e.message.headers.path] = new Array();\r\n }\r\n\r\n this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime);\r\n }\r\n }\r\n }\r\n\r\n public getTelemetry = (): string => {\r\n const metrics = new Array();\r\n\r\n if (this.privListeningTriggerMetric) {\r\n metrics.push(this.privListeningTriggerMetric);\r\n }\r\n\r\n if (this.privMicMetric) {\r\n metrics.push(this.privMicMetric);\r\n }\r\n\r\n if (this.privConnectionEstablishMetric) {\r\n metrics.push(this.privConnectionEstablishMetric);\r\n }\r\n\r\n if (this.privPhraseLatencies.length > 0) {\r\n metrics.push({\r\n PhraseLatencyMs: this.privPhraseLatencies,\r\n });\r\n }\r\n\r\n if (this.privHypothesisLatencies.length > 0) {\r\n metrics.push({\r\n FirstHypothesisLatencyMs: this.privHypothesisLatencies,\r\n });\r\n }\r\n\r\n const telemetry: ITelemetry = {\r\n Metrics: metrics,\r\n ReceivedMessages: this.privReceivedMessages,\r\n };\r\n\r\n const json = JSON.stringify(telemetry);\r\n\r\n // We dont want to send the same telemetry again. So clean those out.\r\n this.privReceivedMessages = {};\r\n this.privListeningTriggerMetric = null;\r\n this.privMicMetric = null;\r\n this.privConnectionEstablishMetric = null;\r\n this.privPhraseLatencies = [];\r\n this.privHypothesisLatencies = [];\r\n return json;\r\n }\r\n\r\n // Determines if there are any telemetry events to send to the service.\r\n public get hasTelemetry(): boolean {\r\n return (Object.keys(this.privReceivedMessages).length !== 0 ||\r\n this.privListeningTriggerMetric !== null ||\r\n this.privMicMetric !== null ||\r\n this.privConnectionEstablishMetric !== null ||\r\n this.privPhraseLatencies.length !== 0 ||\r\n this.privHypothesisLatencies.length !== 0);\r\n }\r\n\r\n public dispose = (): void => {\r\n this.privIsDisposed = true;\r\n }\r\n\r\n private getConnectionError = (statusCode: number): string => {\r\n /*\r\n -- Websocket status codes --\r\n NormalClosure = 1000,\r\n EndpointUnavailable = 1001,\r\n ProtocolError = 1002,\r\n InvalidMessageType = 1003,\r\n Empty = 1005,\r\n InvalidPayloadData = 1007,\r\n PolicyViolation = 1008,\r\n MessageTooBig = 1009,\r\n MandatoryExtension = 1010,\r\n InternalServerError = 1011\r\n */\r\n\r\n switch (statusCode) {\r\n case 400:\r\n case 1002:\r\n case 1003:\r\n case 1005:\r\n case 1007:\r\n case 1008:\r\n case 1009: return \"BadRequest\";\r\n case 401: return \"Unauthorized\";\r\n case 403: return \"Forbidden\";\r\n case 503:\r\n case 1001: return \"ServerUnavailable\";\r\n case 500:\r\n case 1011: return \"ServerError\";\r\n case 408:\r\n case 504: return \"Timeout\";\r\n default: return \"statuscode:\" + statusCode.toString();\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Z_NO_COMPRESSION } from \"zlib\";\r\nimport { ReplayableAudioNode } from \"../common.browser/Exports\";\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n Events,\r\n IDetachable,\r\n IEventSource,\r\n PlatformEvent\r\n} from \"../common/Exports\";\r\nimport {\r\n ConnectingToServiceEvent,\r\n ListeningStartedEvent,\r\n RecognitionStartedEvent,\r\n RecognitionTriggeredEvent,\r\n SpeechRecognitionEvent,\r\n} from \"./RecognitionEvents\";\r\nimport { ServiceTelemetryListener } from \"./ServiceTelemetryListener.Internal\";\r\n\r\nexport class RequestSession {\r\n private privIsDisposed: boolean = false;\r\n private privServiceTelemetryListener: ServiceTelemetryListener;\r\n private privDetachables: IDetachable[] = new Array();\r\n private privRequestId: string;\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n private privAudioNode: ReplayableAudioNode;\r\n private privAuthFetchEventId: string;\r\n private privIsAudioNodeDetached: boolean = false;\r\n private privIsRecognizing: boolean = false;\r\n private privIsSpeechEnded: boolean = false;\r\n private privTurnStartAudioOffset: number = 0;\r\n private privLastRecoOffset: number = 0;\r\n private privHypothesisReceived: boolean = false;\r\n private privBytesSent: number = 0;\r\n private privRecogNumber: number = 0;\r\n private privSessionId: string;\r\n private privTurnDeferral: Deferred;\r\n private privInTurn: boolean = false;\r\n private privConnectionAttempts: number = 0;\r\n\r\n constructor(audioSourceId: string) {\r\n this.privAudioSourceId = audioSourceId;\r\n this.privRequestId = createNoDashGuid();\r\n this.privAudioNodeId = createNoDashGuid();\r\n this.privTurnDeferral = new Deferred();\r\n\r\n // We're not in a turn, so resolve.\r\n this.privTurnDeferral.resolve();\r\n }\r\n\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n\r\n public get turnCompletionPromise(): Promise {\r\n return this.privTurnDeferral.promise;\r\n }\r\n\r\n public get isSpeechEnded(): boolean {\r\n return this.privIsSpeechEnded;\r\n }\r\n\r\n public get isRecognizing(): boolean {\r\n return this.privIsRecognizing;\r\n }\r\n\r\n public get currentTurnAudioOffset(): number {\r\n return this.privTurnStartAudioOffset;\r\n }\r\n\r\n public get recogNumber(): number {\r\n return this.privRecogNumber;\r\n }\r\n\r\n public get numConnectionAttempts(): number {\r\n return this.privConnectionAttempts;\r\n }\r\n\r\n // The number of bytes sent for the current connection.\r\n // Counter is reset to 0 each time a connection is established.\r\n public get bytesSent(): number {\r\n return this.privBytesSent;\r\n }\r\n public listenForServiceTelemetry(eventSource: IEventSource): void {\r\n if (!!this.privServiceTelemetryListener) {\r\n this.privDetachables.push(eventSource.attachListener(this.privServiceTelemetryListener));\r\n }\r\n }\r\n\r\n public startNewRecognition(): void {\r\n this.privIsSpeechEnded = false;\r\n this.privIsRecognizing = true;\r\n this.privTurnStartAudioOffset = 0;\r\n this.privLastRecoOffset = 0;\r\n this.privRequestId = createNoDashGuid();\r\n this.privRecogNumber++;\r\n this.privServiceTelemetryListener = new ServiceTelemetryListener(this.privRequestId, this.privAudioSourceId, this.privAudioNodeId);\r\n this.onEvent(new RecognitionTriggeredEvent(this.requestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId));\r\n }\r\n\r\n public async onAudioSourceAttachCompleted(audioNode: ReplayableAudioNode, isError: boolean, error?: string): Promise {\r\n this.privAudioNode = audioNode;\r\n this.privIsAudioNodeDetached = false;\r\n\r\n if (isError) {\r\n await this.onComplete();\r\n } else {\r\n this.onEvent(new ListeningStartedEvent(this.privRequestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId));\r\n }\r\n }\r\n\r\n public onPreConnectionStart = (authFetchEventId: string, connectionId: string): void => {\r\n this.privAuthFetchEventId = authFetchEventId;\r\n this.privSessionId = connectionId;\r\n this.onEvent(new ConnectingToServiceEvent(this.privRequestId, this.privAuthFetchEventId, this.privSessionId));\r\n }\r\n\r\n public async onAuthCompleted(isError: boolean, error?: string): Promise {\r\n if (isError) {\r\n await this.onComplete();\r\n }\r\n }\r\n\r\n public async onConnectionEstablishCompleted(statusCode: number, reason?: string): Promise {\r\n if (statusCode === 200) {\r\n this.onEvent(new RecognitionStartedEvent(this.requestId, this.privAudioSourceId, this.privAudioNodeId, this.privAuthFetchEventId, this.privSessionId));\r\n if (!!this.privAudioNode) {\r\n this.privAudioNode.replay();\r\n }\r\n this.privTurnStartAudioOffset = this.privLastRecoOffset;\r\n this.privBytesSent = 0;\r\n return;\r\n } else if (statusCode === 403) {\r\n await this.onComplete();\r\n }\r\n }\r\n\r\n public async onServiceTurnEndResponse(continuousRecognition: boolean): Promise {\r\n this.privTurnDeferral.resolve();\r\n\r\n if (!continuousRecognition || this.isSpeechEnded) {\r\n await this.onComplete();\r\n this.privInTurn = false;\r\n } else {\r\n // Start a new request set.\r\n this.privTurnStartAudioOffset = this.privLastRecoOffset;\r\n this.privRequestId = createNoDashGuid();\r\n this.privAudioNode.replay();\r\n }\r\n }\r\n\r\n public onServiceTurnStartResponse = (): void => {\r\n if (!!this.privTurnDeferral && !!this.privInTurn) {\r\n // What? How are we starting a turn with another not done?\r\n this.privTurnDeferral.reject(\"Another turn started before current completed.\");\r\n // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited\r\n /* tslint:disable:no-empty */\r\n this.privTurnDeferral.promise.then().catch(() => { });\r\n }\r\n this.privInTurn = true;\r\n this.privTurnDeferral = new Deferred();\r\n }\r\n\r\n public onHypothesis(offset: number): void {\r\n if (!this.privHypothesisReceived) {\r\n this.privHypothesisReceived = true;\r\n this.privServiceTelemetryListener.hypothesisReceived(this.privAudioNode.findTimeAtOffset(offset));\r\n }\r\n }\r\n\r\n public onPhraseRecognized(offset: number): void {\r\n this.privServiceTelemetryListener.phraseReceived(this.privAudioNode.findTimeAtOffset(offset));\r\n this.onServiceRecognized(offset);\r\n }\r\n\r\n public onServiceRecognized(offset: number): void {\r\n this.privLastRecoOffset = offset;\r\n this.privHypothesisReceived = false;\r\n this.privAudioNode.shrinkBuffers(offset);\r\n this.privConnectionAttempts = 0;\r\n }\r\n\r\n public onAudioSent(bytesSent: number): void {\r\n this.privBytesSent += bytesSent;\r\n }\r\n\r\n public onRetryConnection(): void {\r\n this.privConnectionAttempts++;\r\n }\r\n\r\n public async dispose(error?: string): Promise {\r\n if (!this.privIsDisposed) {\r\n // we should have completed by now. If we did not its an unknown error.\r\n this.privIsDisposed = true;\r\n for (const detachable of this.privDetachables) {\r\n await detachable.detach();\r\n }\r\n\r\n this.privServiceTelemetryListener.dispose();\r\n this.privIsRecognizing = false;\r\n }\r\n }\r\n\r\n public getTelemetry = (): string => {\r\n if (this.privServiceTelemetryListener.hasTelemetry) {\r\n return this.privServiceTelemetryListener.getTelemetry();\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n public async onStopRecognizing(): Promise {\r\n await this.onComplete();\r\n }\r\n\r\n // Should be called with the audioNode for this session has indicated that it is out of speech.\r\n public onSpeechEnded(): void {\r\n this.privIsSpeechEnded = true;\r\n }\r\n\r\n protected onEvent = (event: SpeechRecognitionEvent): void => {\r\n if (!!this.privServiceTelemetryListener) {\r\n this.privServiceTelemetryListener.onEvent(event);\r\n }\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private async onComplete(): Promise {\r\n if (!!this.privIsRecognizing) {\r\n this.privIsRecognizing = false;\r\n await this.detachAudioNode();\r\n }\r\n }\r\n\r\n private async detachAudioNode(): Promise {\r\n if (!this.privIsAudioNodeDetached) {\r\n this.privIsAudioNodeDetached = true;\r\n if (this.privAudioNode) {\r\n await this.privAudioNode.detach();\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IDynamicGrammar,\r\n IDynamicGrammarGeneric,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Responsible for building the object to be sent to the speech service to support dynamic grammars.\r\n * @class DynamicGrammarBuilder\r\n */\r\nexport class DynamicGrammarBuilder {\r\n\r\n private privPhrases: string[];\r\n private privGrammars: string[];\r\n\r\n // Adds one more reference phrases to the dynamic grammar to send.\r\n // All added phrases are generic phrases.\r\n public addPhrase(phrase: string | string[]): void {\r\n if (!this.privPhrases) {\r\n this.privPhrases = [];\r\n }\r\n\r\n if (phrase instanceof Array) {\r\n this.privPhrases = this.privPhrases.concat(phrase as string[]);\r\n } else {\r\n this.privPhrases.push(phrase as string);\r\n }\r\n }\r\n\r\n // Clears all phrases stored in the current object.\r\n public clearPhrases(): void {\r\n this.privPhrases = undefined;\r\n }\r\n\r\n // Adds one or more reference grammars to the current grammar.\r\n public addReferenceGrammar(grammar: string | string[]): void {\r\n if (!this.privGrammars) {\r\n this.privGrammars = [];\r\n }\r\n\r\n if (grammar instanceof Array) {\r\n this.privGrammars = this.privGrammars.concat(grammar as string[]);\r\n } else {\r\n this.privGrammars.push(grammar as string);\r\n }\r\n }\r\n\r\n // clears all grammars stored on the recognizer.\r\n public clearGrammars(): void {\r\n this.privGrammars = undefined;\r\n }\r\n\r\n // Generates an object that represents the dynamic grammar used by the Speech Service.\r\n // This is done by building an object with the correct layout based on the phrases and reference grammars added to this instance\r\n // of a DynamicGrammarBuilder\r\n public generateGrammarObject(): IDynamicGrammar {\r\n if (this.privGrammars === undefined && this.privPhrases === undefined) {\r\n return undefined;\r\n }\r\n\r\n const retObj: IDynamicGrammar = {};\r\n retObj.ReferenceGrammars = this.privGrammars;\r\n\r\n if (undefined !== this.privPhrases && 0 !== this.privPhrases.length) {\r\n const retPhrases: IDynamicGrammarGeneric[] = [];\r\n\r\n this.privPhrases.forEach((value: string, index: number, array: string[]): void => {\r\n retPhrases.push({\r\n Text: value,\r\n });\r\n });\r\n\r\n retObj.Groups = [{ Type: \"Generic\", Items: retPhrases }];\r\n }\r\n\r\n return retObj;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n DynamicGrammarBuilder,\r\n IDynamicGrammar,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Represents the JSON used in the speech.context message sent to the speech service.\r\n * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object.\r\n */\r\nexport class SpeechContext {\r\n private privContext: { [section: string]: any } = {};\r\n private privDynamicGrammar: DynamicGrammarBuilder;\r\n\r\n constructor(dynamicGrammar: DynamicGrammarBuilder) {\r\n this.privDynamicGrammar = dynamicGrammar;\r\n }\r\n\r\n /**\r\n * Adds a section to the speech.context object.\r\n * @param sectionName Name of the section to add.\r\n * @param value JSON serializable object that represents the value.\r\n */\r\n public setSection(sectionName: string, value: any): void {\r\n this.privContext[sectionName] = value;\r\n }\r\n\r\n /**\r\n * @Internal\r\n * This is only used by pronunciation assessment config.\r\n * Do not use externally, object returned will change without warning or notice.\r\n */\r\n public setPronunciationAssessmentParams(params: string): void {\r\n if (this.privContext.phraseDetection === undefined) {\r\n this.privContext.phraseDetection = {\r\n enrichment: {\r\n pronunciationAssessment: {}\r\n }\r\n };\r\n }\r\n this.privContext.phraseDetection.enrichment.pronunciationAssessment = JSON.parse(params);\r\n if (this.privContext.phraseOutput === undefined) {\r\n this.privContext.phraseOutput = {\r\n detailed: {\r\n options: []\r\n },\r\n format: {}\r\n };\r\n }\r\n this.privContext.phraseOutput.format = \"Detailed\";\r\n this.privContext.phraseOutput.detailed.options.push(\"PronunciationAssessment\");\r\n if (this.privContext.phraseOutput.detailed.options.indexOf(\"WordTimings\") === -1) {\r\n this.privContext.phraseOutput.detailed.options.push(\"WordTimings\");\r\n }\r\n }\r\n\r\n public toJSON(): string {\r\n\r\n const dgi: IDynamicGrammar = this.privDynamicGrammar.generateGrammarObject();\r\n this.setSection(\"dgi\", dgi);\r\n\r\n const ret: string = JSON.stringify(this.privContext);\r\n return ret;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// speech.endDetected\r\nexport interface ISpeechDetected {\r\n Offset: number;\r\n}\r\n\r\nexport class SpeechDetected implements ISpeechDetected {\r\n private privSpeechStartDetected: ISpeechDetected;\r\n\r\n private constructor(json: string) {\r\n this.privSpeechStartDetected = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SpeechDetected {\r\n return new SpeechDetected(json);\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privSpeechStartDetected.Offset;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ReplayableAudioNode } from \"../common.browser/Exports\";\r\nimport { ConnectionOpenResponse } from \"../common/ConnectionOpenResponse\";\r\nimport {\r\n ArgumentNullError,\r\n ConnectionClosedEvent,\r\n ConnectionEvent,\r\n ConnectionState,\r\n createNoDashGuid,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IConnection,\r\n IDisposable,\r\n IStreamChunk,\r\n MessageType,\r\n ServiceEvent,\r\n Timeout\r\n} from \"../common/Exports\";\r\nimport { AudioStreamFormatImpl } from \"../sdk/Audio/AudioStreamFormat\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyId,\r\n RecognitionEventArgs,\r\n Recognizer,\r\n SessionEventArgs,\r\n SpeechRecognitionResult,\r\n} from \"../sdk/Exports\";\r\nimport { Callback } from \"../sdk/Transcription/IConversation\";\r\nimport {\r\n AgentConfig,\r\n DynamicGrammarBuilder,\r\n ISpeechConfigAudioDevice,\r\n RecognitionMode,\r\n RequestSession,\r\n SpeechContext,\r\n SpeechDetected,\r\n type\r\n} from \"./Exports\";\r\nimport {\r\n AuthInfo,\r\n IAuthentication,\r\n} from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\nexport abstract class ServiceRecognizerBase implements IDisposable {\r\n private privAuthentication: IAuthentication;\r\n private privConnectionFactory: IConnectionFactory;\r\n\r\n // A promise for a configured connection.\r\n // Do not consume directly, call fetchConnection instead.\r\n private privConnectionConfigurationPromise: Promise;\r\n\r\n // A promise for a connection, but one that has not had the speech context sent yet.\r\n // Do not consume directly, call fetchConnection instead.\r\n private privConnectionPromise: Promise;\r\n private privAuthFetchEventId: string;\r\n private privIsDisposed: boolean;\r\n private privMustReportEndOfStream: boolean;\r\n private privConnectionEvents: EventSource;\r\n private privServiceEvents: EventSource;\r\n private privDynamicGrammar: DynamicGrammarBuilder;\r\n private privAgentConfig: AgentConfig;\r\n private privServiceHasSentMessage: boolean;\r\n private privActivityTemplate: string;\r\n private privSetTimeout: (cb: () => void, delay: number) => number = setTimeout;\r\n private privAudioSource: IAudioSource;\r\n private privIsLiveAudio: boolean = false;\r\n protected privSpeechContext: SpeechContext;\r\n protected privRequestSession: RequestSession;\r\n protected privConnectionId: string;\r\n protected privRecognizerConfig: RecognizerConfig;\r\n protected privRecognizer: Recognizer;\r\n protected privSuccessCallback: (e: SpeechRecognitionResult) => void;\r\n protected privErrorCallback: (e: string) => void;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n recognizer: Recognizer) {\r\n\r\n if (!authentication) {\r\n throw new ArgumentNullError(\"authentication\");\r\n }\r\n\r\n if (!connectionFactory) {\r\n throw new ArgumentNullError(\"connectionFactory\");\r\n }\r\n\r\n if (!audioSource) {\r\n throw new ArgumentNullError(\"audioSource\");\r\n }\r\n\r\n if (!recognizerConfig) {\r\n throw new ArgumentNullError(\"recognizerConfig\");\r\n }\r\n\r\n this.privMustReportEndOfStream = false;\r\n this.privAuthentication = authentication;\r\n this.privConnectionFactory = connectionFactory;\r\n this.privAudioSource = audioSource;\r\n this.privRecognizerConfig = recognizerConfig;\r\n this.privIsDisposed = false;\r\n this.privRecognizer = recognizer;\r\n this.privRequestSession = new RequestSession(this.privAudioSource.id());\r\n this.privConnectionEvents = new EventSource();\r\n this.privServiceEvents = new EventSource();\r\n this.privDynamicGrammar = new DynamicGrammarBuilder();\r\n this.privSpeechContext = new SpeechContext(this.privDynamicGrammar);\r\n this.privAgentConfig = new AgentConfig();\r\n if (typeof (Blob) !== \"undefined\" && typeof (Worker) !== \"undefined\") {\r\n this.privSetTimeout = Timeout.setTimeout;\r\n }\r\n\r\n this.connectionEvents.attach(async (connectionEvent: ConnectionEvent): Promise => {\r\n if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n const connectionClosedEvent = connectionEvent as ConnectionClosedEvent;\r\n if (connectionClosedEvent.statusCode === 1003 ||\r\n connectionClosedEvent.statusCode === 1007 ||\r\n connectionClosedEvent.statusCode === 1002 ||\r\n connectionClosedEvent.statusCode === 4000 ||\r\n this.privRequestSession.numConnectionAttempts > this.privRecognizerConfig.maxRetryCount\r\n ) {\r\n await this.cancelRecognitionLocal(CancellationReason.Error,\r\n connectionClosedEvent.statusCode === 1007 ? CancellationErrorCode.BadRequestParameters : CancellationErrorCode.ConnectionFailure,\r\n connectionClosedEvent.reason + \" websocket error code: \" + connectionClosedEvent.statusCode);\r\n }\r\n }\r\n });\r\n }\r\n\r\n public get audioSource(): IAudioSource {\r\n return this.privAudioSource;\r\n }\r\n\r\n public get speechContext(): SpeechContext {\r\n return this.privSpeechContext;\r\n }\r\n\r\n public get dynamicGrammar(): DynamicGrammarBuilder {\r\n return this.privDynamicGrammar;\r\n }\r\n\r\n public get agentConfig(): AgentConfig {\r\n return this.privAgentConfig;\r\n }\r\n\r\n public set conversationTranslatorToken(token: string) {\r\n this.privRecognizerConfig.parameters.setProperty(PropertyId.ConversationTranslator_Token, token);\r\n }\r\n\r\n public set authentication(auth: IAuthentication) {\r\n this.privAuthentication = this.authentication;\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public async dispose(reason?: string): Promise {\r\n this.privIsDisposed = true;\r\n if (this.privConnectionConfigurationPromise) {\r\n try {\r\n const connection: IConnection = await this.privConnectionConfigurationPromise;\r\n await connection.dispose(reason);\r\n } catch (error) {\r\n // The connection is in a bad state. But we're trying to kill it, so...\r\n return;\r\n }\r\n }\r\n }\r\n\r\n public get connectionEvents(): EventSource {\r\n return this.privConnectionEvents;\r\n }\r\n\r\n public get serviceEvents(): EventSource {\r\n return this.privServiceEvents;\r\n }\r\n\r\n public get recognitionMode(): RecognitionMode {\r\n return this.privRecognizerConfig.recognitionMode;\r\n }\r\n\r\n protected recognizeOverride: (recoMode: RecognitionMode, sc: (e: SpeechRecognitionResult) => void, ec: (e: string) => void) => any = undefined;\r\n\r\n public async recognize(\r\n recoMode: RecognitionMode,\r\n successCallback: (e: SpeechRecognitionResult) => void,\r\n errorCallBack: (e: string) => void,\r\n ): Promise {\r\n\r\n if (this.recognizeOverride !== undefined) {\r\n return this.recognizeOverride(recoMode, successCallback, errorCallBack);\r\n }\r\n // Clear the existing configuration promise to force a re-transmission of config and context.\r\n this.privConnectionConfigurationPromise = null;\r\n this.privRecognizerConfig.recognitionMode = recoMode;\r\n\r\n this.privSuccessCallback = successCallback;\r\n this.privErrorCallback = errorCallBack;\r\n\r\n this.privRequestSession.startNewRecognition();\r\n this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events);\r\n\r\n // Start the connection to the service. The promise this will create is stored and will be used by configureConnection().\r\n const conPromise: Promise = this.connectImpl();\r\n let audioNode: ReplayableAudioNode;\r\n\r\n try {\r\n const audioStreamNode: IAudioStreamNode = await this.audioSource.attach(this.privRequestSession.audioNodeId);\r\n const format: AudioStreamFormatImpl = await this.audioSource.format;\r\n const deviceInfo: ISpeechConfigAudioDevice = await this.audioSource.deviceInfo;\r\n this.privIsLiveAudio = deviceInfo.type && deviceInfo.type === type.Microphones;\r\n\r\n audioNode = new ReplayableAudioNode(audioStreamNode, format.avgBytesPerSec);\r\n await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false);\r\n this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };\r\n\r\n } catch (error) {\r\n await this.privRequestSession.onStopRecognizing();\r\n throw error;\r\n }\r\n\r\n try {\r\n await conPromise;\r\n } catch (error) {\r\n await this.cancelRecognitionLocal(CancellationReason.Error, CancellationErrorCode.ConnectionFailure, error);\r\n return;\r\n }\r\n\r\n const sessionStartEventArgs: SessionEventArgs = new SessionEventArgs(this.privRequestSession.sessionId);\r\n\r\n if (!!this.privRecognizer.sessionStarted) {\r\n this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);\r\n }\r\n\r\n const messageRetrievalPromise = this.receiveMessage();\r\n const audioSendPromise = this.sendAudio(audioNode);\r\n\r\n audioSendPromise.catch(async (error: string) => {\r\n await this.cancelRecognitionLocal(CancellationReason.Error, CancellationErrorCode.RuntimeError, error);\r\n });\r\n\r\n return;\r\n }\r\n\r\n public async stopRecognizing(): Promise {\r\n if (this.privRequestSession.isRecognizing) {\r\n try {\r\n await this.audioSource.turnOff();\r\n await this.sendFinalAudio();\r\n await this.privRequestSession.onStopRecognizing();\r\n await this.privRequestSession.turnCompletionPromise;\r\n } finally {\r\n await this.privRequestSession.dispose();\r\n }\r\n }\r\n return;\r\n }\r\n\r\n public async connect(): Promise {\r\n await this.connectImpl();\r\n return Promise.resolve();\r\n }\r\n\r\n public connectAsync(cb?: Callback, err?: Callback): void {\r\n this.connectImpl().then((connection: IConnection): void => {\r\n try {\r\n if (!!cb) {\r\n cb();\r\n }\r\n } catch (e) {\r\n if (!!err) {\r\n err(e);\r\n }\r\n }\r\n }, (reason: any): void => {\r\n try {\r\n if (!!err) {\r\n err(reason);\r\n }\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n }\r\n });\r\n }\r\n\r\n protected disconnectOverride: () => Promise = undefined;\r\n\r\n public async disconnect(): Promise {\r\n await this.cancelRecognitionLocal(CancellationReason.Error,\r\n CancellationErrorCode.NoError,\r\n \"Disconnecting\");\r\n\r\n if (this.disconnectOverride !== undefined) {\r\n await this.disconnectOverride();\r\n }\r\n\r\n try {\r\n await (await this.privConnectionPromise).dispose();\r\n } catch (error) {\r\n\r\n }\r\n\r\n this.privConnectionPromise = null;\r\n }\r\n\r\n // Called when telemetry data is sent to the service.\r\n // Used for testing Telemetry capture.\r\n public static telemetryData: (json: string) => void;\r\n public static telemetryDataEnabled: boolean = true;\r\n\r\n public sendMessage(message: string): void { }\r\n\r\n public async sendNetworkMessage(path: string, payload: string | ArrayBuffer): Promise {\r\n const type: MessageType = typeof payload === \"string\" ? MessageType.Text : MessageType.Binary;\r\n const contentType: string = typeof payload === \"string\" ? \"application/json\" : \"\";\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n return connection.send(new SpeechConnectionMessage(type, path, this.privRequestSession.requestId, contentType, payload));\r\n }\r\n\r\n public set activityTemplate(messagePayload: string) { this.privActivityTemplate = messagePayload; }\r\n public get activityTemplate(): string { return this.privActivityTemplate; }\r\n\r\n protected abstract processTypeSpecificMessages(\r\n connectionMessage: SpeechConnectionMessage,\r\n successCallback?: (e: SpeechRecognitionResult) => void,\r\n errorCallBack?: (e: string) => void): Promise;\r\n\r\n protected async sendTelemetryData(): Promise {\r\n const telemetryData = this.privRequestSession.getTelemetry();\r\n if (ServiceRecognizerBase.telemetryDataEnabled !== true ||\r\n this.privIsDisposed ||\r\n null === telemetryData) {\r\n return;\r\n }\r\n\r\n if (!!ServiceRecognizerBase.telemetryData) {\r\n try {\r\n ServiceRecognizerBase.telemetryData(telemetryData);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n await connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"telemetry\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n telemetryData));\r\n }\r\n\r\n // Cancels recognition.\r\n protected abstract cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void;\r\n\r\n // Cancels recognition.\r\n protected async cancelRecognitionLocal(\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): Promise {\r\n\r\n if (!!this.privRequestSession.isRecognizing) {\r\n await this.privRequestSession.onStopRecognizing();\r\n\r\n this.cancelRecognition(\r\n this.privRequestSession.sessionId,\r\n this.privRequestSession.requestId,\r\n cancellationReason,\r\n errorCode,\r\n error);\r\n }\r\n }\r\n\r\n protected receiveMessageOverride: () => Promise = undefined;\r\n\r\n protected async receiveMessage(): Promise {\r\n try {\r\n if (this.privIsDisposed) {\r\n // We're done.\r\n return;\r\n }\r\n\r\n let connection = await this.fetchConnection();\r\n const message = await connection.read();\r\n\r\n if (this.receiveMessageOverride !== undefined) {\r\n return this.receiveMessageOverride();\r\n }\r\n\r\n // indicates we are draining the queue and it came with no message;\r\n if (!message) {\r\n if (!this.privRequestSession.isRecognizing) {\r\n return;\r\n } else {\r\n return this.receiveMessage();\r\n }\r\n }\r\n\r\n this.privServiceHasSentMessage = true;\r\n const connectionMessage = SpeechConnectionMessage.fromConnectionMessage(message);\r\n\r\n if (connectionMessage.requestId.toLowerCase() === this.privRequestSession.requestId.toLowerCase()) {\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"turn.start\":\r\n this.privMustReportEndOfStream = true;\r\n this.privRequestSession.onServiceTurnStartResponse();\r\n break;\r\n\r\n case \"speech.startdetected\":\r\n const speechStartDetected: SpeechDetected = SpeechDetected.fromJSON(connectionMessage.textBody);\r\n const speechStartEventArgs = new RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId);\r\n if (!!this.privRecognizer.speechStartDetected) {\r\n this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs);\r\n }\r\n break;\r\n\r\n case \"speech.enddetected\":\r\n let json: string;\r\n if (connectionMessage.textBody.length > 0) {\r\n json = connectionMessage.textBody;\r\n } else {\r\n // If the request was empty, the JSON returned is empty.\r\n json = \"{ Offset: 0 }\";\r\n }\r\n const speechStopDetected: SpeechDetected = SpeechDetected.fromJSON(json);\r\n // Only shrink the buffers for continuous recognition.\r\n // For single shot, the speech.phrase message will come after the speech.end and it should own buffer shrink.\r\n if (this.privRecognizerConfig.isContinuousRecognition) {\r\n this.privRequestSession.onServiceRecognized(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset);\r\n }\r\n const speechStopEventArgs = new RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);\r\n if (!!this.privRecognizer.speechEndDetected) {\r\n this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs);\r\n }\r\n break;\r\n\r\n case \"turn.end\":\r\n await this.sendTelemetryData();\r\n if (this.privRequestSession.isSpeechEnded && this.privMustReportEndOfStream) {\r\n this.privMustReportEndOfStream = false;\r\n await this.cancelRecognitionLocal(CancellationReason.EndOfStream, CancellationErrorCode.NoError, undefined);\r\n }\r\n const sessionStopEventArgs: SessionEventArgs = new SessionEventArgs(this.privRequestSession.sessionId);\r\n await this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition);\r\n if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) {\r\n if (!!this.privRecognizer.sessionStopped) {\r\n this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs);\r\n }\r\n return;\r\n } else {\r\n connection = await this.fetchConnection();\r\n await this.sendPrePayloadJSON(connection);\r\n }\r\n break;\r\n\r\n default:\r\n if (!await this.processTypeSpecificMessages(connectionMessage)) {\r\n // here are some messages that the derived class has not processed, dispatch them to connect class\r\n if (!!this.privServiceEvents) {\r\n this.serviceEvents.onEvent(new ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));\r\n }\r\n }\r\n }\r\n }\r\n return this.receiveMessage();\r\n } catch (error) {\r\n return null;\r\n }\r\n }\r\n\r\n protected sendSpeechContext = (connection: IConnection): Promise => {\r\n const speechContextJson = this.speechContext.toJSON();\r\n\r\n if (speechContextJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.context\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n speechContextJson));\r\n }\r\n return;\r\n }\r\n\r\n protected sendPrePayloadJSONOverride: (connection: IConnection) => Promise = undefined;\r\n\r\n // Encapsulated for derived service recognizers that need to send additional JSON\r\n protected async sendPrePayloadJSON(connection: IConnection): Promise {\r\n if (this.sendPrePayloadJSONOverride !== undefined) {\r\n return this.sendPrePayloadJSONOverride(connection);\r\n }\r\n\r\n await this.sendSpeechContext(connection);\r\n await this.sendWaveHeader(connection);\r\n return;\r\n }\r\n\r\n protected async sendWaveHeader(connection: IConnection): Promise {\r\n const format: AudioStreamFormatImpl = await this.audioSource.format;\r\n // this.writeBufferToConsole(format.header);\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Binary,\r\n \"audio\",\r\n this.privRequestSession.requestId,\r\n \"audio/x-wav\",\r\n format.header\r\n ));\r\n }\r\n\r\n protected postConnectImplOverride: (connection: Promise) => Promise = undefined;\r\n\r\n // Establishes a websocket connection to the end point.\r\n protected connectImpl(): Promise {\r\n if (this.privConnectionPromise) {\r\n return this.privConnectionPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.connectImpl();\r\n }\r\n return this.privConnectionPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.connectImpl();\r\n });\r\n }\r\n\r\n this.privConnectionPromise = this.retryableConnect();\r\n\r\n // Attach an empty handler to allow the promise to run in the background while\r\n // other startup events happen. It'll eventually be awaited on.\r\n this.privConnectionPromise.catch(() => { });\r\n\r\n if (this.postConnectImplOverride !== undefined) {\r\n return this.postConnectImplOverride(this.privConnectionPromise);\r\n }\r\n\r\n return this.privConnectionPromise;\r\n }\r\n\r\n protected configConnectionOverride: (connection: IConnection) => Promise = undefined;\r\n\r\n protected sendSpeechServiceConfig = (connection: IConnection, requestSession: RequestSession, SpeechServiceConfigJson: string): Promise => {\r\n // filter out anything that is not required for the service to work.\r\n if (ServiceRecognizerBase.telemetryDataEnabled !== true) {\r\n const withTelemetry = JSON.parse(SpeechServiceConfigJson);\r\n\r\n const replacement: any = {\r\n context: {\r\n system: withTelemetry.context.system,\r\n },\r\n };\r\n\r\n SpeechServiceConfigJson = JSON.stringify(replacement);\r\n }\r\n\r\n if (this.privRecognizerConfig.parameters.getProperty(\"TranscriptionService_SingleChannel\", \"false\").toLowerCase() === \"true\") {\r\n const json: { context: any } = JSON.parse(SpeechServiceConfigJson);\r\n json.context.DisableReferenceChannel = \"True\";\r\n json.context.MicSpec = \"1_0_0\";\r\n SpeechServiceConfigJson = JSON.stringify(json);\r\n }\r\n\r\n if (SpeechServiceConfigJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.config\",\r\n requestSession.requestId,\r\n \"application/json\",\r\n SpeechServiceConfigJson));\r\n }\r\n\r\n return;\r\n }\r\n\r\n protected async fetchConnection(): Promise {\r\n if (this.privConnectionConfigurationPromise) {\r\n return this.privConnectionConfigurationPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigurationPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.fetchConnection();\r\n }\r\n return this.privConnectionConfigurationPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigurationPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.fetchConnection();\r\n });\r\n }\r\n\r\n this.privConnectionConfigurationPromise = this.configureConnection();\r\n return await this.privConnectionConfigurationPromise;\r\n }\r\n\r\n protected async sendAudio(audioStreamNode: IAudioStreamNode): Promise {\r\n const audioFormat: AudioStreamFormatImpl = await this.audioSource.format;\r\n\r\n // The time we last sent data to the service.\r\n let nextSendTime: number = Date.now();\r\n\r\n // Max amount to send before we start to throttle\r\n const fastLaneSizeMs: string = this.privRecognizerConfig.parameters.getProperty(\"SPEECH-TransmitLengthBeforThrottleMs\", \"5000\");\r\n const maxSendUnthrottledBytes: number = audioFormat.avgBytesPerSec / 1000 * parseInt(fastLaneSizeMs, 10);\r\n const startRecogNumber: number = this.privRequestSession.recogNumber;\r\n\r\n const readAndUploadCycle = async (): Promise => {\r\n // If speech is done, stop sending audio.\r\n if (!this.privIsDisposed &&\r\n !this.privRequestSession.isSpeechEnded &&\r\n this.privRequestSession.isRecognizing &&\r\n this.privRequestSession.recogNumber === startRecogNumber) {\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n const audioStreamChunk: IStreamChunk = await audioStreamNode.read();\r\n // we have a new audio chunk to upload.\r\n if (this.privRequestSession.isSpeechEnded) {\r\n // If service already recognized audio end then don't send any more audio\r\n return;\r\n }\r\n\r\n let payload: ArrayBuffer;\r\n let sendDelay: number;\r\n\r\n if (!audioStreamChunk || audioStreamChunk.isEnd) {\r\n payload = null;\r\n sendDelay = 0;\r\n } else {\r\n payload = audioStreamChunk.buffer;\r\n\r\n this.privRequestSession.onAudioSent(payload.byteLength);\r\n\r\n if (maxSendUnthrottledBytes >= this.privRequestSession.bytesSent) {\r\n sendDelay = 0;\r\n } else {\r\n sendDelay = Math.max(0, nextSendTime - Date.now());\r\n }\r\n }\r\n\r\n if (0 !== sendDelay) {\r\n await this.delay(sendDelay);\r\n }\r\n\r\n if (payload !== null) {\r\n nextSendTime = Date.now() + (payload.byteLength * 1000 / (audioFormat.avgBytesPerSec * 2));\r\n }\r\n\r\n // Are we still alive?\r\n if (!this.privIsDisposed &&\r\n !this.privRequestSession.isSpeechEnded &&\r\n this.privRequestSession.isRecognizing &&\r\n this.privRequestSession.recogNumber === startRecogNumber) {\r\n connection.send(\r\n new SpeechConnectionMessage(MessageType.Binary, \"audio\", this.privRequestSession.requestId, null, payload)\r\n ).catch(() => {\r\n this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch(() => { });\r\n });\r\n\r\n if (!audioStreamChunk?.isEnd) {\r\n // this.writeBufferToConsole(payload);\r\n // Regardless of success or failure, schedule the next upload.\r\n // If the underlying connection was broken, the next cycle will\r\n // get a new connection and re-transmit missing audio automatically.\r\n return readAndUploadCycle();\r\n } else {\r\n // the audio stream has been closed, no need to schedule next\r\n // read-upload cycle.\r\n if (!this.privIsLiveAudio) {\r\n this.privRequestSession.onSpeechEnded();\r\n }\r\n }\r\n }\r\n }\r\n };\r\n\r\n return readAndUploadCycle();\r\n }\r\n\r\n private async retryableConnect(): Promise {\r\n let isUnAuthorized: boolean = false;\r\n\r\n this.privAuthFetchEventId = createNoDashGuid();\r\n const sessionId: string = this.privRequestSession.sessionId;\r\n this.privConnectionId = (sessionId !== undefined) ? sessionId : createNoDashGuid();\r\n\r\n this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId);\r\n let lastStatusCode: number = 0;\r\n let lastReason: string = \"\";\r\n\r\n while (this.privRequestSession.numConnectionAttempts <= this.privRecognizerConfig.maxRetryCount) {\r\n\r\n // 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\r\n // facing event when a connection fails to let them try and provide new auth information.\r\n const authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId);\r\n const auth: AuthInfo = await authPromise;\r\n\r\n await this.privRequestSession.onAuthCompleted(false);\r\n\r\n // Create the connection\r\n const connection: IConnection = this.privConnectionFactory.create(this.privRecognizerConfig, auth, this.privConnectionId);\r\n // Attach the telemetry handlers.\r\n this.privRequestSession.listenForServiceTelemetry(connection.events);\r\n\r\n // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away,\r\n // it'll stop sending events.\r\n connection.events.attach((event: ConnectionEvent) => {\r\n this.connectionEvents.onEvent(event);\r\n });\r\n\r\n const response: ConnectionOpenResponse = await connection.open();\r\n // 200 == everything is fine.\r\n if (response.statusCode === 200) {\r\n await this.privRequestSession.onConnectionEstablishCompleted(response.statusCode);\r\n return Promise.resolve(connection);\r\n } else if (response.statusCode === 1006) {\r\n isUnAuthorized = true;\r\n }\r\n\r\n lastStatusCode = response.statusCode;\r\n lastReason = response.reason;\r\n\r\n this.privRequestSession.onRetryConnection();\r\n }\r\n\r\n await this.privRequestSession.onConnectionEstablishCompleted(lastStatusCode, lastReason);\r\n return Promise.reject(`Unable to contact server. StatusCode: ${lastStatusCode}, ${this.privRecognizerConfig.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint)} Reason: ${lastReason}`);\r\n }\r\n\r\n private delay(delayMs: number): Promise {\r\n return new Promise((resolve: () => void, reject: (error: string) => void) => {\r\n this.privSetTimeout(resolve, delayMs);\r\n });\r\n }\r\n\r\n private writeBufferToConsole(buffer: ArrayBuffer): void {\r\n let out: string = \"Buffer Size: \";\r\n if (null === buffer) {\r\n out += \"null\";\r\n } else {\r\n const readView: Uint8Array = new Uint8Array(buffer);\r\n out += buffer.byteLength + \"\\r\\n\";\r\n for (let i: number = 0; i < buffer.byteLength; i++) {\r\n out += readView[i].toString(16).padStart(2, \"0\") + \" \";\r\n }\r\n }\r\n // tslint:disable-next-line:no-console\r\n console.info(out);\r\n }\r\n\r\n private async sendFinalAudio(): Promise {\r\n const connection: IConnection = await this.fetchConnection();\r\n await connection.send(new SpeechConnectionMessage(MessageType.Binary, \"audio\", this.privRequestSession.requestId, null, null));\r\n return;\r\n }\r\n\r\n // Takes an established websocket connection to the endpoint and sends speech configuration information.\r\n private async configureConnection(): Promise {\r\n const connection: IConnection = await this.connectImpl();\r\n if (this.configConnectionOverride !== undefined) {\r\n return this.configConnectionOverride(connection);\r\n }\r\n await this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize());\r\n await this.sendPrePayloadJSON(connection);\r\n return connection;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport interface IAuthentication {\r\n fetch(authFetchEventId: string): Promise;\r\n fetchOnExpiry(authFetchEventId: string): Promise;\r\n}\r\n\r\nexport class AuthInfo {\r\n private privHeaderName: string;\r\n private privToken: string;\r\n\r\n public constructor(headerName: string, token: string) {\r\n this.privHeaderName = headerName;\r\n this.privToken = token;\r\n }\r\n\r\n public get headerName(): string {\r\n return this.privHeaderName;\r\n }\r\n\r\n public get token(): string {\r\n return this.privToken;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ArgumentNullError,\r\n} from \"../common/Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport {\r\n AuthInfo,\r\n IAuthentication\r\n} from \"./IAuthentication\";\r\n\r\n/**\r\n * @class\r\n */\r\nexport class CognitiveSubscriptionKeyAuthentication implements IAuthentication {\r\n private privAuthInfo: AuthInfo;\r\n\r\n /**\r\n * Creates and initializes an instance of the CognitiveSubscriptionKeyAuthentication class.\r\n * @constructor\r\n * @param {string} subscriptionKey - The subscription key\r\n */\r\n constructor(subscriptionKey: string) {\r\n if (!subscriptionKey) {\r\n throw new ArgumentNullError(\"subscriptionKey\");\r\n }\r\n\r\n this.privAuthInfo = new AuthInfo(HeaderNames.AuthKey, subscriptionKey);\r\n }\r\n\r\n /**\r\n * Fetches the subscription key.\r\n * @member\r\n * @function\r\n * @public\r\n * @param {string} authFetchEventId - The id to fetch.\r\n */\r\n public fetch = (authFetchEventId: string): Promise => {\r\n return Promise.resolve(this.privAuthInfo);\r\n }\r\n\r\n /**\r\n * Fetches the subscription key.\r\n * @member\r\n * @function\r\n * @public\r\n * @param {string} authFetchEventId - The id to fetch.\r\n */\r\n public fetchOnExpiry = (authFetchEventId: string): Promise => {\r\n return Promise.resolve(this.privAuthInfo);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ArgumentNullError } from \"../common/Exports\";\r\nimport { AuthInfo, IAuthentication } from \"./IAuthentication\";\r\n\r\nconst AuthHeader: string = \"Authorization\";\r\n\r\nexport class CognitiveTokenAuthentication implements IAuthentication {\r\n private privFetchCallback: (authFetchEventId: string) => Promise;\r\n private privFetchOnExpiryCallback: (authFetchEventId: string) => Promise;\r\n\r\n constructor(fetchCallback: (authFetchEventId: string) => Promise, fetchOnExpiryCallback: (authFetchEventId: string) => Promise) {\r\n if (!fetchCallback) {\r\n throw new ArgumentNullError(\"fetchCallback\");\r\n }\r\n\r\n if (!fetchOnExpiryCallback) {\r\n throw new ArgumentNullError(\"fetchOnExpiryCallback\");\r\n }\r\n\r\n this.privFetchCallback = fetchCallback;\r\n this.privFetchOnExpiryCallback = fetchOnExpiryCallback;\r\n }\r\n\r\n public fetch = (authFetchEventId: string): Promise => {\r\n return this.privFetchCallback(authFetchEventId).then((token: string) => new AuthInfo(AuthHeader, token));\r\n }\r\n\r\n public fetchOnExpiry = (authFetchEventId: string): Promise => {\r\n return this.privFetchOnExpiryCallback(authFetchEventId).then((token: string) => new AuthInfo(AuthHeader, token));\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CognitiveSubscriptionKeyAuthentication,\r\n CognitiveTokenAuthentication,\r\n Context,\r\n IAuthentication,\r\n IConnectionFactory,\r\n OS,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n Deferred,\r\n marshalPromiseToCallbacks\r\n} from \"../common/Exports\";\r\nimport {\r\n Contracts\r\n} from \"./Contracts\";\r\nimport {\r\n AudioConfig,\r\n Connection,\r\n PropertyCollection,\r\n PropertyId,\r\n RecognitionEventArgs,\r\n SessionEventArgs,\r\n SpeechRecognitionResult,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Defines the base class Recognizer which mainly contains common event handlers.\r\n * @class Recognizer\r\n */\r\nexport abstract class Recognizer {\r\n private privDisposed: boolean;\r\n protected audioConfig: AudioConfig;\r\n protected privReco: ServiceRecognizerBase;\r\n protected privProperties: PropertyCollection;\r\n private privConnectionFactory: IConnectionFactory;\r\n\r\n /**\r\n * Creates and initializes an instance of a Recognizer\r\n * @constructor\r\n * @param {AudioConfig} audioInput - An optional audio input stream associated with the recognizer\r\n */\r\n protected constructor(audioConfig: AudioConfig, properties: PropertyCollection, connectionFactory: IConnectionFactory) {\r\n this.audioConfig = (audioConfig !== undefined) ? audioConfig : AudioConfig.fromDefaultMicrophoneInput();\r\n this.privDisposed = false;\r\n this.privProperties = properties.clone();\r\n this.privConnectionFactory = connectionFactory;\r\n this.implCommonRecognizerSetup();\r\n }\r\n\r\n /**\r\n * Defines event handler for session started events.\r\n * @member Recognizer.prototype.sessionStarted\r\n * @function\r\n * @public\r\n */\r\n public sessionStarted: (sender: Recognizer, event: SessionEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for session stopped events.\r\n * @member Recognizer.prototype.sessionStopped\r\n * @function\r\n * @public\r\n */\r\n public sessionStopped: (sender: Recognizer, event: SessionEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for speech started events.\r\n * @member Recognizer.prototype.speechStartDetected\r\n * @function\r\n * @public\r\n */\r\n public speechStartDetected: (sender: Recognizer, event: RecognitionEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for speech stopped events.\r\n * @member Recognizer.prototype.speechEndDetected\r\n * @function\r\n * @public\r\n */\r\n public speechEndDetected: (sender: Recognizer, event: RecognitionEventArgs) => void;\r\n\r\n /**\r\n * Dispose of associated resources.\r\n * @member Recognizer.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, errorCb?: (error: string) => void): void {\r\n Contracts.throwIfDisposed(this.privDisposed);\r\n marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);\r\n }\r\n\r\n /**\r\n * @Internal\r\n * Internal data member to support fromRecognizer* pattern methods on other classes.\r\n * Do not use externally, object returned will change without warning or notice.\r\n */\r\n public get internalData(): object {\r\n return this.privReco;\r\n }\r\n\r\n /**\r\n * This method performs cleanup of resources.\r\n * The Boolean parameter disposing indicates whether the method is called\r\n * from Dispose (if disposing is true) or from the finalizer (if disposing is false).\r\n * Derived classes should override this method to dispose resource if needed.\r\n * @member Recognizer.prototype.dispose\r\n * @function\r\n * @public\r\n * @param {boolean} disposing - Flag to request disposal.\r\n */\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privDisposed) {\r\n return;\r\n }\r\n\r\n this.privDisposed = true;\r\n\r\n if (disposing) {\r\n if (this.privReco) {\r\n await this.privReco.audioSource.turnOff();\r\n await this.privReco.dispose();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * This method returns the current state of the telemetry setting.\r\n * @member Recognizer.prototype.telemetryEnabled\r\n * @function\r\n * @public\r\n * @returns true if the telemetry is enabled, false otherwise.\r\n */\r\n public static get telemetryEnabled(): boolean {\r\n return ServiceRecognizerBase.telemetryDataEnabled;\r\n }\r\n\r\n /**\r\n * This method globally enables or disables telemetry.\r\n * @member Recognizer.prototype.enableTelemetry\r\n * @function\r\n * @public\r\n * @param enabled - Global setting for telemetry collection.\r\n * If set to true, telemetry information like microphone errors,\r\n * recognition errors are collected and sent to Microsoft.\r\n * If set to false, no telemetry is sent to Microsoft.\r\n */\r\n /* tslint:disable:member-ordering */\r\n public static enableTelemetry(enabled: boolean): void {\r\n ServiceRecognizerBase.telemetryDataEnabled = enabled;\r\n }\r\n\r\n //\r\n // ################################################################################################################\r\n // IMPLEMENTATION.\r\n // Move to independent class\r\n // ################################################################################################################\r\n //\r\n protected abstract createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig;\r\n\r\n // Creates the correct service recognizer for the type\r\n protected abstract createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase;\r\n\r\n // Does the generic recognizer setup that is common across all recognizer types.\r\n protected implCommonRecognizerSetup(): void {\r\n\r\n let osPlatform = (typeof window !== \"undefined\") ? \"Browser\" : \"Node\";\r\n let osName = \"unknown\";\r\n let osVersion = \"unknown\";\r\n\r\n if (typeof navigator !== \"undefined\") {\r\n osPlatform = osPlatform + \"/\" + navigator.platform;\r\n osName = navigator.userAgent;\r\n osVersion = navigator.appVersion;\r\n }\r\n\r\n const recognizerConfig = this.createRecognizerConfig(\r\n new SpeechServiceConfig(\r\n new Context(new OS(osPlatform, osName, osVersion))));\r\n\r\n this.privReco = this.createServiceRecognizer(\r\n Recognizer.getAuthFromProperties(this.privProperties),\r\n this.privConnectionFactory,\r\n this.audioConfig,\r\n recognizerConfig);\r\n }\r\n\r\n protected async recognizeOnceAsyncImpl(recognitionMode: RecognitionMode): Promise {\r\n Contracts.throwIfDisposed(this.privDisposed);\r\n const ret: Deferred = new Deferred();\r\n\r\n await this.implRecognizerStop();\r\n await this.privReco.recognize(recognitionMode, ret.resolve, ret.reject);\r\n const result: SpeechRecognitionResult = await ret.promise;\r\n await this.implRecognizerStop();\r\n\r\n return result;\r\n\r\n }\r\n\r\n protected async startContinuousRecognitionAsyncImpl(recognitionMode: RecognitionMode): Promise {\r\n Contracts.throwIfDisposed(this.privDisposed);\r\n\r\n await this.implRecognizerStop();\r\n await this.privReco.recognize(recognitionMode, undefined, undefined);\r\n }\r\n\r\n protected async stopContinuousRecognitionAsyncImpl(): Promise {\r\n Contracts.throwIfDisposed(this.privDisposed);\r\n await this.implRecognizerStop();\r\n }\r\n\r\n protected async implRecognizerStop(): Promise {\r\n if (this.privReco) {\r\n await this.privReco.stopRecognizing();\r\n }\r\n return;\r\n }\r\n\r\n protected static getAuthFromProperties(properties: PropertyCollection): IAuthentication {\r\n const subscriptionKey = properties.getProperty(PropertyId.SpeechServiceConnection_Key, undefined);\r\n const authentication = (subscriptionKey && subscriptionKey !== \"\") ?\r\n new CognitiveSubscriptionKeyAuthentication(subscriptionKey) :\r\n new CognitiveTokenAuthentication(\r\n (authFetchEventId: string): Promise => {\r\n const authorizationToken = properties.getProperty(PropertyId.SpeechServiceAuthorization_Token, undefined);\r\n return Promise.resolve(authorizationToken);\r\n },\r\n (authFetchEventId: string): Promise => {\r\n const authorizationToken = properties.getProperty(PropertyId.SpeechServiceAuthorization_Token, undefined);\r\n return Promise.resolve(authorizationToken);\r\n });\r\n\r\n return authentication;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport class ConnectionOpenResponse {\r\n private privStatusCode: number;\r\n private privReason: string;\r\n\r\n constructor(statusCode: number, reason: string) {\r\n this.privStatusCode = statusCode;\r\n this.privReason = reason;\r\n }\r\n\r\n public get statusCode(): number {\r\n return this.privStatusCode;\r\n }\r\n\r\n public get reason(): string {\r\n return this.privReason;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { MessageType } from \"./ConnectionMessage\";\r\nimport { ArgumentNullError, InvalidOperationError } from \"./Error\";\r\nimport { createNoDashGuid } from \"./Guid\";\r\n\r\nexport class RawWebsocketMessage {\r\n private privMessageType: MessageType;\r\n private privPayload: any = null;\r\n private privId: string;\r\n\r\n public constructor(messageType: MessageType, payload: any, id?: string) {\r\n if (!payload) {\r\n throw new ArgumentNullError(\"payload\");\r\n }\r\n\r\n if (messageType === MessageType.Binary && payload.__proto__.constructor.name !== \"ArrayBuffer\") {\r\n throw new InvalidOperationError(\"Payload must be ArrayBuffer\");\r\n }\r\n\r\n if (messageType === MessageType.Text && !(typeof (payload) === \"string\")) {\r\n throw new InvalidOperationError(\"Payload must be a string\");\r\n }\r\n\r\n this.privMessageType = messageType;\r\n this.privPayload = payload;\r\n this.privId = id ? id : createNoDashGuid();\r\n }\r\n\r\n public get messageType(): MessageType {\r\n return this.privMessageType;\r\n }\r\n\r\n public get payload(): any {\r\n return this.privPayload;\r\n }\r\n\r\n public get textContent(): string {\r\n if (this.privMessageType === MessageType.Binary) {\r\n throw new InvalidOperationError(\"Not supported for binary message\");\r\n }\r\n\r\n return this.privPayload as string;\r\n }\r\n\r\n public get binaryContent(): ArrayBuffer {\r\n if (this.privMessageType === MessageType.Text) {\r\n throw new InvalidOperationError(\"Not supported for text message\");\r\n }\r\n\r\n return this.privPayload;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { EventType, PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class OCSPEvent extends PlatformEvent {\r\n private privSignature: string;\r\n\r\n constructor(eventName: string, eventType: EventType, signature: string) {\r\n super(eventName, eventType);\r\n\r\n this.privSignature = signature;\r\n }\r\n}\r\n\r\nexport class OCSPMemoryCacheHitEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPMemoryCacheHitEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPCacheMissEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPCacheMissEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPDiskCacheHitEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPDiskCacheHitEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPCacheUpdateNeededEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPCacheUpdateNeededEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPMemoryCacheStoreEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPMemoryCacheStoreEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPDiskCacheStoreEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPDiskCacheStoreEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPCacheUpdatehCompleteEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPCacheUpdatehCompleteEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPStapleReceivedEvent extends OCSPEvent {\r\n constructor() {\r\n super(\"OCSPStapleReceivedEvent\", EventType.Debug, \"\");\r\n }\r\n}\r\n\r\nexport class OCSPWSUpgradeStartedEvent extends OCSPEvent {\r\n constructor(serialNumber: string) {\r\n super(\"OCSPWSUpgradeStartedEvent\", EventType.Debug, serialNumber);\r\n }\r\n}\r\n\r\nexport class OCSPCacheEntryExpiredEvent extends OCSPEvent {\r\n private privExpireTime: number;\r\n\r\n constructor(serialNumber: string, expireTime: number) {\r\n super(\"OCSPCacheEntryExpiredEvent\", EventType.Debug, serialNumber);\r\n this.privExpireTime = expireTime;\r\n }\r\n}\r\n\r\nexport class OCSPCacheEntryNeedsRefreshEvent extends OCSPEvent {\r\n private privExpireTime: number;\r\n private privStartTime: number;\r\n\r\n constructor(serialNumber: string, startTime: number, expireTime: number) {\r\n super(\"OCSPCacheEntryNeedsRefreshEvent\", EventType.Debug, serialNumber);\r\n this.privExpireTime = expireTime;\r\n this.privStartTime = startTime;\r\n }\r\n}\r\n\r\nexport class OCSPCacheHitEvent extends OCSPEvent {\r\n private privExpireTime: number;\r\n private privStartTime: number;\r\n private privExpireTimeString: string;\r\n private privStartTimeString: string;\r\n\r\n constructor(serialNumber: string, startTime: number, expireTime: number) {\r\n super(\"OCSPCacheHitEvent\", EventType.Debug, serialNumber);\r\n this.privExpireTime = expireTime;\r\n this.privExpireTimeString = new Date(expireTime).toLocaleDateString();\r\n this.privStartTime = startTime;\r\n this.privStartTimeString = new Date(startTime).toLocaleTimeString();\r\n }\r\n}\r\n\r\nexport class OCSPVerificationFailedEvent extends OCSPEvent {\r\n private privError: string;\r\n\r\n constructor(serialNumber: string, error: string) {\r\n super(\"OCSPVerificationFailedEvent\", EventType.Debug, serialNumber);\r\n this.privError = error;\r\n }\r\n}\r\n\r\nexport class OCSPCacheFetchErrorEvent extends OCSPEvent {\r\n private privError: string;\r\n\r\n constructor(serialNumber: string, error: string) {\r\n super(\"OCSPCacheFetchErrorEvent\", EventType.Debug, serialNumber);\r\n this.privError = error;\r\n }\r\n}\r\n\r\nexport class OCSPResponseRetrievedEvent extends OCSPEvent {\r\n constructor(serialNumber: string) {\r\n super(\"OCSPResponseRetrievedEvent\", EventType.Debug, serialNumber);\r\n }\r\n}\r\n\r\nexport class OCSPCacheUpdateErrorEvent extends OCSPEvent {\r\n private privError: string;\r\n\r\n constructor(serialNumber: string, error: string) {\r\n super(\"OCSPCacheUpdateErrorEvent\", EventType.Debug, serialNumber);\r\n this.privError = error;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport * as http from \"http\";\r\nimport * as tls from \"tls\";\r\nimport * as parse from \"url-parse\";\r\nimport * as ocsp from \"../../external/ocsp/ocsp\";\r\nimport {\r\n Events,\r\n OCSPCacheEntryExpiredEvent,\r\n OCSPCacheEntryNeedsRefreshEvent,\r\n OCSPCacheFetchErrorEvent,\r\n OCSPCacheHitEvent,\r\n OCSPCacheMissEvent,\r\n OCSPCacheUpdatehCompleteEvent,\r\n OCSPCacheUpdateNeededEvent,\r\n OCSPDiskCacheHitEvent,\r\n OCSPDiskCacheStoreEvent,\r\n OCSPEvent,\r\n OCSPMemoryCacheHitEvent,\r\n OCSPMemoryCacheStoreEvent,\r\n OCSPResponseRetrievedEvent,\r\n OCSPStapleReceivedEvent,\r\n OCSPVerificationFailedEvent,\r\n} from \"../common/Exports\";\r\nimport { IStringDictionary } from \"../common/IDictionary\";\r\nimport { ProxyInfo } from \"./ProxyInfo\";\r\n\r\nimport Agent from \"agent-base\";\r\n\r\n// @ts-ignore\r\nimport Cache from \"async-disk-cache\";\r\nimport HttpsProxyAgent from \"https-proxy-agent\";\r\nimport * as net from \"net\";\r\nimport { OCSPCacheUpdateErrorEvent } from \"../common/OCSPEvents\";\r\n\r\nexport class CertCheckAgent {\r\n\r\n // Test hook to enable forcing expiration / refresh to happen.\r\n public static testTimeOffset: number = 0;\r\n\r\n // Test hook to disable stapling for cache testing.\r\n public static forceDisableOCSPStapling: boolean = false;\r\n\r\n // An in memory cache for recived responses.\r\n private static privMemCache: IStringDictionary = {};\r\n\r\n // The on disk cache.\r\n private static privDiskCache: Cache;\r\n\r\n private privProxyInfo: ProxyInfo;\r\n\r\n constructor(proxyInfo?: ProxyInfo) {\r\n if (!!proxyInfo) {\r\n this.privProxyInfo = proxyInfo;\r\n }\r\n\r\n // Initialize this here to allow tests to set the env variable before the cache is constructed.\r\n if (!CertCheckAgent.privDiskCache) {\r\n CertCheckAgent.privDiskCache = new Cache(\"microsoft-cognitiveservices-speech-sdk-cache\", { supportBuffer: true, location: (typeof process !== \"undefined\" && !!process.env.SPEECH_OCSP_CACHE_ROOT) ? process.env.SPEECH_OCSP_CACHE_ROOT : undefined });\r\n }\r\n }\r\n\r\n // Test hook to force the disk cache to be recreated.\r\n public static forceReinitDiskCache(): void {\r\n CertCheckAgent.privDiskCache = undefined;\r\n CertCheckAgent.privMemCache = {};\r\n }\r\n\r\n public GetAgent(disableStapling?: boolean): http.Agent {\r\n const agent: any = new Agent.Agent(this.CreateConnection);\r\n\r\n if (this.privProxyInfo !== undefined &&\r\n this.privProxyInfo.HostName !== undefined &&\r\n this.privProxyInfo.Port > 0) {\r\n const proxyName: string = \"privProxyInfo\";\r\n agent[proxyName] = this.privProxyInfo;\r\n }\r\n\r\n return agent;\r\n }\r\n\r\n private static GetProxyAgent(proxyInfo: ProxyInfo): HttpsProxyAgent {\r\n const httpProxyOptions: HttpsProxyAgent.HttpsProxyAgentOptions = {\r\n host: proxyInfo.HostName,\r\n port: proxyInfo.Port,\r\n };\r\n\r\n if (!!proxyInfo.UserName) {\r\n httpProxyOptions.headers = {\r\n \"Proxy-Authentication\": \"Basic \" + new Buffer(proxyInfo.UserName + \":\" + (proxyInfo.Password === undefined) ? \"\" : proxyInfo.Password).toString(\"base64\"),\r\n };\r\n } else {\r\n httpProxyOptions.headers = {};\r\n }\r\n\r\n httpProxyOptions.headers.requestOCSP = \"true\";\r\n\r\n const httpProxyAgent: HttpsProxyAgent = new HttpsProxyAgent(httpProxyOptions);\r\n return httpProxyAgent;\r\n }\r\n\r\n private static async OCSPCheck(socketPromise: Promise, proxyInfo: ProxyInfo): Promise {\r\n let ocspRequest: ocsp.Request;\r\n let stapling: Buffer;\r\n let resolved: boolean = false;\r\n\r\n const socket: net.Socket = await socketPromise;\r\n socket.cork();\r\n\r\n const tlsSocket: tls.TLSSocket = socket as tls.TLSSocket;\r\n\r\n return new Promise((resolve: (value: net.Socket) => void, reject: (error: string | Error) => void) => {\r\n socket.on(\"OCSPResponse\", (data: Buffer): void => {\r\n if (!!data) {\r\n this.onEvent(new OCSPStapleReceivedEvent());\r\n stapling = data;\r\n }\r\n });\r\n\r\n socket.on(\"error\", (error: Error) => {\r\n if (!resolved) {\r\n resolved = true;\r\n socket.destroy();\r\n reject(error);\r\n }\r\n });\r\n\r\n tlsSocket.on(\"secure\", async () => {\r\n const peer: tls.DetailedPeerCertificate = tlsSocket.getPeerCertificate(true);\r\n try {\r\n const issuer: tls.DetailedPeerCertificate = await this.GetIssuer(peer);\r\n\r\n // We always need a request to verify the response.\r\n ocspRequest = ocsp.request.generate(peer.raw, issuer.raw);\r\n\r\n // Do we have a result for this certificate in our memory cache?\r\n const sig: string = ocspRequest.id.toString(\"hex\");\r\n\r\n // Stapled response trumps cached response.\r\n if (!stapling) {\r\n const cacheEntry: Buffer = await CertCheckAgent.GetResponseFromCache(sig, ocspRequest, proxyInfo);\r\n stapling = cacheEntry;\r\n }\r\n\r\n await this.VerifyOCSPResponse(stapling, ocspRequest, proxyInfo);\r\n\r\n socket.uncork();\r\n resolved = true;\r\n resolve(socket);\r\n } catch (e) {\r\n socket.destroy();\r\n resolved = true;\r\n reject(e);\r\n }\r\n });\r\n });\r\n }\r\n\r\n private static GetIssuer(peer: tls.DetailedPeerCertificate): Promise {\r\n if (peer.issuerCertificate) {\r\n return Promise.resolve(peer.issuerCertificate);\r\n }\r\n\r\n return new Promise((resolve: (value: tls.DetailedPeerCertificate) => void, reject: (reason: string) => void) => {\r\n const ocspAgent: ocsp.Agent = new ocsp.Agent({});\r\n ocspAgent.fetchIssuer(peer, null, (error: string, value: tls.DetailedPeerCertificate): void => {\r\n if (!!error) {\r\n reject(error);\r\n return;\r\n }\r\n\r\n resolve(value);\r\n });\r\n });\r\n }\r\n\r\n private static async GetResponseFromCache(signature: string, ocspRequest: ocsp.Request, proxyInfo: ProxyInfo): Promise {\r\n let cachedResponse: Buffer = CertCheckAgent.privMemCache[signature];\r\n\r\n if (!!cachedResponse) {\r\n this.onEvent(new OCSPMemoryCacheHitEvent(signature));\r\n }\r\n\r\n // Do we have a result for this certificate on disk in %TMP%?\r\n if (!cachedResponse) {\r\n try {\r\n const diskCacheResponse: any = await CertCheckAgent.privDiskCache.get(signature);\r\n if (!!diskCacheResponse.isCached) {\r\n CertCheckAgent.onEvent(new OCSPDiskCacheHitEvent(signature));\r\n CertCheckAgent.StoreMemoryCacheEntry(signature, diskCacheResponse.value);\r\n cachedResponse = diskCacheResponse.value;\r\n }\r\n } catch (error) {\r\n cachedResponse = null;\r\n }\r\n }\r\n\r\n if (!cachedResponse) {\r\n return cachedResponse;\r\n }\r\n\r\n try {\r\n const cachedOcspResponse: ocsp.Response = ocsp.utils.parseResponse(cachedResponse);\r\n const tbsData = cachedOcspResponse.value.tbsResponseData;\r\n if (tbsData.responses.length < 1) {\r\n this.onEvent(new OCSPCacheFetchErrorEvent(signature, \"Not enough data in cached response\"));\r\n return;\r\n }\r\n\r\n const cachedStartTime: number = tbsData.responses[0].thisUpdate;\r\n const cachedNextTime: number = tbsData.responses[0].nextUpdate;\r\n\r\n if (cachedNextTime < (Date.now() + this.testTimeOffset - 60000)) {\r\n // Cached entry has expired.\r\n this.onEvent(new OCSPCacheEntryExpiredEvent(signature, cachedNextTime));\r\n cachedResponse = null;\r\n } else {\r\n // If we're within one day of the next update, or 50% of the way through the validity period,\r\n // background an update to the cache.\r\n\r\n const minUpdate: number = Math.min(24 * 60 * 60 * 1000, (cachedNextTime - cachedStartTime) / 2);\r\n\r\n if ((cachedNextTime - (Date.now() + this.testTimeOffset)) < minUpdate) {\r\n this.onEvent(new OCSPCacheEntryNeedsRefreshEvent(signature, cachedStartTime, cachedNextTime));\r\n this.UpdateCache(ocspRequest, proxyInfo).catch((error: string) => {\r\n // Well, not much we can do here.\r\n this.onEvent(new OCSPCacheUpdateErrorEvent(signature, error.toString()));\r\n });\r\n } else {\r\n this.onEvent(new OCSPCacheHitEvent(signature, cachedStartTime, cachedNextTime));\r\n }\r\n }\r\n } catch (error) {\r\n this.onEvent(new OCSPCacheFetchErrorEvent(signature, error));\r\n cachedResponse = null;\r\n }\r\n if (!cachedResponse) {\r\n this.onEvent(new OCSPCacheMissEvent(signature));\r\n }\r\n return cachedResponse;\r\n }\r\n\r\n private static async VerifyOCSPResponse(cacheValue: Buffer, ocspRequest: ocsp.Request, proxyInfo: ProxyInfo): Promise {\r\n let ocspResponse: Buffer = cacheValue;\r\n const sig: string = ocspRequest.certID.toString(\"hex\");\r\n\r\n // Do we have a valid response?\r\n if (!ocspResponse) {\r\n ocspResponse = await CertCheckAgent.GetOCSPResponse(ocspRequest, proxyInfo);\r\n }\r\n\r\n return new Promise((resolve: () => void, reject: (error: string | Error) => void) => {\r\n ocsp.verify({ request: ocspRequest, response: ocspResponse }, (error: string, result: any): void => {\r\n if (!!error) {\r\n CertCheckAgent.onEvent(new OCSPVerificationFailedEvent(ocspRequest.id.toString(\"hex\"), error));\r\n\r\n // Bad Cached Value? One more try without the cache.\r\n if (!!cacheValue) {\r\n this.VerifyOCSPResponse(null, ocspRequest, proxyInfo).then(() => {\r\n resolve();\r\n }, (error: Error) => {\r\n reject(error);\r\n });\r\n } else {\r\n reject(error);\r\n }\r\n } else {\r\n if (!cacheValue) {\r\n CertCheckAgent.StoreCacheEntry(ocspRequest.id.toString(\"hex\"), ocspResponse);\r\n }\r\n resolve();\r\n }\r\n });\r\n });\r\n }\r\n\r\n private static async UpdateCache(req: ocsp.Request, proxyInfo: ProxyInfo): Promise {\r\n const signature: string = req.id.toString(\"hex\");\r\n this.onEvent(new OCSPCacheUpdateNeededEvent(signature));\r\n\r\n const rawResponse: Buffer = await this.GetOCSPResponse(req, proxyInfo);\r\n this.StoreCacheEntry(signature, rawResponse);\r\n this.onEvent(new OCSPCacheUpdatehCompleteEvent(req.id.toString(\"hex\")));\r\n\r\n }\r\n\r\n private static StoreCacheEntry(sig: string, rawResponse: Buffer): void {\r\n this.StoreMemoryCacheEntry(sig, rawResponse);\r\n this.StoreDiskCacheEntry(sig, rawResponse);\r\n }\r\n\r\n private static StoreMemoryCacheEntry(sig: string, rawResponse: Buffer): void {\r\n this.privMemCache[sig] = rawResponse;\r\n this.onEvent(new OCSPMemoryCacheStoreEvent(sig));\r\n }\r\n\r\n private static StoreDiskCacheEntry(sig: string, rawResponse: Buffer): void {\r\n this.privDiskCache.set(sig, rawResponse).then(() => {\r\n this.onEvent(new OCSPDiskCacheStoreEvent(sig));\r\n });\r\n }\r\n\r\n private static GetOCSPResponse(req: ocsp.Request, proxyInfo: ProxyInfo): Promise {\r\n\r\n const ocspMethod: string = \"1.3.6.1.5.5.7.48.1\";\r\n let options: http.RequestOptions = {};\r\n\r\n if (!!proxyInfo) {\r\n const agent: HttpsProxyAgent = CertCheckAgent.GetProxyAgent(proxyInfo);\r\n options.agent = agent;\r\n }\r\n\r\n return new Promise((resolve: (value: Buffer) => void, reject: (error: string | Error) => void) => {\r\n ocsp.utils.getAuthorityInfo(req.cert, ocspMethod, (error: string, uri: string): void => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n }\r\n\r\n const parsedUri: {[k: string]: any} = parse.default(uri);\r\n parsedUri.path = parsedUri.pathname;\r\n options = { ...options, ...parsedUri };\r\n\r\n ocsp.utils.getResponse(options, req.data, (error: string, raw: Buffer): void => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n }\r\n\r\n this.onEvent(new OCSPResponseRetrievedEvent(req.certID.toString(\"hex\")));\r\n resolve(raw);\r\n });\r\n });\r\n });\r\n }\r\n\r\n private static onEvent = (event: OCSPEvent): void => {\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private CreateConnection(request: Agent.ClientRequest, options: Agent.RequestOptions): Promise {\r\n const enableOCSP: boolean = (typeof process !== \"undefined\" && process.env.NODE_TLS_REJECT_UNAUTHORIZED !== \"0\" && process.env.SPEECH_CONDUCT_OCSP_CHECK !== \"0\") && options.secureEndpoint;\r\n let socketPromise: Promise;\r\n\r\n options = {\r\n ...options,\r\n ...{\r\n requestOCSP: !CertCheckAgent.forceDisableOCSPStapling,\r\n servername: options.host\r\n }\r\n };\r\n\r\n if (!!this.privProxyInfo) {\r\n const httpProxyAgent: HttpsProxyAgent = CertCheckAgent.GetProxyAgent(this.privProxyInfo);\r\n const baseAgent: Agent.Agent = httpProxyAgent as unknown as Agent.Agent;\r\n\r\n socketPromise = new Promise((resolve: (value: net.Socket) => void, reject: (error: string | Error) => void) => {\r\n baseAgent.callback(request, options, (error: Error, socket: net.Socket) => {\r\n if (!!error) {\r\n reject(error);\r\n } else {\r\n resolve(socket);\r\n }\r\n });\r\n });\r\n } else {\r\n if (!!options.secureEndpoint) {\r\n socketPromise = Promise.resolve(tls.connect(options));\r\n } else {\r\n socketPromise = Promise.resolve(net.connect(options));\r\n }\r\n }\r\n\r\n if (!!enableOCSP) {\r\n return CertCheckAgent.OCSPCheck(socketPromise, this.privProxyInfo);\r\n } else {\r\n return socketPromise;\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { HeaderNames } from \"../common.speech/HeaderNames\";\r\nimport {\r\n ArgumentNullError,\r\n BackgroundEvent,\r\n ConnectionClosedEvent,\r\n ConnectionErrorEvent,\r\n ConnectionEstablishedEvent,\r\n ConnectionEvent,\r\n ConnectionMessage,\r\n ConnectionMessageReceivedEvent,\r\n ConnectionMessageSentEvent,\r\n ConnectionOpenResponse,\r\n ConnectionStartEvent,\r\n ConnectionState,\r\n Deferred,\r\n Events,\r\n EventSource,\r\n IWebsocketMessageFormatter,\r\n MessageType,\r\n Queue,\r\n RawWebsocketMessage,\r\n} from \"../common/Exports\";\r\nimport { ProxyInfo } from \"./ProxyInfo\";\r\n\r\n// Node.JS specific web socket / browser support.\r\nimport ws from \"ws\";\r\nimport { CertCheckAgent } from \"./CertChecks\";\r\n\r\ninterface ISendItem {\r\n Message: ConnectionMessage;\r\n RawWebsocketMessage: RawWebsocketMessage;\r\n sendStatusDeferral: Deferred;\r\n}\r\n\r\nexport class WebsocketMessageAdapter {\r\n private privConnectionState: ConnectionState;\r\n private privMessageFormatter: IWebsocketMessageFormatter;\r\n private privWebsocketClient: WebSocket | ws;\r\n\r\n private privSendMessageQueue: Queue;\r\n private privReceivingMessageQueue: Queue;\r\n private privConnectionEstablishDeferral: Deferred;\r\n private privCertificateValidatedDeferral: Deferred;\r\n private privDisconnectDeferral: Deferred;\r\n private privConnectionEvents: EventSource;\r\n private privConnectionId: string;\r\n private privUri: string;\r\n private proxyInfo: ProxyInfo;\r\n private privHeaders: { [key: string]: string; };\r\n private privLastErrorReceived: string;\r\n private privEnableCompression: boolean;\r\n\r\n public static forceNpmWebSocket: boolean = false;\r\n\r\n public constructor(\r\n uri: string,\r\n connectionId: string,\r\n messageFormatter: IWebsocketMessageFormatter,\r\n proxyInfo: ProxyInfo,\r\n headers: { [key: string]: string; },\r\n enableCompression: boolean) {\r\n\r\n if (!uri) {\r\n throw new ArgumentNullError(\"uri\");\r\n }\r\n\r\n if (!messageFormatter) {\r\n throw new ArgumentNullError(\"messageFormatter\");\r\n }\r\n\r\n this.proxyInfo = proxyInfo;\r\n this.privConnectionEvents = new EventSource();\r\n this.privConnectionId = connectionId;\r\n this.privMessageFormatter = messageFormatter;\r\n this.privConnectionState = ConnectionState.None;\r\n this.privUri = uri;\r\n this.privHeaders = headers;\r\n this.privEnableCompression = enableCompression;\r\n\r\n // Add the connection ID to the headers\r\n this.privHeaders[HeaderNames.ConnectionId] = this.privConnectionId;\r\n\r\n this.privLastErrorReceived = \"\";\r\n }\r\n\r\n public get state(): ConnectionState {\r\n return this.privConnectionState;\r\n }\r\n\r\n public open = (): Promise => {\r\n if (this.privConnectionState === ConnectionState.Disconnected) {\r\n return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);\r\n }\r\n\r\n if (this.privConnectionEstablishDeferral) {\r\n return this.privConnectionEstablishDeferral.promise;\r\n }\r\n\r\n this.privConnectionEstablishDeferral = new Deferred();\r\n this.privCertificateValidatedDeferral = new Deferred();\r\n\r\n this.privConnectionState = ConnectionState.Connecting;\r\n\r\n try {\r\n\r\n if (typeof WebSocket !== \"undefined\" && !WebsocketMessageAdapter.forceNpmWebSocket) {\r\n // Browser handles cert checks.\r\n this.privCertificateValidatedDeferral.resolve();\r\n\r\n this.privWebsocketClient = new WebSocket(this.privUri);\r\n } else {\r\n const options: ws.ClientOptions = { headers: this.privHeaders, perMessageDeflate: this.privEnableCompression };\r\n // The ocsp library will handle validation for us and fail the connection if needed.\r\n this.privCertificateValidatedDeferral.resolve();\r\n const checkAgent: CertCheckAgent = new CertCheckAgent(this.proxyInfo);\r\n\r\n options.agent = checkAgent.GetAgent();\r\n this.privWebsocketClient = new ws(this.privUri, options);\r\n }\r\n\r\n this.privWebsocketClient.binaryType = \"arraybuffer\";\r\n this.privReceivingMessageQueue = new Queue();\r\n this.privDisconnectDeferral = new Deferred();\r\n this.privSendMessageQueue = new Queue();\r\n this.processSendQueue().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n } catch (error) {\r\n this.privConnectionEstablishDeferral.resolve(new ConnectionOpenResponse(500, error));\r\n return this.privConnectionEstablishDeferral.promise;\r\n }\r\n\r\n this.onEvent(new ConnectionStartEvent(this.privConnectionId, this.privUri));\r\n\r\n this.privWebsocketClient.onopen = (e: { target: WebSocket | ws }) => {\r\n this.privCertificateValidatedDeferral.promise.then((): void => {\r\n this.privConnectionState = ConnectionState.Connected;\r\n this.onEvent(new ConnectionEstablishedEvent(this.privConnectionId));\r\n this.privConnectionEstablishDeferral.resolve(new ConnectionOpenResponse(200, \"\"));\r\n }, (error: string): void => {\r\n this.privConnectionEstablishDeferral.reject(error);\r\n });\r\n };\r\n\r\n this.privWebsocketClient.onerror = (e: { error: any; message: string; type: string; target: WebSocket | ws }) => {\r\n this.onEvent(new ConnectionErrorEvent(this.privConnectionId, e.message, e.type));\r\n this.privLastErrorReceived = e.message;\r\n };\r\n\r\n this.privWebsocketClient.onclose = (e: { wasClean: boolean; code: number; reason: string; target: WebSocket | ws }) => {\r\n if (this.privConnectionState === ConnectionState.Connecting) {\r\n this.privConnectionState = ConnectionState.Disconnected;\r\n // this.onEvent(new ConnectionEstablishErrorEvent(this.connectionId, e.code, e.reason));\r\n this.privConnectionEstablishDeferral.resolve(new ConnectionOpenResponse(e.code, e.reason + \" \" + this.privLastErrorReceived));\r\n } else {\r\n this.privConnectionState = ConnectionState.Disconnected;\r\n this.privWebsocketClient = null;\r\n this.onEvent(new ConnectionClosedEvent(this.privConnectionId, e.code, e.reason));\r\n }\r\n\r\n this.onClose(e.code, e.reason).catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n };\r\n\r\n this.privWebsocketClient.onmessage = (e: { data: ws.Data; type: string; target: WebSocket | ws }) => {\r\n const networkReceivedTime = new Date().toISOString();\r\n if (this.privConnectionState === ConnectionState.Connected) {\r\n const deferred = new Deferred();\r\n // let id = ++this.idCounter;\r\n this.privReceivingMessageQueue.enqueueFromPromise(deferred.promise);\r\n if (e.data instanceof ArrayBuffer) {\r\n const rawMessage = new RawWebsocketMessage(MessageType.Binary, e.data);\r\n this.privMessageFormatter\r\n .toConnectionMessage(rawMessage)\r\n .then((connectionMessage: ConnectionMessage) => {\r\n this.onEvent(new ConnectionMessageReceivedEvent(this.privConnectionId, networkReceivedTime, connectionMessage));\r\n deferred.resolve(connectionMessage);\r\n }, (error: string) => {\r\n // TODO: Events for these ?\r\n deferred.reject(`Invalid binary message format. Error: ${error}`);\r\n });\r\n } else {\r\n const rawMessage = new RawWebsocketMessage(MessageType.Text, e.data);\r\n this.privMessageFormatter\r\n .toConnectionMessage(rawMessage)\r\n .then((connectionMessage: ConnectionMessage) => {\r\n this.onEvent(new ConnectionMessageReceivedEvent(this.privConnectionId, networkReceivedTime, connectionMessage));\r\n deferred.resolve(connectionMessage);\r\n }, (error: string) => {\r\n // TODO: Events for these ?\r\n deferred.reject(`Invalid text message format. Error: ${error}`);\r\n });\r\n }\r\n }\r\n };\r\n\r\n return this.privConnectionEstablishDeferral.promise;\r\n }\r\n\r\n public send = (message: ConnectionMessage): Promise => {\r\n if (this.privConnectionState !== ConnectionState.Connected) {\r\n return Promise.reject(`Cannot send on connection that is in ${ConnectionState[this.privConnectionState]} state`);\r\n }\r\n\r\n const messageSendStatusDeferral = new Deferred();\r\n const messageSendDeferral = new Deferred();\r\n\r\n this.privSendMessageQueue.enqueueFromPromise(messageSendDeferral.promise);\r\n\r\n this.privMessageFormatter\r\n .fromConnectionMessage(message)\r\n .then((rawMessage: RawWebsocketMessage) => {\r\n messageSendDeferral.resolve({\r\n Message: message,\r\n RawWebsocketMessage: rawMessage,\r\n sendStatusDeferral: messageSendStatusDeferral,\r\n });\r\n }, (error: string) => {\r\n messageSendDeferral.reject(`Error formatting the message. ${error}`);\r\n });\r\n\r\n return messageSendStatusDeferral.promise;\r\n }\r\n\r\n public read = (): Promise => {\r\n if (this.privConnectionState !== ConnectionState.Connected) {\r\n return Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`);\r\n }\r\n\r\n return this.privReceivingMessageQueue.dequeue();\r\n }\r\n\r\n public close = (reason?: string): Promise => {\r\n if (this.privWebsocketClient) {\r\n if (this.privConnectionState !== ConnectionState.Disconnected) {\r\n this.privWebsocketClient.close(1000, reason ? reason : \"Normal closure by client\");\r\n }\r\n } else {\r\n return Promise.resolve();\r\n }\r\n\r\n return this.privDisconnectDeferral.promise;\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privConnectionEvents;\r\n }\r\n\r\n private sendRawMessage = (sendItem: ISendItem): Promise => {\r\n try {\r\n // indicates we are draining the queue and it came with no message;\r\n if (!sendItem) {\r\n return Promise.resolve();\r\n }\r\n\r\n this.onEvent(new ConnectionMessageSentEvent(this.privConnectionId, new Date().toISOString(), sendItem.Message));\r\n\r\n // add a check for the ws readystate in order to stop the red console error 'WebSocket is already in CLOSING or CLOSED state' appearing\r\n if (this.isWebsocketOpen) {\r\n this.privWebsocketClient.send(sendItem.RawWebsocketMessage.payload);\r\n } else {\r\n return Promise.reject(\"websocket send error: Websocket not ready \" + this.privConnectionId + \" \" + sendItem.Message.id + \" \" + new Error().stack);\r\n }\r\n return Promise.resolve();\r\n\r\n } catch (e) {\r\n return Promise.reject(`websocket send error: ${e}`);\r\n }\r\n }\r\n\r\n private async onClose(code: number, reason: string): Promise {\r\n const closeReason = `Connection closed. ${code}: ${reason}`;\r\n this.privConnectionState = ConnectionState.Disconnected;\r\n this.privDisconnectDeferral.resolve();\r\n await this.privReceivingMessageQueue.drainAndDispose((pendingReceiveItem: ConnectionMessage) => {\r\n // TODO: Events for these ?\r\n // Logger.instance.onEvent(new LoggingEvent(LogType.Warning, null, `Failed to process received message. Reason: ${closeReason}, Message: ${JSON.stringify(pendingReceiveItem)}`));\r\n }, closeReason);\r\n\r\n await this.privSendMessageQueue.drainAndDispose((pendingSendItem: ISendItem) => {\r\n pendingSendItem.sendStatusDeferral.reject(closeReason);\r\n }, closeReason);\r\n }\r\n\r\n private async processSendQueue(): Promise {\r\n while (true) {\r\n const itemToSend: Promise = this.privSendMessageQueue.dequeue();\r\n const sendItem: ISendItem = await itemToSend;\r\n // indicates we are draining the queue and it came with no message;\r\n if (!sendItem) {\r\n return;\r\n }\r\n\r\n try {\r\n await this.sendRawMessage(sendItem);\r\n sendItem.sendStatusDeferral.resolve();\r\n } catch (sendError) {\r\n sendItem.sendStatusDeferral.reject(sendError);\r\n }\r\n }\r\n }\r\n\r\n private onEvent = (event: ConnectionEvent): void => {\r\n this.privConnectionEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private get isWebsocketOpen(): boolean {\r\n return this.privWebsocketClient && this.privWebsocketClient.readyState === this.privWebsocketClient.OPEN;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ArgumentNullError,\r\n ConnectionEvent,\r\n ConnectionMessage,\r\n ConnectionOpenResponse,\r\n ConnectionState,\r\n createNoDashGuid,\r\n EventSource,\r\n IConnection,\r\n IStringDictionary,\r\n IWebsocketMessageFormatter,\r\n} from \"../common/Exports\";\r\nimport { ProxyInfo } from \"./ProxyInfo\";\r\nimport { WebsocketMessageAdapter } from \"./WebsocketMessageAdapter\";\r\n\r\nexport class WebsocketConnection implements IConnection {\r\n\r\n private privUri: string;\r\n private privMessageFormatter: IWebsocketMessageFormatter;\r\n private privConnectionMessageAdapter: WebsocketMessageAdapter;\r\n private privId: string;\r\n private privIsDisposed: boolean = false;\r\n\r\n public constructor(\r\n uri: string,\r\n queryParameters: IStringDictionary,\r\n headers: IStringDictionary,\r\n messageFormatter: IWebsocketMessageFormatter,\r\n proxyInfo: ProxyInfo,\r\n enableCompression: boolean = false,\r\n connectionId?: string) {\r\n\r\n if (!uri) {\r\n throw new ArgumentNullError(\"uri\");\r\n }\r\n\r\n if (!messageFormatter) {\r\n throw new ArgumentNullError(\"messageFormatter\");\r\n }\r\n\r\n this.privMessageFormatter = messageFormatter;\r\n\r\n let queryParams = \"\";\r\n let i = 0;\r\n\r\n if (queryParameters) {\r\n for (const paramName in queryParameters) {\r\n if (paramName) {\r\n queryParams += ((i === 0) && (uri.indexOf(\"?\") === -1)) ? \"?\" : \"&\";\r\n const val = encodeURIComponent(queryParameters[paramName]);\r\n queryParams += `${paramName}=${val}`;\r\n i++;\r\n }\r\n }\r\n }\r\n\r\n if (headers) {\r\n for (const headerName in headers) {\r\n if (headerName) {\r\n queryParams += ((i === 0) && (uri.indexOf(\"?\") === -1)) ? \"?\" : \"&\";\r\n const val = encodeURIComponent(headers[headerName]);\r\n queryParams += `${headerName}=${val}`;\r\n i++;\r\n }\r\n }\r\n }\r\n\r\n this.privUri = uri + queryParams;\r\n this.privId = connectionId ? connectionId : createNoDashGuid();\r\n\r\n this.privConnectionMessageAdapter = new WebsocketMessageAdapter(\r\n this.privUri,\r\n this.id,\r\n this.privMessageFormatter,\r\n proxyInfo,\r\n headers,\r\n enableCompression);\r\n }\r\n\r\n public async dispose(): Promise {\r\n this.privIsDisposed = true;\r\n\r\n if (this.privConnectionMessageAdapter) {\r\n await this.privConnectionMessageAdapter.close();\r\n }\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n\r\n public state = (): ConnectionState => {\r\n return this.privConnectionMessageAdapter.state;\r\n }\r\n\r\n public open = (): Promise => {\r\n return this.privConnectionMessageAdapter.open();\r\n }\r\n\r\n public send = (message: ConnectionMessage): Promise => {\r\n return this.privConnectionMessageAdapter.send(message);\r\n }\r\n\r\n public read = (): Promise => {\r\n return this.privConnectionMessageAdapter.read();\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privConnectionMessageAdapter.events;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RecognizerConfig } from \"../common.speech/Exports\";\r\nimport { PropertyCollection, PropertyId } from \"../sdk/Exports\";\r\n\r\nexport class ProxyInfo {\r\n private privProxyHostName: string;\r\n private privProxyPort: number;\r\n private privProxyUserName: string;\r\n private privProxyPassword: string;\r\n\r\n private constructor(proxyHostName: string, proxyPort: number, proxyUserName: string, proxyPassword: string) {\r\n this.privProxyHostName = proxyHostName;\r\n this.privProxyPort = proxyPort;\r\n this.privProxyUserName = proxyUserName;\r\n this.privProxyPassword = proxyPassword;\r\n }\r\n\r\n public static fromParameters(parameters: PropertyCollection): ProxyInfo {\r\n return new ProxyInfo(parameters.getProperty(PropertyId.SpeechServiceConnection_ProxyHostName),\r\n parseInt(parameters.getProperty(PropertyId.SpeechServiceConnection_ProxyPort), 10),\r\n parameters.getProperty(PropertyId.SpeechServiceConnection_ProxyUserName),\r\n parameters.getProperty(PropertyId.SpeechServiceConnection_ProxyPassword));\r\n }\r\n\r\n public static fromRecognizerConfig(config: RecognizerConfig): ProxyInfo {\r\n return this.fromParameters(config.parameters);\r\n }\r\n\r\n public get HostName(): string {\r\n return this.privProxyHostName;\r\n }\r\n\r\n public get Port(): number {\r\n return this.privProxyPort;\r\n }\r\n\r\n public get UserName(): string {\r\n return this.privProxyUserName;\r\n }\r\n\r\n public get Password(): string {\r\n return this.privProxyPassword;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport class QueryParameterNames {\r\n public static BotId: string = \"botid\";\r\n public static CustomSpeechDeploymentId: string = \"cid\";\r\n public static CustomVoiceDeploymentId: string = \"deploymentId\";\r\n public static EnableAudioLogging: string = \"storeAudio\";\r\n public static EnableLanguageId: string = \"lidEnabled\";\r\n public static EnableWordLevelTimestamps: string = \"wordLevelTimestamps\";\r\n public static EndSilenceTimeoutMs: string = \"endSilenceTimeoutMs\";\r\n public static Format: string = \"format\";\r\n public static InitialSilenceTimeoutMs: string = \"initialSilenceTimeoutMs\";\r\n public static Language: string = \"language\";\r\n public static Profanity: string = \"profanity\";\r\n public static RequestBotStatusMessages: string = \"enableBotMessageStatus\";\r\n public static StableIntermediateThreshold: string = \"stableIntermediateThreshold\";\r\n public static StableTranslation: string = \"stableTranslation\";\r\n public static TestHooks: string = \"testhooks\";\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ServicePropertiesPropertyName,\r\n} from \"../common.speech/Exports\";\r\nimport { IConnection, IStringDictionary } from \"../common/Exports\";\r\nimport { OutputFormat, PropertyId } from \"../sdk/Exports\";\r\nimport { AuthInfo, IConnectionFactory, RecognitionMode, RecognizerConfig, WebsocketMessageFormatter } from \"./Exports\";\r\nimport { QueryParameterNames } from \"./QueryParameterNames\";\r\n\r\nexport abstract class ConnectionFactoryBase implements IConnectionFactory {\r\n public abstract create(\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection;\r\n\r\n protected setCommonUrlParams(\r\n config: RecognizerConfig,\r\n queryParams: IStringDictionary,\r\n endpoint: string): void {\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceConnection_EnableAudioLogging,\r\n QueryParameterNames.EnableAudioLogging,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,\r\n QueryParameterNames.EnableWordLevelTimestamps,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceResponse_ProfanityOption,\r\n QueryParameterNames.Profanity,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs,\r\n QueryParameterNames.InitialSilenceTimeoutMs,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs,\r\n QueryParameterNames.EndSilenceTimeoutMs,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceResponse_StablePartialResultThreshold,\r\n QueryParameterNames.StableIntermediateThreshold,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n const serviceProperties: IStringDictionary = JSON.parse(config.parameters.getProperty(ServicePropertiesPropertyName, \"{}\"));\r\n\r\n Object.keys(serviceProperties).forEach((value: string, num: number, array: string[]) => {\r\n queryParams[value] = serviceProperties[value];\r\n });\r\n }\r\n\r\n protected setUrlParameter(\r\n propId: PropertyId,\r\n parameterName: string,\r\n config: RecognizerConfig,\r\n queryParams: IStringDictionary,\r\n endpoint: string): void {\r\n\r\n const value: string = config.parameters.getProperty(propId, undefined);\r\n\r\n if (value && (!endpoint || endpoint.search(parameterName) === -1)) {\r\n queryParams[parameterName] = value.toLocaleLowerCase();\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionMessage,\r\n Deferred,\r\n IStringDictionary,\r\n IWebsocketMessageFormatter,\r\n MessageType,\r\n RawWebsocketMessage,\r\n} from \"../common/Exports\";\r\n\r\nconst CRLF: string = \"\\r\\n\";\r\n\r\nexport class WebsocketMessageFormatter implements IWebsocketMessageFormatter {\r\n\r\n public toConnectionMessage = (message: RawWebsocketMessage): Promise => {\r\n const deferral = new Deferred();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const textMessage: string = message.textContent;\r\n let headers: IStringDictionary = {};\r\n let body: string = null;\r\n\r\n if (textMessage) {\r\n const headerBodySplit = textMessage.split(\"\\r\\n\\r\\n\");\r\n if (headerBodySplit && headerBodySplit.length > 0) {\r\n headers = this.parseHeaders(headerBodySplit[0]);\r\n if (headerBodySplit.length > 1) {\r\n body = headerBodySplit[1];\r\n }\r\n }\r\n }\r\n\r\n deferral.resolve(new ConnectionMessage(message.messageType, body, headers, message.id));\r\n } else if (message.messageType === MessageType.Binary) {\r\n const binaryMessage: ArrayBuffer = message.binaryContent;\r\n let headers: IStringDictionary = {};\r\n let body: ArrayBuffer = null;\r\n\r\n if (!binaryMessage || binaryMessage.byteLength < 2) {\r\n throw new Error(\"Invalid binary message format. Header length missing.\");\r\n }\r\n\r\n const dataView = new DataView(binaryMessage);\r\n const headerLength = dataView.getInt16(0);\r\n\r\n if (binaryMessage.byteLength < headerLength + 2) {\r\n throw new Error(\"Invalid binary message format. Header content missing.\");\r\n }\r\n\r\n let headersString = \"\";\r\n for (let i = 0; i < headerLength; i++) {\r\n headersString += String.fromCharCode((dataView).getInt8(i + 2));\r\n }\r\n\r\n headers = this.parseHeaders(headersString);\r\n\r\n if (binaryMessage.byteLength > headerLength + 2) {\r\n body = binaryMessage.slice(2 + headerLength);\r\n }\r\n\r\n deferral.resolve(new ConnectionMessage(message.messageType, body, headers, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. Error: ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n public fromConnectionMessage = (message: ConnectionMessage): Promise => {\r\n const deferral = new Deferred();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const payload = `${this.makeHeaders(message)}${CRLF}${message.textBody ? message.textBody : \"\"}`;\r\n\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Text, payload, message.id));\r\n\r\n } else if (message.messageType === MessageType.Binary) {\r\n const headersString = this.makeHeaders(message);\r\n const content = message.binaryBody;\r\n\r\n const headerBuffer = this.stringToArrayBuffer(headersString);\r\n const headerInt8Array = new Int8Array(headerBuffer);\r\n const headerLength = headerInt8Array.byteLength;\r\n\r\n const payloadInt8Array = new Int8Array(2 + headerLength + (content ? content.byteLength : 0));\r\n payloadInt8Array[0] = ((headerLength >> 8) & 0xff);\r\n payloadInt8Array[1] = headerLength & 0xff;\r\n payloadInt8Array.set(headerInt8Array, 2);\r\n\r\n if (content) {\r\n const bodyInt8Array = new Int8Array(content);\r\n payloadInt8Array.set(bodyInt8Array, 2 + headerLength);\r\n }\r\n\r\n const payload: ArrayBuffer = payloadInt8Array.buffer;\r\n\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Binary, payload, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n private makeHeaders = (message: ConnectionMessage): string => {\r\n let headersString: string = \"\";\r\n\r\n if (message.headers) {\r\n for (const header in message.headers) {\r\n if (header) {\r\n headersString += `${header}: ${message.headers[header]}${CRLF}`;\r\n }\r\n }\r\n }\r\n\r\n return headersString;\r\n }\r\n\r\n private parseHeaders = (headersString: string): IStringDictionary => {\r\n const headers: IStringDictionary = {};\r\n\r\n if (headersString) {\r\n const headerMatches = headersString.match(/[^\\r\\n]+/g);\r\n if (headers) {\r\n for (const header of headerMatches) {\r\n if (header) {\r\n const separatorIndex = header.indexOf(\":\");\r\n const headerName = separatorIndex > 0 ? header.substr(0, separatorIndex).trim().toLowerCase() : header;\r\n const headerValue =\r\n separatorIndex > 0 && header.length > (separatorIndex + 1) ?\r\n header.substr(separatorIndex + 1).trim() :\r\n \"\";\r\n\r\n headers[headerName] = headerValue;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return headers;\r\n }\r\n\r\n private stringToArrayBuffer = (str: string): ArrayBuffer => {\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new DataView(buffer);\r\n for (let i = 0; i < str.length; i++) {\r\n view.setUint8(i, str.charCodeAt(i));\r\n }\r\n return buffer;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n ForceDictationPropertyName,\r\n OutputFormatPropertyName,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary\r\n} from \"../common/Exports\";\r\nimport {\r\n OutputFormat,\r\n PropertyId\r\n} from \"../sdk/Exports\";\r\nimport {\r\n ConnectionFactoryBase\r\n} from \"./ConnectionFactoryBase\";\r\nimport {\r\n AuthInfo,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n WebsocketMessageFormatter\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport {\r\n QueryParameterNames\r\n} from \"./QueryParameterNames\";\r\n\r\nexport class SpeechConnectionFactory extends ConnectionFactoryBase {\r\n\r\n private readonly interactiveRelativeUri: string = \"/speech/recognition/interactive/cognitiveservices/v1\";\r\n private readonly conversationRelativeUri: string = \"/speech/recognition/conversation/cognitiveservices/v1\";\r\n private readonly dictationRelativeUri: string = \"/speech/recognition/dictation/cognitiveservices/v1\";\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, undefined);\r\n const hostSuffix: string = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"wss://\" + region + \".stt.speech\" + hostSuffix);\r\n\r\n const queryParams: IStringDictionary = {};\r\n\r\n const endpointId: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_EndpointId, undefined);\r\n const language: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, undefined);\r\n\r\n if (endpointId) {\r\n if (!endpoint || endpoint.search(QueryParameterNames.CustomSpeechDeploymentId) === -1) {\r\n queryParams[QueryParameterNames.CustomSpeechDeploymentId] = endpointId;\r\n }\r\n } else if (language) {\r\n if (!endpoint || endpoint.search(QueryParameterNames.Language) === -1) {\r\n queryParams[QueryParameterNames.Language] = language;\r\n }\r\n }\r\n\r\n if (!endpoint || endpoint.search(QueryParameterNames.Format) === -1) {\r\n queryParams[QueryParameterNames.Format] = config.parameters.getProperty(OutputFormatPropertyName, OutputFormat[OutputFormat.Simple]).toLowerCase();\r\n }\r\n\r\n if (config.autoDetectSourceLanguages !== undefined) {\r\n queryParams[QueryParameterNames.EnableLanguageId] = \"true\";\r\n }\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n\r\n if (!endpoint) {\r\n switch (config.recognitionMode) {\r\n case RecognitionMode.Conversation:\r\n if (config.parameters.getProperty(ForceDictationPropertyName, \"false\") === \"true\") {\r\n endpoint = host + this.dictationRelativeUri;\r\n } else {\r\n endpoint = host + this.conversationRelativeUri;\r\n }\r\n break;\r\n case RecognitionMode.Dictation:\r\n endpoint = host + this.dictationRelativeUri;\r\n break;\r\n default:\r\n endpoint = host + this.interactiveRelativeUri; // default is interactive\r\n break;\r\n }\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IPrimaryLanguage } from \"./SimpleSpeechPhrase\";\r\n\r\n// speech.hypothesis\r\nexport interface ISpeechHypothesis {\r\n Text: string;\r\n Offset: number;\r\n Duration: number;\r\n PrimaryLanguage?: IPrimaryLanguage;\r\n SpeakerId?: string;\r\n}\r\n\r\nexport class SpeechHypothesis implements ISpeechHypothesis {\r\n private privSpeechHypothesis: ISpeechHypothesis;\r\n\r\n private constructor(json: string) {\r\n this.privSpeechHypothesis = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SpeechHypothesis {\r\n return new SpeechHypothesis(json);\r\n }\r\n\r\n public get Text(): string {\r\n return this.privSpeechHypothesis.Text;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privSpeechHypothesis.Offset;\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privSpeechHypothesis.Duration;\r\n }\r\n\r\n public get Language(): string {\r\n return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Language;\r\n }\r\n\r\n public get LanguageDetectionConfidence(): string {\r\n return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Confidence;\r\n }\r\n\r\n public get SpeakerId(): string {\r\n return this.privSpeechHypothesis.SpeakerId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * @class SynthesisStatus\r\n * @private\r\n */\r\nexport enum SynthesisStatus {\r\n /**\r\n * The response contains valid audio data.\r\n * @member SynthesisStatus.Success\r\n */\r\n Success,\r\n\r\n /**\r\n * Indicates the end of audio data. No valid audio data is included in the message.\r\n * @member SynthesisStatus.SynthesisEnd\r\n */\r\n SynthesisEnd,\r\n\r\n /**\r\n * Indicates an error occurred during synthesis data processing.\r\n * @member SynthesisStatus.Error\r\n */\r\n Error,\r\n}\r\n\r\nexport enum RecognitionStatus {\r\n Success,\r\n NoMatch,\r\n InitialSilenceTimeout,\r\n BabbleTimeout,\r\n Error,\r\n EndOfDictation,\r\n TooManyRequests,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RecognitionStatus } from \"../Exports\";\r\n\r\n// speech.phrase\r\nexport interface ISimpleSpeechPhrase {\r\n RecognitionStatus: RecognitionStatus;\r\n DisplayText: string;\r\n Offset?: number;\r\n Duration?: number;\r\n PrimaryLanguage?: IPrimaryLanguage;\r\n SpeakerId?: string;\r\n}\r\n\r\nexport interface IPrimaryLanguage {\r\n Language: string;\r\n Confidence: string;\r\n}\r\n\r\nexport class SimpleSpeechPhrase implements ISimpleSpeechPhrase {\r\n private privSimpleSpeechPhrase: ISimpleSpeechPhrase;\r\n\r\n private constructor(json: string) {\r\n this.privSimpleSpeechPhrase = JSON.parse(json);\r\n this.privSimpleSpeechPhrase.RecognitionStatus = (RecognitionStatus as any)[this.privSimpleSpeechPhrase.RecognitionStatus];\r\n }\r\n\r\n public static fromJSON(json: string): SimpleSpeechPhrase {\r\n return new SimpleSpeechPhrase(json);\r\n }\r\n\r\n public get RecognitionStatus(): RecognitionStatus {\r\n return this.privSimpleSpeechPhrase.RecognitionStatus;\r\n }\r\n\r\n public get DisplayText(): string {\r\n return this.privSimpleSpeechPhrase.DisplayText;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privSimpleSpeechPhrase.Offset;\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privSimpleSpeechPhrase.Duration;\r\n }\r\n\r\n public get Language(): string {\r\n return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Language;\r\n }\r\n\r\n public get LanguageDetectionConfidence(): string {\r\n return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Confidence;\r\n }\r\n\r\n public get SpeakerId(): string {\r\n return this.privSimpleSpeechPhrase.SpeakerId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n ResultReason\r\n} from \"../sdk/Exports\";\r\nimport { RecognitionStatus } from \"./Exports\";\r\n\r\nexport class EnumTranslation {\r\n public static implTranslateRecognitionResult(recognitionStatus: RecognitionStatus): ResultReason {\r\n let reason = ResultReason.Canceled;\r\n switch (recognitionStatus) {\r\n case RecognitionStatus.Success:\r\n reason = ResultReason.RecognizedSpeech;\r\n break;\r\n case RecognitionStatus.NoMatch:\r\n case RecognitionStatus.InitialSilenceTimeout:\r\n case RecognitionStatus.BabbleTimeout:\r\n case RecognitionStatus.EndOfDictation:\r\n reason = ResultReason.NoMatch;\r\n break;\r\n case RecognitionStatus.Error:\r\n default:\r\n reason = ResultReason.Canceled;\r\n break;\r\n }\r\n return reason;\r\n }\r\n\r\n public static implTranslateCancelResult(recognitionStatus: RecognitionStatus): CancellationReason {\r\n let reason = CancellationReason.EndOfStream;\r\n switch (recognitionStatus) {\r\n case RecognitionStatus.Success:\r\n case RecognitionStatus.EndOfDictation:\r\n case RecognitionStatus.NoMatch:\r\n reason = CancellationReason.EndOfStream;\r\n break;\r\n case RecognitionStatus.InitialSilenceTimeout:\r\n case RecognitionStatus.BabbleTimeout:\r\n case RecognitionStatus.Error:\r\n default:\r\n reason = CancellationReason.Error;\r\n break;\r\n }\r\n return reason;\r\n }\r\n\r\n public static implTranslateCancelErrorCode(recognitionStatus: RecognitionStatus): CancellationErrorCode {\r\n let reason: CancellationErrorCode = CancellationErrorCode.NoError;\r\n switch (recognitionStatus) {\r\n case RecognitionStatus.Error:\r\n reason = CancellationErrorCode.ServiceError;\r\n break;\r\n case RecognitionStatus.TooManyRequests:\r\n reason = CancellationErrorCode.TooManyRequests;\r\n break;\r\n default:\r\n reason = CancellationErrorCode.NoError;\r\n break;\r\n }\r\n\r\n return reason;\r\n\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IPrimaryLanguage, RecognitionStatus } from \"../Exports\";\r\n\r\n// speech.phrase for detailed\r\nexport interface IDetailedSpeechPhrase {\r\n RecognitionStatus: RecognitionStatus;\r\n NBest: IPhrase[];\r\n Duration?: number;\r\n Offset?: number;\r\n PrimaryLanguage?: IPrimaryLanguage;\r\n}\r\n\r\nexport interface IPhrase {\r\n Confidence?: number;\r\n Lexical: string;\r\n ITN: string;\r\n MaskedITN: string;\r\n Display: string;\r\n}\r\n\r\nexport class DetailedSpeechPhrase implements IDetailedSpeechPhrase {\r\n private privDetailedSpeechPhrase: IDetailedSpeechPhrase;\r\n\r\n private constructor(json: string) {\r\n this.privDetailedSpeechPhrase = JSON.parse(json);\r\n this.privDetailedSpeechPhrase.RecognitionStatus = (RecognitionStatus as any)[this.privDetailedSpeechPhrase.RecognitionStatus];\r\n }\r\n\r\n public static fromJSON(json: string): DetailedSpeechPhrase {\r\n return new DetailedSpeechPhrase(json);\r\n }\r\n\r\n public get RecognitionStatus(): RecognitionStatus {\r\n return this.privDetailedSpeechPhrase.RecognitionStatus;\r\n }\r\n public get NBest(): IPhrase[] {\r\n return this.privDetailedSpeechPhrase.NBest;\r\n }\r\n public get Duration(): number {\r\n return this.privDetailedSpeechPhrase.Duration;\r\n }\r\n public get Offset(): number {\r\n return this.privDetailedSpeechPhrase.Offset;\r\n }\r\n public get Language(): string {\r\n return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Language;\r\n }\r\n public get LanguageDetectionConfidence(): string {\r\n return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Confidence;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IAudioSource } from \"../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n OutputFormat,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechRecognitionCanceledEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult,\r\n SpeechRecognizer,\r\n} from \"../sdk/Exports\";\r\nimport {\r\n CancellationErrorCodePropertyName,\r\n DetailedSpeechPhrase,\r\n EnumTranslation,\r\n OutputFormatPropertyName,\r\n RecognitionStatus,\r\n ServiceRecognizerBase,\r\n SimpleSpeechPhrase,\r\n SpeechHypothesis,\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class SpeechServiceRecognizer extends ServiceRecognizerBase {\r\n\r\n private privSpeechRecognizer: SpeechRecognizer;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n speechRecognizer: SpeechRecognizer) {\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer);\r\n this.privSpeechRecognizer = speechRecognizer;\r\n if (recognizerConfig.autoDetectSourceLanguages !== undefined) {\r\n const sourceLanguages: string[] = recognizerConfig.autoDetectSourceLanguages.split(\",\");\r\n this.privSpeechContext.setSection(\"languageId\", {\r\n languages: sourceLanguages,\r\n onSuccess: { action: \"Recognize\" },\r\n onUnknown: { action: \"None\" }\r\n });\r\n this.privSpeechContext.setSection(\"phraseOutput\", {\r\n interimResults: {\r\n resultType: \"Auto\"\r\n },\r\n phraseResults: {\r\n resultType: \"Always\"\r\n }\r\n });\r\n }\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n let result: SpeechRecognitionResult;\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n let processed: boolean = false;\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"speech.hypothesis\":\r\n case \"speech.fragment\":\r\n const hypothesis: SpeechHypothesis = SpeechHypothesis.fromJSON(connectionMessage.textBody);\r\n const offset: number = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n ResultReason.RecognizingSpeech,\r\n hypothesis.Text,\r\n hypothesis.Duration,\r\n offset,\r\n hypothesis.Language,\r\n hypothesis.LanguageDetectionConfidence,\r\n undefined, // Speaker Id\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n this.privRequestSession.onHypothesis(offset);\r\n\r\n const ev = new SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privSpeechRecognizer.recognizing) {\r\n try {\r\n this.privSpeechRecognizer.recognizing(this.privSpeechRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.phrase\":\r\n const simple: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n const resultReason: ResultReason = EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus);\r\n\r\n this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + simple.Offset + simple.Duration);\r\n\r\n if (ResultReason.Canceled === resultReason) {\r\n const cancelReason: CancellationReason = EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);\r\n\r\n await this.cancelRecognitionLocal(\r\n cancelReason,\r\n EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus),\r\n undefined);\r\n\r\n } else {\r\n if (!(this.privRequestSession.isSpeechEnded && resultReason === ResultReason.NoMatch && simple.RecognitionStatus !== RecognitionStatus.InitialSilenceTimeout)) {\r\n if (this.privRecognizerConfig.parameters.getProperty(OutputFormatPropertyName) === OutputFormat[OutputFormat.Simple]) {\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n simple.DisplayText,\r\n simple.Duration,\r\n simple.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n simple.Language,\r\n simple.LanguageDetectionConfidence,\r\n undefined, // Speaker Id\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n } else {\r\n const detailed: DetailedSpeechPhrase = DetailedSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n detailed.RecognitionStatus === RecognitionStatus.Success ? detailed.NBest[0].Display : undefined,\r\n detailed.Duration,\r\n detailed.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n detailed.Language,\r\n detailed.LanguageDetectionConfidence,\r\n undefined, // Speaker Id\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n }\r\n\r\n const event: SpeechRecognitionEventArgs = new SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privSpeechRecognizer.recognized) {\r\n try {\r\n this.privSpeechRecognizer.recognized(this.privSpeechRecognizer, event);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n }\r\n processed = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n if (!!this.privSpeechRecognizer.canceled) {\r\n const cancelEvent: SpeechRecognitionCanceledEventArgs = new SpeechRecognitionCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n sessionId);\r\n try {\r\n this.privSpeechRecognizer.canceled(this.privSpeechRecognizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: SpeechRecognitionResult = new SpeechRecognitionResult(\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Duration\r\n undefined, // Offset\r\n undefined, // Language\r\n undefined, // Language Detection Confidence\r\n undefined, // Speaker Id\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n this.privSuccessCallback = undefined;\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IAuthentication,\r\n IConnectionFactory,\r\n OutputFormatPropertyName,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechConnectionFactory,\r\n SpeechServiceConfig,\r\n SpeechServiceRecognizer,\r\n} from \"../common.speech/Exports\";\r\nimport { marshalPromiseToCallbacks } from \"../common/Exports\";\r\nimport { AudioConfigImpl } from \"./Audio/AudioConfig\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n AudioConfig,\r\n AutoDetectSourceLanguageConfig,\r\n KeywordRecognitionModel,\r\n OutputFormat,\r\n PropertyCollection,\r\n PropertyId,\r\n Recognizer,\r\n SpeechRecognitionCanceledEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult,\r\n} from \"./Exports\";\r\nimport { SpeechConfig, SpeechConfigImpl } from \"./SpeechConfig\";\r\n\r\n/**\r\n * Performs speech recognition from microphone, file, or other audio input streams, and gets transcribed text as result.\r\n * @class SpeechRecognizer\r\n */\r\nexport class SpeechRecognizer extends Recognizer {\r\n private privDisposedRecognizer: boolean;\r\n\r\n /**\r\n * SpeechRecognizer constructor.\r\n * @constructor\r\n * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer\r\n * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer\r\n */\r\n public constructor(speechConfig: SpeechConfig, audioConfig?: AudioConfig) {\r\n const speechConfigImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;\r\n Contracts.throwIfNull(speechConfigImpl, \"speechConfig\");\r\n\r\n Contracts.throwIfNullOrWhitespace(\r\n speechConfigImpl.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage),\r\n PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);\r\n\r\n super(audioConfig, speechConfigImpl.properties, new SpeechConnectionFactory());\r\n this.privDisposedRecognizer = false;\r\n }\r\n\r\n /**\r\n * SpeechRecognizer constructor.\r\n * @constructor\r\n * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer\r\n * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the recognizer\r\n * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer\r\n */\r\n public static FromConfig(speechConfig: SpeechConfig, autoDetectSourceLanguageConfig: AutoDetectSourceLanguageConfig, audioConfig?: AudioConfig): SpeechRecognizer {\r\n const speechConfigImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;\r\n autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties);\r\n const recognizer = new SpeechRecognizer(speechConfig, audioConfig);\r\n return recognizer;\r\n }\r\n\r\n /**\r\n * The event recognizing signals that an intermediate recognition result is received.\r\n * @member SpeechRecognizer.prototype.recognizing\r\n * @function\r\n * @public\r\n */\r\n public recognizing: (sender: Recognizer, event: SpeechRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event recognized signals that a final recognition result is received.\r\n * @member SpeechRecognizer.prototype.recognized\r\n * @function\r\n * @public\r\n */\r\n public recognized: (sender: Recognizer, event: SpeechRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event canceled signals that an error occurred during recognition.\r\n * @member SpeechRecognizer.prototype.canceled\r\n * @function\r\n * @public\r\n */\r\n public canceled: (sender: Recognizer, event: SpeechRecognitionCanceledEventArgs) => void;\r\n\r\n /**\r\n * Gets the endpoint id of a customized speech model that is used for speech recognition.\r\n * @member SpeechRecognizer.prototype.endpointId\r\n * @function\r\n * @public\r\n * @returns {string} the endpoint id of a customized speech model that is used for speech recognition.\r\n */\r\n public get endpointId(): string {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_EndpointId, \"00000000-0000-0000-0000-000000000000\");\r\n }\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member SpeechRecognizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Gets/Sets the authorization token used to communicate with the service.\r\n * @member SpeechRecognizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} token - Authorization token.\r\n */\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n /**\r\n * Gets the spoken language of recognition.\r\n * @member SpeechRecognizer.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @returns {string} The spoken language of recognition.\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);\r\n }\r\n\r\n /**\r\n * Gets the output format of recognition.\r\n * @member SpeechRecognizer.prototype.outputFormat\r\n * @function\r\n * @public\r\n * @returns {OutputFormat} The output format of recognition.\r\n */\r\n public get outputFormat(): OutputFormat {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n\r\n if (this.properties.getProperty(OutputFormatPropertyName, OutputFormat[OutputFormat.Simple]) === OutputFormat[OutputFormat.Simple]) {\r\n return OutputFormat.Simple;\r\n } else {\r\n return OutputFormat.Detailed;\r\n }\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this SpeechRecognizer.\r\n * @member SpeechRecognizer.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechRecognizer.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * Starts speech recognition, and stops after the first utterance is recognized.\r\n * The task returns the recognition text as result.\r\n * Note: RecognizeOnceAsync() returns when the first utterance has been recognized,\r\n * so it is suitable only for single shot recognition\r\n * like command or query. For long-running recognition, use StartContinuousRecognitionAsync() instead.\r\n * @member SpeechRecognizer.prototype.recognizeOnceAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback that received the SpeechRecognitionResult.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public recognizeOnceAsync(cb?: (e: SpeechRecognitionResult) => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(RecognitionMode.Interactive), cb, err);\r\n }\r\n\r\n /**\r\n * Starts speech recognition, until stopContinuousRecognitionAsync() is called.\r\n * User must subscribe to events to receive recognition results.\r\n * @member SpeechRecognizer.prototype.startContinuousRecognitionAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback invoked once the recognition has started.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public startContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(RecognitionMode.Conversation), cb, err);\r\n }\r\n\r\n /**\r\n * Stops continuous speech recognition.\r\n * @member SpeechRecognizer.prototype.stopContinuousRecognitionAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback invoked once the recognition has stopped.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public stopContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);\r\n }\r\n\r\n /**\r\n * Starts speech recognition with keyword spotting, until\r\n * stopKeywordRecognitionAsync() is called.\r\n * User must subscribe to events to receive recognition results.\r\n * Note: Key word spotting functionality is only available on the\r\n * Speech Devices SDK. This functionality is currently not included in the SDK itself.\r\n * @member SpeechRecognizer.prototype.startKeywordRecognitionAsync\r\n * @function\r\n * @public\r\n * @param {KeywordRecognitionModel} model The keyword recognition model that\r\n * specifies the keyword to be recognized.\r\n * @param cb - Callback invoked once the recognition has started.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public startKeywordRecognitionAsync(model: KeywordRecognitionModel, cb?: () => void, err?: (e: string) => void): void {\r\n Contracts.throwIfNull(model, \"model\");\r\n\r\n if (!!err) {\r\n err(\"Not yet implemented.\");\r\n }\r\n }\r\n\r\n /**\r\n * Stops continuous speech recognition.\r\n * Note: Key word spotting functionality is only available on the\r\n * Speech Devices SDK. This functionality is currently not included in the SDK itself.\r\n * @member SpeechRecognizer.prototype.stopKeywordRecognitionAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback invoked once the recognition has stopped.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public stopKeywordRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }\r\n\r\n /**\r\n * closes all external resources held by an instance of this class.\r\n * @member SpeechRecognizer.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, errorCb?: (error: string) => void): void {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);\r\n }\r\n\r\n /**\r\n * Disposes any resources held by the object.\r\n * @member SpeechRecognizer.prototype.dispose\r\n * @function\r\n * @public\r\n * @param {boolean} disposing - true if disposing the object.\r\n */\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privDisposedRecognizer) {\r\n return;\r\n }\r\n\r\n if (disposing) {\r\n this.privDisposedRecognizer = true;\r\n await this.implRecognizerStop();\r\n }\r\n\r\n await super.dispose(disposing);\r\n }\r\n\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(\r\n speechConfig,\r\n this.properties);\r\n }\r\n\r\n protected createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n const configImpl: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n return new SpeechServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary\r\n} from \"../common/Exports\";\r\nimport {\r\n PropertyId\r\n} from \"../sdk/Exports\";\r\nimport {\r\n ConnectionFactoryBase\r\n} from \"./ConnectionFactoryBase\";\r\nimport {\r\n AuthInfo,\r\n RecognizerConfig,\r\n WebsocketMessageFormatter,\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\n\r\nexport class IntentConnectionFactory extends ConnectionFactoryBase {\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint);\r\n if (!endpoint) {\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_IntentRegion);\r\n const hostSuffix = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"wss://\" + region + \".sr.speech\" + hostSuffix);\r\n endpoint = host + \"/speech/recognition/interactive/cognitiveservices/v1\";\r\n }\r\n\r\n const queryParams: IStringDictionary = {\r\n format: \"simple\",\r\n language: config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage),\r\n };\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n\r\n private getSpeechRegionFromIntentRegion(intentRegion: string): string {\r\n switch (intentRegion) {\r\n case \"West US\":\r\n case \"US West\":\r\n case \"westus\":\r\n return \"uswest\";\r\n case \"West US 2\":\r\n case \"US West 2\":\r\n case \"westus2\":\r\n return \"uswest2\";\r\n case \"South Central US\":\r\n case \"US South Central\":\r\n case \"southcentralus\":\r\n return \"ussouthcentral\";\r\n case \"West Central US\":\r\n case \"US West Central\":\r\n case \"westcentralus\":\r\n return \"uswestcentral\";\r\n case \"East US\":\r\n case \"US East\":\r\n case \"eastus\":\r\n return \"useast\";\r\n case \"East US 2\":\r\n case \"US East 2\":\r\n case \"eastus2\":\r\n return \"useast2\";\r\n case \"West Europe\":\r\n case \"Europe West\":\r\n case \"westeurope\":\r\n return \"europewest\";\r\n case \"North Europe\":\r\n case \"Europe North\":\r\n case \"northeurope\":\r\n return \"europenorth\";\r\n case \"Brazil South\":\r\n case \"South Brazil\":\r\n case \"southbrazil\":\r\n return \"brazilsouth\";\r\n case \"Australia East\":\r\n case \"East Australia\":\r\n case \"eastaustralia\":\r\n return \"australiaeast\";\r\n case \"Southeast Asia\":\r\n case \"Asia Southeast\":\r\n case \"southeastasia\":\r\n return \"asiasoutheast\";\r\n case \"East Asia\":\r\n case \"Asia East\":\r\n case \"eastasia\":\r\n return \"asiaeast\";\r\n default:\r\n return intentRegion;\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { LanguageUnderstandingModelImpl } from \"../sdk/LanguageUnderstandingModel\";\r\n\r\n/**\r\n * @class AddedLmIntent\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class AddedLmIntent {\r\n public modelImpl: LanguageUnderstandingModelImpl;\r\n public intentName: string;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param modelImpl - The model.\r\n * @param intentName - The intent name.\r\n */\r\n public constructor(modelImpl: LanguageUnderstandingModelImpl, intentName: string) {\r\n this.modelImpl = modelImpl;\r\n this.intentName = intentName;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { CancellationEventArgs } from \"./CancellationEventArgs\";\r\nimport { CancellationErrorCode, CancellationReason, IntentRecognitionEventArgs, IntentRecognitionResult } from \"./Exports\";\r\n\r\n/**\r\n * Define payload of intent recognition canceled result events.\r\n * @class IntentRecognitionCanceledEventArgs\r\n */\r\nexport class IntentRecognitionCanceledEventArgs extends IntentRecognitionEventArgs implements CancellationEventArgs {\r\n private privReason: CancellationReason;\r\n private privErrorDetails: string;\r\n private privErrorCode: CancellationErrorCode;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {CancellationReason} result - The result of the intent recognition.\r\n * @param {string} offset - The offset.\r\n * @param {IntentRecognitionResult} sessionId - The session id.\r\n */\r\n public constructor(\r\n reason: CancellationReason,\r\n errorDetails: string,\r\n errorCode: CancellationErrorCode,\r\n result?: IntentRecognitionResult,\r\n offset?: number,\r\n sessionId?: string) {\r\n super(result, offset, sessionId);\r\n\r\n this.privReason = reason;\r\n this.privErrorDetails = errorDetails;\r\n this.privErrorCode = errorCode;\r\n }\r\n\r\n /**\r\n * The reason the recognition was canceled.\r\n * @member IntentRecognitionCanceledEventArgs.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {CancellationReason} Specifies the reason canceled.\r\n */\r\n public get reason(): CancellationReason {\r\n return this.privReason;\r\n }\r\n\r\n /**\r\n * The error code in case of an unsuccessful recognition.\r\n * Added in version 1.1.0.\r\n * @return An error code that represents the error reason.\r\n */\r\n public get errorCode(): CancellationErrorCode {\r\n return this.privErrorCode;\r\n }\r\n\r\n /**\r\n * In case of an unsuccessful recognition, provides details of the occurred error.\r\n * @member IntentRecognitionCanceledEventArgs.prototype.errorDetails\r\n * @function\r\n * @public\r\n * @returns {string} A String that represents the error details.\r\n */\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// response\r\n\r\nexport interface IIntentResponse {\r\n query: string;\r\n topScoringIntent: ISingleIntent;\r\n entities: IIntentEntity[];\r\n}\r\n\r\nexport interface IIntentEntity {\r\n entity: string;\r\n type: string;\r\n startIndex: number;\r\n endIndex: number;\r\n score: number;\r\n}\r\n\r\nexport interface ISingleIntent {\r\n intent: string;\r\n score: number;\r\n}\r\n\r\nexport class IntentResponse implements IIntentResponse {\r\n private privIntentResponse: IIntentResponse;\r\n\r\n private constructor(json: string) {\r\n this.privIntentResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): IntentResponse {\r\n return new IntentResponse(json);\r\n }\r\n\r\n public get query(): string {\r\n return this.privIntentResponse.query;\r\n }\r\n\r\n public get topScoringIntent(): ISingleIntent {\r\n return this.privIntentResponse.topScoringIntent;\r\n }\r\n\r\n public get entities(): IIntentEntity[] {\r\n return this.privIntentResponse.entities;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IAudioSource,\r\n MessageType,\r\n} from \"../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n IntentRecognitionCanceledEventArgs,\r\n IntentRecognitionEventArgs,\r\n IntentRecognitionResult,\r\n IntentRecognizer,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechRecognitionResult,\r\n} from \"../sdk/Exports\";\r\nimport {\r\n AddedLmIntent,\r\n CancellationErrorCodePropertyName,\r\n EnumTranslation,\r\n IntentResponse,\r\n ServiceRecognizerBase,\r\n SimpleSpeechPhrase,\r\n SpeechHypothesis,\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class IntentServiceRecognizer extends ServiceRecognizerBase {\r\n private privIntentRecognizer: IntentRecognizer;\r\n private privAddedLmIntents: { [id: string]: AddedLmIntent; };\r\n private privIntentDataSent: boolean;\r\n private privUmbrellaIntent: AddedLmIntent;\r\n private privPendingIntentArgs: IntentRecognitionEventArgs;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n recognizer: IntentRecognizer) {\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, recognizer);\r\n this.privIntentRecognizer = recognizer;\r\n this.privIntentDataSent = false;\r\n }\r\n\r\n public setIntents(addedIntents: { [id: string]: AddedLmIntent; }, umbrellaIntent: AddedLmIntent): void {\r\n this.privAddedLmIntents = addedIntents;\r\n this.privUmbrellaIntent = umbrellaIntent;\r\n this.privIntentDataSent = true;\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n let result: IntentRecognitionResult;\r\n let ev: IntentRecognitionEventArgs;\r\n let processed: boolean = false;\r\n\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n if (connectionMessage.messageType === MessageType.Text) {\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n }\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"speech.hypothesis\":\r\n const speechHypothesis: SpeechHypothesis = SpeechHypothesis.fromJSON(connectionMessage.textBody);\r\n\r\n result = new IntentRecognitionResult(\r\n undefined,\r\n this.privRequestSession.requestId,\r\n ResultReason.RecognizingIntent,\r\n speechHypothesis.Text,\r\n speechHypothesis.Duration,\r\n speechHypothesis.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n speechHypothesis.Language,\r\n speechHypothesis.LanguageDetectionConfidence,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n this.privRequestSession.onHypothesis(result.offset);\r\n\r\n ev = new IntentRecognitionEventArgs(result, speechHypothesis.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privIntentRecognizer.recognizing) {\r\n try {\r\n this.privIntentRecognizer.recognizing(this.privIntentRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.phrase\":\r\n const simple: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n result = new IntentRecognitionResult(\r\n undefined,\r\n this.privRequestSession.requestId,\r\n EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus),\r\n simple.DisplayText,\r\n simple.Duration,\r\n simple.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n simple.Language,\r\n simple.LanguageDetectionConfidence,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n ev = new IntentRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);\r\n\r\n const sendEvent: () => void = () => {\r\n if (!!this.privIntentRecognizer.recognized) {\r\n try {\r\n this.privIntentRecognizer.recognized(this.privIntentRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n };\r\n\r\n // If intent data was sent, the terminal result for this recognizer is an intent being found.\r\n // If no intent data was sent, the terminal event is speech recognition being successful.\r\n if (false === this.privIntentDataSent || ResultReason.NoMatch === ev.result.reason) {\r\n // Advance the buffers.\r\n this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration);\r\n sendEvent();\r\n } else {\r\n // Squirrel away the args, when the response event arrives it will build upon them\r\n // and then return\r\n this.privPendingIntentArgs = ev;\r\n }\r\n processed = true;\r\n break;\r\n case \"response\":\r\n // Response from LUIS\r\n ev = this.privPendingIntentArgs;\r\n this.privPendingIntentArgs = undefined;\r\n\r\n if (undefined === ev) {\r\n if (\"\" === connectionMessage.textBody) {\r\n // This condition happens if there is nothing but silence in the\r\n // audio sent to the service.\r\n return;\r\n }\r\n\r\n // Odd... Not sure this can happen\r\n ev = new IntentRecognitionEventArgs(new IntentRecognitionResult(), 0 /*TODO*/, this.privRequestSession.sessionId);\r\n }\r\n\r\n const intentResponse: IntentResponse = IntentResponse.fromJSON(connectionMessage.textBody);\r\n\r\n // If LUIS didn't return anything, send the existing event, else\r\n // modify it to show the match.\r\n // See if the intent found is in the list of intents asked for.\r\n let addedIntent: AddedLmIntent = this.privAddedLmIntents[intentResponse.topScoringIntent.intent];\r\n\r\n if (this.privUmbrellaIntent !== undefined) {\r\n addedIntent = this.privUmbrellaIntent;\r\n }\r\n\r\n if (null !== intentResponse && addedIntent !== undefined) {\r\n const intentId = addedIntent.intentName === undefined ? intentResponse.topScoringIntent.intent : addedIntent.intentName;\r\n let reason = ev.result.reason;\r\n\r\n if (undefined !== intentId) {\r\n reason = ResultReason.RecognizedIntent;\r\n }\r\n\r\n // make sure, properties is set.\r\n const properties = (undefined !== ev.result.properties) ?\r\n ev.result.properties : new PropertyCollection();\r\n\r\n properties.setProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult, connectionMessage.textBody);\r\n\r\n ev = new IntentRecognitionEventArgs(\r\n new IntentRecognitionResult(\r\n intentId,\r\n ev.result.resultId,\r\n reason,\r\n ev.result.text,\r\n ev.result.duration,\r\n ev.result.offset,\r\n undefined,\r\n undefined,\r\n ev.result.errorDetails,\r\n ev.result.json,\r\n properties),\r\n ev.offset,\r\n ev.sessionId);\r\n }\r\n this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration);\r\n\r\n if (!!this.privIntentRecognizer.recognized) {\r\n try {\r\n this.privIntentRecognizer.recognized(this.privIntentRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(ev.result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n processed = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n if (!!this.privIntentRecognizer.canceled) {\r\n\r\n const cancelEvent: IntentRecognitionCanceledEventArgs = new IntentRecognitionCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n undefined,\r\n sessionId);\r\n try {\r\n this.privIntentRecognizer.canceled(this.privIntentRecognizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: IntentRecognitionResult = new IntentRecognitionResult(\r\n undefined, // Intent Id\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Duration\r\n undefined, // Offset\r\n undefined, // Language\r\n undefined, // LanguageDetectionConfidence\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n this.privSuccessCallback = undefined;\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Output format\r\n * @class VoiceProfileType\r\n */\r\nexport enum VoiceProfileType {\r\n\r\n /**\r\n * Text independent speaker identification\r\n * @member VoiceProfileType.TextIndependentIdentification\r\n */\r\n TextIndependentIdentification,\r\n\r\n /**\r\n * Text dependent speaker verification\r\n * @member VoiceProfileType.TextDependentVerification\r\n */\r\n TextDependentVerification,\r\n\r\n /**\r\n * Text independent speaker verification\r\n * @member VoiceProfileType.TextIndependentVerification\r\n */\r\n TextIndependentVerification,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines translation status.\r\n * @class TranslationStatus\r\n */\r\nexport enum TranslationStatus {\r\n /**\r\n * @member TranslationStatus.Success\r\n */\r\n Success = 0,\r\n\r\n /**\r\n * @member TranslationStatus.Error\r\n */\r\n Error,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n AddedLmIntent,\r\n IAuthentication,\r\n IConnectionFactory,\r\n IntentConnectionFactory,\r\n IntentServiceRecognizer,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig,\r\n} from \"../common.speech/Exports\";\r\nimport { marshalPromiseToCallbacks } from \"../common/Exports\";\r\nimport { AudioConfigImpl } from \"./Audio/AudioConfig\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n AudioConfig,\r\n IntentRecognitionCanceledEventArgs,\r\n IntentRecognitionEventArgs,\r\n IntentRecognitionResult,\r\n KeywordRecognitionModel,\r\n LanguageUnderstandingModel,\r\n PropertyCollection,\r\n PropertyId,\r\n Recognizer,\r\n SpeechConfig,\r\n} from \"./Exports\";\r\nimport { LanguageUnderstandingModelImpl } from \"./LanguageUnderstandingModel\";\r\nimport { SpeechConfigImpl } from \"./SpeechConfig\";\r\n\r\n/**\r\n * Intent recognizer.\r\n * @class\r\n */\r\nexport class IntentRecognizer extends Recognizer {\r\n private privDisposedIntentRecognizer: boolean;\r\n private privAddedIntents: string[][];\r\n private privAddedLmIntents: { [id: string]: AddedLmIntent; };\r\n private privUmbrellaIntent: AddedLmIntent;\r\n\r\n /**\r\n * Initializes an instance of the IntentRecognizer.\r\n * @constructor\r\n * @param {SpeechConfig} speechConfig - The set of configuration properties.\r\n * @param {AudioConfig} audioConfig - An optional audio input config associated with the recognizer\r\n */\r\n public constructor(speechConfig: SpeechConfig, audioConfig?: AudioConfig) {\r\n Contracts.throwIfNullOrUndefined(speechConfig, \"speechConfig\");\r\n const configImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;\r\n Contracts.throwIfNullOrUndefined(configImpl, \"speechConfig\");\r\n\r\n super(audioConfig, configImpl.properties, new IntentConnectionFactory());\r\n this.privAddedIntents = [];\r\n this.privAddedLmIntents = {};\r\n\r\n this.privDisposedIntentRecognizer = false;\r\n this.privProperties = configImpl.properties;\r\n\r\n Contracts.throwIfNullOrWhitespace(this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage), PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);\r\n }\r\n\r\n /**\r\n * The event recognizing signals that an intermediate recognition result is received.\r\n * @member IntentRecognizer.prototype.recognizing\r\n * @function\r\n * @public\r\n */\r\n public recognizing: (sender: IntentRecognizer, event: IntentRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event recognized signals that a final recognition result is received.\r\n * @member IntentRecognizer.prototype.recognized\r\n * @function\r\n * @public\r\n */\r\n public recognized: (sender: IntentRecognizer, event: IntentRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event canceled signals that an error occurred during recognition.\r\n * @member IntentRecognizer.prototype.canceled\r\n * @function\r\n * @public\r\n */\r\n public canceled: (sender: IntentRecognizer, event: IntentRecognitionCanceledEventArgs) => void;\r\n\r\n /**\r\n * Gets the spoken language of recognition.\r\n * @member IntentRecognizer.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @returns {string} the spoken language of recognition.\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);\r\n }\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member IntentRecognizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Gets/Sets the authorization token used to communicate with the service.\r\n * Note: Please use a token derived from your LanguageUnderstanding subscription key for the Intent recognizer.\r\n * @member IntentRecognizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} value - Authorization token.\r\n */\r\n public set authorizationToken(value: string) {\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, value);\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this IntentRecognizer.\r\n * @member IntentRecognizer.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their\r\n * values defined for this IntentRecognizer.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * Starts intent recognition, and stops after the first utterance is recognized.\r\n * The task returns the recognition text and intent as result.\r\n * Note: RecognizeOnceAsync() returns when the first utterance has been recognized,\r\n * so it is suitable only for single shot recognition like command or query.\r\n * For long-running recognition, use StartContinuousRecognitionAsync() instead.\r\n * @member IntentRecognizer.prototype.recognizeOnceAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback that received the recognition has finished with an IntentRecognitionResult.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public recognizeOnceAsync(cb?: (e: IntentRecognitionResult) => void, err?: (e: string) => void): void {\r\n Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);\r\n\r\n if (Object.keys(this.privAddedLmIntents).length !== 0 || undefined !== this.privUmbrellaIntent) {\r\n const context: IIntentContext = this.buildSpeechContext();\r\n\r\n this.privReco.speechContext.setSection(\"intent\", context.Intent);\r\n this.privReco.dynamicGrammar.addReferenceGrammar(context.ReferenceGrammars);\r\n\r\n const intentReco: IntentServiceRecognizer = this.privReco as IntentServiceRecognizer;\r\n intentReco.setIntents(this.privAddedLmIntents, this.privUmbrellaIntent);\r\n }\r\n\r\n marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(RecognitionMode.Interactive), cb, err);\r\n }\r\n\r\n /**\r\n * Starts speech recognition, until stopContinuousRecognitionAsync() is called.\r\n * User must subscribe to events to receive recognition results.\r\n * @member IntentRecognizer.prototype.startContinuousRecognitionAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback invoked once the recognition has started.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public startContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n if (Object.keys(this.privAddedLmIntents).length !== 0 || undefined !== this.privUmbrellaIntent) {\r\n const context: IIntentContext = this.buildSpeechContext();\r\n\r\n this.privReco.speechContext.setSection(\"intent\", context.Intent);\r\n this.privReco.dynamicGrammar.addReferenceGrammar(context.ReferenceGrammars);\r\n\r\n const intentReco: IntentServiceRecognizer = this.privReco as IntentServiceRecognizer;\r\n intentReco.setIntents(this.privAddedLmIntents, this.privUmbrellaIntent);\r\n }\r\n\r\n marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(RecognitionMode.Conversation), cb, err);\r\n }\r\n\r\n /**\r\n * Stops continuous intent recognition.\r\n * @member IntentRecognizer.prototype.stopContinuousRecognitionAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback invoked once the recognition has stopped.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public stopContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);\r\n }\r\n\r\n /**\r\n * Starts speech recognition with keyword spotting, until stopKeywordRecognitionAsync() is called.\r\n * User must subscribe to events to receive recognition results.\r\n * Note: Key word spotting functionality is only available on the Speech Devices SDK.\r\n * This functionality is currently not included in the SDK itself.\r\n * @member IntentRecognizer.prototype.startKeywordRecognitionAsync\r\n * @function\r\n * @public\r\n * @param {KeywordRecognitionModel} model - The keyword recognition model that specifies the keyword to be recognized.\r\n * @param cb - Callback invoked once the recognition has started.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public startKeywordRecognitionAsync(model: KeywordRecognitionModel, cb?: () => void, err?: (e: string) => void): void {\r\n Contracts.throwIfNull(model, \"model\");\r\n\r\n if (!!err) {\r\n err(\"Not yet implemented.\");\r\n }\r\n }\r\n\r\n /**\r\n * Stops continuous speech recognition.\r\n * Note: Key word spotting functionality is only available on the Speech Devices SDK.\r\n * This functionality is currently not included in the SDK itself.\r\n * @member IntentRecognizer.prototype.stopKeywordRecognitionAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback invoked once the recognition has stopped.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public stopKeywordRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }\r\n\r\n /**\r\n * Adds a phrase that should be recognized as intent.\r\n * @member IntentRecognizer.prototype.addIntent\r\n * @function\r\n * @public\r\n * @param {string} intentId - A String that represents the identifier of the intent to be recognized.\r\n * @param {string} phrase - A String that specifies the phrase representing the intent.\r\n */\r\n public addIntent(simplePhrase: string, intentId?: string): void {\r\n Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);\r\n Contracts.throwIfNullOrWhitespace(intentId, \"intentId\");\r\n Contracts.throwIfNullOrWhitespace(simplePhrase, \"simplePhrase\");\r\n\r\n this.privAddedIntents.push([intentId, simplePhrase]);\r\n }\r\n\r\n /**\r\n * Adds an intent from Language Understanding service for recognition.\r\n * @member IntentRecognizer.prototype.addIntentWithLanguageModel\r\n * @function\r\n * @public\r\n * @param {string} intentId - A String that represents the identifier of the intent\r\n * to be recognized. Ignored if intentName is empty.\r\n * @param {string} model - The intent model from Language Understanding service.\r\n * @param {string} intentName - The intent name defined in the intent model. If it\r\n * is empty, all intent names defined in the model will be added.\r\n */\r\n public addIntentWithLanguageModel(intentId: string, model: LanguageUnderstandingModel, intentName?: string): void {\r\n Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);\r\n Contracts.throwIfNullOrWhitespace(intentId, \"intentId\");\r\n Contracts.throwIfNull(model, \"model\");\r\n\r\n const modelImpl: LanguageUnderstandingModelImpl = model as LanguageUnderstandingModelImpl;\r\n Contracts.throwIfNullOrWhitespace(modelImpl.appId, \"model.appId\");\r\n\r\n this.privAddedLmIntents[intentId] = new AddedLmIntent(modelImpl, intentName);\r\n }\r\n\r\n /**\r\n * @summary Adds all intents from the specified Language Understanding Model.\r\n * @member IntentRecognizer.prototype.addAllIntents\r\n * @function\r\n * @public\r\n * @function\r\n * @public\r\n * @param {LanguageUnderstandingModel} model - The language understanding model containing the intents.\r\n * @param {string} intentId - A custom id String to be returned in the IntentRecognitionResult's getIntentId() method.\r\n */\r\n public addAllIntents(model: LanguageUnderstandingModel, intentId?: string): void {\r\n Contracts.throwIfNull(model, \"model\");\r\n\r\n const modelImpl: LanguageUnderstandingModelImpl = model as LanguageUnderstandingModelImpl;\r\n Contracts.throwIfNullOrWhitespace(modelImpl.appId, \"model.appId\");\r\n\r\n this.privUmbrellaIntent = new AddedLmIntent(modelImpl, intentId);\r\n }\r\n\r\n /**\r\n * closes all external resources held by an instance of this class.\r\n * @member IntentRecognizer.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, errorCb?: (error: string) => void): void {\r\n Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);\r\n\r\n marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);\r\n }\r\n\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(speechConfig, this.properties);\r\n }\r\n\r\n protected createServiceRecognizer(authentication: IAuthentication, connectionFactory: IConnectionFactory, audioConfig: AudioConfig, recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n const audioImpl: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n return new IntentServiceRecognizer(authentication, connectionFactory, audioImpl, recognizerConfig, this);\r\n }\r\n\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privDisposedIntentRecognizer) {\r\n return;\r\n }\r\n\r\n if (disposing) {\r\n this.privDisposedIntentRecognizer = true;\r\n await super.dispose(disposing);\r\n }\r\n }\r\n\r\n private buildSpeechContext(): IIntentContext {\r\n let appId: string;\r\n let region: string;\r\n let subscriptionKey: string;\r\n const refGrammers: string[] = [];\r\n\r\n if (undefined !== this.privUmbrellaIntent) {\r\n appId = this.privUmbrellaIntent.modelImpl.appId;\r\n region = this.privUmbrellaIntent.modelImpl.region;\r\n subscriptionKey = this.privUmbrellaIntent.modelImpl.subscriptionKey;\r\n }\r\n\r\n // Build the reference grammer array.\r\n for (const intentId of Object.keys(this.privAddedLmIntents)) {\r\n const addedLmIntent: AddedLmIntent = this.privAddedLmIntents[intentId];\r\n\r\n // validate all the same model, region, and key...\r\n if (appId === undefined) {\r\n appId = addedLmIntent.modelImpl.appId;\r\n } else {\r\n if (appId !== addedLmIntent.modelImpl.appId) {\r\n throw new Error(\"Intents must all be from the same LUIS model\");\r\n }\r\n }\r\n\r\n if (region === undefined) {\r\n region = addedLmIntent.modelImpl.region;\r\n } else {\r\n if (region !== addedLmIntent.modelImpl.region) {\r\n throw new Error(\"Intents must all be from the same LUIS model in a single region\");\r\n }\r\n }\r\n\r\n if (subscriptionKey === undefined) {\r\n subscriptionKey = addedLmIntent.modelImpl.subscriptionKey;\r\n } else {\r\n if (subscriptionKey !== addedLmIntent.modelImpl.subscriptionKey) {\r\n throw new Error(\"Intents must all use the same subscription key\");\r\n }\r\n }\r\n\r\n const grammer: string = \"luis/\" + appId + \"-PRODUCTION#\" + intentId;\r\n refGrammers.push(grammer);\r\n }\r\n\r\n return {\r\n Intent: {\r\n id: appId,\r\n key: (subscriptionKey === undefined) ? this.privProperties.getProperty(PropertyId[PropertyId.SpeechServiceConnection_Key]) : subscriptionKey,\r\n provider: \"LUIS\",\r\n },\r\n ReferenceGrammars: (undefined === this.privUmbrellaIntent) ? refGrammers : [\"luis/\" + appId + \"-PRODUCTION\"],\r\n };\r\n }\r\n}\r\n\r\ninterface IIntentContext {\r\n Intent: {\r\n id: string,\r\n key: string,\r\n provider: string,\r\n };\r\n ReferenceGrammars: string[];\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary,\r\n} from \"../common/Exports\";\r\nimport {\r\n PropertyId\r\n} from \"../sdk/Exports\";\r\nimport {\r\n ConnectionFactoryBase\r\n} from \"./ConnectionFactoryBase\";\r\nimport {\r\n AuthInfo,\r\n IConnectionFactory,\r\n RecognizerConfig,\r\n WebsocketMessageFormatter,\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { QueryParameterNames } from \"./QueryParameterNames\";\r\n\r\nexport class TranslationConnectionFactory extends ConnectionFactoryBase {\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n if (!endpoint) {\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, undefined);\r\n const hostSuffix: string = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"wss://\" + region + \".s2s.speech\" + hostSuffix);\r\n endpoint = host + \"/speech/translation/cognitiveservices/v1\";\r\n }\r\n\r\n const queryParams: IStringDictionary = {\r\n from: config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage),\r\n to: config.parameters.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages),\r\n };\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n this.setUrlParameter(\r\n PropertyId.SpeechServiceResponse_TranslationRequestStablePartialResult,\r\n QueryParameterNames.StableTranslation,\r\n config,\r\n queryParams,\r\n endpoint\r\n );\r\n\r\n const voiceName: string = \"voice\";\r\n const featureName: string = \"features\";\r\n\r\n if (config.parameters.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) {\r\n queryParams[voiceName] = config.parameters.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice);\r\n queryParams[featureName] = \"texttospeech\";\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { CancellationErrorCode, CancellationReason, TranslationRecognitionResult } from \"./Exports\";\r\n\r\n/**\r\n * Define payload of speech recognition canceled result events.\r\n * @class TranslationRecognitionCanceledEventArgs\r\n */\r\nexport class TranslationRecognitionCanceledEventArgs {\r\n private privResult: TranslationRecognitionResult;\r\n private privSessionId: string;\r\n private privCancelReason: CancellationReason;\r\n private privErrorDetails: string;\r\n private privErrorCode: CancellationErrorCode;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {string} sessionid - The session id.\r\n * @param {CancellationReason} cancellationReason - The cancellation reason.\r\n * @param {string} errorDetails - Error details, if provided.\r\n * @param {TranslationRecognitionResult} result - The result.\r\n */\r\n public constructor(\r\n sessionid: string,\r\n cancellationReason: CancellationReason,\r\n errorDetails: string,\r\n errorCode: CancellationErrorCode,\r\n result: TranslationRecognitionResult) {\r\n this.privCancelReason = cancellationReason;\r\n this.privErrorDetails = errorDetails;\r\n this.privResult = result;\r\n this.privSessionId = sessionid;\r\n this.privErrorCode = errorCode;\r\n }\r\n\r\n /**\r\n * Specifies the recognition result.\r\n * @member TranslationRecognitionCanceledEventArgs.prototype.result\r\n * @function\r\n * @public\r\n * @returns {TranslationRecognitionResult} the recognition result.\r\n */\r\n public get result(): TranslationRecognitionResult {\r\n return this.privResult;\r\n }\r\n\r\n /**\r\n * Specifies the session identifier.\r\n * @member TranslationRecognitionCanceledEventArgs.prototype.sessionId\r\n * @function\r\n * @public\r\n * @returns {string} the session identifier.\r\n */\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n\r\n /**\r\n * The reason the recognition was canceled.\r\n * @member TranslationRecognitionCanceledEventArgs.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {CancellationReason} Specifies the reason canceled.\r\n */\r\n public get reason(): CancellationReason {\r\n return this.privCancelReason;\r\n }\r\n\r\n /**\r\n * The error code in case of an unsuccessful recognition.\r\n * Added in version 1.1.0.\r\n * @return An error code that represents the error reason.\r\n */\r\n public get errorCode(): CancellationErrorCode {\r\n return this.privErrorCode;\r\n }\r\n\r\n /**\r\n * In case of an unsuccessful recognition, provides details of the occurred error.\r\n * @member TranslationRecognitionCanceledEventArgs.prototype.errorDetails\r\n * @function\r\n * @public\r\n * @returns {string} A String that represents the error details.\r\n */\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection } from \"./Exports\";\r\n\r\n/**\r\n * Represents collection of parameters and their values.\r\n * @class Translation\r\n */\r\nexport class Translations {\r\n // Use an PropertyCollection internally, just wrapping it to hide the | enum syntax it has.\r\n private privMap: PropertyCollection = new PropertyCollection();\r\n\r\n /**\r\n * Returns the parameter value in type String. The parameter must have the same type as String.\r\n * Currently only String, int and bool are allowed.\r\n * If the name is not available, the specified defaultValue is returned.\r\n * @member Translation.prototype.get\r\n * @function\r\n * @public\r\n * @param {string} key - The parameter name.\r\n * @param {string} def - The default value which is returned if the parameter is not available in the collection.\r\n * @returns {string} value of the parameter.\r\n */\r\n public get(key: string, def?: string): string {\r\n return this.privMap.getProperty(key, def);\r\n }\r\n\r\n /**\r\n * Sets the String value of the parameter specified by name.\r\n * @member Translation.prototype.set\r\n * @function\r\n * @public\r\n * @param {string} key - The parameter name.\r\n * @param {string} value - The value of the parameter.\r\n */\r\n public set(key: string, value: string): void {\r\n this.privMap.setProperty(key, value);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ITranslations } from \"../Exports\";\r\nimport { TranslationStatus } from \"../TranslationStatus\";\r\n\r\n// translation.hypothesis\r\nexport interface ITranslationHypothesis {\r\n Duration: number;\r\n Offset: number;\r\n Text: string;\r\n Translation: ITranslations;\r\n}\r\n\r\nexport class TranslationHypothesis implements ITranslationHypothesis {\r\n private privTranslationHypothesis: ITranslationHypothesis;\r\n\r\n private constructor(json: string) {\r\n this.privTranslationHypothesis = JSON.parse(json);\r\n this.privTranslationHypothesis.Translation.TranslationStatus = (TranslationStatus as any)[this.privTranslationHypothesis.Translation.TranslationStatus];\r\n }\r\n\r\n public static fromJSON(json: string): TranslationHypothesis {\r\n return new TranslationHypothesis(json);\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privTranslationHypothesis.Duration;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privTranslationHypothesis.Offset;\r\n }\r\n\r\n public get Text(): string {\r\n return this.privTranslationHypothesis.Text;\r\n }\r\n\r\n public get Translation(): ITranslations {\r\n return this.privTranslationHypothesis.Translation;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ITranslations, RecognitionStatus } from \"../Exports\";\r\nimport { TranslationStatus } from \"../TranslationStatus\";\r\n\r\n// translation.phrase\r\nexport interface ITranslationPhrase {\r\n RecognitionStatus: RecognitionStatus;\r\n Offset: number;\r\n Duration: number;\r\n Text: string;\r\n Translation: ITranslations;\r\n}\r\n\r\nexport class TranslationPhrase implements ITranslationPhrase {\r\n private privTranslationPhrase: ITranslationPhrase;\r\n\r\n private constructor(json: string) {\r\n this.privTranslationPhrase = JSON.parse(json);\r\n this.privTranslationPhrase.RecognitionStatus = (RecognitionStatus as any)[this.privTranslationPhrase.RecognitionStatus];\r\n if (this.privTranslationPhrase.Translation !== undefined) {\r\n this.privTranslationPhrase.Translation.TranslationStatus = (TranslationStatus as any)[this.privTranslationPhrase.Translation.TranslationStatus];\r\n }\r\n }\r\n\r\n public static fromJSON(json: string): TranslationPhrase {\r\n return new TranslationPhrase(json);\r\n }\r\n\r\n public get RecognitionStatus(): RecognitionStatus {\r\n return this.privTranslationPhrase.RecognitionStatus;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privTranslationPhrase.Offset;\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privTranslationPhrase.Duration;\r\n }\r\n\r\n public get Text(): string {\r\n return this.privTranslationPhrase.Text;\r\n }\r\n\r\n public get Translation(): ITranslations {\r\n return this.privTranslationPhrase.Translation;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { SynthesisStatus } from \"../Exports\";\r\n\r\n// translation.synthesis.end\r\nexport interface ITranslationSynthesisEnd {\r\n SynthesisStatus: SynthesisStatus;\r\n FailureReason: string;\r\n}\r\n\r\nexport class TranslationSynthesisEnd implements ITranslationSynthesisEnd {\r\n private privSynthesisEnd: ITranslationSynthesisEnd;\r\n\r\n private constructor(json: string) {\r\n this.privSynthesisEnd = JSON.parse(json);\r\n this.privSynthesisEnd.SynthesisStatus = (SynthesisStatus as any)[this.privSynthesisEnd.SynthesisStatus];\r\n }\r\n\r\n public static fromJSON(json: string): TranslationSynthesisEnd {\r\n return new TranslationSynthesisEnd(json);\r\n }\r\n\r\n public get SynthesisStatus(): SynthesisStatus {\r\n return this.privSynthesisEnd.SynthesisStatus;\r\n }\r\n\r\n public get FailureReason(): string {\r\n return this.privSynthesisEnd.FailureReason;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionEvent,\r\n IAudioSource,\r\n MessageType,\r\n TranslationStatus,\r\n} from \"../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechRecognitionResult,\r\n TranslationRecognitionCanceledEventArgs,\r\n TranslationRecognitionEventArgs,\r\n TranslationRecognitionResult,\r\n TranslationRecognizer,\r\n Translations,\r\n TranslationSynthesisEventArgs,\r\n TranslationSynthesisResult,\r\n} from \"../sdk/Exports\";\r\nimport {\r\n CancellationErrorCodePropertyName,\r\n EnumTranslation,\r\n RecognitionStatus,\r\n ServiceRecognizerBase,\r\n SynthesisStatus,\r\n TranslationHypothesis,\r\n TranslationPhrase,\r\n TranslationSynthesisEnd,\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class TranslationServiceRecognizer extends ServiceRecognizerBase {\r\n private privTranslationRecognizer: TranslationRecognizer;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n translationRecognizer: TranslationRecognizer) {\r\n\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer);\r\n this.privTranslationRecognizer = translationRecognizer;\r\n this.connectionEvents.attach(async (connectionEvent: ConnectionEvent): Promise => {\r\n if (connectionEvent.name === \"ConnectionEstablishedEvent\") {\r\n this.privTranslationRecognizer.onConnection();\r\n } else if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n await this.privTranslationRecognizer.onDisconnection();\r\n }\r\n });\r\n\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n let processed: boolean = false;\r\n\r\n if (connectionMessage.messageType === MessageType.Text) {\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n }\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"translation.hypothesis\":\r\n\r\n const result: TranslationRecognitionEventArgs = this.fireEventForResult(TranslationHypothesis.fromJSON(connectionMessage.textBody), resultProps);\r\n this.privRequestSession.onHypothesis(this.privRequestSession.currentTurnAudioOffset + result.offset);\r\n\r\n if (!!this.privTranslationRecognizer.recognizing) {\r\n try {\r\n this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer, result);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"translation.phrase\":\r\n const translatedPhrase: TranslationPhrase = TranslationPhrase.fromJSON(connectionMessage.textBody);\r\n\r\n this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + translatedPhrase.Offset + translatedPhrase.Duration);\r\n\r\n if (translatedPhrase.RecognitionStatus === RecognitionStatus.Success) {\r\n\r\n // OK, the recognition was successful. How'd the translation do?\r\n const result: TranslationRecognitionEventArgs = this.fireEventForResult(translatedPhrase, resultProps);\r\n if (!!this.privTranslationRecognizer.recognized) {\r\n try {\r\n this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, result);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result.result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n\r\n break;\r\n } else {\r\n const reason: ResultReason = EnumTranslation.implTranslateRecognitionResult(translatedPhrase.RecognitionStatus);\r\n\r\n const result = new TranslationRecognitionResult(\r\n undefined,\r\n this.privRequestSession.requestId,\r\n reason,\r\n translatedPhrase.Text,\r\n translatedPhrase.Duration,\r\n this.privRequestSession.currentTurnAudioOffset + translatedPhrase.Offset,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n if (reason === ResultReason.Canceled) {\r\n const cancelReason: CancellationReason = EnumTranslation.implTranslateCancelResult(translatedPhrase.RecognitionStatus);\r\n\r\n await this.cancelRecognitionLocal(\r\n cancelReason,\r\n EnumTranslation.implTranslateCancelErrorCode(translatedPhrase.RecognitionStatus),\r\n undefined);\r\n } else {\r\n if (!(this.privRequestSession.isSpeechEnded && reason === ResultReason.NoMatch && translatedPhrase.RecognitionStatus !== RecognitionStatus.InitialSilenceTimeout)) {\r\n const ev = new TranslationRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privTranslationRecognizer.recognized) {\r\n try {\r\n this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n }\r\n }\r\n processed = true;\r\n break;\r\n\r\n case \"translation.synthesis\":\r\n this.sendSynthesisAudio(connectionMessage.binaryBody, this.privRequestSession.sessionId);\r\n processed = true;\r\n break;\r\n\r\n case \"translation.synthesis.end\":\r\n const synthEnd: TranslationSynthesisEnd = TranslationSynthesisEnd.fromJSON(connectionMessage.textBody);\r\n\r\n switch (synthEnd.SynthesisStatus) {\r\n case SynthesisStatus.Error:\r\n if (!!this.privTranslationRecognizer.synthesizing) {\r\n const result = new TranslationSynthesisResult(ResultReason.Canceled, undefined);\r\n const retEvent: TranslationSynthesisEventArgs = new TranslationSynthesisEventArgs(result, this.privRequestSession.sessionId);\r\n\r\n try {\r\n this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n if (!!this.privTranslationRecognizer.canceled) {\r\n // And raise a canceled event to send the rich(er) error message back.\r\n const canceledResult: TranslationRecognitionCanceledEventArgs = new TranslationRecognitionCanceledEventArgs(\r\n this.privRequestSession.sessionId,\r\n CancellationReason.Error,\r\n synthEnd.FailureReason,\r\n CancellationErrorCode.ServiceError,\r\n null);\r\n\r\n try {\r\n this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, canceledResult);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n case SynthesisStatus.Success:\r\n this.sendSynthesisAudio(undefined, this.privRequestSession.sessionId);\r\n break;\r\n default:\r\n break;\r\n }\r\n processed = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n if (!!this.privTranslationRecognizer.canceled) {\r\n\r\n const cancelEvent: TranslationRecognitionCanceledEventArgs = new TranslationRecognitionCanceledEventArgs(\r\n sessionId,\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined);\r\n\r\n try {\r\n this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: TranslationRecognitionResult = new TranslationRecognitionResult(\r\n undefined, // Translations\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Druation\r\n undefined, // Offset\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n /* tslint:disable:no-empty */\r\n this.privSuccessCallback = undefined;\r\n } catch { }\r\n }\r\n }\r\n\r\n private fireEventForResult(serviceResult: TranslationHypothesis | TranslationPhrase, properties: PropertyCollection): TranslationRecognitionEventArgs {\r\n let translations: Translations;\r\n\r\n if (undefined !== serviceResult.Translation.Translations) {\r\n translations = new Translations();\r\n for (const translation of serviceResult.Translation.Translations) {\r\n translations.set(translation.Language, translation.Text);\r\n }\r\n }\r\n\r\n let resultReason: ResultReason;\r\n if (serviceResult instanceof TranslationPhrase) {\r\n if (serviceResult.Translation.TranslationStatus === TranslationStatus.Success) {\r\n resultReason = ResultReason.TranslatedSpeech;\r\n } else {\r\n resultReason = ResultReason.RecognizedSpeech;\r\n }\r\n } else {\r\n resultReason = ResultReason.TranslatingSpeech;\r\n }\r\n\r\n const offset: number = serviceResult.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n const result = new TranslationRecognitionResult(\r\n translations,\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n serviceResult.Text,\r\n serviceResult.Duration,\r\n offset,\r\n serviceResult.Translation.FailureReason,\r\n JSON.stringify(serviceResult),\r\n properties);\r\n\r\n const ev = new TranslationRecognitionEventArgs(result, offset, this.privRequestSession.sessionId);\r\n return ev;\r\n }\r\n\r\n private sendSynthesisAudio(audio: ArrayBuffer, sessionId: string): void {\r\n const reason = (undefined === audio) ? ResultReason.SynthesizingAudioCompleted : ResultReason.SynthesizingAudio;\r\n const result = new TranslationSynthesisResult(reason, audio);\r\n const retEvent: TranslationSynthesisEventArgs = new TranslationSynthesisEventArgs(result, sessionId);\r\n\r\n if (!!this.privTranslationRecognizer.synthesizing) {\r\n try {\r\n this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the possible reasons a recognition result might not be recognized.\r\n * @class NoMatchReason\r\n */\r\nexport enum NoMatchReason {\r\n\r\n /**\r\n * Indicates that speech was detected, but not recognized.\r\n * @member NoMatchReason.NotRecognized\r\n */\r\n NotRecognized,\r\n\r\n /**\r\n * Indicates that the start of the audio stream contained only silence,\r\n * and the service timed out waiting for speech.\r\n * @member NoMatchReason.InitialSilenceTimeout\r\n */\r\n InitialSilenceTimeout,\r\n\r\n /**\r\n * Indicates that the start of the audio stream contained only noise,\r\n * and the service timed out waiting for speech.\r\n * @member NoMatchReason.InitialBabbleTimeout\r\n */\r\n InitialBabbleTimeout,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// response\r\n\r\nexport interface IActivityPayloadResponse {\r\n conversationId: string;\r\n messageDataStreamType: number;\r\n messagePayload: any;\r\n version: number;\r\n}\r\n\r\nexport class ActivityPayloadResponse implements IActivityPayloadResponse {\r\n private privActivityResponse: IActivityPayloadResponse;\r\n\r\n private constructor(json: string) {\r\n this.privActivityResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): ActivityPayloadResponse {\r\n return new ActivityPayloadResponse(json);\r\n }\r\n\r\n public get conversationId(): string {\r\n return this.privActivityResponse.conversationId;\r\n }\r\n\r\n public get messageDataStreamType(): number {\r\n return this.privActivityResponse.messageDataStreamType;\r\n }\r\n\r\n public get messagePayload(): any {\r\n return this.privActivityResponse.messagePayload;\r\n }\r\n\r\n public get version(): number {\r\n return this.privActivityResponse.version;\r\n }\r\n}\r\n\r\nexport enum MessageDataStreamType {\r\n None = 0,\r\n TextToSpeechAudio = 1,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig,\r\n TranslationConnectionFactory,\r\n TranslationServiceRecognizer,\r\n} from \"../common.speech/Exports\";\r\nimport { marshalPromiseToCallbacks } from \"../common/Exports\";\r\nimport { AudioConfigImpl } from \"./Audio/AudioConfig\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n AudioConfig,\r\n PropertyCollection,\r\n PropertyId,\r\n Recognizer,\r\n TranslationRecognitionCanceledEventArgs,\r\n TranslationRecognitionEventArgs,\r\n TranslationRecognitionResult,\r\n TranslationSynthesisEventArgs,\r\n} from \"./Exports\";\r\nimport { SpeechTranslationConfig, SpeechTranslationConfigImpl } from \"./SpeechTranslationConfig\";\r\n\r\n/**\r\n * Translation recognizer\r\n * @class TranslationRecognizer\r\n */\r\nexport class TranslationRecognizer extends Recognizer {\r\n private privDisposedTranslationRecognizer: boolean;\r\n\r\n /**\r\n * Initializes an instance of the TranslationRecognizer.\r\n * @constructor\r\n * @param {SpeechTranslationConfig} speechConfig - Set of properties to configure this recognizer.\r\n * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer\r\n */\r\n public constructor(speechConfig: SpeechTranslationConfig, audioConfig?: AudioConfig) {\r\n const configImpl = speechConfig as SpeechTranslationConfigImpl;\r\n Contracts.throwIfNull(configImpl, \"speechConfig\");\r\n\r\n super(audioConfig, configImpl.properties, new TranslationConnectionFactory());\r\n\r\n this.privDisposedTranslationRecognizer = false;\r\n this.privProperties = configImpl.properties.clone();\r\n\r\n if (this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) {\r\n Contracts.throwIfNullOrWhitespace(\r\n this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice),\r\n PropertyId[PropertyId.SpeechServiceConnection_TranslationVoice]);\r\n }\r\n\r\n Contracts.throwIfNullOrWhitespace(\r\n this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages),\r\n PropertyId[PropertyId.SpeechServiceConnection_TranslationToLanguages]);\r\n\r\n Contracts.throwIfNullOrWhitespace(this.properties.getProperty(\r\n PropertyId.SpeechServiceConnection_RecoLanguage),\r\n PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);\r\n\r\n }\r\n\r\n /**\r\n * The event recognizing signals that an intermediate recognition result is received.\r\n * @member TranslationRecognizer.prototype.recognizing\r\n * @function\r\n * @public\r\n */\r\n public recognizing: (sender: TranslationRecognizer, event: TranslationRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event recognized signals that a final recognition result is received.\r\n * @member TranslationRecognizer.prototype.recognized\r\n * @function\r\n * @public\r\n */\r\n public recognized: (sender: TranslationRecognizer, event: TranslationRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event canceled signals that an error occurred during recognition.\r\n * @member TranslationRecognizer.prototype.canceled\r\n * @function\r\n * @public\r\n */\r\n public canceled: (sender: TranslationRecognizer, event: TranslationRecognitionCanceledEventArgs) => void;\r\n\r\n /**\r\n * The event synthesizing signals that a translation synthesis result is received.\r\n * @member TranslationRecognizer.prototype.synthesizing\r\n * @function\r\n * @public\r\n */\r\n public synthesizing: (sender: TranslationRecognizer, event: TranslationSynthesisEventArgs) => void;\r\n\r\n /**\r\n * Gets the language name that was set when the recognizer was created.\r\n * @member TranslationRecognizer.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @returns {string} Gets the language name that was set when the recognizer was created.\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);\r\n }\r\n\r\n /**\r\n * Gets target languages for translation that were set when the recognizer was created.\r\n * The language is specified in BCP-47 format. The translation will provide translated text for each of language.\r\n * @member TranslationRecognizer.prototype.targetLanguages\r\n * @function\r\n * @public\r\n * @returns {string[]} Gets target languages for translation that were set when the recognizer was created.\r\n */\r\n public get targetLanguages(): string[] {\r\n Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages).split(\",\");\r\n }\r\n\r\n /**\r\n * Gets the name of output voice.\r\n * @member TranslationRecognizer.prototype.voiceName\r\n * @function\r\n * @public\r\n * @returns {string} the name of output voice.\r\n */\r\n public get voiceName(): string {\r\n Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice, undefined);\r\n }\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member TranslationRecognizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Gets/Sets the authorization token used to communicate with the service.\r\n * @member TranslationRecognizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} value - Authorization token.\r\n */\r\n public set authorizationToken(value: string) {\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, value);\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this TranslationRecognizer.\r\n * @member TranslationRecognizer.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their values defined for this TranslationRecognizer.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * Starts recognition and translation, and stops after the first utterance is recognized.\r\n * The task returns the translation text as result.\r\n * Note: recognizeOnceAsync returns when the first utterance has been recognized, so it is suitableonly\r\n * for single shot recognition like command or query. For long-running recognition,\r\n * use startContinuousRecognitionAsync() instead.\r\n * @member TranslationRecognizer.prototype.recognizeOnceAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback that received the result when the translation has completed.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public recognizeOnceAsync(cb?: (e: TranslationRecognitionResult) => void, err?: (e: string) => void): void {\r\n Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);\r\n marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(RecognitionMode.Conversation), cb, err);\r\n }\r\n\r\n /**\r\n * Starts recognition and translation, until stopContinuousRecognitionAsync() is called.\r\n * User must subscribe to events to receive translation results.\r\n * @member TranslationRecognizer.prototype.startContinuousRecognitionAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback that received the translation has started.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public startContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(RecognitionMode.Conversation), cb, err);\r\n }\r\n\r\n /**\r\n * Stops continuous recognition and translation.\r\n * @member TranslationRecognizer.prototype.stopContinuousRecognitionAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback that received the translation has stopped.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public stopContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);\r\n }\r\n\r\n /**\r\n * closes all external resources held by an instance of this class.\r\n * @member TranslationRecognizer.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, errorCb?: (error: string) => void): void {\r\n Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);\r\n marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);\r\n }\r\n\r\n /**\r\n * handles ConnectionEstablishedEvent for conversation translation scenarios.\r\n * @member TranslationRecognizer.prototype.onConnection\r\n * @function\r\n * @public\r\n */\r\n /* tslint:disable:no-empty */\r\n public onConnection(): void { }\r\n\r\n /**\r\n * handles disconnection events for conversation translation scenarios.\r\n * @member TranslationRecognizer.prototype.onDisconnection\r\n * @function\r\n * @public\r\n */\r\n /* tslint:disable:no-empty */\r\n public async onDisconnection(): Promise { }\r\n\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privDisposedTranslationRecognizer) {\r\n return;\r\n }\r\n\r\n this.privDisposedTranslationRecognizer = true;\r\n\r\n if (disposing) {\r\n await this.implRecognizerStop();\r\n await super.dispose(disposing);\r\n }\r\n }\r\n\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(speechConfig, this.properties);\r\n }\r\n\r\n protected createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n\r\n const configImpl: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n\r\n return new TranslationServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RecognitionStatus, SimpleSpeechPhrase } from \"../../src/common.speech/Exports\";\r\nimport { IntentRecognitionResult, NoMatchReason, SpeechRecognitionResult, TranslationRecognitionResult } from \"./Exports\";\r\n\r\n/**\r\n * Contains detailed information for NoMatch recognition results.\r\n * @class NoMatchDetails\r\n */\r\nexport class NoMatchDetails {\r\n private privReason: NoMatchReason;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {NoMatchReason} reason - The no-match reason.\r\n */\r\n private constructor(reason: NoMatchReason) {\r\n this.privReason = reason;\r\n }\r\n\r\n /**\r\n * Creates an instance of NoMatchDetails object for the NoMatch SpeechRecognitionResults.\r\n * @member NoMatchDetails.fromResult\r\n * @function\r\n * @public\r\n * @param {SpeechRecognitionResult | IntentRecognitionResult | TranslationRecognitionResult}\r\n * result - The recognition result that was not recognized.\r\n * @returns {NoMatchDetails} The no match details object being created.\r\n */\r\n public static fromResult(result: SpeechRecognitionResult | IntentRecognitionResult | TranslationRecognitionResult): NoMatchDetails {\r\n const simpleSpeech: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(result.json);\r\n\r\n let reason: NoMatchReason = NoMatchReason.NotRecognized;\r\n\r\n switch (simpleSpeech.RecognitionStatus) {\r\n case RecognitionStatus.BabbleTimeout:\r\n reason = NoMatchReason.InitialBabbleTimeout;\r\n break;\r\n case RecognitionStatus.InitialSilenceTimeout:\r\n reason = NoMatchReason.InitialSilenceTimeout;\r\n break;\r\n default:\r\n reason = NoMatchReason.NotRecognized;\r\n break;\r\n }\r\n\r\n return new NoMatchDetails(reason);\r\n }\r\n\r\n /**\r\n * The reason the recognition was canceled.\r\n * @member NoMatchDetails.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {NoMatchReason} Specifies the reason canceled.\r\n */\r\n public get reason(): NoMatchReason {\r\n return this.privReason;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Contains detailed information about why a result was canceled.\r\n * @class CancellationDetailsBase\r\n */\r\nexport class CancellationDetailsBase {\r\n private privReason: CancellationReason;\r\n private privErrorDetails: string;\r\n private privErrorCode: CancellationErrorCode;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {CancellationReason} reason - The cancellation reason.\r\n * @param {string} errorDetails - The error details, if provided.\r\n */\r\n protected constructor(reason: CancellationReason, errorDetails: string, errorCode: CancellationErrorCode) {\r\n this.privReason = reason;\r\n this.privErrorDetails = errorDetails;\r\n this.privErrorCode = errorCode;\r\n }\r\n\r\n /**\r\n * The reason the recognition was canceled.\r\n * @member CancellationDetailsBase.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {CancellationReason} Specifies the reason canceled.\r\n */\r\n public get reason(): CancellationReason {\r\n return this.privReason;\r\n }\r\n\r\n /**\r\n * In case of an unsuccessful recognition, provides details of the occurred error.\r\n * @member CancellationDetailsBase.prototype.errorDetails\r\n * @function\r\n * @public\r\n * @returns {string} A String that represents the error details.\r\n */\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n\r\n /**\r\n * The error code in case of an unsuccessful recognition.\r\n * Added in version 1.1.0.\r\n * @return An error code that represents the error reason.\r\n */\r\n public get ErrorCode(): CancellationErrorCode {\r\n return this.privErrorCode;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { CancellationErrorCodePropertyName, EnumTranslation, SimpleSpeechPhrase } from \"../common.speech/Exports\";\r\nimport { CancellationDetailsBase } from \"./CancellationDetailsBase\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n RecognitionResult,\r\n SpeechSynthesisResult\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Contains detailed information about why a result was canceled.\r\n * @class CancellationDetails\r\n */\r\nexport class CancellationDetails extends CancellationDetailsBase {\r\n\r\n private constructor(reason: CancellationReason, errorDetails: string, errorCode: CancellationErrorCode) {\r\n super(reason, errorDetails, errorCode);\r\n }\r\n\r\n /**\r\n * Creates an instance of CancellationDetails object for the canceled RecognitionResult.\r\n * @member CancellationDetails.fromResult\r\n * @function\r\n * @public\r\n * @param {RecognitionResult | SpeechSynthesisResult} result - The result that was canceled.\r\n * @returns {CancellationDetails} The cancellation details object being created.\r\n */\r\n public static fromResult(result: RecognitionResult | SpeechSynthesisResult): CancellationDetails {\r\n let reason = CancellationReason.Error;\r\n let errorCode: CancellationErrorCode = CancellationErrorCode.NoError;\r\n\r\n if (result instanceof RecognitionResult && !!result.json) {\r\n const simpleSpeech: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(result.json);\r\n reason = EnumTranslation.implTranslateCancelResult(simpleSpeech.RecognitionStatus);\r\n }\r\n\r\n if (!!result.properties) {\r\n errorCode = (CancellationErrorCode as any)[result.properties.getProperty(CancellationErrorCodePropertyName, CancellationErrorCode[CancellationErrorCode.NoError])];\r\n }\r\n\r\n return new CancellationDetails(reason, result.errorDetails, errorCode);\r\n }\r\n\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport { SessionEventArgs } from \"./Exports\";\r\n\r\n/**\r\n * Defines payload for connection events like Connected/Disconnected.\r\n * Added in version 1.2.0\r\n */\r\nexport class ConnectionEventArgs extends SessionEventArgs {\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport { SessionEventArgs } from \"./Exports\";\r\n\r\n/**\r\n * Defines payload for any Service message event\r\n * Added in version 1.9.0\r\n */\r\n\r\nexport class ServiceEventArgs extends SessionEventArgs {\r\n private privJsonResult: string;\r\n private privEventName: string;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {string} json - json payload of the USP message.\r\n */\r\n public constructor(json: string, name: string, sessionId?: string) {\r\n super(sessionId);\r\n this.privJsonResult = json;\r\n this.privEventName = name;\r\n }\r\n\r\n public get jsonString(): string {\r\n return this.privJsonResult;\r\n }\r\n\r\n public get eventName(): string {\r\n return this.privEventName;\r\n }\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport { HeaderNames } from \"../common.speech/HeaderNames\";\r\nimport {\r\n ConnectionMessage as IntConnectionMessage,\r\n MessageType\r\n} from \"../common/Exports\";\r\nimport {\r\n PropertyCollection\r\n} from \"./PropertyCollection\";\r\nimport { PropertyId } from \"./PropertyId\";\r\n\r\n/**\r\n * ConnectionMessage represents implementation specific messages sent to and received from\r\n * the speech service. These messages are provided for debugging purposes and should not\r\n * be used for production use cases with the Azure Cognitive Services Speech Service.\r\n * Messages sent to and received from the Speech Service are subject to change without\r\n * notice. This includes message contents, headers, payloads, ordering, etc.\r\n * Added in version 1.11.0.\r\n */\r\nexport abstract class ConnectionMessage {\r\n /**\r\n * The message path.\r\n */\r\n public abstract get path(): string;\r\n\r\n /**\r\n * Checks to see if the ConnectionMessage is a text message.\r\n * See also IsBinaryMessage().\r\n */\r\n public abstract get isTextMessage(): boolean;\r\n\r\n /**\r\n * Checks to see if the ConnectionMessage is a binary message.\r\n * See also GetBinaryMessage().\r\n */\r\n public abstract get isBinaryMessage(): boolean;\r\n\r\n /**\r\n * Gets the text message payload. Typically the text message content-type is\r\n * application/json. To determine other content-types use\r\n * Properties.GetProperty(\"Content-Type\").\r\n */\r\n public abstract get TextMessage(): string;\r\n\r\n /**\r\n * Gets the binary message payload.\r\n */\r\n public abstract get binaryMessage(): ArrayBuffer;\r\n\r\n /**\r\n * A collection of properties and their values defined for this .\r\n * Message headers can be accessed via this collection (e.g. \"Content-Type\").\r\n */\r\n public abstract get properties(): PropertyCollection;\r\n\r\n /**\r\n * Returns a string that represents the connection message.\r\n */\r\n public abstract toString(): string;\r\n}\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class ConnectionMessageImpl {\r\n\r\n private privConnectionMessage: IntConnectionMessage;\r\n private privProperties: PropertyCollection;\r\n\r\n constructor(message: IntConnectionMessage) {\r\n this.privConnectionMessage = message;\r\n this.privProperties = new PropertyCollection();\r\n if (!!this.privConnectionMessage.headers[HeaderNames.ConnectionId]) {\r\n this.privProperties.setProperty(PropertyId.Speech_SessionId, this.privConnectionMessage.headers[HeaderNames.ConnectionId]);\r\n }\r\n\r\n Object.keys(this.privConnectionMessage.headers).forEach((header: string, index: number, array: string[]): void => {\r\n this.privProperties.setProperty(header, this.privConnectionMessage.headers[header]);\r\n });\r\n }\r\n\r\n /**\r\n * The message path.\r\n */\r\n public get path(): string {\r\n return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find((key: string) => key.toLowerCase() === \"path\".toLowerCase())];\r\n }\r\n\r\n /**\r\n * Checks to see if the ConnectionMessage is a text message.\r\n * See also IsBinaryMessage().\r\n */\r\n public get isTextMessage(): boolean {\r\n return this.privConnectionMessage.messageType === MessageType.Text;\r\n }\r\n\r\n /**\r\n * Checks to see if the ConnectionMessage is a binary message.\r\n * See also GetBinaryMessage().\r\n */\r\n public get isBinaryMessage(): boolean {\r\n return this.privConnectionMessage.messageType === MessageType.Binary;\r\n }\r\n\r\n /**\r\n * Gets the text message payload. Typically the text message content-type is\r\n * application/json. To determine other content-types use\r\n * Properties.GetProperty(\"Content-Type\").\r\n */\r\n public get TextMessage(): string {\r\n return this.privConnectionMessage.textBody;\r\n }\r\n\r\n /**\r\n * Gets the binary message payload.\r\n */\r\n public get binaryMessage(): ArrayBuffer {\r\n return this.privConnectionMessage.binaryBody;\r\n }\r\n\r\n /**\r\n * A collection of properties and their values defined for this .\r\n * Message headers can be accessed via this collection (e.g. \"Content-Type\").\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * Returns a string that represents the connection message.\r\n */\r\n public toString(): string {\r\n return \"\";\r\n }\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport {\r\n ConnectionMessage,\r\n SessionEventArgs\r\n} from \"./Exports\";\r\n\r\nexport class ConnectionMessageEventArgs {\r\n\r\n private privConnectionMessage: ConnectionMessage;\r\n\r\n constructor(message: ConnectionMessage) {\r\n this.privConnectionMessage = message;\r\n }\r\n\r\n /**\r\n * Gets the associated with this .\r\n */\r\n public get message(): ConnectionMessage {\r\n return this.privConnectionMessage;\r\n }\r\n\r\n /**\r\n * Returns a string that represents the connection message event.\r\n */\r\n public toString(): string {\r\n return \"Message: \" + this.privConnectionMessage.toString();\r\n }\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport {\r\n ServiceRecognizerBase,\r\n SynthesisAdapterBase,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n ConnectionEvent,\r\n ConnectionMessageReceivedEvent,\r\n ConnectionMessageSentEvent,\r\n IDetachable,\r\n marshalPromiseToCallbacks,\r\n ServiceEvent,\r\n} from \"../common/Exports\";\r\nimport {\r\n ConnectionMessageImpl\r\n} from \"./ConnectionMessage\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n ConnectionEventArgs,\r\n ConnectionMessageEventArgs,\r\n Recognizer,\r\n ServiceEventArgs,\r\n SpeechSynthesizer,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Connection is a proxy class for managing connection to the speech service of the specified Recognizer.\r\n * By default, a Recognizer autonomously manages connection to service when needed.\r\n * The Connection class provides additional methods for users to explicitly open or close a connection and\r\n * to subscribe to connection status changes.\r\n * The use of Connection is optional, and mainly for scenarios where fine tuning of application\r\n * behavior based on connection status is needed. Users can optionally call Open() to manually set up a connection\r\n * in advance before starting recognition on the Recognizer associated with this Connection.\r\n * If the Recognizer needs to connect or disconnect to service, it will\r\n * setup or shutdown the connection independently. In this case the Connection will be notified by change of connection\r\n * status via Connected/Disconnected events.\r\n * Added in version 1.2.1.\r\n */\r\nexport class Connection {\r\n private privInternalData: ServiceRecognizerBase | SynthesisAdapterBase;\r\n private privEventListener: IDetachable;\r\n private privServiceEventListener: IDetachable;\r\n\r\n /**\r\n * Gets the Connection instance from the specified recognizer.\r\n * @param recognizer The recognizer associated with the connection.\r\n * @return The Connection instance of the recognizer.\r\n */\r\n public static fromRecognizer(recognizer: Recognizer): Connection {\r\n const recoBase: ServiceRecognizerBase = recognizer.internalData as ServiceRecognizerBase;\r\n\r\n const ret: Connection = new Connection();\r\n\r\n ret.privInternalData = recoBase;\r\n ret.setupEvents();\r\n return ret;\r\n }\r\n\r\n /**\r\n * Gets the Connection instance from the specified synthesizer.\r\n * @param synthesizer The synthesizer associated with the connection.\r\n * @return The Connection instance of the synthesizer.\r\n */\r\n public static fromSynthesizer(synthesizer: SpeechSynthesizer): Connection {\r\n const synthBase: SynthesisAdapterBase = synthesizer.internalData as SynthesisAdapterBase;\r\n\r\n const ret: Connection = new Connection();\r\n\r\n ret.privInternalData = synthBase;\r\n ret.setupEvents();\r\n return ret;\r\n }\r\n\r\n /**\r\n * Starts to set up connection to the service.\r\n * Users can optionally call openConnection() to manually set up a connection in advance before starting recognition on the\r\n * Recognizer associated with this Connection. After starting recognition, calling Open() will have no effect\r\n *\r\n * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to\r\n * be notified when the connection is established.\r\n */\r\n public openConnection(cb?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks(this.privInternalData.connect(), cb, err);\r\n }\r\n\r\n /**\r\n * Closes the connection the service.\r\n * Users can optionally call closeConnection() to manually shutdown the connection of the associated Recognizer.\r\n *\r\n * If closeConnection() is called during recognition, recognition will fail and cancel with an error.\r\n */\r\n public closeConnection(cb?: () => void, err?: (error: string) => void): void {\r\n if (this.privInternalData instanceof SynthesisAdapterBase) {\r\n throw new Error(\"Disconnecting a synthesizer's connection is currently not supported\");\r\n } else {\r\n marshalPromiseToCallbacks((this.privInternalData as ServiceRecognizerBase).disconnect(), cb, err);\r\n }\r\n }\r\n\r\n /**\r\n * Appends a parameter in a message to service.\r\n * Added in version 1.12.1.\r\n * @param path The path of the network message.\r\n * @param propertyName Name of the property\r\n * @param propertyValue Value of the property. This is a json string.\r\n */\r\n public setMessageProperty(path: string, propertyName: string, propertyValue: string): void {\r\n Contracts.throwIfNullOrWhitespace(propertyName, \"propertyName\");\r\n\r\n if (this.privInternalData instanceof ServiceRecognizerBase) {\r\n if (path.toLowerCase() !== \"speech.context\") {\r\n throw new Error(\"Only speech.context message property sets are currently supported for recognizer\");\r\n } else {\r\n (this.privInternalData as ServiceRecognizerBase).speechContext.setSection(propertyName, propertyValue);\r\n }\r\n } else if (this.privInternalData instanceof SynthesisAdapterBase) {\r\n if (path.toLowerCase() !== \"synthesis.context\") {\r\n throw new Error(\"Only synthesis.context message property sets are currently supported for synthesizer\");\r\n } else {\r\n (this.privInternalData as SynthesisAdapterBase).synthesisContext.setSection(propertyName, propertyValue);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Sends a message to the speech service.\r\n * Added in version 1.13.0.\r\n * @param path The WebSocket path of the message\r\n * @param payload The payload of the message. This is a json string or a ArrayBuffer.\r\n * @param success A callback to indicate success.\r\n * @param error A callback to indicate an error.\r\n */\r\n public sendMessageAsync(path: string, payload: string | ArrayBuffer, success?: () => void, error?: (error: string) => void): void {\r\n marshalPromiseToCallbacks(this.privInternalData.sendNetworkMessage(path, payload), success, error);\r\n }\r\n\r\n /**\r\n * Any message from service that is not being processed by any other top level recognizers.\r\n *\r\n * Will be removed in 2.0.\r\n */\r\n public receivedServiceMessage: (args: ServiceEventArgs) => void;\r\n\r\n /**\r\n * Any message received from the Speech Service.\r\n */\r\n public messageReceived: (args: ConnectionMessageEventArgs) => void;\r\n\r\n /**\r\n * Any message sent to the Speech Service.\r\n */\r\n public messageSent: (args: ConnectionMessageEventArgs) => void;\r\n\r\n /**\r\n * The Connected event to indicate that the recognizer is connected to service.\r\n */\r\n public connected: (args: ConnectionEventArgs) => void;\r\n\r\n /**\r\n * The Disconnected event to indicate that the recognizer is disconnected from service.\r\n */\r\n public disconnected: (args: ConnectionEventArgs) => void;\r\n\r\n /**\r\n * Dispose of associated resources.\r\n */\r\n public close(): void {\r\n /* tslint:disable:no-empty */\r\n }\r\n\r\n private setupEvents(): void {\r\n this.privEventListener = this.privInternalData.connectionEvents.attach((connectionEvent: ConnectionEvent): void => {\r\n if (connectionEvent.name === \"ConnectionEstablishedEvent\") {\r\n if (!!this.connected) {\r\n this.connected(new ConnectionEventArgs(connectionEvent.connectionId));\r\n }\r\n } else if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n if (!!this.disconnected) {\r\n this.disconnected(new ConnectionEventArgs(connectionEvent.connectionId));\r\n }\r\n } else if (connectionEvent.name === \"ConnectionMessageSentEvent\") {\r\n if (!!this.messageSent) {\r\n this.messageSent(new ConnectionMessageEventArgs(new ConnectionMessageImpl((connectionEvent as ConnectionMessageSentEvent).message)));\r\n }\r\n } else if (connectionEvent.name === \"ConnectionMessageReceivedEvent\") {\r\n if (!!this.messageReceived) {\r\n this.messageReceived(new ConnectionMessageEventArgs(new ConnectionMessageImpl((connectionEvent as ConnectionMessageReceivedEvent).message)));\r\n }\r\n }\r\n });\r\n\r\n this.privServiceEventListener = this.privInternalData.serviceEvents.attach((e: ServiceEvent): void => {\r\n if (!!this.receivedServiceMessage) {\r\n this.receivedServiceMessage(new ServiceEventArgs(e.jsonString, e.name));\r\n }\r\n });\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n DynamicGrammarBuilder,\r\n ServiceRecognizerBase,\r\n} from \"../common.speech/Exports\";\r\nimport { Recognizer } from \"./Exports\";\r\n\r\n/**\r\n * Allows additions of new phrases to improve speech recognition.\r\n *\r\n * Phrases added to the recognizer are effective at the start of the next recognition, or the next time the SpeechSDK must reconnect\r\n * to the speech service.\r\n */\r\nexport class PhraseListGrammar {\r\n private privGrammerBuilder: DynamicGrammarBuilder;\r\n\r\n private constructor(recogBase: ServiceRecognizerBase) {\r\n this.privGrammerBuilder = recogBase.dynamicGrammar;\r\n }\r\n\r\n /**\r\n * Creates a PhraseListGrammar from a given speech recognizer. Will accept any recognizer that derives from @class Recognizer.\r\n * @param recognizer The recognizer to add phrase lists to.\r\n */\r\n public static fromRecognizer(recognizer: Recognizer): PhraseListGrammar {\r\n const recoBase: ServiceRecognizerBase = recognizer.internalData as ServiceRecognizerBase;\r\n\r\n return new PhraseListGrammar(recoBase);\r\n }\r\n\r\n /**\r\n * Adds a single phrase to the current recognizer.\r\n * @param phrase Phrase to add.\r\n */\r\n public addPhrase(phrase: string): void {\r\n this.privGrammerBuilder.addPhrase(phrase);\r\n }\r\n\r\n /**\r\n * Adds multiple phrases to the current recognizer.\r\n * @param phrases Array of phrases to add.\r\n */\r\n public addPhrases(phrases: string[]): void {\r\n this.privGrammerBuilder.addPhrase(phrases);\r\n }\r\n\r\n /**\r\n * Clears all phrases added to the current recognizer.\r\n */\r\n public clear(): void {\r\n this.privGrammerBuilder.clearPhrases();\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport { PropertyCollection, PropertyId, ServicePropertyChannel, SpeechConfigImpl } from \"./Exports\";\r\nimport { OutputFormat } from \"./OutputFormat\";\r\n\r\n/**\r\n * Class that defines base configurations for dialog service connector\r\n * @class DialogServiceConfig\r\n */\r\nexport abstract class DialogServiceConfig {\r\n\r\n /**\r\n * Creates an instance of DialogService config.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Sets an arbitrary property.\r\n * @member DialogServiceConfig.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to set.\r\n * @param {string} value - The new value of the property.\r\n */\r\n public abstract setProperty(name: string | PropertyId, value: string): void;\r\n\r\n /**\r\n * Returns the current value of an arbitrary property.\r\n * @member DialogServiceConfig.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to query.\r\n * @param {string} def - The value to return in case the property is not known.\r\n * @returns {string} The current value, or provided default, of the given property.\r\n */\r\n public abstract getProperty(name: string | PropertyId, def?: string): string;\r\n\r\n /**\r\n * @member DialogServiceConfig.prototype.setServiceProperty\r\n * @function\r\n * @public\r\n * @param {name} The name of the property.\r\n * @param {value} Value to set.\r\n * @param {channel} The channel used to pass the specified property to service.\r\n * @summary Sets a property value that will be passed to service using the specified channel.\r\n */\r\n public abstract setServiceProperty(name: string, value: string, channel: ServicePropertyChannel): void;\r\n\r\n /**\r\n * Sets the proxy configuration.\r\n * Only relevant in Node.js environments.\r\n * Added in version 1.4.0.\r\n * @param proxyHostName The host name of the proxy server.\r\n * @param proxyPort The port number of the proxy server.\r\n */\r\n public abstract setProxy(proxyHostName: string, proxyPort: number): void;\r\n\r\n /**\r\n * Sets the proxy configuration.\r\n * Only relevant in Node.js environments.\r\n * Added in version 1.4.0.\r\n * @param proxyHostName The host name of the proxy server, without the protocol scheme (http://)\r\n * @param porxyPort The port number of the proxy server.\r\n * @param proxyUserName The user name of the proxy server.\r\n * @param proxyPassword The password of the proxy server.\r\n */\r\n public abstract setProxy(proxyHostName: string, proxyPort: number, proxyUserName: string, proxyPassword: string): void;\r\n\r\n /**\r\n * Returns the configured language.\r\n * @member DialogServiceConfig.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n */\r\n public abstract get speechRecognitionLanguage(): string;\r\n\r\n /**\r\n * Gets/Sets the input language.\r\n * @member DialogServiceConfig.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The language to use for recognition.\r\n */\r\n public abstract set speechRecognitionLanguage(value: string);\r\n\r\n /**\r\n * Sets the corresponding backend application identifier.\r\n * @member DialogServiceConfig.prototype.Conversation_ApplicationId\r\n * @function\r\n * @public\r\n * @param {string} value - The application identifier to set.\r\n */\r\n // tslint:disable-next-line: no-empty\r\n public set applicationId(value: string) { }\r\n\r\n public static DialogTypes: any = class {\r\n public static BotFramework: string = \"bot_framework\";\r\n public static CustomCommands: string = \"custom_commands\";\r\n };\r\n}\r\n\r\n/**\r\n * Dialog Service configuration.\r\n * @class DialogServiceConfigImpl\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class DialogServiceConfigImpl extends DialogServiceConfig {\r\n\r\n private privSpeechConfig: SpeechConfigImpl;\r\n\r\n /**\r\n * Creates an instance of dialogService config.\r\n */\r\n public constructor() {\r\n super();\r\n this.privSpeechConfig = new SpeechConfigImpl();\r\n }\r\n\r\n /**\r\n * Provides access to custom properties.\r\n * @member DialogServiceConfigImpl.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The properties.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privSpeechConfig.properties;\r\n }\r\n\r\n /**\r\n * Gets the speech recognition language.\r\n * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n return this.privSpeechConfig.speechRecognitionLanguage;\r\n }\r\n\r\n /**\r\n * Sets the speech recognition language.\r\n * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The language to set.\r\n */\r\n public set speechRecognitionLanguage(value: string) {\r\n Contracts.throwIfNullOrWhitespace(value, \"value\");\r\n this.privSpeechConfig.speechRecognitionLanguage = value;\r\n }\r\n\r\n public get outputFormat(): OutputFormat {\r\n return this.privSpeechConfig.outputFormat;\r\n }\r\n\r\n public set outputFormat(value: OutputFormat) {\r\n this.privSpeechConfig.outputFormat = value;\r\n }\r\n\r\n /**\r\n * Sets a named property as value\r\n * @member DialogServiceConfigImpl.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {PropertyId | string} name - The property to set.\r\n * @param {string} value - The value.\r\n */\r\n public setProperty(name: string | PropertyId, value: string): void {\r\n this.privSpeechConfig.setProperty(name, value);\r\n }\r\n\r\n /**\r\n * Sets a named property as value\r\n * @member DialogServiceConfigImpl.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {PropertyId | string} name - The property to get.\r\n * @param {string} def - The default value to return in case the property is not known.\r\n * @returns {string} The current value, or provided default, of the given property.\r\n */\r\n public getProperty(name: string | PropertyId, def?: string): string {\r\n return this.privSpeechConfig.getProperty(name);\r\n }\r\n\r\n /**\r\n * Sets the proxy configuration.\r\n * Only relevant in Node.js environments.\r\n * Added in version 1.4.0.\r\n * @param proxyHostName The host name of the proxy server, without the protocol scheme (http://)\r\n * @param proxyPort The port number of the proxy server.\r\n * @param proxyUserName The user name of the proxy server.\r\n * @param proxyPassword The password of the proxy server.\r\n */\r\n public setProxy(proxyHostName: string, proxyPort: number, proxyUserName?: string, proxyPassword?: string): void {\r\n this.setProperty(PropertyId.SpeechServiceConnection_ProxyHostName, proxyHostName);\r\n this.setProperty(PropertyId.SpeechServiceConnection_ProxyPort, `${proxyPort}`);\r\n if (proxyUserName) {\r\n this.setProperty(PropertyId.SpeechServiceConnection_ProxyUserName, proxyUserName);\r\n }\r\n if (proxyPassword) {\r\n this.setProperty(PropertyId.SpeechServiceConnection_ProxyPassword, proxyPassword);\r\n }\r\n }\r\n\r\n public setServiceProperty(name: string, value: string, channel: ServicePropertyChannel): void {\r\n this.privSpeechConfig.setServiceProperty(name, value, channel);\r\n }\r\n\r\n /**\r\n * Dispose of associated resources.\r\n * @member DialogServiceConfigImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n return;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport { DialogServiceConfig, DialogServiceConfigImpl } from \"./DialogServiceConfig\";\r\nimport { PropertyId } from \"./Exports\";\r\n\r\n/**\r\n * Class that defines configurations for the dialog service connector object for using a Bot Framework backend.\r\n * @class BotFrameworkConfig\r\n */\r\nexport class BotFrameworkConfig extends DialogServiceConfigImpl {\r\n\r\n /**\r\n * Creates an instance of BotFrameworkConfig.\r\n */\r\n public constructor() {\r\n super();\r\n }\r\n\r\n /**\r\n * Creates a bot framework configuration instance with the provided subscription information.\r\n * @member BotFrameworkConfig.fromSubscription\r\n * @function\r\n * @public\r\n * @param subscription Subscription key associated with the bot\r\n * @param region The region name (see the region page).\r\n * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the\r\n * resource name.\r\n * @returns {BotFrameworkConfig} A new bot framework configuration instance.\r\n */\r\n public static fromSubscription(subscription: string, region: string, botId?: string): BotFrameworkConfig {\r\n Contracts.throwIfNullOrWhitespace(subscription, \"subscription\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const botFrameworkConfig: BotFrameworkConfig = new DialogServiceConfigImpl();\r\n botFrameworkConfig.setProperty(\r\n PropertyId.Conversation_DialogType,\r\n DialogServiceConfig.DialogTypes.BotFramework);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Key, subscription);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n\r\n if (botId) {\r\n botFrameworkConfig.setProperty(PropertyId.Conversation_ApplicationId, botId);\r\n }\r\n\r\n return botFrameworkConfig;\r\n }\r\n\r\n /**\r\n * Creates a bot framework configuration instance for the specified authorization token and region.\r\n * Note: The caller must ensure that an authorization token is valid. Before an authorization token expires, the\r\n * caller must refresh it by setting the authorizationToken property on the corresponding\r\n * DialogServiceConnector instance created with this config. The contents of configuration objects are copied\r\n * when connectors are created, so setting authorizationToken on a DialogServiceConnector will not update the\r\n * original configuration's authorization token. Create a new configuration instance or set the\r\n * SpeechServiceAuthorization_Token property to update an existing instance if it will be used to create\r\n * further DialogServiceConnectors.\r\n * @member BotFrameworkConfig.fromAuthorizationToken\r\n * @function\r\n * @public\r\n * @param authorizationToken The authorization token associated with the bot\r\n * @param region The region name (see the region page).\r\n * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the\r\n * resource name.\r\n * @returns {BotFrameworkConfig} A new bot framework configuration instance.\r\n */\r\n public static fromAuthorizationToken(\r\n authorizationToken: string, region: string, botId?: string\r\n ): BotFrameworkConfig {\r\n Contracts.throwIfNullOrWhitespace(authorizationToken, \"authorizationToken\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const botFrameworkConfig: BotFrameworkConfig = new DialogServiceConfigImpl();\r\n botFrameworkConfig.setProperty(\r\n PropertyId.Conversation_DialogType,\r\n DialogServiceConfig.DialogTypes.BotFramework);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceAuthorization_Token, authorizationToken);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n\r\n if (botId) {\r\n botFrameworkConfig.setProperty(PropertyId.Conversation_ApplicationId, botId);\r\n }\r\n\r\n return botFrameworkConfig;\r\n }\r\n\r\n /**\r\n * Creates an instance of a BotFrameworkConfig.\r\n * This method is intended only for users who use a non-default service host. The standard resource path will be\r\n * assumed. For services with a non-standard resource path or no path at all, use fromEndpoint instead.\r\n * Note: Query parameters are not allowed in the host URI and must be set by other APIs.\r\n * Note: To use an authorization token with fromHost, use fromHost(URL) and then set the AuthorizationToken\r\n * property on the created BotFrameworkConfig instance.\r\n * Note: Added in version 1.15.0.\r\n * @member BotFrameworkConfig.fromHost\r\n * @function\r\n * @public\r\n * @param {URL | string} host - If a URL is provided, the fully-qualified host with protocol (e.g.\r\n * wss://your.host.com:1234) will be used. If a string is provided, it will be embedded in\r\n * wss://{host}.convai.speech.azure.us.\r\n * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization\r\n * token must be set.\r\n * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the\r\n * resource name.\r\n * @returns {BotFrameworkConfig} A new bot framework configuration instance.\r\n */\r\n public static fromHost(\r\n host: URL | string,\r\n subscriptionKey?: string,\r\n botId?: string): BotFrameworkConfig {\r\n\r\n Contracts.throwIfNullOrUndefined(host, \"host\");\r\n const resolvedHost: URL = host instanceof URL ? host : new URL(`wss://${host}.convai.speech.azure.us`);\r\n Contracts.throwIfNullOrUndefined(resolvedHost, \"resolvedHost\");\r\n\r\n const botFrameworkConfig: BotFrameworkConfig = new DialogServiceConfigImpl();\r\n botFrameworkConfig.setProperty(\r\n PropertyId.Conversation_DialogType,\r\n DialogServiceConfig.DialogTypes.BotFramework);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Host, resolvedHost.toString());\r\n\r\n if (undefined !== subscriptionKey) {\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n }\r\n\r\n return botFrameworkConfig;\r\n }\r\n\r\n /**\r\n * Creates an instance of a BotFrameworkConfig.\r\n * This method is intended only for users who use a non-standard service endpoint or parameters.\r\n * Note: The query parameters specified in the endpoint URL are not changed, even if they are set by any other APIs.\r\n * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the\r\n * fromEndpoint method, and then set authorizationToken=\"token\" on the created BotFrameworkConfig instance to\r\n * use the authorization token.\r\n * Note: Added in version 1.15.0.\r\n * @member BotFrameworkConfig.fromEndpoint\r\n * @function\r\n * @public\r\n * @param {URL} endpoint - The service endpoint to connect to.\r\n * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization\r\n * token must be set.\r\n * @returns {BotFrameworkConfig} - A new bot framework configuration instance using the provided endpoint.\r\n */\r\n public static fromEndpoint(endpoint: URL, subscriptionKey?: string): BotFrameworkConfig {\r\n Contracts.throwIfNull(endpoint, \"endpoint\");\r\n\r\n const botFrameworkConfig: BotFrameworkConfig = new DialogServiceConfigImpl();\r\n botFrameworkConfig.setProperty(\r\n PropertyId.Conversation_DialogType,\r\n DialogServiceConfig.DialogTypes.BotFramework);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Endpoint, endpoint.toString());\r\n\r\n if (undefined !== subscriptionKey) {\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n }\r\n\r\n return botFrameworkConfig;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport { DialogServiceConfig, DialogServiceConfigImpl } from \"./DialogServiceConfig\";\r\nimport { PropertyId } from \"./Exports\";\r\n\r\n/**\r\n * Class that defines configurations for the dialog service connector object for using a CustomCommands backend.\r\n * @class CustomCommandsConfig\r\n */\r\nexport class CustomCommandsConfig extends DialogServiceConfigImpl {\r\n\r\n /**\r\n * Creates an instance of CustomCommandsConfig.\r\n */\r\n public constructor() {\r\n super();\r\n }\r\n\r\n /**\r\n * Creates an instance of the bot framework config with the specified subscription and region.\r\n * @member CustomCommandsConfig.fromSubscription\r\n * @function\r\n * @public\r\n * @param applicationId Speech Commands application id.\r\n * @param subscription Subscription key associated with the bot\r\n * @param region The region name (see the region page).\r\n * @returns {CustomCommandsConfig} A new bot framework config.\r\n */\r\n public static fromSubscription(applicationId: string, subscription: string, region: string): CustomCommandsConfig {\r\n Contracts.throwIfNullOrWhitespace(applicationId, \"applicationId\");\r\n Contracts.throwIfNullOrWhitespace(subscription, \"subscription\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const customCommandsConfig: CustomCommandsConfig = new DialogServiceConfigImpl();\r\n customCommandsConfig.setProperty(PropertyId.Conversation_DialogType, DialogServiceConfig.DialogTypes.CustomCommands);\r\n customCommandsConfig.setProperty(PropertyId.Conversation_ApplicationId, applicationId);\r\n customCommandsConfig.setProperty(PropertyId.SpeechServiceConnection_Key, subscription);\r\n customCommandsConfig.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n return customCommandsConfig;\r\n }\r\n\r\n /**\r\n * Creates an instance of the bot framework config with the specified Speech Commands application id, authorization token and region.\r\n * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token\r\n * expires, the caller needs to refresh it by calling this setter with a new valid token.\r\n * As configuration values are copied when creating a new recognizer, the new token value will not apply to recognizers that have already been created.\r\n * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer\r\n * to refresh the token. Otherwise, the recognizers will encounter errors during recognition.\r\n * @member CustomCommandsConfig.fromAuthorizationToken\r\n * @function\r\n * @public\r\n * @param applicationId Speech Commands application id.\r\n * @param authorizationToken The authorization token associated with the application.\r\n * @param region The region name (see the region page).\r\n * @returns {CustomCommandsConfig} A new speech commands config.\r\n */\r\n public static fromAuthorizationToken(applicationId: string, authorizationToken: string, region: string): CustomCommandsConfig {\r\n Contracts.throwIfNullOrWhitespace(applicationId, \"applicationId\");\r\n Contracts.throwIfNullOrWhitespace(authorizationToken, \"authorizationToken\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const customCommandsConfig: CustomCommandsConfig = new DialogServiceConfigImpl();\r\n customCommandsConfig.setProperty(PropertyId.Conversation_DialogType, DialogServiceConfig.DialogTypes.CustomCommands);\r\n customCommandsConfig.setProperty(PropertyId.Conversation_ApplicationId, applicationId);\r\n customCommandsConfig.setProperty(PropertyId.SpeechServiceAuthorization_Token, authorizationToken);\r\n customCommandsConfig.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n return customCommandsConfig;\r\n }\r\n\r\n /**\r\n * Sets the corresponding backend application identifier.\r\n * @member CustomCommandsConfig.prototype.Conversation_ApplicationId\r\n * @function\r\n * @public\r\n * @param {string} value - The application identifier to set.\r\n */\r\n public set applicationId(value: string) {\r\n Contracts.throwIfNullOrWhitespace(value, \"value\");\r\n this.setProperty(PropertyId.Conversation_ApplicationId, value);\r\n }\r\n\r\n /**\r\n * Gets the corresponding backend application identifier.\r\n * @member CustomCommandsConfig.prototype.Conversation_ApplicationId\r\n * @function\r\n * @public\r\n * @param {string} value - The application identifier to get.\r\n */\r\n public get applicationId(): string {\r\n return this.getProperty(PropertyId.Conversation_ApplicationId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport { OutputFormatPropertyName } from \"../common.speech/Exports\";\r\nimport { IConnection, IStringDictionary } from \"../common/Exports\";\r\nimport { DialogServiceConfig, OutputFormat, PropertyId } from \"../sdk/Exports\";\r\nimport { ConnectionFactoryBase } from \"./ConnectionFactoryBase\";\r\nimport { AuthInfo, RecognizerConfig, WebsocketMessageFormatter } from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { QueryParameterNames } from \"./QueryParameterNames\";\r\n\r\nexport class DialogConnectionFactory extends ConnectionFactoryBase {\r\n\r\n private static Constants: any = class {\r\n private static ApiKey: string = \"api\";\r\n private static BaseUrl: string = \"convai.speech\";\r\n };\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n const applicationId: string = config.parameters.getProperty(PropertyId.Conversation_ApplicationId, \"\");\r\n const dialogType: string = config.parameters.getProperty(PropertyId.Conversation_DialogType);\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region);\r\n const language: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, \"en-US\");\r\n const requestTurnStatus: string = config.parameters.getProperty(PropertyId.Conversation_Request_Bot_Status_Messages, \"true\");\r\n\r\n const queryParams: IStringDictionary = {};\r\n queryParams[HeaderNames.ConnectionId] = connectionId;\r\n queryParams[QueryParameterNames.Format] = config.parameters.getProperty(OutputFormatPropertyName, OutputFormat[OutputFormat.Simple]).toLowerCase();\r\n queryParams[QueryParameterNames.Language] = language;\r\n queryParams[QueryParameterNames.RequestBotStatusMessages] = requestTurnStatus;\r\n if (applicationId) {\r\n queryParams[QueryParameterNames.BotId] = applicationId;\r\n if (dialogType === DialogServiceConfig.DialogTypes.CustomCommands) {\r\n queryParams[HeaderNames.CustomCommandsAppId] = applicationId;\r\n }\r\n }\r\n\r\n const resourceInfix: string =\r\n dialogType === DialogServiceConfig.DialogTypes.CustomCommands ? \"commands/\"\r\n : \"\";\r\n const version: string =\r\n dialogType === DialogServiceConfig.DialogTypes.CustomCommands ? \"v1\"\r\n : dialogType === DialogServiceConfig.DialogTypes.BotFramework ? \"v3\"\r\n : \"v0\";\r\n\r\n const headers: IStringDictionary = {};\r\n\r\n if (authInfo.token != null && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n\r\n // The URL used for connection is chosen in a priority order of specification:\r\n // 1. If a custom endpoint is provided, that URL is used verbatim.\r\n // 2. If a custom host is provided (e.g. \"wss://my.custom.endpoint.com:1123\"), a URL is constructed from it.\r\n // 3. If no custom connection details are provided, a URL is constructed from default values.\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, \"\");\r\n if (!endpoint) {\r\n const hostSuffix = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(\r\n PropertyId.SpeechServiceConnection_Host,\r\n `wss://${region}.${DialogConnectionFactory.Constants.BaseUrl}${hostSuffix}`);\r\n const standardizedHost: string = host.endsWith(\"/\") ? host : host + \"/\";\r\n endpoint = `${standardizedHost}${resourceInfix}${DialogConnectionFactory.Constants.ApiKey}/${version}`;\r\n }\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { AgentConfig } from \"../common.speech/Exports\";\r\nimport { EventType, PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class DialogEvent extends PlatformEvent {\r\n\r\n constructor(eventName: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n }\r\n}\r\n\r\nexport class SendingAgentContextMessageEvent extends DialogEvent {\r\n private privAgentConfig: AgentConfig;\r\n\r\n constructor(agentConfig: AgentConfig) {\r\n super(\"SendingAgentContextMessageEvent\");\r\n this.privAgentConfig = agentConfig;\r\n }\r\n\r\n public get agentConfig(): AgentConfig {\r\n return this.privAgentConfig;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PullAudioOutputStream } from \"./Audio/AudioOutputStream\";\r\n\r\n/**\r\n * Defines contents of received message/events.\r\n * @class ActivityReceivedEventArgs\r\n */\r\nexport class ActivityReceivedEventArgs {\r\n private privActivity: any;\r\n private privAudioStream: PullAudioOutputStream;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {any} activity - The activity..\r\n */\r\n public constructor(activity: any, audioStream?: PullAudioOutputStream) {\r\n this.privActivity = activity;\r\n this.privAudioStream = audioStream;\r\n }\r\n\r\n /**\r\n * Gets the received activity\r\n * @member ActivityReceivedEventArgs.prototype.activity\r\n * @function\r\n * @public\r\n * @returns {any} the received activity.\r\n */\r\n public get activity(): any {\r\n return this.privActivity;\r\n }\r\n\r\n public get audioStream(): PullAudioOutputStream {\r\n return this.privAudioStream;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport interface ITurnStatusResponsePayload {\r\n interactionId: string;\r\n conversationId: string;\r\n statusCode: any;\r\n}\r\n\r\nexport class TurnStatusResponsePayload implements ITurnStatusResponsePayload {\r\n private privMessageStatusResponse: ITurnStatusResponsePayload;\r\n\r\n private constructor(json: string) {\r\n this.privMessageStatusResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): TurnStatusResponsePayload {\r\n return new TurnStatusResponsePayload(json);\r\n }\r\n\r\n public get interactionId(): string {\r\n return this.privMessageStatusResponse.interactionId;\r\n }\r\n\r\n public get conversationId(): string {\r\n return this.privMessageStatusResponse.conversationId;\r\n }\r\n\r\n public get statusCode(): any {\r\n // Payloads may contain a limited set of textual representations or a numeric status\r\n // code. The textual values are here converted into numeric ones.\r\n switch (this.privMessageStatusResponse.statusCode) {\r\n case \"Success\":\r\n return 200;\r\n case \"Failed\":\r\n return 400;\r\n case \"TimedOut\":\r\n return 429;\r\n default:\r\n return this.privMessageStatusResponse.statusCode;\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ITurnStatusResponsePayload,\r\n TurnStatusResponsePayload\r\n } from \"../common.speech/ServiceMessages/TurnStatusPayload\";\r\n\r\n/**\r\n * Defines contents of received message/events.\r\n * @class TurnStatusReceivedEventArgs\r\n */\r\nexport class TurnStatusReceivedEventArgs {\r\n private privTurnStatus: ITurnStatusResponsePayload;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {string} turnStatus - The JSON-encoded turn status message.\r\n */\r\n public constructor(turnStatus: string) {\r\n this.privTurnStatus = TurnStatusResponsePayload.fromJSON(turnStatus);\r\n }\r\n\r\n /**\r\n * Gets the interaction identifier associated with this turn status event.\r\n * @member TurnStatusReceivedEventArgs.prototype.interactionId\r\n * @function\r\n * @public\r\n * @returns {any} the received interaction id.\r\n */\r\n public get interactionId(): any {\r\n return this.privTurnStatus.interactionId;\r\n }\r\n\r\n /**\r\n * Gets the conversation identifier associated with this turn status event.\r\n * @member TurnStatusReceivedEventArgs.prototype.conversationId\r\n * @function\r\n * @public\r\n * @returns {any} the received conversation id.\r\n */\r\n public get conversationId(): any {\r\n return this.privTurnStatus.conversationId;\r\n }\r\n\r\n /**\r\n * Gets the received turn status code.\r\n * @member TurnStatusReceivedEventArgs.prototype.statusCode\r\n * @function\r\n * @public\r\n * @returns {number} the received turn status.\r\n */\r\n public get statusCode(): number {\r\n return this.privTurnStatus.statusCode;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport { AudioOutputStream, PullAudioOutputStreamImpl } from \"../sdk/Audio/AudioOutputStream\";\r\nimport { DialogServiceTurnStateManager } from \"./DialogServiceTurnStateManager\";\r\nimport { ActivityPayloadResponse, MessageDataStreamType } from \"./ServiceMessages/ActivityResponsePayload\";\r\n\r\nexport class DialogServiceTurnState {\r\n private privRequestId: string;\r\n private privIsCompleted: boolean;\r\n private privAudioStream: PullAudioOutputStreamImpl;\r\n private privTimeoutToken: any;\r\n private privTurnManager: DialogServiceTurnStateManager;\r\n\r\n constructor(manager: DialogServiceTurnStateManager, requestId: string) {\r\n this.privRequestId = requestId;\r\n this.privIsCompleted = false;\r\n this.privAudioStream = null;\r\n this.privTurnManager = manager;\r\n this.resetTurnEndTimeout();\r\n // tslint:disable-next-line:no-console\r\n // console.info(\"DialogServiceTurnState debugturn start:\" + this.privRequestId);\r\n }\r\n\r\n public get audioStream(): PullAudioOutputStreamImpl {\r\n // Called when is needed to stream.\r\n this.resetTurnEndTimeout();\r\n return this.privAudioStream;\r\n }\r\n\r\n public processActivityPayload(payload: ActivityPayloadResponse, audioFormat?: AudioOutputFormatImpl): PullAudioOutputStreamImpl {\r\n if (payload.messageDataStreamType === MessageDataStreamType.TextToSpeechAudio) {\r\n this.privAudioStream = AudioOutputStream.createPullStream() as PullAudioOutputStreamImpl;\r\n this.privAudioStream.format = (audioFormat !== undefined) ? audioFormat : AudioOutputFormatImpl.getDefaultOutputFormat();\r\n // tslint:disable-next-line:no-console\r\n // console.info(\"Audio start debugturn:\" + this.privRequestId);\r\n }\r\n return this.privAudioStream;\r\n }\r\n\r\n public endAudioStream(): void {\r\n if (this.privAudioStream !== null && !this.privAudioStream.isClosed) {\r\n this.privAudioStream.close();\r\n }\r\n }\r\n\r\n public complete(): void {\r\n if (this.privTimeoutToken !== undefined) {\r\n clearTimeout(this.privTimeoutToken);\r\n }\r\n this.endAudioStream();\r\n }\r\n\r\n private resetTurnEndTimeout(): void {\r\n if (this.privTimeoutToken !== undefined) {\r\n clearTimeout(this.privTimeoutToken);\r\n }\r\n // tslint:disable-next-line:no-console\r\n // console.info(\"Timeout reset debugturn:\" + this.privRequestId);\r\n\r\n this.privTimeoutToken = setTimeout((): void => {\r\n // tslint:disable-next-line:no-console\r\n // console.info(\"Timeout complete debugturn:\" + this.privRequestId);\r\n\r\n this.privTurnManager.CompleteTurn(this.privRequestId);\r\n return;\r\n }, 2000);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError } from \"../common/Error\";\r\nimport { AudioOutputStream, PullAudioOutputStreamImpl } from \"../sdk/Audio/AudioOutputStream\";\r\nimport { DialogServiceTurnState } from \"./DialogServiceTurnState\";\r\nimport { ActivityPayloadResponse } from \"./ServiceMessages/ActivityResponsePayload\";\r\n\r\nexport class DialogServiceTurnStateManager {\r\n private privTurnMap: Map;\r\n\r\n constructor() {\r\n this.privTurnMap = new Map();\r\n return;\r\n }\r\n\r\n public StartTurn(id: string): DialogServiceTurnState {\r\n if (this.privTurnMap.has(id)) {\r\n throw new InvalidOperationError(\"Service error: There is already a turn with id:\" + id);\r\n }\r\n const turnState: DialogServiceTurnState = new DialogServiceTurnState(this, id);\r\n this.privTurnMap.set(id, turnState);\r\n return this.privTurnMap.get(id);\r\n }\r\n\r\n public GetTurn(id: string): DialogServiceTurnState {\r\n return this.privTurnMap.get(id);\r\n }\r\n\r\n public CompleteTurn(id: string): DialogServiceTurnState {\r\n if (!this.privTurnMap.has(id)) {\r\n throw new InvalidOperationError(\"Service error: Received turn end for an unknown turn id:\" + id);\r\n }\r\n const turnState = this.privTurnMap.get(id);\r\n turnState.complete();\r\n this.privTurnMap.delete(id);\r\n return turnState;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// speech.keyword\r\nexport interface ISpeechKeyword {\r\n Status: string;\r\n Text: string;\r\n Offset: number;\r\n Duration: number;\r\n}\r\n\r\nexport class SpeechKeyword implements ISpeechKeyword {\r\n private privSpeechKeyword: ISpeechKeyword;\r\n\r\n private constructor(json: string) {\r\n this.privSpeechKeyword = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SpeechKeyword {\r\n return new SpeechKeyword(json);\r\n }\r\n\r\n public get Status(): string {\r\n return this.privSpeechKeyword.Status;\r\n }\r\n\r\n public get Text(): string {\r\n return this.privSpeechKeyword.Text;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privSpeechKeyword.Offset;\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privSpeechKeyword.Duration;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ReplayableAudioNode\r\n} from \"../common.browser/Exports\";\r\nimport { SendingAgentContextMessageEvent } from \"../common/DialogEvents\";\r\nimport {\r\n BackgroundEvent,\r\n ConnectionEvent,\r\n ConnectionMessage,\r\n createGuid,\r\n createNoDashGuid,\r\n Deferred,\r\n DialogEvent,\r\n Events,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IConnection,\r\n MessageType,\r\n ServiceEvent,\r\n} from \"../common/Exports\";\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport { PullAudioOutputStreamImpl } from \"../sdk/Audio/AudioOutputStream\";\r\nimport { AudioStreamFormatImpl } from \"../sdk/Audio/AudioStreamFormat\";\r\nimport {\r\n ActivityReceivedEventArgs,\r\n CancellationErrorCode,\r\n CancellationReason,\r\n DialogServiceConfig,\r\n DialogServiceConnector,\r\n PropertyCollection,\r\n PropertyId,\r\n RecognitionEventArgs,\r\n ResultReason,\r\n SessionEventArgs,\r\n SpeechRecognitionCanceledEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult,\r\n TurnStatusReceivedEventArgs,\r\n} from \"../sdk/Exports\";\r\nimport { DialogServiceTurnStateManager } from \"./DialogServiceTurnStateManager\";\r\nimport {\r\n CancellationErrorCodePropertyName,\r\n EnumTranslation,\r\n ISpeechConfigAudioDevice,\r\n RecognitionStatus,\r\n ServiceRecognizerBase,\r\n SimpleSpeechPhrase,\r\n SpeechDetected,\r\n SpeechHypothesis,\r\n SpeechKeyword,\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognitionMode, RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { ActivityPayloadResponse } from \"./ServiceMessages/ActivityResponsePayload\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\nexport class DialogServiceAdapter extends ServiceRecognizerBase {\r\n private privDialogServiceConnector: DialogServiceConnector;\r\n\r\n private privDialogAudioSource: IAudioSource;\r\n\r\n private privConnectionLoop: Promise;\r\n private terminateMessageLoop: boolean;\r\n private agentConfigSent: boolean;\r\n private privLastResult: SpeechRecognitionResult;\r\n private privEvents: EventSource;\r\n\r\n // Turns are of two kinds:\r\n // 1: SR turns, end when the SR result is returned and then turn end.\r\n // 2: Service turns where an activity is sent by the service along with the audio.\r\n private privTurnStateManager: DialogServiceTurnStateManager;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n dialogServiceConnector: DialogServiceConnector) {\r\n\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector);\r\n\r\n this.privEvents = new EventSource();\r\n this.privDialogServiceConnector = dialogServiceConnector;\r\n this.receiveMessageOverride = this.receiveDialogMessageOverride;\r\n this.privTurnStateManager = new DialogServiceTurnStateManager();\r\n this.recognizeOverride = this.listenOnce;\r\n this.postConnectImplOverride = this.dialogConnectImpl;\r\n this.configConnectionOverride = this.configConnection;\r\n this.disconnectOverride = this.privDisconnect;\r\n this.privDialogAudioSource = audioSource;\r\n\r\n this.agentConfigSent = false;\r\n this.privLastResult = null;\r\n this.connectionEvents.attach(async (connectionEvent: ConnectionEvent): Promise => {\r\n if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n this.terminateMessageLoop = true;\r\n }\r\n });\r\n }\r\n\r\n public async sendMessage(message: string): Promise {\r\n const interactionGuid: string = createGuid();\r\n const requestId: string = createNoDashGuid();\r\n\r\n const agentMessage: any = {\r\n context: {\r\n interactionId: interactionGuid\r\n },\r\n messagePayload: JSON.parse(message),\r\n version: 0.5\r\n };\r\n\r\n const agentMessageJson = JSON.stringify(agentMessage);\r\n const connection: IConnection = await this.fetchConnection();\r\n await connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"agent\",\r\n requestId,\r\n \"application/json\",\r\n agentMessageJson));\r\n\r\n }\r\n\r\n protected async privDisconnect(): Promise {\r\n await this.cancelRecognition(this.privRequestSession.sessionId,\r\n this.privRequestSession.requestId,\r\n CancellationReason.Error,\r\n CancellationErrorCode.NoError,\r\n \"Disconnecting\");\r\n\r\n this.terminateMessageLoop = true;\r\n this.agentConfigSent = false;\r\n return;\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n if (connectionMessage.messageType === MessageType.Text) {\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n }\r\n\r\n let result: SpeechRecognitionResult;\r\n let processed: boolean;\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"speech.phrase\":\r\n const speechPhrase: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n\r\n this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + speechPhrase.Offset + speechPhrase.Duration);\r\n\r\n if (speechPhrase.RecognitionStatus !== RecognitionStatus.TooManyRequests && speechPhrase.RecognitionStatus !== RecognitionStatus.Error) {\r\n const args: SpeechRecognitionEventArgs = this.fireEventForResult(speechPhrase, resultProps);\r\n this.privLastResult = args.result;\r\n\r\n if (!!this.privDialogServiceConnector.recognized) {\r\n try {\r\n this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, args);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.hypothesis\":\r\n const hypothesis: SpeechHypothesis = SpeechHypothesis.fromJSON(connectionMessage.textBody);\r\n const offset: number = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n ResultReason.RecognizingSpeech,\r\n hypothesis.Text,\r\n hypothesis.Duration,\r\n offset,\r\n hypothesis.Language,\r\n hypothesis.LanguageDetectionConfidence,\r\n undefined,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n this.privRequestSession.onHypothesis(offset);\r\n\r\n const ev = new SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privDialogServiceConnector.recognizing) {\r\n try {\r\n this.privDialogServiceConnector.recognizing(this.privDialogServiceConnector, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.keyword\":\r\n const keyword: SpeechKeyword = SpeechKeyword.fromJSON(connectionMessage.textBody);\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n keyword.Status === \"Accepted\" ? ResultReason.RecognizedKeyword : ResultReason.NoMatch,\r\n keyword.Text,\r\n keyword.Duration,\r\n keyword.Offset,\r\n undefined,\r\n undefined,\r\n undefined,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n if (keyword.Status !== \"Accepted\") {\r\n this.privLastResult = result;\r\n }\r\n\r\n const event = new SpeechRecognitionEventArgs(result, result.duration, result.resultId);\r\n\r\n if (!!this.privDialogServiceConnector.recognized) {\r\n try {\r\n this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, event);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"audio\":\r\n {\r\n const audioRequestId = connectionMessage.requestId.toUpperCase();\r\n const turn = this.privTurnStateManager.GetTurn(audioRequestId);\r\n try {\r\n // Empty binary message signals end of stream.\r\n if (!connectionMessage.binaryBody) {\r\n turn.endAudioStream();\r\n } else {\r\n turn.audioStream.write(connectionMessage.binaryBody);\r\n }\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n\r\n case \"response\":\r\n {\r\n this.handleResponseMessage(connectionMessage);\r\n\r\n }\r\n processed = true;\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected async cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): Promise {\r\n\r\n this.terminateMessageLoop = true;\r\n\r\n if (!!this.privRequestSession.isRecognizing) {\r\n await this.privRequestSession.onStopRecognizing();\r\n }\r\n\r\n if (!!this.privDialogServiceConnector.canceled) {\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n const cancelEvent: SpeechRecognitionCanceledEventArgs = new SpeechRecognitionCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n sessionId);\r\n\r\n try {\r\n this.privDialogServiceConnector.canceled(this.privDialogServiceConnector, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: SpeechRecognitionResult = new SpeechRecognitionResult(\r\n undefined, // ResultId\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Duration\r\n undefined, // Offset\r\n undefined, // Language\r\n undefined, // Language Detection Confidence\r\n undefined, // Speaker Id\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n this.privSuccessCallback = undefined;\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n }\r\n\r\n protected async listenOnce(\r\n recoMode: RecognitionMode,\r\n successCallback: (e: SpeechRecognitionResult) => void,\r\n errorCallback: (e: string) => void\r\n ): Promise {\r\n this.privRecognizerConfig.recognitionMode = recoMode;\r\n\r\n this.privSuccessCallback = successCallback;\r\n this.privErrorCallback = errorCallback;\r\n\r\n this.privRequestSession.startNewRecognition();\r\n this.privRequestSession.listenForServiceTelemetry(this.privDialogAudioSource.events);\r\n\r\n this.privRecognizerConfig.parameters.setProperty(PropertyId.Speech_SessionId, this.privRequestSession.sessionId);\r\n\r\n // Start the connection to the service. The promise this will create is stored and will be used by configureConnection().\r\n const conPromise: Promise = this.connectImpl();\r\n\r\n const preAudioPromise: Promise = this.sendPreAudioMessages();\r\n\r\n const node: IAudioStreamNode = await this.privDialogAudioSource.attach(this.privRequestSession.audioNodeId);\r\n const format: AudioStreamFormatImpl = await this.privDialogAudioSource.format;\r\n const deviceInfo: ISpeechConfigAudioDevice = await this.privDialogAudioSource.deviceInfo;\r\n\r\n const audioNode = new ReplayableAudioNode(node, format.avgBytesPerSec);\r\n await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false);\r\n\r\n this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };\r\n\r\n try {\r\n await conPromise;\r\n await preAudioPromise;\r\n } catch (error) {\r\n await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, CancellationReason.Error, CancellationErrorCode.ConnectionFailure, error);\r\n return Promise.resolve();\r\n }\r\n\r\n const sessionStartEventArgs: SessionEventArgs = new SessionEventArgs(this.privRequestSession.sessionId);\r\n\r\n if (!!this.privRecognizer.sessionStarted) {\r\n this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);\r\n }\r\n\r\n const audioSendPromise = this.sendAudio(audioNode);\r\n\r\n // /* tslint:disable:no-empty */\r\n audioSendPromise.then(() => { /*add? return true;*/ }, async (error: string) => {\r\n await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, CancellationReason.Error, CancellationErrorCode.RuntimeError, error);\r\n });\r\n }\r\n\r\n // Establishes a websocket connection to the end point.\r\n private dialogConnectImpl(connection: Promise): Promise {\r\n this.privConnectionLoop = this.startMessageLoop();\r\n return connection;\r\n }\r\n\r\n private receiveDialogMessageOverride(): Promise {\r\n\r\n // we won't rely on the cascading promises of the connection since we want to continually be available to receive messages\r\n const communicationCustodian: Deferred = new Deferred();\r\n\r\n const loop = async (): Promise => {\r\n try {\r\n const isDisposed: boolean = this.isDisposed();\r\n const terminateMessageLoop = (!this.isDisposed() && this.terminateMessageLoop);\r\n if (isDisposed || terminateMessageLoop) {\r\n // We're done.\r\n communicationCustodian.resolve(undefined);\r\n return;\r\n }\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n const message: ConnectionMessage = await connection.read();\r\n\r\n if (!message) {\r\n return loop();\r\n }\r\n\r\n const connectionMessage = SpeechConnectionMessage.fromConnectionMessage(message);\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"turn.start\":\r\n {\r\n const turnRequestId = connectionMessage.requestId.toUpperCase();\r\n const audioSessionReqId = this.privRequestSession.requestId.toUpperCase();\r\n\r\n // turn started by the service\r\n if (turnRequestId !== audioSessionReqId) {\r\n this.privTurnStateManager.StartTurn(turnRequestId);\r\n } else {\r\n this.privRequestSession.onServiceTurnStartResponse();\r\n }\r\n }\r\n break;\r\n\r\n case \"speech.startdetected\":\r\n const speechStartDetected: SpeechDetected = SpeechDetected.fromJSON(connectionMessage.textBody);\r\n\r\n const speechStartEventArgs = new RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privRecognizer.speechStartDetected) {\r\n this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs);\r\n }\r\n\r\n break;\r\n\r\n case \"speech.enddetected\":\r\n\r\n let json: string;\r\n\r\n if (connectionMessage.textBody.length > 0) {\r\n json = connectionMessage.textBody;\r\n } else {\r\n // If the request was empty, the JSON returned is empty.\r\n json = \"{ Offset: 0 }\";\r\n }\r\n\r\n const speechStopDetected: SpeechDetected = SpeechDetected.fromJSON(json);\r\n\r\n this.privRequestSession.onServiceRecognized(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset);\r\n\r\n const speechStopEventArgs = new RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privRecognizer.speechEndDetected) {\r\n this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs);\r\n }\r\n break;\r\n\r\n case \"turn.end\":\r\n {\r\n const turnEndRequestId = connectionMessage.requestId.toUpperCase();\r\n\r\n const audioSessionReqId = this.privRequestSession.requestId.toUpperCase();\r\n\r\n // turn started by the service\r\n if (turnEndRequestId !== audioSessionReqId) {\r\n this.privTurnStateManager.CompleteTurn(turnEndRequestId);\r\n } else {\r\n // Audio session turn\r\n\r\n const sessionStopEventArgs: SessionEventArgs = new SessionEventArgs(this.privRequestSession.sessionId);\r\n await this.privRequestSession.onServiceTurnEndResponse(false);\r\n\r\n if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) {\r\n if (!!this.privRecognizer.sessionStopped) {\r\n this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs);\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback && this.privLastResult) {\r\n try {\r\n this.privSuccessCallback(this.privLastResult);\r\n this.privLastResult = null;\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n }\r\n }\r\n break;\r\n\r\n default:\r\n if (!this.processTypeSpecificMessages(connectionMessage)) {\r\n if (!!this.serviceEvents) {\r\n this.serviceEvents.onEvent(new ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));\r\n }\r\n }\r\n }\r\n const ret: Promise = loop();\r\n\r\n return ret;\r\n } catch (error) {\r\n this.terminateMessageLoop = true;\r\n communicationCustodian.resolve();\r\n }\r\n };\r\n\r\n loop().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n\r\n return communicationCustodian.promise;\r\n }\r\n\r\n private async startMessageLoop(): Promise {\r\n\r\n this.terminateMessageLoop = false;\r\n\r\n try {\r\n await this.receiveDialogMessageOverride();\r\n } catch (error) {\r\n await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, CancellationReason.Error, CancellationErrorCode.RuntimeError, error);\r\n }\r\n\r\n return Promise.resolve();\r\n }\r\n\r\n // Takes an established websocket connection to the endpoint and sends speech configuration information.\r\n private async configConnection(connection: IConnection): Promise {\r\n if (this.terminateMessageLoop) {\r\n this.terminateMessageLoop = false;\r\n return Promise.reject(`Connection to service terminated.`);\r\n }\r\n\r\n await this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize());\r\n await this.sendAgentConfig(connection);\r\n return connection;\r\n }\r\n\r\n private async sendPreAudioMessages(): Promise {\r\n const connection: IConnection = await this.fetchConnection();\r\n this.addKeywordContextData();\r\n await this.sendSpeechContext(connection);\r\n await this.sendAgentContext(connection);\r\n await this.sendWaveHeader(connection);\r\n }\r\n\r\n private sendAgentConfig = (connection: IConnection): Promise => {\r\n if (this.agentConfig && !this.agentConfigSent) {\r\n\r\n if (this.privRecognizerConfig\r\n .parameters\r\n .getProperty(PropertyId.Conversation_DialogType) === DialogServiceConfig.DialogTypes.CustomCommands) {\r\n const config = this.agentConfig.get();\r\n config.botInfo.commandsCulture = this.privRecognizerConfig.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, \"en-us\");\r\n this.agentConfig.set(config);\r\n }\r\n this.onEvent(new SendingAgentContextMessageEvent(this.agentConfig));\r\n\r\n const agentConfigJson = this.agentConfig.toJsonString();\r\n\r\n // guard against sending this multiple times on one connection\r\n this.agentConfigSent = true;\r\n\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"agent.config\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n agentConfigJson));\r\n }\r\n\r\n return;\r\n }\r\n\r\n private sendAgentContext = (connection: IConnection): Promise => {\r\n const guid: string = createGuid();\r\n\r\n const speechActivityTemplate = this.privDialogServiceConnector.properties.getProperty(PropertyId.Conversation_Speech_Activity_Template);\r\n\r\n const agentContext: any = {\r\n channelData: \"\",\r\n context: {\r\n interactionId: guid\r\n },\r\n messagePayload: typeof speechActivityTemplate === undefined ? undefined : speechActivityTemplate,\r\n version: 0.5\r\n };\r\n\r\n const agentContextJson = JSON.stringify(agentContext);\r\n\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.agent.context\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n agentContextJson));\r\n }\r\n\r\n private fireEventForResult(serviceResult: SimpleSpeechPhrase, properties: PropertyCollection): SpeechRecognitionEventArgs {\r\n const resultReason: ResultReason = EnumTranslation.implTranslateRecognitionResult(serviceResult.RecognitionStatus);\r\n\r\n const offset: number = serviceResult.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n const result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n serviceResult.DisplayText,\r\n serviceResult.Duration,\r\n offset,\r\n serviceResult.Language,\r\n serviceResult.LanguageDetectionConfidence,\r\n undefined,\r\n undefined,\r\n JSON.stringify(serviceResult),\r\n properties);\r\n\r\n const ev = new SpeechRecognitionEventArgs(result, offset, this.privRequestSession.sessionId);\r\n return ev;\r\n }\r\n\r\n private handleResponseMessage = (responseMessage: SpeechConnectionMessage): void => {\r\n // \"response\" messages can contain either \"message\" (activity) or \"MessageStatus\" data. Fire the appropriate\r\n // event according to the message type that's specified.\r\n const responsePayload = JSON.parse(responseMessage.textBody);\r\n switch (responsePayload.messageType.toLowerCase()) {\r\n case \"message\":\r\n const responseRequestId = responseMessage.requestId.toUpperCase();\r\n const activityPayload: ActivityPayloadResponse = ActivityPayloadResponse.fromJSON(responseMessage.textBody);\r\n const turn = this.privTurnStateManager.GetTurn(responseRequestId);\r\n\r\n // update the conversation Id\r\n if (activityPayload.conversationId) {\r\n const updateAgentConfig = this.agentConfig.get();\r\n updateAgentConfig.botInfo.conversationId = activityPayload.conversationId;\r\n this.agentConfig.set(updateAgentConfig);\r\n }\r\n\r\n const pullAudioOutputStream: PullAudioOutputStreamImpl = turn.processActivityPayload(\r\n activityPayload,\r\n AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(this.privDialogServiceConnector.properties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)));\r\n const activity = new ActivityReceivedEventArgs(activityPayload.messagePayload, pullAudioOutputStream);\r\n if (!!this.privDialogServiceConnector.activityReceived) {\r\n try {\r\n this.privDialogServiceConnector.activityReceived(this.privDialogServiceConnector, activity);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n\r\n case \"messagestatus\":\r\n if (!!this.privDialogServiceConnector.turnStatusReceived) {\r\n try {\r\n this.privDialogServiceConnector.turnStatusReceived(\r\n this.privDialogServiceConnector,\r\n new TurnStatusReceivedEventArgs(responseMessage.textBody));\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n\r\n default:\r\n Events.instance.onEvent(\r\n new BackgroundEvent(`Unexpected response of type ${responsePayload.messageType}. Ignoring.`));\r\n break;\r\n }\r\n }\r\n\r\n private onEvent(event: DialogEvent): void {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private addKeywordContextData(): void {\r\n const keywordPropertyValue: string = this.privRecognizerConfig.parameters.getProperty(\"SPEECH-KeywordsToDetect\");\r\n if (keywordPropertyValue === undefined) {\r\n return;\r\n }\r\n\r\n const keywordOffsetPropertyValue: string = this.privRecognizerConfig.parameters\r\n .getProperty(\"SPEECH-KeywordsToDetect-Offsets\");\r\n const keywordDurationPropertyValue: string = this.privRecognizerConfig.parameters\r\n .getProperty(\"SPEECH-KeywordsToDetect-Durations\");\r\n\r\n const keywords = keywordPropertyValue.split(\";\");\r\n const keywordOffsets = keywordOffsetPropertyValue === undefined ? [] : keywordOffsetPropertyValue.split(\";\");\r\n const keywordDurations = keywordDurationPropertyValue === undefined ? [] : keywordDurationPropertyValue.split(\";\");\r\n\r\n const keywordDefinitionArray = [];\r\n for (let i = 0; i < keywords.length; i++) {\r\n const definition: { [section: string]: any } = {};\r\n definition.text = keywords[i];\r\n if (i < keywordOffsets.length) {\r\n definition.offset = Number(keywordOffsets[i]);\r\n }\r\n if (i < keywordDurations.length) {\r\n definition.duration = Number(keywordDurations[i]);\r\n }\r\n keywordDefinitionArray.push(definition);\r\n }\r\n\r\n this.speechContext.setSection(\"invocationSource\", \"VoiceActivationWithKeyword\");\r\n this.speechContext.setSection(\"keywordDetection\", [{\r\n clientDetectedKeywords: keywordDefinitionArray,\r\n onReject: { action: \"EndOfTurn\" },\r\n type: \"startTrigger\"\r\n }]);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines channels used to pass property settings to service.\r\n * Added in version 1.7.0.\r\n */\r\nexport enum ServicePropertyChannel {\r\n /**\r\n * Uses URI query parameter to pass property settings to service.\r\n */\r\n UriQueryParameter = 0.\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { DialogConnectionFactory } from \"../common.speech/DialogConnectorFactory\";\r\nimport {\r\n DialogServiceAdapter,\r\n IAgentConfig,\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n Deferred,\r\n marshalPromiseToCallbacks\r\n} from \"../common/Exports\";\r\nimport { ActivityReceivedEventArgs } from \"./ActivityReceivedEventArgs\";\r\nimport { AudioConfigImpl } from \"./Audio/AudioConfig\";\r\nimport { AudioOutputFormatImpl } from \"./Audio/AudioOutputFormat\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport { DialogServiceConfig, DialogServiceConfigImpl } from \"./DialogServiceConfig\";\r\nimport {\r\n AudioConfig,\r\n PropertyCollection,\r\n Recognizer,\r\n SpeechRecognitionCanceledEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult\r\n} from \"./Exports\";\r\nimport { PropertyId } from \"./PropertyId\";\r\nimport { TurnStatusReceivedEventArgs } from \"./TurnStatusReceivedEventArgs\";\r\n\r\n/**\r\n * Dialog Service Connector\r\n * @class DialogServiceConnector\r\n */\r\nexport class DialogServiceConnector extends Recognizer {\r\n private privIsDisposed: boolean;\r\n private isTurnComplete: boolean;\r\n\r\n /**\r\n * Initializes an instance of the DialogServiceConnector.\r\n * @constructor\r\n * @param {DialogServiceConfig} dialogConfig - Set of properties to configure this recognizer.\r\n * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer\r\n */\r\n public constructor(dialogConfig: DialogServiceConfig, audioConfig?: AudioConfig) {\r\n const dialogServiceConfigImpl = dialogConfig as DialogServiceConfigImpl;\r\n Contracts.throwIfNull(dialogConfig, \"dialogConfig\");\r\n\r\n super(audioConfig, dialogServiceConfigImpl.properties, new DialogConnectionFactory());\r\n\r\n this.isTurnComplete = true;\r\n this.privIsDisposed = false;\r\n this.privProperties = dialogServiceConfigImpl.properties.clone();\r\n\r\n const agentConfig = this.buildAgentConfig();\r\n this.privReco.agentConfig.set(agentConfig);\r\n }\r\n\r\n /**\r\n * The event recognizing signals that an intermediate recognition result is received.\r\n * @member DialogServiceConnector.prototype.recognizing\r\n * @function\r\n * @public\r\n */\r\n public recognizing: (sender: DialogServiceConnector, event: SpeechRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event recognized signals that a final recognition result is received.\r\n * @member DialogServiceConfig.prototype.recognized\r\n * @function\r\n * @public\r\n */\r\n public recognized: (sender: DialogServiceConnector, event: SpeechRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event canceled signals that an error occurred during recognition.\r\n * @member DialogServiceConnector.prototype.canceled\r\n * @function\r\n * @public\r\n */\r\n public canceled: (sender: DialogServiceConnector, event: SpeechRecognitionCanceledEventArgs) => void;\r\n\r\n /**\r\n * The event activityReceived signals that an activity has been received.\r\n * @member DialogServiceConnector.prototype.activityReceived\r\n * @function\r\n * @public\r\n */\r\n public activityReceived: (sender: DialogServiceConnector, event: ActivityReceivedEventArgs) => void;\r\n\r\n /**\r\n * The event turnStatusReceived signals that a turn status message has been received. These messages are\r\n * associated with both an interaction and a conversation. They are used to notify the client in the event\r\n * of an interaction failure with the dialog backend, e.g. in the event of a network issue, timeout, crash,\r\n * or other problem.\r\n * @member DialogServiceConnector.prototype.turnStatusReceived\r\n * @function\r\n * @public\r\n */\r\n public turnStatusReceived: (sender: DialogServiceConnector, event: TurnStatusReceivedEventArgs) => void;\r\n\r\n /**\r\n * Starts a connection to the service.\r\n * Users can optionally call connect() to manually set up a connection in advance, before starting interactions.\r\n *\r\n * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to\r\n * be notified when the connection is established.\r\n * @member DialogServiceConnector.prototype.connect\r\n * @function\r\n * @public\r\n */\r\n public connect(cb?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks(this.privReco.connect(), cb, err);\r\n }\r\n\r\n /**\r\n * Closes the connection the service.\r\n * Users can optionally call disconnect() to manually shutdown the connection of the associated DialogServiceConnector.\r\n *\r\n * If disconnect() is called during a recognition, recognition will fail and cancel with an error.\r\n */\r\n public disconnect(cb?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks(this.privReco.disconnect(), cb, err);\r\n }\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member DialogServiceConnector.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Sets the authorization token used to communicate with the service.\r\n * @member DialogServiceConnector.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} token - Authorization token.\r\n */\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this DialogServiceConnector.\r\n * @member DialogServiceConnector.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their values defined for this DialogServiceConnector.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /** Gets the template for the activity generated by service from speech.\r\n * Properties from the template will be stamped on the generated activity.\r\n * It can be empty\r\n */\r\n public get speechActivityTemplate(): string {\r\n return this.properties.getProperty(PropertyId.Conversation_Speech_Activity_Template);\r\n }\r\n\r\n /** Sets the template for the activity generated by service from speech.\r\n * Properties from the template will be stamped on the generated activity.\r\n * It can be null or empty.\r\n * Note: it has to be a valid Json object.\r\n */\r\n public set speechActivityTemplate(speechActivityTemplate: string) {\r\n this.properties.setProperty(PropertyId.Conversation_Speech_Activity_Template, speechActivityTemplate);\r\n }\r\n\r\n /**\r\n * Starts recognition and stops after the first utterance is recognized.\r\n * @member DialogServiceConnector.prototype.listenOnceAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback that received the result when the reco has completed.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public listenOnceAsync(cb?: (e: SpeechRecognitionResult) => void, err?: (e: string) => void): void {\r\n if (this.isTurnComplete) {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n const callbackHolder = async (): Promise => {\r\n await this.privReco.connect();\r\n await this.implRecognizerStop();\r\n this.isTurnComplete = false;\r\n\r\n const ret: Deferred = new Deferred();\r\n await this.privReco.recognize(RecognitionMode.Conversation, ret.resolve, ret.reject);\r\n\r\n const e: SpeechRecognitionResult = await ret.promise;\r\n await this.implRecognizerStop();\r\n\r\n return e;\r\n };\r\n\r\n const retPromise: Promise = callbackHolder();\r\n\r\n retPromise.catch(() => {\r\n // Destroy the recognizer.\r\n /* tslint:disable:no-empty */ // We've done all we can here.\r\n this.dispose(true).catch(() => { });\r\n });\r\n\r\n marshalPromiseToCallbacks(retPromise.finally((): void => {\r\n this.isTurnComplete = true;\r\n }), cb, err);\r\n }\r\n }\r\n\r\n public sendActivityAsync(activity: string, cb?: () => void, errCb?: (error: string) => void): void {\r\n marshalPromiseToCallbacks((this.privReco as DialogServiceAdapter).sendMessage(activity), cb, errCb);\r\n }\r\n\r\n /**\r\n * closes all external resources held by an instance of this class.\r\n * @member DialogServiceConnector.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, err?: (error: string) => void): void {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n\r\n marshalPromiseToCallbacks(this.dispose(true), cb, err);\r\n }\r\n\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privIsDisposed) {\r\n return;\r\n }\r\n\r\n if (disposing) {\r\n this.privIsDisposed = true;\r\n await this.implRecognizerStop();\r\n await super.dispose(disposing);\r\n }\r\n }\r\n\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(speechConfig, this.privProperties);\r\n }\r\n\r\n protected createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n\r\n const audioSource: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n\r\n return new DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this);\r\n }\r\n\r\n private buildAgentConfig(): IAgentConfig {\r\n const communicationType = this.properties.getProperty(\"Conversation_Communication_Type\", \"Default\");\r\n\r\n return {\r\n botInfo: {\r\n commType: communicationType,\r\n commandsCulture: undefined,\r\n connectionId: this.properties.getProperty(PropertyId.Conversation_Agent_Connection_Id),\r\n conversationId: this.properties.getProperty(PropertyId.Conversation_Conversation_Id, undefined),\r\n fromId: this.properties.getProperty(PropertyId.Conversation_From_Id, undefined),\r\n ttsAudioFormat: this.properties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)\r\n },\r\n version: 0.2\r\n };\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError } from \"../../common/Error\";\r\nimport { marshalPromiseToCallbacks } from \"../../common/Promise\";\r\nimport { AudioStreamFormat, PullAudioInputStreamCallback } from \"../Exports\";\r\nimport { AudioStreamFormatImpl } from \"./AudioStreamFormat\";\r\n\r\ntype AudioDataTypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array;\r\n/**\r\n * Base audio player class\r\n * TODO: Plays only PCM for now.\r\n * @class\r\n */\r\nexport class BaseAudioPlayer {\r\n\r\n private audioContext: AudioContext = null;\r\n private gainNode: GainNode = null;\r\n private audioFormat: AudioStreamFormatImpl;\r\n private autoUpdateBufferTimer: any = 0;\r\n private samples: Float32Array;\r\n private startTime: number;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {AudioStreamFormat} audioFormat audio stream format recognized by the player.\r\n */\r\n public constructor(audioFormat?: AudioStreamFormat) {\r\n if (audioFormat === undefined) {\r\n audioFormat = AudioStreamFormat.getDefaultInputFormat();\r\n }\r\n this.init(audioFormat);\r\n }\r\n\r\n /**\r\n * play Audio sample\r\n * @param newAudioData audio data to be played.\r\n */\r\n public playAudioSample(newAudioData: ArrayBuffer, cb?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n this.ensureInitializedContext();\r\n const audioData = this.formatAudioData(newAudioData);\r\n const newSamplesData = new Float32Array(this.samples.length + audioData.length);\r\n newSamplesData.set(this.samples, 0);\r\n newSamplesData.set(audioData, this.samples.length);\r\n this.samples = newSamplesData;\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * stops audio and clears the buffers\r\n */\r\n public stopAudio(cb?: () => void, err?: (error: string) => void): void {\r\n if (this.audioContext !== null) {\r\n this.samples = new Float32Array();\r\n clearInterval(this.autoUpdateBufferTimer);\r\n this.audioContext.close().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string) => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n this.audioContext = null;\r\n }\r\n }\r\n\r\n private init(audioFormat: AudioStreamFormat): void {\r\n this.audioFormat = audioFormat as AudioStreamFormatImpl;\r\n this.samples = new Float32Array();\r\n }\r\n\r\n private ensureInitializedContext(): void {\r\n if (this.audioContext === null) {\r\n this.createAudioContext();\r\n const timerPeriod = 200;\r\n this.autoUpdateBufferTimer = setInterval(() => {\r\n this.updateAudioBuffer();\r\n }, timerPeriod);\r\n }\r\n }\r\n\r\n private createAudioContext(): void {\r\n // new ((window as any).AudioContext || (window as any).webkitAudioContext)();\r\n this.audioContext = AudioStreamFormatImpl.getAudioContext();\r\n\r\n // TODO: Various examples shows this gain node, it does not seem to be needed unless we plan\r\n // to control the volume, not likely\r\n this.gainNode = this.audioContext.createGain();\r\n this.gainNode.gain.value = 1;\r\n this.gainNode.connect(this.audioContext.destination);\r\n this.startTime = this.audioContext.currentTime;\r\n }\r\n\r\n private formatAudioData(audioData: ArrayBuffer): Float32Array {\r\n switch (this.audioFormat.bitsPerSample) {\r\n case 8:\r\n return this.formatArrayBuffer(new Int8Array(audioData), 128);\r\n case 16:\r\n return this.formatArrayBuffer(new Int16Array(audioData), 32768);\r\n case 32:\r\n return this.formatArrayBuffer(new Int32Array(audioData), 2147483648);\r\n default:\r\n throw new InvalidOperationError(\"Only WAVE_FORMAT_PCM (8/16/32 bps) format supported at this time\");\r\n }\r\n }\r\n\r\n private formatArrayBuffer(audioData: AudioDataTypedArray, maxValue: number): Float32Array {\r\n const float32Data = new Float32Array(audioData.length);\r\n for (let i = 0; i < audioData.length; i++) {\r\n float32Data[i] = audioData[i] / maxValue;\r\n }\r\n return float32Data;\r\n }\r\n\r\n private updateAudioBuffer(): void {\r\n if (this.samples.length === 0) {\r\n return;\r\n }\r\n\r\n const channelCount = this.audioFormat.channels;\r\n const bufferSource = this.audioContext.createBufferSource();\r\n const frameCount = this.samples.length / channelCount;\r\n const audioBuffer = this.audioContext.createBuffer(channelCount, frameCount, this.audioFormat.samplesPerSec);\r\n\r\n // TODO: Should we do the conversion in the pushAudioSample instead?\r\n for (let channel = 0; channel < channelCount; channel++) {\r\n // Fill in individual channel data\r\n let channelOffset = channel;\r\n const audioData = audioBuffer.getChannelData(channel);\r\n for (let i = 0; i < this.samples.length; i++, channelOffset += channelCount) {\r\n audioData[i] = this.samples[channelOffset];\r\n }\r\n }\r\n\r\n if (this.startTime < this.audioContext.currentTime) {\r\n this.startTime = this.audioContext.currentTime;\r\n }\r\n\r\n bufferSource.buffer = audioBuffer;\r\n bufferSource.connect(this.gainNode);\r\n bufferSource.start(this.startTime);\r\n\r\n // Make sure we play the next sample after the current one.\r\n this.startTime += audioBuffer.duration;\r\n\r\n // Clear the samples for the next pushed data.\r\n this.samples = new Float32Array();\r\n }\r\n\r\n private async playAudio(audioData: ArrayBuffer): Promise {\r\n if (this.audioContext === null) {\r\n this.createAudioContext();\r\n }\r\n const source: AudioBufferSourceNode = this.audioContext.createBufferSource();\r\n const destination: AudioDestinationNode = this.audioContext.destination;\r\n await this.audioContext.decodeAudioData(audioData, (newBuffer: AudioBuffer): void => {\r\n source.buffer = newBuffer;\r\n source.connect(destination);\r\n source.start(0);\r\n });\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { VoiceProfileType } from \"./Exports\";\r\n\r\n/**\r\n * Defines Voice Profile class for Speaker Recognition\r\n * @class VoiceProfile\r\n */\r\nexport class VoiceProfile {\r\n private privId: string;\r\n private privProfileType: VoiceProfileType;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {string} profileId - profileId of this Voice Profile.\r\n * @param {VoiceProfileType} profileType - profileType of this Voice Profile.\r\n */\r\n constructor(profileId: string, profileType: VoiceProfileType) {\r\n this.privId = profileId;\r\n this.privProfileType = profileType;\r\n }\r\n\r\n /**\r\n * profileId of this Voice Profile instance\r\n * @member VoiceProfile.prototype.profileId\r\n * @function\r\n * @public\r\n * @returns {string} profileId of this Voice Profile instance.\r\n */\r\n public get profileId(): string {\r\n return this.privId;\r\n }\r\n\r\n /**\r\n * profileType of this Voice Profile instance\r\n * @member VoiceProfile.prototype.profileType\r\n * @function\r\n * @public\r\n * @returns {VoiceProfileType} profile type of this Voice Profile instance.\r\n */\r\n public get profileType(): VoiceProfileType {\r\n return this.privProfileType;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { CancellationErrorCodePropertyName } from \"../common.speech/Exports\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n CancellationDetailsBase,\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyCollection,\r\n ResultReason,\r\n} from \"./Exports\";\r\n\r\nexport interface EnrollmentResultDetails {\r\n profileId: string;\r\n enrollmentsCount: number;\r\n enrollmentsLength: number;\r\n enrollmentsSpeechLength: number;\r\n remainingEnrollmentsCount: number;\r\n remainingEnrollmentsSpeechLength: number;\r\n audioLength: number;\r\n audioSpeechLength: number;\r\n enrollmentStatus: string;\r\n}\r\n\r\n/**\r\n * Output format\r\n * @class VoiceProfileEnrollmentResult\r\n */\r\nexport class VoiceProfileEnrollmentResult {\r\n private privReason: ResultReason;\r\n private privDetails: EnrollmentResultDetails;\r\n private privProperties: PropertyCollection;\r\n private privErrorDetails: string;\r\n\r\n public constructor(reason: ResultReason, json: string, statusText: string) {\r\n this.privReason = reason;\r\n this.privProperties = new PropertyCollection();\r\n if (this.privReason !== ResultReason.Canceled) {\r\n if (!!json) {\r\n this.privDetails = JSON.parse(json);\r\n if (this.privDetails.enrollmentStatus.toLowerCase() === \"enrolling\") {\r\n this.privReason = ResultReason.EnrollingVoiceProfile;\r\n }\r\n }\r\n } else {\r\n this.privErrorDetails = statusText;\r\n this.privProperties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[CancellationErrorCode.ServiceError]);\r\n }\r\n }\r\n\r\n public static FromIdentificationProfileList(json: { profiles: any[] }): VoiceProfileEnrollmentResult[] {\r\n const results: VoiceProfileEnrollmentResult[] = [];\r\n for (const item of json.profiles) {\r\n const reason: ResultReason = item.enrollmentStatus.toLowerCase() === \"enrolling\" ?\r\n ResultReason.EnrollingVoiceProfile : item.enrollmentStatus.toLowerCase() === \"enrolled\" ?\r\n ResultReason.EnrolledVoiceProfile : ResultReason.Canceled;\r\n const result = new VoiceProfileEnrollmentResult(reason, null, null);\r\n result.privDetails = this.getIdentificationDetails(item);\r\n results.push(result);\r\n }\r\n return results;\r\n }\r\n\r\n public static FromVerificationProfileList(json: { profiles: any[] }): VoiceProfileEnrollmentResult[] {\r\n const results: VoiceProfileEnrollmentResult[] = [];\r\n for (const item of json.profiles) {\r\n const reason: ResultReason = item.enrollmentStatus.toLowerCase() === \"enrolling\" ?\r\n ResultReason.EnrollingVoiceProfile : item.enrollmentStatus.toLowerCase() === \"enrolled\" ?\r\n ResultReason.EnrolledVoiceProfile : ResultReason.Canceled;\r\n const result = new VoiceProfileEnrollmentResult(reason, null, null);\r\n result.privDetails = this.getVerificationDetails(item);\r\n results.push(result);\r\n }\r\n return results;\r\n }\r\n\r\n public get reason(): ResultReason {\r\n return this.privReason;\r\n }\r\n\r\n public get enrollmentsCount(): number {\r\n return this.privDetails.enrollmentsCount;\r\n }\r\n\r\n public get enrollmentsLength(): number {\r\n return this.privDetails.enrollmentsLength;\r\n }\r\n\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public get enrollmentResultDetails(): EnrollmentResultDetails {\r\n return this.privDetails;\r\n }\r\n\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n\r\n private static getIdentificationDetails(json: any): any {\r\n return {\r\n audioSpeechLength: json.speechTime ? parseFloat(json.speechTime) : 0,\r\n enrollmentStatus: json.enrollmentStatus,\r\n enrollmentsLength: json.enrollmentSpeechTime ? parseFloat(json.enrollmentSpeechTime) : 0,\r\n profileId: json.profileId || json.identificationProfileId,\r\n remainingEnrollmentSpeechLength: json.remainingEnrollmentSpeechTime ? parseFloat(json.remainingEnrollmentSpeechTime) : 0\r\n };\r\n }\r\n\r\n private static getVerificationDetails(json: any): any {\r\n return {\r\n enrollmentStatus: json.enrollmentStatus,\r\n enrollmentsCount: json.enrollmentsCount,\r\n profileId: json.profileId || json.verificationProfileId,\r\n remainingEnrollmentSpeechLength: json.remainingEnrollmentSpeechLength ? parseFloat(json.remainingEnrollmentSpeechLength) : 0,\r\n remainingEnrollmentsCount: json.remainingEnrollments || json.remainingEnrollmentsCount\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * @class VoiceProfileEnrollmentCancellationDetails\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class VoiceProfileEnrollmentCancellationDetails extends CancellationDetailsBase {\r\n\r\n private constructor(reason: CancellationReason, errorDetails: string, errorCode: CancellationErrorCode) {\r\n super(reason, errorDetails, errorCode);\r\n }\r\n\r\n /**\r\n * Creates an instance of VoiceProfileEnrollmentCancellationDetails object for the canceled VoiceProfileEnrollmentResult.\r\n * @member VoiceProfileEnrollmentCancellationDetails.fromResult\r\n * @function\r\n * @public\r\n * @param {VoiceProfileEnrollmentResult} result - The result that was canceled.\r\n * @returns {VoiceProfileEnrollmentCancellationDetails} The cancellation details object being created.\r\n */\r\n public static fromResult(result: VoiceProfileEnrollmentResult): VoiceProfileEnrollmentCancellationDetails {\r\n const reason = CancellationReason.Error;\r\n let errorCode: CancellationErrorCode = CancellationErrorCode.NoError;\r\n\r\n if (!!result.properties) {\r\n errorCode = (CancellationErrorCode as any)[result.properties.getProperty(CancellationErrorCodePropertyName, CancellationErrorCode[CancellationErrorCode.NoError])];\r\n }\r\n\r\n return new VoiceProfileEnrollmentCancellationDetails(reason, result.errorDetails, errorCode);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { CancellationErrorCodePropertyName } from \"../common.speech/Exports\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n CancellationDetailsBase,\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyCollection,\r\n ResultReason,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Output format\r\n * @class VoiceProfileResult\r\n */\r\nexport class VoiceProfileResult {\r\n private privReason: ResultReason;\r\n private privProperties: PropertyCollection;\r\n private privErrorDetails: string;\r\n\r\n public constructor(reason: ResultReason, statusText: string) {\r\n this.privReason = reason;\r\n this.privProperties = new PropertyCollection();\r\n if (reason === ResultReason.Canceled) {\r\n Contracts.throwIfNullOrUndefined(statusText, \"statusText\");\r\n this.privErrorDetails = statusText;\r\n this.privProperties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[CancellationErrorCode.ServiceError]);\r\n }\r\n }\r\n\r\n public get reason(): ResultReason {\r\n return this.privReason;\r\n }\r\n\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n}\r\n\r\n/**\r\n * @class VoiceProfileCancellationDetails\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class VoiceProfileCancellationDetails extends CancellationDetailsBase {\r\n\r\n private constructor(reason: CancellationReason, errorDetails: string, errorCode: CancellationErrorCode) {\r\n super(reason, errorDetails, errorCode);\r\n }\r\n\r\n /**\r\n * Creates an instance of VoiceProfileCancellationDetails object for the canceled VoiceProfileResult.\r\n * @member VoiceProfileCancellationDetails.fromResult\r\n * @function\r\n * @public\r\n * @param {VoiceProfileResult} result - The result that was canceled.\r\n * @returns {VoiceProfileCancellationDetails} The cancellation details object being created.\r\n */\r\n public static fromResult(result: VoiceProfileResult): VoiceProfileCancellationDetails {\r\n const reason = CancellationReason.Error;\r\n let errorCode: CancellationErrorCode = CancellationErrorCode.NoError;\r\n\r\n if (!!result.properties) {\r\n errorCode = (CancellationErrorCode as any)[result.properties.getProperty(CancellationErrorCodePropertyName, CancellationErrorCode[CancellationErrorCode.NoError])];\r\n }\r\n\r\n return new VoiceProfileCancellationDetails(reason, result.errorDetails, errorCode);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n ResultReason,\r\n VoiceProfileResult\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Output format\r\n * @class VoiceProfileAuthorizationPhraseResult\r\n */\r\nexport class VoiceProfileAuthorizationPhraseResult extends VoiceProfileResult {\r\n private privPhrases: string[] = [];\r\n\r\n public constructor(reason: ResultReason, statusText: string, json: any) {\r\n super(reason, statusText);\r\n Contracts.throwIfNullOrUndefined(json, \"phrases array\");\r\n for (const item of json) {\r\n this.privPhrases.push(item.passPhrase);\r\n }\r\n }\r\n\r\n public get phrases(): string[] {\r\n return this.privPhrases;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection } from \"../sdk/Exports\";\r\nimport { Context } from \"./Exports\";\r\n\r\nexport class SpeakerRecognitionConfig {\r\n private privParameters: PropertyCollection;\r\n private privContext: Context;\r\n\r\n constructor(\r\n context: Context,\r\n parameters: PropertyCollection) {\r\n this.privContext = context ? context : new Context(null);\r\n this.privParameters = parameters;\r\n }\r\n\r\n public get parameters(): PropertyCollection {\r\n return this.privParameters;\r\n }\r\n\r\n public get Context(): Context {\r\n return this.privContext;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IErrorMessages } from \"../common/Exports\";\r\n/**\r\n * HTTP request helper\r\n */\r\nexport interface IRequestOptions {\r\n headers?: {[key: string]: string};\r\n ignoreCache?: boolean;\r\n timeout?: number;\r\n}\r\n\r\nexport interface IRestParams {\r\n apiVersion: string;\r\n authorization: string;\r\n clientAppId: string;\r\n contentTypeKey: string;\r\n correlationId: string;\r\n languageCode: string;\r\n nickname: string;\r\n profanity: string;\r\n requestId: string;\r\n roomId: string;\r\n sessionToken: string;\r\n subscriptionKey: string;\r\n subscriptionRegion: string;\r\n token: string;\r\n}\r\n\r\nexport class RestConfigBase {\r\n\r\n public static get requestOptions(): IRequestOptions {\r\n return RestConfigBase.privDefaultRequestOptions;\r\n }\r\n\r\n public static get configParams(): IRestParams {\r\n return RestConfigBase.privDefaultParams;\r\n }\r\n\r\n public static get restErrors(): IErrorMessages {\r\n return RestConfigBase.privRestErrors;\r\n }\r\n\r\n private static readonly privDefaultRequestOptions: IRequestOptions = {\r\n headers: {\r\n Accept: \"application/json\",\r\n },\r\n ignoreCache: false,\r\n timeout: 10000,\r\n };\r\n\r\n private static readonly privRestErrors: IErrorMessages = {\r\n authInvalidSubscriptionKey: \"You must specify either an authentication token to use, or a Cognitive Speech subscription key.\",\r\n authInvalidSubscriptionRegion: \"You must specify the Cognitive Speech region to use.\",\r\n invalidArgs: \"Required input not found: {arg}.\",\r\n invalidCreateJoinConversationResponse: \"Creating/Joining conversation failed with HTTP {status}.\",\r\n invalidParticipantRequest: \"The requested participant was not found.\",\r\n permissionDeniedConnect: \"Required credentials not found.\",\r\n permissionDeniedConversation: \"Invalid operation: only the host can {command} the conversation.\",\r\n permissionDeniedParticipant: \"Invalid operation: only the host can {command} a participant.\",\r\n permissionDeniedSend: \"Invalid operation: the conversation is not in a connected state.\",\r\n permissionDeniedStart: \"Invalid operation: there is already an active conversation.\",\r\n };\r\n\r\n private static readonly privDefaultParams: IRestParams = {\r\n apiVersion: \"api-version\",\r\n authorization: \"Authorization\",\r\n clientAppId: \"X-ClientAppId\",\r\n contentTypeKey: \"Content-Type\",\r\n correlationId: \"X-CorrelationId\",\r\n languageCode: \"language\",\r\n nickname: \"nickname\",\r\n profanity: \"profanity\",\r\n requestId: \"X-RequestId\",\r\n roomId: \"roomid\",\r\n sessionToken: \"token\",\r\n subscriptionKey: \"Ocp-Apim-Subscription-Key\",\r\n subscriptionRegion: \"Ocp-Apim-Subscription-Region\",\r\n token: \"X-CapitoToken\",\r\n };\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ArgumentNullError,\r\n Deferred\r\n} from \"../common/Exports\";\r\nimport { IRequestOptions } from \"./Exports\";\r\n\r\n// Node.JS specific xmlhttprequest / browser support.\r\nimport * as XHR from \"xmlhttprequest-ts\";\r\n\r\nexport enum RestRequestType {\r\n Get = \"get\",\r\n Post = \"post\",\r\n Delete = \"delete\",\r\n File = \"file\",\r\n}\r\n\r\nexport interface IRestResponse {\r\n ok: boolean;\r\n status: number;\r\n statusText: string;\r\n data: string;\r\n json: () => T;\r\n headers: string;\r\n}\r\n\r\n// accept rest operations via request method and return abstracted objects from server response\r\nexport class RestMessageAdapter {\r\n\r\n private privTimeout: number;\r\n private privIgnoreCache: boolean;\r\n private privHeaders: { [key: string]: string; };\r\n\r\n public constructor(\r\n configParams: IRequestOptions,\r\n connectionId?: string\r\n ) {\r\n\r\n if (!configParams) {\r\n throw new ArgumentNullError(\"configParams\");\r\n }\r\n\r\n this.privHeaders = configParams.headers;\r\n this.privTimeout = configParams.timeout;\r\n this.privIgnoreCache = configParams.ignoreCache;\r\n }\r\n\r\n public setHeaders(key: string, value: string ): void {\r\n this.privHeaders[key] = value;\r\n }\r\n\r\n public request(\r\n method: RestRequestType,\r\n uri: string,\r\n queryParams: any = {},\r\n body: any = null,\r\n binaryBody: Blob | Buffer = null,\r\n ): Promise {\r\n\r\n const responseReceivedDeferral = new Deferred();\r\n\r\n let xhr: XMLHttpRequest | XHR.XMLHttpRequest;\r\n if (typeof (XMLHttpRequest) === \"undefined\") {\r\n xhr = new XHR.XMLHttpRequest();\r\n } else {\r\n xhr = new XMLHttpRequest();\r\n }\r\n const requestCommand = method === RestRequestType.File ? \"post\" : method;\r\n xhr.open(requestCommand, this.withQuery(uri, queryParams), true);\r\n\r\n if (this.privHeaders) {\r\n Object.keys(this.privHeaders).forEach((key: any) => xhr.setRequestHeader(key, this.privHeaders[key]));\r\n }\r\n\r\n if (this.privIgnoreCache) {\r\n xhr.setRequestHeader(\"Cache-Control\", \"no-cache\");\r\n }\r\n\r\n xhr.timeout = this.privTimeout;\r\n\r\n xhr.onload = () => {\r\n responseReceivedDeferral.resolve(this.parseXHRResult(xhr));\r\n };\r\n\r\n xhr.onerror = () => {\r\n responseReceivedDeferral.resolve(this.errorResponse(xhr, \"Failed to make request.\"));\r\n };\r\n\r\n xhr.ontimeout = () => {\r\n responseReceivedDeferral.resolve(this.errorResponse(xhr, \"Request took longer than expected.\"));\r\n };\r\n\r\n if (method === RestRequestType.File && binaryBody) {\r\n xhr.setRequestHeader(\"Content-Type\", \"multipart/form-data\");\r\n xhr.send(binaryBody);\r\n } else if (method === RestRequestType.Post && body) {\r\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\r\n xhr.send(JSON.stringify(body));\r\n } else {\r\n xhr.send();\r\n }\r\n\r\n return responseReceivedDeferral.promise;\r\n }\r\n\r\n private parseXHRResult(xhr: XMLHttpRequest | XHR.XMLHttpRequest): IRestResponse {\r\n return {\r\n data: xhr.responseText,\r\n headers: xhr.getAllResponseHeaders(),\r\n json: () => JSON.parse(xhr.responseText) as T,\r\n ok: xhr.status >= 200 && xhr.status < 300,\r\n status: xhr.status,\r\n statusText: xhr.statusText,\r\n };\r\n }\r\n\r\n private errorResponse(xhr: XMLHttpRequest | XHR.XMLHttpRequest, message: string | null = null): IRestResponse {\r\n return {\r\n data: message || xhr.statusText,\r\n headers: xhr.getAllResponseHeaders(),\r\n json: () => JSON.parse(message || (\"\\\"\" + xhr.statusText + \"\\\"\")) as T,\r\n ok: false,\r\n status: xhr.status,\r\n statusText: xhr.statusText,\r\n };\r\n }\r\n\r\n private withQuery(url: string, params: any = {}): any {\r\n const queryString = this.queryParams(params);\r\n return queryString ? url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + queryString : url;\r\n }\r\n\r\n private queryParams(params: any = {}): any {\r\n return Object.keys(params)\r\n .map((k: any) => encodeURIComponent(k) + \"=\" + encodeURIComponent(params[k]))\r\n .join(\"&\");\r\n }\r\n}\r\n","import {\r\n IRequestOptions,\r\n IRestResponse,\r\n RestConfigBase,\r\n RestMessageAdapter,\r\n RestRequestType,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n IAudioSource,\r\n PromiseResult,\r\n} from \"../common/Exports\";\r\nimport {\r\n PropertyId,\r\n SpeakerIdentificationModel,\r\n SpeakerVerificationModel,\r\n VoiceProfile,\r\n VoiceProfileType,\r\n} from \"../sdk/Exports\";\r\nimport { SpeakerRecognitionConfig } from \"./Exports\";\r\n\r\n/**\r\n * Implements methods for speaker recognition classes, sending requests to endpoint\r\n * and parsing response into expected format\r\n * @class SpeakerIdMessageAdapter\r\n */\r\nexport class SpeakerIdMessageAdapter {\r\n private privRestAdapter: RestMessageAdapter;\r\n private privUri: string;\r\n\r\n public constructor(config: SpeakerRecognitionConfig) {\r\n\r\n let endpoint = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n if (!endpoint) {\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, \"westus\");\r\n const hostSuffix: string = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"https://\" + region + \".api.cognitive\" + hostSuffix + \"/speaker/{mode}/v2.0/{dependency}\");\r\n endpoint = host + \"/profiles\";\r\n }\r\n this.privUri = endpoint;\r\n\r\n const options: IRequestOptions = RestConfigBase.requestOptions;\r\n options.headers[RestConfigBase.configParams.subscriptionKey] = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Key, undefined);\r\n\r\n this.privRestAdapter = new RestMessageAdapter(options);\r\n }\r\n\r\n /**\r\n * Sends create profile request to endpoint.\r\n * @function\r\n * @param {VoiceProfileType} profileType - type of voice profile to create.\r\n * @param {string} lang - language/locale of voice profile\r\n * @public\r\n * @returns {Promise} promised rest response containing id of created profile.\r\n */\r\n public createProfile(profileType: VoiceProfileType, lang: string):\r\n Promise {\r\n\r\n const uri = this.getOperationUri(profileType);\r\n this.privRestAdapter.setHeaders(RestConfigBase.configParams.contentTypeKey, \"application/json\");\r\n return this.privRestAdapter.request(RestRequestType.Post, uri, {}, { locale: lang });\r\n }\r\n\r\n /**\r\n * Sends create enrollment request to endpoint.\r\n * @function\r\n * @param {VoiceProfile} profileType - voice profile for which to create new enrollment.\r\n * @param {IAudioSource} audioSource - audioSource from which to pull data to send\r\n * @public\r\n * @returns {Promise} rest response to enrollment request.\r\n */\r\n public createEnrollment(profile: VoiceProfile, audioSource: IAudioSource):\r\n Promise {\r\n\r\n this.privRestAdapter.setHeaders(RestConfigBase.configParams.contentTypeKey, \"multipart/form-data\");\r\n const uri = this.getOperationUri(profile.profileType) + \"/\" + profile.profileId + \"/enrollments\";\r\n return audioSource.blob.then((result: Blob | Buffer): Promise => {\r\n return this.privRestAdapter.request(RestRequestType.File, uri, { ignoreMinLength: \"true\" }, null, result);\r\n });\r\n }\r\n\r\n /**\r\n * Sends verification request to endpoint.\r\n * @function\r\n * @param {SpeakerVerificationModel} model - voice model to verify against.\r\n * @param {IAudioSource} audioSource - audioSource from which to pull data to send\r\n * @public\r\n * @returns {Promise} rest response to enrollment request.\r\n */\r\n public async verifySpeaker(model: SpeakerVerificationModel, audioSource: IAudioSource):\r\n Promise {\r\n\r\n this.privRestAdapter.setHeaders(RestConfigBase.configParams.contentTypeKey, \"multipart/form-data\");\r\n const uri = this.getOperationUri(model.voiceProfile.profileType) + \"/\" + model.voiceProfile.profileId + \"/verify\";\r\n try {\r\n const result: Blob | Buffer = await audioSource.blob;\r\n return this.privRestAdapter.request(RestRequestType.File, uri, { ignoreMinLength: \"true\" }, null, result);\r\n } catch (e) {\r\n return Promise.resolve({ data: e } as IRestResponse);\r\n }\r\n }\r\n\r\n /**\r\n * Sends identification request to endpoint.\r\n * @function\r\n * @param {SpeakerIdentificationModel} model - voice profiles against which to identify.\r\n * @param {IAudioSource} audioSource - audioSource from which to pull data to send\r\n * @public\r\n * @returns {Promise} rest response to enrollment request.\r\n */\r\n public async identifySpeaker(model: SpeakerIdentificationModel, audioSource: IAudioSource):\r\n Promise {\r\n\r\n this.privRestAdapter.setHeaders(RestConfigBase.configParams.contentTypeKey, \"multipart/form-data\");\r\n const uri = this.getOperationUri(VoiceProfileType.TextIndependentIdentification) + \"/identifySingleSpeaker\";\r\n try {\r\n const result: Blob | Buffer = await audioSource.blob;\r\n return this.privRestAdapter.request(RestRequestType.File, uri, { profileIds: model.voiceProfileIds, ignoreMinLength: \"true\" }, null, result);\r\n } catch (e) {\r\n return Promise.resolve({ data: e } as IRestResponse);\r\n }\r\n }\r\n\r\n /**\r\n * Sends profile status request to endpoint.\r\n * @function\r\n * @param {VoiceProfile} profile - voice profile to check.\r\n * @public\r\n * @returns {Promise} rest response to status request\r\n */\r\n public getProfileStatus(profile: VoiceProfile): Promise {\r\n\r\n const uri = `${this.getOperationUri(profile.profileType)}/${profile.profileId}`;\r\n return this.privRestAdapter.request(RestRequestType.Get, uri, {});\r\n }\r\n\r\n /**\r\n * Sends get all profiles request to endpoint.\r\n * @function\r\n * @param {VoiceProfileType} profileType - type of profiles to return list of\r\n * @public\r\n * @returns {Promise} promised rest response containing all profiles\r\n */\r\n public getProfiles(profileType: VoiceProfileType): Promise {\r\n const uri = this.getOperationUri(profileType);\r\n return this.privRestAdapter.request(RestRequestType.Get, uri, {});\r\n }\r\n\r\n /**\r\n * Sends get authorization phrases request to endpoint.\r\n * @function\r\n * @param {string} lang - language/locale of voice profile\r\n * @public\r\n * @returns {Promise} promised rest response containing list of valid phrases\r\n */\r\n public getAuthorizationPhrases(lang: string): Promise {\r\n const uri = `${this.getOperationUri(VoiceProfileType.TextDependentVerification)}`.replace(`profiles`, `phrases`) + \"/\" + lang;\r\n return this.privRestAdapter.request(RestRequestType.Get, uri, {});\r\n }\r\n\r\n /**\r\n * Sends delete profile request to endpoint.\r\n * @function\r\n * @param {VoiceProfile} profile - voice profile to delete.\r\n * @public\r\n * @returns {Promise} rest response to deletion request\r\n */\r\n public deleteProfile(profile: VoiceProfile): Promise {\r\n\r\n const uri = this.getOperationUri(profile.profileType) + \"/\" + profile.profileId;\r\n return this.privRestAdapter.request(RestRequestType.Delete, uri, {});\r\n }\r\n\r\n /**\r\n * Sends reset profile request to endpoint.\r\n * @function\r\n * @param {VoiceProfile} profile - voice profile to reset enrollments for.\r\n * @public\r\n * @returns {Promise} rest response to reset request\r\n */\r\n public resetProfile(profile: VoiceProfile): Promise {\r\n\r\n const uri = this.getOperationUri(profile.profileType) + \"/\" + profile.profileId + \"/reset\";\r\n return this.privRestAdapter.request(RestRequestType.Post, uri, {});\r\n }\r\n\r\n private getOperationUri(profileType: VoiceProfileType): string {\r\n\r\n const mode = profileType === VoiceProfileType.TextIndependentIdentification ? \"identification\" : \"verification\";\r\n const dependency = profileType === VoiceProfileType.TextDependentVerification ? \"text-dependent\" : \"text-independent\";\r\n return this.privUri.replace(\"{mode}\", mode).replace(\"{dependency}\", dependency);\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { CancellationErrorCodePropertyName } from \"../common.speech/Exports\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n CancellationDetailsBase,\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n} from \"./Exports\";\r\n\r\nexport enum SpeakerRecognitionResultType {\r\n Verify,\r\n Identify\r\n}\r\n/**\r\n * Output format\r\n * @class SpeakerRecognitionResult\r\n */\r\nexport class SpeakerRecognitionResult {\r\n private privReason: ResultReason;\r\n private privProperties: PropertyCollection;\r\n private privProfileId: string;\r\n private privScore: number;\r\n private privErrorDetails: string;\r\n\r\n public constructor(resultType: SpeakerRecognitionResultType, data: string, profileId: string, resultReason: ResultReason = ResultReason.RecognizedSpeaker) {\r\n this.privProperties = new PropertyCollection();\r\n this.privReason = resultReason;\r\n if (this.privReason !== ResultReason.Canceled) {\r\n if (resultType === SpeakerRecognitionResultType.Identify) {\r\n const json: { identifiedProfile: { profileId: string, score: number } } = JSON.parse(data);\r\n Contracts.throwIfNullOrUndefined(json, \"JSON\");\r\n this.privProfileId = json.identifiedProfile.profileId;\r\n this.privScore = json.identifiedProfile.score;\r\n } else {\r\n const json: { recognitionResult: string, score: number } = JSON.parse(data);\r\n Contracts.throwIfNullOrUndefined(json, \"JSON\");\r\n this.privScore = json.score;\r\n if (json.recognitionResult.toLowerCase() !== \"accept\") {\r\n this.privReason = ResultReason.NoMatch;\r\n }\r\n if (profileId !== undefined && profileId !== \"\") {\r\n this.privProfileId = profileId;\r\n }\r\n }\r\n } else {\r\n const json: { statusText: string } = JSON.parse(data);\r\n Contracts.throwIfNullOrUndefined(json, \"JSON\");\r\n this.privErrorDetails = json.statusText;\r\n this.privProperties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[CancellationErrorCode.ServiceError]);\r\n }\r\n this.privProperties.setProperty(PropertyId.SpeechServiceResponse_JsonResult, data);\r\n }\r\n\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public get reason(): ResultReason {\r\n return this.privReason;\r\n }\r\n\r\n public get profileId(): string {\r\n return this.privProfileId;\r\n }\r\n\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n\r\n public get score(): number {\r\n return this.privScore;\r\n }\r\n}\r\n\r\n/**\r\n * @class SpeakerRecognitionCancellationDetails\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class SpeakerRecognitionCancellationDetails extends CancellationDetailsBase {\r\n\r\n private constructor(reason: CancellationReason, errorDetails: string, errorCode: CancellationErrorCode) {\r\n super(reason, errorDetails, errorCode);\r\n }\r\n\r\n /**\r\n * Creates an instance of SpeakerRecognitionCancellationDetails object for the canceled SpeakerRecognitionResult\r\n * @member SpeakerRecognitionCancellationDetails.fromResult\r\n * @function\r\n * @public\r\n * @param {SpeakerRecognitionResult} result - The result that was canceled.\r\n * @returns {SpeakerRecognitionCancellationDetails} The cancellation details object being created.\r\n */\r\n public static fromResult(result: SpeakerRecognitionResult): SpeakerRecognitionCancellationDetails {\r\n const reason = CancellationReason.Error;\r\n let errorCode: CancellationErrorCode = CancellationErrorCode.NoError;\r\n\r\n if (!!result.properties) {\r\n errorCode = (CancellationErrorCode as any)[result.properties.getProperty(CancellationErrorCodePropertyName, CancellationErrorCode[CancellationErrorCode.NoError])];\r\n }\r\n\r\n return new SpeakerRecognitionCancellationDetails(reason, result.errorDetails, errorCode);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IRestResponse,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n Context,\r\n OS,\r\n SpeakerIdMessageAdapter,\r\n SpeakerRecognitionConfig,\r\n} from \"../common.speech/Exports\";\r\nimport { marshalPromiseToCallbacks } from \"../common/Exports\";\r\nimport { AudioConfig, AudioConfigImpl } from \"./Audio/AudioConfig\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n VoiceProfile,\r\n VoiceProfileAuthorizationPhraseResult,\r\n VoiceProfileEnrollmentResult,\r\n VoiceProfileResult,\r\n VoiceProfileType,\r\n} from \"./Exports\";\r\nimport { SpeechConfig, SpeechConfigImpl } from \"./SpeechConfig\";\r\n\r\n/**\r\n * Defines VoiceProfileClient class for Speaker Recognition\r\n * Handles operations from user for Voice Profile operations (e.g. createProfile, deleteProfile)\r\n * @class VoiceProfileClient\r\n */\r\nexport class VoiceProfileClient {\r\n protected privProperties: PropertyCollection;\r\n private privAdapter: SpeakerIdMessageAdapter;\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member VoiceProfileClient.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Gets/Sets the authorization token used to communicate with the service.\r\n * @member VoiceProfileClient.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} token - Authorization token.\r\n */\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this VoiceProfileClient.\r\n * @member VoiceProfileClient.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their values defined for this VoiceProfileClient.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * VoiceProfileClient constructor.\r\n * @constructor\r\n * @param {SpeechConfig} speechConfig - An set of initial properties for this synthesizer (authentication key, region, &c)\r\n */\r\n public constructor(speechConfig: SpeechConfig) {\r\n const speechConfigImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;\r\n Contracts.throwIfNull(speechConfigImpl, \"speechConfig\");\r\n\r\n this.privProperties = speechConfigImpl.properties.clone();\r\n this.implClientSetup();\r\n }\r\n\r\n /**\r\n * Create a speaker recognition voice profile\r\n * @member VoiceProfileClient.prototype.createProfileAsync\r\n * @function\r\n * @public\r\n * @param {VoiceProfileType} profileType Type of Voice Profile to be created\r\n * specifies the keyword to be recognized.\r\n * @param {string} lang Language string (locale) for Voice Profile\r\n * @param cb - Callback invoked once Voice Profile has been created.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public createProfileAsync(profileType: VoiceProfileType, lang: string, cb?: (e: VoiceProfile) => void, err?: (e: string) => void): void {\r\n\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n const result: IRestResponse = await this.privAdapter.createProfile(profileType, lang);\r\n const response: { profileId: string } = result.json();\r\n const profile = new VoiceProfile(response.profileId, profileType);\r\n return profile;\r\n })(), cb, err);\r\n }\r\n /**\r\n * Get current information of a voice profile\r\n * @member VoiceProfileClient.prototype.retrieveEnrollmentResultAsync\r\n * @function\r\n * @public\r\n * @param {VoiceProfile} profile Voice Profile to retrieve info for\r\n * @param cb - Callback invoked once Voice Profile has been created.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public retrieveEnrollmentResultAsync(profile: VoiceProfile, cb?: (e: VoiceProfileEnrollmentResult) => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n const result: IRestResponse = await this.privAdapter.getProfileStatus(profile);\r\n return new VoiceProfileEnrollmentResult(\r\n result.ok ? ResultReason.EnrolledVoiceProfile : ResultReason.Canceled,\r\n result.data,\r\n result.statusText,\r\n );\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * Get all voice profiles on account with given voice profile type\r\n * @member VoiceProfileClient.prototype.getAllProfilesAsync\r\n * @function\r\n * @public\r\n * @param {VoiceProfileType} profileType profile type (identification/verification) for which to list profiles\r\n * @param cb - Callback invoked once Profile list has been returned.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public getAllProfilesAsync(profileType: VoiceProfileType, cb?: (e: VoiceProfileEnrollmentResult[]) => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n const result: IRestResponse = await this.privAdapter.getProfiles(profileType);\r\n if (profileType === VoiceProfileType.TextIndependentIdentification) {\r\n return VoiceProfileEnrollmentResult.FromIdentificationProfileList(result.json());\r\n }\r\n return VoiceProfileEnrollmentResult.FromVerificationProfileList(result.json());\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * Get valid authorization phrases for voice profile enrollment\r\n * @member VoiceProfileClient.prototype.getAuthorizationPhrasesAsync\r\n * @function\r\n * @public\r\n * @param {string} lang Language string (locale) for Voice Profile\r\n * @param cb - Callback invoked once phrases have been returned.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public getAuthorizationPhrasesAsync(lang: string, cb?: (e: VoiceProfileAuthorizationPhraseResult) => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n const result: IRestResponse = await this.privAdapter.getAuthorizationPhrases(lang);\r\n return new VoiceProfileAuthorizationPhraseResult(\r\n result.ok ? ResultReason.EnrollingVoiceProfile : ResultReason.Canceled,\r\n result.statusText,\r\n result.json()\r\n );\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * Create a speaker recognition voice profile\r\n * @member VoiceProfileClient.prototype.enrollProfileAsync\r\n * @function\r\n * @public\r\n * @param {VoiceProfile} profile Voice Profile to create enrollment for\r\n * @param {AudioConfig} audioConfig source info from which to create enrollment\r\n * @param cb - Callback invoked once Enrollment request has been submitted.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public enrollProfileAsync(profile: VoiceProfile, audioConfig: AudioConfig, cb?: (e: VoiceProfileEnrollmentResult) => void, err?: (e: string) => void): void {\r\n const configImpl: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n Contracts.throwIfNullOrUndefined(configImpl, \"audioConfig\");\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n const result: IRestResponse = await this.privAdapter.createEnrollment(profile, configImpl);\r\n return new VoiceProfileEnrollmentResult(\r\n result.ok ? ResultReason.EnrolledVoiceProfile : ResultReason.Canceled,\r\n result.data,\r\n result.statusText,\r\n );\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * Delete a speaker recognition voice profile\r\n * @member VoiceProfileClient.prototype.deleteProfileAsync\r\n * @function\r\n * @public\r\n * @param {VoiceProfile} profile Voice Profile to be deleted\r\n * @param cb - Callback invoked once Voice Profile has been deleted.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public deleteProfileAsync(profile: VoiceProfile, cb?: (response: VoiceProfileResult) => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n const result: IRestResponse = await this.privAdapter.deleteProfile(profile);\r\n return this.getResult(result, ResultReason.DeletedVoiceProfile);\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * Remove all enrollments for a speaker recognition voice profile\r\n * @member VoiceProfileClient.prototype.resetProfileAsync\r\n * @function\r\n * @public\r\n * @param {VoiceProfile} profile Voice Profile to be reset\r\n * @param cb - Callback invoked once Voice Profile has been reset.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public resetProfileAsync(profile: VoiceProfile, cb?: (response: VoiceProfileResult) => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n const result: IRestResponse = await this.privAdapter.resetProfile(profile);\r\n return this.getResult(result, ResultReason.ResetVoiceProfile);\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * Included for compatibility\r\n * @member VoiceProfileClient.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n return;\r\n }\r\n\r\n // Does class setup, swiped from Recognizer.\r\n protected implClientSetup(): void {\r\n\r\n let osPlatform = (typeof window !== \"undefined\") ? \"Browser\" : \"Node\";\r\n let osName = \"unknown\";\r\n let osVersion = \"unknown\";\r\n\r\n if (typeof navigator !== \"undefined\") {\r\n osPlatform = osPlatform + \"/\" + navigator.platform;\r\n osName = navigator.userAgent;\r\n osVersion = navigator.appVersion;\r\n }\r\n\r\n const recognizerConfig =\r\n new SpeakerRecognitionConfig(\r\n new Context(new OS(osPlatform, osName, osVersion)),\r\n this.privProperties);\r\n\r\n this.privAdapter = new SpeakerIdMessageAdapter(recognizerConfig);\r\n }\r\n\r\n private getResult(result: IRestResponse, successReason: ResultReason, cb?: (response: VoiceProfileResult) => void): VoiceProfileResult {\r\n const response: VoiceProfileResult =\r\n new VoiceProfileResult(\r\n result.ok ? successReason : ResultReason.Canceled,\r\n result.statusText\r\n );\r\n return (response);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n VoiceProfile,\r\n VoiceProfileType,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Defines SpeakerIdentificationModel class for Speaker Recognition\r\n * Model contains a set of profiles against which to identify speaker(s)\r\n * @class SpeakerIdentificationModel\r\n */\r\nexport class SpeakerIdentificationModel {\r\n private privVoiceProfiles: VoiceProfile[] = [];\r\n\r\n private constructor(profiles: VoiceProfile[]) {\r\n Contracts.throwIfNullOrUndefined(profiles, \"VoiceProfiles\");\r\n if (profiles.length === 0) {\r\n throw new Error(\"Empty Voice Profiles array\");\r\n }\r\n profiles.forEach((profile: VoiceProfile) => {\r\n if (profile.profileType !== VoiceProfileType.TextIndependentIdentification) {\r\n throw new Error(\"Identification model can only be created from Identification profile: \" + profile.profileId);\r\n }\r\n this.privVoiceProfiles.push(profile);\r\n });\r\n }\r\n public static fromProfiles(profiles: VoiceProfile[]): SpeakerIdentificationModel {\r\n return new SpeakerIdentificationModel(profiles);\r\n }\r\n\r\n public get voiceProfileIds(): string {\r\n return this.privVoiceProfiles.map((profile: VoiceProfile) => profile.profileId).join(\",\");\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n VoiceProfile,\r\n VoiceProfileType,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Defines SpeakerVerificationModel class for Speaker Recognition\r\n * Model contains a profile against which to verify a speaker\r\n * @class SpeakerVerificationModel\r\n */\r\nexport class SpeakerVerificationModel {\r\n private privVoiceProfile: VoiceProfile;\r\n\r\n private constructor(profile: VoiceProfile) {\r\n Contracts.throwIfNullOrUndefined(profile, \"VoiceProfile\");\r\n if (profile.profileType === VoiceProfileType.TextIndependentIdentification) {\r\n throw new Error(\"Verification model cannot be created from Identification profile\");\r\n }\r\n this.privVoiceProfile = profile;\r\n }\r\n\r\n public static fromProfile(profile: VoiceProfile): SpeakerVerificationModel {\r\n return new SpeakerVerificationModel(profile);\r\n }\r\n\r\n public get voiceProfile(): VoiceProfile {\r\n return this.privVoiceProfile;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IRestResponse,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n Context,\r\n OS,\r\n SpeakerIdMessageAdapter,\r\n SpeakerRecognitionConfig,\r\n} from \"../common.speech/Exports\";\r\nimport { marshalPromiseToCallbacks } from \"../common/Exports\";\r\nimport { AudioConfig, AudioConfigImpl } from \"./Audio/AudioConfig\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeakerIdentificationModel,\r\n SpeakerRecognitionResult,\r\n SpeakerRecognitionResultType,\r\n SpeakerVerificationModel,\r\n} from \"./Exports\";\r\nimport { SpeechConfig, SpeechConfigImpl } from \"./SpeechConfig\";\r\n\r\n/**\r\n * Defines SpeakerRecognizer class for Speaker Recognition\r\n * Handles operations from user for Voice Profile operations (e.g. createProfile, deleteProfile)\r\n * @class SpeakerRecognizer\r\n */\r\nexport class SpeakerRecognizer {\r\n protected privProperties: PropertyCollection;\r\n private privAdapter: SpeakerIdMessageAdapter;\r\n private privAudioConfigImpl: AudioConfigImpl;\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member SpeakerRecognizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Gets/Sets the authorization token used to communicate with the service.\r\n * @member SpeakerRecognizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} token - Authorization token.\r\n */\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this SpeakerRecognizer.\r\n * @member SpeakerRecognizer.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their values defined for this SpeakerRecognizer.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * SpeakerRecognizer constructor.\r\n * @constructor\r\n * @param {SpeechConfig} speechConfig - An set of initial properties for this recognizer (authentication key, region, &c)\r\n */\r\n public constructor(speechConfig: SpeechConfig, audioConfig: AudioConfig) {\r\n const speechConfigImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;\r\n Contracts.throwIfNull(speechConfigImpl, \"speechConfig\");\r\n\r\n this.privAudioConfigImpl = audioConfig as AudioConfigImpl;\r\n Contracts.throwIfNull(this.privAudioConfigImpl, \"audioConfig\");\r\n\r\n this.privProperties = speechConfigImpl.properties.clone();\r\n this.implSRSetup();\r\n }\r\n\r\n /**\r\n * Get recognition result for model using given audio\r\n * @member SpeakerRecognizer.prototype.recognizeOnceAsync\r\n * @function\r\n * @public\r\n * @param {SpeakerIdentificationModel} model Model containing Voice Profiles to be identified\r\n * @param cb - Callback invoked once result is returned.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public recognizeOnceAsync(model: SpeakerIdentificationModel | SpeakerVerificationModel, cb?: (e: SpeakerRecognitionResult) => void, err?: (e: string) => void): void {\r\n\r\n if (model instanceof SpeakerIdentificationModel) {\r\n const responsePromise: Promise = this.privAdapter.identifySpeaker(model, this.privAudioConfigImpl);\r\n marshalPromiseToCallbacks(this.getResult(responsePromise, SpeakerRecognitionResultType.Identify, undefined), cb, err);\r\n } else if (model instanceof SpeakerVerificationModel) {\r\n const responsePromise: Promise = this.privAdapter.verifySpeaker(model, this.privAudioConfigImpl);\r\n marshalPromiseToCallbacks(this.getResult(responsePromise, SpeakerRecognitionResultType.Verify, model.voiceProfile.profileId), cb, err);\r\n } else {\r\n throw new Error(\"SpeakerRecognizer.recognizeOnce: Unexpected model type\");\r\n }\r\n }\r\n\r\n /**\r\n * Included for compatibility\r\n * @member SpeakerRecognizer.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n return;\r\n }\r\n\r\n // Does class setup, swiped from Recognizer.\r\n private implSRSetup(): void {\r\n\r\n let osPlatform = (typeof window !== \"undefined\") ? \"Browser\" : \"Node\";\r\n let osName = \"unknown\";\r\n let osVersion = \"unknown\";\r\n\r\n if (typeof navigator !== \"undefined\") {\r\n osPlatform = osPlatform + \"/\" + navigator.platform;\r\n osName = navigator.userAgent;\r\n osVersion = navigator.appVersion;\r\n }\r\n\r\n const recognizerConfig =\r\n new SpeakerRecognitionConfig(\r\n new Context(new OS(osPlatform, osName, osVersion)),\r\n this.privProperties);\r\n\r\n this.privAdapter = new SpeakerIdMessageAdapter(recognizerConfig);\r\n }\r\n\r\n private async getResult(responsePromise: Promise, resultType: SpeakerRecognitionResultType, profileId?: string): Promise {\r\n const response: IRestResponse = await responsePromise;\r\n return new SpeakerRecognitionResult(\r\n resultType,\r\n response.data,\r\n profileId,\r\n response.ok ? ResultReason.RecognizedSpeaker : ResultReason.Canceled,\r\n );\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { AutoDetectSourceLanguagesOpenRangeOptionName } from \"../common.speech/Exports\";\r\nimport {Contracts} from \"./Contracts\";\r\nimport {\r\n PropertyCollection,\r\n PropertyId,\r\n SourceLanguageConfig,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Language auto detect configuration.\r\n * @class AutoDetectSourceLanguageConfig\r\n * Added in version 1.13.0.\r\n */\r\nexport class AutoDetectSourceLanguageConfig {\r\n private privProperties: PropertyCollection;\r\n\r\n private constructor() {\r\n this.privProperties = new PropertyCollection();\r\n }\r\n\r\n /**\r\n * @member AutoDetectSourceLanguageConfig.fromOpenRange\r\n * @function\r\n * @public\r\n * Only [[SpeechSynthesizer]] supports source language auto detection from open range,\r\n * for [[Recognizer]], please use AutoDetectSourceLanguageConfig with specific source languages.\r\n * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig\r\n * @summary Creates an instance of the AutoDetectSourceLanguageConfig with open range.\r\n */\r\n public static fromOpenRange(): AutoDetectSourceLanguageConfig {\r\n const config = new AutoDetectSourceLanguageConfig();\r\n config.properties.setProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, AutoDetectSourceLanguagesOpenRangeOptionName);\r\n return config;\r\n }\r\n\r\n /**\r\n * @member AutoDetectSourceLanguageConfig.fromLanguages\r\n * @function\r\n * @public\r\n * @param {string[]} languages Comma-separated string of languages (eg. \"en-US,fr-FR\") to populate properties of config.\r\n * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig\r\n * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given languages.\r\n */\r\n public static fromLanguages(languages: string[]): AutoDetectSourceLanguageConfig {\r\n Contracts.throwIfArrayEmptyOrWhitespace(languages, \"languages\");\r\n const config = new AutoDetectSourceLanguageConfig();\r\n config.properties.setProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, languages.join());\r\n return config;\r\n }\r\n\r\n /**\r\n * @member AutoDetectSourceLanguageConfig.fromSourceLanguageConfigs\r\n * @function\r\n * @public\r\n * @param {SourceLanguageConfig[]} configs SourceLanguageConfigs to populate properties of config.\r\n * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig\r\n * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given SourceLanguageConfigs.\r\n */\r\n public static fromSourceLanguageConfigs(configs: SourceLanguageConfig[]): AutoDetectSourceLanguageConfig {\r\n if (configs.length < 1) {\r\n throw new Error(\"Expected non-empty SourceLanguageConfig array.\");\r\n }\r\n const autoConfig = new AutoDetectSourceLanguageConfig();\r\n const langs: string[] = [];\r\n configs.forEach((config: SourceLanguageConfig) => {\r\n langs.push(config.language);\r\n if (config.endpointId !== undefined && config.endpointId !== \"\") {\r\n const customProperty = config.language + PropertyId.SpeechServiceConnection_EndpointId.toString();\r\n autoConfig.properties.setProperty(customProperty, config.endpointId);\r\n }\r\n });\r\n autoConfig.properties.setProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, langs.join());\r\n\r\n return autoConfig;\r\n }\r\n\r\n /**\r\n * @member AutoDetectSourceLanguageConfig.prototype.properties\r\n * @function\r\n * @public\r\n * @return {PropertyCollection} Properties of the config.\r\n * @summary Gets an auto detected language config properties\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n SpeechRecognitionResult,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Output format\r\n * @class AutoDetectSourceLanguageResult\r\n */\r\nexport class AutoDetectSourceLanguageResult {\r\n\r\n private privLanguage: string;\r\n private privLanguageDetectionConfidence: string;\r\n\r\n private constructor(language: string, languageDetectionConfidence: string) {\r\n Contracts.throwIfNullOrUndefined(language, \"language\");\r\n Contracts.throwIfNullOrUndefined(languageDetectionConfidence, \"languageDetectionConfidence\");\r\n this.privLanguage = language;\r\n this.privLanguageDetectionConfidence = languageDetectionConfidence;\r\n }\r\n\r\n /**\r\n * Creates an instance of AutoDetectSourceLanguageResult object from a SpeechRecognitionResult instance.\r\n * @member AutoDetectSourceLanguageResult.fromResult\r\n * @function\r\n * @public\r\n * @param {SpeechRecognitionResult} result - The recognition result.\r\n * @returns {AutoDetectSourceLanguageResult} AutoDetectSourceLanguageResult object being created.\r\n */\r\n public static fromResult(result: SpeechRecognitionResult): AutoDetectSourceLanguageResult {\r\n return new AutoDetectSourceLanguageResult(result.language, result.languageDetectionConfidence);\r\n }\r\n\r\n public get language(): string {\r\n return this.privLanguage;\r\n }\r\n\r\n public get languageDetectionConfidence(): string {\r\n return this.privLanguageDetectionConfidence;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\n\r\n/**\r\n * Source Language configuration.\r\n * @class SourceLanguageConfig\r\n */\r\nexport class SourceLanguageConfig {\r\n private privLanguage: string;\r\n private privEndpointId: string;\r\n\r\n private constructor(language: string, endpointId?: string) {\r\n Contracts.throwIfNullOrUndefined(language, \"language\");\r\n this.privLanguage = language;\r\n this.privEndpointId = endpointId;\r\n }\r\n\r\n /**\r\n * @member SourceLanguageConfig.fromLanguage\r\n * @function\r\n * @public\r\n * @param {string} language language (eg. \"en-US\") value of config.\r\n * @param {string?} endpointId endpointId of model bound to given language of config.\r\n * @return {SourceLanguageConfig} Instance of SourceLanguageConfig\r\n * @summary Creates an instance of the SourceLanguageConfig with the given language and optional endpointId.\r\n * Added in version 1.13.0.\r\n */\r\n public static fromLanguage(language: string, endpointId?: string): SourceLanguageConfig {\r\n return new SourceLanguageConfig(language, endpointId);\r\n }\r\n\r\n public get language(): string {\r\n return this.privLanguage;\r\n }\r\n\r\n public get endpointId(): string {\r\n return this.privEndpointId;\r\n }\r\n}\r\n","\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n RestConfigBase\r\n} from \"../../common.browser/RestConfigBase\";\r\n\r\nexport class ConversationConnectionConfig extends RestConfigBase {\r\n\r\n private static readonly privHost: string = \"dev.microsofttranslator.com\";\r\n private static readonly privRestPath: string = \"/capito/room\";\r\n private static readonly privApiVersion: string = \"2.0\";\r\n private static readonly privDefaultLanguageCode: string = \"en-US\";\r\n private static readonly privClientAppId: string = \"FC539C22-1767-4F1F-84BC-B4D811114F15\";\r\n private static readonly privWebSocketPath: string = \"/capito/translate\";\r\n private static readonly privSpeechHost: string = \"{region}.s2s.speech.microsoft.com\";\r\n private static readonly privSpeechPath: string = \"/speech/translation/cognitiveservices/v1\";\r\n private static readonly privTranscriptionEventKeys: string[] = [\"iCalUid\", \"callId\", \"organizer\", \"FLAC\", \"MTUri\", \"DifferenciateGuestSpeakers\", \"audiorecording\", \"Threadid\", \"OrganizerMri\", \"OrganizerTenantId\", \"UserToken\"];\r\n\r\n public static get host(): string {\r\n return ConversationConnectionConfig.privHost;\r\n }\r\n\r\n public static get apiVersion(): string {\r\n return ConversationConnectionConfig.privApiVersion;\r\n }\r\n\r\n public static get clientAppId(): string {\r\n return ConversationConnectionConfig.privClientAppId;\r\n }\r\n\r\n public static get defaultLanguageCode(): string {\r\n return ConversationConnectionConfig.privDefaultLanguageCode;\r\n }\r\n\r\n public static get restPath(): string {\r\n return ConversationConnectionConfig.privRestPath;\r\n }\r\n\r\n public static get webSocketPath(): string {\r\n return ConversationConnectionConfig.privWebSocketPath;\r\n }\r\n\r\n public static get speechHost(): string {\r\n return ConversationConnectionConfig.privSpeechHost;\r\n }\r\n\r\n public static get speechPath(): string {\r\n return ConversationConnectionConfig.privSpeechPath;\r\n }\r\n\r\n public static get transcriptionEventKeys(): string[] {\r\n return ConversationConnectionConfig.privTranscriptionEventKeys;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionEventArgs,\r\n ConversationExpirationEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n SessionEventArgs,\r\n VoiceSignature,\r\n } from \"../../sdk/Exports\";\r\n// import { ConversationClient } from \"./ConversationConnection\";\r\nimport {\r\n ConversationReceivedTranslationEventArgs,\r\n LockRoomEventArgs,\r\n MuteAllEventArgs,\r\n ParticipantAttributeEventArgs,\r\n ParticipantEventArgs,\r\n ParticipantsListEventArgs } from \"./ConversationTranslatorEventArgs\";\r\n\r\n/**\r\n * Internal conversation data\r\n */\r\nexport interface IInternalConversation {\r\n // the token to use for connecting to the Speech Service\r\n cognitiveSpeechAuthToken: string;\r\n // the region to use for connecting to the Speech Service\r\n cognitiveSpeechRegion: string;\r\n // the unique id of the user who started or joined the Conversation\r\n participantId: string;\r\n // a descriptive name for the Conversation\r\n name: string;\r\n // a descriptive name for the Conversation\r\n description: string;\r\n // the speech model ID for custom speech\r\n speechModel: string;\r\n // represents the level of speech supported in the Conversation (0: everyone can speak, 2: only host can speak, 3: no-one can speak)\r\n modalities: number;\r\n // ?\r\n isApproved: boolean;\r\n // the mute flag has been set at conversation level and only the host can speak\r\n isMuted: boolean;\r\n // the 5 character conversation Id\r\n roomId: string;\r\n // the hex color string to represent a user. If there are many users this hex color may be reused (?).\r\n avatar: string;\r\n // the token to use when calling the websocket\r\n token: string;\r\n // used for tracking the session and help with troubleshooting problems in the logs\r\n correlationId: string;\r\n // extracted from the headers\r\n requestId: string;\r\n}\r\n\r\n/**\r\n * The user who is participating in the conversation.\r\n */\r\nexport interface IInternalParticipant {\r\n avatar?: string;\r\n displayName?: string;\r\n id?: string;\r\n isHost?: boolean;\r\n isMuted?: boolean;\r\n isUsingTts?: boolean;\r\n preferredLanguage?: string;\r\n voice?: string;\r\n}\r\n\r\n/** Users participating in the conversation */\r\nexport class InternalParticipants {\r\n\r\n constructor(public participants: IInternalParticipant[] = [], public meId?: string) {\r\n\r\n }\r\n\r\n /**\r\n * Add or update a participant\r\n * @param value\r\n */\r\n public addOrUpdateParticipant(value: IInternalParticipant): IInternalParticipant {\r\n if (value === undefined) {\r\n return;\r\n }\r\n\r\n const exists: number = this.getParticipantIndex(value.id);\r\n if (exists > -1) {\r\n this.participants.splice(exists, 1, value);\r\n } else {\r\n this.participants.push(value);\r\n }\r\n\r\n // ensure it was added ok\r\n return this.getParticipant(value.id);\r\n }\r\n\r\n /**\r\n * Find the participant's position in the participants list.\r\n * @param id\r\n */\r\n public getParticipantIndex(id: string): number {\r\n return this.participants.findIndex((p: IInternalParticipant) => p.id === id);\r\n }\r\n\r\n /**\r\n * Find the participant by id.\r\n * @param id\r\n */\r\n public getParticipant(id: string): IInternalParticipant {\r\n return this.participants.find((p: IInternalParticipant) => p.id === id);\r\n }\r\n\r\n /***\r\n * Remove a participant from the participants list.\r\n */\r\n public deleteParticipant(id: string): void {\r\n this.participants = this.participants.filter((p: IInternalParticipant) => p.id !== id);\r\n }\r\n\r\n /***\r\n * Helper to return the conversation host.\r\n */\r\n public get host(): IInternalParticipant {\r\n return this.participants.find((p: IInternalParticipant) => p.isHost === true );\r\n }\r\n\r\n /**\r\n * Helper to return the current user.\r\n */\r\n public get me(): IInternalParticipant {\r\n return this.getParticipant(this.meId);\r\n }\r\n}\r\n\r\n/**\r\n * Recognizer for handling Conversation Translator websocket messages\r\n */\r\nexport interface ConversationRecognizer {\r\n isDisposed(): boolean;\r\n sendRequest: (command: string, cb?: () => void, err?: (e: string) => void) => void;\r\n cancelSpeech?: () => Promise;\r\n close?: () => Promise;\r\n conversationExpiration?: (sender: ConversationRecognizer, event: ConversationExpirationEventArgs) => void;\r\n connected?: (e: ConnectionEventArgs) => void;\r\n disconnected?: (e: ConnectionEventArgs) => void;\r\n canceled?: (sender: ConversationRecognizer, event: ConversationTranslationCanceledEventArgs) => void;\r\n connectionOpened?: (sender: ConversationRecognizer, event: SessionEventArgs) => void;\r\n connectionClosed?: (sender: ConversationRecognizer, event: SessionEventArgs) => void;\r\n participantsListReceived?: (sender: ConversationRecognizer, event: ParticipantsListEventArgs) => void;\r\n translationReceived?: (sender: ConversationRecognizer, event: ConversationReceivedTranslationEventArgs) => void;\r\n lockRoomCommandReceived?: (sender: ConversationRecognizer, event: LockRoomEventArgs) => void;\r\n muteAllCommandReceived?: (sender: ConversationRecognizer, event: MuteAllEventArgs) => void;\r\n participantJoinCommandReceived?: (sender: ConversationRecognizer, event: ParticipantEventArgs) => void;\r\n participantLeaveCommandReceived?: (sender: ConversationRecognizer, event: ParticipantEventArgs) => void;\r\n participantUpdateCommandReceived?: (sender: ConversationRecognizer, event: ParticipantAttributeEventArgs) => void;\r\n connect?: (token: string, cb?: () => void, err?: (e: string) => void) => void;\r\n}\r\n\r\n/**\r\n * Error message returned from the Conversation Translator websocket\r\n */\r\nexport interface IConversationResponseErrorMessage {\r\n code: string;\r\n message: string;\r\n}\r\n\r\n/**\r\n * Error returned from the Conversation Translator websocket\r\n */\r\nexport interface IConversationResponseError {\r\n error: IConversationResponseErrorMessage;\r\n}\r\n\r\n/**\r\n * Base message command\r\n */\r\nexport interface IClientMessage {\r\n type: any;\r\n}\r\n\r\n/**\r\n * Command message\r\n */\r\nexport interface ICommandMessage extends IClientMessage {\r\n command?: string;\r\n}\r\n\r\n/**\r\n * Text message command\r\n */\r\nexport interface IInstantMessageCommand extends ICommandMessage {\r\n roomId: string;\r\n nickname?: string;\r\n participantId: string;\r\n text: string;\r\n}\r\n\r\n/**\r\n * Lock command\r\n */\r\nexport interface ILockConversationCommand extends ICommandMessage {\r\n id?: string; // incoming ws\r\n nickname?: string; // incoming ws\r\n participantId: string; // host - incoming ws\r\n roomid: string;\r\n value: boolean;\r\n}\r\n\r\n/**\r\n * Mute all command\r\n */\r\nexport interface IMuteAllCommand extends ICommandMessage {\r\n roomid: string;\r\n nickname?: string; // incoming ws\r\n participantId: string; // host\r\n value: boolean;\r\n id?: string; // incoming ws\r\n}\r\n\r\n/**\r\n * Mute participant command\r\n */\r\nexport interface IMuteCommand extends ICommandMessage {\r\n roomid: string;\r\n nickname?: string;\r\n participantId: string; // participant\r\n value: boolean;\r\n id?: string; // incoming ws\r\n}\r\n\r\n/**\r\n * Remove participant command\r\n */\r\nexport interface IEjectParticipantCommand extends ICommandMessage {\r\n roomid: string;\r\n participantId: string; // participant\r\n}\r\n\r\n/**\r\n * Change nickname command\r\n */\r\nexport interface IChangeNicknameCommand extends ICommandMessage {\r\n roomid: string;\r\n participantId: string;\r\n nickname: string;\r\n value: string;\r\n}\r\n\r\n/**\r\n * List of command message types\r\n */\r\nexport const ConversationTranslatorMessageTypes = {\r\n command: \"command\",\r\n final: \"final\",\r\n info: \"info\",\r\n instantMessage: \"instant_message\",\r\n partial: \"partial\",\r\n participantCommand: \"participant_command\",\r\n translatedMessage: \"translated_message\"\r\n};\r\n\r\n/**\r\n * List of command types\r\n */\r\nexport const ConversationTranslatorCommandTypes = {\r\n changeNickname: \"ChangeNickname\",\r\n disconnectSession: \"DisconnectSession\",\r\n ejectParticipant: \"EjectParticipant\",\r\n instant_message: \"instant_message\",\r\n joinSession: \"JoinSession\",\r\n leaveSession: \"LeaveSession\",\r\n participantList: \"ParticipantList\",\r\n roomExpirationWarning: \"RoomExpirationWarning\",\r\n setLockState: \"SetLockState\",\r\n setMute: \"SetMute\",\r\n setMuteAll: \"SetMuteAll\",\r\n setProfanityFiltering: \"SetProfanityFiltering\",\r\n setTranslateToLanguages: \"SetTranslateToLanguages\",\r\n setUseTTS: \"SetUseTTS\"\r\n};\r\n\r\n/**\r\n * HTTP response helper\r\n */\r\nexport interface IResponse {\r\n ok: boolean;\r\n status: number;\r\n statusText: string;\r\n data: string;\r\n json: () => T;\r\n headers: string;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IResponse } from \"./ConversationTranslatorInterfaces\";\r\n\r\nimport { IRequestOptions, RestConfigBase } from \"../../common.browser/RestConfigBase\";\r\nimport { Callback } from \"../../sdk/Transcription/IConversation\";\r\n\r\n// Node.JS specific xmlhttprequest / browser support.\r\nimport * as XHR from \"xmlhttprequest-ts\";\r\n\r\n/**\r\n * Config settings for Conversation Translator\r\n */\r\n/**\r\n * Helpers for sending / receiving HTTPS requests / responses.\r\n * @param params\r\n */\r\nfunction queryParams(params: any = {}): any {\r\n return Object.keys(params)\r\n .map((k: any) => encodeURIComponent(k) + \"=\" + encodeURIComponent(params[k]))\r\n .join(\"&\");\r\n}\r\n\r\nfunction withQuery(url: string, params: any = {}): any {\r\n const queryString = queryParams(params);\r\n return queryString ? url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + queryString : url;\r\n}\r\n\r\nfunction parseXHRResult(xhr: XMLHttpRequest | XHR.XMLHttpRequest): IResponse {\r\n return {\r\n data: xhr.responseText,\r\n headers: xhr.getAllResponseHeaders(),\r\n json: () => JSON.parse(xhr.responseText) as T,\r\n ok: xhr.status >= 200 && xhr.status < 300,\r\n status: xhr.status,\r\n statusText: xhr.statusText,\r\n };\r\n}\r\n\r\nfunction errorResponse(xhr: XMLHttpRequest | XHR.XMLHttpRequest, message: string | null = null): IResponse {\r\n return {\r\n data: message || xhr.statusText,\r\n headers: xhr.getAllResponseHeaders(),\r\n json: () => JSON.parse(message || (\"\\\"\" + xhr.statusText + \"\\\"\")) as T,\r\n ok: false,\r\n status: xhr.status,\r\n statusText: xhr.statusText,\r\n };\r\n}\r\n\r\nexport function extractHeaderValue(headerKey: string, headers: string): string {\r\n\r\n let headerValue: string = \"\";\r\n\r\n try {\r\n const arr = headers.trim().split(/[\\r\\n]+/);\r\n const headerMap: any = {};\r\n arr.forEach((line: any) => {\r\n const parts = line.split(\": \");\r\n const header = parts.shift().toLowerCase();\r\n const value = parts.join(\": \");\r\n headerMap[header] = value;\r\n });\r\n\r\n headerValue = headerMap[headerKey.toLowerCase()];\r\n } catch (e) {\r\n // ignore the error\r\n }\r\n\r\n return headerValue;\r\n}\r\n\r\nexport function request(\r\n method: \"get\" | \"post\" | \"delete\",\r\n url: string,\r\n queryParams: any = {},\r\n body: any = null,\r\n options: IRequestOptions = {},\r\n callback: any): any {\r\n\r\n const defaultRequestOptions = RestConfigBase.requestOptions;\r\n\r\n const ignoreCache = options.ignoreCache || defaultRequestOptions.ignoreCache;\r\n const headers = options.headers || defaultRequestOptions.headers;\r\n const timeout = options.timeout || defaultRequestOptions.timeout;\r\n\r\n let xhr: XMLHttpRequest | XHR.XMLHttpRequest;\r\n if (typeof window === \"undefined\") { // Node\r\n xhr = new XHR.XMLHttpRequest();\r\n\r\n } else {\r\n xhr = new XMLHttpRequest();\r\n }\r\n xhr.open(method, withQuery(url, queryParams), true);\r\n\r\n if (headers) {\r\n Object.keys(headers).forEach((key: any) => xhr.setRequestHeader(key, headers[key]));\r\n }\r\n\r\n if (ignoreCache) {\r\n xhr.setRequestHeader(\"Cache-Control\", \"no-cache\");\r\n }\r\n\r\n xhr.timeout = timeout;\r\n\r\n xhr.onload = (evt: any) => {\r\n callback(parseXHRResult(xhr));\r\n };\r\n\r\n xhr.onerror = (evt: any) => {\r\n callback(errorResponse(xhr, \"Failed to make request.\"));\r\n };\r\n\r\n xhr.ontimeout = (evt: any) => {\r\n callback(errorResponse(xhr, \"Request took longer than expected.\"));\r\n };\r\n\r\n if (method === \"post\" && body) {\r\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\r\n xhr.send(JSON.stringify(body));\r\n } else {\r\n xhr.send();\r\n }\r\n}\r\n\r\nexport function PromiseToEmptyCallback(promise: Promise, cb?: Callback, err?: Callback): void {\r\n if (!!promise) {\r\n promise.then((result: T): void => {\r\n try {\r\n if (!!cb) {\r\n cb();\r\n }\r\n } catch (e) {\r\n if (!!err) {\r\n err(`'Unhandled error on promise callback: ${e}'`);\r\n }\r\n }\r\n }, (reason: any) => {\r\n try {\r\n if (!!err) {\r\n err(reason);\r\n }\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n }\r\n });\r\n } else {\r\n if (!!err) {\r\n err(\"Null promise\");\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IRequestOptions,\r\n IRestParams,\r\n} from \"../../common.browser/RestConfigBase\";\r\nimport { IErrorMessages, IStringDictionary } from \"../../common/Exports\";\r\nimport { Contracts } from \"../../sdk/Contracts\";\r\nimport { PropertyCollection, PropertyId } from \"../../sdk/Exports\";\r\nimport { ConversationConnectionConfig } from \"./ConversationConnectionConfig\";\r\nimport { IConversationResponseError, IInternalConversation, IResponse } from \"./ConversationTranslatorInterfaces\";\r\nimport { extractHeaderValue, request } from \"./ConversationUtils\";\r\n\r\nexport class ConversationManager {\r\n\r\n private privRequestParams: IRestParams;\r\n private privErrors: IErrorMessages;\r\n private privHost: string;\r\n private privApiVersion: string;\r\n private privRestPath: string;\r\n\r\n public constructor() {\r\n //\r\n this.privRequestParams = ConversationConnectionConfig.configParams;\r\n this.privErrors = ConversationConnectionConfig.restErrors;\r\n this.privHost = ConversationConnectionConfig.host;\r\n this.privApiVersion = ConversationConnectionConfig.apiVersion;\r\n this.privRestPath = ConversationConnectionConfig.restPath;\r\n }\r\n\r\n /**\r\n * Make a POST request to the Conversation Manager service endpoint to create or join a conversation.\r\n * @param args\r\n * @param conversationCode\r\n * @param callback\r\n * @param errorCallback\r\n */\r\n public createOrJoin(args: PropertyCollection, conversationCode: string, cb?: any, err?: any): void {\r\n\r\n try {\r\n\r\n Contracts.throwIfNullOrUndefined(args, \"args\");\r\n\r\n const languageCode: string = args.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, ConversationConnectionConfig.defaultLanguageCode);\r\n const nickname: string = args.getProperty(PropertyId.ConversationTranslator_Name);\r\n const endpointHost: string = args.getProperty(PropertyId.ConversationTranslator_Host, this.privHost);\r\n const correlationId: string = args.getProperty(PropertyId.ConversationTranslator_CorrelationId);\r\n const subscriptionKey: string = args.getProperty(PropertyId.SpeechServiceConnection_Key);\r\n const subscriptionRegion: string = args.getProperty(PropertyId.SpeechServiceConnection_Region);\r\n const authToken: string = args.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n\r\n Contracts.throwIfNullOrWhitespace(languageCode, \"languageCode\");\r\n Contracts.throwIfNullOrWhitespace(nickname, \"nickname\");\r\n Contracts.throwIfNullOrWhitespace(endpointHost, \"endpointHost\");\r\n\r\n const queryParams: IStringDictionary = {};\r\n queryParams[this.privRequestParams.apiVersion] = this.privApiVersion;\r\n queryParams[this.privRequestParams.languageCode] = languageCode;\r\n queryParams[this.privRequestParams.nickname] = nickname;\r\n\r\n const headers: IStringDictionary = {};\r\n if (correlationId) {\r\n headers[this.privRequestParams.correlationId] = correlationId;\r\n }\r\n headers[this.privRequestParams.clientAppId] = ConversationConnectionConfig.clientAppId;\r\n\r\n if (conversationCode !== undefined) {\r\n queryParams[this.privRequestParams.roomId] = conversationCode;\r\n } else {\r\n Contracts.throwIfNullOrUndefined(subscriptionRegion, this.privErrors.authInvalidSubscriptionRegion);\r\n headers[this.privRequestParams.subscriptionRegion] = subscriptionRegion;\r\n if (subscriptionKey) {\r\n headers[this.privRequestParams.subscriptionKey] = subscriptionKey;\r\n } else if (authToken) {\r\n headers[this.privRequestParams.authorization] = `Bearer ${authToken}`;\r\n } else {\r\n Contracts.throwIfNullOrUndefined(subscriptionKey, this.privErrors.authInvalidSubscriptionKey);\r\n }\r\n }\r\n\r\n const config: IRequestOptions = {};\r\n config.headers = headers;\r\n\r\n const endpoint: string = `https://${endpointHost}${this.privRestPath}`;\r\n\r\n // TODO: support a proxy and certificate validation\r\n request(\"post\", endpoint, queryParams, null, config, (response: IResponse) => {\r\n\r\n const requestId: string = extractHeaderValue(this.privRequestParams.requestId, response.headers);\r\n\r\n if (!response.ok) {\r\n if (!!err) {\r\n // get the error\r\n let errorMessage: string = this.privErrors.invalidCreateJoinConversationResponse.replace(\"{status}\", response.status.toString());\r\n let errMessageRaw: IConversationResponseError;\r\n try {\r\n errMessageRaw = JSON.parse(response.data) as IConversationResponseError;\r\n errorMessage += ` [${errMessageRaw.error.code}: ${errMessageRaw.error.message}]`;\r\n } catch (e) {\r\n errorMessage += ` [${response.data}]`;\r\n }\r\n if (requestId) {\r\n errorMessage += ` ${requestId}`;\r\n }\r\n\r\n err(errorMessage);\r\n }\r\n return;\r\n }\r\n const conversation: IInternalConversation = JSON.parse(response.data) as IInternalConversation;\r\n if (conversation) {\r\n conversation.requestId = requestId;\r\n }\r\n if (!!cb) {\r\n try {\r\n cb(conversation);\r\n } catch (e) {\r\n if (!!err) {\r\n err(e);\r\n }\r\n }\r\n cb = undefined;\r\n }\r\n\r\n });\r\n\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n\r\n } else {\r\n err(error);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Make a DELETE request to the Conversation Manager service endpoint to leave the conversation.\r\n * @param args\r\n * @param sessionToken\r\n * @param callback\r\n */\r\n public leave(args: PropertyCollection, sessionToken: string): Promise {\r\n return new Promise((resolve: () => void, reject: (reason: string) => void): void => {\r\n try {\r\n\r\n Contracts.throwIfNullOrUndefined(args, this.privErrors.invalidArgs.replace(\"{arg}\", \"config\"));\r\n Contracts.throwIfNullOrWhitespace(sessionToken, this.privErrors.invalidArgs.replace(\"{arg}\", \"token\"));\r\n\r\n const endpointHost: string = args.getProperty(PropertyId.ConversationTranslator_Host, this.privHost);\r\n const correlationId: string = args.getProperty(PropertyId.ConversationTranslator_CorrelationId);\r\n\r\n const queryParams: IStringDictionary = {};\r\n queryParams[this.privRequestParams.apiVersion] = this.privApiVersion;\r\n queryParams[this.privRequestParams.sessionToken] = sessionToken;\r\n\r\n const headers: IStringDictionary = {};\r\n if (correlationId) {\r\n headers[this.privRequestParams.correlationId] = correlationId;\r\n }\r\n\r\n const config: IRequestOptions = {};\r\n config.headers = headers;\r\n\r\n const endpoint: string = `https://${endpointHost}${this.privRestPath}`;\r\n\r\n // TODO: support a proxy and certificate validation\r\n request(\"delete\", endpoint, queryParams, null, config, (response: IResponse) => {\r\n\r\n if (!response.ok) {\r\n // ignore errors on delete\r\n }\r\n\r\n resolve();\r\n });\r\n\r\n } catch (error) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n reject(typedError.name + \": \" + typedError.message);\r\n\r\n } else {\r\n reject(error);\r\n }\r\n }\r\n });\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ConnectionMessage, IStringDictionary, MessageType } from \"../../common/Exports\";\r\n\r\nexport class ConversationConnectionMessage extends ConnectionMessage {\r\n private privConversationMessageType: string;\r\n\r\n public constructor(\r\n messageType: MessageType,\r\n body: any,\r\n headers?: IStringDictionary,\r\n id?: string) {\r\n super(messageType, body, headers, id);\r\n const json = JSON.parse(this.textBody);\r\n if (json.type !== undefined) {\r\n this.privConversationMessageType = json.type;\r\n }\r\n }\r\n\r\n public get conversationMessageType(): string {\r\n return this.privConversationMessageType;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionMessage,\r\n Deferred,\r\n IStringDictionary,\r\n IWebsocketMessageFormatter,\r\n MessageType,\r\n RawWebsocketMessage,\r\n} from \"../../common/Exports\";\r\nimport { ConversationConnectionMessage } from \"./ConversationConnectionMessage\";\r\n\r\n/**\r\n * Based off WebsocketMessageFormatter. The messages for Conversation Translator have some variations from the Speech messages.\r\n */\r\nexport class ConversationWebsocketMessageFormatter implements IWebsocketMessageFormatter {\r\n\r\n /**\r\n * Format incoming messages: text (speech partial/final, IM) or binary (tts)\r\n */\r\n public toConnectionMessage = (message: RawWebsocketMessage): Promise => {\r\n const deferral = new Deferred();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const incomingMessage: ConversationConnectionMessage = new ConversationConnectionMessage(message.messageType, message.textContent, {}, message.id);\r\n deferral.resolve(incomingMessage);\r\n } else if (message.messageType === MessageType.Binary) {\r\n deferral.resolve(new ConversationConnectionMessage(message.messageType, message.binaryContent, undefined, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. Error: ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n /**\r\n * Format outgoing messages: text (commands or IM)\r\n */\r\n public fromConnectionMessage = (message: ConnectionMessage): Promise => {\r\n\r\n const deferral = new Deferred();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const payload = `${message.textBody ? message.textBody : \"\"}`;\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Text, payload, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ProxyInfo, WebsocketConnection } from \"../../common.browser/Exports\";\r\nimport { createGuid, IConnection, IStringDictionary } from \"../../common/Exports\";\r\nimport { Contracts } from \"../../sdk/Contracts\";\r\nimport { PropertyId } from \"../../sdk/Exports\";\r\nimport { ConnectionFactoryBase } from \"../ConnectionFactoryBase\";\r\nimport { AuthInfo, RecognizerConfig } from \"../Exports\";\r\nimport { ConversationConnectionConfig } from \"./ConversationConnectionConfig\";\r\nimport { ConversationWebsocketMessageFormatter } from \"./ConversationWebsocketMessageFormatter\";\r\n\r\n/**\r\n * Create a connection to the Conversation Translator websocket for sending instant messages and commands, and for receiving translated messages.\r\n * The conversation must already have been started or joined.\r\n */\r\nexport class ConversationConnectionFactory extends ConnectionFactoryBase {\r\n\r\n public create(config: RecognizerConfig, authInfo: AuthInfo, connectionId?: string): IConnection {\r\n\r\n const endpointHost: string = config.parameters.getProperty(PropertyId.ConversationTranslator_Host, ConversationConnectionConfig.host);\r\n const correlationId: string = config.parameters.getProperty(PropertyId.ConversationTranslator_CorrelationId, createGuid());\r\n\r\n const endpoint: string = `wss://${endpointHost}${ConversationConnectionConfig.webSocketPath}`;\r\n const token: string = config.parameters.getProperty(PropertyId.ConversationTranslator_Token, undefined);\r\n Contracts.throwIfNullOrUndefined(token, \"token\");\r\n\r\n const queryParams: IStringDictionary = {};\r\n queryParams[ConversationConnectionConfig.configParams.apiVersion] = ConversationConnectionConfig.apiVersion;\r\n queryParams[ConversationConnectionConfig.configParams.token] = token;\r\n queryParams[ConversationConnectionConfig.configParams.correlationId] = correlationId;\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, {}, new ConversationWebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nimport { CancellationEventArgsBase } from \"../CancellationEventArgsBase\";\r\n\r\nexport class ConversationTranslationCanceledEventArgs extends CancellationEventArgsBase {\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nimport { SessionEventArgs } from \"../Exports\";\r\n\r\nexport class ConversationExpirationEventArgs extends SessionEventArgs {\r\n private privExpirationTime: number;\r\n\r\n constructor(expirationTime: number, sessionId?: string) {\r\n super(sessionId);\r\n this.privExpirationTime = expirationTime;\r\n }\r\n\r\n /** How much longer until the conversation expires (in minutes). */\r\n get expirationTime(): number {\r\n return this.privExpirationTime;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nimport { PropertyCollection } from \"../PropertyCollection\";\r\nimport { ResultReason } from \"../ResultReason\";\r\nimport { TranslationRecognitionResult } from \"../TranslationRecognitionResult\";\r\nimport { Translations } from \"../Translations\";\r\n\r\nexport class ConversationTranslationResult extends TranslationRecognitionResult {\r\n private privId: string;\r\n private privOrigLang: string;\r\n\r\n public constructor(participantId: string,\r\n translations: Translations,\r\n originalLanguage?: string,\r\n resultId?: string,\r\n reason?: ResultReason,\r\n text?: string,\r\n duration?: number,\r\n offset?: number,\r\n errorDetails?: string,\r\n json?: string,\r\n properties?: PropertyCollection) {\r\n super(translations, resultId, reason, text, duration, offset, errorDetails, json, properties);\r\n this.privId = participantId;\r\n this.privOrigLang = originalLanguage;\r\n }\r\n\r\n /**\r\n * The unique identifier for the participant this result is for.\r\n */\r\n public get participantId(): string {\r\n return this.privId;\r\n }\r\n\r\n /**\r\n * The original language this result was in.\r\n */\r\n public get originalLang(): string {\r\n return this.privOrigLang;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n IDetachable,\r\n} from \"../../common/Exports\";\r\n\r\n/**\r\n * Placeholder class for the Conversation Request Session. Based off RequestSession.\r\n * TODO: define what telemetry is required.\r\n */\r\nexport class ConversationRequestSession {\r\n private privIsDisposed: boolean = false;\r\n private privDetachables: IDetachable[] = new Array();\r\n private privRequestId: string;\r\n private privRequestCompletionDeferral: Deferred;\r\n private privSessionId: string;\r\n\r\n constructor(sessionId: string) {\r\n this.privSessionId = sessionId;\r\n this.privRequestId = createNoDashGuid();\r\n this.privRequestCompletionDeferral = new Deferred();\r\n }\r\n\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get completionPromise(): Promise {\r\n return this.privRequestCompletionDeferral.promise;\r\n }\r\n\r\n public onPreConnectionStart = (authFetchEventId: string, connectionId: string): void => {\r\n this.privSessionId = connectionId;\r\n }\r\n\r\n public onAuthCompleted = (isError: boolean, error?: string): void => {\r\n if (isError) {\r\n this.onComplete();\r\n }\r\n }\r\n\r\n public onConnectionEstablishCompleted = (statusCode: number, reason?: string): void => {\r\n if (statusCode === 200) {\r\n return;\r\n } else if (statusCode === 403) {\r\n this.onComplete();\r\n }\r\n }\r\n\r\n public onServiceTurnEndResponse = (continuousRecognition: boolean): void => {\r\n if (!continuousRecognition) {\r\n this.onComplete();\r\n } else {\r\n this.privRequestId = createNoDashGuid();\r\n }\r\n }\r\n\r\n public async dispose(error?: string): Promise {\r\n if (!this.privIsDisposed) {\r\n // we should have completed by now. If we did not its an unknown error.\r\n this.privIsDisposed = true;\r\n for (const detachable of this.privDetachables) {\r\n await detachable.detach();\r\n }\r\n }\r\n }\r\n\r\n private onComplete = (): void => {\r\n //\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\nimport { SessionEventArgs } from \"../../sdk/Exports\";\r\nimport { IInternalParticipant } from \"./ConversationTranslatorInterfaces\";\r\n\r\nexport class MuteAllEventArgs extends SessionEventArgs {\r\n private privIsMuted: boolean;\r\n\r\n public constructor(isMuted: boolean, sessionId?: string) {\r\n super(sessionId);\r\n\r\n this.privIsMuted = isMuted;\r\n }\r\n\r\n public get isMuted(): boolean {\r\n return this.privIsMuted;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class LockRoomEventArgs extends SessionEventArgs {\r\n private privIsLocked: boolean;\r\n\r\n public constructor(isLocked: boolean, sessionId?: string) {\r\n super(sessionId);\r\n\r\n this.privIsLocked = isLocked;\r\n }\r\n\r\n public get isMuted(): boolean {\r\n return this.privIsLocked;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ParticipantEventArgs extends SessionEventArgs {\r\n private privParticipant: IInternalParticipant;\r\n\r\n public constructor(participant: IInternalParticipant, sessionId?: string) {\r\n super(sessionId);\r\n this.privParticipant = participant;\r\n }\r\n\r\n public get participant(): IInternalParticipant {\r\n return this.privParticipant;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ParticipantAttributeEventArgs extends SessionEventArgs {\r\n private privValue: boolean | number | string | string[];\r\n private privKey: string;\r\n private privParticipantId: string;\r\n\r\n public constructor(participantId: string, key: string, value: boolean | number | string | string[], sessionId?: string) {\r\n super(sessionId);\r\n\r\n this.privKey = key;\r\n this.privValue = value;\r\n this.privParticipantId = participantId;\r\n }\r\n\r\n public get value(): boolean | number | string | string[] {\r\n return this.privValue;\r\n }\r\n\r\n public get key(): string {\r\n return this.privKey;\r\n }\r\n public get id(): string {\r\n return this.privParticipantId;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ParticipantsListEventArgs extends SessionEventArgs {\r\n\r\n private privRoomId: string;\r\n private privSessionToken: string;\r\n private privTranslateTo: string[];\r\n private privProfanityFilter: string;\r\n private privRoomProfanityFilter: string;\r\n private privIsRoomLocked: boolean;\r\n private privIsMuteAll: boolean;\r\n private privParticipants: IInternalParticipant[];\r\n\r\n public constructor(conversationId: string, token: string, translateTo: string[], profanityFilter: string,\r\n roomProfanityFilter: string, isRoomLocked: boolean, isMuteAll: boolean, participants: IInternalParticipant[], sessionId?: string) {\r\n super(sessionId);\r\n this.privRoomId = conversationId;\r\n this.privSessionToken = token;\r\n this.privTranslateTo = translateTo;\r\n this.privProfanityFilter = profanityFilter;\r\n this.privRoomProfanityFilter = roomProfanityFilter;\r\n this.privIsRoomLocked = isRoomLocked;\r\n this.privIsRoomLocked = isMuteAll;\r\n this.privParticipants = participants;\r\n }\r\n public get sessionToken(): string {\r\n return this.privSessionToken;\r\n }\r\n\r\n public get conversationId(): string {\r\n return this.privRoomId;\r\n }\r\n\r\n public get translateTo(): string[] {\r\n return this.privTranslateTo;\r\n }\r\n\r\n public get profanityFilter(): string {\r\n return this.privProfanityFilter;\r\n }\r\n\r\n public get roomProfanityFilter(): string {\r\n return this.privRoomProfanityFilter;\r\n }\r\n\r\n public get isRoomLocked(): boolean {\r\n return this.privIsRoomLocked;\r\n }\r\n\r\n public get isMuteAll(): boolean {\r\n return this.privIsMuteAll;\r\n }\r\n\r\n public get participants(): IInternalParticipant[] {\r\n return this.privParticipants;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ConversationReceivedTranslationEventArgs {\r\n private privPayload: any;\r\n private privCommand: string;\r\n private privSessionId: string;\r\n\r\n public constructor(command: string, payload: any, sessionId?: string) {\r\n this.privPayload = payload;\r\n this.privCommand = command;\r\n this.privSessionId = sessionId;\r\n }\r\n\r\n public get payload(): any {\r\n return this.privPayload;\r\n }\r\n\r\n public get command(): string {\r\n return this.privCommand;\r\n }\r\n\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the payload for incoming websocket commands\r\n */\r\nexport interface ICommandResponsePayload {\r\n type: string;\r\n command?: string;\r\n id?: string; // incoming ws\r\n nickname?: string; // incoming ws\r\n participantId?: string;\r\n roomid?: string;\r\n value: boolean | number | string;\r\n}\r\n\r\nexport class CommandResponsePayload implements ICommandResponsePayload {\r\n private privCommandResponse: ICommandResponsePayload;\r\n\r\n public constructor(json: string) {\r\n this.privCommandResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): CommandResponsePayload {\r\n return new CommandResponsePayload(json);\r\n }\r\n\r\n public get type(): string {\r\n return this.privCommandResponse.type;\r\n }\r\n public get command(): string {\r\n return this.privCommandResponse.command;\r\n }\r\n public get id(): string {\r\n return this.privCommandResponse.id;\r\n }\r\n public get nickname(): string {\r\n return this.privCommandResponse.nickname;\r\n }\r\n public get participantId(): string {\r\n return this.privCommandResponse.participantId;\r\n }\r\n public get roomid(): string {\r\n return this.privCommandResponse.roomid;\r\n }\r\n public get value(): boolean | number | string {\r\n return this.privCommandResponse.value;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the payload for incoming list of participants\r\n */\r\nexport interface IParticipantsListPayloadResponse {\r\n roomid: string;\r\n id: string;\r\n command: string;\r\n participants: IParticipantPayloadResponse[];\r\n token: string;\r\n translateTo: string[];\r\n profanityFilter: string;\r\n roomProfanityFilter: string;\r\n roomLocked: boolean;\r\n muteAll: boolean;\r\n type: string;\r\n}\r\n\r\n/**\r\n * Defines the payload for incoming participant\r\n */\r\nexport interface IParticipantPayloadResponse {\r\n nickname: string;\r\n locale: string;\r\n usetts: boolean;\r\n ismuted: boolean;\r\n ishost: boolean;\r\n participantId: string;\r\n avatar?: string;\r\n}\r\n\r\nexport class ParticipantsListPayloadResponse implements IParticipantsListPayloadResponse {\r\n private privParticipantsPayloadResponse: IParticipantsListPayloadResponse;\r\n\r\n private constructor(json: string) {\r\n this.privParticipantsPayloadResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): ParticipantsListPayloadResponse {\r\n return new ParticipantsListPayloadResponse(json);\r\n }\r\n\r\n public get roomid(): string {\r\n return this.privParticipantsPayloadResponse.roomid;\r\n }\r\n\r\n public get id(): string {\r\n return this.privParticipantsPayloadResponse.id;\r\n }\r\n\r\n public get command(): string {\r\n return this.privParticipantsPayloadResponse.command;\r\n }\r\n\r\n public get participants(): IParticipantPayloadResponse[] {\r\n return this.privParticipantsPayloadResponse.participants;\r\n }\r\n\r\n public get token(): string {\r\n return this.privParticipantsPayloadResponse.token;\r\n }\r\n\r\n public get translateTo(): string[] {\r\n return this.privParticipantsPayloadResponse.translateTo;\r\n }\r\n\r\n public get profanityFilter(): string {\r\n return this.privParticipantsPayloadResponse.profanityFilter;\r\n }\r\n\r\n public get roomProfanityFilter(): string {\r\n return this.privParticipantsPayloadResponse.roomProfanityFilter;\r\n }\r\n\r\n public get roomLocked(): boolean {\r\n return this.privParticipantsPayloadResponse.roomLocked;\r\n }\r\n\r\n public get muteAll(): boolean {\r\n return this.privParticipantsPayloadResponse.muteAll;\r\n }\r\n\r\n public get type(): string {\r\n return this.privParticipantsPayloadResponse.type;\r\n }\r\n\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ParticipantPayloadResponse implements IParticipantPayloadResponse {\r\n\r\n private privParticipantPayloadResponse: IParticipantPayloadResponse;\r\n\r\n private constructor(json: string) {\r\n this.privParticipantPayloadResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): ParticipantPayloadResponse {\r\n return new ParticipantPayloadResponse(json);\r\n }\r\n\r\n public get nickname(): string {\r\n return this.privParticipantPayloadResponse.nickname;\r\n }\r\n\r\n public get locale(): string {\r\n return this.privParticipantPayloadResponse.locale;\r\n }\r\n\r\n public get usetts(): boolean {\r\n return this.privParticipantPayloadResponse.usetts;\r\n }\r\n\r\n public get ismuted(): boolean {\r\n return this.privParticipantPayloadResponse.ismuted;\r\n }\r\n\r\n public get ishost(): boolean {\r\n return this.privParticipantPayloadResponse.ishost;\r\n }\r\n\r\n public get participantId(): string {\r\n return this.privParticipantPayloadResponse.participantId;\r\n }\r\n\r\n public get avatar(): string {\r\n return this.privParticipantPayloadResponse.avatar;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the payload for incoming translation messages\r\n */\r\nexport interface ITranslationResponsePayload {\r\n lang: string;\r\n translation: string;\r\n}\r\n\r\nexport interface ITranslationCommandMessage {\r\n translations: ITranslationResponsePayload[];\r\n id: string;\r\n language: string;\r\n nickname: string;\r\n participantId: string;\r\n roomid: string;\r\n timestamp: string;\r\n type: string;\r\n}\r\n\r\nexport interface ISpeechResponsePayload extends ITranslationCommandMessage {\r\n recognition: string;\r\n isFinal: boolean;\r\n}\r\n\r\nexport interface ITextResponsePayload extends ITranslationCommandMessage {\r\n originalText: string;\r\n}\r\n\r\nexport class SpeechResponsePayload implements ISpeechResponsePayload {\r\n\r\n private privSpeechResponse: ISpeechResponsePayload;\r\n\r\n private constructor(json: string) {\r\n this.privSpeechResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SpeechResponsePayload {\r\n return new SpeechResponsePayload(json);\r\n }\r\n\r\n public get recognition(): string {\r\n return this.privSpeechResponse.recognition;\r\n }\r\n\r\n public get translations(): ITranslationResponsePayload[] {\r\n return this.privSpeechResponse.translations;\r\n }\r\n\r\n public get id(): string {\r\n return this.privSpeechResponse.id;\r\n }\r\n\r\n public get language(): string {\r\n return this.privSpeechResponse.language;\r\n }\r\n\r\n public get nickname(): string {\r\n return this.privSpeechResponse.nickname;\r\n }\r\n\r\n public get participantId(): string {\r\n return this.privSpeechResponse.participantId;\r\n }\r\n\r\n public get roomid(): string {\r\n return this.privSpeechResponse.roomid;\r\n }\r\n\r\n public get timestamp(): string {\r\n return this.privSpeechResponse.timestamp;\r\n }\r\n\r\n public get type(): string {\r\n return this.privSpeechResponse.type;\r\n }\r\n\r\n public get isFinal(): boolean {\r\n return this.privSpeechResponse.type === \"final\";\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class TextResponsePayload implements ITextResponsePayload {\r\n\r\n private privTextResponse: ITextResponsePayload;\r\n\r\n private constructor(json: string) {\r\n this.privTextResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): TextResponsePayload {\r\n return new TextResponsePayload(json);\r\n }\r\n\r\n public get originalText(): string {\r\n return this.privTextResponse.originalText;\r\n }\r\n\r\n public get translations(): ITranslationResponsePayload[] {\r\n return this.privTextResponse.translations;\r\n }\r\n\r\n public get id(): string {\r\n return this.privTextResponse.id;\r\n }\r\n\r\n public get language(): string {\r\n return this.privTextResponse.language;\r\n }\r\n\r\n public get nickname(): string {\r\n return this.privTextResponse.nickname;\r\n }\r\n\r\n public get participantId(): string {\r\n return this.privTextResponse.participantId;\r\n }\r\n\r\n public get roomid(): string {\r\n return this.privTextResponse.roomid;\r\n }\r\n\r\n public get timestamp(): string {\r\n return this.privTextResponse.timestamp;\r\n }\r\n\r\n public get type(): string {\r\n return this.privTextResponse.type;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionMessage,\r\n ConnectionState,\r\n createNoDashGuid,\r\n Deferred,\r\n IAudioSource,\r\n IConnection,\r\n MessageType,\r\n} from \"../../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n ConversationExpirationEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n ConversationTranslationResult,\r\n Translations\r\n} from \"../../sdk/Exports\";\r\nimport {\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognizerConfig,\r\n ServiceRecognizerBase\r\n} from \"../Exports\";\r\nimport { ConversationConnectionMessage } from \"./ConversationConnectionMessage\";\r\nimport { ConversationRequestSession } from \"./ConversationRequestSession\";\r\nimport {\r\n ConversationReceivedTranslationEventArgs,\r\n LockRoomEventArgs,\r\n MuteAllEventArgs,\r\n ParticipantAttributeEventArgs,\r\n ParticipantEventArgs,\r\n ParticipantsListEventArgs\r\n} from \"./ConversationTranslatorEventArgs\";\r\nimport {\r\n ConversationTranslatorCommandTypes,\r\n ConversationTranslatorMessageTypes,\r\n IInternalParticipant\r\n} from \"./ConversationTranslatorInterfaces\";\r\nimport { ConversationTranslatorRecognizer } from \"./ConversationTranslatorRecognizer\";\r\nimport {\r\n CommandResponsePayload,\r\n IParticipantPayloadResponse,\r\n IParticipantsListPayloadResponse,\r\n ITranslationResponsePayload,\r\n ParticipantPayloadResponse,\r\n ParticipantsListPayloadResponse,\r\n SpeechResponsePayload,\r\n TextResponsePayload\r\n} from \"./ServiceMessages/Exports\";\r\n\r\n/***\r\n * The service adapter handles sending and receiving messages to the Conversation Translator websocket.\r\n */\r\nexport class ConversationServiceAdapter extends ServiceRecognizerBase {\r\n private privConversationServiceConnector: ConversationTranslatorRecognizer;\r\n private privConversationConnectionFactory: IConnectionFactory;\r\n private privConversationAuthFetchEventId: string;\r\n private privConversationAuthentication: IAuthentication;\r\n private privConversationRequestSession: ConversationRequestSession;\r\n private privConnectionConfigPromise: Promise;\r\n private privConnectionLoop: Promise;\r\n private terminateMessageLoop: boolean;\r\n private privLastPartialUtteranceId: string = \"\";\r\n private privConversationIsDisposed: boolean;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n conversationServiceConnector: ConversationTranslatorRecognizer) {\r\n\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, conversationServiceConnector);\r\n\r\n this.privConversationServiceConnector = conversationServiceConnector;\r\n this.privConversationAuthentication = authentication;\r\n this.receiveMessageOverride = this.receiveConversationMessageOverride;\r\n this.recognizeOverride = this.noOp;\r\n this.postConnectImplOverride = this.conversationConnectImpl;\r\n this.configConnectionOverride = this.configConnection;\r\n this.disconnectOverride = this.privDisconnect;\r\n this.privConversationRequestSession = new ConversationRequestSession(createNoDashGuid());\r\n this.privConversationConnectionFactory = connectionFactory;\r\n this.privConversationIsDisposed = false;\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return super.isDisposed() || this.privConversationIsDisposed;\r\n }\r\n\r\n public async dispose(reason?: string): Promise {\r\n this.privConversationIsDisposed = true;\r\n if (this.privConnectionConfigPromise) {\r\n const connection: IConnection = await this.privConnectionConfigPromise;\r\n await connection.dispose(reason);\r\n }\r\n await super.dispose(reason);\r\n }\r\n\r\n public async sendMessage(message: string): Promise {\r\n const connection: IConnection = await this.fetchConnection();\r\n return connection.send(new ConversationConnectionMessage(\r\n MessageType.Text,\r\n message));\r\n }\r\n\r\n public async sendMessageAsync(message: string): Promise {\r\n const sink: Deferred = new Deferred();\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n\r\n await connection.send(new ConversationConnectionMessage(MessageType.Text, message));\r\n }\r\n\r\n protected privDisconnect(): Promise {\r\n if (this.terminateMessageLoop) {\r\n return;\r\n }\r\n this.cancelRecognition(this.privConversationRequestSession.sessionId,\r\n this.privConversationRequestSession.requestId,\r\n CancellationReason.Error,\r\n CancellationErrorCode.NoError,\r\n \"Disconnecting\");\r\n\r\n this.terminateMessageLoop = true;\r\n return Promise.resolve();\r\n }\r\n\r\n protected async processTypeSpecificMessages(\r\n connectionMessage: ConnectionMessage,\r\n successCallback?: (e: any) => void,\r\n errorCallBack?: (e: string) => void): Promise {\r\n return true;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n this.terminateMessageLoop = true;\r\n\r\n const cancelEvent: ConversationTranslationCanceledEventArgs = new ConversationTranslationCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n sessionId);\r\n\r\n try {\r\n if (!!this.privConversationServiceConnector.canceled) {\r\n this.privConversationServiceConnector.canceled(this.privConversationServiceConnector, cancelEvent);\r\n }\r\n } catch {\r\n // continue on error\r\n }\r\n }\r\n\r\n protected noOp = (): any => {\r\n // operation not supported\r\n }\r\n\r\n /**\r\n * Establishes a websocket connection to the end point.\r\n * @param isUnAuthorized\r\n */\r\n protected async conversationConnectImpl(connection: Promise): Promise {\r\n this.privConnectionLoop = this.startMessageLoop();\r\n return connection;\r\n }\r\n\r\n /**\r\n * Process incoming websocket messages\r\n */\r\n private async receiveConversationMessageOverride(): Promise {\r\n if (this.isDisposed() || this.terminateMessageLoop) {\r\n return Promise.resolve();\r\n }\r\n // we won't rely on the cascading promises of the connection since we want to continually be available to receive messages\r\n const communicationCustodian: Deferred = new Deferred();\r\n\r\n try {\r\n const connection: IConnection = await this.fetchConnection();\r\n const message: ConversationConnectionMessage = await connection.read() as ConversationConnectionMessage;\r\n if (this.isDisposed() || this.terminateMessageLoop) {\r\n // We're done.\r\n communicationCustodian.resolve();\r\n return Promise.resolve();\r\n }\r\n\r\n if (!message) {\r\n return this.receiveConversationMessageOverride();\r\n }\r\n\r\n const sessionId: string = this.privConversationRequestSession.sessionId;\r\n let sendFinal: boolean = false;\r\n\r\n try {\r\n switch (message.conversationMessageType.toLowerCase()) {\r\n case \"info\":\r\n case \"participant_command\":\r\n case \"command\":\r\n const commandPayload: CommandResponsePayload = CommandResponsePayload.fromJSON(message.textBody);\r\n switch (commandPayload.command.toLowerCase()) {\r\n\r\n /**\r\n * 'ParticpantList' is the first message sent to the user after the websocket connection has opened.\r\n * The consuming client must wait for this message to arrive\r\n * before starting to send their own data.\r\n */\r\n case \"participantlist\":\r\n\r\n const participantsPayload: IParticipantsListPayloadResponse = ParticipantsListPayloadResponse.fromJSON(message.textBody);\r\n\r\n const participantsResult: IInternalParticipant[] = participantsPayload.participants.map((p: IParticipantPayloadResponse) => {\r\n const participant: IInternalParticipant = {\r\n avatar: p.avatar,\r\n displayName: p.nickname,\r\n id: p.participantId,\r\n isHost: p.ishost,\r\n isMuted: p.ismuted,\r\n isUsingTts: p.usetts,\r\n preferredLanguage: p.locale\r\n };\r\n return participant;\r\n });\r\n\r\n if (!!this.privConversationServiceConnector.participantsListReceived) {\r\n this.privConversationServiceConnector.participantsListReceived(this.privConversationServiceConnector,\r\n new ParticipantsListEventArgs(participantsPayload.roomid, participantsPayload.token,\r\n participantsPayload.translateTo, participantsPayload.profanityFilter,\r\n participantsPayload.roomProfanityFilter, participantsPayload.roomLocked,\r\n participantsPayload.muteAll, participantsResult, sessionId));\r\n }\r\n break;\r\n\r\n /**\r\n * 'SetTranslateToLanguages' represents the list of languages being used in the Conversation by all users(?).\r\n * This is sent at the start of the Conversation\r\n */\r\n case \"settranslatetolanguages\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.setTranslateToLanguages,\r\n commandPayload.value, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetProfanityFiltering' lets the client set the level of profanity filtering.\r\n * If sent by the participant the setting will effect only their own profanity level.\r\n * If sent by the host, the setting will effect all participants including the host.\r\n * Note: the profanity filters differ from Speech Service (?): 'marked', 'raw', 'removed', 'tagged'\r\n */\r\n case \"setprofanityfiltering\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.setProfanityFiltering,\r\n commandPayload.value, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetMute' is sent if the participant has been muted by the host.\r\n * Check the 'participantId' to determine if the current user has been muted.\r\n */\r\n case \"setmute\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.setMute,\r\n commandPayload.value, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetMuteAll' is sent if the Conversation has been muted by the host.\r\n */\r\n case \"setmuteall\":\r\n\r\n if (!!this.privConversationServiceConnector.muteAllCommandReceived) {\r\n this.privConversationServiceConnector.muteAllCommandReceived(this.privConversationServiceConnector,\r\n new MuteAllEventArgs(commandPayload.value as boolean, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'RoomExpirationWarning' is sent towards the end of the Conversation session to give a timeout warning.\r\n */\r\n case \"roomexpirationwarning\":\r\n\r\n if (!!this.privConversationServiceConnector.conversationExpiration) {\r\n this.privConversationServiceConnector.conversationExpiration(this.privConversationServiceConnector,\r\n new ConversationExpirationEventArgs(commandPayload.value as number, this.privConversationRequestSession.sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetUseTts' is sent as a confirmation if the user requests TTS to be turned on or off.\r\n */\r\n case \"setusetts\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.setUseTTS,\r\n commandPayload.value, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetLockState' is set if the host has locked or unlocked the Conversation.\r\n */\r\n case \"setlockstate\":\r\n\r\n if (!!this.privConversationServiceConnector.lockRoomCommandReceived) {\r\n this.privConversationServiceConnector.lockRoomCommandReceived(this.privConversationServiceConnector,\r\n new LockRoomEventArgs(commandPayload.value as boolean, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'ChangeNickname' is received if a user changes their display name.\r\n * Any cached particpiants list should be updated to reflect the display name.\r\n */\r\n case \"changenickname\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.changeNickname,\r\n commandPayload.nickname, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'JoinSession' is sent when a user joins the Conversation.\r\n */\r\n case \"joinsession\":\r\n\r\n const joinParticipantPayload: ParticipantPayloadResponse = ParticipantPayloadResponse.fromJSON(message.textBody);\r\n\r\n const joiningParticipant: IInternalParticipant = {\r\n avatar: joinParticipantPayload.avatar,\r\n displayName: joinParticipantPayload.nickname,\r\n id: joinParticipantPayload.participantId,\r\n isHost: joinParticipantPayload.ishost,\r\n isMuted: joinParticipantPayload.ismuted,\r\n isUsingTts: joinParticipantPayload.usetts,\r\n preferredLanguage: joinParticipantPayload.locale,\r\n };\r\n\r\n if (!!this.privConversationServiceConnector.participantJoinCommandReceived) {\r\n this.privConversationServiceConnector.participantJoinCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantEventArgs(\r\n joiningParticipant,\r\n sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'LeaveSession' is sent when a user leaves the Conversation'.\r\n */\r\n case \"leavesession\":\r\n\r\n const leavingParticipant: IInternalParticipant = {\r\n id: commandPayload.participantId\r\n };\r\n\r\n if (!!this.privConversationServiceConnector.participantLeaveCommandReceived) {\r\n this.privConversationServiceConnector.participantLeaveCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantEventArgs(leavingParticipant, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'DisconnectSession' is sent when a user is disconnected from the session (e.g. network problem).\r\n * Check the 'ParticipantId' to check whether the message is for the current user.\r\n */\r\n case \"disconnectsession\":\r\n\r\n const disconnectParticipant: IInternalParticipant = {\r\n id: commandPayload.participantId\r\n };\r\n\r\n break;\r\n\r\n /**\r\n * Message not recognized.\r\n */\r\n default:\r\n break;\r\n }\r\n break;\r\n\r\n /**\r\n * 'partial' (or 'hypothesis') represents a unfinalized speech message.\r\n */\r\n case \"partial\":\r\n\r\n /**\r\n * 'final' (or 'phrase') represents a finalized speech message.\r\n */\r\n case \"final\":\r\n\r\n const speechPayload: SpeechResponsePayload = SpeechResponsePayload.fromJSON(message.textBody);\r\n\r\n const speechResult: ConversationTranslationResult = new ConversationTranslationResult(speechPayload.participantId,\r\n this.getTranslations(speechPayload.translations),\r\n speechPayload.language,\r\n undefined,\r\n undefined,\r\n speechPayload.recognition,\r\n undefined,\r\n undefined,\r\n message.textBody,\r\n undefined);\r\n\r\n if (speechPayload.isFinal) {\r\n // check the length, sometimes empty finals are returned\r\n if (speechResult.text !== undefined && speechResult.text.length > 0) {\r\n sendFinal = true;\r\n } else if (speechPayload.id === this.privLastPartialUtteranceId) {\r\n // send final as normal. We had a non-empty partial for this same utterance\r\n // so sending the empty final is important\r\n sendFinal = true;\r\n } else {\r\n // suppress unneeded final\r\n }\r\n\r\n if (sendFinal) {\r\n if (!!this.privConversationServiceConnector.translationReceived) {\r\n this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector,\r\n new ConversationReceivedTranslationEventArgs(ConversationTranslatorMessageTypes.final, speechResult, sessionId));\r\n }\r\n }\r\n } else if (speechResult.text !== undefined) {\r\n this.privLastPartialUtteranceId = speechPayload.id;\r\n if (!!this.privConversationServiceConnector.translationReceived) {\r\n this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector,\r\n new ConversationReceivedTranslationEventArgs(ConversationTranslatorMessageTypes.partial, speechResult, sessionId));\r\n }\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * \"translated_message\" is a text message or instant message (IM).\r\n */\r\n case \"translated_message\":\r\n\r\n const textPayload: TextResponsePayload = TextResponsePayload.fromJSON(message.textBody);\r\n\r\n const textResult: ConversationTranslationResult = new ConversationTranslationResult(textPayload.participantId,\r\n this.getTranslations(textPayload.translations),\r\n textPayload.language,\r\n undefined,\r\n undefined,\r\n textPayload.originalText,\r\n undefined,\r\n undefined,\r\n undefined,\r\n message.textBody,\r\n undefined);\r\n\r\n if (!!this.privConversationServiceConnector.translationReceived) {\r\n this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector,\r\n new ConversationReceivedTranslationEventArgs(ConversationTranslatorMessageTypes.instantMessage, textResult, sessionId));\r\n }\r\n break;\r\n\r\n default:\r\n // ignore any unsupported message types\r\n break;\r\n }\r\n } catch (e) {\r\n // continue\r\n }\r\n return this.receiveConversationMessageOverride();\r\n } catch (e) {\r\n this.terminateMessageLoop = true;\r\n }\r\n\r\n return communicationCustodian.promise;\r\n }\r\n\r\n private async startMessageLoop(): Promise {\r\n if (this.isDisposed()) {\r\n return Promise.resolve();\r\n }\r\n this.terminateMessageLoop = false;\r\n\r\n const messageRetrievalPromise = this.receiveConversationMessageOverride();\r\n\r\n try {\r\n const r = await messageRetrievalPromise;\r\n return r;\r\n } catch (error) {\r\n this.cancelRecognition(this.privRequestSession ? this.privRequestSession.sessionId : \"\", this.privRequestSession ? this.privRequestSession.requestId : \"\", CancellationReason.Error, CancellationErrorCode.RuntimeError, error);\r\n return null;\r\n }\r\n }\r\n\r\n // Takes an established websocket connection to the endpoint\r\n private configConnection(): Promise {\r\n if (this.isDisposed()) {\r\n return Promise.resolve(undefined);\r\n }\r\n if (this.privConnectionConfigPromise) {\r\n return this.privConnectionConfigPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigPromise = null;\r\n return this.configConnection();\r\n }\r\n return this.privConnectionConfigPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigPromise = null;\r\n return this.configConnection();\r\n });\r\n }\r\n if (this.terminateMessageLoop) {\r\n return Promise.resolve(undefined);\r\n }\r\n\r\n this.privConnectionConfigPromise = this.connectImpl().then((connection: IConnection): any => {\r\n return connection;\r\n });\r\n\r\n return this.privConnectionConfigPromise;\r\n }\r\n\r\n private getTranslations(serviceResultTranslations: ITranslationResponsePayload[]): Translations {\r\n let translations: Translations;\r\n\r\n if (undefined !== serviceResultTranslations) {\r\n translations = new Translations();\r\n for (const translation of serviceResultTranslations) {\r\n translations.set(translation.lang, translation.translation);\r\n }\r\n }\r\n\r\n return translations;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nexport enum ParticipantChangedReason {\r\n /** Participant has joined the conversation. */\r\n JoinedConversation,\r\n\r\n /** Participant has left the conversation. This could be voluntary, or involuntary\r\n * (e.g. they are experiencing networking issues).\r\n */\r\n LeftConversation,\r\n\r\n /** The participants' state has changed (e.g. they became muted, changed their nickname). */\r\n Updated\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig\r\n} from \"../../common.speech/Exports\";\r\nimport {\r\n BackgroundEvent,\r\n Events\r\n} from \"../../common/Exports\";\r\nimport { AudioConfigImpl } from \"../../sdk/Audio/AudioConfig\";\r\nimport { Contracts } from \"../../sdk/Contracts\";\r\nimport {\r\n AudioConfig,\r\n Connection,\r\n ConnectionEventArgs,\r\n ConversationExpirationEventArgs,\r\n ConversationParticipantsChangedEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n PropertyCollection,\r\n Recognizer,\r\n SessionEventArgs,\r\n SpeechTranslationConfig\r\n} from \"../../sdk/Exports\";\r\nimport { SpeechTranslationConfigImpl } from \"../../sdk/SpeechTranslationConfig\";\r\nimport { Callback } from \"../../sdk/Transcription/IConversation\";\r\nimport { ConversationConnectionFactory } from \"./ConversationConnectionFactory\";\r\nimport { ConversationServiceAdapter } from \"./ConversationServiceAdapter\";\r\nimport {\r\n ConversationReceivedTranslationEventArgs,\r\n LockRoomEventArgs,\r\n MuteAllEventArgs,\r\n ParticipantAttributeEventArgs,\r\n ParticipantEventArgs,\r\n ParticipantsListEventArgs\r\n} from \"./ConversationTranslatorEventArgs\";\r\nimport {\r\n ConversationRecognizer,\r\n} from \"./ConversationTranslatorInterfaces\";\r\nimport { PromiseToEmptyCallback } from \"./ConversationUtils\";\r\n\r\nexport class ConversationRecognizerFactory {\r\n public static fromConfig(speechConfig: SpeechTranslationConfig, audioConfig?: AudioConfig): ConversationRecognizer {\r\n return new ConversationTranslatorRecognizer(speechConfig, audioConfig);\r\n }\r\n}\r\n\r\n/**\r\n * Sends messages to the Conversation Translator websocket and listens for incoming events containing websocket messages.\r\n * Based off the recognizers in the SDK folder.\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class ConversationTranslatorRecognizer extends Recognizer implements ConversationRecognizer {\r\n\r\n private privIsDisposed: boolean;\r\n private privSpeechRecognitionLanguage: string;\r\n private privConnection: Connection;\r\n\r\n public constructor(speechConfig: SpeechTranslationConfig, audioConfig?: AudioConfig) {\r\n const serviceConfigImpl = speechConfig as SpeechTranslationConfigImpl;\r\n Contracts.throwIfNull(serviceConfigImpl, \"speechConfig\");\r\n\r\n super(audioConfig, serviceConfigImpl.properties, new ConversationConnectionFactory());\r\n\r\n this.privIsDisposed = false;\r\n this.privProperties = serviceConfigImpl.properties.clone();\r\n this.privConnection = Connection.fromRecognizer(this);\r\n }\r\n\r\n public canceled: (sender: ConversationRecognizer, event: ConversationTranslationCanceledEventArgs) => void;\r\n public conversationExpiration: (sender: ConversationRecognizer, event: ConversationExpirationEventArgs) => void;\r\n public lockRoomCommandReceived: (sender: ConversationRecognizer, event: LockRoomEventArgs) => void;\r\n public muteAllCommandReceived: (sender: ConversationRecognizer, event: MuteAllEventArgs) => void;\r\n public participantJoinCommandReceived: (sender: ConversationRecognizer, event: ParticipantEventArgs) => void;\r\n public participantLeaveCommandReceived: (sender: ConversationRecognizer, event: ParticipantEventArgs) => void;\r\n public participantUpdateCommandReceived: (sender: ConversationRecognizer, event: ParticipantAttributeEventArgs) => void;\r\n public connectionOpened: (sender: ConversationRecognizer, event: SessionEventArgs) => void;\r\n public connectionClosed: (sender: ConversationRecognizer, event: SessionEventArgs) => void;\r\n public translationReceived: (sender: ConversationRecognizer, event: ConversationReceivedTranslationEventArgs) => void;\r\n public participantsListReceived: (sender: ConversationRecognizer, event: ParticipantsListEventArgs) => void;\r\n public participantsChanged: (sender: ConversationRecognizer, event: ConversationParticipantsChangedEventArgs) => void;\r\n\r\n public set connected(cb: (e: ConnectionEventArgs) => void) {\r\n this.privConnection.connected = cb;\r\n }\r\n\r\n public set disconnected(cb: (e: ConnectionEventArgs) => void) {\r\n this.privConnection.disconnected = cb;\r\n }\r\n\r\n /**\r\n * Return the speech language used by the recognizer\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n return this.privSpeechRecognitionLanguage;\r\n }\r\n\r\n /**\r\n * Return the properties for the recognizer\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return this.privIsDisposed;\r\n }\r\n\r\n /**\r\n * Connect to the recognizer\r\n * @param token\r\n */\r\n public connect(token: string, cb?: () => void, err?: (e: string) => void): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.privReco.conversationTranslatorToken = token;\r\n this.privReco.connectAsync(cb, err);\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Disconnect from the recognizer\r\n */\r\n public disconnect(cb?: () => void, err?: (e: string) => void): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n this.privReco.disconnect().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string) => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n }\r\n // Destroy the recognizer.\r\n this.dispose(true).catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n\r\n }\r\n }\r\n\r\n /**\r\n * Send the mute all participants command to the websocket\r\n * @param conversationId\r\n * @param participantId\r\n * @param isMuted\r\n */\r\n public sendRequest(command: string, cb?: () => void, err?: (e: string) => void): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n this.sendMessage(command, cb, err);\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n }\r\n\r\n // Destroy the recognizer.\r\n this.dispose(true).catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n\r\n }\r\n }\r\n\r\n /**\r\n * Close and dispose the recognizer\r\n */\r\n public async close(): Promise {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n this.privConnection?.closeConnection();\r\n this.privConnection?.close();\r\n this.privConnection = undefined;\r\n await this.dispose(true);\r\n }\r\n\r\n /**\r\n * Dispose the recognizer\r\n * @param disposing\r\n */\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privIsDisposed) {\r\n return;\r\n }\r\n if (disposing) {\r\n this.privIsDisposed = true;\r\n if (!!this.privConnection) {\r\n this.privConnection.closeConnection();\r\n this.privConnection.close();\r\n this.privConnection = undefined;\r\n }\r\n await super.dispose(disposing);\r\n }\r\n }\r\n\r\n /**\r\n * Create the config for the recognizer\r\n * @param speechConfig\r\n */\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(speechConfig, this.privProperties);\r\n }\r\n\r\n /**\r\n * Create the service recognizer.\r\n * The audio source is redundnant here but is required by the implementation.\r\n * @param authentication\r\n * @param connectionFactory\r\n * @param audioConfig\r\n * @param recognizerConfig\r\n */\r\n protected createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n\r\n const audioSource: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n\r\n return new ConversationServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this);\r\n }\r\n\r\n private sendMessage(msg: string, cb?: Callback, err?: Callback): void {\r\n const withAsync = this.privReco as ConversationServiceAdapter;\r\n PromiseToEmptyCallback(withAsync.sendMessageAsync(msg), cb, err);\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nimport { SessionEventArgs } from \"../Exports\";\r\nimport { ParticipantChangedReason } from \"./Exports\";\r\nimport { IParticipant } from \"./IParticipant\";\r\n\r\nexport class ConversationParticipantsChangedEventArgs extends SessionEventArgs {\r\n private privReason: ParticipantChangedReason;\r\n private privParticipant: IParticipant[];\r\n\r\n public constructor(reason: ParticipantChangedReason, participants: IParticipant[], sessionId?: string) {\r\n super(sessionId);\r\n this.privReason = reason;\r\n this.privParticipant = participants;\r\n }\r\n\r\n public get reason(): ParticipantChangedReason {\r\n return this.privReason;\r\n }\r\n\r\n public get participants(): IParticipant[] {\r\n return this.privParticipant;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nimport { RecognitionEventArgs } from \"../Exports\";\r\nimport { ConversationTranslationResult } from \"./Exports\";\r\n\r\nexport class ConversationTranslationEventArgs extends RecognitionEventArgs {\r\n private privResult: ConversationTranslationResult;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {ConversationTranslationResult} result - The translation recognition result.\r\n * @param {number} offset - The offset.\r\n * @param {string} sessionId - The session id.\r\n */\r\n public constructor(result: ConversationTranslationResult, offset?: number, sessionId?: string) {\r\n super(offset, sessionId);\r\n this.privResult = result;\r\n }\r\n\r\n /**\r\n * Specifies the recognition result.\r\n * @returns {ConversationTranslationResult} the recognition result.\r\n */\r\n public get result(): ConversationTranslationResult {\r\n return this.privResult;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nimport { PropertyCollection } from \"../Exports\";\r\n\r\n/**\r\n * Represents a user in a conversation.\r\n * Added in version 1.4.0\r\n */\r\nexport interface IUser {\r\n /** Gets the user's ID */\r\n readonly userId: string;\r\n}\r\n\r\nexport class User implements IUser {\r\n private privUserId: string;\r\n\r\n constructor(userId: string) {\r\n this.privUserId = userId;\r\n }\r\n\r\n public get userId(): string {\r\n return this.privUserId;\r\n }\r\n}\r\n\r\nexport interface VoiceSignature {\r\n Version: number;\r\n Tag: string;\r\n Data: string;\r\n}\r\n\r\nexport interface TranscriptionParticipant {\r\n /** The unique identifier for the participant. */\r\n readonly id: string;\r\n /** The participant's preferred spoken language. */\r\n readonly preferredLanguage: string;\r\n /** The participant's voice signature */\r\n readonly voice: string;\r\n}\r\n\r\n/**\r\n * Represents a participant in a conversation.\r\n * Added in version 1.4.0\r\n */\r\nexport interface IParticipant extends TranscriptionParticipant {\r\n /** Gets the colour of the user's avatar as an HTML hex string (e.g. FF0000 for red). */\r\n readonly avatar: string;\r\n /**\r\n * The participant's display name. Please note that there may be more than one participant\r\n * with the same name. You can use property to tell them apart.\r\n */\r\n readonly displayName: string;\r\n /** Gets whether or not this participant is the host. */\r\n readonly isHost: boolean;\r\n /** Gets whether or not this participant is muted. */\r\n readonly isMuted: boolean;\r\n /** Gets whether or not the participant is using Text To Speech (TTS). */\r\n readonly isUsingTts: boolean;\r\n /** Contains properties of the participant. */\r\n readonly properties: PropertyCollection;\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class Participant implements IParticipant {\r\n private privAvatar: string;\r\n private privDisplayName: string;\r\n private privId: string;\r\n private privIsHost: boolean;\r\n private privIsMuted: boolean;\r\n private privIsUsingTts: boolean;\r\n private privPreferredLanguage: string;\r\n private privVoice: string;\r\n private privProperties: PropertyCollection;\r\n\r\n constructor(id: string, avatar: string, displayName: string, isHost: boolean, isMuted: boolean, isUsingTts: boolean, preferredLanguage: string, voice?: string) {\r\n this.privId = id;\r\n this.privAvatar = avatar;\r\n this.privDisplayName = displayName;\r\n this.privIsHost = isHost;\r\n this.privIsMuted = isMuted;\r\n this.privIsUsingTts = isUsingTts;\r\n this.privPreferredLanguage = preferredLanguage;\r\n this.privVoice = voice;\r\n this.privProperties = new PropertyCollection();\r\n }\r\n\r\n public static From(id: string, language: string, voice: string): IParticipant {\r\n return new Participant(id, \"\", id, false, false, false, language, voice);\r\n }\r\n\r\n public get avatar(): string {\r\n return this.privAvatar;\r\n }\r\n\r\n public get displayName(): string {\r\n return this.privDisplayName;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n\r\n public get preferredLanguage(): string {\r\n return this.privPreferredLanguage;\r\n }\r\n\r\n public get isHost(): boolean {\r\n return this.privIsHost;\r\n }\r\n\r\n public get isMuted(): boolean {\r\n return this.privIsMuted;\r\n }\r\n\r\n public get isUsingTts(): boolean {\r\n return this.privIsUsingTts;\r\n }\r\n\r\n public get voice(): string {\r\n return this.privVoice;\r\n }\r\n\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nimport {\r\n ConversationConnectionConfig,\r\n ConversationManager,\r\n ConversationReceivedTranslationEventArgs,\r\n ConversationRecognizer,\r\n ConversationRecognizerFactory,\r\n ConversationTranslatorCommandTypes,\r\n ConversationTranslatorMessageTypes,\r\n IInternalConversation,\r\n IInternalParticipant,\r\n InternalParticipants,\r\n LockRoomEventArgs,\r\n MuteAllEventArgs,\r\n ParticipantAttributeEventArgs,\r\n ParticipantEventArgs,\r\n ParticipantsListEventArgs,\r\n TranscriberRecognizer\r\n} from \"../../common.speech/Exports\";\r\nimport {\r\n IDisposable,\r\n IErrorMessages,\r\n marshalPromiseToCallbacks\r\n} from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n Connection,\r\n ConnectionEventArgs,\r\n ConversationExpirationEventArgs,\r\n ConversationParticipantsChangedEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n ConversationTranslationEventArgs,\r\n ConversationTranslator,\r\n Participant,\r\n ParticipantChangedReason,\r\n ProfanityOption,\r\n PropertyCollection,\r\n PropertyId,\r\n SpeechTranslationConfig,\r\n} from \"../Exports\";\r\nimport { SpeechTranslationConfigImpl } from \"../SpeechTranslationConfig\";\r\nimport { Callback, ConversationInfo, IConversation } from \"./IConversation\";\r\nimport { IParticipant, IUser, TranscriptionParticipant } from \"./IParticipant\";\r\n\r\nexport abstract class Conversation implements IConversation {\r\n\r\n public abstract get authorizationToken(): string;\r\n public abstract set authorizationToken(value: string);\r\n\r\n public abstract get config(): SpeechTranslationConfig;\r\n\r\n public abstract get conversationId(): string;\r\n public abstract get conversationInfo(): ConversationInfo;\r\n public abstract get properties(): PropertyCollection;\r\n public abstract get speechRecognitionLanguage(): string;\r\n public abstract get participants(): Participant[];\r\n\r\n protected constructor() { }\r\n\r\n /**\r\n * Create a conversation\r\n * @param speechConfig\r\n * @param cb\r\n * @param err\r\n */\r\n public static createConversationAsync(speechConfig: SpeechTranslationConfig, arg2?: string | Callback, arg3?: Callback, arg4?: Callback): Conversation {\r\n Contracts.throwIfNullOrUndefined(speechConfig, ConversationConnectionConfig.restErrors.invalidArgs.replace(\"{arg}\", \"config\"));\r\n Contracts.throwIfNullOrUndefined(speechConfig.region, ConversationConnectionConfig.restErrors.invalidArgs.replace(\"{arg}\", \"SpeechServiceConnection_Region\"));\r\n if (!speechConfig.subscriptionKey && !speechConfig.getProperty(PropertyId[PropertyId.SpeechServiceAuthorization_Token])) {\r\n Contracts.throwIfNullOrUndefined(speechConfig.subscriptionKey, ConversationConnectionConfig.restErrors.invalidArgs.replace(\"{arg}\", \"SpeechServiceConnection_Key\"));\r\n }\r\n if (typeof arg2 === \"string\") {\r\n const conversationImpl: ConversationImpl = new ConversationImpl(speechConfig, arg2);\r\n marshalPromiseToCallbacks((async (): Promise => { return; })(), arg3, arg4);\r\n return conversationImpl;\r\n } else {\r\n const conversationImpl: ConversationImpl = new ConversationImpl(speechConfig);\r\n const cb: Callback = arg2;\r\n const err: Callback = arg3;\r\n conversationImpl.createConversationAsync(\r\n (() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }),\r\n (error: any) => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n return conversationImpl;\r\n }\r\n\r\n }\r\n\r\n /** Start a conversation. */\r\n public abstract startConversationAsync(cb?: Callback, err?: Callback): void;\r\n\r\n /** Delete a conversation. After this no one will be able to join the conversation. */\r\n public abstract deleteConversationAsync(cb?: Callback, err?: Callback): void;\r\n\r\n /** End a conversation. */\r\n public abstract endConversationAsync(cb?: Callback, err?: Callback): void;\r\n\r\n /** Lock a conversation. This will prevent new participants from joining. */\r\n public abstract lockConversationAsync(cb?: Callback, err?: Callback): void;\r\n\r\n /** Add Participant to Conversation. */\r\n public abstract addParticipantAsync(participant: IParticipant, cb?: Callback, err?: Callback): void;\r\n\r\n /**\r\n * Mute all other participants in the conversation. After this no other participants will\r\n * have their speech recognitions broadcast, nor be able to send text messages.\r\n */\r\n public abstract muteAllParticipantsAsync(cb?: Callback, err?: Callback): void;\r\n\r\n /**\r\n * Mute a participant.\r\n * @param userId A user identifier\r\n */\r\n public abstract muteParticipantAsync(userId: string, cb?: Callback, err?: Callback): void;\r\n\r\n /**\r\n * Remove a participant from a conversation using the user id, Participant or User object\r\n * @param userId A user identifier\r\n */\r\n public abstract removeParticipantAsync(userId: string | IParticipant | IUser, cb?: Callback, err?: Callback): void;\r\n\r\n /** Unlocks a conversation. */\r\n public abstract unlockConversationAsync(cb?: Callback, err?: Callback): void;\r\n\r\n /** Unmute all other participants in the conversation. */\r\n public abstract unmuteAllParticipantsAsync(cb?: Callback, err?: Callback): void;\r\n\r\n /**\r\n * Unmute a participant.\r\n * @param userId A user identifier\r\n */\r\n public abstract unmuteParticipantAsync(userId: string, cb?: Callback, err?: Callback): void;\r\n}\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class ConversationImpl extends Conversation implements IDisposable {\r\n\r\n private privConfig: SpeechTranslationConfig;\r\n private privProperties: PropertyCollection;\r\n private privLanguage: string;\r\n private privToken: string;\r\n private privIsDisposed: boolean = false;\r\n private privRoom: IInternalConversation;\r\n private privManager: ConversationManager;\r\n private privConversationRecognizer: ConversationRecognizer;\r\n private privIsConnected: boolean = false;\r\n private privParticipants: InternalParticipants;\r\n private privIsReady: boolean;\r\n private privConversationTranslator: ConversationTranslator;\r\n private privTranscriberRecognizer: TranscriberRecognizer;\r\n private privErrors: IErrorMessages = ConversationConnectionConfig.restErrors;\r\n private privConversationId: string = \"\";\r\n private readonly privTextMessageMaxLength: number;\r\n\r\n public set conversationTranslator(value: ConversationTranslator) {\r\n this.privConversationTranslator = value;\r\n }\r\n\r\n // get the internal data about a conversation\r\n public get room(): IInternalConversation {\r\n return this.privRoom;\r\n }\r\n\r\n // get the wrapper for connecting to the websockets\r\n public get connection(): ConversationRecognizer {\r\n return this.privConversationRecognizer; // this.privConnection;\r\n }\r\n\r\n // get / set the speech auth token\r\n public get authorizationToken(): string {\r\n return this.privToken;\r\n }\r\n\r\n public set authorizationToken(value: string) {\r\n Contracts.throwIfNullOrWhitespace(value, \"authorizationToken\");\r\n this.privToken = value;\r\n }\r\n\r\n // get the config\r\n public get config(): SpeechTranslationConfig {\r\n return this.privConfig;\r\n }\r\n\r\n // get the conversation Id\r\n public get conversationId(): string {\r\n return this.privRoom ? this.privRoom.roomId : this.privConversationId;\r\n }\r\n\r\n // get the properties\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n // get the speech language\r\n public get speechRecognitionLanguage(): string {\r\n return this.privLanguage;\r\n }\r\n\r\n public get isMutedByHost(): boolean {\r\n return this.privParticipants.me?.isHost ? false : this.privParticipants.me?.isMuted;\r\n }\r\n\r\n public get isConnected(): boolean {\r\n return this.privIsConnected && this.privIsReady;\r\n }\r\n\r\n public get participants(): Participant[] {\r\n return this.toParticipants(true);\r\n }\r\n\r\n public get me(): Participant {\r\n return this.toParticipant(this.privParticipants.me);\r\n }\r\n\r\n public get host(): Participant {\r\n return this.toParticipant(this.privParticipants.host);\r\n }\r\n\r\n /**\r\n * Create a conversation impl\r\n * @param speechConfig\r\n * @param {string} id - optional conversationId\r\n */\r\n public constructor(speechConfig: SpeechTranslationConfig, id?: string) {\r\n super();\r\n this.privProperties = new PropertyCollection();\r\n this.privManager = new ConversationManager();\r\n\r\n // check the speech language\r\n const language: string = speechConfig.getProperty(PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);\r\n if (!language) {\r\n speechConfig.setProperty(PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage], ConversationConnectionConfig.defaultLanguageCode);\r\n }\r\n this.privLanguage = speechConfig.getProperty(PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);\r\n\r\n if (!id) {\r\n // check the target language(s)\r\n if (speechConfig.targetLanguages.length === 0) {\r\n speechConfig.addTargetLanguage(this.privLanguage);\r\n }\r\n\r\n // check the profanity setting: speech and conversationTranslator should be in sync\r\n const profanity: string = speechConfig.getProperty(PropertyId[PropertyId.SpeechServiceResponse_ProfanityOption]);\r\n if (!profanity) {\r\n speechConfig.setProfanity(ProfanityOption.Masked);\r\n }\r\n // check the nickname: it should pass this regex: ^\\w+([\\s-][\\w\\(\\)]+)*$\"\r\n // TODO: specify the regex required. Nicknames must be unique or get the duplicate nickname error\r\n // TODO: check what the max length is and if a truncation is required or if the service handles it without an error\r\n let hostNickname: string = speechConfig.getProperty(PropertyId[PropertyId.ConversationTranslator_Name]);\r\n if (hostNickname === undefined || hostNickname === null || hostNickname.length <= 1 || hostNickname.length > 50) {\r\n hostNickname = \"Host\";\r\n }\r\n speechConfig.setProperty(PropertyId[PropertyId.ConversationTranslator_Name], hostNickname);\r\n\r\n } else {\r\n this.privConversationId = id;\r\n }\r\n\r\n // save the speech config for future usage\r\n this.privConfig = speechConfig;\r\n\r\n // save the config properties\r\n const configImpl = speechConfig as SpeechTranslationConfigImpl;\r\n Contracts.throwIfNull(configImpl, \"speechConfig\");\r\n this.privProperties = configImpl.properties.clone();\r\n this.privIsConnected = false;\r\n this.privParticipants = new InternalParticipants();\r\n this.privIsReady = false;\r\n this.privTextMessageMaxLength = 1000;\r\n }\r\n\r\n /**\r\n * Create a new conversation as Host\r\n * @param cb\r\n * @param err\r\n */\r\n public createConversationAsync(cb?: Callback, err?: Callback): void {\r\n try {\r\n if (!!this.privConversationRecognizer) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedStart), err);\r\n }\r\n this.privManager.createOrJoin(this.privProperties, undefined,\r\n ((room: IInternalConversation) => {\r\n if (!room) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedConnect), err);\r\n }\r\n this.privRoom = room;\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Starts a new conversation as host.\r\n * @param cb\r\n * @param err\r\n */\r\n public startConversationAsync(cb?: Callback, err?: Callback): void {\r\n try {\r\n // check if there is already a recognizer\r\n if (!!this.privConversationRecognizer) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedStart), err);\r\n }\r\n // check if there is conversation data available\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedConnect);\r\n // connect to the conversation websocket\r\n this.privParticipants.meId = this.privRoom.participantId;\r\n this.privConversationRecognizer = ConversationRecognizerFactory.fromConfig(this.privConfig);\r\n\r\n // Because ConversationTranslator manually sets up and manages the connection, Conversation\r\n // has to forward serviceRecognizer connection events that usually get passed automatically\r\n this.privConversationRecognizer.connected = this.onConnected;\r\n this.privConversationRecognizer.disconnected = this.onDisconnected;\r\n this.privConversationRecognizer.canceled = this.onCanceled;\r\n\r\n this.privConversationRecognizer.participantUpdateCommandReceived = this.onParticipantUpdateCommandReceived;\r\n this.privConversationRecognizer.lockRoomCommandReceived = this.onLockRoomCommandReceived;\r\n this.privConversationRecognizer.muteAllCommandReceived = this.onMuteAllCommandReceived;\r\n this.privConversationRecognizer.participantJoinCommandReceived = this.onParticipantJoinCommandReceived;\r\n this.privConversationRecognizer.participantLeaveCommandReceived = this.onParticipantLeaveCommandReceived;\r\n this.privConversationRecognizer.translationReceived = this.onTranslationReceived;\r\n this.privConversationRecognizer.participantsListReceived = this.onParticipantsListReceived;\r\n this.privConversationRecognizer.conversationExpiration = this.onConversationExpiration;\r\n this.privConversationRecognizer.connect(this.privRoom.token,\r\n (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Join a conversation as a participant.\r\n * @param { IParticipant } participant - participant to add\r\n * @param cb\r\n * @param err\r\n */\r\n public addParticipantAsync(participant: IParticipant, cb?: Callback, err?: Callback): void {\r\n Contracts.throwIfNullOrUndefined(participant, \"Participant\");\r\n marshalPromiseToCallbacks(this.addParticipantImplAsync(participant), cb, err);\r\n }\r\n\r\n /**\r\n * Join a conversation as a participant.\r\n * @param conversation\r\n * @param nickname\r\n * @param lang\r\n * @param cb\r\n * @param err\r\n */\r\n public joinConversationAsync(conversationId: string, nickname: string, lang: string, cb?: Callback, err?: Callback): void {\r\n try {\r\n // TODO\r\n // if (!!this.privConversationRecognizer) {\r\n // throw new Error(this.privErrors.permissionDeniedStart);\r\n // }\r\n Contracts.throwIfNullOrWhitespace(conversationId, this.privErrors.invalidArgs.replace(\"{arg}\", \"conversationId\"));\r\n Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace(\"{arg}\", \"nickname\"));\r\n Contracts.throwIfNullOrWhitespace(lang, this.privErrors.invalidArgs.replace(\"{arg}\", \"language\"));\r\n // join the conversation\r\n this.privManager.createOrJoin(this.privProperties, conversationId,\r\n ((room: IInternalConversation) => {\r\n Contracts.throwIfNullOrUndefined(room, this.privErrors.permissionDeniedConnect);\r\n this.privRoom = room;\r\n this.privConfig.authorizationToken = room.cognitiveSpeechAuthToken;\r\n // join callback\r\n if (!!cb) {\r\n cb(room.cognitiveSpeechAuthToken);\r\n }\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Deletes a conversation\r\n * @param cb\r\n * @param err\r\n */\r\n public deleteConversationAsync(cb?: Callback, err?: Callback): void {\r\n marshalPromiseToCallbacks(this.deleteConversationImplAsync(), cb, err);\r\n }\r\n\r\n public async deleteConversationImplAsync(): Promise {\r\n Contracts.throwIfNullOrUndefined(this.privProperties, this.privErrors.permissionDeniedConnect);\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.token, this.privErrors.permissionDeniedConnect);\r\n await this.privManager.leave(this.privProperties, this.privRoom.token);\r\n\r\n this.dispose();\r\n }\r\n\r\n /**\r\n * Issues a request to close the client websockets\r\n * @param cb\r\n * @param err\r\n */\r\n public endConversationAsync(cb?: Callback, err?: Callback): void {\r\n marshalPromiseToCallbacks(this.endConversationImplAsync(), cb, err);\r\n }\r\n\r\n public endConversationImplAsync(): Promise {\r\n return this.close(true);\r\n }\r\n\r\n /**\r\n * Issues a request to lock the conversation\r\n * @param cb\r\n * @param err\r\n */\r\n public lockConversationAsync(cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n if (!this.canSendAsHost) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace(\"{command}\", \"lock\")), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getLockCommand(true),\r\n (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Issues a request to mute the conversation\r\n * @param cb\r\n * @param err\r\n */\r\n public muteAllParticipantsAsync(cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrUndefined(this.privConversationRecognizer, this.privErrors.permissionDeniedSend);\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n // check the user's permissions\r\n if (!this.canSendAsHost) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace(\"{command}\", \"mute\")), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getMuteAllCommand(true),\r\n (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Issues a request to mute a participant in the conversation\r\n * @param userId\r\n * @param cb\r\n * @param err\r\n */\r\n public muteParticipantAsync(userId: string, cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace(\"{arg}\", \"userId\"));\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n // check the connection is open (host + participant can perform the mute command)\r\n if (!this.canSend) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedSend), err);\r\n }\r\n // if not host, check the participant is not muting another participant\r\n if (!this.me.isHost && this.me.id !== userId) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace(\"{command}\", \"mute\")), err);\r\n }\r\n // check the user exists\r\n const exists: number = this.privParticipants.getParticipantIndex(userId);\r\n if (exists === -1) {\r\n this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getMuteCommand(userId, true), (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Issues a request to remove a participant from the conversation\r\n * @param userId\r\n * @param cb\r\n * @param err\r\n */\r\n public removeParticipantAsync(userId: string | IParticipant | IUser, cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n if (!!this.privTranscriberRecognizer && userId.hasOwnProperty(\"id\")) {\r\n // Assume this is a transcription participant\r\n marshalPromiseToCallbacks(this.removeParticipantImplAsync(userId as IParticipant), cb, err);\r\n } else {\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n if (!this.canSendAsHost) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace(\"{command}\", \"remove\")), err);\r\n }\r\n let participantId: string = \"\";\r\n if (typeof userId === \"string\") {\r\n participantId = userId as string;\r\n } else if (userId.hasOwnProperty(\"id\")) {\r\n const participant: IParticipant = userId as IParticipant;\r\n participantId = participant.id;\r\n } else if (userId.hasOwnProperty(\"userId\")) {\r\n const user: IUser = userId as IUser;\r\n participantId = user.userId;\r\n }\r\n Contracts.throwIfNullOrWhitespace(participantId, this.privErrors.invalidArgs.replace(\"{arg}\", \"userId\"));\r\n // check the participant exists\r\n const index: number = this.participants.findIndex((p: Participant) => p.id === participantId);\r\n if (index === -1) {\r\n this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getEjectCommand(participantId), (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n }\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Issues a request to unlock the conversation\r\n * @param cb\r\n * @param err\r\n */\r\n public unlockConversationAsync(cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n if (!this.canSendAsHost) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace(\"{command}\", \"unlock\")), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getLockCommand(false), (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Issues a request to unmute all participants in the conversation\r\n * @param cb\r\n * @param err\r\n */\r\n public unmuteAllParticipantsAsync(cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n if (!this.canSendAsHost) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace(\"{command}\", \"unmute all\")), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getMuteAllCommand(false), (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Issues a request to unmute a participant in the conversation\r\n * @param userId\r\n * @param cb\r\n * @param err\r\n */\r\n public unmuteParticipantAsync(userId: string, cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace(\"{arg}\", \"userId\"));\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n // check the connection is open (host + participant can perform the mute command)\r\n if (!this.canSend) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedSend), err);\r\n }\r\n // if not host, check the participant is not muting another participant\r\n if (!this.me.isHost && this.me.id !== userId) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace(\"{command}\", \"mute\")), err);\r\n }\r\n // check the user exists\r\n const exists: number = this.privParticipants.getParticipantIndex(userId);\r\n if (exists === -1) {\r\n this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getMuteCommand(userId, false), (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Send a text message\r\n * @param message\r\n * @param cb\r\n * @param err\r\n */\r\n public sendTextMessageAsync(message: string, cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace(\"{arg}\", \"message\"));\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n if (!this.canSend) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedSend), err);\r\n }\r\n // TODO: is a max length check required?\r\n if (message.length > this.privTextMessageMaxLength) {\r\n this.handleError(new Error(this.privErrors.invalidArgs.replace(\"{arg}\", \"message length\")), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getMessageCommand(message), (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Change nickname\r\n * @param message\r\n * @param cb\r\n * @param err\r\n */\r\n public changeNicknameAsync(nickname: string, cb?: Callback, err?: Callback): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());\r\n Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace(\"{arg}\", \"nickname\"));\r\n Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);\r\n if (!this.canSend) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedSend), err);\r\n }\r\n this.privConversationRecognizer?.sendRequest(this.getChangeNicknameCommand(nickname), (() => {\r\n this.handleCallback(cb, err);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, err);\r\n }));\r\n } catch (error) {\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public dispose(reason?: string): void {\r\n if (this.isDisposed) {\r\n return;\r\n }\r\n this.privIsDisposed = true;\r\n this.config?.close();\r\n this.privConfig = undefined;\r\n this.privLanguage = undefined;\r\n this.privProperties = undefined;\r\n this.privRoom = undefined;\r\n this.privToken = undefined;\r\n this.privManager = undefined;\r\n this.privConversationRecognizer = undefined;\r\n this.privIsConnected = false;\r\n this.privIsReady = false;\r\n this.privParticipants = undefined;\r\n }\r\n\r\n public get transcriberRecognizer(): TranscriberRecognizer {\r\n return this.privTranscriberRecognizer;\r\n }\r\n\r\n public async connectTranscriberRecognizer(recognizer: TranscriberRecognizer): Promise {\r\n if (!!this.privTranscriberRecognizer) {\r\n await this.privTranscriberRecognizer.close();\r\n }\r\n this.privTranscriberRecognizer = recognizer;\r\n this.privTranscriberRecognizer.conversation = this;\r\n }\r\n\r\n public get conversationInfo(): ConversationInfo {\r\n const convId: string = this.conversationId;\r\n const p: TranscriptionParticipant[] = this.participants.map((part: Participant) => {\r\n return {\r\n id: part.id,\r\n preferredLanguage: part.preferredLanguage,\r\n voice: part.voice\r\n };\r\n });\r\n const props: { [id: string]: string } = {};\r\n for (const key of ConversationConnectionConfig.transcriptionEventKeys) {\r\n const val: string = this.properties.getProperty(key, \"\");\r\n if (val !== \"\") {\r\n props[key] = val;\r\n }\r\n }\r\n const info: ConversationInfo = { id: convId, participants: p, conversationProperties: props };\r\n return info;\r\n }\r\n\r\n private addParticipantImplAsync(participant: IParticipant): Promise {\r\n const newParticipant: IInternalParticipant = this.privParticipants.addOrUpdateParticipant(participant);\r\n if (newParticipant !== undefined) {\r\n if (!!this.privTranscriberRecognizer) {\r\n const conversationInfo = this.conversationInfo;\r\n conversationInfo.participants = [participant];\r\n return this.privTranscriberRecognizer.pushConversationEvent(conversationInfo, \"join\");\r\n }\r\n }\r\n }\r\n\r\n private removeParticipantImplAsync(participant: IParticipant): Promise {\r\n this.privParticipants.deleteParticipant(participant.id);\r\n const conversationInfo = this.conversationInfo;\r\n conversationInfo.participants = [participant];\r\n return this.privTranscriberRecognizer.pushConversationEvent(conversationInfo, \"leave\");\r\n }\r\n\r\n /** websocket callbacks */\r\n private onConnected = (e: ConnectionEventArgs): void => {\r\n this.privIsConnected = true;\r\n try {\r\n if (!!this.privConversationTranslator.sessionStarted) {\r\n this.privConversationTranslator.sessionStarted(this.privConversationTranslator, e);\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onDisconnected = async (e: ConnectionEventArgs): Promise => {\r\n await this.close(false);\r\n try {\r\n if (!!this.privConversationTranslator.sessionStopped) {\r\n this.privConversationTranslator.sessionStopped(this.privConversationTranslator, e);\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onCanceled = async (r: ConversationRecognizer, e: ConversationTranslationCanceledEventArgs): Promise => {\r\n await this.close(false); // ?\r\n try {\r\n if (!!this.privConversationTranslator.canceled) {\r\n this.privConversationTranslator.canceled(this.privConversationTranslator, e);\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onParticipantUpdateCommandReceived = (r: ConversationRecognizer, e: ParticipantAttributeEventArgs): void => {\r\n try {\r\n const updatedParticipant: any = this.privParticipants.getParticipant(e.id);\r\n if (updatedParticipant !== undefined) {\r\n\r\n switch (e.key) {\r\n case ConversationTranslatorCommandTypes.changeNickname:\r\n updatedParticipant.displayName = e.value;\r\n break;\r\n case ConversationTranslatorCommandTypes.setUseTTS:\r\n updatedParticipant.useTts = e.value;\r\n break;\r\n case ConversationTranslatorCommandTypes.setProfanityFiltering:\r\n updatedParticipant.profanity = e.value;\r\n break;\r\n case ConversationTranslatorCommandTypes.setMute:\r\n updatedParticipant.isMuted = e.value;\r\n break;\r\n case ConversationTranslatorCommandTypes.setTranslateToLanguages:\r\n updatedParticipant.translateToLanguages = e.value;\r\n break;\r\n }\r\n this.privParticipants.addOrUpdateParticipant(updatedParticipant);\r\n\r\n if (!!this.privConversationTranslator?.participantsChanged) {\r\n this.privConversationTranslator?.participantsChanged(\r\n this.privConversationTranslator,\r\n new ConversationParticipantsChangedEventArgs(ParticipantChangedReason.Updated,\r\n [this.toParticipant(updatedParticipant)], e.sessionId));\r\n }\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onLockRoomCommandReceived = (r: ConversationRecognizer, e: LockRoomEventArgs): void => {\r\n // TODO\r\n }\r\n\r\n private onMuteAllCommandReceived = (r: ConversationRecognizer, e: MuteAllEventArgs): void => {\r\n try {\r\n this.privParticipants.participants.forEach((p: IInternalParticipant) => p.isMuted = (p.isHost ? false : e.isMuted));\r\n if (!!this.privConversationTranslator?.participantsChanged) {\r\n this.privConversationTranslator?.participantsChanged(\r\n this.privConversationTranslator,\r\n new ConversationParticipantsChangedEventArgs(ParticipantChangedReason.Updated,\r\n this.toParticipants(false), e.sessionId));\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onParticipantJoinCommandReceived = (r: ConversationRecognizer, e: ParticipantEventArgs): void => {\r\n try {\r\n const newParticipant: IInternalParticipant = this.privParticipants.addOrUpdateParticipant(e.participant);\r\n if (newParticipant !== undefined) {\r\n if (!!this.privConversationTranslator?.participantsChanged) {\r\n this.privConversationTranslator?.participantsChanged(\r\n this.privConversationTranslator,\r\n new ConversationParticipantsChangedEventArgs(ParticipantChangedReason.JoinedConversation,\r\n [this.toParticipant(newParticipant)], e.sessionId));\r\n }\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onParticipantLeaveCommandReceived = (r: ConversationRecognizer, e: ParticipantEventArgs): void => {\r\n try {\r\n const ejectedParticipant: IInternalParticipant = this.privParticipants.getParticipant(e.participant.id);\r\n if (ejectedParticipant !== undefined) {\r\n // remove the participant from the internal participants list\r\n this.privParticipants.deleteParticipant(e.participant.id);\r\n if (!!this.privConversationTranslator?.participantsChanged) {\r\n // notify subscribers that the participant has left the conversation\r\n this.privConversationTranslator?.participantsChanged(\r\n this.privConversationTranslator,\r\n new ConversationParticipantsChangedEventArgs(ParticipantChangedReason.LeftConversation,\r\n [this.toParticipant(ejectedParticipant)], e.sessionId));\r\n }\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onTranslationReceived = (r: ConversationRecognizer, e: ConversationReceivedTranslationEventArgs): void => {\r\n try {\r\n switch (e.command) {\r\n case ConversationTranslatorMessageTypes.final:\r\n if (!!this.privConversationTranslator?.transcribed) {\r\n this.privConversationTranslator?.transcribed(\r\n this.privConversationTranslator,\r\n new ConversationTranslationEventArgs(e.payload, undefined, e.sessionId));\r\n }\r\n break;\r\n case ConversationTranslatorMessageTypes.partial:\r\n if (!!this.privConversationTranslator?.transcribing) {\r\n this.privConversationTranslator?.transcribing(\r\n this.privConversationTranslator,\r\n new ConversationTranslationEventArgs(e.payload, undefined, e.sessionId));\r\n }\r\n break;\r\n case ConversationTranslatorMessageTypes.instantMessage:\r\n if (!!this.privConversationTranslator?.textMessageReceived) {\r\n this.privConversationTranslator?.textMessageReceived(\r\n this.privConversationTranslator,\r\n new ConversationTranslationEventArgs(e.payload, undefined, e.sessionId));\r\n }\r\n break;\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onParticipantsListReceived = (r: ConversationRecognizer, e: ParticipantsListEventArgs): void => {\r\n try {\r\n // check if the session token needs to be updated\r\n if (e.sessionToken !== undefined && e.sessionToken !== null) {\r\n this.privRoom.token = e.sessionToken;\r\n }\r\n // save the participants\r\n this.privParticipants.participants = [...e.participants];\r\n // enable the conversation\r\n if (this.privParticipants.me !== undefined) {\r\n this.privIsReady = true;\r\n }\r\n if (!!this.privConversationTranslator?.participantsChanged) {\r\n this.privConversationTranslator?.participantsChanged(\r\n this.privConversationTranslator,\r\n new ConversationParticipantsChangedEventArgs(ParticipantChangedReason.JoinedConversation, this.toParticipants(true), e.sessionId));\r\n }\r\n // if this is the host, update the nickname if needed\r\n if (this.me.isHost) {\r\n const nickname: string = this.privConversationTranslator?.properties.getProperty(PropertyId.ConversationTranslator_Name);\r\n if (nickname !== undefined && nickname.length > 0 && nickname !== this.me.displayName) {\r\n // issue a change nickname request\r\n this.changeNicknameAsync(nickname);\r\n }\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private onConversationExpiration = (r: ConversationRecognizer, e: ConversationExpirationEventArgs): void => {\r\n try {\r\n if (!!this.privConversationTranslator?.conversationExpiration) {\r\n this.privConversationTranslator?.conversationExpiration(\r\n this.privConversationTranslator,\r\n e);\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private async close(dispose: boolean): Promise {\r\n try {\r\n this.privIsConnected = false;\r\n await this.privConversationRecognizer.close();\r\n await this.privTranscriberRecognizer?.close();\r\n this.privConversationRecognizer = undefined;\r\n this.privConversationTranslator?.dispose();\r\n } catch (e) {\r\n // ignore error\r\n }\r\n if (dispose) {\r\n this.dispose();\r\n }\r\n }\r\n\r\n /** Helpers */\r\n private get canSend(): boolean {\r\n return this.privIsConnected && !this.privParticipants.me?.isMuted;\r\n }\r\n\r\n private get canSendAsHost(): boolean {\r\n return this.privIsConnected && this.privParticipants.me?.isHost;\r\n }\r\n\r\n private handleCallback(cb: any, err: any): void {\r\n if (!!cb) {\r\n try {\r\n cb();\r\n } catch (e) {\r\n if (!!err) {\r\n err(e);\r\n }\r\n }\r\n cb = undefined;\r\n }\r\n }\r\n\r\n private handleError(error: any, err: any): void {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n\r\n } else {\r\n err(error);\r\n }\r\n }\r\n }\r\n\r\n /** Participant Helpers */\r\n private toParticipants(includeHost: boolean): Participant[] {\r\n\r\n const participants: Participant[] = this.privParticipants.participants.map((p: IInternalParticipant) => {\r\n return this.toParticipant(p);\r\n });\r\n if (!includeHost) {\r\n return participants.filter((p: Participant) => p.isHost === false);\r\n } else {\r\n return participants;\r\n }\r\n }\r\n\r\n private toParticipant(p: IInternalParticipant): Participant {\r\n return new Participant(p.id, p.avatar, p.displayName, p.isHost, p.isMuted, p.isUsingTts, p.preferredLanguage, p.voice);\r\n }\r\n\r\n private getMuteAllCommand(isMuted: boolean): string {\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, \"conversationId\");\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, \"participantId\");\r\n\r\n return JSON.stringify({\r\n command: ConversationTranslatorCommandTypes.setMuteAll,\r\n // tslint:disable-next-line: object-literal-shorthand\r\n participantId: this.privRoom.participantId, // the id of the host\r\n roomid: this.privRoom.roomId,\r\n type: ConversationTranslatorMessageTypes.participantCommand,\r\n value: isMuted\r\n });\r\n }\r\n\r\n private getMuteCommand(participantId: string, isMuted: boolean): string {\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, \"conversationId\");\r\n Contracts.throwIfNullOrWhitespace(participantId, \"participantId\");\r\n\r\n return JSON.stringify({\r\n command: ConversationTranslatorCommandTypes.setMute,\r\n // tslint:disable-next-line: object-literal-shorthand\r\n participantId: participantId, // the id of the host\r\n roomid: this.privRoom.roomId,\r\n type: ConversationTranslatorMessageTypes.participantCommand,\r\n value: isMuted\r\n });\r\n }\r\n\r\n private getLockCommand(isLocked: boolean): string {\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, \"conversationId\");\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, \"participantId\");\r\n\r\n return JSON.stringify({\r\n command: ConversationTranslatorCommandTypes.setLockState,\r\n // tslint:disable-next-line: object-literal-shorthand\r\n participantId: this.privRoom.participantId,\r\n roomid: this.privRoom.roomId,\r\n type: ConversationTranslatorMessageTypes.participantCommand,\r\n value: isLocked\r\n });\r\n }\r\n\r\n private getEjectCommand(participantId: string): string {\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, \"conversationId\");\r\n Contracts.throwIfNullOrWhitespace(participantId, \"participantId\");\r\n\r\n return JSON.stringify({\r\n command: ConversationTranslatorCommandTypes.ejectParticipant,\r\n // tslint:disable-next-line: object-literal-shorthand\r\n participantId: participantId,\r\n roomid: this.privRoom.roomId,\r\n type: ConversationTranslatorMessageTypes.participantCommand,\r\n });\r\n }\r\n\r\n private getChangeNicknameCommand(nickname: string): string {\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, \"conversationId\");\r\n Contracts.throwIfNullOrWhitespace(nickname, \"nickname\");\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, \"participantId\");\r\n\r\n return JSON.stringify({\r\n command: ConversationTranslatorCommandTypes.changeNickname,\r\n nickname,\r\n // tslint:disable-next-line: object-literal-shorthand\r\n participantId: this.privRoom.participantId, // the id of the host\r\n roomid: this.privRoom.roomId,\r\n type: ConversationTranslatorMessageTypes.participantCommand,\r\n value: nickname\r\n });\r\n }\r\n\r\n private getMessageCommand(message: string): string {\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, \"conversationId\");\r\n Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, \"participantId\");\r\n Contracts.throwIfNullOrWhitespace(message, \"message\");\r\n\r\n return JSON.stringify({\r\n // tslint:disable-next-line: object-literal-shorthand\r\n participantId: this.privRoom.participantId,\r\n roomId: this.privRoom.roomId,\r\n text: message,\r\n type: ConversationTranslatorMessageTypes.instantMessage\r\n });\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n AudioConfig,\r\n SpeechTranslationConfig,\r\n} from \"../Exports\";\r\nimport { Callback, IConversation } from \"./IConversation\";\r\n\r\nexport class ConversationCommon {\r\n\r\n protected privAudioConfig: AudioConfig;\r\n protected privSpeechTranslationConfig: SpeechTranslationConfig;\r\n\r\n public constructor(audioConfig?: AudioConfig) {\r\n this.privAudioConfig = audioConfig;\r\n }\r\n\r\n protected handleCallback(cb: Callback, err: Callback): void {\r\n if (!!cb) {\r\n try {\r\n cb();\r\n } catch (e) {\r\n if (!!err) {\r\n err(e);\r\n }\r\n }\r\n cb = undefined;\r\n }\r\n }\r\n\r\n protected handleError(error: any, err: Callback): void {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n\r\n } else {\r\n err(error);\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// Multi-device Conversation is a Preview feature.\r\n\r\nimport { ConversationConnectionConfig } from \"../../common.speech/Exports\";\r\nimport {\r\n IDisposable,\r\n IErrorMessages,\r\n marshalPromiseToCallbacks\r\n} from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n AudioConfig,\r\n CancellationErrorCode,\r\n CancellationReason,\r\n ProfanityOption,\r\n PropertyCollection,\r\n PropertyId,\r\n SessionEventArgs,\r\n SpeechTranslationConfig,\r\n TranslationRecognitionCanceledEventArgs,\r\n TranslationRecognitionEventArgs,\r\n TranslationRecognizer\r\n} from \"../Exports\";\r\nimport { ConversationImpl } from \"./Conversation\";\r\nimport {\r\n ConversationCommon,\r\n ConversationExpirationEventArgs,\r\n ConversationHandler,\r\n ConversationParticipantsChangedEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n ConversationTranslationEventArgs,\r\n IConversationTranslator,\r\n Participant,\r\n} from \"./Exports\";\r\nimport { Callback, IConversation } from \"./IConversation\";\r\n\r\nexport enum SpeechState {\r\n Inactive, Connecting, Connected\r\n}\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\n// child class of TranslationRecognizer meant only for use with ConversationTranslator\r\nclass ConversationTranslationRecognizer extends TranslationRecognizer {\r\n private privTranslator: ConversationTranslator;\r\n private privSpeechState: SpeechState;\r\n public constructor(speechConfig: SpeechTranslationConfig, audioConfig?: AudioConfig, translator?: ConversationTranslator) {\r\n super(speechConfig, audioConfig);\r\n this.privSpeechState = SpeechState.Inactive;\r\n if (!!translator) {\r\n this.privTranslator = translator;\r\n this.sessionStarted = () => {\r\n this.privSpeechState = SpeechState.Connected;\r\n };\r\n\r\n this.sessionStopped = () => {\r\n this.privSpeechState = SpeechState.Inactive;\r\n };\r\n\r\n this.recognized = async (tr: TranslationRecognizer, e: TranslationRecognitionEventArgs) => {\r\n // TODO: add support for getting recognitions from here if own speech\r\n\r\n // if there is an error connecting to the conversation service from the speech service the error will be returned in the ErrorDetails field.\r\n if (e.result?.errorDetails) {\r\n await this.cancelSpeech();\r\n // TODO: format the error message contained in 'errorDetails'\r\n this.fireCancelEvent(e.result.errorDetails);\r\n }\r\n };\r\n\r\n this.canceled = async (r: TranslationRecognizer, e: TranslationRecognitionCanceledEventArgs) => {\r\n if (this.privSpeechState !== SpeechState.Inactive) {\r\n try {\r\n await this.cancelSpeech();\r\n } catch (error) {\r\n this.privSpeechState = SpeechState.Inactive;\r\n }\r\n }\r\n };\r\n }\r\n }\r\n public get state(): SpeechState {\r\n return this.privSpeechState;\r\n }\r\n\r\n public set state(newState: SpeechState) {\r\n this.privSpeechState = newState;\r\n }\r\n\r\n public onConnection(): void {\r\n this.privSpeechState = SpeechState.Connected;\r\n }\r\n\r\n public async onDisconnection(): Promise {\r\n this.privSpeechState = SpeechState.Inactive;\r\n await this.cancelSpeech();\r\n }\r\n\r\n /**\r\n * Fire a cancel event\r\n * @param error\r\n */\r\n private fireCancelEvent(error: any): void {\r\n try {\r\n if (!!this.privTranslator.canceled) {\r\n const cancelEvent: ConversationTranslationCanceledEventArgs = new ConversationTranslationCanceledEventArgs(\r\n error?.reason ?? CancellationReason.Error,\r\n error?.errorDetails ?? error,\r\n error?.errorCode ?? CancellationErrorCode.RuntimeError,\r\n undefined,\r\n error?.sessionId);\r\n\r\n this.privTranslator.canceled(this.privTranslator, cancelEvent);\r\n }\r\n } catch (e) {\r\n //\r\n }\r\n }\r\n\r\n private async cancelSpeech(): Promise {\r\n try {\r\n this.stopContinuousRecognitionAsync();\r\n await this.privReco?.disconnect();\r\n this.privSpeechState = SpeechState.Inactive;\r\n } catch (e) {\r\n // ignore the error\r\n }\r\n }\r\n\r\n}\r\n\r\n/***\r\n * Join, leave or connect to a conversation.\r\n */\r\nexport class ConversationTranslator extends ConversationCommon implements IConversationTranslator, IDisposable {\r\n\r\n private privSpeechRecognitionLanguage: string;\r\n private privProperties: PropertyCollection;\r\n private privIsDisposed: boolean = false;\r\n private privCTRecognizer: ConversationTranslationRecognizer;\r\n private privIsSpeaking: boolean = false;\r\n private privConversation: ConversationImpl;\r\n private privErrors: IErrorMessages = ConversationConnectionConfig.restErrors;\r\n private privPlaceholderKey: string = \"abcdefghijklmnopqrstuvwxyz012345\";\r\n private privPlaceholderRegion: string = \"westus\";\r\n\r\n public constructor(audioConfig?: AudioConfig) {\r\n super(audioConfig);\r\n this.privProperties = new PropertyCollection();\r\n }\r\n\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public get speechRecognitionLanguage(): string {\r\n return this.privSpeechRecognitionLanguage;\r\n }\r\n\r\n public get participants(): Participant[] {\r\n return this.privConversation?.participants;\r\n }\r\n\r\n public canceled: (sender: ConversationHandler, event: ConversationTranslationCanceledEventArgs) => void;\r\n public conversationExpiration: (sender: IConversationTranslator, event: ConversationExpirationEventArgs) => void;\r\n public participantsChanged: (sender: IConversationTranslator, event: ConversationParticipantsChangedEventArgs) => void;\r\n public sessionStarted: (sender: ConversationHandler, event: SessionEventArgs) => void;\r\n public sessionStopped: (sender: ConversationHandler, event: SessionEventArgs) => void;\r\n public textMessageReceived: (sender: IConversationTranslator, event: ConversationTranslationEventArgs) => void;\r\n public transcribed: (sender: IConversationTranslator, event: ConversationTranslationEventArgs) => void;\r\n public transcribing: (sender: IConversationTranslator, event: ConversationTranslationEventArgs) => void;\r\n\r\n /**\r\n * Join a conversation. If this is the host, pass in the previously created Conversation object.\r\n * @param conversation\r\n * @param nickname\r\n * @param lang\r\n * @param cb\r\n * @param err\r\n */\r\n public joinConversationAsync(conversation: IConversation, nickname: string, cb?: Callback, err?: Callback): void;\r\n public joinConversationAsync(conversationId: string, nickname: string, lang: string, cb?: Callback, err?: Callback): void;\r\n public joinConversationAsync(conversation: any, nickname: string, param1?: string | Callback, param2?: Callback, param3?: Callback): void {\r\n\r\n try {\r\n\r\n if (typeof conversation === \"string\") {\r\n\r\n Contracts.throwIfNullOrUndefined(conversation, this.privErrors.invalidArgs.replace(\"{arg}\", \"conversation id\"));\r\n Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace(\"{arg}\", \"nickname\"));\r\n\r\n if (!!this.privConversation) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedStart), param3);\r\n }\r\n\r\n let lang: string = param1 as string;\r\n if (lang === undefined || lang === null || lang === \"\") { lang = ConversationConnectionConfig.defaultLanguageCode; }\r\n\r\n // create a placeholder config\r\n this.privSpeechTranslationConfig = SpeechTranslationConfig.fromSubscription(\r\n this.privPlaceholderKey,\r\n this.privPlaceholderRegion);\r\n this.privSpeechTranslationConfig.setProfanity(ProfanityOption.Masked);\r\n this.privSpeechTranslationConfig.addTargetLanguage(lang);\r\n this.privSpeechTranslationConfig.setProperty(PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage], lang);\r\n this.privSpeechTranslationConfig.setProperty(PropertyId[PropertyId.ConversationTranslator_Name], nickname);\r\n\r\n const endpoint: string = this.privProperties.getProperty(PropertyId.ConversationTranslator_Host);\r\n if (endpoint) {\r\n this.privSpeechTranslationConfig.setProperty(PropertyId[PropertyId.ConversationTranslator_Host], endpoint);\r\n }\r\n const speechEndpointHost: string = this.privProperties.getProperty(PropertyId.SpeechServiceConnection_Host);\r\n if (speechEndpointHost) {\r\n this.privSpeechTranslationConfig.setProperty(PropertyId[PropertyId.SpeechServiceConnection_Host], speechEndpointHost);\r\n }\r\n\r\n // join the conversation\r\n this.privConversation = new ConversationImpl(this.privSpeechTranslationConfig);\r\n this.privConversation.conversationTranslator = this;\r\n\r\n this.privConversation.joinConversationAsync(\r\n conversation,\r\n nickname,\r\n lang,\r\n ((result: string) => {\r\n\r\n if (!result) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedConnect), param3);\r\n }\r\n\r\n this.privSpeechTranslationConfig.authorizationToken = result;\r\n\r\n // connect to the ws\r\n this.privConversation.startConversationAsync(\r\n (() => {\r\n this.handleCallback(param2, param3);\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, param3);\r\n }));\r\n\r\n }),\r\n ((error: any) => {\r\n this.handleError(error, param3);\r\n }));\r\n\r\n } else if (typeof conversation === \"object\") {\r\n\r\n Contracts.throwIfNullOrUndefined(conversation, this.privErrors.invalidArgs.replace(\"{arg}\", \"conversation id\"));\r\n Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace(\"{arg}\", \"nickname\"));\r\n\r\n // save the nickname\r\n this.privProperties.setProperty(PropertyId.ConversationTranslator_Name, nickname);\r\n // ref the conversation object\r\n this.privConversation = conversation as ConversationImpl;\r\n // ref the conversation translator object\r\n this.privConversation.conversationTranslator = this;\r\n\r\n Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedConnect);\r\n Contracts.throwIfNullOrUndefined(this.privConversation.room.token, this.privErrors.permissionDeniedConnect);\r\n\r\n this.privSpeechTranslationConfig = conversation.config;\r\n\r\n this.handleCallback(param1 as Callback, param2);\r\n } else {\r\n this.handleError(\r\n new Error(this.privErrors.invalidArgs.replace(\"{arg}\", \"invalid conversation type\")),\r\n param2);\r\n }\r\n\r\n } catch (error) {\r\n this.handleError(error, typeof param1 === \"string\" ? param3 : param2);\r\n }\r\n }\r\n\r\n /**\r\n * Leave the conversation\r\n * @param cb\r\n * @param err\r\n */\r\n public leaveConversationAsync(cb?: Callback, err?: Callback): void {\r\n\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n\r\n // stop the speech websocket\r\n await this.cancelSpeech();\r\n // stop the websocket\r\n await this.privConversation.endConversationImplAsync();\r\n // https delete request\r\n await this.privConversation.deleteConversationImplAsync();\r\n this.dispose();\r\n\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * Send a text message\r\n * @param message\r\n * @param cb\r\n * @param err\r\n */\r\n public sendTextMessageAsync(message: string, cb?: Callback, err?: Callback): void {\r\n\r\n try {\r\n Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedSend);\r\n Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace(\"{arg}\", message));\r\n\r\n this.privConversation?.sendTextMessageAsync(message, cb, err);\r\n } catch (error) {\r\n\r\n this.handleError(error, err);\r\n }\r\n }\r\n\r\n /**\r\n * Start speaking\r\n * @param cb\r\n * @param err\r\n */\r\n public startTranscribingAsync(cb?: Callback, err?: Callback): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n try {\r\n Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedSend);\r\n Contracts.throwIfNullOrUndefined(this.privConversation.room.token, this.privErrors.permissionDeniedConnect);\r\n\r\n if (this.privCTRecognizer === undefined) {\r\n await this.connectTranslatorRecognizer();\r\n }\r\n Contracts.throwIfNullOrUndefined(this.privCTRecognizer, this.privErrors.permissionDeniedSend);\r\n\r\n if (!this.canSpeak) {\r\n this.handleError(new Error(this.privErrors.permissionDeniedSend), err);\r\n }\r\n\r\n await this.startContinuousRecognition();\r\n\r\n this.privIsSpeaking = true;\r\n } catch (error) {\r\n this.privIsSpeaking = false;\r\n await this.cancelSpeech();\r\n throw error;\r\n }\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * Stop speaking\r\n * @param cb\r\n * @param err\r\n */\r\n public stopTranscribingAsync(cb?: Callback, err?: Callback): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n try {\r\n if (!this.privIsSpeaking) {\r\n // stop speech\r\n await this.cancelSpeech();\r\n return;\r\n }\r\n\r\n // stop the recognition but leave the websocket open\r\n this.privIsSpeaking = false;\r\n await new Promise((resolve: () => void, reject: (error: string) => void): void => {\r\n this.privCTRecognizer?.stopContinuousRecognitionAsync(resolve, reject);\r\n });\r\n\r\n } catch (error) {\r\n await this.cancelSpeech();\r\n }\r\n })(), cb, err);\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public dispose(reason?: string, success?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n if (this.isDisposed && !this.privIsSpeaking) {\r\n return;\r\n }\r\n await this.cancelSpeech();\r\n this.privIsDisposed = true;\r\n this.privSpeechTranslationConfig?.close();\r\n this.privSpeechRecognitionLanguage = undefined;\r\n this.privProperties = undefined;\r\n this.privAudioConfig = undefined;\r\n this.privSpeechTranslationConfig = undefined;\r\n this.privConversation?.dispose();\r\n this.privConversation = undefined;\r\n })(), success, err);\r\n }\r\n\r\n /**\r\n * Cancel the speech websocket\r\n */\r\n private async cancelSpeech(): Promise {\r\n try {\r\n this.privIsSpeaking = false;\r\n await this.privCTRecognizer?.onDisconnection();\r\n this.privCTRecognizer = undefined;\r\n } catch (e) {\r\n // ignore the error\r\n }\r\n }\r\n\r\n /**\r\n * Connect to the speech translation recognizer.\r\n * Currently there is no language validation performed before sending the SpeechLanguage code to the service.\r\n * If it's an invalid language the raw error will be: 'Error during WebSocket handshake: Unexpected response code: 400'\r\n * e.g. pass in 'fr' instead of 'fr-FR', or a text-only language 'cy'\r\n * @param cb\r\n * @param err\r\n */\r\n private async connectTranslatorRecognizer(): Promise {\r\n try {\r\n\r\n if (this.privAudioConfig === undefined) {\r\n this.privAudioConfig = AudioConfig.fromDefaultMicrophoneInput();\r\n }\r\n\r\n // clear the temp subscription key if it's a participant joining\r\n if (this.privSpeechTranslationConfig.getProperty(PropertyId[PropertyId.SpeechServiceConnection_Key])\r\n === this.privPlaceholderKey) {\r\n this.privSpeechTranslationConfig.setProperty(PropertyId[PropertyId.SpeechServiceConnection_Key], \"\");\r\n }\r\n\r\n // TODO\r\n const token: string = encodeURIComponent(this.privConversation.room.token);\r\n\r\n let endpointHost: string = this.privSpeechTranslationConfig.getProperty(\r\n PropertyId[PropertyId.SpeechServiceConnection_Host], ConversationConnectionConfig.speechHost);\r\n endpointHost = endpointHost.replace(\"{region}\", this.privConversation.room.cognitiveSpeechRegion);\r\n\r\n const url: string = `wss://${endpointHost}${ConversationConnectionConfig.speechPath}?${ConversationConnectionConfig.configParams.token}=${token}`;\r\n\r\n this.privSpeechTranslationConfig.setProperty(PropertyId[PropertyId.SpeechServiceConnection_Endpoint], url);\r\n\r\n this.privCTRecognizer = new ConversationTranslationRecognizer(this.privSpeechTranslationConfig, this.privAudioConfig, this);\r\n } catch (error) {\r\n await this.cancelSpeech();\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Handle the start speaking request\r\n * @param cb\r\n * @param err\r\n */\r\n private startContinuousRecognition(): Promise {\r\n return new Promise((resolve: () => void, reject: (error: string) => void): void => {\r\n this.privCTRecognizer.startContinuousRecognitionAsync(resolve, reject);\r\n });\r\n }\r\n\r\n private get canSpeak(): boolean {\r\n\r\n // is there a Conversation websocket available and has the Recognizer been set up\r\n if (!this.privConversation.isConnected || !this.privCTRecognizer) {\r\n return false;\r\n }\r\n\r\n // is the user already speaking\r\n if (this.privIsSpeaking || this.privCTRecognizer.state === SpeechState.Connected || this.privCTRecognizer.state === SpeechState.Connecting) {\r\n return false;\r\n }\r\n\r\n // is the user muted\r\n if (this.privConversation.isMutedByHost) {\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n OutputFormatPropertyName,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary\r\n} from \"../common/Exports\";\r\nimport {\r\n OutputFormat,\r\n PropertyId\r\n} from \"../sdk/Exports\";\r\nimport {\r\n ConnectionFactoryBase\r\n} from \"./ConnectionFactoryBase\";\r\nimport {\r\n AuthInfo,\r\n RecognizerConfig,\r\n WebsocketMessageFormatter\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport {\r\n QueryParameterNames\r\n} from \"./QueryParameterNames\";\r\n\r\nexport class TranscriberConnectionFactory extends ConnectionFactoryBase {\r\n\r\n private readonly multiaudioRelativeUri: string = \"/speech/recognition/multiaudio\";\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, \"centralus\");\r\n const hostSuffix: string = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const hostDefault: string = \"wss://transcribe.\" + region + \".cts.speech\" + hostSuffix + this.multiaudioRelativeUri;\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, hostDefault);\r\n\r\n const queryParams: IStringDictionary = {};\r\n\r\n const endpointId: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_EndpointId, undefined);\r\n const language: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, undefined);\r\n\r\n if (endpointId) {\r\n if (!endpoint || endpoint.search(QueryParameterNames.CustomSpeechDeploymentId) === -1) {\r\n queryParams[QueryParameterNames.CustomSpeechDeploymentId] = endpointId;\r\n }\r\n } else if (language) {\r\n if (!endpoint || endpoint.search(QueryParameterNames.Language) === -1) {\r\n queryParams[QueryParameterNames.Language] = language;\r\n }\r\n }\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n if (!endpoint) {\r\n endpoint = host;\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationEventArgsBase,\r\n} from \"./CancellationEventArgsBase\";\r\n\r\n/**\r\n * Defines content of a RecognitionErrorEvent.\r\n * @class ConversationTranscriptionCanceledEventArgs\r\n */\r\nexport class ConversationTranscriptionCanceledEventArgs extends CancellationEventArgsBase {\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IAudioSource,\r\n IConnection,\r\n MessageType\r\n} from \"../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n ConversationTranscriptionCanceledEventArgs,\r\n OutputFormat,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult,\r\n} from \"../sdk/Exports\";\r\nimport { ConversationInfo } from \"../sdk/Transcription/Exports\";\r\nimport {\r\n CancellationErrorCodePropertyName,\r\n DetailedSpeechPhrase,\r\n EnumTranslation,\r\n OutputFormatPropertyName,\r\n RecognitionStatus,\r\n ServiceRecognizerBase,\r\n SimpleSpeechPhrase,\r\n SpeechHypothesis,\r\n TranscriberRecognizer\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class TranscriptionServiceRecognizer extends ServiceRecognizerBase {\r\n\r\n private privTranscriberRecognizer: TranscriberRecognizer;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n transcriber: TranscriberRecognizer) {\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, transcriber);\r\n this.privTranscriberRecognizer = transcriber;\r\n this.sendPrePayloadJSONOverride = this.sendTranscriptionStartJSON;\r\n }\r\n\r\n public async sendSpeechEventAsync(info: ConversationInfo, command: string): Promise {\r\n if (!!this.privRequestSession.isRecognizing) {\r\n const connection: IConnection = await this.fetchConnection();\r\n await this.sendSpeechEvent(connection, this.createSpeechEventPayload(info, command));\r\n }\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n let result: SpeechRecognitionResult;\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n let processed: boolean = false;\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"speech.hypothesis\":\r\n case \"speech.fragment\":\r\n const hypothesis: SpeechHypothesis = SpeechHypothesis.fromJSON(connectionMessage.textBody);\r\n const offset: number = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n ResultReason.RecognizingSpeech,\r\n hypothesis.Text,\r\n hypothesis.Duration,\r\n offset,\r\n hypothesis.Language,\r\n hypothesis.LanguageDetectionConfidence,\r\n hypothesis.SpeakerId,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n this.privRequestSession.onHypothesis(offset);\r\n\r\n const ev = new SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privTranscriberRecognizer.recognizing) {\r\n try {\r\n this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.phrase\":\r\n const simple: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n const resultReason: ResultReason = EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus);\r\n\r\n this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + simple.Offset + simple.Duration);\r\n\r\n if (ResultReason.Canceled === resultReason) {\r\n const cancelReason: CancellationReason = EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);\r\n\r\n await this.cancelRecognitionLocal(\r\n cancelReason,\r\n EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus),\r\n undefined);\r\n\r\n } else {\r\n if (!(this.privRequestSession.isSpeechEnded && resultReason === ResultReason.NoMatch && simple.RecognitionStatus !== RecognitionStatus.InitialSilenceTimeout)) {\r\n if (this.privRecognizerConfig.parameters.getProperty(OutputFormatPropertyName) === OutputFormat[OutputFormat.Simple]) {\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n simple.DisplayText,\r\n simple.Duration,\r\n simple.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n simple.Language,\r\n simple.LanguageDetectionConfidence,\r\n simple.SpeakerId,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n } else {\r\n const detailed: DetailedSpeechPhrase = DetailedSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n detailed.RecognitionStatus === RecognitionStatus.Success ? detailed.NBest[0].Display : undefined,\r\n detailed.Duration,\r\n detailed.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n detailed.Language,\r\n detailed.LanguageDetectionConfidence,\r\n undefined,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n }\r\n\r\n const event: SpeechRecognitionEventArgs = new SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privTranscriberRecognizer.recognized) {\r\n try {\r\n this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer, event);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n }\r\n processed = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n if (!!this.privTranscriberRecognizer.canceled) {\r\n const cancelEvent: ConversationTranscriptionCanceledEventArgs = new ConversationTranscriptionCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n sessionId);\r\n try {\r\n this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: SpeechRecognitionResult = new SpeechRecognitionResult(\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Duration\r\n undefined, // Offset\r\n undefined, // Language\r\n undefined, // Language Detection Confidence\r\n undefined, // Speaker Id\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n this.privSuccessCallback = undefined;\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n\r\n // Encapsulated for derived service recognizers that need to send additional JSON\r\n protected async sendTranscriptionStartJSON(connection: IConnection): Promise {\r\n await this.sendSpeechContext(connection);\r\n const info: ConversationInfo = this.privTranscriberRecognizer.getConversationInfo();\r\n const payload: { [id: string]: any } = this.createSpeechEventPayload(info, \"start\");\r\n await this.sendSpeechEvent(connection, payload);\r\n await this.sendWaveHeader(connection);\r\n return;\r\n }\r\n\r\n protected sendSpeechEvent = (connection: IConnection, payload: { [id: string]: any }): Promise => {\r\n const speechEventJson = JSON.stringify(payload);\r\n\r\n if (speechEventJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.event\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n speechEventJson));\r\n }\r\n return;\r\n }\r\n\r\n private createSpeechEventPayload(info: ConversationInfo, command: string): { [id: string]: any } {\r\n const meeting: string = \"meeting\";\r\n const eventDict: { [id: string]: any } = { id: meeting, name: command, meeting: info.conversationProperties };\r\n const idString: string = \"id\";\r\n const attendees: string = \"attendees\";\r\n const record: string = \"record\";\r\n eventDict[meeting][idString] = info.id;\r\n eventDict[meeting][attendees] = info.participants;\r\n eventDict[meeting][record] = info.conversationProperties.audiorecording === \"on\" ? \"true\" : \"false\";\r\n return eventDict;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { marshalPromiseToCallbacks } from \"../../common/Exports\";\r\nimport { AudioConfigImpl } from \"../../sdk/Audio/AudioConfig\";\r\nimport { Contracts } from \"../../sdk/Contracts\";\r\nimport {\r\n AudioConfig,\r\n CancellationEventArgs,\r\n Conversation,\r\n ConversationInfo,\r\n ConversationTranscriber,\r\n PropertyCollection,\r\n PropertyId,\r\n Recognizer,\r\n SessionEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechTranslationConfig,\r\n SpeechTranslationConfigImpl,\r\n} from \"../../sdk/Exports\";\r\nimport {\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig,\r\n TranscriberConnectionFactory,\r\n TranscriptionServiceRecognizer,\r\n} from \"../Exports\";\r\n\r\nexport class TranscriberRecognizer extends Recognizer {\r\n private privDisposedRecognizer: boolean;\r\n private privConversation: Conversation;\r\n\r\n /**\r\n * TranscriberRecognizer constructor.\r\n * @constructor\r\n * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer\r\n */\r\n public constructor(speechTranslationConfig: SpeechTranslationConfig, audioConfig?: AudioConfig) {\r\n const speechTranslationConfigImpl: SpeechTranslationConfigImpl = speechTranslationConfig as SpeechTranslationConfigImpl;\r\n Contracts.throwIfNull(speechTranslationConfigImpl, \"speechTranslationConfig\");\r\n\r\n Contracts.throwIfNullOrWhitespace(\r\n speechTranslationConfigImpl.speechRecognitionLanguage,\r\n PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);\r\n\r\n super(audioConfig, speechTranslationConfigImpl.properties, new TranscriberConnectionFactory());\r\n this.privDisposedRecognizer = false;\r\n }\r\n\r\n public recognizing: (sender: Recognizer, event: SpeechRecognitionEventArgs) => void;\r\n\r\n public recognized: (sender: Recognizer, event: SpeechRecognitionEventArgs) => void;\r\n\r\n public canceled: (sender: Recognizer, event: CancellationEventArgs) => void;\r\n\r\n public getConversationInfo(): ConversationInfo {\r\n Contracts.throwIfNullOrUndefined(this.privConversation, \"Conversation\");\r\n return this.privConversation.conversationInfo;\r\n }\r\n\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n public set conversation(c: Conversation) {\r\n Contracts.throwIfNullOrUndefined(c, \"Conversation\");\r\n this.privConversation = c;\r\n }\r\n\r\n public get speechRecognitionLanguage(): string {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);\r\n }\r\n\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public startContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(RecognitionMode.Conversation), cb, err);\r\n }\r\n\r\n public stopContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);\r\n }\r\n\r\n public async close(): Promise {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n await this.dispose(true);\r\n }\r\n\r\n // Push async join/leave conversation message via serviceRecognizer\r\n public async pushConversationEvent(conversationInfo: ConversationInfo, command: string): Promise {\r\n const reco = (this.privReco) as TranscriptionServiceRecognizer;\r\n Contracts.throwIfNullOrUndefined(reco, \"serviceRecognizer\");\r\n await reco.sendSpeechEventAsync(conversationInfo, command);\r\n }\r\n\r\n public connectCallbacks(transcriber: ConversationTranscriber): void {\r\n this.canceled = (s: any, e: CancellationEventArgs): void => {\r\n if (!!transcriber.canceled) {\r\n transcriber.canceled(transcriber, e);\r\n }\r\n };\r\n this.recognizing = (s: any, e: SpeechRecognitionEventArgs): void => {\r\n if (!!transcriber.transcribing) {\r\n transcriber.transcribing(transcriber, e);\r\n }\r\n };\r\n this.recognized = (s: any, e: SpeechRecognitionEventArgs): void => {\r\n if (!!transcriber.transcribed) {\r\n transcriber.transcribed(transcriber, e);\r\n }\r\n };\r\n this.sessionStarted = (s: any, e: SessionEventArgs): void => {\r\n if (!!transcriber.sessionStarted) {\r\n transcriber.sessionStarted(transcriber, e);\r\n }\r\n };\r\n this.sessionStopped = (s: any, e: SessionEventArgs): void => {\r\n if (!!transcriber.sessionStopped) {\r\n transcriber.sessionStopped(transcriber, e);\r\n }\r\n };\r\n }\r\n\r\n public disconnectCallbacks(): void {\r\n this.canceled = undefined;\r\n this.recognizing = undefined;\r\n this.recognized = undefined;\r\n this.sessionStarted = undefined;\r\n this.sessionStopped = undefined;\r\n }\r\n\r\n /**\r\n * Disposes any resources held by the object.\r\n * @member ConversationTranscriber.prototype.dispose\r\n * @function\r\n * @public\r\n * @param {boolean} disposing - true if disposing the object.\r\n */\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privDisposedRecognizer) {\r\n return;\r\n }\r\n\r\n if (disposing) {\r\n this.privDisposedRecognizer = true;\r\n await this.implRecognizerStop();\r\n }\r\n\r\n await super.dispose(disposing);\r\n }\r\n\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(\r\n speechConfig,\r\n this.properties);\r\n }\r\n\r\n protected createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n const configImpl: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n return new TranscriptionServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection } from \"../sdk/Exports\";\r\nimport {Context, SpeechServiceConfig} from \"./Exports\";\r\n\r\nexport enum SynthesisServiceType {\r\n Standard,\r\n Custom,\r\n}\r\n\r\nexport class SynthesizerConfig {\r\n private privSynthesisServiceType: SynthesisServiceType = SynthesisServiceType.Standard;\r\n private privSpeechServiceConfig: SpeechServiceConfig;\r\n private privParameters: PropertyCollection;\r\n\r\n constructor(\r\n speechServiceConfig: SpeechServiceConfig,\r\n parameters: PropertyCollection) {\r\n this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new SpeechServiceConfig(new Context(null));\r\n this.privParameters = parameters;\r\n }\r\n\r\n public get parameters(): PropertyCollection {\r\n return this.privParameters;\r\n }\r\n\r\n public get synthesisServiceType(): SynthesisServiceType {\r\n return this.privSynthesisServiceType;\r\n }\r\n\r\n public set synthesisServiceType(value: SynthesisServiceType) {\r\n this.privSynthesisServiceType = value;\r\n }\r\n\r\n public get SpeechServiceConfig(): SpeechServiceConfig {\r\n return this.privSpeechServiceConfig;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { TranscriberRecognizer } from \"../../common.speech/Exports\";\r\nimport { marshalPromiseToCallbacks } from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n AudioConfig,\r\n CancellationEventArgs,\r\n ConversationTranscriptionEventArgs,\r\n PropertyCollection,\r\n PropertyId,\r\n SessionEventArgs,\r\n} from \"../Exports\";\r\nimport {\r\n ConversationHandler,\r\n ConversationImpl,\r\n ConversationTranscriptionHandler,\r\n} from \"./Exports\";\r\nimport { Callback, IConversation } from \"./IConversation\";\r\n\r\nexport class ConversationTranscriber implements ConversationTranscriptionHandler {\r\n private privDisposedRecognizer: boolean;\r\n private privRecognizer: TranscriberRecognizer;\r\n private privProperties: PropertyCollection;\r\n protected privAudioConfig: AudioConfig;\r\n\r\n /**\r\n * ConversationTranscriber constructor.\r\n * @constructor\r\n * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer\r\n */\r\n public constructor(audioConfig?: AudioConfig) {\r\n this.privAudioConfig = audioConfig;\r\n this.privProperties = new PropertyCollection();\r\n this.privRecognizer = undefined;\r\n this.privDisposedRecognizer = false;\r\n }\r\n\r\n /**\r\n * The event canceled signals that an error occurred during transcription.\r\n * @member ConversationTranscriber.prototype.canceled\r\n * @function\r\n * @public\r\n */\r\n public canceled: (sender: ConversationHandler, event: CancellationEventArgs) => void;\r\n\r\n /**\r\n * @param {Conversation} converation - conversation to be recognized\r\n */\r\n public joinConversationAsync(conversation: IConversation, cb?: Callback, err?: Callback): void {\r\n const conversationImpl = conversation as ConversationImpl;\r\n Contracts.throwIfNullOrUndefined(conversationImpl, \"Conversation\");\r\n\r\n // ref the conversation object\r\n // create recognizer and subscribe to recognizer events\r\n this.privRecognizer = new TranscriberRecognizer(conversation.config, this.privAudioConfig);\r\n Contracts.throwIfNullOrUndefined(this.privRecognizer, \"Recognizer\");\r\n this.privRecognizer.connectCallbacks(this);\r\n\r\n marshalPromiseToCallbacks(conversationImpl.connectTranscriberRecognizer(this.privRecognizer), cb, err);\r\n }\r\n\r\n /**\r\n * The event recognized signals that a final conversation transcription result is received.\r\n * @member ConversationTranscriber.prototype.transcribed\r\n * @function\r\n * @public\r\n */\r\n public transcribed: (sender: ConversationTranscriptionHandler, event: ConversationTranscriptionEventArgs) => void;\r\n\r\n /**\r\n * The event recognizing signals that an intermediate conversation transcription result is received.\r\n * @member ConversationTranscriber.prototype.transcribing\r\n * @function\r\n * @public\r\n */\r\n public transcribing: (sender: ConversationTranscriptionHandler, event: ConversationTranscriptionEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for session started events.\r\n * @member ConversationTranscriber.prototype.sessionStarted\r\n * @function\r\n * @public\r\n */\r\n public sessionStarted: (sender: ConversationHandler, event: SessionEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for session stopped events.\r\n * @member ConversationTranscriber.prototype.sessionStopped\r\n * @function\r\n * @public\r\n */\r\n public sessionStopped: (sender: ConversationHandler, event: SessionEventArgs) => void;\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member ConversationTranscriber.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Gets/Sets the authorization token used to communicate with the service.\r\n * @member ConversationTranscriber.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} token - Authorization token.\r\n */\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n /**\r\n * Gets the spoken language of recognition.\r\n * @member ConversationTranscriber.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @returns {string} The spoken language of recognition.\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this ConversationTranscriber.\r\n * @member ConversationTranscriber.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their values defined for this ConversationTranscriber.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * Starts conversation transcription, until stopTranscribingAsync() is called.\r\n * User must subscribe to events to receive transcription results.\r\n * @member ConversationTranscriber.prototype.startTranscribingAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback invoked once the transcription has started.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public startTranscribingAsync(cb?: Callback, err?: Callback): void {\r\n this.privRecognizer.startContinuousRecognitionAsync(cb, err);\r\n }\r\n\r\n /**\r\n * Starts conversation transcription, until stopTranscribingAsync() is called.\r\n * User must subscribe to events to receive transcription results.\r\n * @member ConversationTranscriber.prototype.stopTranscribingAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback invoked once the transcription has started.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public stopTranscribingAsync(cb?: Callback, err?: Callback): void {\r\n this.privRecognizer.stopContinuousRecognitionAsync(cb, err);\r\n }\r\n\r\n /**\r\n * Leave the current conversation. After this is called, you will no longer receive any events.\r\n */\r\n public leaveConversationAsync(cb?: Callback, err?: Callback): void {\r\n this.privRecognizer.disconnectCallbacks();\r\n marshalPromiseToCallbacks((async (): Promise => { return; })(), cb, err);\r\n }\r\n\r\n /**\r\n * closes all external resources held by an instance of this class.\r\n * @member ConversationTranscriber.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, errorCb?: (error: string) => void): void {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);\r\n }\r\n\r\n /**\r\n * Disposes any resources held by the object.\r\n * @member ConversationTranscriber.prototype.dispose\r\n * @function\r\n * @public\r\n * @param {boolean} disposing - true if disposing the object.\r\n */\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privDisposedRecognizer) {\r\n return;\r\n }\r\n\r\n if (disposing) {\r\n this.privDisposedRecognizer = true;\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection, WebsocketMessageAdapter,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary\r\n} from \"../common/Exports\";\r\nimport { PropertyId } from \"../sdk/Exports\";\r\nimport {\r\n AuthInfo,\r\n SynthesizerConfig,\r\n WebsocketMessageFormatter\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { ISynthesisConnectionFactory } from \"./ISynthesisConnectionFactory\";\r\nimport {\r\n QueryParameterNames\r\n} from \"./QueryParameterNames\";\r\n\r\nexport class SpeechSynthesisConnectionFactory implements ISynthesisConnectionFactory {\r\n\r\n private readonly synthesisUri: string = \"/cognitiveservices/websocket/v1\";\r\n\r\n public create = (\r\n config: SynthesizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, undefined);\r\n const hostSuffix = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const endpointId = config.parameters.getProperty(PropertyId.SpeechServiceConnection_EndpointId, undefined);\r\n const hostPrefix = (endpointId === undefined) ? \"tts\" : \"voice\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"wss://\" + region + \".\" + hostPrefix + \".speech\" + hostSuffix);\r\n\r\n const queryParams: IStringDictionary = {};\r\n\r\n if (!endpoint) {\r\n endpoint = host + this.synthesisUri;\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n if (endpointId !== undefined) {\r\n headers[QueryParameterNames.CustomVoiceDeploymentId] = endpointId;\r\n }\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromParameters(config.parameters), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the point system for pronunciation score calibration; default value is FivePoint.\r\n * Added in version 1.15.0\r\n * @class PronunciationAssessmentGradingSystem\r\n */\r\nexport enum PronunciationAssessmentGradingSystem {\r\n /**\r\n * Five point calibration\r\n * @member PronunciationAssessmentGradingSystem.FivePoint\r\n */\r\n FivePoint = 1,\r\n\r\n /**\r\n * Hundred mark\r\n * @member PronunciationAssessmentGradingSystem.HundredMark\r\n */\r\n HundredMark,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the pronunciation evaluation granularity; default value is Phoneme.\r\n * Added in version 1.15.0\r\n * @class PronunciationAssessmentGranularity\r\n */\r\nexport enum PronunciationAssessmentGranularity {\r\n /**\r\n * Shows the score on the full text, word and phoneme level\r\n * @member PronunciationAssessmentGranularity.Phoneme\r\n */\r\n Phoneme = 1,\r\n\r\n /**\r\n * Shows the score on the full text and word level\r\n * @member PronunciationAssessmentGranularity.Word\r\n */\r\n Word,\r\n\r\n /**\r\n * Shows the score on the full text level only\r\n * @member PronunciationAssessmentGranularity.FullText\r\n */\r\n FullText,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PathLike } from \"fs\";\r\nimport {\r\n AutoDetectSourceLanguagesOpenRangeOptionName,\r\n CognitiveSubscriptionKeyAuthentication,\r\n CognitiveTokenAuthentication,\r\n Context,\r\n IAuthentication,\r\n ISynthesisConnectionFactory,\r\n OS,\r\n SpeechServiceConfig,\r\n SpeechSynthesisConnectionFactory,\r\n SynthesisAdapterBase,\r\n SynthesizerConfig,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n createNoDashGuid,\r\n IAudioDestination,\r\n IStringDictionary,\r\n marshalPromiseToCallbacks,\r\n Queue\r\n} from \"../common/Exports\";\r\nimport { AudioOutputConfigImpl } from \"./Audio/AudioConfig\";\r\nimport { AudioFileWriter } from \"./Audio/AudioFileWriter\";\r\nimport { AudioOutputFormatImpl } from \"./Audio/AudioOutputFormat\";\r\nimport {\r\n PullAudioOutputStreamImpl,\r\n PushAudioOutputStreamImpl\r\n} from \"./Audio/AudioOutputStream\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n AudioConfig,\r\n AudioOutputStream,\r\n AutoDetectSourceLanguageConfig,\r\n PropertyCollection,\r\n PropertyId,\r\n PullAudioOutputStream,\r\n PushAudioOutputStreamCallback,\r\n SpeechConfig,\r\n SpeechSynthesisBookmarkEventArgs,\r\n SpeechSynthesisEventArgs,\r\n SpeechSynthesisOutputFormat,\r\n SpeechSynthesisResult,\r\n SpeechSynthesisVisemeEventArgs,\r\n SpeechSynthesisWordBoundaryEventArgs,\r\n} from \"./Exports\";\r\nimport { SpeechConfigImpl } from \"./SpeechConfig\";\r\n\r\n/**\r\n * Defines the class SpeechSynthesizer for text to speech.\r\n * Updated in version 1.16.0\r\n * @class SpeechSynthesizer\r\n */\r\nexport class SpeechSynthesizer {\r\n protected audioConfig: AudioConfig;\r\n protected privAdapter: SynthesisAdapterBase;\r\n protected privProperties: PropertyCollection;\r\n protected synthesisRequestQueue: Queue;\r\n\r\n /**\r\n * Defines event handler for synthesis start events.\r\n * @member SpeechSynthesizer.prototype.synthesisStarted\r\n * @function\r\n * @public\r\n */\r\n public synthesisStarted: (sender: SpeechSynthesizer, event: SpeechSynthesisEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for synthesizing events.\r\n * @member SpeechSynthesizer.prototype.synthesizing\r\n * @function\r\n * @public\r\n */\r\n public synthesizing: (sender: SpeechSynthesizer, event: SpeechSynthesisEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for synthesis completed events.\r\n * @member SpeechSynthesizer.prototype.synthesisCompleted\r\n * @function\r\n * @public\r\n */\r\n public synthesisCompleted: (sender: SpeechSynthesizer, event: SpeechSynthesisEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for synthesis cancelled events.\r\n * @member SpeechSynthesizer.prototype.SynthesisCanceled\r\n * @function\r\n * @public\r\n */\r\n public SynthesisCanceled: (sender: SpeechSynthesizer, event: SpeechSynthesisEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for word boundary events\r\n * @member SpeechSynthesizer.prototype.wordBoundary\r\n * @function\r\n * @public\r\n */\r\n public wordBoundary: (sender: SpeechSynthesizer, event: SpeechSynthesisWordBoundaryEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for bookmark reached events\r\n * Added in version 1.16.0\r\n * @member SpeechSynthesizer.prototype.bookmarkReached\r\n * @function\r\n * @public\r\n */\r\n public bookmarkReached: (sender: SpeechSynthesizer, event: SpeechSynthesisBookmarkEventArgs) => void;\r\n\r\n /**\r\n * Defines event handler for viseme received event\r\n * Added in version 1.16.0\r\n * @member SpeechSynthesizer.prototype.visemeReceived\r\n * @function\r\n * @public\r\n */\r\n public visemeReceived: (sender: SpeechSynthesizer, event: SpeechSynthesisVisemeEventArgs) => void;\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member SpeechSynthesizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Gets/Sets the authorization token used to communicate with the service.\r\n * @member SpeechSynthesizer.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} token - Authorization token.\r\n */\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this SpeechSynthesizer.\r\n * @member SpeechSynthesizer.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechSynthesizer.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * Indicates if auto detect source language is enabled\r\n * @member SpeechSynthesizer.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {boolean} if auto detect source language is enabled\r\n */\r\n public get autoDetectSourceLanguage(): boolean {\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages) === AutoDetectSourceLanguagesOpenRangeOptionName;\r\n }\r\n\r\n private privDisposed: boolean;\r\n private privConnectionFactory: ISynthesisConnectionFactory;\r\n private privSynthesizing: boolean;\r\n\r\n /**\r\n * SpeechSynthesizer constructor.\r\n * @constructor\r\n * @param {SpeechConfig} speechConfig - An set of initial properties for this synthesizer.\r\n * @param {AudioConfig} audioConfig - An optional audio configuration associated with the synthesizer.\r\n */\r\n public constructor(speechConfig: SpeechConfig, audioConfig?: AudioConfig) {\r\n const speechConfigImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;\r\n Contracts.throwIfNull(speechConfigImpl, \"speechConfig\");\r\n\r\n if (audioConfig !== null) {\r\n if (audioConfig === undefined) {\r\n this.audioConfig = (typeof window === \"undefined\") ? undefined : AudioConfig.fromDefaultSpeakerOutput();\r\n } else {\r\n this.audioConfig = audioConfig;\r\n }\r\n }\r\n\r\n this.privProperties = speechConfigImpl.properties.clone();\r\n this.privDisposed = false;\r\n this.privSynthesizing = false;\r\n this.privConnectionFactory = new SpeechSynthesisConnectionFactory();\r\n this.synthesisRequestQueue = new Queue();\r\n this.implCommonSynthesizeSetup();\r\n }\r\n\r\n /**\r\n * SpeechSynthesizer constructor.\r\n * @constructor\r\n * @param {SpeechConfig} speechConfig - an set of initial properties for this synthesizer\r\n * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the synthesizer\r\n * @param {AudioConfig} audioConfig - An optional audio configuration associated with the synthesizer\r\n */\r\n public static FromConfig(speechConfig: SpeechConfig, autoDetectSourceLanguageConfig: AutoDetectSourceLanguageConfig, audioConfig?: AudioConfig): SpeechSynthesizer {\r\n const speechConfigImpl: SpeechConfigImpl = speechConfig as SpeechConfigImpl;\r\n autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties);\r\n return new SpeechSynthesizer(speechConfig, audioConfig);\r\n }\r\n\r\n public buildSsml(text: string): string {\r\n const languageToDefaultVoice: IStringDictionary = {\r\n [\"ar-EG\"]: \"Microsoft Server Speech Text to Speech Voice (ar-EG, Hoda)\",\r\n [\"ar-SA\"]: \"Microsoft Server Speech Text to Speech Voice (ar-SA, Naayf)\",\r\n [\"bg-BG\"]: \"Microsoft Server Speech Text to Speech Voice (bg-BG, Ivan)\",\r\n [\"ca-ES\"]: \"Microsoft Server Speech Text to Speech Voice (ca-ES, HerenaRUS)\",\r\n [\"cs-CZ\"]: \"Microsoft Server Speech Text to Speech Voice (cs-CZ, Jakub)\",\r\n [\"da-DK\"]: \"Microsoft Server Speech Text to Speech Voice (da-DK, HelleRUS)\",\r\n [\"de-AT\"]: \"Microsoft Server Speech Text to Speech Voice (de-AT, Michael)\",\r\n [\"de-CH\"]: \"Microsoft Server Speech Text to Speech Voice (de-CH, Karsten)\",\r\n [\"de-DE\"]: \"Microsoft Server Speech Text to Speech Voice (de-DE, HeddaRUS)\",\r\n [\"el-GR\"]: \"Microsoft Server Speech Text to Speech Voice (el-GR, Stefanos)\",\r\n [\"en-AU\"]: \"Microsoft Server Speech Text to Speech Voice (en-AU, HayleyRUS)\",\r\n [\"en-CA\"]: \"Microsoft Server Speech Text to Speech Voice (en-CA, HeatherRUS)\",\r\n [\"en-GB\"]: \"Microsoft Server Speech Text to Speech Voice (en-GB, HazelRUS)\",\r\n [\"en-IE\"]: \"Microsoft Server Speech Text to Speech Voice (en-IE, Sean)\",\r\n [\"en-IN\"]: \"Microsoft Server Speech Text to Speech Voice (en-IN, PriyaRUS)\",\r\n [\"en-US\"]: \"Microsoft Server Speech Text to Speech Voice (en-US, AriaRUS)\",\r\n [\"es-ES\"]: \"Microsoft Server Speech Text to Speech Voice (es-ES, HelenaRUS)\",\r\n [\"es-MX\"]: \"Microsoft Server Speech Text to Speech Voice (es-MX, HildaRUS)\",\r\n [\"fi-FI\"]: \"Microsoft Server Speech Text to Speech Voice (fi-FI, HeidiRUS)\",\r\n [\"fr-CA\"]: \"Microsoft Server Speech Text to Speech Voice (fr-CA, HarmonieRUS)\",\r\n [\"fr-CH\"]: \"Microsoft Server Speech Text to Speech Voice (fr-CH, Guillaume)\",\r\n [\"fr-FR\"]: \"Microsoft Server Speech Text to Speech Voice (fr-FR, HortenseRUS)\",\r\n [\"he-IL\"]: \"Microsoft Server Speech Text to Speech Voice (he-IL, Asaf)\",\r\n [\"hi-IN\"]: \"Microsoft Server Speech Text to Speech Voice (hi-IN, Kalpana)\",\r\n [\"hr-HR\"]: \"Microsoft Server Speech Text to Speech Voice (hr-HR, Matej)\",\r\n [\"hu-HU\"]: \"Microsoft Server Speech Text to Speech Voice (hu-HU, Szabolcs)\",\r\n [\"id-ID\"]: \"Microsoft Server Speech Text to Speech Voice (id-ID, Andika)\",\r\n [\"it-IT\"]: \"Microsoft Server Speech Text to Speech Voice (it-IT, LuciaRUS)\",\r\n [\"ja-JP\"]: \"Microsoft Server Speech Text to Speech Voice (ja-JP, HarukaRUS)\",\r\n [\"ko-KR\"]: \"Microsoft Server Speech Text to Speech Voice (ko-KR, HeamiRUS)\",\r\n [\"ms-MY\"]: \"Microsoft Server Speech Text to Speech Voice (ms-MY, Rizwan)\",\r\n [\"nb-NO\"]: \"Microsoft Server Speech Text to Speech Voice (nb-NO, HuldaRUS)\",\r\n [\"nl-NL\"]: \"Microsoft Server Speech Text to Speech Voice (nl-NL, HannaRUS)\",\r\n [\"pl-PL\"]: \"Microsoft Server Speech Text to Speech Voice (pl-PL, PaulinaRUS)\",\r\n [\"pt-BR\"]: \"Microsoft Server Speech Text to Speech Voice (pt-BR, HeloisaRUS)\",\r\n [\"pt-PT\"]: \"Microsoft Server Speech Text to Speech Voice (pt-PT, HeliaRUS)\",\r\n [\"ro-RO\"]: \"Microsoft Server Speech Text to Speech Voice (ro-RO, Andrei)\",\r\n [\"ru-RU\"]: \"Microsoft Server Speech Text to Speech Voice (ru-RU, EkaterinaRUS)\",\r\n [\"sk-SK\"]: \"Microsoft Server Speech Text to Speech Voice (sk-SK, Filip)\",\r\n [\"sl-SI\"]: \"Microsoft Server Speech Text to Speech Voice (sl-SI, Lado)\",\r\n [\"sv-SE\"]: \"Microsoft Server Speech Text to Speech Voice (sv-SE, HedvigRUS)\",\r\n [\"ta-IN\"]: \"Microsoft Server Speech Text to Speech Voice (ta-IN, Valluvar)\",\r\n [\"te-IN\"]: \"Microsoft Server Speech Text to Speech Voice (te-IN, Chitra)\",\r\n [\"th-TH\"]: \"Microsoft Server Speech Text to Speech Voice (th-TH, Pattara)\",\r\n [\"tr-TR\"]: \"Microsoft Server Speech Text to Speech Voice (tr-TR, SedaRUS)\",\r\n [\"vi-VN\"]: \"Microsoft Server Speech Text to Speech Voice (vi-VN, An)\",\r\n [\"zh-CN\"]: \"Microsoft Server Speech Text to Speech Voice (zh-CN, HuihuiRUS)\",\r\n [\"zh-HK\"]: \"Microsoft Server Speech Text to Speech Voice (zh-HK, TracyRUS)\",\r\n [\"zh-TW\"]: \"Microsoft Server Speech Text to Speech Voice (zh-TW, HanHanRUS)\",\r\n };\r\n\r\n let language = this.properties.getProperty(PropertyId.SpeechServiceConnection_SynthLanguage, \"en-US\");\r\n let voice = this.properties.getProperty(PropertyId.SpeechServiceConnection_SynthVoice, \"\");\r\n let ssml: string = SpeechSynthesizer.XMLEncode(text);\r\n if (this.autoDetectSourceLanguage) {\r\n language = \"en-US\";\r\n } else {\r\n voice = voice || languageToDefaultVoice[language];\r\n }\r\n if (voice) {\r\n ssml = `${ssml}`;\r\n }\r\n ssml = `${ssml}`;\r\n return ssml;\r\n }\r\n\r\n /**\r\n * Executes speech synthesis on plain text.\r\n * The task returns the synthesis result.\r\n * @member SpeechSynthesizer.prototype.speakTextAsync\r\n * @function\r\n * @public\r\n * @param text - Text to be synthesized.\r\n * @param cb - Callback that received the SpeechSynthesisResult.\r\n * @param err - Callback invoked in case of an error.\r\n * @param stream - AudioOutputStream to receive the synthesized audio.\r\n */\r\n public speakTextAsync(text: string, cb?: (e: SpeechSynthesisResult) => void, err?: (e: string) => void, stream?: AudioOutputStream | PushAudioOutputStreamCallback | PathLike): void {\r\n this.speakImpl(text, false, cb, err, stream);\r\n }\r\n\r\n /**\r\n * Executes speech synthesis on SSML.\r\n * The task returns the synthesis result.\r\n * @member SpeechSynthesizer.prototype.speakSsmlAsync\r\n * @function\r\n * @public\r\n * @param ssml - SSML to be synthesized.\r\n * @param cb - Callback that received the SpeechSynthesisResult.\r\n * @param err - Callback invoked in case of an error.\r\n * @param stream - AudioOutputStream to receive the synthesized audio.\r\n */\r\n public speakSsmlAsync(ssml: string, cb?: (e: SpeechSynthesisResult) => void, err?: (e: string) => void, stream?: AudioOutputStream | PushAudioOutputStreamCallback | PathLike): void {\r\n this.speakImpl(ssml, true, cb, err, stream);\r\n }\r\n\r\n /**\r\n * Dispose of associated resources.\r\n * @member SpeechSynthesizer.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, err?: (error: string) => void): void {\r\n Contracts.throwIfDisposed(this.privDisposed);\r\n\r\n marshalPromiseToCallbacks(this.dispose(true), cb, err);\r\n }\r\n\r\n /**\r\n * @Internal\r\n * Do not use externally, object returned will change without warning or notice.\r\n */\r\n public get internalData(): object {\r\n return this.privAdapter;\r\n }\r\n\r\n /**\r\n * This method performs cleanup of resources.\r\n * The Boolean parameter disposing indicates whether the method is called\r\n * from Dispose (if disposing is true) or from the finalizer (if disposing is false).\r\n * Derived classes should override this method to dispose resource if needed.\r\n * @member SpeechSynthesizer.prototype.dispose\r\n * @function\r\n * @public\r\n * @param {boolean} disposing - Flag to request disposal.\r\n */\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privDisposed) {\r\n return;\r\n }\r\n\r\n if (disposing) {\r\n if (this.privAdapter) {\r\n await this.privAdapter.dispose();\r\n }\r\n }\r\n\r\n this.privDisposed = true;\r\n }\r\n\r\n //\r\n // ################################################################################################################\r\n // IMPLEMENTATION.\r\n // Move to independent class\r\n // ################################################################################################################\r\n //\r\n protected createSynthesizerConfig(speechConfig: SpeechServiceConfig): SynthesizerConfig {\r\n return new SynthesizerConfig(\r\n speechConfig,\r\n this.privProperties);\r\n }\r\n\r\n // Creates the synthesis adapter\r\n protected createSynthesisAdapter(\r\n authentication: IAuthentication,\r\n connectionFactory: ISynthesisConnectionFactory,\r\n audioConfig: AudioConfig,\r\n synthesizerConfig: SynthesizerConfig): SynthesisAdapterBase {\r\n return new SynthesisAdapterBase(authentication, connectionFactory,\r\n synthesizerConfig, this, this.audioConfig as AudioOutputConfigImpl);\r\n }\r\n\r\n protected implCommonSynthesizeSetup(): void {\r\n\r\n let osPlatform = (typeof window !== \"undefined\") ? \"Browser\" : \"Node\";\r\n let osName = \"unknown\";\r\n let osVersion = \"unknown\";\r\n\r\n if (typeof navigator !== \"undefined\") {\r\n osPlatform = osPlatform + \"/\" + navigator.platform;\r\n osName = navigator.userAgent;\r\n osVersion = navigator.appVersion;\r\n }\r\n\r\n const synthesizerConfig = this.createSynthesizerConfig(\r\n new SpeechServiceConfig(\r\n new Context(new OS(osPlatform, osName, osVersion))));\r\n\r\n const subscriptionKey = this.privProperties.getProperty(PropertyId.SpeechServiceConnection_Key, undefined);\r\n const authentication = (subscriptionKey && subscriptionKey !== \"\") ?\r\n new CognitiveSubscriptionKeyAuthentication(subscriptionKey) :\r\n new CognitiveTokenAuthentication(\r\n (authFetchEventId: string): Promise => {\r\n const authorizationToken = this.privProperties.getProperty(PropertyId.SpeechServiceAuthorization_Token, undefined);\r\n return Promise.resolve(authorizationToken);\r\n },\r\n (authFetchEventId: string): Promise => {\r\n const authorizationToken = this.privProperties.getProperty(PropertyId.SpeechServiceAuthorization_Token, undefined);\r\n return Promise.resolve(authorizationToken);\r\n });\r\n\r\n this.privAdapter = this.createSynthesisAdapter(\r\n authentication,\r\n this.privConnectionFactory,\r\n this.audioConfig,\r\n synthesizerConfig);\r\n\r\n this.privAdapter.audioOutputFormat = AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(\r\n (SpeechSynthesisOutputFormat as any)[this.properties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)]\r\n );\r\n }\r\n\r\n protected speakImpl(text: string, IsSsml: boolean, cb?: (e: SpeechSynthesisResult) => void, err?: (e: string) => void, dataStream?: AudioOutputStream | PushAudioOutputStreamCallback | PathLike): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privDisposed);\r\n const requestId = createNoDashGuid();\r\n let audioDestination;\r\n if (dataStream instanceof PushAudioOutputStreamCallback) {\r\n audioDestination = new PushAudioOutputStreamImpl(dataStream);\r\n } else if (dataStream instanceof PullAudioOutputStream) {\r\n audioDestination = dataStream as PullAudioOutputStreamImpl;\r\n } else if (dataStream !== undefined) {\r\n audioDestination = new AudioFileWriter(dataStream as PathLike);\r\n } else {\r\n audioDestination = undefined;\r\n }\r\n this.synthesisRequestQueue.enqueue(new SynthesisRequest(requestId, text, IsSsml, (e: SpeechSynthesisResult): void => {\r\n this.privSynthesizing = false;\r\n if (!!cb) {\r\n try {\r\n cb(e);\r\n } catch (e) {\r\n if (!!err) {\r\n err(e);\r\n }\r\n }\r\n }\r\n cb = undefined;\r\n /* tslint:disable:no-empty */\r\n this.adapterSpeak().catch(() => { });\r\n\r\n }, (e: string): void => {\r\n if (!!err) {\r\n err(e);\r\n }\r\n }, audioDestination));\r\n\r\n /* tslint:disable:no-empty */\r\n this.adapterSpeak().catch(() => { });\r\n\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n }\r\n\r\n // Destroy the synthesizer.\r\n /* tslint:disable:no-empty */\r\n this.dispose(true).catch(() => { });\r\n }\r\n }\r\n\r\n protected async adapterSpeak(): Promise {\r\n if (!this.privDisposed && !this.privSynthesizing) {\r\n this.privSynthesizing = true;\r\n const request: SynthesisRequest = await this.synthesisRequestQueue.dequeue();\r\n return this.privAdapter.Speak(request.text, request.isSSML, request.requestId, request.cb, request.err, request.dataStream);\r\n }\r\n }\r\n\r\n private static XMLEncode(text: string): string {\r\n return text.replace(/&/g, \"&\")\r\n .replace(//g, \">\")\r\n .replace(/\"/g, \""\")\r\n .replace(/'/g, \"'\");\r\n }\r\n}\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class SynthesisRequest {\r\n public requestId: string;\r\n public text: string;\r\n public isSSML: boolean;\r\n public cb: (e: SpeechSynthesisResult) => void;\r\n public err: (e: string) => void;\r\n public dataStream: IAudioDestination;\r\n\r\n constructor(requestId: string, text: string, isSSML: boolean, cb?: (e: SpeechSynthesisResult) => void, err?: (e: string) => void, dataStream?: IAudioDestination) {\r\n this.requestId = requestId;\r\n this.text = text;\r\n this.isSSML = isSSML;\r\n this.cb = cb;\r\n this.err = err;\r\n this.dataStream = dataStream;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ServiceRecognizerBase } from \"../common.speech/ServiceRecognizerBase\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n PronunciationAssessmentGradingSystem,\r\n PronunciationAssessmentGranularity,\r\n PropertyCollection,\r\n PropertyId,\r\n Recognizer\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Pronunciation assessment configuration.\r\n * @class PronunciationAssessmentConfig\r\n * Added in version 1.15.0.\r\n */\r\nexport class PronunciationAssessmentConfig {\r\n private privProperties: PropertyCollection;\r\n\r\n /**\r\n * PronunciationAssessmentConfig constructor.\r\n * @constructor\r\n * @param {string} referenceText\r\n * @param gradingSystem\r\n * @param granularity\r\n * @param enableMiscue\r\n */\r\n public constructor(referenceText: string,\r\n gradingSystem: PronunciationAssessmentGradingSystem = PronunciationAssessmentGradingSystem.FivePoint,\r\n granularity: PronunciationAssessmentGranularity = PronunciationAssessmentGranularity.Phoneme,\r\n enableMiscue: boolean = false) {\r\n Contracts.throwIfNullOrUndefined(referenceText, \"referenceText\");\r\n this.privProperties = new PropertyCollection();\r\n this.privProperties.setProperty(PropertyId.PronunciationAssessment_ReferenceText, referenceText);\r\n this.privProperties.setProperty(PropertyId.PronunciationAssessment_GradingSystem, PronunciationAssessmentGradingSystem[gradingSystem]);\r\n this.privProperties.setProperty(PropertyId.PronunciationAssessment_Granularity, PronunciationAssessmentGranularity[granularity]);\r\n this.privProperties.setProperty(PropertyId.PronunciationAssessment_EnableMiscue, String(enableMiscue));\r\n }\r\n\r\n /**\r\n * @member PronunciationAssessmentConfig.fromJSON\r\n * @function\r\n * @public\r\n * @param {string} json The json string containing the pronunciation assessment parameters.\r\n * @return {PronunciationAssessmentConfig} Instance of PronunciationAssessmentConfig\r\n * @summary Creates an instance of the PronunciationAssessmentConfig from json.\r\n */\r\n public static fromJSON(json: string): PronunciationAssessmentConfig {\r\n Contracts.throwIfNullOrUndefined(json, \"json\");\r\n const config = new PronunciationAssessmentConfig(\"\");\r\n config.privProperties = new PropertyCollection();\r\n config.properties.setProperty(PropertyId.PronunciationAssessment_Json, json);\r\n return config;\r\n }\r\n\r\n public toJSON(): string {\r\n this.updateJson();\r\n return this.privProperties.getProperty(PropertyId.PronunciationAssessment_Params);\r\n }\r\n\r\n public applyTo(recognizer: Recognizer): void {\r\n this.updateJson();\r\n const recoBase = recognizer.internalData as ServiceRecognizerBase;\r\n recoBase.speechContext.setPronunciationAssessmentParams(this.properties.getProperty(PropertyId.PronunciationAssessment_Params));\r\n }\r\n\r\n /**\r\n * Gets the reference text.\r\n * @member PronunciationAssessmentConfig.prototype.referenceText\r\n * @function\r\n * @public\r\n * @returns {string} Reference text.\r\n */\r\n public get referenceText(): string {\r\n return this.properties.getProperty(PropertyId.PronunciationAssessment_ReferenceText);\r\n }\r\n\r\n /**\r\n * Gets/Sets the reference text.\r\n * @member PronunciationAssessmentConfig.prototype.referenceText\r\n * @function\r\n * @public\r\n * @param {string} referenceText - Reference text.\r\n */\r\n public set referenceText(referenceText: string) {\r\n Contracts.throwIfNullOrWhitespace(referenceText, \"referenceText\");\r\n this.properties.setProperty(PropertyId.PronunciationAssessment_ReferenceText, referenceText);\r\n }\r\n\r\n /**\r\n * @member PronunciationAssessmentConfig.prototype.properties\r\n * @function\r\n * @public\r\n * @return {PropertyCollection} Properties of the config.\r\n * @summary Gets a pronunciation assessment config properties\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n private updateJson(): void {\r\n const jsonString = this.privProperties.getProperty(PropertyId.PronunciationAssessment_Json, \"{}\");\r\n const paramsJson = JSON.parse(jsonString);\r\n\r\n const referenceText = this.privProperties.getProperty(PropertyId.PronunciationAssessment_ReferenceText);\r\n if (referenceText) {\r\n paramsJson.referenceText = referenceText;\r\n }\r\n\r\n const gradingSystem = this.privProperties.getProperty(PropertyId.PronunciationAssessment_GradingSystem);\r\n if (gradingSystem) {\r\n paramsJson.gradingSystem = gradingSystem;\r\n }\r\n\r\n const granularity = this.privProperties.getProperty(PropertyId.PronunciationAssessment_Granularity);\r\n if (granularity) {\r\n paramsJson.granularity = granularity;\r\n }\r\n\r\n // always set dimension to Comprehensive\r\n paramsJson.dimension = \"Comprehensive\";\r\n\r\n const enableMiscueString = this.privProperties.getProperty(PropertyId.PronunciationAssessment_EnableMiscue);\r\n if (enableMiscueString === \"true\") {\r\n paramsJson.enableMiscue = true;\r\n } else if (enableMiscueString === \"false\") {\r\n paramsJson.enableMiscue = false;\r\n }\r\n\r\n this.privProperties.setProperty(PropertyId.PronunciationAssessment_Params, JSON.stringify(paramsJson));\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {Contracts} from \"./Contracts\";\r\nimport {\r\n PropertyId,\r\n RecognitionResult\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Pronunciation assessment results.\r\n * @class PronunciationAssessmentResult\r\n * Added in version 1.15.0.\r\n */\r\nexport class PronunciationAssessmentResult {\r\n private privPronJson: any;\r\n\r\n private constructor(jsonString: string) {\r\n const j = JSON.parse(jsonString);\r\n Contracts.throwIfNullOrUndefined(j.NBest[0], \"NBest\");\r\n this.privPronJson = j.NBest[0];\r\n }\r\n\r\n /**\r\n * @member PronunciationAssessmentResult.fromResult\r\n * @function\r\n * @public\r\n * @param {RecognitionResult} result The recognition result.\r\n * @return {PronunciationAssessmentConfig} Instance of PronunciationAssessmentConfig\r\n * @summary Creates an instance of the PronunciationAssessmentResult from recognition result.\r\n */\r\n public static fromResult(result: RecognitionResult): PronunciationAssessmentResult {\r\n Contracts.throwIfNullOrUndefined(result, \"result\");\r\n const json: string = result.properties.getProperty(PropertyId.SpeechServiceResponse_JsonResult);\r\n Contracts.throwIfNullOrUndefined(json, \"json\");\r\n return new PronunciationAssessmentResult(json);\r\n }\r\n\r\n /**\r\n * Gets the detail result of pronunciation assessment.\r\n * @member PronunciationAssessmentConfig.prototype.detailResult\r\n * @function\r\n * @public\r\n * @returns {any} detail result.\r\n */\r\n public get detailResult(): any {\r\n return this.privPronJson;\r\n }\r\n\r\n /**\r\n * The score indicating the pronunciation accuracy of the given speech, which indicates\r\n * how closely the phonemes match a native speaker's pronunciation.\r\n * @member PronunciationAssessmentResult.prototype.accuracyScore\r\n * @function\r\n * @public\r\n * @returns {number} Accuracy score.\r\n */\r\n public get accuracyScore(): number {\r\n return this.detailResult.PronunciationAssessment.AccuracyScore;\r\n }\r\n\r\n /**\r\n * The overall score indicating the pronunciation quality of the given speech.\r\n * This is calculated from AccuracyScore, FluencyScore and CompletenessScore with weight.\r\n * @member PronunciationAssessmentResult.prototype.pronunciationScore\r\n * @function\r\n * @public\r\n * @returns {number} Pronunciation score.\r\n */\r\n public get pronunciationScore(): number {\r\n return this.detailResult.PronunciationAssessment.PronScore;\r\n }\r\n\r\n /**\r\n * The score indicating the completeness of the given speech by calculating the ratio of pronounced words towards entire input.\r\n * @member PronunciationAssessmentResult.prototype.completenessScore\r\n * @function\r\n * @public\r\n * @returns {number} Completeness score.\r\n */\r\n public get completenessScore(): number {\r\n return this.detailResult.PronunciationAssessment.CompletenessScore;\r\n }\r\n\r\n /**\r\n * The score indicating the fluency of the given speech.\r\n * @member PronunciationAssessmentResult.prototype.fluencyScore\r\n * @function\r\n * @public\r\n * @returns {number} Fluency score.\r\n */\r\n public get fluencyScore(): number {\r\n return this.detailResult.PronunciationAssessment.FluencyScore;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\nimport { ConsoleLoggingListener } from \"./src/common.browser/Exports\";\r\nimport { Events } from \"./src/common/Exports\";\r\n\r\n// Common.Storage.SetLocalStorage(new Common.Browser.LocalStorage());\r\n// Common.Storage.SetSessionStorage(new Common.Browser.SessionStorage());\r\nEvents.instance.attachListener(new ConsoleLoggingListener());\r\n\r\n// Speech SDK API\r\nexport * from \"./src/sdk/Exports\";\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { EventType, IEventListener, PlatformEvent } from \"../common/Exports\";\r\n\r\nexport class ConsoleLoggingListener implements IEventListener {\r\n private privLogLevelFilter: EventType;\r\n\r\n public constructor(logLevelFilter: EventType = EventType.Warning) {\r\n this.privLogLevelFilter = logLevelFilter;\r\n }\r\n\r\n public onEvent = (event: PlatformEvent): void => {\r\n if (event.eventType >= this.privLogLevelFilter) {\r\n const log = this.toString(event);\r\n\r\n switch (event.eventType) {\r\n case EventType.Debug:\r\n // tslint:disable-next-line:no-console\r\n console.debug(log);\r\n break;\r\n case EventType.Info:\r\n // tslint:disable-next-line:no-console\r\n console.info(log);\r\n break;\r\n case EventType.Warning:\r\n // tslint:disable-next-line:no-console\r\n console.warn(log);\r\n break;\r\n case EventType.Error:\r\n // tslint:disable-next-line:no-console\r\n console.error(log);\r\n break;\r\n default:\r\n // tslint:disable-next-line:no-console\r\n console.log(log);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n private toString = (event: any): string => {\r\n const logFragments = [\r\n `${event.EventTime}`,\r\n `${event.Name}`,\r\n ];\r\n\r\n for (const prop in event) {\r\n if (prop && event.hasOwnProperty(prop) &&\r\n prop !== \"eventTime\" && prop !== \"eventType\" &&\r\n prop !== \"eventId\" && prop !== \"name\" &&\r\n prop !== \"constructor\") {\r\n const value = event[prop];\r\n let valueToLog = \"\";\r\n if (value !== undefined && value !== null) {\r\n if (typeof (value) === \"number\" || typeof (value) === \"string\") {\r\n valueToLog = value.toString();\r\n } else {\r\n valueToLog = JSON.stringify(value);\r\n }\r\n }\r\n\r\n logFragments.push(`${prop}: ${valueToLog}`);\r\n }\r\n\r\n }\r\n\r\n return logFragments.join(\" | \");\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\nimport { ConsoleLoggingListener } from \"./src/common.browser/Exports\";\r\nimport { Events } from \"./src/common/Exports\";\r\n\r\n// Common.Storage.SetLocalStorage(new Common.Browser.LocalStorage());\r\n// Common.Storage.SetSessionStorage(new Common.Browser.SessionStorage());\r\nEvents.instance.attachListener(new ConsoleLoggingListener());\r\n\r\n// Speech SDK API\r\nexport * from \"./src/sdk/Exports\";\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport * as http from \"http\";\r\nimport * as tls from \"tls\";\r\nimport * as parse from \"url-parse\";\r\nimport * as ocsp from \"../../external/ocsp/ocsp\";\r\nimport {\r\n Events,\r\n OCSPCacheEntryExpiredEvent,\r\n OCSPCacheEntryNeedsRefreshEvent,\r\n OCSPCacheFetchErrorEvent,\r\n OCSPCacheHitEvent,\r\n OCSPCacheMissEvent,\r\n OCSPCacheUpdatehCompleteEvent,\r\n OCSPCacheUpdateNeededEvent,\r\n OCSPDiskCacheHitEvent,\r\n OCSPDiskCacheStoreEvent,\r\n OCSPEvent,\r\n OCSPMemoryCacheHitEvent,\r\n OCSPMemoryCacheStoreEvent,\r\n OCSPResponseRetrievedEvent,\r\n OCSPStapleReceivedEvent,\r\n OCSPVerificationFailedEvent,\r\n} from \"../common/Exports\";\r\nimport { IStringDictionary } from \"../common/IDictionary\";\r\nimport { ProxyInfo } from \"./ProxyInfo\";\r\n\r\nimport Agent from \"agent-base\";\r\n\r\n// @ts-ignore\r\nimport Cache from \"async-disk-cache\";\r\nimport HttpsProxyAgent from \"https-proxy-agent\";\r\nimport * as net from \"net\";\r\nimport { OCSPCacheUpdateErrorEvent } from \"../common/OCSPEvents\";\r\n\r\nexport class CertCheckAgent {\r\n\r\n // Test hook to enable forcing expiration / refresh to happen.\r\n public static testTimeOffset: number = 0;\r\n\r\n // Test hook to disable stapling for cache testing.\r\n public static forceDisableOCSPStapling: boolean = false;\r\n\r\n // An in memory cache for recived responses.\r\n private static privMemCache: IStringDictionary = {};\r\n\r\n // The on disk cache.\r\n private static privDiskCache: Cache;\r\n\r\n private privProxyInfo: ProxyInfo;\r\n\r\n constructor(proxyInfo?: ProxyInfo) {\r\n if (!!proxyInfo) {\r\n this.privProxyInfo = proxyInfo;\r\n }\r\n\r\n // Initialize this here to allow tests to set the env variable before the cache is constructed.\r\n if (!CertCheckAgent.privDiskCache) {\r\n CertCheckAgent.privDiskCache = new Cache(\"microsoft-cognitiveservices-speech-sdk-cache\", { supportBuffer: true, location: (typeof process !== \"undefined\" && !!process.env.SPEECH_OCSP_CACHE_ROOT) ? process.env.SPEECH_OCSP_CACHE_ROOT : undefined });\r\n }\r\n }\r\n\r\n // Test hook to force the disk cache to be recreated.\r\n public static forceReinitDiskCache(): void {\r\n CertCheckAgent.privDiskCache = undefined;\r\n CertCheckAgent.privMemCache = {};\r\n }\r\n\r\n public GetAgent(disableStapling?: boolean): http.Agent {\r\n const agent: any = new Agent.Agent(this.CreateConnection);\r\n\r\n if (this.privProxyInfo !== undefined &&\r\n this.privProxyInfo.HostName !== undefined &&\r\n this.privProxyInfo.Port > 0) {\r\n const proxyName: string = \"privProxyInfo\";\r\n agent[proxyName] = this.privProxyInfo;\r\n }\r\n\r\n return agent;\r\n }\r\n\r\n private static GetProxyAgent(proxyInfo: ProxyInfo): HttpsProxyAgent {\r\n const httpProxyOptions: HttpsProxyAgent.HttpsProxyAgentOptions = {\r\n host: proxyInfo.HostName,\r\n port: proxyInfo.Port,\r\n };\r\n\r\n if (!!proxyInfo.UserName) {\r\n httpProxyOptions.headers = {\r\n \"Proxy-Authentication\": \"Basic \" + new Buffer(proxyInfo.UserName + \":\" + (proxyInfo.Password === undefined) ? \"\" : proxyInfo.Password).toString(\"base64\"),\r\n };\r\n } else {\r\n httpProxyOptions.headers = {};\r\n }\r\n\r\n httpProxyOptions.headers.requestOCSP = \"true\";\r\n\r\n const httpProxyAgent: HttpsProxyAgent = new HttpsProxyAgent(httpProxyOptions);\r\n return httpProxyAgent;\r\n }\r\n\r\n private static async OCSPCheck(socketPromise: Promise, proxyInfo: ProxyInfo): Promise {\r\n let ocspRequest: ocsp.Request;\r\n let stapling: Buffer;\r\n let resolved: boolean = false;\r\n\r\n const socket: net.Socket = await socketPromise;\r\n socket.cork();\r\n\r\n const tlsSocket: tls.TLSSocket = socket as tls.TLSSocket;\r\n\r\n return new Promise((resolve: (value: net.Socket) => void, reject: (error: string | Error) => void) => {\r\n socket.on(\"OCSPResponse\", (data: Buffer): void => {\r\n if (!!data) {\r\n this.onEvent(new OCSPStapleReceivedEvent());\r\n stapling = data;\r\n }\r\n });\r\n\r\n socket.on(\"error\", (error: Error) => {\r\n if (!resolved) {\r\n resolved = true;\r\n socket.destroy();\r\n reject(error);\r\n }\r\n });\r\n\r\n tlsSocket.on(\"secure\", async () => {\r\n const peer: tls.DetailedPeerCertificate = tlsSocket.getPeerCertificate(true);\r\n try {\r\n const issuer: tls.DetailedPeerCertificate = await this.GetIssuer(peer);\r\n\r\n // We always need a request to verify the response.\r\n ocspRequest = ocsp.request.generate(peer.raw, issuer.raw);\r\n\r\n // Do we have a result for this certificate in our memory cache?\r\n const sig: string = ocspRequest.id.toString(\"hex\");\r\n\r\n // Stapled response trumps cached response.\r\n if (!stapling) {\r\n const cacheEntry: Buffer = await CertCheckAgent.GetResponseFromCache(sig, ocspRequest, proxyInfo);\r\n stapling = cacheEntry;\r\n }\r\n\r\n await this.VerifyOCSPResponse(stapling, ocspRequest, proxyInfo);\r\n\r\n socket.uncork();\r\n resolved = true;\r\n resolve(socket);\r\n } catch (e) {\r\n socket.destroy();\r\n resolved = true;\r\n reject(e);\r\n }\r\n });\r\n });\r\n }\r\n\r\n private static GetIssuer(peer: tls.DetailedPeerCertificate): Promise {\r\n if (peer.issuerCertificate) {\r\n return Promise.resolve(peer.issuerCertificate);\r\n }\r\n\r\n return new Promise((resolve: (value: tls.DetailedPeerCertificate) => void, reject: (reason: string) => void) => {\r\n const ocspAgent: ocsp.Agent = new ocsp.Agent({});\r\n ocspAgent.fetchIssuer(peer, null, (error: string, value: tls.DetailedPeerCertificate): void => {\r\n if (!!error) {\r\n reject(error);\r\n return;\r\n }\r\n\r\n resolve(value);\r\n });\r\n });\r\n }\r\n\r\n private static async GetResponseFromCache(signature: string, ocspRequest: ocsp.Request, proxyInfo: ProxyInfo): Promise {\r\n let cachedResponse: Buffer = CertCheckAgent.privMemCache[signature];\r\n\r\n if (!!cachedResponse) {\r\n this.onEvent(new OCSPMemoryCacheHitEvent(signature));\r\n }\r\n\r\n // Do we have a result for this certificate on disk in %TMP%?\r\n if (!cachedResponse) {\r\n try {\r\n const diskCacheResponse: any = await CertCheckAgent.privDiskCache.get(signature);\r\n if (!!diskCacheResponse.isCached) {\r\n CertCheckAgent.onEvent(new OCSPDiskCacheHitEvent(signature));\r\n CertCheckAgent.StoreMemoryCacheEntry(signature, diskCacheResponse.value);\r\n cachedResponse = diskCacheResponse.value;\r\n }\r\n } catch (error) {\r\n cachedResponse = null;\r\n }\r\n }\r\n\r\n if (!cachedResponse) {\r\n return cachedResponse;\r\n }\r\n\r\n try {\r\n const cachedOcspResponse: ocsp.Response = ocsp.utils.parseResponse(cachedResponse);\r\n const tbsData = cachedOcspResponse.value.tbsResponseData;\r\n if (tbsData.responses.length < 1) {\r\n this.onEvent(new OCSPCacheFetchErrorEvent(signature, \"Not enough data in cached response\"));\r\n return;\r\n }\r\n\r\n const cachedStartTime: number = tbsData.responses[0].thisUpdate;\r\n const cachedNextTime: number = tbsData.responses[0].nextUpdate;\r\n\r\n if (cachedNextTime < (Date.now() + this.testTimeOffset - 60000)) {\r\n // Cached entry has expired.\r\n this.onEvent(new OCSPCacheEntryExpiredEvent(signature, cachedNextTime));\r\n cachedResponse = null;\r\n } else {\r\n // If we're within one day of the next update, or 50% of the way through the validity period,\r\n // background an update to the cache.\r\n\r\n const minUpdate: number = Math.min(24 * 60 * 60 * 1000, (cachedNextTime - cachedStartTime) / 2);\r\n\r\n if ((cachedNextTime - (Date.now() + this.testTimeOffset)) < minUpdate) {\r\n this.onEvent(new OCSPCacheEntryNeedsRefreshEvent(signature, cachedStartTime, cachedNextTime));\r\n this.UpdateCache(ocspRequest, proxyInfo).catch((error: string) => {\r\n // Well, not much we can do here.\r\n this.onEvent(new OCSPCacheUpdateErrorEvent(signature, error.toString()));\r\n });\r\n } else {\r\n this.onEvent(new OCSPCacheHitEvent(signature, cachedStartTime, cachedNextTime));\r\n }\r\n }\r\n } catch (error) {\r\n this.onEvent(new OCSPCacheFetchErrorEvent(signature, error));\r\n cachedResponse = null;\r\n }\r\n if (!cachedResponse) {\r\n this.onEvent(new OCSPCacheMissEvent(signature));\r\n }\r\n return cachedResponse;\r\n }\r\n\r\n private static async VerifyOCSPResponse(cacheValue: Buffer, ocspRequest: ocsp.Request, proxyInfo: ProxyInfo): Promise {\r\n let ocspResponse: Buffer = cacheValue;\r\n const sig: string = ocspRequest.certID.toString(\"hex\");\r\n\r\n // Do we have a valid response?\r\n if (!ocspResponse) {\r\n ocspResponse = await CertCheckAgent.GetOCSPResponse(ocspRequest, proxyInfo);\r\n }\r\n\r\n return new Promise((resolve: () => void, reject: (error: string | Error) => void) => {\r\n ocsp.verify({ request: ocspRequest, response: ocspResponse }, (error: string, result: any): void => {\r\n if (!!error) {\r\n CertCheckAgent.onEvent(new OCSPVerificationFailedEvent(ocspRequest.id.toString(\"hex\"), error));\r\n\r\n // Bad Cached Value? One more try without the cache.\r\n if (!!cacheValue) {\r\n this.VerifyOCSPResponse(null, ocspRequest, proxyInfo).then(() => {\r\n resolve();\r\n }, (error: Error) => {\r\n reject(error);\r\n });\r\n } else {\r\n reject(error);\r\n }\r\n } else {\r\n if (!cacheValue) {\r\n CertCheckAgent.StoreCacheEntry(ocspRequest.id.toString(\"hex\"), ocspResponse);\r\n }\r\n resolve();\r\n }\r\n });\r\n });\r\n }\r\n\r\n private static async UpdateCache(req: ocsp.Request, proxyInfo: ProxyInfo): Promise {\r\n const signature: string = req.id.toString(\"hex\");\r\n this.onEvent(new OCSPCacheUpdateNeededEvent(signature));\r\n\r\n const rawResponse: Buffer = await this.GetOCSPResponse(req, proxyInfo);\r\n this.StoreCacheEntry(signature, rawResponse);\r\n this.onEvent(new OCSPCacheUpdatehCompleteEvent(req.id.toString(\"hex\")));\r\n\r\n }\r\n\r\n private static StoreCacheEntry(sig: string, rawResponse: Buffer): void {\r\n this.StoreMemoryCacheEntry(sig, rawResponse);\r\n this.StoreDiskCacheEntry(sig, rawResponse);\r\n }\r\n\r\n private static StoreMemoryCacheEntry(sig: string, rawResponse: Buffer): void {\r\n this.privMemCache[sig] = rawResponse;\r\n this.onEvent(new OCSPMemoryCacheStoreEvent(sig));\r\n }\r\n\r\n private static StoreDiskCacheEntry(sig: string, rawResponse: Buffer): void {\r\n this.privDiskCache.set(sig, rawResponse).then(() => {\r\n this.onEvent(new OCSPDiskCacheStoreEvent(sig));\r\n });\r\n }\r\n\r\n private static GetOCSPResponse(req: ocsp.Request, proxyInfo: ProxyInfo): Promise {\r\n\r\n const ocspMethod: string = \"1.3.6.1.5.5.7.48.1\";\r\n let options: http.RequestOptions = {};\r\n\r\n if (!!proxyInfo) {\r\n const agent: HttpsProxyAgent = CertCheckAgent.GetProxyAgent(proxyInfo);\r\n options.agent = agent;\r\n }\r\n\r\n return new Promise((resolve: (value: Buffer) => void, reject: (error: string | Error) => void) => {\r\n ocsp.utils.getAuthorityInfo(req.cert, ocspMethod, (error: string, uri: string): void => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n }\r\n\r\n const parsedUri: {[k: string]: any} = parse.default(uri);\r\n parsedUri.path = parsedUri.pathname;\r\n options = { ...options, ...parsedUri };\r\n\r\n ocsp.utils.getResponse(options, req.data, (error: string, raw: Buffer): void => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n }\r\n\r\n this.onEvent(new OCSPResponseRetrievedEvent(req.certID.toString(\"hex\")));\r\n resolve(raw);\r\n });\r\n });\r\n });\r\n }\r\n\r\n private static onEvent = (event: OCSPEvent): void => {\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private CreateConnection(request: Agent.ClientRequest, options: Agent.RequestOptions): Promise {\r\n const enableOCSP: boolean = (typeof process !== \"undefined\" && process.env.NODE_TLS_REJECT_UNAUTHORIZED !== \"0\" && process.env.SPEECH_CONDUCT_OCSP_CHECK !== \"0\") && options.secureEndpoint;\r\n let socketPromise: Promise;\r\n\r\n options = {\r\n ...options,\r\n ...{\r\n requestOCSP: !CertCheckAgent.forceDisableOCSPStapling,\r\n servername: options.host\r\n }\r\n };\r\n\r\n if (!!this.privProxyInfo) {\r\n const httpProxyAgent: HttpsProxyAgent = CertCheckAgent.GetProxyAgent(this.privProxyInfo);\r\n const baseAgent: Agent.Agent = httpProxyAgent as unknown as Agent.Agent;\r\n\r\n socketPromise = new Promise((resolve: (value: net.Socket) => void, reject: (error: string | Error) => void) => {\r\n baseAgent.callback(request, options, (error: Error, socket: net.Socket) => {\r\n if (!!error) {\r\n reject(error);\r\n } else {\r\n resolve(socket);\r\n }\r\n });\r\n });\r\n } else {\r\n if (!!options.secureEndpoint) {\r\n socketPromise = Promise.resolve(tls.connect(options));\r\n } else {\r\n socketPromise = Promise.resolve(net.connect(options));\r\n }\r\n }\r\n\r\n if (!!enableOCSP) {\r\n return CertCheckAgent.OCSPCheck(socketPromise, this.privProxyInfo);\r\n } else {\r\n return socketPromise;\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { EventType, IEventListener, PlatformEvent } from \"../common/Exports\";\r\n\r\nexport class ConsoleLoggingListener implements IEventListener {\r\n private privLogLevelFilter: EventType;\r\n\r\n public constructor(logLevelFilter: EventType = EventType.Warning) {\r\n this.privLogLevelFilter = logLevelFilter;\r\n }\r\n\r\n public onEvent = (event: PlatformEvent): void => {\r\n if (event.eventType >= this.privLogLevelFilter) {\r\n const log = this.toString(event);\r\n\r\n switch (event.eventType) {\r\n case EventType.Debug:\r\n // tslint:disable-next-line:no-console\r\n console.debug(log);\r\n break;\r\n case EventType.Info:\r\n // tslint:disable-next-line:no-console\r\n console.info(log);\r\n break;\r\n case EventType.Warning:\r\n // tslint:disable-next-line:no-console\r\n console.warn(log);\r\n break;\r\n case EventType.Error:\r\n // tslint:disable-next-line:no-console\r\n console.error(log);\r\n break;\r\n default:\r\n // tslint:disable-next-line:no-console\r\n console.log(log);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n private toString = (event: any): string => {\r\n const logFragments = [\r\n `${event.EventTime}`,\r\n `${event.Name}`,\r\n ];\r\n\r\n for (const prop in event) {\r\n if (prop && event.hasOwnProperty(prop) &&\r\n prop !== \"eventTime\" && prop !== \"eventType\" &&\r\n prop !== \"eventId\" && prop !== \"name\" &&\r\n prop !== \"constructor\") {\r\n const value = event[prop];\r\n let valueToLog = \"\";\r\n if (value !== undefined && value !== null) {\r\n if (typeof (value) === \"number\" || typeof (value) === \"string\") {\r\n valueToLog = value.toString();\r\n } else {\r\n valueToLog = JSON.stringify(value);\r\n }\r\n }\r\n\r\n logFragments.push(`${prop}: ${valueToLog}`);\r\n }\r\n\r\n }\r\n\r\n return logFragments.join(\" | \");\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport * from \"./ConsoleLoggingListener\";\r\nexport * from \"./IRecorder\";\r\nexport * from \"./MicAudioSource\";\r\nexport * from \"./FileAudioSource\";\r\nexport * from \"./PCMRecorder\";\r\nexport * from \"./WebsocketConnection\";\r\nexport * from \"./WebsocketMessageAdapter\";\r\nexport * from \"./ReplayableAudioNode\";\r\nexport * from \"./ProxyInfo\";\r\nexport * from \"./RestMessageAdapter\";\r\nexport * from \"./RestConfigBase\";\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n connectivity,\r\n ISpeechConfigAudioDevice,\r\n type,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n AudioSourceErrorEvent,\r\n AudioSourceEvent,\r\n AudioSourceInitializingEvent,\r\n AudioSourceOffEvent,\r\n AudioSourceReadyEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n AudioStreamNodeErrorEvent,\r\n ChunkedArrayBufferStream,\r\n createNoDashGuid,\r\n Deferred,\r\n Events,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IStreamChunk,\r\n IStringDictionary,\r\n Stream,\r\n} from \"../common/Exports\";\r\nimport { AudioStreamFormat, AudioStreamFormatImpl } from \"../sdk/Audio/AudioStreamFormat\";\r\n\r\nexport class FileAudioSource implements IAudioSource {\r\n\r\n private privAudioFormatPromise: Promise;\r\n\r\n private privStreams: IStringDictionary> = {};\r\n\r\n private privId: string;\r\n\r\n private privEvents: EventSource;\r\n\r\n private privSource: Blob | Buffer;\r\n\r\n private privFilename: string;\r\n\r\n private privHeaderEnd: number = 44;\r\n\r\n public constructor(file: File | Buffer, filename?: string, audioSourceId?: string) {\r\n this.privId = audioSourceId ? audioSourceId : createNoDashGuid();\r\n this.privEvents = new EventSource();\r\n this.privSource = file;\r\n if (typeof window !== \"undefined\" && typeof Blob !== \"undefined\" && this.privSource instanceof Blob) {\r\n this.privFilename = (file as File).name;\r\n } else {\r\n this.privFilename = filename || \"unknown.wav\";\r\n }\r\n\r\n // Read the header.\r\n this.privAudioFormatPromise = this.readHeader();\r\n }\r\n\r\n public get format(): Promise {\r\n return this.privAudioFormatPromise;\r\n }\r\n\r\n public get blob(): Promise {\r\n return Promise.resolve(this.privSource);\r\n }\r\n\r\n public turnOn = (): Promise => {\r\n if (this.privFilename.lastIndexOf(\".wav\") !== this.privFilename.length - 4) {\r\n const errorMsg = this.privFilename + \" is not supported. Only WAVE files are allowed at the moment.\";\r\n this.onEvent(new AudioSourceErrorEvent(errorMsg, \"\"));\r\n return Promise.reject(errorMsg);\r\n }\r\n\r\n this.onEvent(new AudioSourceInitializingEvent(this.privId)); // no stream id\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n return;\r\n }\r\n\r\n public id = (): string => {\r\n return this.privId;\r\n }\r\n\r\n public attach = async (audioNodeId: string): Promise => {\r\n this.onEvent(new AudioStreamNodeAttachingEvent(this.privId, audioNodeId));\r\n\r\n const stream: Stream = await this.upload(audioNodeId);\r\n\r\n this.onEvent(new AudioStreamNodeAttachedEvent(this.privId, audioNodeId));\r\n return Promise.resolve({\r\n detach: async (): Promise => {\r\n stream.readEnded();\r\n delete this.privStreams[audioNodeId];\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n await this.turnOff();\r\n },\r\n id: () => {\r\n return audioNodeId;\r\n },\r\n read: (): Promise> => {\r\n return stream.read();\r\n },\r\n });\r\n }\r\n\r\n public detach = (audioNodeId: string): void => {\r\n if (audioNodeId && this.privStreams[audioNodeId]) {\r\n this.privStreams[audioNodeId].close();\r\n delete this.privStreams[audioNodeId];\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n }\r\n }\r\n\r\n public turnOff = (): Promise => {\r\n for (const streamId in this.privStreams) {\r\n if (streamId) {\r\n const stream = this.privStreams[streamId];\r\n if (stream && !stream.isClosed) {\r\n stream.close();\r\n }\r\n }\r\n }\r\n\r\n this.onEvent(new AudioSourceOffEvent(this.privId)); // no stream now\r\n return Promise.resolve();\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privEvents;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return this.privAudioFormatPromise.then((result: AudioStreamFormatImpl) => {\r\n return Promise.resolve({\r\n bitspersample: result.bitsPerSample,\r\n channelcount: result.channels,\r\n connectivity: connectivity.Unknown,\r\n manufacturer: \"Speech SDK\",\r\n model: \"File\",\r\n samplerate: result.samplesPerSec,\r\n type: type.File,\r\n });\r\n });\r\n }\r\n\r\n private readHeader(): Promise {\r\n // Read the wave header.\r\n const maxHeaderSize: number = 512;\r\n const header: Blob | Buffer = this.privSource.slice(0, maxHeaderSize);\r\n\r\n const headerResult: Deferred = new Deferred();\r\n\r\n const processHeader = (header: ArrayBuffer): void => {\r\n const view: DataView = new DataView(header);\r\n\r\n const getWord = (index: number): string => {\r\n return String.fromCharCode(view.getUint8(index), view.getUint8(index + 1), view.getUint8(index + 2), view.getUint8(index + 3));\r\n };\r\n\r\n // RIFF 4 bytes.\r\n if (\"RIFF\" !== getWord(0)) {\r\n headerResult.reject(\"Invalid WAV header in file, RIFF was not found\");\r\n return;\r\n }\r\n\r\n // length, 4 bytes\r\n // RIFF Type & fmt 8 bytes\r\n if (\"WAVE\" !== getWord(8) || \"fmt \" !== getWord(12)) {\r\n headerResult.reject(\"Invalid WAV header in file, WAVEfmt was not found\");\r\n return;\r\n }\r\n\r\n const formatSize: number = view.getInt32(16, true);\r\n const channelCount: number = view.getUint16(22, true);\r\n const sampleRate: number = view.getUint32(24, true);\r\n const bitsPerSample: number = view.getUint16(34, true);\r\n // Confirm if header is 44 bytes long.\r\n let pos: number = 36 + Math.max(formatSize - 16, 0);\r\n for (; getWord(pos) !== \"data\"; pos += 2) {\r\n if (pos > maxHeaderSize - 8) {\r\n headerResult.reject(\"Invalid WAV header in file, data block was not found\");\r\n return;\r\n }\r\n }\r\n this.privHeaderEnd = pos + 8;\r\n headerResult.resolve(AudioStreamFormat.getWaveFormatPCM(sampleRate, bitsPerSample, channelCount) as AudioStreamFormatImpl);\r\n };\r\n\r\n if (typeof window !== \"undefined\" && typeof Blob !== \"undefined\" && header instanceof Blob) {\r\n const reader: FileReader = new FileReader();\r\n\r\n reader.onload = (event: Event) => {\r\n const header: ArrayBuffer = (event.target as FileReader).result as ArrayBuffer;\r\n processHeader(header);\r\n };\r\n\r\n reader.readAsArrayBuffer(header);\r\n } else {\r\n const h: Buffer = header as Buffer;\r\n processHeader(h.buffer.slice(h.byteOffset, h.byteOffset + h.byteLength));\r\n }\r\n return headerResult.promise;\r\n }\r\n\r\n private async upload(audioNodeId: string): Promise> {\r\n const onerror = (error: string) => {\r\n const errorMsg = `Error occurred while processing '${this.privFilename}'. ${error}`;\r\n this.onEvent(new AudioStreamNodeErrorEvent(this.privId, audioNodeId, errorMsg));\r\n throw new Error(errorMsg);\r\n };\r\n\r\n try {\r\n await this.turnOn();\r\n\r\n const format: AudioStreamFormatImpl = await this.privAudioFormatPromise;\r\n const stream = new ChunkedArrayBufferStream(format.avgBytesPerSec / 10, audioNodeId);\r\n\r\n this.privStreams[audioNodeId] = stream;\r\n const chunk: Blob | Buffer = this.privSource.slice(this.privHeaderEnd);\r\n\r\n const processFile = (buff: ArrayBuffer): void => {\r\n if (stream.isClosed) {\r\n return; // output stream was closed (somebody called TurnOff). We're done here.\r\n }\r\n\r\n stream.writeStreamChunk({\r\n buffer: buff,\r\n isEnd: false,\r\n timeReceived: Date.now(),\r\n });\r\n stream.close();\r\n };\r\n\r\n if (typeof window !== \"undefined\" && typeof Blob !== \"undefined\" && chunk instanceof Blob) {\r\n const reader: FileReader = new FileReader();\r\n reader.onerror = (ev: ProgressEvent) => { onerror(ev.toString()); };\r\n\r\n reader.onload = (event: Event) => {\r\n const fileBuffer: ArrayBuffer = (event.target as FileReader).result as ArrayBuffer;\r\n processFile(fileBuffer);\r\n };\r\n\r\n reader.readAsArrayBuffer(chunk);\r\n } else {\r\n const c: Buffer = chunk as Buffer;\r\n processFile(c.buffer.slice(c.byteOffset, c.byteOffset + c.byteLength));\r\n }\r\n\r\n return stream;\r\n } catch (e) {\r\n onerror(e);\r\n }\r\n }\r\n\r\n private onEvent = (event: AudioSourceEvent): void => {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n connectivity,\r\n ISpeechConfigAudioDevice,\r\n type\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n AudioSourceErrorEvent,\r\n AudioSourceEvent,\r\n AudioSourceInitializingEvent,\r\n AudioSourceOffEvent,\r\n AudioSourceReadyEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n AudioStreamNodeErrorEvent,\r\n ChunkedArrayBufferStream,\r\n createNoDashGuid,\r\n Deferred,\r\n Events,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IStringDictionary,\r\n Stream,\r\n} from \"../common/Exports\";\r\nimport {\r\n AudioStreamFormat,\r\n AudioStreamFormatImpl,\r\n} from \"../sdk/Audio/AudioStreamFormat\";\r\nimport { IRecorder } from \"./IRecorder\";\r\n\r\n// Extending the default definition with browser specific definitions for backward compatibility\r\ninterface INavigator extends Navigator {\r\n webkitGetUserMedia?: (constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback) => void;\r\n mozGetUserMedia?: (constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback) => void;\r\n msGetUserMedia?: (constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback) => void;\r\n}\r\n\r\nexport const AudioWorkletSourceURLPropertyName = \"MICROPHONE-WorkletSourceUrl\";\r\n\r\nexport class MicAudioSource implements IAudioSource {\r\n\r\n private static readonly AUDIOFORMAT: AudioStreamFormatImpl = AudioStreamFormat.getDefaultInputFormat() as AudioStreamFormatImpl;\r\n\r\n private privStreams: IStringDictionary> = {};\r\n\r\n private privId: string;\r\n\r\n private privEvents: EventSource;\r\n\r\n private privInitializeDeferral: Deferred;\r\n\r\n private privMediaStream: MediaStream;\r\n\r\n private privContext: AudioContext;\r\n\r\n private privMicrophoneLabel: string;\r\n\r\n private privOutputChunkSize: number;\r\n\r\n public constructor(\r\n private readonly privRecorder: IRecorder,\r\n private readonly deviceId?: string,\r\n audioSourceId?: string,\r\n mediaStream?: MediaStream\r\n ) {\r\n\r\n this.privOutputChunkSize = MicAudioSource.AUDIOFORMAT.avgBytesPerSec / 10;\r\n this.privId = audioSourceId ? audioSourceId : createNoDashGuid();\r\n this.privEvents = new EventSource();\r\n this.privMediaStream = mediaStream || null;\r\n }\r\n\r\n public get format(): Promise {\r\n return Promise.resolve(MicAudioSource.AUDIOFORMAT);\r\n }\r\n\r\n public get blob(): Promise {\r\n return Promise.reject(\"Not implemented for Mic input\");\r\n }\r\n\r\n public turnOn = (): Promise => {\r\n if (this.privInitializeDeferral) {\r\n return this.privInitializeDeferral.promise;\r\n }\r\n\r\n this.privInitializeDeferral = new Deferred();\r\n\r\n try {\r\n this.createAudioContext();\r\n } catch (error) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n this.privInitializeDeferral.reject(typedError.name + \": \" + typedError.message);\r\n } else {\r\n this.privInitializeDeferral.reject(error);\r\n }\r\n return this.privInitializeDeferral.promise;\r\n }\r\n\r\n const nav = window.navigator as INavigator;\r\n\r\n let getUserMedia = (\r\n nav.getUserMedia ||\r\n nav.webkitGetUserMedia ||\r\n nav.mozGetUserMedia ||\r\n nav.msGetUserMedia\r\n );\r\n\r\n if (!!nav.mediaDevices) {\r\n getUserMedia = (constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void => {\r\n nav.mediaDevices\r\n .getUserMedia(constraints)\r\n .then(successCallback)\r\n .catch(errorCallback);\r\n };\r\n }\r\n\r\n if (!getUserMedia) {\r\n const errorMsg = \"Browser does not support getUserMedia.\";\r\n this.privInitializeDeferral.reject(errorMsg);\r\n this.onEvent(new AudioSourceErrorEvent(errorMsg, \"\")); // mic initialized error - no streamid at this point\r\n } else {\r\n const next = () => {\r\n this.onEvent(new AudioSourceInitializingEvent(this.privId)); // no stream id\r\n if (this.privMediaStream && this.privMediaStream.active) {\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n this.privInitializeDeferral.resolve();\r\n } else {\r\n getUserMedia(\r\n { audio: this.deviceId ? { deviceId: this.deviceId } : true, video: false },\r\n (mediaStream: MediaStream) => {\r\n this.privMediaStream = mediaStream;\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n this.privInitializeDeferral.resolve();\r\n }, (error: MediaStreamError) => {\r\n const errorMsg = `Error occurred during microphone initialization: ${error}`;\r\n this.privInitializeDeferral.reject(errorMsg);\r\n this.onEvent(new AudioSourceErrorEvent(this.privId, errorMsg));\r\n });\r\n }\r\n };\r\n\r\n if (this.privContext.state === \"suspended\") {\r\n // NOTE: On iOS, the Web Audio API requires sounds to be triggered from an explicit user action.\r\n // https://github.com/WebAudio/web-audio-api/issues/790\r\n this.privContext.resume()\r\n .then(next)\r\n .catch((reason: any) => {\r\n this.privInitializeDeferral.reject(`Failed to initialize audio context: ${reason}`);\r\n });\r\n } else {\r\n next();\r\n }\r\n }\r\n\r\n return this.privInitializeDeferral.promise;\r\n }\r\n\r\n public id = (): string => {\r\n return this.privId;\r\n }\r\n\r\n public attach = (audioNodeId: string): Promise => {\r\n this.onEvent(new AudioStreamNodeAttachingEvent(this.privId, audioNodeId));\r\n\r\n return this.listen(audioNodeId).then(\r\n (stream: Stream) => {\r\n this.onEvent(new AudioStreamNodeAttachedEvent(this.privId, audioNodeId));\r\n return {\r\n detach: async () => {\r\n stream.readEnded();\r\n delete this.privStreams[audioNodeId];\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n return this.turnOff();\r\n },\r\n id: () => {\r\n return audioNodeId;\r\n },\r\n read: () => {\r\n return stream.read();\r\n },\r\n };\r\n });\r\n }\r\n\r\n public detach = (audioNodeId: string): void => {\r\n if (audioNodeId && this.privStreams[audioNodeId]) {\r\n this.privStreams[audioNodeId].close();\r\n delete this.privStreams[audioNodeId];\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n }\r\n }\r\n\r\n public async turnOff(): Promise {\r\n for (const streamId in this.privStreams) {\r\n if (streamId) {\r\n const stream = this.privStreams[streamId];\r\n if (stream) {\r\n stream.close();\r\n }\r\n }\r\n }\r\n\r\n this.onEvent(new AudioSourceOffEvent(this.privId)); // no stream now\r\n if (this.privInitializeDeferral) {\r\n // Correctly handle when browser forces mic off before turnOn() completes\r\n await this.privInitializeDeferral;\r\n this.privInitializeDeferral = null;\r\n }\r\n\r\n await this.destroyAudioContext();\r\n\r\n return;\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privEvents;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return this.getMicrophoneLabel().then((label: string) => {\r\n return {\r\n bitspersample: MicAudioSource.AUDIOFORMAT.bitsPerSample,\r\n channelcount: MicAudioSource.AUDIOFORMAT.channels,\r\n connectivity: connectivity.Unknown,\r\n manufacturer: \"Speech SDK\",\r\n model: label,\r\n samplerate: MicAudioSource.AUDIOFORMAT.samplesPerSec,\r\n type: type.Microphones,\r\n };\r\n });\r\n }\r\n\r\n public setProperty(name: string, value: string): void {\r\n if (name === AudioWorkletSourceURLPropertyName) {\r\n this.privRecorder.setWorkletUrl(value);\r\n } else {\r\n throw new Error(\"Property '\" + name + \"' is not supported on Microphone.\");\r\n }\r\n }\r\n\r\n private getMicrophoneLabel(): Promise {\r\n const defaultMicrophoneName: string = \"microphone\";\r\n\r\n // If we did this already, return the value.\r\n if (this.privMicrophoneLabel !== undefined) {\r\n return Promise.resolve(this.privMicrophoneLabel);\r\n }\r\n\r\n // If the stream isn't currently running, we can't query devices because security.\r\n if (this.privMediaStream === undefined || !this.privMediaStream.active) {\r\n return Promise.resolve(defaultMicrophoneName);\r\n }\r\n\r\n // Setup a default\r\n this.privMicrophoneLabel = defaultMicrophoneName;\r\n\r\n // Get the id of the device running the audio track.\r\n const microphoneDeviceId: string = this.privMediaStream.getTracks()[0].getSettings().deviceId;\r\n\r\n // If the browser doesn't support getting the device ID, set a default and return.\r\n if (undefined === microphoneDeviceId) {\r\n return Promise.resolve(this.privMicrophoneLabel);\r\n }\r\n\r\n const deferred: Deferred = new Deferred();\r\n\r\n // Enumerate the media devices.\r\n navigator.mediaDevices.enumerateDevices().then((devices: MediaDeviceInfo[]) => {\r\n for (const device of devices) {\r\n if (device.deviceId === microphoneDeviceId) {\r\n // Found the device\r\n this.privMicrophoneLabel = device.label;\r\n break;\r\n }\r\n }\r\n deferred.resolve(this.privMicrophoneLabel);\r\n }, () => deferred.resolve(this.privMicrophoneLabel));\r\n\r\n return deferred.promise;\r\n }\r\n\r\n private listen = async (audioNodeId: string): Promise> => {\r\n await this.turnOn();\r\n const stream = new ChunkedArrayBufferStream(this.privOutputChunkSize, audioNodeId);\r\n this.privStreams[audioNodeId] = stream;\r\n try {\r\n this.privRecorder.record(this.privContext, this.privMediaStream, stream);\r\n } catch (error) {\r\n this.onEvent(new AudioStreamNodeErrorEvent(this.privId, audioNodeId, error));\r\n throw error;\r\n }\r\n const result: Stream = stream;\r\n return result;\r\n }\r\n\r\n private onEvent = (event: AudioSourceEvent): void => {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private createAudioContext = (): void => {\r\n if (!!this.privContext) {\r\n return;\r\n }\r\n\r\n this.privContext = AudioStreamFormatImpl.getAudioContext(MicAudioSource.AUDIOFORMAT.samplesPerSec);\r\n }\r\n\r\n private async destroyAudioContext(): Promise {\r\n if (!this.privContext) {\r\n return;\r\n }\r\n\r\n this.privRecorder.releaseMediaResources(this.privContext);\r\n\r\n // This pattern brought to you by a bug in the TypeScript compiler where it\r\n // confuses the (\"close\" in this.privContext) with this.privContext always being null as the alternate.\r\n // https://github.com/Microsoft/TypeScript/issues/11498\r\n let hasClose: boolean = false;\r\n if (\"close\" in this.privContext) {\r\n hasClose = true;\r\n }\r\n\r\n if (hasClose) {\r\n await this.privContext.close();\r\n this.privContext = null;\r\n } else if (null !== this.privContext && this.privContext.state === \"running\") {\r\n // Suspend actually takes a callback, but analogous to the\r\n // resume method, it'll be only fired if suspend is called\r\n // in a direct response to a user action. The later is not always\r\n // the case, as TurnOff is also called, when we receive an\r\n // end-of-speech message from the service. So, doing a best effort\r\n // fire-and-forget here.\r\n await this.privContext.suspend();\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RiffPcmEncoder, Stream } from \"../common/Exports\";\r\nimport { IRecorder } from \"./IRecorder\";\r\n\r\nexport class PcmRecorder implements IRecorder {\r\n private privMediaResources: IMediaResources;\r\n private privSpeechProcessorScript: string; // speech-processor.js Url\r\n\r\n public record = (context: AudioContext, mediaStream: MediaStream, outputStream: Stream): void => {\r\n const desiredSampleRate = 16000;\r\n\r\n const scriptNode = (() => {\r\n let bufferSize = 0;\r\n try {\r\n return context.createScriptProcessor(bufferSize, 1, 1);\r\n } catch (error) {\r\n // Webkit (<= version 31) requires a valid bufferSize.\r\n bufferSize = 2048;\r\n let audioSampleRate = context.sampleRate;\r\n while (bufferSize < 16384 && audioSampleRate >= (2 * desiredSampleRate)) {\r\n bufferSize <<= 1;\r\n audioSampleRate >>= 1;\r\n }\r\n return context.createScriptProcessor(bufferSize, 1, 1);\r\n }\r\n })();\r\n\r\n const waveStreamEncoder = new RiffPcmEncoder(context.sampleRate, desiredSampleRate);\r\n let needHeader: boolean = true;\r\n const that = this;\r\n scriptNode.onaudioprocess = (event: AudioProcessingEvent) => {\r\n const inputFrame = event.inputBuffer.getChannelData(0);\r\n\r\n if (outputStream && !outputStream.isClosed) {\r\n const waveFrame = waveStreamEncoder.encode(inputFrame);\r\n if (!!waveFrame) {\r\n outputStream.writeStreamChunk({\r\n buffer: waveFrame,\r\n isEnd: false,\r\n timeReceived: Date.now(),\r\n });\r\n needHeader = false;\r\n }\r\n }\r\n };\r\n\r\n const micInput = context.createMediaStreamSource(mediaStream);\r\n\r\n // https://webaudio.github.io/web-audio-api/#audioworklet\r\n // Using AudioWorklet to improve audio quality and avoid audio glitches due to blocking the UI thread\r\n\r\n if (!!this.privSpeechProcessorScript && !!context.audioWorklet) {\r\n context.audioWorklet\r\n .addModule(this.privSpeechProcessorScript)\r\n .then(() => {\r\n const workletNode = new AudioWorkletNode(context, \"speech-processor\");\r\n workletNode.port.onmessage = (ev: MessageEvent) => {\r\n const inputFrame: Float32Array = ev.data as Float32Array;\r\n\r\n if (outputStream && !outputStream.isClosed) {\r\n const waveFrame = waveStreamEncoder.encode(inputFrame);\r\n if (!!waveFrame) {\r\n outputStream.writeStreamChunk({\r\n buffer: waveFrame,\r\n isEnd: false,\r\n timeReceived: Date.now(),\r\n });\r\n needHeader = false;\r\n }\r\n }\r\n };\r\n micInput.connect(workletNode);\r\n workletNode.connect(context.destination);\r\n this.privMediaResources = {\r\n scriptProcessorNode: workletNode,\r\n source: micInput,\r\n stream: mediaStream,\r\n };\r\n })\r\n .catch(() => {\r\n micInput.connect(scriptNode);\r\n scriptNode.connect(context.destination);\r\n this.privMediaResources = {\r\n scriptProcessorNode: scriptNode,\r\n source: micInput,\r\n stream: mediaStream,\r\n };\r\n });\r\n } else {\r\n micInput.connect(scriptNode);\r\n scriptNode.connect(context.destination);\r\n this.privMediaResources = {\r\n scriptProcessorNode: scriptNode,\r\n source: micInput,\r\n stream: mediaStream,\r\n };\r\n }\r\n }\r\n\r\n public releaseMediaResources = (context: AudioContext): void => {\r\n if (this.privMediaResources) {\r\n if (this.privMediaResources.scriptProcessorNode) {\r\n this.privMediaResources.scriptProcessorNode.disconnect(context.destination);\r\n this.privMediaResources.scriptProcessorNode = null;\r\n }\r\n if (this.privMediaResources.source) {\r\n this.privMediaResources.source.disconnect();\r\n this.privMediaResources.stream.getTracks().forEach((track: any) => track.stop());\r\n this.privMediaResources.source = null;\r\n }\r\n }\r\n }\r\n\r\n public setWorkletUrl(url: string): void {\r\n this.privSpeechProcessorScript = url;\r\n }\r\n}\r\n\r\ninterface IMediaResources {\r\n source: MediaStreamAudioSourceNode;\r\n scriptProcessorNode: ScriptProcessorNode | AudioWorkletNode;\r\n stream: MediaStream;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RecognizerConfig } from \"../common.speech/Exports\";\r\nimport { PropertyCollection, PropertyId } from \"../sdk/Exports\";\r\n\r\nexport class ProxyInfo {\r\n private privProxyHostName: string;\r\n private privProxyPort: number;\r\n private privProxyUserName: string;\r\n private privProxyPassword: string;\r\n\r\n private constructor(proxyHostName: string, proxyPort: number, proxyUserName: string, proxyPassword: string) {\r\n this.privProxyHostName = proxyHostName;\r\n this.privProxyPort = proxyPort;\r\n this.privProxyUserName = proxyUserName;\r\n this.privProxyPassword = proxyPassword;\r\n }\r\n\r\n public static fromParameters(parameters: PropertyCollection): ProxyInfo {\r\n return new ProxyInfo(parameters.getProperty(PropertyId.SpeechServiceConnection_ProxyHostName),\r\n parseInt(parameters.getProperty(PropertyId.SpeechServiceConnection_ProxyPort), 10),\r\n parameters.getProperty(PropertyId.SpeechServiceConnection_ProxyUserName),\r\n parameters.getProperty(PropertyId.SpeechServiceConnection_ProxyPassword));\r\n }\r\n\r\n public static fromRecognizerConfig(config: RecognizerConfig): ProxyInfo {\r\n return this.fromParameters(config.parameters);\r\n }\r\n\r\n public get HostName(): string {\r\n return this.privProxyHostName;\r\n }\r\n\r\n public get Port(): number {\r\n return this.privProxyPort;\r\n }\r\n\r\n public get UserName(): string {\r\n return this.privProxyUserName;\r\n }\r\n\r\n public get Password(): string {\r\n return this.privProxyPassword;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { AudioStreamFormatImpl } from \"../../src/sdk/Audio/AudioStreamFormat\";\r\nimport {\r\n IAudioStreamNode,\r\n IStreamChunk,\r\n} from \"../common/Exports\";\r\n\r\nexport class ReplayableAudioNode implements IAudioStreamNode {\r\n private privAudioNode: IAudioStreamNode;\r\n private privBytesPerSecond: number;\r\n private privBuffers: BufferEntry[] = [];\r\n private privReplayOffset: number = 0;\r\n private privLastShrinkOffset: number = 0;\r\n private privBufferStartOffset: number = 0;\r\n private privBufferSerial: number = 0;\r\n private privBufferedBytes: number = 0;\r\n private privReplay: boolean = false;\r\n private privLastChunkAcquiredTime: number = 0;\r\n\r\n public constructor(audioSource: IAudioStreamNode, bytesPerSecond: number) {\r\n this.privAudioNode = audioSource;\r\n this.privBytesPerSecond = bytesPerSecond;\r\n }\r\n\r\n public id = (): string => {\r\n return this.privAudioNode.id();\r\n }\r\n\r\n // Reads and returns the next chunk of audio buffer.\r\n // If replay of existing buffers are needed, read() will first seek and replay\r\n // existing content, and upoin completion it will read new content from the underlying\r\n // audio node, saving that content into the replayable buffers.\r\n public read(): Promise> {\r\n // if there is a replay request to honor.\r\n if (!!this.privReplay && this.privBuffers.length !== 0) {\r\n // Find the start point in the buffers.\r\n // Offsets are in 100ns increments.\r\n // So how many bytes do we need to seek to get the right offset?\r\n const offsetToSeek: number = this.privReplayOffset - this.privBufferStartOffset;\r\n\r\n let bytesToSeek: number = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7);\r\n if (0 !== (bytesToSeek % 2)) {\r\n bytesToSeek++;\r\n }\r\n\r\n let i: number = 0;\r\n\r\n while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) {\r\n bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength;\r\n }\r\n\r\n if (i < this.privBuffers.length) {\r\n const retVal: ArrayBuffer = this.privBuffers[i].chunk.buffer.slice(bytesToSeek);\r\n\r\n this.privReplayOffset += (retVal.byteLength / this.privBytesPerSecond) * 1e+7;\r\n\r\n // If we've reached the end of the buffers, stop replaying.\r\n if (i === this.privBuffers.length - 1) {\r\n this.privReplay = false;\r\n }\r\n\r\n return Promise.resolve>({\r\n buffer: retVal,\r\n isEnd: false,\r\n timeReceived: this.privBuffers[i].chunk.timeReceived,\r\n });\r\n }\r\n }\r\n\r\n return this.privAudioNode.read()\r\n .then((result: IStreamChunk) => {\r\n if (result && result.buffer) {\r\n this.privBuffers.push(new BufferEntry(result, this.privBufferSerial++, this.privBufferedBytes));\r\n this.privBufferedBytes += result.buffer.byteLength;\r\n }\r\n return result;\r\n });\r\n }\r\n\r\n public detach(): Promise {\r\n this.privBuffers = undefined;\r\n return this.privAudioNode.detach();\r\n }\r\n\r\n public replay(): void {\r\n if (this.privBuffers && 0 !== this.privBuffers.length) {\r\n this.privReplay = true;\r\n this.privReplayOffset = this.privLastShrinkOffset;\r\n }\r\n }\r\n\r\n // Shrinks the existing audio buffers to start at the new offset, or at the\r\n // beginning of the buffer closest to the requested offset.\r\n // A replay request will start from the last shrink point.\r\n public shrinkBuffers(offset: number): void {\r\n if (this.privBuffers === undefined || this.privBuffers.length === 0) {\r\n return;\r\n }\r\n\r\n this.privLastShrinkOffset = offset;\r\n\r\n // Find the start point in the buffers.\r\n // Offsets are in 100ns increments.\r\n // So how many bytes do we need to seek to get the right offset?\r\n const offsetToSeek: number = offset - this.privBufferStartOffset;\r\n\r\n let bytesToSeek: number = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7);\r\n\r\n let i: number = 0;\r\n\r\n while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) {\r\n bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength;\r\n }\r\n this.privBufferStartOffset = Math.round(offset - ((bytesToSeek / this.privBytesPerSecond) * 1e+7));\r\n this.privBuffers = this.privBuffers.slice(i);\r\n }\r\n\r\n // Finds the time a buffer of audio was first seen by offset.\r\n public findTimeAtOffset(offset: number): number {\r\n if (offset < this.privBufferStartOffset || this.privBuffers === undefined) {\r\n return 0;\r\n }\r\n\r\n for (const value of this.privBuffers) {\r\n const startOffset: number = (value.byteOffset / this.privBytesPerSecond) * 1e7;\r\n const endOffset: number = startOffset + ((value.chunk.buffer.byteLength / this.privBytesPerSecond) * 1e7);\r\n\r\n if (offset >= startOffset && offset <= endOffset) {\r\n return value.chunk.timeReceived;\r\n }\r\n }\r\n\r\n return 0;\r\n }\r\n}\r\n\r\n// Primary use of this class is to help debugging problems with the replay\r\n// code. If the memory cost of alloc / dealloc gets too much, drop it and just use\r\n// the ArrayBuffer directly.\r\n// tslint:disable-next-line:max-classes-per-file\r\nclass BufferEntry {\r\n public chunk: IStreamChunk;\r\n public serial: number;\r\n public byteOffset: number;\r\n\r\n public constructor(chunk: IStreamChunk, serial: number, byteOffset: number) {\r\n this.chunk = chunk;\r\n this.serial = serial;\r\n this.byteOffset = byteOffset;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IErrorMessages } from \"../common/Exports\";\r\n/**\r\n * HTTP request helper\r\n */\r\nexport interface IRequestOptions {\r\n headers?: {[key: string]: string};\r\n ignoreCache?: boolean;\r\n timeout?: number;\r\n}\r\n\r\nexport interface IRestParams {\r\n apiVersion: string;\r\n authorization: string;\r\n clientAppId: string;\r\n contentTypeKey: string;\r\n correlationId: string;\r\n languageCode: string;\r\n nickname: string;\r\n profanity: string;\r\n requestId: string;\r\n roomId: string;\r\n sessionToken: string;\r\n subscriptionKey: string;\r\n subscriptionRegion: string;\r\n token: string;\r\n}\r\n\r\nexport class RestConfigBase {\r\n\r\n public static get requestOptions(): IRequestOptions {\r\n return RestConfigBase.privDefaultRequestOptions;\r\n }\r\n\r\n public static get configParams(): IRestParams {\r\n return RestConfigBase.privDefaultParams;\r\n }\r\n\r\n public static get restErrors(): IErrorMessages {\r\n return RestConfigBase.privRestErrors;\r\n }\r\n\r\n private static readonly privDefaultRequestOptions: IRequestOptions = {\r\n headers: {\r\n Accept: \"application/json\",\r\n },\r\n ignoreCache: false,\r\n timeout: 10000,\r\n };\r\n\r\n private static readonly privRestErrors: IErrorMessages = {\r\n authInvalidSubscriptionKey: \"You must specify either an authentication token to use, or a Cognitive Speech subscription key.\",\r\n authInvalidSubscriptionRegion: \"You must specify the Cognitive Speech region to use.\",\r\n invalidArgs: \"Required input not found: {arg}.\",\r\n invalidCreateJoinConversationResponse: \"Creating/Joining conversation failed with HTTP {status}.\",\r\n invalidParticipantRequest: \"The requested participant was not found.\",\r\n permissionDeniedConnect: \"Required credentials not found.\",\r\n permissionDeniedConversation: \"Invalid operation: only the host can {command} the conversation.\",\r\n permissionDeniedParticipant: \"Invalid operation: only the host can {command} a participant.\",\r\n permissionDeniedSend: \"Invalid operation: the conversation is not in a connected state.\",\r\n permissionDeniedStart: \"Invalid operation: there is already an active conversation.\",\r\n };\r\n\r\n private static readonly privDefaultParams: IRestParams = {\r\n apiVersion: \"api-version\",\r\n authorization: \"Authorization\",\r\n clientAppId: \"X-ClientAppId\",\r\n contentTypeKey: \"Content-Type\",\r\n correlationId: \"X-CorrelationId\",\r\n languageCode: \"language\",\r\n nickname: \"nickname\",\r\n profanity: \"profanity\",\r\n requestId: \"X-RequestId\",\r\n roomId: \"roomid\",\r\n sessionToken: \"token\",\r\n subscriptionKey: \"Ocp-Apim-Subscription-Key\",\r\n subscriptionRegion: \"Ocp-Apim-Subscription-Region\",\r\n token: \"X-CapitoToken\",\r\n };\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ArgumentNullError,\r\n Deferred\r\n} from \"../common/Exports\";\r\nimport { IRequestOptions } from \"./Exports\";\r\n\r\n// Node.JS specific xmlhttprequest / browser support.\r\nimport * as XHR from \"xmlhttprequest-ts\";\r\n\r\nexport enum RestRequestType {\r\n Get = \"get\",\r\n Post = \"post\",\r\n Delete = \"delete\",\r\n File = \"file\",\r\n}\r\n\r\nexport interface IRestResponse {\r\n ok: boolean;\r\n status: number;\r\n statusText: string;\r\n data: string;\r\n json: () => T;\r\n headers: string;\r\n}\r\n\r\n// accept rest operations via request method and return abstracted objects from server response\r\nexport class RestMessageAdapter {\r\n\r\n private privTimeout: number;\r\n private privIgnoreCache: boolean;\r\n private privHeaders: { [key: string]: string; };\r\n\r\n public constructor(\r\n configParams: IRequestOptions,\r\n connectionId?: string\r\n ) {\r\n\r\n if (!configParams) {\r\n throw new ArgumentNullError(\"configParams\");\r\n }\r\n\r\n this.privHeaders = configParams.headers;\r\n this.privTimeout = configParams.timeout;\r\n this.privIgnoreCache = configParams.ignoreCache;\r\n }\r\n\r\n public setHeaders(key: string, value: string ): void {\r\n this.privHeaders[key] = value;\r\n }\r\n\r\n public request(\r\n method: RestRequestType,\r\n uri: string,\r\n queryParams: any = {},\r\n body: any = null,\r\n binaryBody: Blob | Buffer = null,\r\n ): Promise {\r\n\r\n const responseReceivedDeferral = new Deferred();\r\n\r\n let xhr: XMLHttpRequest | XHR.XMLHttpRequest;\r\n if (typeof (XMLHttpRequest) === \"undefined\") {\r\n xhr = new XHR.XMLHttpRequest();\r\n } else {\r\n xhr = new XMLHttpRequest();\r\n }\r\n const requestCommand = method === RestRequestType.File ? \"post\" : method;\r\n xhr.open(requestCommand, this.withQuery(uri, queryParams), true);\r\n\r\n if (this.privHeaders) {\r\n Object.keys(this.privHeaders).forEach((key: any) => xhr.setRequestHeader(key, this.privHeaders[key]));\r\n }\r\n\r\n if (this.privIgnoreCache) {\r\n xhr.setRequestHeader(\"Cache-Control\", \"no-cache\");\r\n }\r\n\r\n xhr.timeout = this.privTimeout;\r\n\r\n xhr.onload = () => {\r\n responseReceivedDeferral.resolve(this.parseXHRResult(xhr));\r\n };\r\n\r\n xhr.onerror = () => {\r\n responseReceivedDeferral.resolve(this.errorResponse(xhr, \"Failed to make request.\"));\r\n };\r\n\r\n xhr.ontimeout = () => {\r\n responseReceivedDeferral.resolve(this.errorResponse(xhr, \"Request took longer than expected.\"));\r\n };\r\n\r\n if (method === RestRequestType.File && binaryBody) {\r\n xhr.setRequestHeader(\"Content-Type\", \"multipart/form-data\");\r\n xhr.send(binaryBody);\r\n } else if (method === RestRequestType.Post && body) {\r\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\r\n xhr.send(JSON.stringify(body));\r\n } else {\r\n xhr.send();\r\n }\r\n\r\n return responseReceivedDeferral.promise;\r\n }\r\n\r\n private parseXHRResult(xhr: XMLHttpRequest | XHR.XMLHttpRequest): IRestResponse {\r\n return {\r\n data: xhr.responseText,\r\n headers: xhr.getAllResponseHeaders(),\r\n json: () => JSON.parse(xhr.responseText) as T,\r\n ok: xhr.status >= 200 && xhr.status < 300,\r\n status: xhr.status,\r\n statusText: xhr.statusText,\r\n };\r\n }\r\n\r\n private errorResponse(xhr: XMLHttpRequest | XHR.XMLHttpRequest, message: string | null = null): IRestResponse {\r\n return {\r\n data: message || xhr.statusText,\r\n headers: xhr.getAllResponseHeaders(),\r\n json: () => JSON.parse(message || (\"\\\"\" + xhr.statusText + \"\\\"\")) as T,\r\n ok: false,\r\n status: xhr.status,\r\n statusText: xhr.statusText,\r\n };\r\n }\r\n\r\n private withQuery(url: string, params: any = {}): any {\r\n const queryString = this.queryParams(params);\r\n return queryString ? url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + queryString : url;\r\n }\r\n\r\n private queryParams(params: any = {}): any {\r\n return Object.keys(params)\r\n .map((k: any) => encodeURIComponent(k) + \"=\" + encodeURIComponent(params[k]))\r\n .join(\"&\");\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ArgumentNullError,\r\n ConnectionEvent,\r\n ConnectionMessage,\r\n ConnectionOpenResponse,\r\n ConnectionState,\r\n createNoDashGuid,\r\n EventSource,\r\n IConnection,\r\n IStringDictionary,\r\n IWebsocketMessageFormatter,\r\n} from \"../common/Exports\";\r\nimport { ProxyInfo } from \"./ProxyInfo\";\r\nimport { WebsocketMessageAdapter } from \"./WebsocketMessageAdapter\";\r\n\r\nexport class WebsocketConnection implements IConnection {\r\n\r\n private privUri: string;\r\n private privMessageFormatter: IWebsocketMessageFormatter;\r\n private privConnectionMessageAdapter: WebsocketMessageAdapter;\r\n private privId: string;\r\n private privIsDisposed: boolean = false;\r\n\r\n public constructor(\r\n uri: string,\r\n queryParameters: IStringDictionary,\r\n headers: IStringDictionary,\r\n messageFormatter: IWebsocketMessageFormatter,\r\n proxyInfo: ProxyInfo,\r\n enableCompression: boolean = false,\r\n connectionId?: string) {\r\n\r\n if (!uri) {\r\n throw new ArgumentNullError(\"uri\");\r\n }\r\n\r\n if (!messageFormatter) {\r\n throw new ArgumentNullError(\"messageFormatter\");\r\n }\r\n\r\n this.privMessageFormatter = messageFormatter;\r\n\r\n let queryParams = \"\";\r\n let i = 0;\r\n\r\n if (queryParameters) {\r\n for (const paramName in queryParameters) {\r\n if (paramName) {\r\n queryParams += ((i === 0) && (uri.indexOf(\"?\") === -1)) ? \"?\" : \"&\";\r\n const val = encodeURIComponent(queryParameters[paramName]);\r\n queryParams += `${paramName}=${val}`;\r\n i++;\r\n }\r\n }\r\n }\r\n\r\n if (headers) {\r\n for (const headerName in headers) {\r\n if (headerName) {\r\n queryParams += ((i === 0) && (uri.indexOf(\"?\") === -1)) ? \"?\" : \"&\";\r\n const val = encodeURIComponent(headers[headerName]);\r\n queryParams += `${headerName}=${val}`;\r\n i++;\r\n }\r\n }\r\n }\r\n\r\n this.privUri = uri + queryParams;\r\n this.privId = connectionId ? connectionId : createNoDashGuid();\r\n\r\n this.privConnectionMessageAdapter = new WebsocketMessageAdapter(\r\n this.privUri,\r\n this.id,\r\n this.privMessageFormatter,\r\n proxyInfo,\r\n headers,\r\n enableCompression);\r\n }\r\n\r\n public async dispose(): Promise {\r\n this.privIsDisposed = true;\r\n\r\n if (this.privConnectionMessageAdapter) {\r\n await this.privConnectionMessageAdapter.close();\r\n }\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n\r\n public state = (): ConnectionState => {\r\n return this.privConnectionMessageAdapter.state;\r\n }\r\n\r\n public open = (): Promise => {\r\n return this.privConnectionMessageAdapter.open();\r\n }\r\n\r\n public send = (message: ConnectionMessage): Promise => {\r\n return this.privConnectionMessageAdapter.send(message);\r\n }\r\n\r\n public read = (): Promise => {\r\n return this.privConnectionMessageAdapter.read();\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privConnectionMessageAdapter.events;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { HeaderNames } from \"../common.speech/HeaderNames\";\r\nimport {\r\n ArgumentNullError,\r\n BackgroundEvent,\r\n ConnectionClosedEvent,\r\n ConnectionErrorEvent,\r\n ConnectionEstablishedEvent,\r\n ConnectionEvent,\r\n ConnectionMessage,\r\n ConnectionMessageReceivedEvent,\r\n ConnectionMessageSentEvent,\r\n ConnectionOpenResponse,\r\n ConnectionStartEvent,\r\n ConnectionState,\r\n Deferred,\r\n Events,\r\n EventSource,\r\n IWebsocketMessageFormatter,\r\n MessageType,\r\n Queue,\r\n RawWebsocketMessage,\r\n} from \"../common/Exports\";\r\nimport { ProxyInfo } from \"./ProxyInfo\";\r\n\r\n// Node.JS specific web socket / browser support.\r\nimport ws from \"ws\";\r\nimport { CertCheckAgent } from \"./CertChecks\";\r\n\r\ninterface ISendItem {\r\n Message: ConnectionMessage;\r\n RawWebsocketMessage: RawWebsocketMessage;\r\n sendStatusDeferral: Deferred;\r\n}\r\n\r\nexport class WebsocketMessageAdapter {\r\n private privConnectionState: ConnectionState;\r\n private privMessageFormatter: IWebsocketMessageFormatter;\r\n private privWebsocketClient: WebSocket | ws;\r\n\r\n private privSendMessageQueue: Queue;\r\n private privReceivingMessageQueue: Queue;\r\n private privConnectionEstablishDeferral: Deferred;\r\n private privCertificateValidatedDeferral: Deferred;\r\n private privDisconnectDeferral: Deferred;\r\n private privConnectionEvents: EventSource;\r\n private privConnectionId: string;\r\n private privUri: string;\r\n private proxyInfo: ProxyInfo;\r\n private privHeaders: { [key: string]: string; };\r\n private privLastErrorReceived: string;\r\n private privEnableCompression: boolean;\r\n\r\n public static forceNpmWebSocket: boolean = false;\r\n\r\n public constructor(\r\n uri: string,\r\n connectionId: string,\r\n messageFormatter: IWebsocketMessageFormatter,\r\n proxyInfo: ProxyInfo,\r\n headers: { [key: string]: string; },\r\n enableCompression: boolean) {\r\n\r\n if (!uri) {\r\n throw new ArgumentNullError(\"uri\");\r\n }\r\n\r\n if (!messageFormatter) {\r\n throw new ArgumentNullError(\"messageFormatter\");\r\n }\r\n\r\n this.proxyInfo = proxyInfo;\r\n this.privConnectionEvents = new EventSource();\r\n this.privConnectionId = connectionId;\r\n this.privMessageFormatter = messageFormatter;\r\n this.privConnectionState = ConnectionState.None;\r\n this.privUri = uri;\r\n this.privHeaders = headers;\r\n this.privEnableCompression = enableCompression;\r\n\r\n // Add the connection ID to the headers\r\n this.privHeaders[HeaderNames.ConnectionId] = this.privConnectionId;\r\n\r\n this.privLastErrorReceived = \"\";\r\n }\r\n\r\n public get state(): ConnectionState {\r\n return this.privConnectionState;\r\n }\r\n\r\n public open = (): Promise => {\r\n if (this.privConnectionState === ConnectionState.Disconnected) {\r\n return Promise.reject(`Cannot open a connection that is in ${this.privConnectionState} state`);\r\n }\r\n\r\n if (this.privConnectionEstablishDeferral) {\r\n return this.privConnectionEstablishDeferral.promise;\r\n }\r\n\r\n this.privConnectionEstablishDeferral = new Deferred();\r\n this.privCertificateValidatedDeferral = new Deferred();\r\n\r\n this.privConnectionState = ConnectionState.Connecting;\r\n\r\n try {\r\n\r\n if (typeof WebSocket !== \"undefined\" && !WebsocketMessageAdapter.forceNpmWebSocket) {\r\n // Browser handles cert checks.\r\n this.privCertificateValidatedDeferral.resolve();\r\n\r\n this.privWebsocketClient = new WebSocket(this.privUri);\r\n } else {\r\n const options: ws.ClientOptions = { headers: this.privHeaders, perMessageDeflate: this.privEnableCompression };\r\n // The ocsp library will handle validation for us and fail the connection if needed.\r\n this.privCertificateValidatedDeferral.resolve();\r\n const checkAgent: CertCheckAgent = new CertCheckAgent(this.proxyInfo);\r\n\r\n options.agent = checkAgent.GetAgent();\r\n this.privWebsocketClient = new ws(this.privUri, options);\r\n }\r\n\r\n this.privWebsocketClient.binaryType = \"arraybuffer\";\r\n this.privReceivingMessageQueue = new Queue();\r\n this.privDisconnectDeferral = new Deferred();\r\n this.privSendMessageQueue = new Queue();\r\n this.processSendQueue().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n } catch (error) {\r\n this.privConnectionEstablishDeferral.resolve(new ConnectionOpenResponse(500, error));\r\n return this.privConnectionEstablishDeferral.promise;\r\n }\r\n\r\n this.onEvent(new ConnectionStartEvent(this.privConnectionId, this.privUri));\r\n\r\n this.privWebsocketClient.onopen = (e: { target: WebSocket | ws }) => {\r\n this.privCertificateValidatedDeferral.promise.then((): void => {\r\n this.privConnectionState = ConnectionState.Connected;\r\n this.onEvent(new ConnectionEstablishedEvent(this.privConnectionId));\r\n this.privConnectionEstablishDeferral.resolve(new ConnectionOpenResponse(200, \"\"));\r\n }, (error: string): void => {\r\n this.privConnectionEstablishDeferral.reject(error);\r\n });\r\n };\r\n\r\n this.privWebsocketClient.onerror = (e: { error: any; message: string; type: string; target: WebSocket | ws }) => {\r\n this.onEvent(new ConnectionErrorEvent(this.privConnectionId, e.message, e.type));\r\n this.privLastErrorReceived = e.message;\r\n };\r\n\r\n this.privWebsocketClient.onclose = (e: { wasClean: boolean; code: number; reason: string; target: WebSocket | ws }) => {\r\n if (this.privConnectionState === ConnectionState.Connecting) {\r\n this.privConnectionState = ConnectionState.Disconnected;\r\n // this.onEvent(new ConnectionEstablishErrorEvent(this.connectionId, e.code, e.reason));\r\n this.privConnectionEstablishDeferral.resolve(new ConnectionOpenResponse(e.code, e.reason + \" \" + this.privLastErrorReceived));\r\n } else {\r\n this.privConnectionState = ConnectionState.Disconnected;\r\n this.privWebsocketClient = null;\r\n this.onEvent(new ConnectionClosedEvent(this.privConnectionId, e.code, e.reason));\r\n }\r\n\r\n this.onClose(e.code, e.reason).catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n };\r\n\r\n this.privWebsocketClient.onmessage = (e: { data: ws.Data; type: string; target: WebSocket | ws }) => {\r\n const networkReceivedTime = new Date().toISOString();\r\n if (this.privConnectionState === ConnectionState.Connected) {\r\n const deferred = new Deferred();\r\n // let id = ++this.idCounter;\r\n this.privReceivingMessageQueue.enqueueFromPromise(deferred.promise);\r\n if (e.data instanceof ArrayBuffer) {\r\n const rawMessage = new RawWebsocketMessage(MessageType.Binary, e.data);\r\n this.privMessageFormatter\r\n .toConnectionMessage(rawMessage)\r\n .then((connectionMessage: ConnectionMessage) => {\r\n this.onEvent(new ConnectionMessageReceivedEvent(this.privConnectionId, networkReceivedTime, connectionMessage));\r\n deferred.resolve(connectionMessage);\r\n }, (error: string) => {\r\n // TODO: Events for these ?\r\n deferred.reject(`Invalid binary message format. Error: ${error}`);\r\n });\r\n } else {\r\n const rawMessage = new RawWebsocketMessage(MessageType.Text, e.data);\r\n this.privMessageFormatter\r\n .toConnectionMessage(rawMessage)\r\n .then((connectionMessage: ConnectionMessage) => {\r\n this.onEvent(new ConnectionMessageReceivedEvent(this.privConnectionId, networkReceivedTime, connectionMessage));\r\n deferred.resolve(connectionMessage);\r\n }, (error: string) => {\r\n // TODO: Events for these ?\r\n deferred.reject(`Invalid text message format. Error: ${error}`);\r\n });\r\n }\r\n }\r\n };\r\n\r\n return this.privConnectionEstablishDeferral.promise;\r\n }\r\n\r\n public send = (message: ConnectionMessage): Promise => {\r\n if (this.privConnectionState !== ConnectionState.Connected) {\r\n return Promise.reject(`Cannot send on connection that is in ${ConnectionState[this.privConnectionState]} state`);\r\n }\r\n\r\n const messageSendStatusDeferral = new Deferred();\r\n const messageSendDeferral = new Deferred();\r\n\r\n this.privSendMessageQueue.enqueueFromPromise(messageSendDeferral.promise);\r\n\r\n this.privMessageFormatter\r\n .fromConnectionMessage(message)\r\n .then((rawMessage: RawWebsocketMessage) => {\r\n messageSendDeferral.resolve({\r\n Message: message,\r\n RawWebsocketMessage: rawMessage,\r\n sendStatusDeferral: messageSendStatusDeferral,\r\n });\r\n }, (error: string) => {\r\n messageSendDeferral.reject(`Error formatting the message. ${error}`);\r\n });\r\n\r\n return messageSendStatusDeferral.promise;\r\n }\r\n\r\n public read = (): Promise => {\r\n if (this.privConnectionState !== ConnectionState.Connected) {\r\n return Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`);\r\n }\r\n\r\n return this.privReceivingMessageQueue.dequeue();\r\n }\r\n\r\n public close = (reason?: string): Promise => {\r\n if (this.privWebsocketClient) {\r\n if (this.privConnectionState !== ConnectionState.Disconnected) {\r\n this.privWebsocketClient.close(1000, reason ? reason : \"Normal closure by client\");\r\n }\r\n } else {\r\n return Promise.resolve();\r\n }\r\n\r\n return this.privDisconnectDeferral.promise;\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privConnectionEvents;\r\n }\r\n\r\n private sendRawMessage = (sendItem: ISendItem): Promise => {\r\n try {\r\n // indicates we are draining the queue and it came with no message;\r\n if (!sendItem) {\r\n return Promise.resolve();\r\n }\r\n\r\n this.onEvent(new ConnectionMessageSentEvent(this.privConnectionId, new Date().toISOString(), sendItem.Message));\r\n\r\n // add a check for the ws readystate in order to stop the red console error 'WebSocket is already in CLOSING or CLOSED state' appearing\r\n if (this.isWebsocketOpen) {\r\n this.privWebsocketClient.send(sendItem.RawWebsocketMessage.payload);\r\n } else {\r\n return Promise.reject(\"websocket send error: Websocket not ready \" + this.privConnectionId + \" \" + sendItem.Message.id + \" \" + new Error().stack);\r\n }\r\n return Promise.resolve();\r\n\r\n } catch (e) {\r\n return Promise.reject(`websocket send error: ${e}`);\r\n }\r\n }\r\n\r\n private async onClose(code: number, reason: string): Promise {\r\n const closeReason = `Connection closed. ${code}: ${reason}`;\r\n this.privConnectionState = ConnectionState.Disconnected;\r\n this.privDisconnectDeferral.resolve();\r\n await this.privReceivingMessageQueue.drainAndDispose((pendingReceiveItem: ConnectionMessage) => {\r\n // TODO: Events for these ?\r\n // Logger.instance.onEvent(new LoggingEvent(LogType.Warning, null, `Failed to process received message. Reason: ${closeReason}, Message: ${JSON.stringify(pendingReceiveItem)}`));\r\n }, closeReason);\r\n\r\n await this.privSendMessageQueue.drainAndDispose((pendingSendItem: ISendItem) => {\r\n pendingSendItem.sendStatusDeferral.reject(closeReason);\r\n }, closeReason);\r\n }\r\n\r\n private async processSendQueue(): Promise {\r\n while (true) {\r\n const itemToSend: Promise = this.privSendMessageQueue.dequeue();\r\n const sendItem: ISendItem = await itemToSend;\r\n // indicates we are draining the queue and it came with no message;\r\n if (!sendItem) {\r\n return;\r\n }\r\n\r\n try {\r\n await this.sendRawMessage(sendItem);\r\n sendItem.sendStatusDeferral.resolve();\r\n } catch (sendError) {\r\n sendItem.sendStatusDeferral.reject(sendError);\r\n }\r\n }\r\n }\r\n\r\n private onEvent = (event: ConnectionEvent): void => {\r\n this.privConnectionEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private get isWebsocketOpen(): boolean {\r\n return this.privWebsocketClient && this.privWebsocketClient.readyState === this.privWebsocketClient.OPEN;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { LanguageUnderstandingModelImpl } from \"../sdk/LanguageUnderstandingModel\";\r\n\r\n/**\r\n * @class AddedLmIntent\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class AddedLmIntent {\r\n public modelImpl: LanguageUnderstandingModelImpl;\r\n public intentName: string;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param modelImpl - The model.\r\n * @param intentName - The intent name.\r\n */\r\n public constructor(modelImpl: LanguageUnderstandingModelImpl, intentName: string) {\r\n this.modelImpl = modelImpl;\r\n this.intentName = intentName;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Represents the JSON used in the agent.config message sent to the speech service.\r\n */\r\nexport class AgentConfig {\r\n private iPrivConfig: IAgentConfig;\r\n\r\n public toJsonString(): string {\r\n return JSON.stringify(this.iPrivConfig);\r\n }\r\n\r\n public get(): IAgentConfig {\r\n return this.iPrivConfig;\r\n }\r\n\r\n /**\r\n * Setter for the agent.config object.\r\n * @param value a JSON serializable object.\r\n */\r\n public set(value: IAgentConfig): void {\r\n this.iPrivConfig = value;\r\n }\r\n}\r\n\r\nexport interface IAgentConfig {\r\n botInfo: {\r\n commType: string,\r\n connectionId: string,\r\n conversationId: string,\r\n fromId: string\r\n commandsCulture: string,\r\n ttsAudioFormat: string\r\n };\r\n version: number;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ArgumentNullError,\r\n} from \"../common/Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport {\r\n AuthInfo,\r\n IAuthentication\r\n} from \"./IAuthentication\";\r\n\r\n/**\r\n * @class\r\n */\r\nexport class CognitiveSubscriptionKeyAuthentication implements IAuthentication {\r\n private privAuthInfo: AuthInfo;\r\n\r\n /**\r\n * Creates and initializes an instance of the CognitiveSubscriptionKeyAuthentication class.\r\n * @constructor\r\n * @param {string} subscriptionKey - The subscription key\r\n */\r\n constructor(subscriptionKey: string) {\r\n if (!subscriptionKey) {\r\n throw new ArgumentNullError(\"subscriptionKey\");\r\n }\r\n\r\n this.privAuthInfo = new AuthInfo(HeaderNames.AuthKey, subscriptionKey);\r\n }\r\n\r\n /**\r\n * Fetches the subscription key.\r\n * @member\r\n * @function\r\n * @public\r\n * @param {string} authFetchEventId - The id to fetch.\r\n */\r\n public fetch = (authFetchEventId: string): Promise => {\r\n return Promise.resolve(this.privAuthInfo);\r\n }\r\n\r\n /**\r\n * Fetches the subscription key.\r\n * @member\r\n * @function\r\n * @public\r\n * @param {string} authFetchEventId - The id to fetch.\r\n */\r\n public fetchOnExpiry = (authFetchEventId: string): Promise => {\r\n return Promise.resolve(this.privAuthInfo);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ArgumentNullError } from \"../common/Exports\";\r\nimport { AuthInfo, IAuthentication } from \"./IAuthentication\";\r\n\r\nconst AuthHeader: string = \"Authorization\";\r\n\r\nexport class CognitiveTokenAuthentication implements IAuthentication {\r\n private privFetchCallback: (authFetchEventId: string) => Promise;\r\n private privFetchOnExpiryCallback: (authFetchEventId: string) => Promise;\r\n\r\n constructor(fetchCallback: (authFetchEventId: string) => Promise, fetchOnExpiryCallback: (authFetchEventId: string) => Promise) {\r\n if (!fetchCallback) {\r\n throw new ArgumentNullError(\"fetchCallback\");\r\n }\r\n\r\n if (!fetchOnExpiryCallback) {\r\n throw new ArgumentNullError(\"fetchOnExpiryCallback\");\r\n }\r\n\r\n this.privFetchCallback = fetchCallback;\r\n this.privFetchOnExpiryCallback = fetchOnExpiryCallback;\r\n }\r\n\r\n public fetch = (authFetchEventId: string): Promise => {\r\n return this.privFetchCallback(authFetchEventId).then((token: string) => new AuthInfo(AuthHeader, token));\r\n }\r\n\r\n public fetchOnExpiry = (authFetchEventId: string): Promise => {\r\n return this.privFetchOnExpiryCallback(authFetchEventId).then((token: string) => new AuthInfo(AuthHeader, token));\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ServicePropertiesPropertyName,\r\n} from \"../common.speech/Exports\";\r\nimport { IConnection, IStringDictionary } from \"../common/Exports\";\r\nimport { OutputFormat, PropertyId } from \"../sdk/Exports\";\r\nimport { AuthInfo, IConnectionFactory, RecognitionMode, RecognizerConfig, WebsocketMessageFormatter } from \"./Exports\";\r\nimport { QueryParameterNames } from \"./QueryParameterNames\";\r\n\r\nexport abstract class ConnectionFactoryBase implements IConnectionFactory {\r\n public abstract create(\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection;\r\n\r\n protected setCommonUrlParams(\r\n config: RecognizerConfig,\r\n queryParams: IStringDictionary,\r\n endpoint: string): void {\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceConnection_EnableAudioLogging,\r\n QueryParameterNames.EnableAudioLogging,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps,\r\n QueryParameterNames.EnableWordLevelTimestamps,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceResponse_ProfanityOption,\r\n QueryParameterNames.Profanity,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs,\r\n QueryParameterNames.InitialSilenceTimeoutMs,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs,\r\n QueryParameterNames.EndSilenceTimeoutMs,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n this.setUrlParameter(PropertyId.SpeechServiceResponse_StablePartialResultThreshold,\r\n QueryParameterNames.StableIntermediateThreshold,\r\n config,\r\n queryParams,\r\n endpoint);\r\n\r\n const serviceProperties: IStringDictionary = JSON.parse(config.parameters.getProperty(ServicePropertiesPropertyName, \"{}\"));\r\n\r\n Object.keys(serviceProperties).forEach((value: string, num: number, array: string[]) => {\r\n queryParams[value] = serviceProperties[value];\r\n });\r\n }\r\n\r\n protected setUrlParameter(\r\n propId: PropertyId,\r\n parameterName: string,\r\n config: RecognizerConfig,\r\n queryParams: IStringDictionary,\r\n endpoint: string): void {\r\n\r\n const value: string = config.parameters.getProperty(propId, undefined);\r\n\r\n if (value && (!endpoint || endpoint.search(parameterName) === -1)) {\r\n queryParams[parameterName] = value.toLocaleLowerCase();\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport { OutputFormatPropertyName } from \"../common.speech/Exports\";\r\nimport { IConnection, IStringDictionary } from \"../common/Exports\";\r\nimport { DialogServiceConfig, OutputFormat, PropertyId } from \"../sdk/Exports\";\r\nimport { ConnectionFactoryBase } from \"./ConnectionFactoryBase\";\r\nimport { AuthInfo, RecognizerConfig, WebsocketMessageFormatter } from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { QueryParameterNames } from \"./QueryParameterNames\";\r\n\r\nexport class DialogConnectionFactory extends ConnectionFactoryBase {\r\n\r\n private static Constants: any = class {\r\n private static ApiKey: string = \"api\";\r\n private static BaseUrl: string = \"convai.speech\";\r\n };\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n const applicationId: string = config.parameters.getProperty(PropertyId.Conversation_ApplicationId, \"\");\r\n const dialogType: string = config.parameters.getProperty(PropertyId.Conversation_DialogType);\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region);\r\n const language: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, \"en-US\");\r\n const requestTurnStatus: string = config.parameters.getProperty(PropertyId.Conversation_Request_Bot_Status_Messages, \"true\");\r\n\r\n const queryParams: IStringDictionary = {};\r\n queryParams[HeaderNames.ConnectionId] = connectionId;\r\n queryParams[QueryParameterNames.Format] = config.parameters.getProperty(OutputFormatPropertyName, OutputFormat[OutputFormat.Simple]).toLowerCase();\r\n queryParams[QueryParameterNames.Language] = language;\r\n queryParams[QueryParameterNames.RequestBotStatusMessages] = requestTurnStatus;\r\n if (applicationId) {\r\n queryParams[QueryParameterNames.BotId] = applicationId;\r\n if (dialogType === DialogServiceConfig.DialogTypes.CustomCommands) {\r\n queryParams[HeaderNames.CustomCommandsAppId] = applicationId;\r\n }\r\n }\r\n\r\n const resourceInfix: string =\r\n dialogType === DialogServiceConfig.DialogTypes.CustomCommands ? \"commands/\"\r\n : \"\";\r\n const version: string =\r\n dialogType === DialogServiceConfig.DialogTypes.CustomCommands ? \"v1\"\r\n : dialogType === DialogServiceConfig.DialogTypes.BotFramework ? \"v3\"\r\n : \"v0\";\r\n\r\n const headers: IStringDictionary = {};\r\n\r\n if (authInfo.token != null && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n\r\n // The URL used for connection is chosen in a priority order of specification:\r\n // 1. If a custom endpoint is provided, that URL is used verbatim.\r\n // 2. If a custom host is provided (e.g. \"wss://my.custom.endpoint.com:1123\"), a URL is constructed from it.\r\n // 3. If no custom connection details are provided, a URL is constructed from default values.\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, \"\");\r\n if (!endpoint) {\r\n const hostSuffix = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(\r\n PropertyId.SpeechServiceConnection_Host,\r\n `wss://${region}.${DialogConnectionFactory.Constants.BaseUrl}${hostSuffix}`);\r\n const standardizedHost: string = host.endsWith(\"/\") ? host : host + \"/\";\r\n endpoint = `${standardizedHost}${resourceInfix}${DialogConnectionFactory.Constants.ApiKey}/${version}`;\r\n }\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ReplayableAudioNode\r\n} from \"../common.browser/Exports\";\r\nimport { SendingAgentContextMessageEvent } from \"../common/DialogEvents\";\r\nimport {\r\n BackgroundEvent,\r\n ConnectionEvent,\r\n ConnectionMessage,\r\n createGuid,\r\n createNoDashGuid,\r\n Deferred,\r\n DialogEvent,\r\n Events,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IConnection,\r\n MessageType,\r\n ServiceEvent,\r\n} from \"../common/Exports\";\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport { PullAudioOutputStreamImpl } from \"../sdk/Audio/AudioOutputStream\";\r\nimport { AudioStreamFormatImpl } from \"../sdk/Audio/AudioStreamFormat\";\r\nimport {\r\n ActivityReceivedEventArgs,\r\n CancellationErrorCode,\r\n CancellationReason,\r\n DialogServiceConfig,\r\n DialogServiceConnector,\r\n PropertyCollection,\r\n PropertyId,\r\n RecognitionEventArgs,\r\n ResultReason,\r\n SessionEventArgs,\r\n SpeechRecognitionCanceledEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult,\r\n TurnStatusReceivedEventArgs,\r\n} from \"../sdk/Exports\";\r\nimport { DialogServiceTurnStateManager } from \"./DialogServiceTurnStateManager\";\r\nimport {\r\n CancellationErrorCodePropertyName,\r\n EnumTranslation,\r\n ISpeechConfigAudioDevice,\r\n RecognitionStatus,\r\n ServiceRecognizerBase,\r\n SimpleSpeechPhrase,\r\n SpeechDetected,\r\n SpeechHypothesis,\r\n SpeechKeyword,\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognitionMode, RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { ActivityPayloadResponse } from \"./ServiceMessages/ActivityResponsePayload\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\nexport class DialogServiceAdapter extends ServiceRecognizerBase {\r\n private privDialogServiceConnector: DialogServiceConnector;\r\n\r\n private privDialogAudioSource: IAudioSource;\r\n\r\n private privConnectionLoop: Promise;\r\n private terminateMessageLoop: boolean;\r\n private agentConfigSent: boolean;\r\n private privLastResult: SpeechRecognitionResult;\r\n private privEvents: EventSource;\r\n\r\n // Turns are of two kinds:\r\n // 1: SR turns, end when the SR result is returned and then turn end.\r\n // 2: Service turns where an activity is sent by the service along with the audio.\r\n private privTurnStateManager: DialogServiceTurnStateManager;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n dialogServiceConnector: DialogServiceConnector) {\r\n\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector);\r\n\r\n this.privEvents = new EventSource();\r\n this.privDialogServiceConnector = dialogServiceConnector;\r\n this.receiveMessageOverride = this.receiveDialogMessageOverride;\r\n this.privTurnStateManager = new DialogServiceTurnStateManager();\r\n this.recognizeOverride = this.listenOnce;\r\n this.postConnectImplOverride = this.dialogConnectImpl;\r\n this.configConnectionOverride = this.configConnection;\r\n this.disconnectOverride = this.privDisconnect;\r\n this.privDialogAudioSource = audioSource;\r\n\r\n this.agentConfigSent = false;\r\n this.privLastResult = null;\r\n this.connectionEvents.attach(async (connectionEvent: ConnectionEvent): Promise => {\r\n if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n this.terminateMessageLoop = true;\r\n }\r\n });\r\n }\r\n\r\n public async sendMessage(message: string): Promise {\r\n const interactionGuid: string = createGuid();\r\n const requestId: string = createNoDashGuid();\r\n\r\n const agentMessage: any = {\r\n context: {\r\n interactionId: interactionGuid\r\n },\r\n messagePayload: JSON.parse(message),\r\n version: 0.5\r\n };\r\n\r\n const agentMessageJson = JSON.stringify(agentMessage);\r\n const connection: IConnection = await this.fetchConnection();\r\n await connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"agent\",\r\n requestId,\r\n \"application/json\",\r\n agentMessageJson));\r\n\r\n }\r\n\r\n protected async privDisconnect(): Promise {\r\n await this.cancelRecognition(this.privRequestSession.sessionId,\r\n this.privRequestSession.requestId,\r\n CancellationReason.Error,\r\n CancellationErrorCode.NoError,\r\n \"Disconnecting\");\r\n\r\n this.terminateMessageLoop = true;\r\n this.agentConfigSent = false;\r\n return;\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n if (connectionMessage.messageType === MessageType.Text) {\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n }\r\n\r\n let result: SpeechRecognitionResult;\r\n let processed: boolean;\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"speech.phrase\":\r\n const speechPhrase: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n\r\n this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + speechPhrase.Offset + speechPhrase.Duration);\r\n\r\n if (speechPhrase.RecognitionStatus !== RecognitionStatus.TooManyRequests && speechPhrase.RecognitionStatus !== RecognitionStatus.Error) {\r\n const args: SpeechRecognitionEventArgs = this.fireEventForResult(speechPhrase, resultProps);\r\n this.privLastResult = args.result;\r\n\r\n if (!!this.privDialogServiceConnector.recognized) {\r\n try {\r\n this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, args);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.hypothesis\":\r\n const hypothesis: SpeechHypothesis = SpeechHypothesis.fromJSON(connectionMessage.textBody);\r\n const offset: number = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n ResultReason.RecognizingSpeech,\r\n hypothesis.Text,\r\n hypothesis.Duration,\r\n offset,\r\n hypothesis.Language,\r\n hypothesis.LanguageDetectionConfidence,\r\n undefined,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n this.privRequestSession.onHypothesis(offset);\r\n\r\n const ev = new SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privDialogServiceConnector.recognizing) {\r\n try {\r\n this.privDialogServiceConnector.recognizing(this.privDialogServiceConnector, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.keyword\":\r\n const keyword: SpeechKeyword = SpeechKeyword.fromJSON(connectionMessage.textBody);\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n keyword.Status === \"Accepted\" ? ResultReason.RecognizedKeyword : ResultReason.NoMatch,\r\n keyword.Text,\r\n keyword.Duration,\r\n keyword.Offset,\r\n undefined,\r\n undefined,\r\n undefined,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n if (keyword.Status !== \"Accepted\") {\r\n this.privLastResult = result;\r\n }\r\n\r\n const event = new SpeechRecognitionEventArgs(result, result.duration, result.resultId);\r\n\r\n if (!!this.privDialogServiceConnector.recognized) {\r\n try {\r\n this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, event);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"audio\":\r\n {\r\n const audioRequestId = connectionMessage.requestId.toUpperCase();\r\n const turn = this.privTurnStateManager.GetTurn(audioRequestId);\r\n try {\r\n // Empty binary message signals end of stream.\r\n if (!connectionMessage.binaryBody) {\r\n turn.endAudioStream();\r\n } else {\r\n turn.audioStream.write(connectionMessage.binaryBody);\r\n }\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n\r\n case \"response\":\r\n {\r\n this.handleResponseMessage(connectionMessage);\r\n\r\n }\r\n processed = true;\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected async cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): Promise {\r\n\r\n this.terminateMessageLoop = true;\r\n\r\n if (!!this.privRequestSession.isRecognizing) {\r\n await this.privRequestSession.onStopRecognizing();\r\n }\r\n\r\n if (!!this.privDialogServiceConnector.canceled) {\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n const cancelEvent: SpeechRecognitionCanceledEventArgs = new SpeechRecognitionCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n sessionId);\r\n\r\n try {\r\n this.privDialogServiceConnector.canceled(this.privDialogServiceConnector, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: SpeechRecognitionResult = new SpeechRecognitionResult(\r\n undefined, // ResultId\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Duration\r\n undefined, // Offset\r\n undefined, // Language\r\n undefined, // Language Detection Confidence\r\n undefined, // Speaker Id\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n this.privSuccessCallback = undefined;\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n }\r\n\r\n protected async listenOnce(\r\n recoMode: RecognitionMode,\r\n successCallback: (e: SpeechRecognitionResult) => void,\r\n errorCallback: (e: string) => void\r\n ): Promise {\r\n this.privRecognizerConfig.recognitionMode = recoMode;\r\n\r\n this.privSuccessCallback = successCallback;\r\n this.privErrorCallback = errorCallback;\r\n\r\n this.privRequestSession.startNewRecognition();\r\n this.privRequestSession.listenForServiceTelemetry(this.privDialogAudioSource.events);\r\n\r\n this.privRecognizerConfig.parameters.setProperty(PropertyId.Speech_SessionId, this.privRequestSession.sessionId);\r\n\r\n // Start the connection to the service. The promise this will create is stored and will be used by configureConnection().\r\n const conPromise: Promise = this.connectImpl();\r\n\r\n const preAudioPromise: Promise = this.sendPreAudioMessages();\r\n\r\n const node: IAudioStreamNode = await this.privDialogAudioSource.attach(this.privRequestSession.audioNodeId);\r\n const format: AudioStreamFormatImpl = await this.privDialogAudioSource.format;\r\n const deviceInfo: ISpeechConfigAudioDevice = await this.privDialogAudioSource.deviceInfo;\r\n\r\n const audioNode = new ReplayableAudioNode(node, format.avgBytesPerSec);\r\n await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false);\r\n\r\n this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };\r\n\r\n try {\r\n await conPromise;\r\n await preAudioPromise;\r\n } catch (error) {\r\n await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, CancellationReason.Error, CancellationErrorCode.ConnectionFailure, error);\r\n return Promise.resolve();\r\n }\r\n\r\n const sessionStartEventArgs: SessionEventArgs = new SessionEventArgs(this.privRequestSession.sessionId);\r\n\r\n if (!!this.privRecognizer.sessionStarted) {\r\n this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);\r\n }\r\n\r\n const audioSendPromise = this.sendAudio(audioNode);\r\n\r\n // /* tslint:disable:no-empty */\r\n audioSendPromise.then(() => { /*add? return true;*/ }, async (error: string) => {\r\n await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, CancellationReason.Error, CancellationErrorCode.RuntimeError, error);\r\n });\r\n }\r\n\r\n // Establishes a websocket connection to the end point.\r\n private dialogConnectImpl(connection: Promise): Promise {\r\n this.privConnectionLoop = this.startMessageLoop();\r\n return connection;\r\n }\r\n\r\n private receiveDialogMessageOverride(): Promise {\r\n\r\n // we won't rely on the cascading promises of the connection since we want to continually be available to receive messages\r\n const communicationCustodian: Deferred = new Deferred();\r\n\r\n const loop = async (): Promise => {\r\n try {\r\n const isDisposed: boolean = this.isDisposed();\r\n const terminateMessageLoop = (!this.isDisposed() && this.terminateMessageLoop);\r\n if (isDisposed || terminateMessageLoop) {\r\n // We're done.\r\n communicationCustodian.resolve(undefined);\r\n return;\r\n }\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n const message: ConnectionMessage = await connection.read();\r\n\r\n if (!message) {\r\n return loop();\r\n }\r\n\r\n const connectionMessage = SpeechConnectionMessage.fromConnectionMessage(message);\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"turn.start\":\r\n {\r\n const turnRequestId = connectionMessage.requestId.toUpperCase();\r\n const audioSessionReqId = this.privRequestSession.requestId.toUpperCase();\r\n\r\n // turn started by the service\r\n if (turnRequestId !== audioSessionReqId) {\r\n this.privTurnStateManager.StartTurn(turnRequestId);\r\n } else {\r\n this.privRequestSession.onServiceTurnStartResponse();\r\n }\r\n }\r\n break;\r\n\r\n case \"speech.startdetected\":\r\n const speechStartDetected: SpeechDetected = SpeechDetected.fromJSON(connectionMessage.textBody);\r\n\r\n const speechStartEventArgs = new RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privRecognizer.speechStartDetected) {\r\n this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs);\r\n }\r\n\r\n break;\r\n\r\n case \"speech.enddetected\":\r\n\r\n let json: string;\r\n\r\n if (connectionMessage.textBody.length > 0) {\r\n json = connectionMessage.textBody;\r\n } else {\r\n // If the request was empty, the JSON returned is empty.\r\n json = \"{ Offset: 0 }\";\r\n }\r\n\r\n const speechStopDetected: SpeechDetected = SpeechDetected.fromJSON(json);\r\n\r\n this.privRequestSession.onServiceRecognized(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset);\r\n\r\n const speechStopEventArgs = new RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privRecognizer.speechEndDetected) {\r\n this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs);\r\n }\r\n break;\r\n\r\n case \"turn.end\":\r\n {\r\n const turnEndRequestId = connectionMessage.requestId.toUpperCase();\r\n\r\n const audioSessionReqId = this.privRequestSession.requestId.toUpperCase();\r\n\r\n // turn started by the service\r\n if (turnEndRequestId !== audioSessionReqId) {\r\n this.privTurnStateManager.CompleteTurn(turnEndRequestId);\r\n } else {\r\n // Audio session turn\r\n\r\n const sessionStopEventArgs: SessionEventArgs = new SessionEventArgs(this.privRequestSession.sessionId);\r\n await this.privRequestSession.onServiceTurnEndResponse(false);\r\n\r\n if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) {\r\n if (!!this.privRecognizer.sessionStopped) {\r\n this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs);\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback && this.privLastResult) {\r\n try {\r\n this.privSuccessCallback(this.privLastResult);\r\n this.privLastResult = null;\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n }\r\n }\r\n break;\r\n\r\n default:\r\n if (!this.processTypeSpecificMessages(connectionMessage)) {\r\n if (!!this.serviceEvents) {\r\n this.serviceEvents.onEvent(new ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));\r\n }\r\n }\r\n }\r\n const ret: Promise = loop();\r\n\r\n return ret;\r\n } catch (error) {\r\n this.terminateMessageLoop = true;\r\n communicationCustodian.resolve();\r\n }\r\n };\r\n\r\n loop().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n\r\n return communicationCustodian.promise;\r\n }\r\n\r\n private async startMessageLoop(): Promise {\r\n\r\n this.terminateMessageLoop = false;\r\n\r\n try {\r\n await this.receiveDialogMessageOverride();\r\n } catch (error) {\r\n await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, CancellationReason.Error, CancellationErrorCode.RuntimeError, error);\r\n }\r\n\r\n return Promise.resolve();\r\n }\r\n\r\n // Takes an established websocket connection to the endpoint and sends speech configuration information.\r\n private async configConnection(connection: IConnection): Promise {\r\n if (this.terminateMessageLoop) {\r\n this.terminateMessageLoop = false;\r\n return Promise.reject(`Connection to service terminated.`);\r\n }\r\n\r\n await this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize());\r\n await this.sendAgentConfig(connection);\r\n return connection;\r\n }\r\n\r\n private async sendPreAudioMessages(): Promise {\r\n const connection: IConnection = await this.fetchConnection();\r\n this.addKeywordContextData();\r\n await this.sendSpeechContext(connection);\r\n await this.sendAgentContext(connection);\r\n await this.sendWaveHeader(connection);\r\n }\r\n\r\n private sendAgentConfig = (connection: IConnection): Promise => {\r\n if (this.agentConfig && !this.agentConfigSent) {\r\n\r\n if (this.privRecognizerConfig\r\n .parameters\r\n .getProperty(PropertyId.Conversation_DialogType) === DialogServiceConfig.DialogTypes.CustomCommands) {\r\n const config = this.agentConfig.get();\r\n config.botInfo.commandsCulture = this.privRecognizerConfig.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, \"en-us\");\r\n this.agentConfig.set(config);\r\n }\r\n this.onEvent(new SendingAgentContextMessageEvent(this.agentConfig));\r\n\r\n const agentConfigJson = this.agentConfig.toJsonString();\r\n\r\n // guard against sending this multiple times on one connection\r\n this.agentConfigSent = true;\r\n\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"agent.config\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n agentConfigJson));\r\n }\r\n\r\n return;\r\n }\r\n\r\n private sendAgentContext = (connection: IConnection): Promise => {\r\n const guid: string = createGuid();\r\n\r\n const speechActivityTemplate = this.privDialogServiceConnector.properties.getProperty(PropertyId.Conversation_Speech_Activity_Template);\r\n\r\n const agentContext: any = {\r\n channelData: \"\",\r\n context: {\r\n interactionId: guid\r\n },\r\n messagePayload: typeof speechActivityTemplate === undefined ? undefined : speechActivityTemplate,\r\n version: 0.5\r\n };\r\n\r\n const agentContextJson = JSON.stringify(agentContext);\r\n\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.agent.context\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n agentContextJson));\r\n }\r\n\r\n private fireEventForResult(serviceResult: SimpleSpeechPhrase, properties: PropertyCollection): SpeechRecognitionEventArgs {\r\n const resultReason: ResultReason = EnumTranslation.implTranslateRecognitionResult(serviceResult.RecognitionStatus);\r\n\r\n const offset: number = serviceResult.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n const result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n serviceResult.DisplayText,\r\n serviceResult.Duration,\r\n offset,\r\n serviceResult.Language,\r\n serviceResult.LanguageDetectionConfidence,\r\n undefined,\r\n undefined,\r\n JSON.stringify(serviceResult),\r\n properties);\r\n\r\n const ev = new SpeechRecognitionEventArgs(result, offset, this.privRequestSession.sessionId);\r\n return ev;\r\n }\r\n\r\n private handleResponseMessage = (responseMessage: SpeechConnectionMessage): void => {\r\n // \"response\" messages can contain either \"message\" (activity) or \"MessageStatus\" data. Fire the appropriate\r\n // event according to the message type that's specified.\r\n const responsePayload = JSON.parse(responseMessage.textBody);\r\n switch (responsePayload.messageType.toLowerCase()) {\r\n case \"message\":\r\n const responseRequestId = responseMessage.requestId.toUpperCase();\r\n const activityPayload: ActivityPayloadResponse = ActivityPayloadResponse.fromJSON(responseMessage.textBody);\r\n const turn = this.privTurnStateManager.GetTurn(responseRequestId);\r\n\r\n // update the conversation Id\r\n if (activityPayload.conversationId) {\r\n const updateAgentConfig = this.agentConfig.get();\r\n updateAgentConfig.botInfo.conversationId = activityPayload.conversationId;\r\n this.agentConfig.set(updateAgentConfig);\r\n }\r\n\r\n const pullAudioOutputStream: PullAudioOutputStreamImpl = turn.processActivityPayload(\r\n activityPayload,\r\n AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(this.privDialogServiceConnector.properties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)));\r\n const activity = new ActivityReceivedEventArgs(activityPayload.messagePayload, pullAudioOutputStream);\r\n if (!!this.privDialogServiceConnector.activityReceived) {\r\n try {\r\n this.privDialogServiceConnector.activityReceived(this.privDialogServiceConnector, activity);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n\r\n case \"messagestatus\":\r\n if (!!this.privDialogServiceConnector.turnStatusReceived) {\r\n try {\r\n this.privDialogServiceConnector.turnStatusReceived(\r\n this.privDialogServiceConnector,\r\n new TurnStatusReceivedEventArgs(responseMessage.textBody));\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n\r\n default:\r\n Events.instance.onEvent(\r\n new BackgroundEvent(`Unexpected response of type ${responsePayload.messageType}. Ignoring.`));\r\n break;\r\n }\r\n }\r\n\r\n private onEvent(event: DialogEvent): void {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private addKeywordContextData(): void {\r\n const keywordPropertyValue: string = this.privRecognizerConfig.parameters.getProperty(\"SPEECH-KeywordsToDetect\");\r\n if (keywordPropertyValue === undefined) {\r\n return;\r\n }\r\n\r\n const keywordOffsetPropertyValue: string = this.privRecognizerConfig.parameters\r\n .getProperty(\"SPEECH-KeywordsToDetect-Offsets\");\r\n const keywordDurationPropertyValue: string = this.privRecognizerConfig.parameters\r\n .getProperty(\"SPEECH-KeywordsToDetect-Durations\");\r\n\r\n const keywords = keywordPropertyValue.split(\";\");\r\n const keywordOffsets = keywordOffsetPropertyValue === undefined ? [] : keywordOffsetPropertyValue.split(\";\");\r\n const keywordDurations = keywordDurationPropertyValue === undefined ? [] : keywordDurationPropertyValue.split(\";\");\r\n\r\n const keywordDefinitionArray = [];\r\n for (let i = 0; i < keywords.length; i++) {\r\n const definition: { [section: string]: any } = {};\r\n definition.text = keywords[i];\r\n if (i < keywordOffsets.length) {\r\n definition.offset = Number(keywordOffsets[i]);\r\n }\r\n if (i < keywordDurations.length) {\r\n definition.duration = Number(keywordDurations[i]);\r\n }\r\n keywordDefinitionArray.push(definition);\r\n }\r\n\r\n this.speechContext.setSection(\"invocationSource\", \"VoiceActivationWithKeyword\");\r\n this.speechContext.setSection(\"keywordDetection\", [{\r\n clientDetectedKeywords: keywordDefinitionArray,\r\n onReject: { action: \"EndOfTurn\" },\r\n type: \"startTrigger\"\r\n }]);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport { AudioOutputStream, PullAudioOutputStreamImpl } from \"../sdk/Audio/AudioOutputStream\";\r\nimport { DialogServiceTurnStateManager } from \"./DialogServiceTurnStateManager\";\r\nimport { ActivityPayloadResponse, MessageDataStreamType } from \"./ServiceMessages/ActivityResponsePayload\";\r\n\r\nexport class DialogServiceTurnState {\r\n private privRequestId: string;\r\n private privIsCompleted: boolean;\r\n private privAudioStream: PullAudioOutputStreamImpl;\r\n private privTimeoutToken: any;\r\n private privTurnManager: DialogServiceTurnStateManager;\r\n\r\n constructor(manager: DialogServiceTurnStateManager, requestId: string) {\r\n this.privRequestId = requestId;\r\n this.privIsCompleted = false;\r\n this.privAudioStream = null;\r\n this.privTurnManager = manager;\r\n this.resetTurnEndTimeout();\r\n // tslint:disable-next-line:no-console\r\n // console.info(\"DialogServiceTurnState debugturn start:\" + this.privRequestId);\r\n }\r\n\r\n public get audioStream(): PullAudioOutputStreamImpl {\r\n // Called when is needed to stream.\r\n this.resetTurnEndTimeout();\r\n return this.privAudioStream;\r\n }\r\n\r\n public processActivityPayload(payload: ActivityPayloadResponse, audioFormat?: AudioOutputFormatImpl): PullAudioOutputStreamImpl {\r\n if (payload.messageDataStreamType === MessageDataStreamType.TextToSpeechAudio) {\r\n this.privAudioStream = AudioOutputStream.createPullStream() as PullAudioOutputStreamImpl;\r\n this.privAudioStream.format = (audioFormat !== undefined) ? audioFormat : AudioOutputFormatImpl.getDefaultOutputFormat();\r\n // tslint:disable-next-line:no-console\r\n // console.info(\"Audio start debugturn:\" + this.privRequestId);\r\n }\r\n return this.privAudioStream;\r\n }\r\n\r\n public endAudioStream(): void {\r\n if (this.privAudioStream !== null && !this.privAudioStream.isClosed) {\r\n this.privAudioStream.close();\r\n }\r\n }\r\n\r\n public complete(): void {\r\n if (this.privTimeoutToken !== undefined) {\r\n clearTimeout(this.privTimeoutToken);\r\n }\r\n this.endAudioStream();\r\n }\r\n\r\n private resetTurnEndTimeout(): void {\r\n if (this.privTimeoutToken !== undefined) {\r\n clearTimeout(this.privTimeoutToken);\r\n }\r\n // tslint:disable-next-line:no-console\r\n // console.info(\"Timeout reset debugturn:\" + this.privRequestId);\r\n\r\n this.privTimeoutToken = setTimeout((): void => {\r\n // tslint:disable-next-line:no-console\r\n // console.info(\"Timeout complete debugturn:\" + this.privRequestId);\r\n\r\n this.privTurnManager.CompleteTurn(this.privRequestId);\r\n return;\r\n }, 2000);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError } from \"../common/Error\";\r\nimport { AudioOutputStream, PullAudioOutputStreamImpl } from \"../sdk/Audio/AudioOutputStream\";\r\nimport { DialogServiceTurnState } from \"./DialogServiceTurnState\";\r\nimport { ActivityPayloadResponse } from \"./ServiceMessages/ActivityResponsePayload\";\r\n\r\nexport class DialogServiceTurnStateManager {\r\n private privTurnMap: Map;\r\n\r\n constructor() {\r\n this.privTurnMap = new Map();\r\n return;\r\n }\r\n\r\n public StartTurn(id: string): DialogServiceTurnState {\r\n if (this.privTurnMap.has(id)) {\r\n throw new InvalidOperationError(\"Service error: There is already a turn with id:\" + id);\r\n }\r\n const turnState: DialogServiceTurnState = new DialogServiceTurnState(this, id);\r\n this.privTurnMap.set(id, turnState);\r\n return this.privTurnMap.get(id);\r\n }\r\n\r\n public GetTurn(id: string): DialogServiceTurnState {\r\n return this.privTurnMap.get(id);\r\n }\r\n\r\n public CompleteTurn(id: string): DialogServiceTurnState {\r\n if (!this.privTurnMap.has(id)) {\r\n throw new InvalidOperationError(\"Service error: Received turn end for an unknown turn id:\" + id);\r\n }\r\n const turnState = this.privTurnMap.get(id);\r\n turnState.complete();\r\n this.privTurnMap.delete(id);\r\n return turnState;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IDynamicGrammar,\r\n IDynamicGrammarGeneric,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Responsible for building the object to be sent to the speech service to support dynamic grammars.\r\n * @class DynamicGrammarBuilder\r\n */\r\nexport class DynamicGrammarBuilder {\r\n\r\n private privPhrases: string[];\r\n private privGrammars: string[];\r\n\r\n // Adds one more reference phrases to the dynamic grammar to send.\r\n // All added phrases are generic phrases.\r\n public addPhrase(phrase: string | string[]): void {\r\n if (!this.privPhrases) {\r\n this.privPhrases = [];\r\n }\r\n\r\n if (phrase instanceof Array) {\r\n this.privPhrases = this.privPhrases.concat(phrase as string[]);\r\n } else {\r\n this.privPhrases.push(phrase as string);\r\n }\r\n }\r\n\r\n // Clears all phrases stored in the current object.\r\n public clearPhrases(): void {\r\n this.privPhrases = undefined;\r\n }\r\n\r\n // Adds one or more reference grammars to the current grammar.\r\n public addReferenceGrammar(grammar: string | string[]): void {\r\n if (!this.privGrammars) {\r\n this.privGrammars = [];\r\n }\r\n\r\n if (grammar instanceof Array) {\r\n this.privGrammars = this.privGrammars.concat(grammar as string[]);\r\n } else {\r\n this.privGrammars.push(grammar as string);\r\n }\r\n }\r\n\r\n // clears all grammars stored on the recognizer.\r\n public clearGrammars(): void {\r\n this.privGrammars = undefined;\r\n }\r\n\r\n // Generates an object that represents the dynamic grammar used by the Speech Service.\r\n // This is done by building an object with the correct layout based on the phrases and reference grammars added to this instance\r\n // of a DynamicGrammarBuilder\r\n public generateGrammarObject(): IDynamicGrammar {\r\n if (this.privGrammars === undefined && this.privPhrases === undefined) {\r\n return undefined;\r\n }\r\n\r\n const retObj: IDynamicGrammar = {};\r\n retObj.ReferenceGrammars = this.privGrammars;\r\n\r\n if (undefined !== this.privPhrases && 0 !== this.privPhrases.length) {\r\n const retPhrases: IDynamicGrammarGeneric[] = [];\r\n\r\n this.privPhrases.forEach((value: string, index: number, array: string[]): void => {\r\n retPhrases.push({\r\n Text: value,\r\n });\r\n });\r\n\r\n retObj.Groups = [{ Type: \"Generic\", Items: retPhrases }];\r\n }\r\n\r\n return retObj;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n ResultReason\r\n} from \"../sdk/Exports\";\r\nimport { RecognitionStatus } from \"./Exports\";\r\n\r\nexport class EnumTranslation {\r\n public static implTranslateRecognitionResult(recognitionStatus: RecognitionStatus): ResultReason {\r\n let reason = ResultReason.Canceled;\r\n switch (recognitionStatus) {\r\n case RecognitionStatus.Success:\r\n reason = ResultReason.RecognizedSpeech;\r\n break;\r\n case RecognitionStatus.NoMatch:\r\n case RecognitionStatus.InitialSilenceTimeout:\r\n case RecognitionStatus.BabbleTimeout:\r\n case RecognitionStatus.EndOfDictation:\r\n reason = ResultReason.NoMatch;\r\n break;\r\n case RecognitionStatus.Error:\r\n default:\r\n reason = ResultReason.Canceled;\r\n break;\r\n }\r\n return reason;\r\n }\r\n\r\n public static implTranslateCancelResult(recognitionStatus: RecognitionStatus): CancellationReason {\r\n let reason = CancellationReason.EndOfStream;\r\n switch (recognitionStatus) {\r\n case RecognitionStatus.Success:\r\n case RecognitionStatus.EndOfDictation:\r\n case RecognitionStatus.NoMatch:\r\n reason = CancellationReason.EndOfStream;\r\n break;\r\n case RecognitionStatus.InitialSilenceTimeout:\r\n case RecognitionStatus.BabbleTimeout:\r\n case RecognitionStatus.Error:\r\n default:\r\n reason = CancellationReason.Error;\r\n break;\r\n }\r\n return reason;\r\n }\r\n\r\n public static implTranslateCancelErrorCode(recognitionStatus: RecognitionStatus): CancellationErrorCode {\r\n let reason: CancellationErrorCode = CancellationErrorCode.NoError;\r\n switch (recognitionStatus) {\r\n case RecognitionStatus.Error:\r\n reason = CancellationErrorCode.ServiceError;\r\n break;\r\n case RecognitionStatus.TooManyRequests:\r\n reason = CancellationErrorCode.TooManyRequests;\r\n break;\r\n default:\r\n reason = CancellationErrorCode.NoError;\r\n break;\r\n }\r\n\r\n return reason;\r\n\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// Make sure not to export internal modules.\r\n//\r\nexport * from \"./CognitiveSubscriptionKeyAuthentication\";\r\nexport * from \"./CognitiveTokenAuthentication\";\r\nexport * from \"./IAuthentication\";\r\nexport * from \"./IConnectionFactory\";\r\nexport * from \"./ISynthesisConnectionFactory\";\r\nexport * from \"./IntentConnectionFactory\";\r\nexport * from \"./RecognitionEvents\";\r\nexport * from \"./ServiceRecognizerBase\";\r\nexport * from \"./RecognizerConfig\";\r\nexport * from \"./SpeechServiceInterfaces\";\r\nexport * from \"./WebsocketMessageFormatter\";\r\nexport * from \"./SpeechConnectionFactory\";\r\nexport * from \"./TranscriberConnectionFactory\";\r\nexport * from \"./TranslationConnectionFactory\";\r\nexport * from \"./SpeechSynthesisConnectionFactory\";\r\nexport * from \"./EnumTranslation\";\r\nexport * from \"./ServiceMessages/Enums\";\r\nexport * from \"./ServiceMessages/TranslationSynthesisEnd\";\r\nexport * from \"./ServiceMessages/TranslationHypothesis\";\r\nexport * from \"./ServiceMessages/TranslationPhrase\";\r\nexport * from \"./TranslationServiceRecognizer\";\r\nexport * from \"./ServiceMessages/SpeechDetected\";\r\nexport * from \"./ServiceMessages/SpeechHypothesis\";\r\nexport * from \"./ServiceMessages/SpeechKeyword\";\r\nexport * from \"./SpeechServiceRecognizer\";\r\nexport * from \"./TranscriptionServiceRecognizer\";\r\nexport * from \"./ServiceMessages/DetailedSpeechPhrase\";\r\nexport * from \"./ServiceMessages/SimpleSpeechPhrase\";\r\nexport * from \"./AddedLmIntent\";\r\nexport * from \"./IntentServiceRecognizer\";\r\nexport * from \"./ServiceMessages/IntentResponse\";\r\nexport * from \"./RequestSession\";\r\nexport * from \"./SpeechContext\";\r\nexport * from \"./DynamicGrammarBuilder\";\r\nexport * from \"./DynamicGrammarInterfaces\";\r\nexport * from \"./DialogServiceAdapter\";\r\nexport * from \"./AgentConfig\";\r\nexport * from \"./Transcription/Exports\";\r\nexport * from \"./ServiceMessages/SynthesisAudioMetadata\";\r\nexport * from \"./SynthesisTurn\";\r\nexport * from \"./SynthesisAdapterBase\";\r\nexport * from \"./SynthesizerConfig\";\r\nexport * from \"./SynthesisContext\";\r\nexport * from \"./SpeakerRecognitionConfig\";\r\nexport * from \"./SpeakerIdMessageAdapter\";\r\n\r\nexport const OutputFormatPropertyName: string = \"OutputFormat\";\r\nexport const CancellationErrorCodePropertyName: string = \"CancellationErrorCode\";\r\nexport const ServicePropertiesPropertyName: string = \"ServiceProperties\";\r\nexport const ForceDictationPropertyName: string = \"ForceDictation\";\r\nexport const AutoDetectSourceLanguagesOpenRangeOptionName: string = \"OpenRange\";\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport class HeaderNames {\r\n public static AuthKey: string = \"Ocp-Apim-Subscription-Key\";\r\n public static ConnectionId: string = \"X-ConnectionId\";\r\n public static ContentType: string = \"Content-Type\";\r\n public static CustomCommandsAppId: string = \"X-CommandsAppId\";\r\n public static Path: string = \"Path\";\r\n public static RequestId: string = \"X-RequestId\";\r\n public static RequestStreamId: string = \"X-StreamId\";\r\n public static RequestTimestamp: string = \"X-Timestamp\";\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport interface IAuthentication {\r\n fetch(authFetchEventId: string): Promise;\r\n fetchOnExpiry(authFetchEventId: string): Promise;\r\n}\r\n\r\nexport class AuthInfo {\r\n private privHeaderName: string;\r\n private privToken: string;\r\n\r\n public constructor(headerName: string, token: string) {\r\n this.privHeaderName = headerName;\r\n this.privToken = token;\r\n }\r\n\r\n public get headerName(): string {\r\n return this.privHeaderName;\r\n }\r\n\r\n public get token(): string {\r\n return this.privToken;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary\r\n} from \"../common/Exports\";\r\nimport {\r\n PropertyId\r\n} from \"../sdk/Exports\";\r\nimport {\r\n ConnectionFactoryBase\r\n} from \"./ConnectionFactoryBase\";\r\nimport {\r\n AuthInfo,\r\n RecognizerConfig,\r\n WebsocketMessageFormatter,\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\n\r\nexport class IntentConnectionFactory extends ConnectionFactoryBase {\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint);\r\n if (!endpoint) {\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_IntentRegion);\r\n const hostSuffix = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"wss://\" + region + \".sr.speech\" + hostSuffix);\r\n endpoint = host + \"/speech/recognition/interactive/cognitiveservices/v1\";\r\n }\r\n\r\n const queryParams: IStringDictionary = {\r\n format: \"simple\",\r\n language: config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage),\r\n };\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n\r\n private getSpeechRegionFromIntentRegion(intentRegion: string): string {\r\n switch (intentRegion) {\r\n case \"West US\":\r\n case \"US West\":\r\n case \"westus\":\r\n return \"uswest\";\r\n case \"West US 2\":\r\n case \"US West 2\":\r\n case \"westus2\":\r\n return \"uswest2\";\r\n case \"South Central US\":\r\n case \"US South Central\":\r\n case \"southcentralus\":\r\n return \"ussouthcentral\";\r\n case \"West Central US\":\r\n case \"US West Central\":\r\n case \"westcentralus\":\r\n return \"uswestcentral\";\r\n case \"East US\":\r\n case \"US East\":\r\n case \"eastus\":\r\n return \"useast\";\r\n case \"East US 2\":\r\n case \"US East 2\":\r\n case \"eastus2\":\r\n return \"useast2\";\r\n case \"West Europe\":\r\n case \"Europe West\":\r\n case \"westeurope\":\r\n return \"europewest\";\r\n case \"North Europe\":\r\n case \"Europe North\":\r\n case \"northeurope\":\r\n return \"europenorth\";\r\n case \"Brazil South\":\r\n case \"South Brazil\":\r\n case \"southbrazil\":\r\n return \"brazilsouth\";\r\n case \"Australia East\":\r\n case \"East Australia\":\r\n case \"eastaustralia\":\r\n return \"australiaeast\";\r\n case \"Southeast Asia\":\r\n case \"Asia Southeast\":\r\n case \"southeastasia\":\r\n return \"asiasoutheast\";\r\n case \"East Asia\":\r\n case \"Asia East\":\r\n case \"eastasia\":\r\n return \"asiaeast\";\r\n default:\r\n return intentRegion;\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IAudioSource,\r\n MessageType,\r\n} from \"../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n IntentRecognitionCanceledEventArgs,\r\n IntentRecognitionEventArgs,\r\n IntentRecognitionResult,\r\n IntentRecognizer,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechRecognitionResult,\r\n} from \"../sdk/Exports\";\r\nimport {\r\n AddedLmIntent,\r\n CancellationErrorCodePropertyName,\r\n EnumTranslation,\r\n IntentResponse,\r\n ServiceRecognizerBase,\r\n SimpleSpeechPhrase,\r\n SpeechHypothesis,\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class IntentServiceRecognizer extends ServiceRecognizerBase {\r\n private privIntentRecognizer: IntentRecognizer;\r\n private privAddedLmIntents: { [id: string]: AddedLmIntent; };\r\n private privIntentDataSent: boolean;\r\n private privUmbrellaIntent: AddedLmIntent;\r\n private privPendingIntentArgs: IntentRecognitionEventArgs;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n recognizer: IntentRecognizer) {\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, recognizer);\r\n this.privIntentRecognizer = recognizer;\r\n this.privIntentDataSent = false;\r\n }\r\n\r\n public setIntents(addedIntents: { [id: string]: AddedLmIntent; }, umbrellaIntent: AddedLmIntent): void {\r\n this.privAddedLmIntents = addedIntents;\r\n this.privUmbrellaIntent = umbrellaIntent;\r\n this.privIntentDataSent = true;\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n let result: IntentRecognitionResult;\r\n let ev: IntentRecognitionEventArgs;\r\n let processed: boolean = false;\r\n\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n if (connectionMessage.messageType === MessageType.Text) {\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n }\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"speech.hypothesis\":\r\n const speechHypothesis: SpeechHypothesis = SpeechHypothesis.fromJSON(connectionMessage.textBody);\r\n\r\n result = new IntentRecognitionResult(\r\n undefined,\r\n this.privRequestSession.requestId,\r\n ResultReason.RecognizingIntent,\r\n speechHypothesis.Text,\r\n speechHypothesis.Duration,\r\n speechHypothesis.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n speechHypothesis.Language,\r\n speechHypothesis.LanguageDetectionConfidence,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n this.privRequestSession.onHypothesis(result.offset);\r\n\r\n ev = new IntentRecognitionEventArgs(result, speechHypothesis.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privIntentRecognizer.recognizing) {\r\n try {\r\n this.privIntentRecognizer.recognizing(this.privIntentRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.phrase\":\r\n const simple: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n result = new IntentRecognitionResult(\r\n undefined,\r\n this.privRequestSession.requestId,\r\n EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus),\r\n simple.DisplayText,\r\n simple.Duration,\r\n simple.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n simple.Language,\r\n simple.LanguageDetectionConfidence,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n ev = new IntentRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);\r\n\r\n const sendEvent: () => void = () => {\r\n if (!!this.privIntentRecognizer.recognized) {\r\n try {\r\n this.privIntentRecognizer.recognized(this.privIntentRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n };\r\n\r\n // If intent data was sent, the terminal result for this recognizer is an intent being found.\r\n // If no intent data was sent, the terminal event is speech recognition being successful.\r\n if (false === this.privIntentDataSent || ResultReason.NoMatch === ev.result.reason) {\r\n // Advance the buffers.\r\n this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration);\r\n sendEvent();\r\n } else {\r\n // Squirrel away the args, when the response event arrives it will build upon them\r\n // and then return\r\n this.privPendingIntentArgs = ev;\r\n }\r\n processed = true;\r\n break;\r\n case \"response\":\r\n // Response from LUIS\r\n ev = this.privPendingIntentArgs;\r\n this.privPendingIntentArgs = undefined;\r\n\r\n if (undefined === ev) {\r\n if (\"\" === connectionMessage.textBody) {\r\n // This condition happens if there is nothing but silence in the\r\n // audio sent to the service.\r\n return;\r\n }\r\n\r\n // Odd... Not sure this can happen\r\n ev = new IntentRecognitionEventArgs(new IntentRecognitionResult(), 0 /*TODO*/, this.privRequestSession.sessionId);\r\n }\r\n\r\n const intentResponse: IntentResponse = IntentResponse.fromJSON(connectionMessage.textBody);\r\n\r\n // If LUIS didn't return anything, send the existing event, else\r\n // modify it to show the match.\r\n // See if the intent found is in the list of intents asked for.\r\n let addedIntent: AddedLmIntent = this.privAddedLmIntents[intentResponse.topScoringIntent.intent];\r\n\r\n if (this.privUmbrellaIntent !== undefined) {\r\n addedIntent = this.privUmbrellaIntent;\r\n }\r\n\r\n if (null !== intentResponse && addedIntent !== undefined) {\r\n const intentId = addedIntent.intentName === undefined ? intentResponse.topScoringIntent.intent : addedIntent.intentName;\r\n let reason = ev.result.reason;\r\n\r\n if (undefined !== intentId) {\r\n reason = ResultReason.RecognizedIntent;\r\n }\r\n\r\n // make sure, properties is set.\r\n const properties = (undefined !== ev.result.properties) ?\r\n ev.result.properties : new PropertyCollection();\r\n\r\n properties.setProperty(PropertyId.LanguageUnderstandingServiceResponse_JsonResult, connectionMessage.textBody);\r\n\r\n ev = new IntentRecognitionEventArgs(\r\n new IntentRecognitionResult(\r\n intentId,\r\n ev.result.resultId,\r\n reason,\r\n ev.result.text,\r\n ev.result.duration,\r\n ev.result.offset,\r\n undefined,\r\n undefined,\r\n ev.result.errorDetails,\r\n ev.result.json,\r\n properties),\r\n ev.offset,\r\n ev.sessionId);\r\n }\r\n this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration);\r\n\r\n if (!!this.privIntentRecognizer.recognized) {\r\n try {\r\n this.privIntentRecognizer.recognized(this.privIntentRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(ev.result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n processed = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n if (!!this.privIntentRecognizer.canceled) {\r\n\r\n const cancelEvent: IntentRecognitionCanceledEventArgs = new IntentRecognitionCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n undefined,\r\n sessionId);\r\n try {\r\n this.privIntentRecognizer.canceled(this.privIntentRecognizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: IntentRecognitionResult = new IntentRecognitionResult(\r\n undefined, // Intent Id\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Duration\r\n undefined, // Offset\r\n undefined, // Language\r\n undefined, // LanguageDetectionConfidence\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n this.privSuccessCallback = undefined;\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport class QueryParameterNames {\r\n public static BotId: string = \"botid\";\r\n public static CustomSpeechDeploymentId: string = \"cid\";\r\n public static CustomVoiceDeploymentId: string = \"deploymentId\";\r\n public static EnableAudioLogging: string = \"storeAudio\";\r\n public static EnableLanguageId: string = \"lidEnabled\";\r\n public static EnableWordLevelTimestamps: string = \"wordLevelTimestamps\";\r\n public static EndSilenceTimeoutMs: string = \"endSilenceTimeoutMs\";\r\n public static Format: string = \"format\";\r\n public static InitialSilenceTimeoutMs: string = \"initialSilenceTimeoutMs\";\r\n public static Language: string = \"language\";\r\n public static Profanity: string = \"profanity\";\r\n public static RequestBotStatusMessages: string = \"enableBotMessageStatus\";\r\n public static StableIntermediateThreshold: string = \"stableIntermediateThreshold\";\r\n public static StableTranslation: string = \"stableTranslation\";\r\n public static TestHooks: string = \"testhooks\";\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { EventType, PlatformEvent } from \"../common/Exports\";\r\n\r\nexport class SpeechRecognitionEvent extends PlatformEvent {\r\n private privRequestId: string;\r\n private privSessionId: string;\r\n\r\n constructor(eventName: string, requestId: string, sessionId: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n\r\n this.privRequestId = requestId;\r\n this.privSessionId = sessionId;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n}\r\n\r\nexport class RecognitionTriggeredEvent extends SpeechRecognitionEvent {\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n\r\n constructor(requestId: string, sessionId: string, audioSourceId: string, audioNodeId: string) {\r\n super(\"RecognitionTriggeredEvent\", requestId, sessionId);\r\n\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n}\r\n\r\nexport class ListeningStartedEvent extends SpeechRecognitionEvent {\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n\r\n constructor(requestId: string, sessionId: string, audioSourceId: string, audioNodeId: string) {\r\n super(\"ListeningStartedEvent\", requestId, sessionId);\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n}\r\n\r\nexport class ConnectingToServiceEvent extends SpeechRecognitionEvent {\r\n private privAuthFetchEventid: string;\r\n\r\n constructor(requestId: string, authFetchEventid: string, sessionId: string) {\r\n super(\"ConnectingToServiceEvent\", requestId, sessionId);\r\n this.privAuthFetchEventid = authFetchEventid;\r\n }\r\n\r\n public get authFetchEventid(): string {\r\n return this.privAuthFetchEventid;\r\n }\r\n}\r\n\r\nexport class RecognitionStartedEvent extends SpeechRecognitionEvent {\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n private privAuthFetchEventId: string;\r\n\r\n constructor(requestId: string, audioSourceId: string, audioNodeId: string, authFetchEventId: string, sessionId: string) {\r\n super(\"RecognitionStartedEvent\", requestId, sessionId);\r\n\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n this.privAuthFetchEventId = authFetchEventId;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n\r\n public get authFetchEventId(): string {\r\n return this.privAuthFetchEventId;\r\n }\r\n}\r\n\r\nexport enum RecognitionCompletionStatus {\r\n Success,\r\n AudioSourceError,\r\n AudioSourceTimeout,\r\n AuthTokenFetchError,\r\n AuthTokenFetchTimeout,\r\n UnAuthorized,\r\n ConnectTimeout,\r\n ConnectError,\r\n ClientRecognitionActivityTimeout,\r\n UnknownError,\r\n}\r\n\r\nexport class RecognitionEndedEvent extends SpeechRecognitionEvent {\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n private privAuthFetchEventId: string;\r\n private privServiceTag: string;\r\n private privStatus: RecognitionCompletionStatus;\r\n private privError: string;\r\n\r\n constructor(\r\n requestId: string,\r\n audioSourceId: string,\r\n audioNodeId: string,\r\n authFetchEventId: string,\r\n sessionId: string,\r\n serviceTag: string,\r\n status: RecognitionCompletionStatus,\r\n error: string) {\r\n\r\n super(\"RecognitionEndedEvent\", requestId, sessionId, status === RecognitionCompletionStatus.Success ? EventType.Info : EventType.Error);\r\n\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n this.privAuthFetchEventId = authFetchEventId;\r\n this.privStatus = status;\r\n this.privError = error;\r\n this.privServiceTag = serviceTag;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n\r\n public get authFetchEventId(): string {\r\n return this.privAuthFetchEventId;\r\n }\r\n\r\n public get serviceTag(): string {\r\n return this.privServiceTag;\r\n }\r\n\r\n public get status(): RecognitionCompletionStatus {\r\n return this.privStatus;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { PropertyCollection, PropertyId } from \"../sdk/Exports\";\r\n\r\nexport enum RecognitionMode {\r\n Interactive,\r\n Conversation,\r\n Dictation,\r\n}\r\n\r\nexport enum SpeechResultFormat {\r\n Simple,\r\n Detailed,\r\n}\r\n\r\nexport class RecognizerConfig {\r\n private privRecognitionMode: RecognitionMode = RecognitionMode.Interactive;\r\n private privSpeechServiceConfig: SpeechServiceConfig;\r\n private privRecognitionActivityTimeout: number;\r\n private privParameters: PropertyCollection;\r\n private privMaxRetryCount: number;\r\n\r\n constructor(\r\n speechServiceConfig: SpeechServiceConfig,\r\n parameters: PropertyCollection) {\r\n this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new SpeechServiceConfig(new Context(null));\r\n this.privParameters = parameters;\r\n this.privMaxRetryCount = parseInt(parameters.getProperty(\"SPEECH-Error-MaxRetryCount\", \"4\"), 10);\r\n }\r\n\r\n public get parameters(): PropertyCollection {\r\n return this.privParameters;\r\n }\r\n\r\n public get recognitionMode(): RecognitionMode {\r\n return this.privRecognitionMode;\r\n }\r\n\r\n public set recognitionMode(value: RecognitionMode) {\r\n this.privRecognitionMode = value;\r\n this.privRecognitionActivityTimeout = value === RecognitionMode.Interactive ? 8000 : 25000;\r\n this.privSpeechServiceConfig.Recognition = RecognitionMode[value];\r\n }\r\n\r\n public get SpeechServiceConfig(): SpeechServiceConfig {\r\n return this.privSpeechServiceConfig;\r\n }\r\n\r\n public get recognitionActivityTimeout(): number {\r\n return this.privRecognitionActivityTimeout;\r\n }\r\n\r\n public get isContinuousRecognition(): boolean {\r\n return this.privRecognitionMode !== RecognitionMode.Interactive;\r\n }\r\n\r\n public get autoDetectSourceLanguages(): string {\r\n return this.parameters.getProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, undefined);\r\n }\r\n\r\n public get maxRetryCount(): number {\r\n return this.privMaxRetryCount;\r\n }\r\n}\r\n\r\n// The config is serialized and sent as the Speech.Config\r\nexport class SpeechServiceConfig {\r\n private context: Context;\r\n private recognition: string;\r\n\r\n constructor(context: Context) {\r\n this.context = context;\r\n }\r\n\r\n public serialize = (): string => {\r\n return JSON.stringify(this, (key: any, value: any): any => {\r\n if (value && typeof value === \"object\") {\r\n const replacement: any = {};\r\n for (const k in value) {\r\n if (Object.hasOwnProperty.call(value, k)) {\r\n replacement[k && k.charAt(0).toLowerCase() + k.substring(1)] = value[k];\r\n }\r\n }\r\n return replacement;\r\n }\r\n return value;\r\n });\r\n }\r\n\r\n public get Context(): Context {\r\n return this.context;\r\n }\r\n\r\n public get Recognition(): string {\r\n return this.recognition;\r\n }\r\n\r\n public set Recognition(value: string) {\r\n this.recognition = value.toLowerCase();\r\n }\r\n}\r\n\r\nexport class Context {\r\n public system: System;\r\n public os: OS;\r\n public audio: ISpeechConfigAudio;\r\n\r\n constructor(os: OS) {\r\n this.system = new System();\r\n this.os = os;\r\n }\r\n}\r\n\r\nexport class System {\r\n public name: string;\r\n public version: string;\r\n public build: string;\r\n public lang: string;\r\n\r\n constructor() {\r\n // Note: below will be patched for official builds.\r\n const SPEECHSDK_CLIENTSDK_VERSION = \"1.17.0\";\r\n\r\n this.name = \"SpeechSDK\";\r\n this.version = SPEECHSDK_CLIENTSDK_VERSION;\r\n this.build = \"JavaScript\";\r\n this.lang = \"JavaScript\";\r\n }\r\n}\r\n\r\nexport class OS {\r\n public platform: string;\r\n public name: string;\r\n public version: string;\r\n\r\n constructor(platform: string, name: string, version: string) {\r\n this.platform = platform;\r\n this.name = name;\r\n this.version = version;\r\n }\r\n}\r\n\r\nexport class Device {\r\n public manufacturer: string;\r\n public model: string;\r\n public version: string;\r\n\r\n constructor(manufacturer: string, model: string, version: string) {\r\n this.manufacturer = manufacturer;\r\n this.model = model;\r\n this.version = version;\r\n }\r\n}\r\n\r\nexport interface ISpeechConfigAudio {\r\n source?: ISpeechConfigAudioDevice;\r\n playback?: ISpeechConfigAudioDevice;\r\n}\r\n\r\nexport interface ISpeechConfigAudioDevice {\r\n manufacturer: string;\r\n model: string;\r\n connectivity: connectivity;\r\n type: type;\r\n samplerate: number;\r\n bitspersample: number;\r\n channelcount: number;\r\n}\r\n\r\nexport enum connectivity {\r\n Bluetooth = \"Bluetooth\",\r\n Wired = \"Wired\",\r\n WiFi = \"WiFi\",\r\n Cellular = \"Cellular\",\r\n InBuilt = \"InBuilt\",\r\n Unknown = \"Unknown\",\r\n}\r\n\r\nexport enum type {\r\n Phone = \"Phone\",\r\n Speaker = \"Speaker\",\r\n Car = \"Car\",\r\n Headset = \"Headset\",\r\n Thermostat = \"Thermostat\",\r\n Microphones = \"Microphones\",\r\n Deskphone = \"Deskphone\",\r\n RemoteControl = \"RemoteControl\",\r\n Unknown = \"Unknown\",\r\n File = \"File\",\r\n Stream = \"Stream\",\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Z_NO_COMPRESSION } from \"zlib\";\r\nimport { ReplayableAudioNode } from \"../common.browser/Exports\";\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n Events,\r\n IDetachable,\r\n IEventSource,\r\n PlatformEvent\r\n} from \"../common/Exports\";\r\nimport {\r\n ConnectingToServiceEvent,\r\n ListeningStartedEvent,\r\n RecognitionStartedEvent,\r\n RecognitionTriggeredEvent,\r\n SpeechRecognitionEvent,\r\n} from \"./RecognitionEvents\";\r\nimport { ServiceTelemetryListener } from \"./ServiceTelemetryListener.Internal\";\r\n\r\nexport class RequestSession {\r\n private privIsDisposed: boolean = false;\r\n private privServiceTelemetryListener: ServiceTelemetryListener;\r\n private privDetachables: IDetachable[] = new Array();\r\n private privRequestId: string;\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n private privAudioNode: ReplayableAudioNode;\r\n private privAuthFetchEventId: string;\r\n private privIsAudioNodeDetached: boolean = false;\r\n private privIsRecognizing: boolean = false;\r\n private privIsSpeechEnded: boolean = false;\r\n private privTurnStartAudioOffset: number = 0;\r\n private privLastRecoOffset: number = 0;\r\n private privHypothesisReceived: boolean = false;\r\n private privBytesSent: number = 0;\r\n private privRecogNumber: number = 0;\r\n private privSessionId: string;\r\n private privTurnDeferral: Deferred;\r\n private privInTurn: boolean = false;\r\n private privConnectionAttempts: number = 0;\r\n\r\n constructor(audioSourceId: string) {\r\n this.privAudioSourceId = audioSourceId;\r\n this.privRequestId = createNoDashGuid();\r\n this.privAudioNodeId = createNoDashGuid();\r\n this.privTurnDeferral = new Deferred();\r\n\r\n // We're not in a turn, so resolve.\r\n this.privTurnDeferral.resolve();\r\n }\r\n\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n\r\n public get turnCompletionPromise(): Promise {\r\n return this.privTurnDeferral.promise;\r\n }\r\n\r\n public get isSpeechEnded(): boolean {\r\n return this.privIsSpeechEnded;\r\n }\r\n\r\n public get isRecognizing(): boolean {\r\n return this.privIsRecognizing;\r\n }\r\n\r\n public get currentTurnAudioOffset(): number {\r\n return this.privTurnStartAudioOffset;\r\n }\r\n\r\n public get recogNumber(): number {\r\n return this.privRecogNumber;\r\n }\r\n\r\n public get numConnectionAttempts(): number {\r\n return this.privConnectionAttempts;\r\n }\r\n\r\n // The number of bytes sent for the current connection.\r\n // Counter is reset to 0 each time a connection is established.\r\n public get bytesSent(): number {\r\n return this.privBytesSent;\r\n }\r\n public listenForServiceTelemetry(eventSource: IEventSource): void {\r\n if (!!this.privServiceTelemetryListener) {\r\n this.privDetachables.push(eventSource.attachListener(this.privServiceTelemetryListener));\r\n }\r\n }\r\n\r\n public startNewRecognition(): void {\r\n this.privIsSpeechEnded = false;\r\n this.privIsRecognizing = true;\r\n this.privTurnStartAudioOffset = 0;\r\n this.privLastRecoOffset = 0;\r\n this.privRequestId = createNoDashGuid();\r\n this.privRecogNumber++;\r\n this.privServiceTelemetryListener = new ServiceTelemetryListener(this.privRequestId, this.privAudioSourceId, this.privAudioNodeId);\r\n this.onEvent(new RecognitionTriggeredEvent(this.requestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId));\r\n }\r\n\r\n public async onAudioSourceAttachCompleted(audioNode: ReplayableAudioNode, isError: boolean, error?: string): Promise {\r\n this.privAudioNode = audioNode;\r\n this.privIsAudioNodeDetached = false;\r\n\r\n if (isError) {\r\n await this.onComplete();\r\n } else {\r\n this.onEvent(new ListeningStartedEvent(this.privRequestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId));\r\n }\r\n }\r\n\r\n public onPreConnectionStart = (authFetchEventId: string, connectionId: string): void => {\r\n this.privAuthFetchEventId = authFetchEventId;\r\n this.privSessionId = connectionId;\r\n this.onEvent(new ConnectingToServiceEvent(this.privRequestId, this.privAuthFetchEventId, this.privSessionId));\r\n }\r\n\r\n public async onAuthCompleted(isError: boolean, error?: string): Promise {\r\n if (isError) {\r\n await this.onComplete();\r\n }\r\n }\r\n\r\n public async onConnectionEstablishCompleted(statusCode: number, reason?: string): Promise {\r\n if (statusCode === 200) {\r\n this.onEvent(new RecognitionStartedEvent(this.requestId, this.privAudioSourceId, this.privAudioNodeId, this.privAuthFetchEventId, this.privSessionId));\r\n if (!!this.privAudioNode) {\r\n this.privAudioNode.replay();\r\n }\r\n this.privTurnStartAudioOffset = this.privLastRecoOffset;\r\n this.privBytesSent = 0;\r\n return;\r\n } else if (statusCode === 403) {\r\n await this.onComplete();\r\n }\r\n }\r\n\r\n public async onServiceTurnEndResponse(continuousRecognition: boolean): Promise {\r\n this.privTurnDeferral.resolve();\r\n\r\n if (!continuousRecognition || this.isSpeechEnded) {\r\n await this.onComplete();\r\n this.privInTurn = false;\r\n } else {\r\n // Start a new request set.\r\n this.privTurnStartAudioOffset = this.privLastRecoOffset;\r\n this.privRequestId = createNoDashGuid();\r\n this.privAudioNode.replay();\r\n }\r\n }\r\n\r\n public onServiceTurnStartResponse = (): void => {\r\n if (!!this.privTurnDeferral && !!this.privInTurn) {\r\n // What? How are we starting a turn with another not done?\r\n this.privTurnDeferral.reject(\"Another turn started before current completed.\");\r\n // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited\r\n /* tslint:disable:no-empty */\r\n this.privTurnDeferral.promise.then().catch(() => { });\r\n }\r\n this.privInTurn = true;\r\n this.privTurnDeferral = new Deferred();\r\n }\r\n\r\n public onHypothesis(offset: number): void {\r\n if (!this.privHypothesisReceived) {\r\n this.privHypothesisReceived = true;\r\n this.privServiceTelemetryListener.hypothesisReceived(this.privAudioNode.findTimeAtOffset(offset));\r\n }\r\n }\r\n\r\n public onPhraseRecognized(offset: number): void {\r\n this.privServiceTelemetryListener.phraseReceived(this.privAudioNode.findTimeAtOffset(offset));\r\n this.onServiceRecognized(offset);\r\n }\r\n\r\n public onServiceRecognized(offset: number): void {\r\n this.privLastRecoOffset = offset;\r\n this.privHypothesisReceived = false;\r\n this.privAudioNode.shrinkBuffers(offset);\r\n this.privConnectionAttempts = 0;\r\n }\r\n\r\n public onAudioSent(bytesSent: number): void {\r\n this.privBytesSent += bytesSent;\r\n }\r\n\r\n public onRetryConnection(): void {\r\n this.privConnectionAttempts++;\r\n }\r\n\r\n public async dispose(error?: string): Promise {\r\n if (!this.privIsDisposed) {\r\n // we should have completed by now. If we did not its an unknown error.\r\n this.privIsDisposed = true;\r\n for (const detachable of this.privDetachables) {\r\n await detachable.detach();\r\n }\r\n\r\n this.privServiceTelemetryListener.dispose();\r\n this.privIsRecognizing = false;\r\n }\r\n }\r\n\r\n public getTelemetry = (): string => {\r\n if (this.privServiceTelemetryListener.hasTelemetry) {\r\n return this.privServiceTelemetryListener.getTelemetry();\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n public async onStopRecognizing(): Promise {\r\n await this.onComplete();\r\n }\r\n\r\n // Should be called with the audioNode for this session has indicated that it is out of speech.\r\n public onSpeechEnded(): void {\r\n this.privIsSpeechEnded = true;\r\n }\r\n\r\n protected onEvent = (event: SpeechRecognitionEvent): void => {\r\n if (!!this.privServiceTelemetryListener) {\r\n this.privServiceTelemetryListener.onEvent(event);\r\n }\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private async onComplete(): Promise {\r\n if (!!this.privIsRecognizing) {\r\n this.privIsRecognizing = false;\r\n await this.detachAudioNode();\r\n }\r\n }\r\n\r\n private async detachAudioNode(): Promise {\r\n if (!this.privIsAudioNodeDetached) {\r\n this.privIsAudioNodeDetached = true;\r\n if (this.privAudioNode) {\r\n await this.privAudioNode.detach();\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// response\r\n\r\nexport interface IActivityPayloadResponse {\r\n conversationId: string;\r\n messageDataStreamType: number;\r\n messagePayload: any;\r\n version: number;\r\n}\r\n\r\nexport class ActivityPayloadResponse implements IActivityPayloadResponse {\r\n private privActivityResponse: IActivityPayloadResponse;\r\n\r\n private constructor(json: string) {\r\n this.privActivityResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): ActivityPayloadResponse {\r\n return new ActivityPayloadResponse(json);\r\n }\r\n\r\n public get conversationId(): string {\r\n return this.privActivityResponse.conversationId;\r\n }\r\n\r\n public get messageDataStreamType(): number {\r\n return this.privActivityResponse.messageDataStreamType;\r\n }\r\n\r\n public get messagePayload(): any {\r\n return this.privActivityResponse.messagePayload;\r\n }\r\n\r\n public get version(): number {\r\n return this.privActivityResponse.version;\r\n }\r\n}\r\n\r\nexport enum MessageDataStreamType {\r\n None = 0,\r\n TextToSpeechAudio = 1,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IPrimaryLanguage, RecognitionStatus } from \"../Exports\";\r\n\r\n// speech.phrase for detailed\r\nexport interface IDetailedSpeechPhrase {\r\n RecognitionStatus: RecognitionStatus;\r\n NBest: IPhrase[];\r\n Duration?: number;\r\n Offset?: number;\r\n PrimaryLanguage?: IPrimaryLanguage;\r\n}\r\n\r\nexport interface IPhrase {\r\n Confidence?: number;\r\n Lexical: string;\r\n ITN: string;\r\n MaskedITN: string;\r\n Display: string;\r\n}\r\n\r\nexport class DetailedSpeechPhrase implements IDetailedSpeechPhrase {\r\n private privDetailedSpeechPhrase: IDetailedSpeechPhrase;\r\n\r\n private constructor(json: string) {\r\n this.privDetailedSpeechPhrase = JSON.parse(json);\r\n this.privDetailedSpeechPhrase.RecognitionStatus = (RecognitionStatus as any)[this.privDetailedSpeechPhrase.RecognitionStatus];\r\n }\r\n\r\n public static fromJSON(json: string): DetailedSpeechPhrase {\r\n return new DetailedSpeechPhrase(json);\r\n }\r\n\r\n public get RecognitionStatus(): RecognitionStatus {\r\n return this.privDetailedSpeechPhrase.RecognitionStatus;\r\n }\r\n public get NBest(): IPhrase[] {\r\n return this.privDetailedSpeechPhrase.NBest;\r\n }\r\n public get Duration(): number {\r\n return this.privDetailedSpeechPhrase.Duration;\r\n }\r\n public get Offset(): number {\r\n return this.privDetailedSpeechPhrase.Offset;\r\n }\r\n public get Language(): string {\r\n return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Language;\r\n }\r\n public get LanguageDetectionConfidence(): string {\r\n return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Confidence;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * @class SynthesisStatus\r\n * @private\r\n */\r\nexport enum SynthesisStatus {\r\n /**\r\n * The response contains valid audio data.\r\n * @member SynthesisStatus.Success\r\n */\r\n Success,\r\n\r\n /**\r\n * Indicates the end of audio data. No valid audio data is included in the message.\r\n * @member SynthesisStatus.SynthesisEnd\r\n */\r\n SynthesisEnd,\r\n\r\n /**\r\n * Indicates an error occurred during synthesis data processing.\r\n * @member SynthesisStatus.Error\r\n */\r\n Error,\r\n}\r\n\r\nexport enum RecognitionStatus {\r\n Success,\r\n NoMatch,\r\n InitialSilenceTimeout,\r\n BabbleTimeout,\r\n Error,\r\n EndOfDictation,\r\n TooManyRequests,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n// response\r\n\r\nexport interface IIntentResponse {\r\n query: string;\r\n topScoringIntent: ISingleIntent;\r\n entities: IIntentEntity[];\r\n}\r\n\r\nexport interface IIntentEntity {\r\n entity: string;\r\n type: string;\r\n startIndex: number;\r\n endIndex: number;\r\n score: number;\r\n}\r\n\r\nexport interface ISingleIntent {\r\n intent: string;\r\n score: number;\r\n}\r\n\r\nexport class IntentResponse implements IIntentResponse {\r\n private privIntentResponse: IIntentResponse;\r\n\r\n private constructor(json: string) {\r\n this.privIntentResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): IntentResponse {\r\n return new IntentResponse(json);\r\n }\r\n\r\n public get query(): string {\r\n return this.privIntentResponse.query;\r\n }\r\n\r\n public get topScoringIntent(): ISingleIntent {\r\n return this.privIntentResponse.topScoringIntent;\r\n }\r\n\r\n public get entities(): IIntentEntity[] {\r\n return this.privIntentResponse.entities;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { RecognitionStatus } from \"../Exports\";\r\n\r\n// speech.phrase\r\nexport interface ISimpleSpeechPhrase {\r\n RecognitionStatus: RecognitionStatus;\r\n DisplayText: string;\r\n Offset?: number;\r\n Duration?: number;\r\n PrimaryLanguage?: IPrimaryLanguage;\r\n SpeakerId?: string;\r\n}\r\n\r\nexport interface IPrimaryLanguage {\r\n Language: string;\r\n Confidence: string;\r\n}\r\n\r\nexport class SimpleSpeechPhrase implements ISimpleSpeechPhrase {\r\n private privSimpleSpeechPhrase: ISimpleSpeechPhrase;\r\n\r\n private constructor(json: string) {\r\n this.privSimpleSpeechPhrase = JSON.parse(json);\r\n this.privSimpleSpeechPhrase.RecognitionStatus = (RecognitionStatus as any)[this.privSimpleSpeechPhrase.RecognitionStatus];\r\n }\r\n\r\n public static fromJSON(json: string): SimpleSpeechPhrase {\r\n return new SimpleSpeechPhrase(json);\r\n }\r\n\r\n public get RecognitionStatus(): RecognitionStatus {\r\n return this.privSimpleSpeechPhrase.RecognitionStatus;\r\n }\r\n\r\n public get DisplayText(): string {\r\n return this.privSimpleSpeechPhrase.DisplayText;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privSimpleSpeechPhrase.Offset;\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privSimpleSpeechPhrase.Duration;\r\n }\r\n\r\n public get Language(): string {\r\n return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Language;\r\n }\r\n\r\n public get LanguageDetectionConfidence(): string {\r\n return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Confidence;\r\n }\r\n\r\n public get SpeakerId(): string {\r\n return this.privSimpleSpeechPhrase.SpeakerId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// speech.endDetected\r\nexport interface ISpeechDetected {\r\n Offset: number;\r\n}\r\n\r\nexport class SpeechDetected implements ISpeechDetected {\r\n private privSpeechStartDetected: ISpeechDetected;\r\n\r\n private constructor(json: string) {\r\n this.privSpeechStartDetected = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SpeechDetected {\r\n return new SpeechDetected(json);\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privSpeechStartDetected.Offset;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IPrimaryLanguage } from \"./SimpleSpeechPhrase\";\r\n\r\n// speech.hypothesis\r\nexport interface ISpeechHypothesis {\r\n Text: string;\r\n Offset: number;\r\n Duration: number;\r\n PrimaryLanguage?: IPrimaryLanguage;\r\n SpeakerId?: string;\r\n}\r\n\r\nexport class SpeechHypothesis implements ISpeechHypothesis {\r\n private privSpeechHypothesis: ISpeechHypothesis;\r\n\r\n private constructor(json: string) {\r\n this.privSpeechHypothesis = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SpeechHypothesis {\r\n return new SpeechHypothesis(json);\r\n }\r\n\r\n public get Text(): string {\r\n return this.privSpeechHypothesis.Text;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privSpeechHypothesis.Offset;\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privSpeechHypothesis.Duration;\r\n }\r\n\r\n public get Language(): string {\r\n return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Language;\r\n }\r\n\r\n public get LanguageDetectionConfidence(): string {\r\n return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Confidence;\r\n }\r\n\r\n public get SpeakerId(): string {\r\n return this.privSpeechHypothesis.SpeakerId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// speech.keyword\r\nexport interface ISpeechKeyword {\r\n Status: string;\r\n Text: string;\r\n Offset: number;\r\n Duration: number;\r\n}\r\n\r\nexport class SpeechKeyword implements ISpeechKeyword {\r\n private privSpeechKeyword: ISpeechKeyword;\r\n\r\n private constructor(json: string) {\r\n this.privSpeechKeyword = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SpeechKeyword {\r\n return new SpeechKeyword(json);\r\n }\r\n\r\n public get Status(): string {\r\n return this.privSpeechKeyword.Status;\r\n }\r\n\r\n public get Text(): string {\r\n return this.privSpeechKeyword.Text;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privSpeechKeyword.Offset;\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privSpeechKeyword.Duration;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport enum MetadataType {\r\n WordBoundary = \"WordBoundary\",\r\n Bookmark = \"Bookmark\",\r\n Viseme = \"Viseme\"\r\n}\r\n\r\nexport interface ISynthesisMetadata {\r\n Type: MetadataType;\r\n Data: {\r\n Offset: number;\r\n text: {\r\n Text: string;\r\n Length: number;\r\n };\r\n Bookmark: string;\r\n VisemeId: number;\r\n AnimationChunk: string;\r\n IsLastAnimation: boolean;\r\n };\r\n}\r\n\r\n// audio.metadata\r\nexport interface ISynthesisAudioMetadata {\r\n Metadata: ISynthesisMetadata[];\r\n}\r\n\r\nexport class SynthesisAudioMetadata implements ISynthesisAudioMetadata {\r\n private privSynthesisAudioMetadata: ISynthesisAudioMetadata;\r\n\r\n private constructor(json: string) {\r\n this.privSynthesisAudioMetadata = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SynthesisAudioMetadata {\r\n return new SynthesisAudioMetadata(json);\r\n }\r\n\r\n public get Metadata(): ISynthesisMetadata[] {\r\n return this.privSynthesisAudioMetadata.Metadata;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ITranslations } from \"../Exports\";\r\nimport { TranslationStatus } from \"../TranslationStatus\";\r\n\r\n// translation.hypothesis\r\nexport interface ITranslationHypothesis {\r\n Duration: number;\r\n Offset: number;\r\n Text: string;\r\n Translation: ITranslations;\r\n}\r\n\r\nexport class TranslationHypothesis implements ITranslationHypothesis {\r\n private privTranslationHypothesis: ITranslationHypothesis;\r\n\r\n private constructor(json: string) {\r\n this.privTranslationHypothesis = JSON.parse(json);\r\n this.privTranslationHypothesis.Translation.TranslationStatus = (TranslationStatus as any)[this.privTranslationHypothesis.Translation.TranslationStatus];\r\n }\r\n\r\n public static fromJSON(json: string): TranslationHypothesis {\r\n return new TranslationHypothesis(json);\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privTranslationHypothesis.Duration;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privTranslationHypothesis.Offset;\r\n }\r\n\r\n public get Text(): string {\r\n return this.privTranslationHypothesis.Text;\r\n }\r\n\r\n public get Translation(): ITranslations {\r\n return this.privTranslationHypothesis.Translation;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ITranslations, RecognitionStatus } from \"../Exports\";\r\nimport { TranslationStatus } from \"../TranslationStatus\";\r\n\r\n// translation.phrase\r\nexport interface ITranslationPhrase {\r\n RecognitionStatus: RecognitionStatus;\r\n Offset: number;\r\n Duration: number;\r\n Text: string;\r\n Translation: ITranslations;\r\n}\r\n\r\nexport class TranslationPhrase implements ITranslationPhrase {\r\n private privTranslationPhrase: ITranslationPhrase;\r\n\r\n private constructor(json: string) {\r\n this.privTranslationPhrase = JSON.parse(json);\r\n this.privTranslationPhrase.RecognitionStatus = (RecognitionStatus as any)[this.privTranslationPhrase.RecognitionStatus];\r\n if (this.privTranslationPhrase.Translation !== undefined) {\r\n this.privTranslationPhrase.Translation.TranslationStatus = (TranslationStatus as any)[this.privTranslationPhrase.Translation.TranslationStatus];\r\n }\r\n }\r\n\r\n public static fromJSON(json: string): TranslationPhrase {\r\n return new TranslationPhrase(json);\r\n }\r\n\r\n public get RecognitionStatus(): RecognitionStatus {\r\n return this.privTranslationPhrase.RecognitionStatus;\r\n }\r\n\r\n public get Offset(): number {\r\n return this.privTranslationPhrase.Offset;\r\n }\r\n\r\n public get Duration(): number {\r\n return this.privTranslationPhrase.Duration;\r\n }\r\n\r\n public get Text(): string {\r\n return this.privTranslationPhrase.Text;\r\n }\r\n\r\n public get Translation(): ITranslations {\r\n return this.privTranslationPhrase.Translation;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { SynthesisStatus } from \"../Exports\";\r\n\r\n// translation.synthesis.end\r\nexport interface ITranslationSynthesisEnd {\r\n SynthesisStatus: SynthesisStatus;\r\n FailureReason: string;\r\n}\r\n\r\nexport class TranslationSynthesisEnd implements ITranslationSynthesisEnd {\r\n private privSynthesisEnd: ITranslationSynthesisEnd;\r\n\r\n private constructor(json: string) {\r\n this.privSynthesisEnd = JSON.parse(json);\r\n this.privSynthesisEnd.SynthesisStatus = (SynthesisStatus as any)[this.privSynthesisEnd.SynthesisStatus];\r\n }\r\n\r\n public static fromJSON(json: string): TranslationSynthesisEnd {\r\n return new TranslationSynthesisEnd(json);\r\n }\r\n\r\n public get SynthesisStatus(): SynthesisStatus {\r\n return this.privSynthesisEnd.SynthesisStatus;\r\n }\r\n\r\n public get FailureReason(): string {\r\n return this.privSynthesisEnd.FailureReason;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport interface ITurnStatusResponsePayload {\r\n interactionId: string;\r\n conversationId: string;\r\n statusCode: any;\r\n}\r\n\r\nexport class TurnStatusResponsePayload implements ITurnStatusResponsePayload {\r\n private privMessageStatusResponse: ITurnStatusResponsePayload;\r\n\r\n private constructor(json: string) {\r\n this.privMessageStatusResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): TurnStatusResponsePayload {\r\n return new TurnStatusResponsePayload(json);\r\n }\r\n\r\n public get interactionId(): string {\r\n return this.privMessageStatusResponse.interactionId;\r\n }\r\n\r\n public get conversationId(): string {\r\n return this.privMessageStatusResponse.conversationId;\r\n }\r\n\r\n public get statusCode(): any {\r\n // Payloads may contain a limited set of textual representations or a numeric status\r\n // code. The textual values are here converted into numeric ones.\r\n switch (this.privMessageStatusResponse.statusCode) {\r\n case \"Success\":\r\n return 200;\r\n case \"Failed\":\r\n return 400;\r\n case \"TimedOut\":\r\n return 429;\r\n default:\r\n return this.privMessageStatusResponse.statusCode;\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ReplayableAudioNode } from \"../common.browser/Exports\";\r\nimport { ConnectionOpenResponse } from \"../common/ConnectionOpenResponse\";\r\nimport {\r\n ArgumentNullError,\r\n ConnectionClosedEvent,\r\n ConnectionEvent,\r\n ConnectionState,\r\n createNoDashGuid,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IConnection,\r\n IDisposable,\r\n IStreamChunk,\r\n MessageType,\r\n ServiceEvent,\r\n Timeout\r\n} from \"../common/Exports\";\r\nimport { AudioStreamFormatImpl } from \"../sdk/Audio/AudioStreamFormat\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyId,\r\n RecognitionEventArgs,\r\n Recognizer,\r\n SessionEventArgs,\r\n SpeechRecognitionResult,\r\n} from \"../sdk/Exports\";\r\nimport { Callback } from \"../sdk/Transcription/IConversation\";\r\nimport {\r\n AgentConfig,\r\n DynamicGrammarBuilder,\r\n ISpeechConfigAudioDevice,\r\n RecognitionMode,\r\n RequestSession,\r\n SpeechContext,\r\n SpeechDetected,\r\n type\r\n} from \"./Exports\";\r\nimport {\r\n AuthInfo,\r\n IAuthentication,\r\n} from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\nexport abstract class ServiceRecognizerBase implements IDisposable {\r\n private privAuthentication: IAuthentication;\r\n private privConnectionFactory: IConnectionFactory;\r\n\r\n // A promise for a configured connection.\r\n // Do not consume directly, call fetchConnection instead.\r\n private privConnectionConfigurationPromise: Promise;\r\n\r\n // A promise for a connection, but one that has not had the speech context sent yet.\r\n // Do not consume directly, call fetchConnection instead.\r\n private privConnectionPromise: Promise;\r\n private privAuthFetchEventId: string;\r\n private privIsDisposed: boolean;\r\n private privMustReportEndOfStream: boolean;\r\n private privConnectionEvents: EventSource;\r\n private privServiceEvents: EventSource;\r\n private privDynamicGrammar: DynamicGrammarBuilder;\r\n private privAgentConfig: AgentConfig;\r\n private privServiceHasSentMessage: boolean;\r\n private privActivityTemplate: string;\r\n private privSetTimeout: (cb: () => void, delay: number) => number = setTimeout;\r\n private privAudioSource: IAudioSource;\r\n private privIsLiveAudio: boolean = false;\r\n protected privSpeechContext: SpeechContext;\r\n protected privRequestSession: RequestSession;\r\n protected privConnectionId: string;\r\n protected privRecognizerConfig: RecognizerConfig;\r\n protected privRecognizer: Recognizer;\r\n protected privSuccessCallback: (e: SpeechRecognitionResult) => void;\r\n protected privErrorCallback: (e: string) => void;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n recognizer: Recognizer) {\r\n\r\n if (!authentication) {\r\n throw new ArgumentNullError(\"authentication\");\r\n }\r\n\r\n if (!connectionFactory) {\r\n throw new ArgumentNullError(\"connectionFactory\");\r\n }\r\n\r\n if (!audioSource) {\r\n throw new ArgumentNullError(\"audioSource\");\r\n }\r\n\r\n if (!recognizerConfig) {\r\n throw new ArgumentNullError(\"recognizerConfig\");\r\n }\r\n\r\n this.privMustReportEndOfStream = false;\r\n this.privAuthentication = authentication;\r\n this.privConnectionFactory = connectionFactory;\r\n this.privAudioSource = audioSource;\r\n this.privRecognizerConfig = recognizerConfig;\r\n this.privIsDisposed = false;\r\n this.privRecognizer = recognizer;\r\n this.privRequestSession = new RequestSession(this.privAudioSource.id());\r\n this.privConnectionEvents = new EventSource();\r\n this.privServiceEvents = new EventSource();\r\n this.privDynamicGrammar = new DynamicGrammarBuilder();\r\n this.privSpeechContext = new SpeechContext(this.privDynamicGrammar);\r\n this.privAgentConfig = new AgentConfig();\r\n if (typeof (Blob) !== \"undefined\" && typeof (Worker) !== \"undefined\") {\r\n this.privSetTimeout = Timeout.setTimeout;\r\n }\r\n\r\n this.connectionEvents.attach(async (connectionEvent: ConnectionEvent): Promise => {\r\n if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n const connectionClosedEvent = connectionEvent as ConnectionClosedEvent;\r\n if (connectionClosedEvent.statusCode === 1003 ||\r\n connectionClosedEvent.statusCode === 1007 ||\r\n connectionClosedEvent.statusCode === 1002 ||\r\n connectionClosedEvent.statusCode === 4000 ||\r\n this.privRequestSession.numConnectionAttempts > this.privRecognizerConfig.maxRetryCount\r\n ) {\r\n await this.cancelRecognitionLocal(CancellationReason.Error,\r\n connectionClosedEvent.statusCode === 1007 ? CancellationErrorCode.BadRequestParameters : CancellationErrorCode.ConnectionFailure,\r\n connectionClosedEvent.reason + \" websocket error code: \" + connectionClosedEvent.statusCode);\r\n }\r\n }\r\n });\r\n }\r\n\r\n public get audioSource(): IAudioSource {\r\n return this.privAudioSource;\r\n }\r\n\r\n public get speechContext(): SpeechContext {\r\n return this.privSpeechContext;\r\n }\r\n\r\n public get dynamicGrammar(): DynamicGrammarBuilder {\r\n return this.privDynamicGrammar;\r\n }\r\n\r\n public get agentConfig(): AgentConfig {\r\n return this.privAgentConfig;\r\n }\r\n\r\n public set conversationTranslatorToken(token: string) {\r\n this.privRecognizerConfig.parameters.setProperty(PropertyId.ConversationTranslator_Token, token);\r\n }\r\n\r\n public set authentication(auth: IAuthentication) {\r\n this.privAuthentication = this.authentication;\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public async dispose(reason?: string): Promise {\r\n this.privIsDisposed = true;\r\n if (this.privConnectionConfigurationPromise) {\r\n try {\r\n const connection: IConnection = await this.privConnectionConfigurationPromise;\r\n await connection.dispose(reason);\r\n } catch (error) {\r\n // The connection is in a bad state. But we're trying to kill it, so...\r\n return;\r\n }\r\n }\r\n }\r\n\r\n public get connectionEvents(): EventSource {\r\n return this.privConnectionEvents;\r\n }\r\n\r\n public get serviceEvents(): EventSource {\r\n return this.privServiceEvents;\r\n }\r\n\r\n public get recognitionMode(): RecognitionMode {\r\n return this.privRecognizerConfig.recognitionMode;\r\n }\r\n\r\n protected recognizeOverride: (recoMode: RecognitionMode, sc: (e: SpeechRecognitionResult) => void, ec: (e: string) => void) => any = undefined;\r\n\r\n public async recognize(\r\n recoMode: RecognitionMode,\r\n successCallback: (e: SpeechRecognitionResult) => void,\r\n errorCallBack: (e: string) => void,\r\n ): Promise {\r\n\r\n if (this.recognizeOverride !== undefined) {\r\n return this.recognizeOverride(recoMode, successCallback, errorCallBack);\r\n }\r\n // Clear the existing configuration promise to force a re-transmission of config and context.\r\n this.privConnectionConfigurationPromise = null;\r\n this.privRecognizerConfig.recognitionMode = recoMode;\r\n\r\n this.privSuccessCallback = successCallback;\r\n this.privErrorCallback = errorCallBack;\r\n\r\n this.privRequestSession.startNewRecognition();\r\n this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events);\r\n\r\n // Start the connection to the service. The promise this will create is stored and will be used by configureConnection().\r\n const conPromise: Promise = this.connectImpl();\r\n let audioNode: ReplayableAudioNode;\r\n\r\n try {\r\n const audioStreamNode: IAudioStreamNode = await this.audioSource.attach(this.privRequestSession.audioNodeId);\r\n const format: AudioStreamFormatImpl = await this.audioSource.format;\r\n const deviceInfo: ISpeechConfigAudioDevice = await this.audioSource.deviceInfo;\r\n this.privIsLiveAudio = deviceInfo.type && deviceInfo.type === type.Microphones;\r\n\r\n audioNode = new ReplayableAudioNode(audioStreamNode, format.avgBytesPerSec);\r\n await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false);\r\n this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };\r\n\r\n } catch (error) {\r\n await this.privRequestSession.onStopRecognizing();\r\n throw error;\r\n }\r\n\r\n try {\r\n await conPromise;\r\n } catch (error) {\r\n await this.cancelRecognitionLocal(CancellationReason.Error, CancellationErrorCode.ConnectionFailure, error);\r\n return;\r\n }\r\n\r\n const sessionStartEventArgs: SessionEventArgs = new SessionEventArgs(this.privRequestSession.sessionId);\r\n\r\n if (!!this.privRecognizer.sessionStarted) {\r\n this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);\r\n }\r\n\r\n const messageRetrievalPromise = this.receiveMessage();\r\n const audioSendPromise = this.sendAudio(audioNode);\r\n\r\n audioSendPromise.catch(async (error: string) => {\r\n await this.cancelRecognitionLocal(CancellationReason.Error, CancellationErrorCode.RuntimeError, error);\r\n });\r\n\r\n return;\r\n }\r\n\r\n public async stopRecognizing(): Promise {\r\n if (this.privRequestSession.isRecognizing) {\r\n try {\r\n await this.audioSource.turnOff();\r\n await this.sendFinalAudio();\r\n await this.privRequestSession.onStopRecognizing();\r\n await this.privRequestSession.turnCompletionPromise;\r\n } finally {\r\n await this.privRequestSession.dispose();\r\n }\r\n }\r\n return;\r\n }\r\n\r\n public async connect(): Promise {\r\n await this.connectImpl();\r\n return Promise.resolve();\r\n }\r\n\r\n public connectAsync(cb?: Callback, err?: Callback): void {\r\n this.connectImpl().then((connection: IConnection): void => {\r\n try {\r\n if (!!cb) {\r\n cb();\r\n }\r\n } catch (e) {\r\n if (!!err) {\r\n err(e);\r\n }\r\n }\r\n }, (reason: any): void => {\r\n try {\r\n if (!!err) {\r\n err(reason);\r\n }\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n }\r\n });\r\n }\r\n\r\n protected disconnectOverride: () => Promise = undefined;\r\n\r\n public async disconnect(): Promise {\r\n await this.cancelRecognitionLocal(CancellationReason.Error,\r\n CancellationErrorCode.NoError,\r\n \"Disconnecting\");\r\n\r\n if (this.disconnectOverride !== undefined) {\r\n await this.disconnectOverride();\r\n }\r\n\r\n try {\r\n await (await this.privConnectionPromise).dispose();\r\n } catch (error) {\r\n\r\n }\r\n\r\n this.privConnectionPromise = null;\r\n }\r\n\r\n // Called when telemetry data is sent to the service.\r\n // Used for testing Telemetry capture.\r\n public static telemetryData: (json: string) => void;\r\n public static telemetryDataEnabled: boolean = true;\r\n\r\n public sendMessage(message: string): void { }\r\n\r\n public async sendNetworkMessage(path: string, payload: string | ArrayBuffer): Promise {\r\n const type: MessageType = typeof payload === \"string\" ? MessageType.Text : MessageType.Binary;\r\n const contentType: string = typeof payload === \"string\" ? \"application/json\" : \"\";\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n return connection.send(new SpeechConnectionMessage(type, path, this.privRequestSession.requestId, contentType, payload));\r\n }\r\n\r\n public set activityTemplate(messagePayload: string) { this.privActivityTemplate = messagePayload; }\r\n public get activityTemplate(): string { return this.privActivityTemplate; }\r\n\r\n protected abstract processTypeSpecificMessages(\r\n connectionMessage: SpeechConnectionMessage,\r\n successCallback?: (e: SpeechRecognitionResult) => void,\r\n errorCallBack?: (e: string) => void): Promise;\r\n\r\n protected async sendTelemetryData(): Promise {\r\n const telemetryData = this.privRequestSession.getTelemetry();\r\n if (ServiceRecognizerBase.telemetryDataEnabled !== true ||\r\n this.privIsDisposed ||\r\n null === telemetryData) {\r\n return;\r\n }\r\n\r\n if (!!ServiceRecognizerBase.telemetryData) {\r\n try {\r\n ServiceRecognizerBase.telemetryData(telemetryData);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n await connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"telemetry\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n telemetryData));\r\n }\r\n\r\n // Cancels recognition.\r\n protected abstract cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void;\r\n\r\n // Cancels recognition.\r\n protected async cancelRecognitionLocal(\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): Promise {\r\n\r\n if (!!this.privRequestSession.isRecognizing) {\r\n await this.privRequestSession.onStopRecognizing();\r\n\r\n this.cancelRecognition(\r\n this.privRequestSession.sessionId,\r\n this.privRequestSession.requestId,\r\n cancellationReason,\r\n errorCode,\r\n error);\r\n }\r\n }\r\n\r\n protected receiveMessageOverride: () => Promise = undefined;\r\n\r\n protected async receiveMessage(): Promise {\r\n try {\r\n if (this.privIsDisposed) {\r\n // We're done.\r\n return;\r\n }\r\n\r\n let connection = await this.fetchConnection();\r\n const message = await connection.read();\r\n\r\n if (this.receiveMessageOverride !== undefined) {\r\n return this.receiveMessageOverride();\r\n }\r\n\r\n // indicates we are draining the queue and it came with no message;\r\n if (!message) {\r\n if (!this.privRequestSession.isRecognizing) {\r\n return;\r\n } else {\r\n return this.receiveMessage();\r\n }\r\n }\r\n\r\n this.privServiceHasSentMessage = true;\r\n const connectionMessage = SpeechConnectionMessage.fromConnectionMessage(message);\r\n\r\n if (connectionMessage.requestId.toLowerCase() === this.privRequestSession.requestId.toLowerCase()) {\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"turn.start\":\r\n this.privMustReportEndOfStream = true;\r\n this.privRequestSession.onServiceTurnStartResponse();\r\n break;\r\n\r\n case \"speech.startdetected\":\r\n const speechStartDetected: SpeechDetected = SpeechDetected.fromJSON(connectionMessage.textBody);\r\n const speechStartEventArgs = new RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId);\r\n if (!!this.privRecognizer.speechStartDetected) {\r\n this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs);\r\n }\r\n break;\r\n\r\n case \"speech.enddetected\":\r\n let json: string;\r\n if (connectionMessage.textBody.length > 0) {\r\n json = connectionMessage.textBody;\r\n } else {\r\n // If the request was empty, the JSON returned is empty.\r\n json = \"{ Offset: 0 }\";\r\n }\r\n const speechStopDetected: SpeechDetected = SpeechDetected.fromJSON(json);\r\n // Only shrink the buffers for continuous recognition.\r\n // For single shot, the speech.phrase message will come after the speech.end and it should own buffer shrink.\r\n if (this.privRecognizerConfig.isContinuousRecognition) {\r\n this.privRequestSession.onServiceRecognized(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset);\r\n }\r\n const speechStopEventArgs = new RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);\r\n if (!!this.privRecognizer.speechEndDetected) {\r\n this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs);\r\n }\r\n break;\r\n\r\n case \"turn.end\":\r\n await this.sendTelemetryData();\r\n if (this.privRequestSession.isSpeechEnded && this.privMustReportEndOfStream) {\r\n this.privMustReportEndOfStream = false;\r\n await this.cancelRecognitionLocal(CancellationReason.EndOfStream, CancellationErrorCode.NoError, undefined);\r\n }\r\n const sessionStopEventArgs: SessionEventArgs = new SessionEventArgs(this.privRequestSession.sessionId);\r\n await this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition);\r\n if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) {\r\n if (!!this.privRecognizer.sessionStopped) {\r\n this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs);\r\n }\r\n return;\r\n } else {\r\n connection = await this.fetchConnection();\r\n await this.sendPrePayloadJSON(connection);\r\n }\r\n break;\r\n\r\n default:\r\n if (!await this.processTypeSpecificMessages(connectionMessage)) {\r\n // here are some messages that the derived class has not processed, dispatch them to connect class\r\n if (!!this.privServiceEvents) {\r\n this.serviceEvents.onEvent(new ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));\r\n }\r\n }\r\n }\r\n }\r\n return this.receiveMessage();\r\n } catch (error) {\r\n return null;\r\n }\r\n }\r\n\r\n protected sendSpeechContext = (connection: IConnection): Promise => {\r\n const speechContextJson = this.speechContext.toJSON();\r\n\r\n if (speechContextJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.context\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n speechContextJson));\r\n }\r\n return;\r\n }\r\n\r\n protected sendPrePayloadJSONOverride: (connection: IConnection) => Promise = undefined;\r\n\r\n // Encapsulated for derived service recognizers that need to send additional JSON\r\n protected async sendPrePayloadJSON(connection: IConnection): Promise {\r\n if (this.sendPrePayloadJSONOverride !== undefined) {\r\n return this.sendPrePayloadJSONOverride(connection);\r\n }\r\n\r\n await this.sendSpeechContext(connection);\r\n await this.sendWaveHeader(connection);\r\n return;\r\n }\r\n\r\n protected async sendWaveHeader(connection: IConnection): Promise {\r\n const format: AudioStreamFormatImpl = await this.audioSource.format;\r\n // this.writeBufferToConsole(format.header);\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Binary,\r\n \"audio\",\r\n this.privRequestSession.requestId,\r\n \"audio/x-wav\",\r\n format.header\r\n ));\r\n }\r\n\r\n protected postConnectImplOverride: (connection: Promise) => Promise = undefined;\r\n\r\n // Establishes a websocket connection to the end point.\r\n protected connectImpl(): Promise {\r\n if (this.privConnectionPromise) {\r\n return this.privConnectionPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.connectImpl();\r\n }\r\n return this.privConnectionPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.connectImpl();\r\n });\r\n }\r\n\r\n this.privConnectionPromise = this.retryableConnect();\r\n\r\n // Attach an empty handler to allow the promise to run in the background while\r\n // other startup events happen. It'll eventually be awaited on.\r\n this.privConnectionPromise.catch(() => { });\r\n\r\n if (this.postConnectImplOverride !== undefined) {\r\n return this.postConnectImplOverride(this.privConnectionPromise);\r\n }\r\n\r\n return this.privConnectionPromise;\r\n }\r\n\r\n protected configConnectionOverride: (connection: IConnection) => Promise = undefined;\r\n\r\n protected sendSpeechServiceConfig = (connection: IConnection, requestSession: RequestSession, SpeechServiceConfigJson: string): Promise => {\r\n // filter out anything that is not required for the service to work.\r\n if (ServiceRecognizerBase.telemetryDataEnabled !== true) {\r\n const withTelemetry = JSON.parse(SpeechServiceConfigJson);\r\n\r\n const replacement: any = {\r\n context: {\r\n system: withTelemetry.context.system,\r\n },\r\n };\r\n\r\n SpeechServiceConfigJson = JSON.stringify(replacement);\r\n }\r\n\r\n if (this.privRecognizerConfig.parameters.getProperty(\"TranscriptionService_SingleChannel\", \"false\").toLowerCase() === \"true\") {\r\n const json: { context: any } = JSON.parse(SpeechServiceConfigJson);\r\n json.context.DisableReferenceChannel = \"True\";\r\n json.context.MicSpec = \"1_0_0\";\r\n SpeechServiceConfigJson = JSON.stringify(json);\r\n }\r\n\r\n if (SpeechServiceConfigJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.config\",\r\n requestSession.requestId,\r\n \"application/json\",\r\n SpeechServiceConfigJson));\r\n }\r\n\r\n return;\r\n }\r\n\r\n protected async fetchConnection(): Promise {\r\n if (this.privConnectionConfigurationPromise) {\r\n return this.privConnectionConfigurationPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigurationPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.fetchConnection();\r\n }\r\n return this.privConnectionConfigurationPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigurationPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.fetchConnection();\r\n });\r\n }\r\n\r\n this.privConnectionConfigurationPromise = this.configureConnection();\r\n return await this.privConnectionConfigurationPromise;\r\n }\r\n\r\n protected async sendAudio(audioStreamNode: IAudioStreamNode): Promise {\r\n const audioFormat: AudioStreamFormatImpl = await this.audioSource.format;\r\n\r\n // The time we last sent data to the service.\r\n let nextSendTime: number = Date.now();\r\n\r\n // Max amount to send before we start to throttle\r\n const fastLaneSizeMs: string = this.privRecognizerConfig.parameters.getProperty(\"SPEECH-TransmitLengthBeforThrottleMs\", \"5000\");\r\n const maxSendUnthrottledBytes: number = audioFormat.avgBytesPerSec / 1000 * parseInt(fastLaneSizeMs, 10);\r\n const startRecogNumber: number = this.privRequestSession.recogNumber;\r\n\r\n const readAndUploadCycle = async (): Promise => {\r\n // If speech is done, stop sending audio.\r\n if (!this.privIsDisposed &&\r\n !this.privRequestSession.isSpeechEnded &&\r\n this.privRequestSession.isRecognizing &&\r\n this.privRequestSession.recogNumber === startRecogNumber) {\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n const audioStreamChunk: IStreamChunk = await audioStreamNode.read();\r\n // we have a new audio chunk to upload.\r\n if (this.privRequestSession.isSpeechEnded) {\r\n // If service already recognized audio end then don't send any more audio\r\n return;\r\n }\r\n\r\n let payload: ArrayBuffer;\r\n let sendDelay: number;\r\n\r\n if (!audioStreamChunk || audioStreamChunk.isEnd) {\r\n payload = null;\r\n sendDelay = 0;\r\n } else {\r\n payload = audioStreamChunk.buffer;\r\n\r\n this.privRequestSession.onAudioSent(payload.byteLength);\r\n\r\n if (maxSendUnthrottledBytes >= this.privRequestSession.bytesSent) {\r\n sendDelay = 0;\r\n } else {\r\n sendDelay = Math.max(0, nextSendTime - Date.now());\r\n }\r\n }\r\n\r\n if (0 !== sendDelay) {\r\n await this.delay(sendDelay);\r\n }\r\n\r\n if (payload !== null) {\r\n nextSendTime = Date.now() + (payload.byteLength * 1000 / (audioFormat.avgBytesPerSec * 2));\r\n }\r\n\r\n // Are we still alive?\r\n if (!this.privIsDisposed &&\r\n !this.privRequestSession.isSpeechEnded &&\r\n this.privRequestSession.isRecognizing &&\r\n this.privRequestSession.recogNumber === startRecogNumber) {\r\n connection.send(\r\n new SpeechConnectionMessage(MessageType.Binary, \"audio\", this.privRequestSession.requestId, null, payload)\r\n ).catch(() => {\r\n this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch(() => { });\r\n });\r\n\r\n if (!audioStreamChunk?.isEnd) {\r\n // this.writeBufferToConsole(payload);\r\n // Regardless of success or failure, schedule the next upload.\r\n // If the underlying connection was broken, the next cycle will\r\n // get a new connection and re-transmit missing audio automatically.\r\n return readAndUploadCycle();\r\n } else {\r\n // the audio stream has been closed, no need to schedule next\r\n // read-upload cycle.\r\n if (!this.privIsLiveAudio) {\r\n this.privRequestSession.onSpeechEnded();\r\n }\r\n }\r\n }\r\n }\r\n };\r\n\r\n return readAndUploadCycle();\r\n }\r\n\r\n private async retryableConnect(): Promise {\r\n let isUnAuthorized: boolean = false;\r\n\r\n this.privAuthFetchEventId = createNoDashGuid();\r\n const sessionId: string = this.privRequestSession.sessionId;\r\n this.privConnectionId = (sessionId !== undefined) ? sessionId : createNoDashGuid();\r\n\r\n this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId);\r\n let lastStatusCode: number = 0;\r\n let lastReason: string = \"\";\r\n\r\n while (this.privRequestSession.numConnectionAttempts <= this.privRecognizerConfig.maxRetryCount) {\r\n\r\n // 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\r\n // facing event when a connection fails to let them try and provide new auth information.\r\n const authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId);\r\n const auth: AuthInfo = await authPromise;\r\n\r\n await this.privRequestSession.onAuthCompleted(false);\r\n\r\n // Create the connection\r\n const connection: IConnection = this.privConnectionFactory.create(this.privRecognizerConfig, auth, this.privConnectionId);\r\n // Attach the telemetry handlers.\r\n this.privRequestSession.listenForServiceTelemetry(connection.events);\r\n\r\n // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away,\r\n // it'll stop sending events.\r\n connection.events.attach((event: ConnectionEvent) => {\r\n this.connectionEvents.onEvent(event);\r\n });\r\n\r\n const response: ConnectionOpenResponse = await connection.open();\r\n // 200 == everything is fine.\r\n if (response.statusCode === 200) {\r\n await this.privRequestSession.onConnectionEstablishCompleted(response.statusCode);\r\n return Promise.resolve(connection);\r\n } else if (response.statusCode === 1006) {\r\n isUnAuthorized = true;\r\n }\r\n\r\n lastStatusCode = response.statusCode;\r\n lastReason = response.reason;\r\n\r\n this.privRequestSession.onRetryConnection();\r\n }\r\n\r\n await this.privRequestSession.onConnectionEstablishCompleted(lastStatusCode, lastReason);\r\n return Promise.reject(`Unable to contact server. StatusCode: ${lastStatusCode}, ${this.privRecognizerConfig.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint)} Reason: ${lastReason}`);\r\n }\r\n\r\n private delay(delayMs: number): Promise {\r\n return new Promise((resolve: () => void, reject: (error: string) => void) => {\r\n this.privSetTimeout(resolve, delayMs);\r\n });\r\n }\r\n\r\n private writeBufferToConsole(buffer: ArrayBuffer): void {\r\n let out: string = \"Buffer Size: \";\r\n if (null === buffer) {\r\n out += \"null\";\r\n } else {\r\n const readView: Uint8Array = new Uint8Array(buffer);\r\n out += buffer.byteLength + \"\\r\\n\";\r\n for (let i: number = 0; i < buffer.byteLength; i++) {\r\n out += readView[i].toString(16).padStart(2, \"0\") + \" \";\r\n }\r\n }\r\n // tslint:disable-next-line:no-console\r\n console.info(out);\r\n }\r\n\r\n private async sendFinalAudio(): Promise {\r\n const connection: IConnection = await this.fetchConnection();\r\n await connection.send(new SpeechConnectionMessage(MessageType.Binary, \"audio\", this.privRequestSession.requestId, null, null));\r\n return;\r\n }\r\n\r\n // Takes an established websocket connection to the endpoint and sends speech configuration information.\r\n private async configureConnection(): Promise {\r\n const connection: IConnection = await this.connectImpl();\r\n if (this.configConnectionOverride !== undefined) {\r\n return this.configConnectionOverride(connection);\r\n }\r\n await this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize());\r\n await this.sendPrePayloadJSON(connection);\r\n return connection;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n AudioSourceErrorEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n AudioStreamNodeErrorEvent,\r\n ConnectionEstablishedEvent,\r\n ConnectionEstablishErrorEvent,\r\n ConnectionMessageReceivedEvent,\r\n ConnectionStartEvent,\r\n IEventListener,\r\n IStringDictionary,\r\n PlatformEvent,\r\n} from \"../common/Exports\";\r\nimport { ConnectingToServiceEvent, RecognitionTriggeredEvent } from \"./RecognitionEvents\";\r\n\r\nexport interface ITelemetry {\r\n Metrics: IMetric[];\r\n ReceivedMessages: IStringDictionary;\r\n}\r\n\r\nexport interface IMetric {\r\n End?: string;\r\n Error?: string;\r\n Id?: string;\r\n Name?: string;\r\n Start?: string;\r\n PhraseLatencyMs?: number[];\r\n FirstHypothesisLatencyMs?: number[];\r\n}\r\n\r\nexport class ServiceTelemetryListener implements IEventListener {\r\n private privIsDisposed: boolean = false;\r\n\r\n private privRequestId: string;\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n\r\n private privListeningTriggerMetric: IMetric = null;\r\n private privMicMetric: IMetric = null;\r\n private privConnectionEstablishMetric: IMetric = null;\r\n\r\n private privMicStartTime: string;\r\n\r\n private privConnectionId: string;\r\n private privConnectionStartTime: string;\r\n\r\n private privReceivedMessages: IStringDictionary;\r\n private privPhraseLatencies: number[];\r\n private privHypothesisLatencies: number[];\r\n\r\n constructor(requestId: string, audioSourceId: string, audioNodeId: string) {\r\n this.privRequestId = requestId;\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n\r\n this.privReceivedMessages = {};\r\n this.privPhraseLatencies = [];\r\n this.privHypothesisLatencies = [];\r\n }\r\n\r\n public phraseReceived(audioReceivedTime: number): void {\r\n if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.\r\n this.privPhraseLatencies.push(Date.now() - audioReceivedTime);\r\n }\r\n }\r\n\r\n public hypothesisReceived(audioReceivedTime: number): void {\r\n if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.\r\n this.privHypothesisLatencies.push(Date.now() - audioReceivedTime);\r\n }\r\n }\r\n\r\n public onEvent = (e: PlatformEvent): void => {\r\n if (this.privIsDisposed) {\r\n return;\r\n }\r\n\r\n if (e instanceof RecognitionTriggeredEvent && e.requestId === this.privRequestId) {\r\n this.privListeningTriggerMetric = {\r\n End: e.eventTime,\r\n Name: \"ListeningTrigger\",\r\n Start: e.eventTime,\r\n };\r\n }\r\n\r\n if (e instanceof AudioStreamNodeAttachingEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n this.privMicStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof AudioStreamNodeAttachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n this.privMicStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof AudioSourceErrorEvent && e.audioSourceId === this.privAudioSourceId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Error: e.error,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof AudioStreamNodeErrorEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Error: e.error,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof AudioStreamNodeDetachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectingToServiceEvent && e.requestId === this.privRequestId) {\r\n this.privConnectionId = e.sessionId;\r\n }\r\n\r\n if (e instanceof ConnectionStartEvent && e.connectionId === this.privConnectionId) {\r\n this.privConnectionStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof ConnectionEstablishedEvent && e.connectionId === this.privConnectionId) {\r\n if (!this.privConnectionEstablishMetric) {\r\n this.privConnectionEstablishMetric = {\r\n End: e.eventTime,\r\n Id: this.privConnectionId,\r\n Name: \"Connection\",\r\n Start: this.privConnectionStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectionEstablishErrorEvent && e.connectionId === this.privConnectionId) {\r\n if (!this.privConnectionEstablishMetric) {\r\n this.privConnectionEstablishMetric = {\r\n End: e.eventTime,\r\n Error: this.getConnectionError(e.statusCode),\r\n Id: this.privConnectionId,\r\n Name: \"Connection\",\r\n Start: this.privConnectionStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectionMessageReceivedEvent && e.connectionId === this.privConnectionId) {\r\n if (e.message && e.message.headers && e.message.headers.path) {\r\n if (!this.privReceivedMessages[e.message.headers.path]) {\r\n this.privReceivedMessages[e.message.headers.path] = new Array();\r\n }\r\n\r\n this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime);\r\n }\r\n }\r\n }\r\n\r\n public getTelemetry = (): string => {\r\n const metrics = new Array();\r\n\r\n if (this.privListeningTriggerMetric) {\r\n metrics.push(this.privListeningTriggerMetric);\r\n }\r\n\r\n if (this.privMicMetric) {\r\n metrics.push(this.privMicMetric);\r\n }\r\n\r\n if (this.privConnectionEstablishMetric) {\r\n metrics.push(this.privConnectionEstablishMetric);\r\n }\r\n\r\n if (this.privPhraseLatencies.length > 0) {\r\n metrics.push({\r\n PhraseLatencyMs: this.privPhraseLatencies,\r\n });\r\n }\r\n\r\n if (this.privHypothesisLatencies.length > 0) {\r\n metrics.push({\r\n FirstHypothesisLatencyMs: this.privHypothesisLatencies,\r\n });\r\n }\r\n\r\n const telemetry: ITelemetry = {\r\n Metrics: metrics,\r\n ReceivedMessages: this.privReceivedMessages,\r\n };\r\n\r\n const json = JSON.stringify(telemetry);\r\n\r\n // We dont want to send the same telemetry again. So clean those out.\r\n this.privReceivedMessages = {};\r\n this.privListeningTriggerMetric = null;\r\n this.privMicMetric = null;\r\n this.privConnectionEstablishMetric = null;\r\n this.privPhraseLatencies = [];\r\n this.privHypothesisLatencies = [];\r\n return json;\r\n }\r\n\r\n // Determines if there are any telemetry events to send to the service.\r\n public get hasTelemetry(): boolean {\r\n return (Object.keys(this.privReceivedMessages).length !== 0 ||\r\n this.privListeningTriggerMetric !== null ||\r\n this.privMicMetric !== null ||\r\n this.privConnectionEstablishMetric !== null ||\r\n this.privPhraseLatencies.length !== 0 ||\r\n this.privHypothesisLatencies.length !== 0);\r\n }\r\n\r\n public dispose = (): void => {\r\n this.privIsDisposed = true;\r\n }\r\n\r\n private getConnectionError = (statusCode: number): string => {\r\n /*\r\n -- Websocket status codes --\r\n NormalClosure = 1000,\r\n EndpointUnavailable = 1001,\r\n ProtocolError = 1002,\r\n InvalidMessageType = 1003,\r\n Empty = 1005,\r\n InvalidPayloadData = 1007,\r\n PolicyViolation = 1008,\r\n MessageTooBig = 1009,\r\n MandatoryExtension = 1010,\r\n InternalServerError = 1011\r\n */\r\n\r\n switch (statusCode) {\r\n case 400:\r\n case 1002:\r\n case 1003:\r\n case 1005:\r\n case 1007:\r\n case 1008:\r\n case 1009: return \"BadRequest\";\r\n case 401: return \"Unauthorized\";\r\n case 403: return \"Forbidden\";\r\n case 503:\r\n case 1001: return \"ServerUnavailable\";\r\n case 500:\r\n case 1011: return \"ServerError\";\r\n case 408:\r\n case 504: return \"Timeout\";\r\n default: return \"statuscode:\" + statusCode.toString();\r\n }\r\n }\r\n}\r\n","import {\r\n IRequestOptions,\r\n IRestResponse,\r\n RestConfigBase,\r\n RestMessageAdapter,\r\n RestRequestType,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n IAudioSource,\r\n PromiseResult,\r\n} from \"../common/Exports\";\r\nimport {\r\n PropertyId,\r\n SpeakerIdentificationModel,\r\n SpeakerVerificationModel,\r\n VoiceProfile,\r\n VoiceProfileType,\r\n} from \"../sdk/Exports\";\r\nimport { SpeakerRecognitionConfig } from \"./Exports\";\r\n\r\n/**\r\n * Implements methods for speaker recognition classes, sending requests to endpoint\r\n * and parsing response into expected format\r\n * @class SpeakerIdMessageAdapter\r\n */\r\nexport class SpeakerIdMessageAdapter {\r\n private privRestAdapter: RestMessageAdapter;\r\n private privUri: string;\r\n\r\n public constructor(config: SpeakerRecognitionConfig) {\r\n\r\n let endpoint = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n if (!endpoint) {\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, \"westus\");\r\n const hostSuffix: string = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"https://\" + region + \".api.cognitive\" + hostSuffix + \"/speaker/{mode}/v2.0/{dependency}\");\r\n endpoint = host + \"/profiles\";\r\n }\r\n this.privUri = endpoint;\r\n\r\n const options: IRequestOptions = RestConfigBase.requestOptions;\r\n options.headers[RestConfigBase.configParams.subscriptionKey] = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Key, undefined);\r\n\r\n this.privRestAdapter = new RestMessageAdapter(options);\r\n }\r\n\r\n /**\r\n * Sends create profile request to endpoint.\r\n * @function\r\n * @param {VoiceProfileType} profileType - type of voice profile to create.\r\n * @param {string} lang - language/locale of voice profile\r\n * @public\r\n * @returns {Promise} promised rest response containing id of created profile.\r\n */\r\n public createProfile(profileType: VoiceProfileType, lang: string):\r\n Promise {\r\n\r\n const uri = this.getOperationUri(profileType);\r\n this.privRestAdapter.setHeaders(RestConfigBase.configParams.contentTypeKey, \"application/json\");\r\n return this.privRestAdapter.request(RestRequestType.Post, uri, {}, { locale: lang });\r\n }\r\n\r\n /**\r\n * Sends create enrollment request to endpoint.\r\n * @function\r\n * @param {VoiceProfile} profileType - voice profile for which to create new enrollment.\r\n * @param {IAudioSource} audioSource - audioSource from which to pull data to send\r\n * @public\r\n * @returns {Promise} rest response to enrollment request.\r\n */\r\n public createEnrollment(profile: VoiceProfile, audioSource: IAudioSource):\r\n Promise {\r\n\r\n this.privRestAdapter.setHeaders(RestConfigBase.configParams.contentTypeKey, \"multipart/form-data\");\r\n const uri = this.getOperationUri(profile.profileType) + \"/\" + profile.profileId + \"/enrollments\";\r\n return audioSource.blob.then((result: Blob | Buffer): Promise => {\r\n return this.privRestAdapter.request(RestRequestType.File, uri, { ignoreMinLength: \"true\" }, null, result);\r\n });\r\n }\r\n\r\n /**\r\n * Sends verification request to endpoint.\r\n * @function\r\n * @param {SpeakerVerificationModel} model - voice model to verify against.\r\n * @param {IAudioSource} audioSource - audioSource from which to pull data to send\r\n * @public\r\n * @returns {Promise} rest response to enrollment request.\r\n */\r\n public async verifySpeaker(model: SpeakerVerificationModel, audioSource: IAudioSource):\r\n Promise {\r\n\r\n this.privRestAdapter.setHeaders(RestConfigBase.configParams.contentTypeKey, \"multipart/form-data\");\r\n const uri = this.getOperationUri(model.voiceProfile.profileType) + \"/\" + model.voiceProfile.profileId + \"/verify\";\r\n try {\r\n const result: Blob | Buffer = await audioSource.blob;\r\n return this.privRestAdapter.request(RestRequestType.File, uri, { ignoreMinLength: \"true\" }, null, result);\r\n } catch (e) {\r\n return Promise.resolve({ data: e } as IRestResponse);\r\n }\r\n }\r\n\r\n /**\r\n * Sends identification request to endpoint.\r\n * @function\r\n * @param {SpeakerIdentificationModel} model - voice profiles against which to identify.\r\n * @param {IAudioSource} audioSource - audioSource from which to pull data to send\r\n * @public\r\n * @returns {Promise} rest response to enrollment request.\r\n */\r\n public async identifySpeaker(model: SpeakerIdentificationModel, audioSource: IAudioSource):\r\n Promise {\r\n\r\n this.privRestAdapter.setHeaders(RestConfigBase.configParams.contentTypeKey, \"multipart/form-data\");\r\n const uri = this.getOperationUri(VoiceProfileType.TextIndependentIdentification) + \"/identifySingleSpeaker\";\r\n try {\r\n const result: Blob | Buffer = await audioSource.blob;\r\n return this.privRestAdapter.request(RestRequestType.File, uri, { profileIds: model.voiceProfileIds, ignoreMinLength: \"true\" }, null, result);\r\n } catch (e) {\r\n return Promise.resolve({ data: e } as IRestResponse);\r\n }\r\n }\r\n\r\n /**\r\n * Sends profile status request to endpoint.\r\n * @function\r\n * @param {VoiceProfile} profile - voice profile to check.\r\n * @public\r\n * @returns {Promise} rest response to status request\r\n */\r\n public getProfileStatus(profile: VoiceProfile): Promise {\r\n\r\n const uri = `${this.getOperationUri(profile.profileType)}/${profile.profileId}`;\r\n return this.privRestAdapter.request(RestRequestType.Get, uri, {});\r\n }\r\n\r\n /**\r\n * Sends get all profiles request to endpoint.\r\n * @function\r\n * @param {VoiceProfileType} profileType - type of profiles to return list of\r\n * @public\r\n * @returns {Promise} promised rest response containing all profiles\r\n */\r\n public getProfiles(profileType: VoiceProfileType): Promise {\r\n const uri = this.getOperationUri(profileType);\r\n return this.privRestAdapter.request(RestRequestType.Get, uri, {});\r\n }\r\n\r\n /**\r\n * Sends get authorization phrases request to endpoint.\r\n * @function\r\n * @param {string} lang - language/locale of voice profile\r\n * @public\r\n * @returns {Promise} promised rest response containing list of valid phrases\r\n */\r\n public getAuthorizationPhrases(lang: string): Promise {\r\n const uri = `${this.getOperationUri(VoiceProfileType.TextDependentVerification)}`.replace(`profiles`, `phrases`) + \"/\" + lang;\r\n return this.privRestAdapter.request(RestRequestType.Get, uri, {});\r\n }\r\n\r\n /**\r\n * Sends delete profile request to endpoint.\r\n * @function\r\n * @param {VoiceProfile} profile - voice profile to delete.\r\n * @public\r\n * @returns {Promise} rest response to deletion request\r\n */\r\n public deleteProfile(profile: VoiceProfile): Promise {\r\n\r\n const uri = this.getOperationUri(profile.profileType) + \"/\" + profile.profileId;\r\n return this.privRestAdapter.request(RestRequestType.Delete, uri, {});\r\n }\r\n\r\n /**\r\n * Sends reset profile request to endpoint.\r\n * @function\r\n * @param {VoiceProfile} profile - voice profile to reset enrollments for.\r\n * @public\r\n * @returns {Promise} rest response to reset request\r\n */\r\n public resetProfile(profile: VoiceProfile): Promise {\r\n\r\n const uri = this.getOperationUri(profile.profileType) + \"/\" + profile.profileId + \"/reset\";\r\n return this.privRestAdapter.request(RestRequestType.Post, uri, {});\r\n }\r\n\r\n private getOperationUri(profileType: VoiceProfileType): string {\r\n\r\n const mode = profileType === VoiceProfileType.TextIndependentIdentification ? \"identification\" : \"verification\";\r\n const dependency = profileType === VoiceProfileType.TextDependentVerification ? \"text-dependent\" : \"text-independent\";\r\n return this.privUri.replace(\"{mode}\", mode).replace(\"{dependency}\", dependency);\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection } from \"../sdk/Exports\";\r\nimport { Context } from \"./Exports\";\r\n\r\nexport class SpeakerRecognitionConfig {\r\n private privParameters: PropertyCollection;\r\n private privContext: Context;\r\n\r\n constructor(\r\n context: Context,\r\n parameters: PropertyCollection) {\r\n this.privContext = context ? context : new Context(null);\r\n this.privParameters = parameters;\r\n }\r\n\r\n public get parameters(): PropertyCollection {\r\n return this.privParameters;\r\n }\r\n\r\n public get Context(): Context {\r\n return this.privContext;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n ForceDictationPropertyName,\r\n OutputFormatPropertyName,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary\r\n} from \"../common/Exports\";\r\nimport {\r\n OutputFormat,\r\n PropertyId\r\n} from \"../sdk/Exports\";\r\nimport {\r\n ConnectionFactoryBase\r\n} from \"./ConnectionFactoryBase\";\r\nimport {\r\n AuthInfo,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n WebsocketMessageFormatter\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport {\r\n QueryParameterNames\r\n} from \"./QueryParameterNames\";\r\n\r\nexport class SpeechConnectionFactory extends ConnectionFactoryBase {\r\n\r\n private readonly interactiveRelativeUri: string = \"/speech/recognition/interactive/cognitiveservices/v1\";\r\n private readonly conversationRelativeUri: string = \"/speech/recognition/conversation/cognitiveservices/v1\";\r\n private readonly dictationRelativeUri: string = \"/speech/recognition/dictation/cognitiveservices/v1\";\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, undefined);\r\n const hostSuffix: string = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"wss://\" + region + \".stt.speech\" + hostSuffix);\r\n\r\n const queryParams: IStringDictionary = {};\r\n\r\n const endpointId: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_EndpointId, undefined);\r\n const language: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, undefined);\r\n\r\n if (endpointId) {\r\n if (!endpoint || endpoint.search(QueryParameterNames.CustomSpeechDeploymentId) === -1) {\r\n queryParams[QueryParameterNames.CustomSpeechDeploymentId] = endpointId;\r\n }\r\n } else if (language) {\r\n if (!endpoint || endpoint.search(QueryParameterNames.Language) === -1) {\r\n queryParams[QueryParameterNames.Language] = language;\r\n }\r\n }\r\n\r\n if (!endpoint || endpoint.search(QueryParameterNames.Format) === -1) {\r\n queryParams[QueryParameterNames.Format] = config.parameters.getProperty(OutputFormatPropertyName, OutputFormat[OutputFormat.Simple]).toLowerCase();\r\n }\r\n\r\n if (config.autoDetectSourceLanguages !== undefined) {\r\n queryParams[QueryParameterNames.EnableLanguageId] = \"true\";\r\n }\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n\r\n if (!endpoint) {\r\n switch (config.recognitionMode) {\r\n case RecognitionMode.Conversation:\r\n if (config.parameters.getProperty(ForceDictationPropertyName, \"false\") === \"true\") {\r\n endpoint = host + this.dictationRelativeUri;\r\n } else {\r\n endpoint = host + this.conversationRelativeUri;\r\n }\r\n break;\r\n case RecognitionMode.Dictation:\r\n endpoint = host + this.dictationRelativeUri;\r\n break;\r\n default:\r\n endpoint = host + this.interactiveRelativeUri; // default is interactive\r\n break;\r\n }\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ArgumentNullError, ConnectionMessage, IStringDictionary, MessageType } from \"../common/Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\n\r\nexport class SpeechConnectionMessage extends ConnectionMessage {\r\n\r\n private privPath: string;\r\n private privRequestId: string;\r\n private privContentType: string;\r\n private privStreamId: string;\r\n private privAdditionalHeaders: IStringDictionary;\r\n\r\n public constructor(\r\n messageType: MessageType,\r\n path: string,\r\n requestId: string,\r\n contentType: string,\r\n body: any,\r\n streamId?: string,\r\n additionalHeaders?: IStringDictionary,\r\n id?: string) {\r\n\r\n if (!path) {\r\n throw new ArgumentNullError(\"path\");\r\n }\r\n\r\n if (!requestId) {\r\n throw new ArgumentNullError(\"requestId\");\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n headers[HeaderNames.Path] = path;\r\n headers[HeaderNames.RequestId] = requestId;\r\n headers[HeaderNames.RequestTimestamp] = new Date().toISOString();\r\n if (contentType) {\r\n headers[HeaderNames.ContentType] = contentType;\r\n }\r\n\r\n if (streamId) {\r\n headers[HeaderNames.RequestStreamId] = streamId;\r\n }\r\n\r\n if (additionalHeaders) {\r\n for (const headerName in additionalHeaders) {\r\n if (headerName) {\r\n headers[headerName] = additionalHeaders[headerName];\r\n }\r\n\r\n }\r\n }\r\n\r\n if (id) {\r\n super(messageType, body, headers, id);\r\n } else {\r\n super(messageType, body, headers);\r\n }\r\n\r\n this.privPath = path;\r\n this.privRequestId = requestId;\r\n this.privContentType = contentType;\r\n this.privStreamId = streamId;\r\n this.privAdditionalHeaders = additionalHeaders;\r\n }\r\n\r\n public get path(): string {\r\n return this.privPath;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get contentType(): string {\r\n return this.privContentType;\r\n }\r\n\r\n public get streamId(): string {\r\n return this.privStreamId;\r\n }\r\n\r\n public get additionalHeaders(): IStringDictionary {\r\n return this.privAdditionalHeaders;\r\n }\r\n\r\n public static fromConnectionMessage = (message: ConnectionMessage): SpeechConnectionMessage => {\r\n let path = null;\r\n let requestId = null;\r\n let contentType = null;\r\n let requestTimestamp = null;\r\n let streamId = null;\r\n const additionalHeaders: IStringDictionary = {};\r\n\r\n if (message.headers) {\r\n for (const headerName in message.headers) {\r\n if (headerName) {\r\n if (headerName.toLowerCase() === HeaderNames.Path.toLowerCase()) {\r\n path = message.headers[headerName];\r\n } else if (headerName.toLowerCase() === HeaderNames.RequestId.toLowerCase()) {\r\n requestId = message.headers[headerName];\r\n } else if (headerName.toLowerCase() === HeaderNames.RequestTimestamp.toLowerCase()) {\r\n requestTimestamp = message.headers[headerName];\r\n } else if (headerName.toLowerCase() === HeaderNames.ContentType.toLowerCase()) {\r\n contentType = message.headers[headerName];\r\n } else if (headerName.toLowerCase() === HeaderNames.RequestStreamId.toLowerCase()) {\r\n streamId = message.headers[headerName];\r\n } else {\r\n additionalHeaders[headerName] = message.headers[headerName];\r\n }\r\n }\r\n }\r\n }\r\n\r\n return new SpeechConnectionMessage(\r\n message.messageType,\r\n path,\r\n requestId,\r\n contentType,\r\n message.body,\r\n streamId,\r\n additionalHeaders,\r\n message.id);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n DynamicGrammarBuilder,\r\n IDynamicGrammar,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Represents the JSON used in the speech.context message sent to the speech service.\r\n * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object.\r\n */\r\nexport class SpeechContext {\r\n private privContext: { [section: string]: any } = {};\r\n private privDynamicGrammar: DynamicGrammarBuilder;\r\n\r\n constructor(dynamicGrammar: DynamicGrammarBuilder) {\r\n this.privDynamicGrammar = dynamicGrammar;\r\n }\r\n\r\n /**\r\n * Adds a section to the speech.context object.\r\n * @param sectionName Name of the section to add.\r\n * @param value JSON serializable object that represents the value.\r\n */\r\n public setSection(sectionName: string, value: any): void {\r\n this.privContext[sectionName] = value;\r\n }\r\n\r\n /**\r\n * @Internal\r\n * This is only used by pronunciation assessment config.\r\n * Do not use externally, object returned will change without warning or notice.\r\n */\r\n public setPronunciationAssessmentParams(params: string): void {\r\n if (this.privContext.phraseDetection === undefined) {\r\n this.privContext.phraseDetection = {\r\n enrichment: {\r\n pronunciationAssessment: {}\r\n }\r\n };\r\n }\r\n this.privContext.phraseDetection.enrichment.pronunciationAssessment = JSON.parse(params);\r\n if (this.privContext.phraseOutput === undefined) {\r\n this.privContext.phraseOutput = {\r\n detailed: {\r\n options: []\r\n },\r\n format: {}\r\n };\r\n }\r\n this.privContext.phraseOutput.format = \"Detailed\";\r\n this.privContext.phraseOutput.detailed.options.push(\"PronunciationAssessment\");\r\n if (this.privContext.phraseOutput.detailed.options.indexOf(\"WordTimings\") === -1) {\r\n this.privContext.phraseOutput.detailed.options.push(\"WordTimings\");\r\n }\r\n }\r\n\r\n public toJSON(): string {\r\n\r\n const dgi: IDynamicGrammar = this.privDynamicGrammar.generateGrammarObject();\r\n this.setSection(\"dgi\", dgi);\r\n\r\n const ret: string = JSON.stringify(this.privContext);\r\n return ret;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IAudioSource } from \"../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n OutputFormat,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechRecognitionCanceledEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult,\r\n SpeechRecognizer,\r\n} from \"../sdk/Exports\";\r\nimport {\r\n CancellationErrorCodePropertyName,\r\n DetailedSpeechPhrase,\r\n EnumTranslation,\r\n OutputFormatPropertyName,\r\n RecognitionStatus,\r\n ServiceRecognizerBase,\r\n SimpleSpeechPhrase,\r\n SpeechHypothesis,\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class SpeechServiceRecognizer extends ServiceRecognizerBase {\r\n\r\n private privSpeechRecognizer: SpeechRecognizer;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n speechRecognizer: SpeechRecognizer) {\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer);\r\n this.privSpeechRecognizer = speechRecognizer;\r\n if (recognizerConfig.autoDetectSourceLanguages !== undefined) {\r\n const sourceLanguages: string[] = recognizerConfig.autoDetectSourceLanguages.split(\",\");\r\n this.privSpeechContext.setSection(\"languageId\", {\r\n languages: sourceLanguages,\r\n onSuccess: { action: \"Recognize\" },\r\n onUnknown: { action: \"None\" }\r\n });\r\n this.privSpeechContext.setSection(\"phraseOutput\", {\r\n interimResults: {\r\n resultType: \"Auto\"\r\n },\r\n phraseResults: {\r\n resultType: \"Always\"\r\n }\r\n });\r\n }\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n let result: SpeechRecognitionResult;\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n let processed: boolean = false;\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"speech.hypothesis\":\r\n case \"speech.fragment\":\r\n const hypothesis: SpeechHypothesis = SpeechHypothesis.fromJSON(connectionMessage.textBody);\r\n const offset: number = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n ResultReason.RecognizingSpeech,\r\n hypothesis.Text,\r\n hypothesis.Duration,\r\n offset,\r\n hypothesis.Language,\r\n hypothesis.LanguageDetectionConfidence,\r\n undefined, // Speaker Id\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n this.privRequestSession.onHypothesis(offset);\r\n\r\n const ev = new SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privSpeechRecognizer.recognizing) {\r\n try {\r\n this.privSpeechRecognizer.recognizing(this.privSpeechRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.phrase\":\r\n const simple: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n const resultReason: ResultReason = EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus);\r\n\r\n this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + simple.Offset + simple.Duration);\r\n\r\n if (ResultReason.Canceled === resultReason) {\r\n const cancelReason: CancellationReason = EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);\r\n\r\n await this.cancelRecognitionLocal(\r\n cancelReason,\r\n EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus),\r\n undefined);\r\n\r\n } else {\r\n if (!(this.privRequestSession.isSpeechEnded && resultReason === ResultReason.NoMatch && simple.RecognitionStatus !== RecognitionStatus.InitialSilenceTimeout)) {\r\n if (this.privRecognizerConfig.parameters.getProperty(OutputFormatPropertyName) === OutputFormat[OutputFormat.Simple]) {\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n simple.DisplayText,\r\n simple.Duration,\r\n simple.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n simple.Language,\r\n simple.LanguageDetectionConfidence,\r\n undefined, // Speaker Id\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n } else {\r\n const detailed: DetailedSpeechPhrase = DetailedSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n detailed.RecognitionStatus === RecognitionStatus.Success ? detailed.NBest[0].Display : undefined,\r\n detailed.Duration,\r\n detailed.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n detailed.Language,\r\n detailed.LanguageDetectionConfidence,\r\n undefined, // Speaker Id\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n }\r\n\r\n const event: SpeechRecognitionEventArgs = new SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privSpeechRecognizer.recognized) {\r\n try {\r\n this.privSpeechRecognizer.recognized(this.privSpeechRecognizer, event);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n }\r\n processed = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n if (!!this.privSpeechRecognizer.canceled) {\r\n const cancelEvent: SpeechRecognitionCanceledEventArgs = new SpeechRecognitionCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n sessionId);\r\n try {\r\n this.privSpeechRecognizer.canceled(this.privSpeechRecognizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: SpeechRecognitionResult = new SpeechRecognitionResult(\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Duration\r\n undefined, // Offset\r\n undefined, // Language\r\n undefined, // Language Detection Confidence\r\n undefined, // Speaker Id\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n this.privSuccessCallback = undefined;\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection, WebsocketMessageAdapter,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary\r\n} from \"../common/Exports\";\r\nimport { PropertyId } from \"../sdk/Exports\";\r\nimport {\r\n AuthInfo,\r\n SynthesizerConfig,\r\n WebsocketMessageFormatter\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { ISynthesisConnectionFactory } from \"./ISynthesisConnectionFactory\";\r\nimport {\r\n QueryParameterNames\r\n} from \"./QueryParameterNames\";\r\n\r\nexport class SpeechSynthesisConnectionFactory implements ISynthesisConnectionFactory {\r\n\r\n private readonly synthesisUri: string = \"/cognitiveservices/websocket/v1\";\r\n\r\n public create = (\r\n config: SynthesizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, undefined);\r\n const hostSuffix = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const endpointId = config.parameters.getProperty(PropertyId.SpeechServiceConnection_EndpointId, undefined);\r\n const hostPrefix = (endpointId === undefined) ? \"tts\" : \"voice\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"wss://\" + region + \".\" + hostPrefix + \".speech\" + hostSuffix);\r\n\r\n const queryParams: IStringDictionary = {};\r\n\r\n if (!endpoint) {\r\n endpoint = host + this.synthesisUri;\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n if (endpointId !== undefined) {\r\n headers[QueryParameterNames.CustomVoiceDeploymentId] = endpointId;\r\n }\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromParameters(config.parameters), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ArgumentNullError,\r\n ConnectionClosedEvent,\r\n ConnectionEvent,\r\n ConnectionMessage,\r\n ConnectionState,\r\n createNoDashGuid,\r\n EventSource,\r\n IAudioDestination,\r\n IConnection,\r\n IDisposable,\r\n MessageType,\r\n ServiceEvent,\r\n} from \"../common/Exports\";\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechSynthesisBookmarkEventArgs,\r\n SpeechSynthesisEventArgs,\r\n SpeechSynthesisResult,\r\n SpeechSynthesisVisemeEventArgs,\r\n SpeechSynthesisWordBoundaryEventArgs,\r\n SpeechSynthesizer,\r\n} from \"../sdk/Exports\";\r\nimport {\r\n AgentConfig,\r\n CancellationErrorCodePropertyName,\r\n ISynthesisConnectionFactory,\r\n MetadataType,\r\n SynthesisAudioMetadata,\r\n SynthesisContext,\r\n SynthesisTurn,\r\n SynthesizerConfig\r\n} from \"./Exports\";\r\nimport { AuthInfo, IAuthentication } from \"./IAuthentication\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\nexport class SynthesisAdapterBase implements IDisposable {\r\n protected privSynthesisTurn: SynthesisTurn;\r\n protected privConnectionId: string;\r\n protected privSynthesizerConfig: SynthesizerConfig;\r\n protected privSpeechSynthesizer: SpeechSynthesizer;\r\n protected privSuccessCallback: (e: SpeechSynthesisResult) => void;\r\n protected privErrorCallback: (e: string) => void;\r\n\r\n public get synthesisContext(): SynthesisContext {\r\n return this.privSynthesisContext;\r\n }\r\n\r\n public get agentConfig(): AgentConfig {\r\n return this.privAgentConfig;\r\n }\r\n\r\n public get connectionEvents(): EventSource {\r\n return this.privConnectionEvents;\r\n }\r\n\r\n public get serviceEvents(): EventSource {\r\n return this.privServiceEvents;\r\n }\r\n\r\n protected speakOverride: (ssml: string, requestId: string, sc: (e: SpeechSynthesisResult) => void, ec: (e: string) => void) => any = undefined;\r\n\r\n // Called when telemetry data is sent to the service.\r\n // Used for testing Telemetry capture.\r\n public static telemetryData: (json: string) => void;\r\n public static telemetryDataEnabled: boolean = true;\r\n\r\n public set activityTemplate(messagePayload: string) { this.privActivityTemplate = messagePayload; }\r\n public get activityTemplate(): string { return this.privActivityTemplate; }\r\n\r\n protected receiveMessageOverride: () => any = undefined;\r\n\r\n protected connectImplOverride: (isUnAuthorized: boolean) => any = undefined;\r\n\r\n protected configConnectionOverride: (connection: IConnection) => any = undefined;\r\n\r\n public set audioOutputFormat(format: AudioOutputFormatImpl) {\r\n this.privAudioOutputFormat = format;\r\n this.privSynthesisTurn.audioOutputFormat = format;\r\n if (this.privSessionAudioDestination !== undefined) {\r\n this.privSessionAudioDestination.format = format;\r\n }\r\n if (this.synthesisContext !== undefined) {\r\n this.synthesisContext.audioOutputFormat = format;\r\n }\r\n }\r\n private privAuthentication: IAuthentication;\r\n private privConnectionFactory: ISynthesisConnectionFactory;\r\n\r\n // A promise for a configured connection.\r\n // Do not consume directly, call fetchConnection instead.\r\n private privConnectionConfigurationPromise: Promise;\r\n\r\n // A promise for a connection, but one that has not had the speech context sent yet.\r\n // Do not consume directly, call fetchConnection instead.\r\n private privConnectionPromise: Promise;\r\n private privAuthFetchEventId: string;\r\n private privIsDisposed: boolean;\r\n private privConnectionEvents: EventSource;\r\n private privServiceEvents: EventSource;\r\n private privSynthesisContext: SynthesisContext;\r\n private privAgentConfig: AgentConfig;\r\n private privServiceHasSentMessage: boolean;\r\n private privActivityTemplate: string;\r\n private privAudioOutputFormat: AudioOutputFormatImpl;\r\n private privSessionAudioDestination: IAudioDestination;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: ISynthesisConnectionFactory,\r\n synthesizerConfig: SynthesizerConfig,\r\n speechSynthesizer: SpeechSynthesizer,\r\n audioDestination: IAudioDestination) {\r\n\r\n if (!authentication) {\r\n throw new ArgumentNullError(\"authentication\");\r\n }\r\n\r\n if (!connectionFactory) {\r\n throw new ArgumentNullError(\"connectionFactory\");\r\n }\r\n\r\n if (!synthesizerConfig) {\r\n throw new ArgumentNullError(\"synthesizerConfig\");\r\n }\r\n\r\n this.privAuthentication = authentication;\r\n this.privConnectionFactory = connectionFactory;\r\n this.privSynthesizerConfig = synthesizerConfig;\r\n this.privIsDisposed = false;\r\n this.privSpeechSynthesizer = speechSynthesizer;\r\n this.privSessionAudioDestination = audioDestination;\r\n this.privSynthesisTurn = new SynthesisTurn();\r\n this.privConnectionEvents = new EventSource();\r\n this.privServiceEvents = new EventSource();\r\n this.privSynthesisContext = new SynthesisContext(this.privSpeechSynthesizer);\r\n this.privAgentConfig = new AgentConfig();\r\n\r\n this.connectionEvents.attach((connectionEvent: ConnectionEvent): void => {\r\n if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n const connectionClosedEvent = connectionEvent as ConnectionClosedEvent;\r\n if (connectionClosedEvent.statusCode !== 1000) {\r\n this.cancelSynthesisLocal(CancellationReason.Error,\r\n connectionClosedEvent.statusCode === 1007 ? CancellationErrorCode.BadRequestParameters : CancellationErrorCode.ConnectionFailure,\r\n connectionClosedEvent.reason + \" websocket error code: \" + connectionClosedEvent.statusCode);\r\n }\r\n }\r\n });\r\n }\r\n\r\n public static addHeader(audio: ArrayBuffer, format: AudioOutputFormatImpl): ArrayBuffer {\r\n if (!format.hasHeader) {\r\n return audio;\r\n }\r\n format.updateHeader(audio.byteLength);\r\n const tmp = new Uint8Array(audio.byteLength + format.header.byteLength);\r\n tmp.set(new Uint8Array(format.header), 0);\r\n tmp.set(new Uint8Array(audio), format.header.byteLength);\r\n return tmp.buffer;\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public async dispose(reason?: string): Promise {\r\n this.privIsDisposed = true;\r\n if (this.privSessionAudioDestination !== undefined) {\r\n this.privSessionAudioDestination.close();\r\n }\r\n if (this.privConnectionConfigurationPromise) {\r\n const connection: IConnection = await this.privConnectionConfigurationPromise;\r\n await connection.dispose(reason);\r\n }\r\n }\r\n\r\n public async connect(): Promise {\r\n await this.connectImpl();\r\n }\r\n\r\n public async sendNetworkMessage(path: string, payload: string | ArrayBuffer): Promise {\r\n const type: MessageType = typeof payload === \"string\" ? MessageType.Text : MessageType.Binary;\r\n const contentType: string = typeof payload === \"string\" ? \"application/json\" : \"\";\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n return connection.send(new SpeechConnectionMessage(type, path, this.privSynthesisTurn.requestId, contentType, payload));\r\n }\r\n\r\n public async Speak(\r\n text: string,\r\n isSSML: boolean,\r\n requestId: string,\r\n successCallback: (e: SpeechSynthesisResult) => void,\r\n errorCallBack: (e: string) => void,\r\n audioDestination: IAudioDestination,\r\n ): Promise {\r\n\r\n let ssml: string;\r\n\r\n if (isSSML) {\r\n ssml = text;\r\n } else {\r\n ssml = this.privSpeechSynthesizer.buildSsml(text);\r\n }\r\n\r\n if (this.speakOverride !== undefined) {\r\n return this.speakOverride(ssml, requestId, successCallback, errorCallBack);\r\n }\r\n\r\n this.privSuccessCallback = successCallback;\r\n this.privErrorCallback = errorCallBack;\r\n\r\n this.privSynthesisTurn.startNewSynthesis(requestId, text, isSSML, audioDestination);\r\n\r\n try {\r\n await this.connectImpl();\r\n const connection: IConnection = await this.fetchConnection();\r\n await this.sendSynthesisContext(connection);\r\n await this.sendSsmlMessage(connection, ssml, requestId);\r\n const synthesisStartEventArgs: SpeechSynthesisEventArgs = new SpeechSynthesisEventArgs(\r\n new SpeechSynthesisResult(\r\n requestId,\r\n ResultReason.SynthesizingAudioStarted,\r\n )\r\n );\r\n\r\n if (!!this.privSpeechSynthesizer.synthesisStarted) {\r\n this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer, synthesisStartEventArgs);\r\n }\r\n\r\n const messageRetrievalPromise = this.receiveMessage();\r\n } catch (e) {\r\n this.cancelSynthesisLocal(CancellationReason.Error, CancellationErrorCode.ConnectionFailure, e);\r\n return Promise.reject(e);\r\n }\r\n }\r\n\r\n // Cancels synthesis.\r\n protected cancelSynthesis(\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n const result: SpeechSynthesisResult = new SpeechSynthesisResult(\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined,\r\n error,\r\n properties\r\n );\r\n\r\n if (!!this.privSpeechSynthesizer.SynthesisCanceled) {\r\n const cancelEvent: SpeechSynthesisEventArgs = new SpeechSynthesisEventArgs(result);\r\n try {\r\n this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n\r\n // Cancels synthesis.\r\n protected cancelSynthesisLocal(\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n if (!!this.privSynthesisTurn.isSynthesizing) {\r\n this.privSynthesisTurn.onStopSynthesizing();\r\n\r\n this.cancelSynthesis(\r\n this.privSynthesisTurn.requestId,\r\n cancellationReason,\r\n errorCode,\r\n error);\r\n }\r\n }\r\n\r\n protected processTypeSpecificMessages(\r\n connectionMessage: SpeechConnectionMessage,\r\n successCallback?: (e: SpeechSynthesisResult) => void,\r\n errorCallBack?: (e: string) => void): boolean {\r\n return true;\r\n }\r\n\r\n protected async receiveMessage(): Promise {\r\n try {\r\n const connection: IConnection = await this.fetchConnection();\r\n const message: ConnectionMessage = await connection.read();\r\n\r\n if (this.receiveMessageOverride !== undefined) {\r\n return this.receiveMessageOverride();\r\n }\r\n if (this.privIsDisposed) {\r\n // We're done.\r\n return;\r\n }\r\n\r\n // indicates we are draining the queue and it came with no message;\r\n if (!message) {\r\n if (!this.privSynthesisTurn.isSynthesizing) {\r\n return;\r\n } else {\r\n return this.receiveMessage();\r\n }\r\n }\r\n\r\n this.privServiceHasSentMessage = true;\r\n\r\n const connectionMessage = SpeechConnectionMessage.fromConnectionMessage(message);\r\n\r\n if (connectionMessage.requestId.toLowerCase() === this.privSynthesisTurn.requestId.toLowerCase()) {\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"turn.start\":\r\n this.privSynthesisTurn.onServiceTurnStartResponse();\r\n break;\r\n case \"response\":\r\n this.privSynthesisTurn.onServiceResponseMessage(connectionMessage.textBody);\r\n break;\r\n case \"audio\":\r\n if (this.privSynthesisTurn.streamId.toLowerCase() === connectionMessage.streamId.toLowerCase()\r\n && !!connectionMessage.binaryBody) {\r\n this.privSynthesisTurn.onAudioChunkReceived(connectionMessage.binaryBody);\r\n if (!!this.privSpeechSynthesizer.synthesizing) {\r\n try {\r\n const audioWithHeader = SynthesisAdapterBase.addHeader(connectionMessage.binaryBody, this.privSynthesisTurn.audioOutputFormat);\r\n const ev: SpeechSynthesisEventArgs = new SpeechSynthesisEventArgs(\r\n new SpeechSynthesisResult(\r\n this.privSynthesisTurn.requestId,\r\n ResultReason.SynthesizingAudio,\r\n audioWithHeader));\r\n this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer, ev);\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n if (this.privSessionAudioDestination !== undefined) {\r\n this.privSessionAudioDestination.write(connectionMessage.binaryBody);\r\n }\r\n }\r\n break;\r\n case \"audio.metadata\":\r\n const metadataList = SynthesisAudioMetadata.fromJSON(connectionMessage.textBody).Metadata;\r\n for (const metadata of metadataList) {\r\n switch (metadata.Type) {\r\n case MetadataType.WordBoundary:\r\n this.privSynthesisTurn.onWordBoundaryEvent(metadata.Data.text.Text);\r\n\r\n const wordBoundaryEventArgs: SpeechSynthesisWordBoundaryEventArgs = new SpeechSynthesisWordBoundaryEventArgs(\r\n metadata.Data.Offset,\r\n metadata.Data.text.Text,\r\n metadata.Data.text.Length,\r\n this.privSynthesisTurn.currentTextOffset);\r\n\r\n if (!!this.privSpeechSynthesizer.wordBoundary) {\r\n try {\r\n this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer, wordBoundaryEventArgs);\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n case MetadataType.Bookmark:\r\n const bookmarkEventArgs: SpeechSynthesisBookmarkEventArgs = new SpeechSynthesisBookmarkEventArgs(\r\n metadata.Data.Offset,\r\n metadata.Data.Bookmark);\r\n\r\n if (!!this.privSpeechSynthesizer.bookmarkReached) {\r\n try {\r\n this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer, bookmarkEventArgs);\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n case MetadataType.Viseme:\r\n\r\n this.privSynthesisTurn.onVisemeMetadataReceived(metadata);\r\n\r\n if (metadata.Data.IsLastAnimation) {\r\n const visemeEventArgs: SpeechSynthesisVisemeEventArgs = new SpeechSynthesisVisemeEventArgs(\r\n metadata.Data.Offset,\r\n metadata.Data.VisemeId,\r\n this.privSynthesisTurn.getAndClearVisemeAnimation());\r\n\r\n if (!!this.privSpeechSynthesizer.visemeReceived) {\r\n try {\r\n this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer, visemeEventArgs);\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n break;\r\n case \"turn.end\":\r\n this.privSynthesisTurn.onServiceTurnEndResponse();\r\n let result: SpeechSynthesisResult;\r\n try {\r\n const audioBuffer: ArrayBuffer = await this.privSynthesisTurn.getAllReceivedAudioWithHeader();\r\n result = new SpeechSynthesisResult(\r\n this.privSynthesisTurn.requestId,\r\n ResultReason.SynthesizingAudioCompleted,\r\n audioBuffer\r\n );\r\n if (!!this.privSuccessCallback) {\r\n this.privSuccessCallback(result);\r\n }\r\n } catch (error) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(error);\r\n }\r\n }\r\n if (this.privSpeechSynthesizer.synthesisCompleted) {\r\n try {\r\n this.privSpeechSynthesizer.synthesisCompleted(\r\n this.privSpeechSynthesizer,\r\n new SpeechSynthesisEventArgs(result)\r\n );\r\n } catch (e) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n\r\n default:\r\n\r\n if (!this.processTypeSpecificMessages(connectionMessage)) {\r\n // here are some messages that the derived class has not processed, dispatch them to connect class\r\n if (!!this.privServiceEvents) {\r\n this.serviceEvents.onEvent(new ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));\r\n }\r\n }\r\n\r\n }\r\n }\r\n\r\n return this.receiveMessage();\r\n\r\n } catch (e) {\r\n // TODO: What goes here?\r\n }\r\n }\r\n\r\n protected sendSynthesisContext = (connection: IConnection): Promise => {\r\n const synthesisContextJson = this.synthesisContext.toJSON();\r\n\r\n if (synthesisContextJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"synthesis.context\",\r\n this.privSynthesisTurn.requestId,\r\n \"application/json\",\r\n synthesisContextJson));\r\n }\r\n return;\r\n }\r\n\r\n protected connectImpl(isUnAuthorized: boolean = false): Promise {\r\n if (this.privConnectionPromise) {\r\n return this.privConnectionPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.connectImpl();\r\n }\r\n return this.privConnectionPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.connectImpl();\r\n });\r\n }\r\n this.privAuthFetchEventId = createNoDashGuid();\r\n this.privConnectionId = createNoDashGuid();\r\n\r\n this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId);\r\n\r\n const authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId);\r\n\r\n this.privConnectionPromise = authPromise.then(async (result: AuthInfo) => {\r\n await this.privSynthesisTurn.onAuthCompleted(false);\r\n\r\n const connection: IConnection = this.privConnectionFactory.create(this.privSynthesizerConfig, result, this.privConnectionId);\r\n\r\n // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away,\r\n // it'll stop sending events.\r\n connection.events.attach((event: ConnectionEvent) => {\r\n this.connectionEvents.onEvent(event);\r\n });\r\n const response = await connection.open();\r\n if (response.statusCode === 200) {\r\n await this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode);\r\n return Promise.resolve(connection);\r\n } else if (response.statusCode === 403 && !isUnAuthorized) {\r\n return this.connectImpl(true);\r\n } else {\r\n await this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode, response.reason);\r\n return Promise.reject(`Unable to contact server. StatusCode: ${response.statusCode}, ${this.privSynthesizerConfig.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint)} Reason: ${response.reason}`);\r\n }\r\n }, async (error: string): Promise => {\r\n await this.privSynthesisTurn.onAuthCompleted(true, error);\r\n throw new Error(error);\r\n });\r\n\r\n // Attach an empty handler to allow the promise to run in the background while\r\n // other startup events happen. It'll eventually be awaited on.\r\n this.privConnectionPromise.catch(() => { });\r\n\r\n return this.privConnectionPromise;\r\n }\r\n protected sendSpeechServiceConfig = (connection: IConnection, SpeechServiceConfigJson: string): Promise => {\r\n if (SpeechServiceConfigJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.config\",\r\n this.privSynthesisTurn.requestId,\r\n \"application/json\",\r\n SpeechServiceConfigJson));\r\n }\r\n }\r\n\r\n protected sendSsmlMessage = (connection: IConnection, ssml: string, requestId: string): Promise => {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"ssml\",\r\n requestId,\r\n \"application/ssml+xml\",\r\n ssml));\r\n }\r\n\r\n private async fetchConnection(): Promise {\r\n if (this.privConnectionConfigurationPromise) {\r\n return this.privConnectionConfigurationPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigurationPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.fetchConnection();\r\n }\r\n return this.privConnectionConfigurationPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigurationPromise = null;\r\n this.privServiceHasSentMessage = false;\r\n return this.fetchConnection();\r\n });\r\n }\r\n this.privConnectionConfigurationPromise = this.configureConnection();\r\n return await this.privConnectionConfigurationPromise;\r\n }\r\n\r\n // Takes an established websocket connection to the endpoint and sends speech configuration information.\r\n private async configureConnection(): Promise {\r\n const connection: IConnection = await this.connectImpl();\r\n if (this.configConnectionOverride !== undefined) {\r\n return this.configConnectionOverride(connection);\r\n }\r\n await this.sendSpeechServiceConfig(connection, this.privSynthesizerConfig.SpeechServiceConfig.serialize());\r\n return connection;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport { SpeechSynthesizer } from \"../sdk/Exports\";\r\n\r\n/**\r\n * Represents the JSON used in the synthesis.context message sent to the speech service.\r\n * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object.\r\n */\r\nexport class SynthesisContext {\r\n private privContext: { [section: string]: any } = {};\r\n private privSpeechSynthesizer: SpeechSynthesizer;\r\n private privAudioOutputFormat: AudioOutputFormatImpl;\r\n\r\n constructor(speechSynthesizer: SpeechSynthesizer) {\r\n this.privSpeechSynthesizer = speechSynthesizer;\r\n }\r\n\r\n /**\r\n * Adds a section to the synthesis.context object.\r\n * @param sectionName Name of the section to add.\r\n * @param value JSON serializable object that represents the value.\r\n */\r\n public setSection(sectionName: string, value: any): void {\r\n this.privContext[sectionName] = value;\r\n }\r\n\r\n /**\r\n * Sets the audio output format for synthesis context generation.\r\n * @param format {AudioOutputFormatImpl} the output format\r\n */\r\n public set audioOutputFormat(format: AudioOutputFormatImpl) {\r\n this.privAudioOutputFormat = format;\r\n }\r\n\r\n public toJSON(): string {\r\n\r\n const synthesisSection: ISynthesisSection = this.buildSynthesisContext();\r\n this.setSection(\"synthesis\", synthesisSection);\r\n\r\n return JSON.stringify(this.privContext);\r\n }\r\n\r\n private buildSynthesisContext(): ISynthesisSection {\r\n return {\r\n audio: {\r\n metadataOptions: {\r\n bookmarkEnabled: (!!this.privSpeechSynthesizer.bookmarkReached),\r\n sentenceBoundaryEnabled: false,\r\n visemeEnabled: (!!this.privSpeechSynthesizer.visemeReceived),\r\n wordBoundaryEnabled: (!!this.privSpeechSynthesizer.wordBoundary),\r\n },\r\n outputFormat: this.privAudioOutputFormat.requestAudioFormatString,\r\n },\r\n language: {\r\n autoDetection: this.privSpeechSynthesizer.autoDetectSourceLanguage\r\n }\r\n };\r\n }\r\n}\r\n\r\ninterface ISynthesisSection {\r\n audio: {\r\n outputFormat: string,\r\n metadataOptions: {\r\n bookmarkEnabled: boolean,\r\n wordBoundaryEnabled: boolean,\r\n visemeEnabled: boolean,\r\n sentenceBoundaryEnabled: boolean,\r\n }\r\n };\r\n language: {\r\n autoDetection: boolean\r\n };\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { EventType, PlatformEvent } from \"../common/Exports\";\r\n\r\nexport class SpeechSynthesisEvent extends PlatformEvent {\r\n private privRequestId: string;\r\n\r\n constructor(eventName: string, requestId: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n\r\n this.privRequestId = requestId;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n}\r\n\r\nexport class SynthesisTriggeredEvent extends SpeechSynthesisEvent {\r\n private privSessionAudioDestinationId: string;\r\n private privTurnAudioDestinationId: string;\r\n\r\n constructor(requestId: string, sessionAudioDestinationId: string, turnAudioDestinationId: string) {\r\n super(\"SynthesisTriggeredEvent\", requestId);\r\n\r\n this.privSessionAudioDestinationId = sessionAudioDestinationId;\r\n this.privTurnAudioDestinationId = turnAudioDestinationId;\r\n }\r\n\r\n public get audioSessionDestinationId(): string {\r\n return this.privSessionAudioDestinationId;\r\n }\r\n\r\n public get audioTurnDestinationId(): string {\r\n return this.privTurnAudioDestinationId;\r\n }\r\n}\r\n\r\nexport class ConnectingToSynthesisServiceEvent extends SpeechSynthesisEvent {\r\n private privAuthFetchEventId: string;\r\n\r\n constructor(requestId: string, authFetchEventId: string) {\r\n super(\"ConnectingToSynthesisServiceEvent\", requestId);\r\n this.privAuthFetchEventId = authFetchEventId;\r\n }\r\n\r\n public get authFetchEventId(): string {\r\n return this.privAuthFetchEventId;\r\n }\r\n}\r\n\r\nexport class SynthesisStartedEvent extends SpeechSynthesisEvent {\r\n private privAuthFetchEventId: string;\r\n\r\n constructor(requestId: string, authFetchEventId: string) {\r\n super(\"SynthesisStartedEvent\", requestId);\r\n\r\n this.privAuthFetchEventId = authFetchEventId;\r\n }\r\n\r\n public get authFetchEventId(): string {\r\n return this.privAuthFetchEventId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n Events, IAudioDestination\r\n} from \"../common/Exports\";\r\nimport { AudioOutputFormatImpl } from \"../sdk/Audio/AudioOutputFormat\";\r\nimport { PullAudioOutputStreamImpl } from \"../sdk/Audio/AudioOutputStream\";\r\nimport { ISynthesisMetadata } from \"./ServiceMessages/SynthesisAudioMetadata\";\r\nimport { SynthesisAdapterBase } from \"./SynthesisAdapterBase\";\r\nimport {\r\n ConnectingToSynthesisServiceEvent,\r\n SpeechSynthesisEvent,\r\n SynthesisStartedEvent,\r\n SynthesisTriggeredEvent,\r\n} from \"./SynthesisEvents\";\r\n\r\nexport interface ISynthesisResponseContext {\r\n serviceTag: string;\r\n}\r\n\r\nexport interface ISynthesisResponseAudio {\r\n type: string;\r\n streamId: string;\r\n}\r\n\r\nexport interface ISynthesisResponse {\r\n context: ISynthesisResponseContext;\r\n audio: ISynthesisResponseAudio;\r\n}\r\n\r\nexport class SynthesisTurn {\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get streamId(): string {\r\n return this.privStreamId;\r\n }\r\n\r\n public set streamId(value: string) {\r\n this.privStreamId = value;\r\n }\r\n\r\n public get audioOutputFormat(): AudioOutputFormatImpl {\r\n return this.privAudioOutputFormat;\r\n }\r\n\r\n public set audioOutputFormat(format: AudioOutputFormatImpl) {\r\n this.privAudioOutputFormat = format;\r\n }\r\n\r\n public get turnCompletionPromise(): Promise {\r\n return this.privTurnDeferral.promise;\r\n }\r\n\r\n public get isSynthesisEnded(): boolean {\r\n return this.privIsSynthesisEnded;\r\n }\r\n\r\n public get isSynthesizing(): boolean {\r\n return this.privIsSynthesizing;\r\n }\r\n\r\n public get currentTextOffset(): number {\r\n return this.privTextOffset;\r\n }\r\n\r\n // The number of bytes received for current turn\r\n public get bytesReceived(): number {\r\n return this.privBytesReceived;\r\n }\r\n\r\n private privIsDisposed: boolean = false;\r\n private privAuthFetchEventId: string;\r\n private privIsSynthesizing: boolean = false;\r\n private privIsSynthesisEnded: boolean = false;\r\n private privBytesReceived: number = 0;\r\n private privRequestId: string;\r\n private privStreamId: string;\r\n private privTurnDeferral: Deferred;\r\n private privInTurn: boolean = false;\r\n private privAudioOutputFormat: AudioOutputFormatImpl;\r\n private privAudioOutputStream: PullAudioOutputStreamImpl;\r\n private privReceivedAudio: ArrayBuffer;\r\n private privReceivedAudioWithHeader: ArrayBuffer;\r\n private privTextOffset: number = 0;\r\n private privNextSearchTextIndex: number = 0;\r\n private privPartialVisemeAnimation: string;\r\n private privRawText: string;\r\n private privIsSSML: boolean;\r\n private privTurnAudioDestination: IAudioDestination;\r\n\r\n constructor() {\r\n this.privRequestId = createNoDashGuid();\r\n this.privTurnDeferral = new Deferred();\r\n\r\n // We're not in a turn, so resolve.\r\n this.privTurnDeferral.resolve();\r\n }\r\n\r\n public async getAllReceivedAudio(): Promise {\r\n if (!!this.privReceivedAudio) {\r\n return Promise.resolve(this.privReceivedAudio);\r\n }\r\n if (!this.privIsSynthesisEnded) {\r\n return null;\r\n }\r\n await this.readAllAudioFromStream();\r\n return Promise.resolve(this.privReceivedAudio);\r\n }\r\n\r\n public async getAllReceivedAudioWithHeader(): Promise {\r\n if (!!this.privReceivedAudioWithHeader) {\r\n return this.privReceivedAudioWithHeader;\r\n }\r\n if (!this.privIsSynthesisEnded) {\r\n return null;\r\n }\r\n if (this.audioOutputFormat.hasHeader) {\r\n const audio: ArrayBuffer = await this.getAllReceivedAudio();\r\n this.privReceivedAudioWithHeader = SynthesisAdapterBase.addHeader(audio, this.audioOutputFormat);\r\n return this.privReceivedAudioWithHeader;\r\n } else {\r\n return this.getAllReceivedAudio();\r\n }\r\n }\r\n\r\n public startNewSynthesis(requestId: string, rawText: string, isSSML: boolean, audioDestination?: IAudioDestination): void {\r\n this.privIsSynthesisEnded = false;\r\n this.privIsSynthesizing = true;\r\n this.privRequestId = requestId;\r\n this.privRawText = rawText;\r\n this.privIsSSML = isSSML;\r\n this.privAudioOutputStream = new PullAudioOutputStreamImpl();\r\n this.privAudioOutputStream.format = this.privAudioOutputFormat;\r\n this.privReceivedAudio = null;\r\n this.privReceivedAudioWithHeader = null;\r\n this.privBytesReceived = 0;\r\n this.privTextOffset = 0;\r\n this.privNextSearchTextIndex = 0;\r\n this.privPartialVisemeAnimation = \"\";\r\n if (audioDestination !== undefined) {\r\n this.privTurnAudioDestination = audioDestination;\r\n this.privTurnAudioDestination.format = this.privAudioOutputFormat;\r\n }\r\n this.onEvent(new SynthesisTriggeredEvent(this.requestId, undefined, audioDestination === undefined ? undefined : audioDestination.id()));\r\n }\r\n\r\n public onPreConnectionStart = (authFetchEventId: string, connectionId: string): void => {\r\n this.privAuthFetchEventId = authFetchEventId;\r\n this.onEvent(new ConnectingToSynthesisServiceEvent(this.privRequestId, this.privAuthFetchEventId));\r\n }\r\n\r\n public onAuthCompleted = (isError: boolean, error?: string): void => {\r\n if (isError) {\r\n this.onComplete();\r\n }\r\n }\r\n\r\n public onConnectionEstablishCompleted = (statusCode: number, reason?: string): void => {\r\n if (statusCode === 200) {\r\n this.onEvent(new SynthesisStartedEvent(this.requestId, this.privAuthFetchEventId));\r\n this.privBytesReceived = 0;\r\n return;\r\n } else if (statusCode === 403) {\r\n this.onComplete();\r\n }\r\n }\r\n\r\n public onServiceResponseMessage = (responseJson: string): void => {\r\n const response: ISynthesisResponse = JSON.parse(responseJson);\r\n this.streamId = response.audio.streamId;\r\n }\r\n\r\n public onServiceTurnEndResponse = (): void => {\r\n this.privInTurn = false;\r\n this.privTurnDeferral.resolve();\r\n this.onComplete();\r\n }\r\n\r\n public onServiceTurnStartResponse = (): void => {\r\n if (!!this.privTurnDeferral && !!this.privInTurn) {\r\n // What? How are we starting a turn with another not done?\r\n this.privTurnDeferral.reject(\"Another turn started before current completed.\");\r\n // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited\r\n /* tslint:disable:no-empty */\r\n this.privTurnDeferral.promise.then().catch(() => { });\r\n }\r\n this.privInTurn = true;\r\n this.privTurnDeferral = new Deferred();\r\n }\r\n\r\n public onAudioChunkReceived(data: ArrayBuffer): void {\r\n if (this.isSynthesizing) {\r\n this.privAudioOutputStream.write(data);\r\n this.privBytesReceived += data.byteLength;\r\n if (this.privTurnAudioDestination !== undefined) {\r\n this.privTurnAudioDestination.write(data);\r\n }\r\n }\r\n }\r\n\r\n public onWordBoundaryEvent(text: string): void {\r\n this.updateTextOffset(text);\r\n }\r\n\r\n public onVisemeMetadataReceived(metadata: ISynthesisMetadata): void {\r\n if (metadata.Data.AnimationChunk !== undefined) {\r\n this.privPartialVisemeAnimation += metadata.Data.AnimationChunk;\r\n }\r\n }\r\n\r\n public dispose = (error?: string): void => {\r\n if (!this.privIsDisposed) {\r\n // we should have completed by now. If we did not its an unknown error.\r\n this.privIsDisposed = true;\r\n }\r\n }\r\n\r\n public onStopSynthesizing(): void {\r\n this.onComplete();\r\n }\r\n\r\n /**\r\n * Gets the viseme animation string (merged from animation chunk), and clears the internal\r\n * partial animation.\r\n */\r\n public getAndClearVisemeAnimation(): string {\r\n const animation: string = this.privPartialVisemeAnimation;\r\n this.privPartialVisemeAnimation = \"\";\r\n return animation;\r\n }\r\n\r\n protected onEvent = (event: SpeechSynthesisEvent): void => {\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private updateTextOffset(text: string): void {\r\n if (this.privTextOffset >= 0) {\r\n this.privTextOffset = this.privRawText.indexOf(text, this.privNextSearchTextIndex);\r\n if (this.privTextOffset >= 0) {\r\n this.privNextSearchTextIndex = this.privTextOffset + text.length;\r\n }\r\n if (this.privIsSSML) {\r\n if (this.privRawText.indexOf(\"<\", this.privTextOffset + 1) > this.privRawText.indexOf(\">\", this.privTextOffset + 1)) {\r\n this.updateTextOffset(text);\r\n }\r\n }\r\n }\r\n }\r\n\r\n private onComplete = (): void => {\r\n if (this.privIsSynthesizing) {\r\n this.privIsSynthesizing = false;\r\n this.privIsSynthesisEnded = true;\r\n this.privAudioOutputStream.close();\r\n this.privInTurn = false;\r\n if (this.privTurnAudioDestination !== undefined) {\r\n this.privTurnAudioDestination.close();\r\n this.privTurnAudioDestination = undefined;\r\n }\r\n }\r\n }\r\n\r\n private async readAllAudioFromStream(): Promise {\r\n if (this.privIsSynthesisEnded) {\r\n this.privReceivedAudio = new ArrayBuffer(this.bytesReceived);\r\n try {\r\n await this.privAudioOutputStream.read(this.privReceivedAudio);\r\n } catch (e) {\r\n this.privReceivedAudio = new ArrayBuffer(0);\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PropertyCollection } from \"../sdk/Exports\";\r\nimport {Context, SpeechServiceConfig} from \"./Exports\";\r\n\r\nexport enum SynthesisServiceType {\r\n Standard,\r\n Custom,\r\n}\r\n\r\nexport class SynthesizerConfig {\r\n private privSynthesisServiceType: SynthesisServiceType = SynthesisServiceType.Standard;\r\n private privSpeechServiceConfig: SpeechServiceConfig;\r\n private privParameters: PropertyCollection;\r\n\r\n constructor(\r\n speechServiceConfig: SpeechServiceConfig,\r\n parameters: PropertyCollection) {\r\n this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new SpeechServiceConfig(new Context(null));\r\n this.privParameters = parameters;\r\n }\r\n\r\n public get parameters(): PropertyCollection {\r\n return this.privParameters;\r\n }\r\n\r\n public get synthesisServiceType(): SynthesisServiceType {\r\n return this.privSynthesisServiceType;\r\n }\r\n\r\n public set synthesisServiceType(value: SynthesisServiceType) {\r\n this.privSynthesisServiceType = value;\r\n }\r\n\r\n public get SpeechServiceConfig(): SpeechServiceConfig {\r\n return this.privSpeechServiceConfig;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n OutputFormatPropertyName,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary\r\n} from \"../common/Exports\";\r\nimport {\r\n OutputFormat,\r\n PropertyId\r\n} from \"../sdk/Exports\";\r\nimport {\r\n ConnectionFactoryBase\r\n} from \"./ConnectionFactoryBase\";\r\nimport {\r\n AuthInfo,\r\n RecognizerConfig,\r\n WebsocketMessageFormatter\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport {\r\n QueryParameterNames\r\n} from \"./QueryParameterNames\";\r\n\r\nexport class TranscriberConnectionFactory extends ConnectionFactoryBase {\r\n\r\n private readonly multiaudioRelativeUri: string = \"/speech/recognition/multiaudio\";\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, \"centralus\");\r\n const hostSuffix: string = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const hostDefault: string = \"wss://transcribe.\" + region + \".cts.speech\" + hostSuffix + this.multiaudioRelativeUri;\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, hostDefault);\r\n\r\n const queryParams: IStringDictionary = {};\r\n\r\n const endpointId: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_EndpointId, undefined);\r\n const language: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, undefined);\r\n\r\n if (endpointId) {\r\n if (!endpoint || endpoint.search(QueryParameterNames.CustomSpeechDeploymentId) === -1) {\r\n queryParams[QueryParameterNames.CustomSpeechDeploymentId] = endpointId;\r\n }\r\n } else if (language) {\r\n if (!endpoint || endpoint.search(QueryParameterNames.Language) === -1) {\r\n queryParams[QueryParameterNames.Language] = language;\r\n }\r\n }\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n if (!endpoint) {\r\n endpoint = host;\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IAudioSource,\r\n IConnection,\r\n MessageType\r\n} from \"../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n ConversationTranscriptionCanceledEventArgs,\r\n OutputFormat,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult,\r\n} from \"../sdk/Exports\";\r\nimport { ConversationInfo } from \"../sdk/Transcription/Exports\";\r\nimport {\r\n CancellationErrorCodePropertyName,\r\n DetailedSpeechPhrase,\r\n EnumTranslation,\r\n OutputFormatPropertyName,\r\n RecognitionStatus,\r\n ServiceRecognizerBase,\r\n SimpleSpeechPhrase,\r\n SpeechHypothesis,\r\n TranscriberRecognizer\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class TranscriptionServiceRecognizer extends ServiceRecognizerBase {\r\n\r\n private privTranscriberRecognizer: TranscriberRecognizer;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n transcriber: TranscriberRecognizer) {\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, transcriber);\r\n this.privTranscriberRecognizer = transcriber;\r\n this.sendPrePayloadJSONOverride = this.sendTranscriptionStartJSON;\r\n }\r\n\r\n public async sendSpeechEventAsync(info: ConversationInfo, command: string): Promise {\r\n if (!!this.privRequestSession.isRecognizing) {\r\n const connection: IConnection = await this.fetchConnection();\r\n await this.sendSpeechEvent(connection, this.createSpeechEventPayload(info, command));\r\n }\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n let result: SpeechRecognitionResult;\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n let processed: boolean = false;\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"speech.hypothesis\":\r\n case \"speech.fragment\":\r\n const hypothesis: SpeechHypothesis = SpeechHypothesis.fromJSON(connectionMessage.textBody);\r\n const offset: number = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n ResultReason.RecognizingSpeech,\r\n hypothesis.Text,\r\n hypothesis.Duration,\r\n offset,\r\n hypothesis.Language,\r\n hypothesis.LanguageDetectionConfidence,\r\n hypothesis.SpeakerId,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n this.privRequestSession.onHypothesis(offset);\r\n\r\n const ev = new SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privTranscriberRecognizer.recognizing) {\r\n try {\r\n this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"speech.phrase\":\r\n const simple: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n const resultReason: ResultReason = EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus);\r\n\r\n this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + simple.Offset + simple.Duration);\r\n\r\n if (ResultReason.Canceled === resultReason) {\r\n const cancelReason: CancellationReason = EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);\r\n\r\n await this.cancelRecognitionLocal(\r\n cancelReason,\r\n EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus),\r\n undefined);\r\n\r\n } else {\r\n if (!(this.privRequestSession.isSpeechEnded && resultReason === ResultReason.NoMatch && simple.RecognitionStatus !== RecognitionStatus.InitialSilenceTimeout)) {\r\n if (this.privRecognizerConfig.parameters.getProperty(OutputFormatPropertyName) === OutputFormat[OutputFormat.Simple]) {\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n simple.DisplayText,\r\n simple.Duration,\r\n simple.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n simple.Language,\r\n simple.LanguageDetectionConfidence,\r\n simple.SpeakerId,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n } else {\r\n const detailed: DetailedSpeechPhrase = DetailedSpeechPhrase.fromJSON(connectionMessage.textBody);\r\n\r\n result = new SpeechRecognitionResult(\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n detailed.RecognitionStatus === RecognitionStatus.Success ? detailed.NBest[0].Display : undefined,\r\n detailed.Duration,\r\n detailed.Offset + this.privRequestSession.currentTurnAudioOffset,\r\n detailed.Language,\r\n detailed.LanguageDetectionConfidence,\r\n undefined,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n }\r\n\r\n const event: SpeechRecognitionEventArgs = new SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privTranscriberRecognizer.recognized) {\r\n try {\r\n this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer, event);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n }\r\n processed = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n if (!!this.privTranscriberRecognizer.canceled) {\r\n const cancelEvent: ConversationTranscriptionCanceledEventArgs = new ConversationTranscriptionCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n sessionId);\r\n try {\r\n this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: SpeechRecognitionResult = new SpeechRecognitionResult(\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Duration\r\n undefined, // Offset\r\n undefined, // Language\r\n undefined, // Language Detection Confidence\r\n undefined, // Speaker Id\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n this.privSuccessCallback = undefined;\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n }\r\n\r\n // Encapsulated for derived service recognizers that need to send additional JSON\r\n protected async sendTranscriptionStartJSON(connection: IConnection): Promise {\r\n await this.sendSpeechContext(connection);\r\n const info: ConversationInfo = this.privTranscriberRecognizer.getConversationInfo();\r\n const payload: { [id: string]: any } = this.createSpeechEventPayload(info, \"start\");\r\n await this.sendSpeechEvent(connection, payload);\r\n await this.sendWaveHeader(connection);\r\n return;\r\n }\r\n\r\n protected sendSpeechEvent = (connection: IConnection, payload: { [id: string]: any }): Promise => {\r\n const speechEventJson = JSON.stringify(payload);\r\n\r\n if (speechEventJson) {\r\n return connection.send(new SpeechConnectionMessage(\r\n MessageType.Text,\r\n \"speech.event\",\r\n this.privRequestSession.requestId,\r\n \"application/json\",\r\n speechEventJson));\r\n }\r\n return;\r\n }\r\n\r\n private createSpeechEventPayload(info: ConversationInfo, command: string): { [id: string]: any } {\r\n const meeting: string = \"meeting\";\r\n const eventDict: { [id: string]: any } = { id: meeting, name: command, meeting: info.conversationProperties };\r\n const idString: string = \"id\";\r\n const attendees: string = \"attendees\";\r\n const record: string = \"record\";\r\n eventDict[meeting][idString] = info.id;\r\n eventDict[meeting][attendees] = info.participants;\r\n eventDict[meeting][record] = info.conversationProperties.audiorecording === \"on\" ? \"true\" : \"false\";\r\n return eventDict;\r\n }\r\n}\r\n","\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n RestConfigBase\r\n} from \"../../common.browser/RestConfigBase\";\r\n\r\nexport class ConversationConnectionConfig extends RestConfigBase {\r\n\r\n private static readonly privHost: string = \"dev.microsofttranslator.com\";\r\n private static readonly privRestPath: string = \"/capito/room\";\r\n private static readonly privApiVersion: string = \"2.0\";\r\n private static readonly privDefaultLanguageCode: string = \"en-US\";\r\n private static readonly privClientAppId: string = \"FC539C22-1767-4F1F-84BC-B4D811114F15\";\r\n private static readonly privWebSocketPath: string = \"/capito/translate\";\r\n private static readonly privSpeechHost: string = \"{region}.s2s.speech.microsoft.com\";\r\n private static readonly privSpeechPath: string = \"/speech/translation/cognitiveservices/v1\";\r\n private static readonly privTranscriptionEventKeys: string[] = [\"iCalUid\", \"callId\", \"organizer\", \"FLAC\", \"MTUri\", \"DifferenciateGuestSpeakers\", \"audiorecording\", \"Threadid\", \"OrganizerMri\", \"OrganizerTenantId\", \"UserToken\"];\r\n\r\n public static get host(): string {\r\n return ConversationConnectionConfig.privHost;\r\n }\r\n\r\n public static get apiVersion(): string {\r\n return ConversationConnectionConfig.privApiVersion;\r\n }\r\n\r\n public static get clientAppId(): string {\r\n return ConversationConnectionConfig.privClientAppId;\r\n }\r\n\r\n public static get defaultLanguageCode(): string {\r\n return ConversationConnectionConfig.privDefaultLanguageCode;\r\n }\r\n\r\n public static get restPath(): string {\r\n return ConversationConnectionConfig.privRestPath;\r\n }\r\n\r\n public static get webSocketPath(): string {\r\n return ConversationConnectionConfig.privWebSocketPath;\r\n }\r\n\r\n public static get speechHost(): string {\r\n return ConversationConnectionConfig.privSpeechHost;\r\n }\r\n\r\n public static get speechPath(): string {\r\n return ConversationConnectionConfig.privSpeechPath;\r\n }\r\n\r\n public static get transcriptionEventKeys(): string[] {\r\n return ConversationConnectionConfig.privTranscriptionEventKeys;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ProxyInfo, WebsocketConnection } from \"../../common.browser/Exports\";\r\nimport { createGuid, IConnection, IStringDictionary } from \"../../common/Exports\";\r\nimport { Contracts } from \"../../sdk/Contracts\";\r\nimport { PropertyId } from \"../../sdk/Exports\";\r\nimport { ConnectionFactoryBase } from \"../ConnectionFactoryBase\";\r\nimport { AuthInfo, RecognizerConfig } from \"../Exports\";\r\nimport { ConversationConnectionConfig } from \"./ConversationConnectionConfig\";\r\nimport { ConversationWebsocketMessageFormatter } from \"./ConversationWebsocketMessageFormatter\";\r\n\r\n/**\r\n * Create a connection to the Conversation Translator websocket for sending instant messages and commands, and for receiving translated messages.\r\n * The conversation must already have been started or joined.\r\n */\r\nexport class ConversationConnectionFactory extends ConnectionFactoryBase {\r\n\r\n public create(config: RecognizerConfig, authInfo: AuthInfo, connectionId?: string): IConnection {\r\n\r\n const endpointHost: string = config.parameters.getProperty(PropertyId.ConversationTranslator_Host, ConversationConnectionConfig.host);\r\n const correlationId: string = config.parameters.getProperty(PropertyId.ConversationTranslator_CorrelationId, createGuid());\r\n\r\n const endpoint: string = `wss://${endpointHost}${ConversationConnectionConfig.webSocketPath}`;\r\n const token: string = config.parameters.getProperty(PropertyId.ConversationTranslator_Token, undefined);\r\n Contracts.throwIfNullOrUndefined(token, \"token\");\r\n\r\n const queryParams: IStringDictionary = {};\r\n queryParams[ConversationConnectionConfig.configParams.apiVersion] = ConversationConnectionConfig.apiVersion;\r\n queryParams[ConversationConnectionConfig.configParams.token] = token;\r\n queryParams[ConversationConnectionConfig.configParams.correlationId] = correlationId;\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, {}, new ConversationWebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ConnectionMessage, IStringDictionary, MessageType } from \"../../common/Exports\";\r\n\r\nexport class ConversationConnectionMessage extends ConnectionMessage {\r\n private privConversationMessageType: string;\r\n\r\n public constructor(\r\n messageType: MessageType,\r\n body: any,\r\n headers?: IStringDictionary,\r\n id?: string) {\r\n super(messageType, body, headers, id);\r\n const json = JSON.parse(this.textBody);\r\n if (json.type !== undefined) {\r\n this.privConversationMessageType = json.type;\r\n }\r\n }\r\n\r\n public get conversationMessageType(): string {\r\n return this.privConversationMessageType;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IRequestOptions,\r\n IRestParams,\r\n} from \"../../common.browser/RestConfigBase\";\r\nimport { IErrorMessages, IStringDictionary } from \"../../common/Exports\";\r\nimport { Contracts } from \"../../sdk/Contracts\";\r\nimport { PropertyCollection, PropertyId } from \"../../sdk/Exports\";\r\nimport { ConversationConnectionConfig } from \"./ConversationConnectionConfig\";\r\nimport { IConversationResponseError, IInternalConversation, IResponse } from \"./ConversationTranslatorInterfaces\";\r\nimport { extractHeaderValue, request } from \"./ConversationUtils\";\r\n\r\nexport class ConversationManager {\r\n\r\n private privRequestParams: IRestParams;\r\n private privErrors: IErrorMessages;\r\n private privHost: string;\r\n private privApiVersion: string;\r\n private privRestPath: string;\r\n\r\n public constructor() {\r\n //\r\n this.privRequestParams = ConversationConnectionConfig.configParams;\r\n this.privErrors = ConversationConnectionConfig.restErrors;\r\n this.privHost = ConversationConnectionConfig.host;\r\n this.privApiVersion = ConversationConnectionConfig.apiVersion;\r\n this.privRestPath = ConversationConnectionConfig.restPath;\r\n }\r\n\r\n /**\r\n * Make a POST request to the Conversation Manager service endpoint to create or join a conversation.\r\n * @param args\r\n * @param conversationCode\r\n * @param callback\r\n * @param errorCallback\r\n */\r\n public createOrJoin(args: PropertyCollection, conversationCode: string, cb?: any, err?: any): void {\r\n\r\n try {\r\n\r\n Contracts.throwIfNullOrUndefined(args, \"args\");\r\n\r\n const languageCode: string = args.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage, ConversationConnectionConfig.defaultLanguageCode);\r\n const nickname: string = args.getProperty(PropertyId.ConversationTranslator_Name);\r\n const endpointHost: string = args.getProperty(PropertyId.ConversationTranslator_Host, this.privHost);\r\n const correlationId: string = args.getProperty(PropertyId.ConversationTranslator_CorrelationId);\r\n const subscriptionKey: string = args.getProperty(PropertyId.SpeechServiceConnection_Key);\r\n const subscriptionRegion: string = args.getProperty(PropertyId.SpeechServiceConnection_Region);\r\n const authToken: string = args.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n\r\n Contracts.throwIfNullOrWhitespace(languageCode, \"languageCode\");\r\n Contracts.throwIfNullOrWhitespace(nickname, \"nickname\");\r\n Contracts.throwIfNullOrWhitespace(endpointHost, \"endpointHost\");\r\n\r\n const queryParams: IStringDictionary = {};\r\n queryParams[this.privRequestParams.apiVersion] = this.privApiVersion;\r\n queryParams[this.privRequestParams.languageCode] = languageCode;\r\n queryParams[this.privRequestParams.nickname] = nickname;\r\n\r\n const headers: IStringDictionary = {};\r\n if (correlationId) {\r\n headers[this.privRequestParams.correlationId] = correlationId;\r\n }\r\n headers[this.privRequestParams.clientAppId] = ConversationConnectionConfig.clientAppId;\r\n\r\n if (conversationCode !== undefined) {\r\n queryParams[this.privRequestParams.roomId] = conversationCode;\r\n } else {\r\n Contracts.throwIfNullOrUndefined(subscriptionRegion, this.privErrors.authInvalidSubscriptionRegion);\r\n headers[this.privRequestParams.subscriptionRegion] = subscriptionRegion;\r\n if (subscriptionKey) {\r\n headers[this.privRequestParams.subscriptionKey] = subscriptionKey;\r\n } else if (authToken) {\r\n headers[this.privRequestParams.authorization] = `Bearer ${authToken}`;\r\n } else {\r\n Contracts.throwIfNullOrUndefined(subscriptionKey, this.privErrors.authInvalidSubscriptionKey);\r\n }\r\n }\r\n\r\n const config: IRequestOptions = {};\r\n config.headers = headers;\r\n\r\n const endpoint: string = `https://${endpointHost}${this.privRestPath}`;\r\n\r\n // TODO: support a proxy and certificate validation\r\n request(\"post\", endpoint, queryParams, null, config, (response: IResponse) => {\r\n\r\n const requestId: string = extractHeaderValue(this.privRequestParams.requestId, response.headers);\r\n\r\n if (!response.ok) {\r\n if (!!err) {\r\n // get the error\r\n let errorMessage: string = this.privErrors.invalidCreateJoinConversationResponse.replace(\"{status}\", response.status.toString());\r\n let errMessageRaw: IConversationResponseError;\r\n try {\r\n errMessageRaw = JSON.parse(response.data) as IConversationResponseError;\r\n errorMessage += ` [${errMessageRaw.error.code}: ${errMessageRaw.error.message}]`;\r\n } catch (e) {\r\n errorMessage += ` [${response.data}]`;\r\n }\r\n if (requestId) {\r\n errorMessage += ` ${requestId}`;\r\n }\r\n\r\n err(errorMessage);\r\n }\r\n return;\r\n }\r\n const conversation: IInternalConversation = JSON.parse(response.data) as IInternalConversation;\r\n if (conversation) {\r\n conversation.requestId = requestId;\r\n }\r\n if (!!cb) {\r\n try {\r\n cb(conversation);\r\n } catch (e) {\r\n if (!!err) {\r\n err(e);\r\n }\r\n }\r\n cb = undefined;\r\n }\r\n\r\n });\r\n\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n\r\n } else {\r\n err(error);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Make a DELETE request to the Conversation Manager service endpoint to leave the conversation.\r\n * @param args\r\n * @param sessionToken\r\n * @param callback\r\n */\r\n public leave(args: PropertyCollection, sessionToken: string): Promise {\r\n return new Promise((resolve: () => void, reject: (reason: string) => void): void => {\r\n try {\r\n\r\n Contracts.throwIfNullOrUndefined(args, this.privErrors.invalidArgs.replace(\"{arg}\", \"config\"));\r\n Contracts.throwIfNullOrWhitespace(sessionToken, this.privErrors.invalidArgs.replace(\"{arg}\", \"token\"));\r\n\r\n const endpointHost: string = args.getProperty(PropertyId.ConversationTranslator_Host, this.privHost);\r\n const correlationId: string = args.getProperty(PropertyId.ConversationTranslator_CorrelationId);\r\n\r\n const queryParams: IStringDictionary = {};\r\n queryParams[this.privRequestParams.apiVersion] = this.privApiVersion;\r\n queryParams[this.privRequestParams.sessionToken] = sessionToken;\r\n\r\n const headers: IStringDictionary = {};\r\n if (correlationId) {\r\n headers[this.privRequestParams.correlationId] = correlationId;\r\n }\r\n\r\n const config: IRequestOptions = {};\r\n config.headers = headers;\r\n\r\n const endpoint: string = `https://${endpointHost}${this.privRestPath}`;\r\n\r\n // TODO: support a proxy and certificate validation\r\n request(\"delete\", endpoint, queryParams, null, config, (response: IResponse) => {\r\n\r\n if (!response.ok) {\r\n // ignore errors on delete\r\n }\r\n\r\n resolve();\r\n });\r\n\r\n } catch (error) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n reject(typedError.name + \": \" + typedError.message);\r\n\r\n } else {\r\n reject(error);\r\n }\r\n }\r\n });\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n IDetachable,\r\n} from \"../../common/Exports\";\r\n\r\n/**\r\n * Placeholder class for the Conversation Request Session. Based off RequestSession.\r\n * TODO: define what telemetry is required.\r\n */\r\nexport class ConversationRequestSession {\r\n private privIsDisposed: boolean = false;\r\n private privDetachables: IDetachable[] = new Array();\r\n private privRequestId: string;\r\n private privRequestCompletionDeferral: Deferred;\r\n private privSessionId: string;\r\n\r\n constructor(sessionId: string) {\r\n this.privSessionId = sessionId;\r\n this.privRequestId = createNoDashGuid();\r\n this.privRequestCompletionDeferral = new Deferred();\r\n }\r\n\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n\r\n public get requestId(): string {\r\n return this.privRequestId;\r\n }\r\n\r\n public get completionPromise(): Promise {\r\n return this.privRequestCompletionDeferral.promise;\r\n }\r\n\r\n public onPreConnectionStart = (authFetchEventId: string, connectionId: string): void => {\r\n this.privSessionId = connectionId;\r\n }\r\n\r\n public onAuthCompleted = (isError: boolean, error?: string): void => {\r\n if (isError) {\r\n this.onComplete();\r\n }\r\n }\r\n\r\n public onConnectionEstablishCompleted = (statusCode: number, reason?: string): void => {\r\n if (statusCode === 200) {\r\n return;\r\n } else if (statusCode === 403) {\r\n this.onComplete();\r\n }\r\n }\r\n\r\n public onServiceTurnEndResponse = (continuousRecognition: boolean): void => {\r\n if (!continuousRecognition) {\r\n this.onComplete();\r\n } else {\r\n this.privRequestId = createNoDashGuid();\r\n }\r\n }\r\n\r\n public async dispose(error?: string): Promise {\r\n if (!this.privIsDisposed) {\r\n // we should have completed by now. If we did not its an unknown error.\r\n this.privIsDisposed = true;\r\n for (const detachable of this.privDetachables) {\r\n await detachable.detach();\r\n }\r\n }\r\n }\r\n\r\n private onComplete = (): void => {\r\n //\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionMessage,\r\n ConnectionState,\r\n createNoDashGuid,\r\n Deferred,\r\n IAudioSource,\r\n IConnection,\r\n MessageType,\r\n} from \"../../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n ConversationExpirationEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n ConversationTranslationResult,\r\n Translations\r\n} from \"../../sdk/Exports\";\r\nimport {\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognizerConfig,\r\n ServiceRecognizerBase\r\n} from \"../Exports\";\r\nimport { ConversationConnectionMessage } from \"./ConversationConnectionMessage\";\r\nimport { ConversationRequestSession } from \"./ConversationRequestSession\";\r\nimport {\r\n ConversationReceivedTranslationEventArgs,\r\n LockRoomEventArgs,\r\n MuteAllEventArgs,\r\n ParticipantAttributeEventArgs,\r\n ParticipantEventArgs,\r\n ParticipantsListEventArgs\r\n} from \"./ConversationTranslatorEventArgs\";\r\nimport {\r\n ConversationTranslatorCommandTypes,\r\n ConversationTranslatorMessageTypes,\r\n IInternalParticipant\r\n} from \"./ConversationTranslatorInterfaces\";\r\nimport { ConversationTranslatorRecognizer } from \"./ConversationTranslatorRecognizer\";\r\nimport {\r\n CommandResponsePayload,\r\n IParticipantPayloadResponse,\r\n IParticipantsListPayloadResponse,\r\n ITranslationResponsePayload,\r\n ParticipantPayloadResponse,\r\n ParticipantsListPayloadResponse,\r\n SpeechResponsePayload,\r\n TextResponsePayload\r\n} from \"./ServiceMessages/Exports\";\r\n\r\n/***\r\n * The service adapter handles sending and receiving messages to the Conversation Translator websocket.\r\n */\r\nexport class ConversationServiceAdapter extends ServiceRecognizerBase {\r\n private privConversationServiceConnector: ConversationTranslatorRecognizer;\r\n private privConversationConnectionFactory: IConnectionFactory;\r\n private privConversationAuthFetchEventId: string;\r\n private privConversationAuthentication: IAuthentication;\r\n private privConversationRequestSession: ConversationRequestSession;\r\n private privConnectionConfigPromise: Promise;\r\n private privConnectionLoop: Promise;\r\n private terminateMessageLoop: boolean;\r\n private privLastPartialUtteranceId: string = \"\";\r\n private privConversationIsDisposed: boolean;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n conversationServiceConnector: ConversationTranslatorRecognizer) {\r\n\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, conversationServiceConnector);\r\n\r\n this.privConversationServiceConnector = conversationServiceConnector;\r\n this.privConversationAuthentication = authentication;\r\n this.receiveMessageOverride = this.receiveConversationMessageOverride;\r\n this.recognizeOverride = this.noOp;\r\n this.postConnectImplOverride = this.conversationConnectImpl;\r\n this.configConnectionOverride = this.configConnection;\r\n this.disconnectOverride = this.privDisconnect;\r\n this.privConversationRequestSession = new ConversationRequestSession(createNoDashGuid());\r\n this.privConversationConnectionFactory = connectionFactory;\r\n this.privConversationIsDisposed = false;\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return super.isDisposed() || this.privConversationIsDisposed;\r\n }\r\n\r\n public async dispose(reason?: string): Promise {\r\n this.privConversationIsDisposed = true;\r\n if (this.privConnectionConfigPromise) {\r\n const connection: IConnection = await this.privConnectionConfigPromise;\r\n await connection.dispose(reason);\r\n }\r\n await super.dispose(reason);\r\n }\r\n\r\n public async sendMessage(message: string): Promise {\r\n const connection: IConnection = await this.fetchConnection();\r\n return connection.send(new ConversationConnectionMessage(\r\n MessageType.Text,\r\n message));\r\n }\r\n\r\n public async sendMessageAsync(message: string): Promise {\r\n const sink: Deferred = new Deferred();\r\n\r\n const connection: IConnection = await this.fetchConnection();\r\n\r\n await connection.send(new ConversationConnectionMessage(MessageType.Text, message));\r\n }\r\n\r\n protected privDisconnect(): Promise {\r\n if (this.terminateMessageLoop) {\r\n return;\r\n }\r\n this.cancelRecognition(this.privConversationRequestSession.sessionId,\r\n this.privConversationRequestSession.requestId,\r\n CancellationReason.Error,\r\n CancellationErrorCode.NoError,\r\n \"Disconnecting\");\r\n\r\n this.terminateMessageLoop = true;\r\n return Promise.resolve();\r\n }\r\n\r\n protected async processTypeSpecificMessages(\r\n connectionMessage: ConnectionMessage,\r\n successCallback?: (e: any) => void,\r\n errorCallBack?: (e: string) => void): Promise {\r\n return true;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n this.terminateMessageLoop = true;\r\n\r\n const cancelEvent: ConversationTranslationCanceledEventArgs = new ConversationTranslationCanceledEventArgs(\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined,\r\n sessionId);\r\n\r\n try {\r\n if (!!this.privConversationServiceConnector.canceled) {\r\n this.privConversationServiceConnector.canceled(this.privConversationServiceConnector, cancelEvent);\r\n }\r\n } catch {\r\n // continue on error\r\n }\r\n }\r\n\r\n protected noOp = (): any => {\r\n // operation not supported\r\n }\r\n\r\n /**\r\n * Establishes a websocket connection to the end point.\r\n * @param isUnAuthorized\r\n */\r\n protected async conversationConnectImpl(connection: Promise): Promise {\r\n this.privConnectionLoop = this.startMessageLoop();\r\n return connection;\r\n }\r\n\r\n /**\r\n * Process incoming websocket messages\r\n */\r\n private async receiveConversationMessageOverride(): Promise {\r\n if (this.isDisposed() || this.terminateMessageLoop) {\r\n return Promise.resolve();\r\n }\r\n // we won't rely on the cascading promises of the connection since we want to continually be available to receive messages\r\n const communicationCustodian: Deferred = new Deferred();\r\n\r\n try {\r\n const connection: IConnection = await this.fetchConnection();\r\n const message: ConversationConnectionMessage = await connection.read() as ConversationConnectionMessage;\r\n if (this.isDisposed() || this.terminateMessageLoop) {\r\n // We're done.\r\n communicationCustodian.resolve();\r\n return Promise.resolve();\r\n }\r\n\r\n if (!message) {\r\n return this.receiveConversationMessageOverride();\r\n }\r\n\r\n const sessionId: string = this.privConversationRequestSession.sessionId;\r\n let sendFinal: boolean = false;\r\n\r\n try {\r\n switch (message.conversationMessageType.toLowerCase()) {\r\n case \"info\":\r\n case \"participant_command\":\r\n case \"command\":\r\n const commandPayload: CommandResponsePayload = CommandResponsePayload.fromJSON(message.textBody);\r\n switch (commandPayload.command.toLowerCase()) {\r\n\r\n /**\r\n * 'ParticpantList' is the first message sent to the user after the websocket connection has opened.\r\n * The consuming client must wait for this message to arrive\r\n * before starting to send their own data.\r\n */\r\n case \"participantlist\":\r\n\r\n const participantsPayload: IParticipantsListPayloadResponse = ParticipantsListPayloadResponse.fromJSON(message.textBody);\r\n\r\n const participantsResult: IInternalParticipant[] = participantsPayload.participants.map((p: IParticipantPayloadResponse) => {\r\n const participant: IInternalParticipant = {\r\n avatar: p.avatar,\r\n displayName: p.nickname,\r\n id: p.participantId,\r\n isHost: p.ishost,\r\n isMuted: p.ismuted,\r\n isUsingTts: p.usetts,\r\n preferredLanguage: p.locale\r\n };\r\n return participant;\r\n });\r\n\r\n if (!!this.privConversationServiceConnector.participantsListReceived) {\r\n this.privConversationServiceConnector.participantsListReceived(this.privConversationServiceConnector,\r\n new ParticipantsListEventArgs(participantsPayload.roomid, participantsPayload.token,\r\n participantsPayload.translateTo, participantsPayload.profanityFilter,\r\n participantsPayload.roomProfanityFilter, participantsPayload.roomLocked,\r\n participantsPayload.muteAll, participantsResult, sessionId));\r\n }\r\n break;\r\n\r\n /**\r\n * 'SetTranslateToLanguages' represents the list of languages being used in the Conversation by all users(?).\r\n * This is sent at the start of the Conversation\r\n */\r\n case \"settranslatetolanguages\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.setTranslateToLanguages,\r\n commandPayload.value, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetProfanityFiltering' lets the client set the level of profanity filtering.\r\n * If sent by the participant the setting will effect only their own profanity level.\r\n * If sent by the host, the setting will effect all participants including the host.\r\n * Note: the profanity filters differ from Speech Service (?): 'marked', 'raw', 'removed', 'tagged'\r\n */\r\n case \"setprofanityfiltering\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.setProfanityFiltering,\r\n commandPayload.value, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetMute' is sent if the participant has been muted by the host.\r\n * Check the 'participantId' to determine if the current user has been muted.\r\n */\r\n case \"setmute\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.setMute,\r\n commandPayload.value, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetMuteAll' is sent if the Conversation has been muted by the host.\r\n */\r\n case \"setmuteall\":\r\n\r\n if (!!this.privConversationServiceConnector.muteAllCommandReceived) {\r\n this.privConversationServiceConnector.muteAllCommandReceived(this.privConversationServiceConnector,\r\n new MuteAllEventArgs(commandPayload.value as boolean, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'RoomExpirationWarning' is sent towards the end of the Conversation session to give a timeout warning.\r\n */\r\n case \"roomexpirationwarning\":\r\n\r\n if (!!this.privConversationServiceConnector.conversationExpiration) {\r\n this.privConversationServiceConnector.conversationExpiration(this.privConversationServiceConnector,\r\n new ConversationExpirationEventArgs(commandPayload.value as number, this.privConversationRequestSession.sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetUseTts' is sent as a confirmation if the user requests TTS to be turned on or off.\r\n */\r\n case \"setusetts\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.setUseTTS,\r\n commandPayload.value, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'SetLockState' is set if the host has locked or unlocked the Conversation.\r\n */\r\n case \"setlockstate\":\r\n\r\n if (!!this.privConversationServiceConnector.lockRoomCommandReceived) {\r\n this.privConversationServiceConnector.lockRoomCommandReceived(this.privConversationServiceConnector,\r\n new LockRoomEventArgs(commandPayload.value as boolean, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'ChangeNickname' is received if a user changes their display name.\r\n * Any cached particpiants list should be updated to reflect the display name.\r\n */\r\n case \"changenickname\":\r\n\r\n if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {\r\n this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantAttributeEventArgs(commandPayload.participantId,\r\n ConversationTranslatorCommandTypes.changeNickname,\r\n commandPayload.nickname, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'JoinSession' is sent when a user joins the Conversation.\r\n */\r\n case \"joinsession\":\r\n\r\n const joinParticipantPayload: ParticipantPayloadResponse = ParticipantPayloadResponse.fromJSON(message.textBody);\r\n\r\n const joiningParticipant: IInternalParticipant = {\r\n avatar: joinParticipantPayload.avatar,\r\n displayName: joinParticipantPayload.nickname,\r\n id: joinParticipantPayload.participantId,\r\n isHost: joinParticipantPayload.ishost,\r\n isMuted: joinParticipantPayload.ismuted,\r\n isUsingTts: joinParticipantPayload.usetts,\r\n preferredLanguage: joinParticipantPayload.locale,\r\n };\r\n\r\n if (!!this.privConversationServiceConnector.participantJoinCommandReceived) {\r\n this.privConversationServiceConnector.participantJoinCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantEventArgs(\r\n joiningParticipant,\r\n sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'LeaveSession' is sent when a user leaves the Conversation'.\r\n */\r\n case \"leavesession\":\r\n\r\n const leavingParticipant: IInternalParticipant = {\r\n id: commandPayload.participantId\r\n };\r\n\r\n if (!!this.privConversationServiceConnector.participantLeaveCommandReceived) {\r\n this.privConversationServiceConnector.participantLeaveCommandReceived(this.privConversationServiceConnector,\r\n new ParticipantEventArgs(leavingParticipant, sessionId));\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * 'DisconnectSession' is sent when a user is disconnected from the session (e.g. network problem).\r\n * Check the 'ParticipantId' to check whether the message is for the current user.\r\n */\r\n case \"disconnectsession\":\r\n\r\n const disconnectParticipant: IInternalParticipant = {\r\n id: commandPayload.participantId\r\n };\r\n\r\n break;\r\n\r\n /**\r\n * Message not recognized.\r\n */\r\n default:\r\n break;\r\n }\r\n break;\r\n\r\n /**\r\n * 'partial' (or 'hypothesis') represents a unfinalized speech message.\r\n */\r\n case \"partial\":\r\n\r\n /**\r\n * 'final' (or 'phrase') represents a finalized speech message.\r\n */\r\n case \"final\":\r\n\r\n const speechPayload: SpeechResponsePayload = SpeechResponsePayload.fromJSON(message.textBody);\r\n\r\n const speechResult: ConversationTranslationResult = new ConversationTranslationResult(speechPayload.participantId,\r\n this.getTranslations(speechPayload.translations),\r\n speechPayload.language,\r\n undefined,\r\n undefined,\r\n speechPayload.recognition,\r\n undefined,\r\n undefined,\r\n message.textBody,\r\n undefined);\r\n\r\n if (speechPayload.isFinal) {\r\n // check the length, sometimes empty finals are returned\r\n if (speechResult.text !== undefined && speechResult.text.length > 0) {\r\n sendFinal = true;\r\n } else if (speechPayload.id === this.privLastPartialUtteranceId) {\r\n // send final as normal. We had a non-empty partial for this same utterance\r\n // so sending the empty final is important\r\n sendFinal = true;\r\n } else {\r\n // suppress unneeded final\r\n }\r\n\r\n if (sendFinal) {\r\n if (!!this.privConversationServiceConnector.translationReceived) {\r\n this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector,\r\n new ConversationReceivedTranslationEventArgs(ConversationTranslatorMessageTypes.final, speechResult, sessionId));\r\n }\r\n }\r\n } else if (speechResult.text !== undefined) {\r\n this.privLastPartialUtteranceId = speechPayload.id;\r\n if (!!this.privConversationServiceConnector.translationReceived) {\r\n this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector,\r\n new ConversationReceivedTranslationEventArgs(ConversationTranslatorMessageTypes.partial, speechResult, sessionId));\r\n }\r\n }\r\n\r\n break;\r\n\r\n /**\r\n * \"translated_message\" is a text message or instant message (IM).\r\n */\r\n case \"translated_message\":\r\n\r\n const textPayload: TextResponsePayload = TextResponsePayload.fromJSON(message.textBody);\r\n\r\n const textResult: ConversationTranslationResult = new ConversationTranslationResult(textPayload.participantId,\r\n this.getTranslations(textPayload.translations),\r\n textPayload.language,\r\n undefined,\r\n undefined,\r\n textPayload.originalText,\r\n undefined,\r\n undefined,\r\n undefined,\r\n message.textBody,\r\n undefined);\r\n\r\n if (!!this.privConversationServiceConnector.translationReceived) {\r\n this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector,\r\n new ConversationReceivedTranslationEventArgs(ConversationTranslatorMessageTypes.instantMessage, textResult, sessionId));\r\n }\r\n break;\r\n\r\n default:\r\n // ignore any unsupported message types\r\n break;\r\n }\r\n } catch (e) {\r\n // continue\r\n }\r\n return this.receiveConversationMessageOverride();\r\n } catch (e) {\r\n this.terminateMessageLoop = true;\r\n }\r\n\r\n return communicationCustodian.promise;\r\n }\r\n\r\n private async startMessageLoop(): Promise {\r\n if (this.isDisposed()) {\r\n return Promise.resolve();\r\n }\r\n this.terminateMessageLoop = false;\r\n\r\n const messageRetrievalPromise = this.receiveConversationMessageOverride();\r\n\r\n try {\r\n const r = await messageRetrievalPromise;\r\n return r;\r\n } catch (error) {\r\n this.cancelRecognition(this.privRequestSession ? this.privRequestSession.sessionId : \"\", this.privRequestSession ? this.privRequestSession.requestId : \"\", CancellationReason.Error, CancellationErrorCode.RuntimeError, error);\r\n return null;\r\n }\r\n }\r\n\r\n // Takes an established websocket connection to the endpoint\r\n private configConnection(): Promise {\r\n if (this.isDisposed()) {\r\n return Promise.resolve(undefined);\r\n }\r\n if (this.privConnectionConfigPromise) {\r\n return this.privConnectionConfigPromise.then((connection: IConnection): Promise => {\r\n if (connection.state() === ConnectionState.Disconnected) {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigPromise = null;\r\n return this.configConnection();\r\n }\r\n return this.privConnectionConfigPromise;\r\n }, (error: string): Promise => {\r\n this.privConnectionId = null;\r\n this.privConnectionConfigPromise = null;\r\n return this.configConnection();\r\n });\r\n }\r\n if (this.terminateMessageLoop) {\r\n return Promise.resolve(undefined);\r\n }\r\n\r\n this.privConnectionConfigPromise = this.connectImpl().then((connection: IConnection): any => {\r\n return connection;\r\n });\r\n\r\n return this.privConnectionConfigPromise;\r\n }\r\n\r\n private getTranslations(serviceResultTranslations: ITranslationResponsePayload[]): Translations {\r\n let translations: Translations;\r\n\r\n if (undefined !== serviceResultTranslations) {\r\n translations = new Translations();\r\n for (const translation of serviceResultTranslations) {\r\n translations.set(translation.lang, translation.translation);\r\n }\r\n }\r\n\r\n return translations;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\nimport { SessionEventArgs } from \"../../sdk/Exports\";\r\nimport { IInternalParticipant } from \"./ConversationTranslatorInterfaces\";\r\n\r\nexport class MuteAllEventArgs extends SessionEventArgs {\r\n private privIsMuted: boolean;\r\n\r\n public constructor(isMuted: boolean, sessionId?: string) {\r\n super(sessionId);\r\n\r\n this.privIsMuted = isMuted;\r\n }\r\n\r\n public get isMuted(): boolean {\r\n return this.privIsMuted;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class LockRoomEventArgs extends SessionEventArgs {\r\n private privIsLocked: boolean;\r\n\r\n public constructor(isLocked: boolean, sessionId?: string) {\r\n super(sessionId);\r\n\r\n this.privIsLocked = isLocked;\r\n }\r\n\r\n public get isMuted(): boolean {\r\n return this.privIsLocked;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ParticipantEventArgs extends SessionEventArgs {\r\n private privParticipant: IInternalParticipant;\r\n\r\n public constructor(participant: IInternalParticipant, sessionId?: string) {\r\n super(sessionId);\r\n this.privParticipant = participant;\r\n }\r\n\r\n public get participant(): IInternalParticipant {\r\n return this.privParticipant;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ParticipantAttributeEventArgs extends SessionEventArgs {\r\n private privValue: boolean | number | string | string[];\r\n private privKey: string;\r\n private privParticipantId: string;\r\n\r\n public constructor(participantId: string, key: string, value: boolean | number | string | string[], sessionId?: string) {\r\n super(sessionId);\r\n\r\n this.privKey = key;\r\n this.privValue = value;\r\n this.privParticipantId = participantId;\r\n }\r\n\r\n public get value(): boolean | number | string | string[] {\r\n return this.privValue;\r\n }\r\n\r\n public get key(): string {\r\n return this.privKey;\r\n }\r\n public get id(): string {\r\n return this.privParticipantId;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ParticipantsListEventArgs extends SessionEventArgs {\r\n\r\n private privRoomId: string;\r\n private privSessionToken: string;\r\n private privTranslateTo: string[];\r\n private privProfanityFilter: string;\r\n private privRoomProfanityFilter: string;\r\n private privIsRoomLocked: boolean;\r\n private privIsMuteAll: boolean;\r\n private privParticipants: IInternalParticipant[];\r\n\r\n public constructor(conversationId: string, token: string, translateTo: string[], profanityFilter: string,\r\n roomProfanityFilter: string, isRoomLocked: boolean, isMuteAll: boolean, participants: IInternalParticipant[], sessionId?: string) {\r\n super(sessionId);\r\n this.privRoomId = conversationId;\r\n this.privSessionToken = token;\r\n this.privTranslateTo = translateTo;\r\n this.privProfanityFilter = profanityFilter;\r\n this.privRoomProfanityFilter = roomProfanityFilter;\r\n this.privIsRoomLocked = isRoomLocked;\r\n this.privIsRoomLocked = isMuteAll;\r\n this.privParticipants = participants;\r\n }\r\n public get sessionToken(): string {\r\n return this.privSessionToken;\r\n }\r\n\r\n public get conversationId(): string {\r\n return this.privRoomId;\r\n }\r\n\r\n public get translateTo(): string[] {\r\n return this.privTranslateTo;\r\n }\r\n\r\n public get profanityFilter(): string {\r\n return this.privProfanityFilter;\r\n }\r\n\r\n public get roomProfanityFilter(): string {\r\n return this.privRoomProfanityFilter;\r\n }\r\n\r\n public get isRoomLocked(): boolean {\r\n return this.privIsRoomLocked;\r\n }\r\n\r\n public get isMuteAll(): boolean {\r\n return this.privIsMuteAll;\r\n }\r\n\r\n public get participants(): IInternalParticipant[] {\r\n return this.privParticipants;\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ConversationReceivedTranslationEventArgs {\r\n private privPayload: any;\r\n private privCommand: string;\r\n private privSessionId: string;\r\n\r\n public constructor(command: string, payload: any, sessionId?: string) {\r\n this.privPayload = payload;\r\n this.privCommand = command;\r\n this.privSessionId = sessionId;\r\n }\r\n\r\n public get payload(): any {\r\n return this.privPayload;\r\n }\r\n\r\n public get command(): string {\r\n return this.privCommand;\r\n }\r\n\r\n public get sessionId(): string {\r\n return this.privSessionId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionEventArgs,\r\n ConversationExpirationEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n SessionEventArgs,\r\n VoiceSignature,\r\n } from \"../../sdk/Exports\";\r\n// import { ConversationClient } from \"./ConversationConnection\";\r\nimport {\r\n ConversationReceivedTranslationEventArgs,\r\n LockRoomEventArgs,\r\n MuteAllEventArgs,\r\n ParticipantAttributeEventArgs,\r\n ParticipantEventArgs,\r\n ParticipantsListEventArgs } from \"./ConversationTranslatorEventArgs\";\r\n\r\n/**\r\n * Internal conversation data\r\n */\r\nexport interface IInternalConversation {\r\n // the token to use for connecting to the Speech Service\r\n cognitiveSpeechAuthToken: string;\r\n // the region to use for connecting to the Speech Service\r\n cognitiveSpeechRegion: string;\r\n // the unique id of the user who started or joined the Conversation\r\n participantId: string;\r\n // a descriptive name for the Conversation\r\n name: string;\r\n // a descriptive name for the Conversation\r\n description: string;\r\n // the speech model ID for custom speech\r\n speechModel: string;\r\n // represents the level of speech supported in the Conversation (0: everyone can speak, 2: only host can speak, 3: no-one can speak)\r\n modalities: number;\r\n // ?\r\n isApproved: boolean;\r\n // the mute flag has been set at conversation level and only the host can speak\r\n isMuted: boolean;\r\n // the 5 character conversation Id\r\n roomId: string;\r\n // the hex color string to represent a user. If there are many users this hex color may be reused (?).\r\n avatar: string;\r\n // the token to use when calling the websocket\r\n token: string;\r\n // used for tracking the session and help with troubleshooting problems in the logs\r\n correlationId: string;\r\n // extracted from the headers\r\n requestId: string;\r\n}\r\n\r\n/**\r\n * The user who is participating in the conversation.\r\n */\r\nexport interface IInternalParticipant {\r\n avatar?: string;\r\n displayName?: string;\r\n id?: string;\r\n isHost?: boolean;\r\n isMuted?: boolean;\r\n isUsingTts?: boolean;\r\n preferredLanguage?: string;\r\n voice?: string;\r\n}\r\n\r\n/** Users participating in the conversation */\r\nexport class InternalParticipants {\r\n\r\n constructor(public participants: IInternalParticipant[] = [], public meId?: string) {\r\n\r\n }\r\n\r\n /**\r\n * Add or update a participant\r\n * @param value\r\n */\r\n public addOrUpdateParticipant(value: IInternalParticipant): IInternalParticipant {\r\n if (value === undefined) {\r\n return;\r\n }\r\n\r\n const exists: number = this.getParticipantIndex(value.id);\r\n if (exists > -1) {\r\n this.participants.splice(exists, 1, value);\r\n } else {\r\n this.participants.push(value);\r\n }\r\n\r\n // ensure it was added ok\r\n return this.getParticipant(value.id);\r\n }\r\n\r\n /**\r\n * Find the participant's position in the participants list.\r\n * @param id\r\n */\r\n public getParticipantIndex(id: string): number {\r\n return this.participants.findIndex((p: IInternalParticipant) => p.id === id);\r\n }\r\n\r\n /**\r\n * Find the participant by id.\r\n * @param id\r\n */\r\n public getParticipant(id: string): IInternalParticipant {\r\n return this.participants.find((p: IInternalParticipant) => p.id === id);\r\n }\r\n\r\n /***\r\n * Remove a participant from the participants list.\r\n */\r\n public deleteParticipant(id: string): void {\r\n this.participants = this.participants.filter((p: IInternalParticipant) => p.id !== id);\r\n }\r\n\r\n /***\r\n * Helper to return the conversation host.\r\n */\r\n public get host(): IInternalParticipant {\r\n return this.participants.find((p: IInternalParticipant) => p.isHost === true );\r\n }\r\n\r\n /**\r\n * Helper to return the current user.\r\n */\r\n public get me(): IInternalParticipant {\r\n return this.getParticipant(this.meId);\r\n }\r\n}\r\n\r\n/**\r\n * Recognizer for handling Conversation Translator websocket messages\r\n */\r\nexport interface ConversationRecognizer {\r\n isDisposed(): boolean;\r\n sendRequest: (command: string, cb?: () => void, err?: (e: string) => void) => void;\r\n cancelSpeech?: () => Promise;\r\n close?: () => Promise;\r\n conversationExpiration?: (sender: ConversationRecognizer, event: ConversationExpirationEventArgs) => void;\r\n connected?: (e: ConnectionEventArgs) => void;\r\n disconnected?: (e: ConnectionEventArgs) => void;\r\n canceled?: (sender: ConversationRecognizer, event: ConversationTranslationCanceledEventArgs) => void;\r\n connectionOpened?: (sender: ConversationRecognizer, event: SessionEventArgs) => void;\r\n connectionClosed?: (sender: ConversationRecognizer, event: SessionEventArgs) => void;\r\n participantsListReceived?: (sender: ConversationRecognizer, event: ParticipantsListEventArgs) => void;\r\n translationReceived?: (sender: ConversationRecognizer, event: ConversationReceivedTranslationEventArgs) => void;\r\n lockRoomCommandReceived?: (sender: ConversationRecognizer, event: LockRoomEventArgs) => void;\r\n muteAllCommandReceived?: (sender: ConversationRecognizer, event: MuteAllEventArgs) => void;\r\n participantJoinCommandReceived?: (sender: ConversationRecognizer, event: ParticipantEventArgs) => void;\r\n participantLeaveCommandReceived?: (sender: ConversationRecognizer, event: ParticipantEventArgs) => void;\r\n participantUpdateCommandReceived?: (sender: ConversationRecognizer, event: ParticipantAttributeEventArgs) => void;\r\n connect?: (token: string, cb?: () => void, err?: (e: string) => void) => void;\r\n}\r\n\r\n/**\r\n * Error message returned from the Conversation Translator websocket\r\n */\r\nexport interface IConversationResponseErrorMessage {\r\n code: string;\r\n message: string;\r\n}\r\n\r\n/**\r\n * Error returned from the Conversation Translator websocket\r\n */\r\nexport interface IConversationResponseError {\r\n error: IConversationResponseErrorMessage;\r\n}\r\n\r\n/**\r\n * Base message command\r\n */\r\nexport interface IClientMessage {\r\n type: any;\r\n}\r\n\r\n/**\r\n * Command message\r\n */\r\nexport interface ICommandMessage extends IClientMessage {\r\n command?: string;\r\n}\r\n\r\n/**\r\n * Text message command\r\n */\r\nexport interface IInstantMessageCommand extends ICommandMessage {\r\n roomId: string;\r\n nickname?: string;\r\n participantId: string;\r\n text: string;\r\n}\r\n\r\n/**\r\n * Lock command\r\n */\r\nexport interface ILockConversationCommand extends ICommandMessage {\r\n id?: string; // incoming ws\r\n nickname?: string; // incoming ws\r\n participantId: string; // host - incoming ws\r\n roomid: string;\r\n value: boolean;\r\n}\r\n\r\n/**\r\n * Mute all command\r\n */\r\nexport interface IMuteAllCommand extends ICommandMessage {\r\n roomid: string;\r\n nickname?: string; // incoming ws\r\n participantId: string; // host\r\n value: boolean;\r\n id?: string; // incoming ws\r\n}\r\n\r\n/**\r\n * Mute participant command\r\n */\r\nexport interface IMuteCommand extends ICommandMessage {\r\n roomid: string;\r\n nickname?: string;\r\n participantId: string; // participant\r\n value: boolean;\r\n id?: string; // incoming ws\r\n}\r\n\r\n/**\r\n * Remove participant command\r\n */\r\nexport interface IEjectParticipantCommand extends ICommandMessage {\r\n roomid: string;\r\n participantId: string; // participant\r\n}\r\n\r\n/**\r\n * Change nickname command\r\n */\r\nexport interface IChangeNicknameCommand extends ICommandMessage {\r\n roomid: string;\r\n participantId: string;\r\n nickname: string;\r\n value: string;\r\n}\r\n\r\n/**\r\n * List of command message types\r\n */\r\nexport const ConversationTranslatorMessageTypes = {\r\n command: \"command\",\r\n final: \"final\",\r\n info: \"info\",\r\n instantMessage: \"instant_message\",\r\n partial: \"partial\",\r\n participantCommand: \"participant_command\",\r\n translatedMessage: \"translated_message\"\r\n};\r\n\r\n/**\r\n * List of command types\r\n */\r\nexport const ConversationTranslatorCommandTypes = {\r\n changeNickname: \"ChangeNickname\",\r\n disconnectSession: \"DisconnectSession\",\r\n ejectParticipant: \"EjectParticipant\",\r\n instant_message: \"instant_message\",\r\n joinSession: \"JoinSession\",\r\n leaveSession: \"LeaveSession\",\r\n participantList: \"ParticipantList\",\r\n roomExpirationWarning: \"RoomExpirationWarning\",\r\n setLockState: \"SetLockState\",\r\n setMute: \"SetMute\",\r\n setMuteAll: \"SetMuteAll\",\r\n setProfanityFiltering: \"SetProfanityFiltering\",\r\n setTranslateToLanguages: \"SetTranslateToLanguages\",\r\n setUseTTS: \"SetUseTTS\"\r\n};\r\n\r\n/**\r\n * HTTP response helper\r\n */\r\nexport interface IResponse {\r\n ok: boolean;\r\n status: number;\r\n statusText: string;\r\n data: string;\r\n json: () => T;\r\n headers: string;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig\r\n} from \"../../common.speech/Exports\";\r\nimport {\r\n BackgroundEvent,\r\n Events\r\n} from \"../../common/Exports\";\r\nimport { AudioConfigImpl } from \"../../sdk/Audio/AudioConfig\";\r\nimport { Contracts } from \"../../sdk/Contracts\";\r\nimport {\r\n AudioConfig,\r\n Connection,\r\n ConnectionEventArgs,\r\n ConversationExpirationEventArgs,\r\n ConversationParticipantsChangedEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n PropertyCollection,\r\n Recognizer,\r\n SessionEventArgs,\r\n SpeechTranslationConfig\r\n} from \"../../sdk/Exports\";\r\nimport { SpeechTranslationConfigImpl } from \"../../sdk/SpeechTranslationConfig\";\r\nimport { Callback } from \"../../sdk/Transcription/IConversation\";\r\nimport { ConversationConnectionFactory } from \"./ConversationConnectionFactory\";\r\nimport { ConversationServiceAdapter } from \"./ConversationServiceAdapter\";\r\nimport {\r\n ConversationReceivedTranslationEventArgs,\r\n LockRoomEventArgs,\r\n MuteAllEventArgs,\r\n ParticipantAttributeEventArgs,\r\n ParticipantEventArgs,\r\n ParticipantsListEventArgs\r\n} from \"./ConversationTranslatorEventArgs\";\r\nimport {\r\n ConversationRecognizer,\r\n} from \"./ConversationTranslatorInterfaces\";\r\nimport { PromiseToEmptyCallback } from \"./ConversationUtils\";\r\n\r\nexport class ConversationRecognizerFactory {\r\n public static fromConfig(speechConfig: SpeechTranslationConfig, audioConfig?: AudioConfig): ConversationRecognizer {\r\n return new ConversationTranslatorRecognizer(speechConfig, audioConfig);\r\n }\r\n}\r\n\r\n/**\r\n * Sends messages to the Conversation Translator websocket and listens for incoming events containing websocket messages.\r\n * Based off the recognizers in the SDK folder.\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class ConversationTranslatorRecognizer extends Recognizer implements ConversationRecognizer {\r\n\r\n private privIsDisposed: boolean;\r\n private privSpeechRecognitionLanguage: string;\r\n private privConnection: Connection;\r\n\r\n public constructor(speechConfig: SpeechTranslationConfig, audioConfig?: AudioConfig) {\r\n const serviceConfigImpl = speechConfig as SpeechTranslationConfigImpl;\r\n Contracts.throwIfNull(serviceConfigImpl, \"speechConfig\");\r\n\r\n super(audioConfig, serviceConfigImpl.properties, new ConversationConnectionFactory());\r\n\r\n this.privIsDisposed = false;\r\n this.privProperties = serviceConfigImpl.properties.clone();\r\n this.privConnection = Connection.fromRecognizer(this);\r\n }\r\n\r\n public canceled: (sender: ConversationRecognizer, event: ConversationTranslationCanceledEventArgs) => void;\r\n public conversationExpiration: (sender: ConversationRecognizer, event: ConversationExpirationEventArgs) => void;\r\n public lockRoomCommandReceived: (sender: ConversationRecognizer, event: LockRoomEventArgs) => void;\r\n public muteAllCommandReceived: (sender: ConversationRecognizer, event: MuteAllEventArgs) => void;\r\n public participantJoinCommandReceived: (sender: ConversationRecognizer, event: ParticipantEventArgs) => void;\r\n public participantLeaveCommandReceived: (sender: ConversationRecognizer, event: ParticipantEventArgs) => void;\r\n public participantUpdateCommandReceived: (sender: ConversationRecognizer, event: ParticipantAttributeEventArgs) => void;\r\n public connectionOpened: (sender: ConversationRecognizer, event: SessionEventArgs) => void;\r\n public connectionClosed: (sender: ConversationRecognizer, event: SessionEventArgs) => void;\r\n public translationReceived: (sender: ConversationRecognizer, event: ConversationReceivedTranslationEventArgs) => void;\r\n public participantsListReceived: (sender: ConversationRecognizer, event: ParticipantsListEventArgs) => void;\r\n public participantsChanged: (sender: ConversationRecognizer, event: ConversationParticipantsChangedEventArgs) => void;\r\n\r\n public set connected(cb: (e: ConnectionEventArgs) => void) {\r\n this.privConnection.connected = cb;\r\n }\r\n\r\n public set disconnected(cb: (e: ConnectionEventArgs) => void) {\r\n this.privConnection.disconnected = cb;\r\n }\r\n\r\n /**\r\n * Return the speech language used by the recognizer\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n return this.privSpeechRecognitionLanguage;\r\n }\r\n\r\n /**\r\n * Return the properties for the recognizer\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public isDisposed(): boolean {\r\n return this.privIsDisposed;\r\n }\r\n\r\n /**\r\n * Connect to the recognizer\r\n * @param token\r\n */\r\n public connect(token: string, cb?: () => void, err?: (e: string) => void): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.privReco.conversationTranslatorToken = token;\r\n this.privReco.connectAsync(cb, err);\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Disconnect from the recognizer\r\n */\r\n public disconnect(cb?: () => void, err?: (e: string) => void): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n this.privReco.disconnect().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string) => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n }\r\n // Destroy the recognizer.\r\n this.dispose(true).catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n\r\n }\r\n }\r\n\r\n /**\r\n * Send the mute all participants command to the websocket\r\n * @param conversationId\r\n * @param participantId\r\n * @param isMuted\r\n */\r\n public sendRequest(command: string, cb?: () => void, err?: (e: string) => void): void {\r\n try {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n this.sendMessage(command, cb, err);\r\n } catch (error) {\r\n if (!!err) {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n }\r\n\r\n // Destroy the recognizer.\r\n this.dispose(true).catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n\r\n }\r\n }\r\n\r\n /**\r\n * Close and dispose the recognizer\r\n */\r\n public async close(): Promise {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n this.privConnection?.closeConnection();\r\n this.privConnection?.close();\r\n this.privConnection = undefined;\r\n await this.dispose(true);\r\n }\r\n\r\n /**\r\n * Dispose the recognizer\r\n * @param disposing\r\n */\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privIsDisposed) {\r\n return;\r\n }\r\n if (disposing) {\r\n this.privIsDisposed = true;\r\n if (!!this.privConnection) {\r\n this.privConnection.closeConnection();\r\n this.privConnection.close();\r\n this.privConnection = undefined;\r\n }\r\n await super.dispose(disposing);\r\n }\r\n }\r\n\r\n /**\r\n * Create the config for the recognizer\r\n * @param speechConfig\r\n */\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(speechConfig, this.privProperties);\r\n }\r\n\r\n /**\r\n * Create the service recognizer.\r\n * The audio source is redundnant here but is required by the implementation.\r\n * @param authentication\r\n * @param connectionFactory\r\n * @param audioConfig\r\n * @param recognizerConfig\r\n */\r\n protected createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n\r\n const audioSource: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n\r\n return new ConversationServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this);\r\n }\r\n\r\n private sendMessage(msg: string, cb?: Callback, err?: Callback): void {\r\n const withAsync = this.privReco as ConversationServiceAdapter;\r\n PromiseToEmptyCallback(withAsync.sendMessageAsync(msg), cb, err);\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IResponse } from \"./ConversationTranslatorInterfaces\";\r\n\r\nimport { IRequestOptions, RestConfigBase } from \"../../common.browser/RestConfigBase\";\r\nimport { Callback } from \"../../sdk/Transcription/IConversation\";\r\n\r\n// Node.JS specific xmlhttprequest / browser support.\r\nimport * as XHR from \"xmlhttprequest-ts\";\r\n\r\n/**\r\n * Config settings for Conversation Translator\r\n */\r\n/**\r\n * Helpers for sending / receiving HTTPS requests / responses.\r\n * @param params\r\n */\r\nfunction queryParams(params: any = {}): any {\r\n return Object.keys(params)\r\n .map((k: any) => encodeURIComponent(k) + \"=\" + encodeURIComponent(params[k]))\r\n .join(\"&\");\r\n}\r\n\r\nfunction withQuery(url: string, params: any = {}): any {\r\n const queryString = queryParams(params);\r\n return queryString ? url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + queryString : url;\r\n}\r\n\r\nfunction parseXHRResult(xhr: XMLHttpRequest | XHR.XMLHttpRequest): IResponse {\r\n return {\r\n data: xhr.responseText,\r\n headers: xhr.getAllResponseHeaders(),\r\n json: () => JSON.parse(xhr.responseText) as T,\r\n ok: xhr.status >= 200 && xhr.status < 300,\r\n status: xhr.status,\r\n statusText: xhr.statusText,\r\n };\r\n}\r\n\r\nfunction errorResponse(xhr: XMLHttpRequest | XHR.XMLHttpRequest, message: string | null = null): IResponse {\r\n return {\r\n data: message || xhr.statusText,\r\n headers: xhr.getAllResponseHeaders(),\r\n json: () => JSON.parse(message || (\"\\\"\" + xhr.statusText + \"\\\"\")) as T,\r\n ok: false,\r\n status: xhr.status,\r\n statusText: xhr.statusText,\r\n };\r\n}\r\n\r\nexport function extractHeaderValue(headerKey: string, headers: string): string {\r\n\r\n let headerValue: string = \"\";\r\n\r\n try {\r\n const arr = headers.trim().split(/[\\r\\n]+/);\r\n const headerMap: any = {};\r\n arr.forEach((line: any) => {\r\n const parts = line.split(\": \");\r\n const header = parts.shift().toLowerCase();\r\n const value = parts.join(\": \");\r\n headerMap[header] = value;\r\n });\r\n\r\n headerValue = headerMap[headerKey.toLowerCase()];\r\n } catch (e) {\r\n // ignore the error\r\n }\r\n\r\n return headerValue;\r\n}\r\n\r\nexport function request(\r\n method: \"get\" | \"post\" | \"delete\",\r\n url: string,\r\n queryParams: any = {},\r\n body: any = null,\r\n options: IRequestOptions = {},\r\n callback: any): any {\r\n\r\n const defaultRequestOptions = RestConfigBase.requestOptions;\r\n\r\n const ignoreCache = options.ignoreCache || defaultRequestOptions.ignoreCache;\r\n const headers = options.headers || defaultRequestOptions.headers;\r\n const timeout = options.timeout || defaultRequestOptions.timeout;\r\n\r\n let xhr: XMLHttpRequest | XHR.XMLHttpRequest;\r\n if (typeof window === \"undefined\") { // Node\r\n xhr = new XHR.XMLHttpRequest();\r\n\r\n } else {\r\n xhr = new XMLHttpRequest();\r\n }\r\n xhr.open(method, withQuery(url, queryParams), true);\r\n\r\n if (headers) {\r\n Object.keys(headers).forEach((key: any) => xhr.setRequestHeader(key, headers[key]));\r\n }\r\n\r\n if (ignoreCache) {\r\n xhr.setRequestHeader(\"Cache-Control\", \"no-cache\");\r\n }\r\n\r\n xhr.timeout = timeout;\r\n\r\n xhr.onload = (evt: any) => {\r\n callback(parseXHRResult(xhr));\r\n };\r\n\r\n xhr.onerror = (evt: any) => {\r\n callback(errorResponse(xhr, \"Failed to make request.\"));\r\n };\r\n\r\n xhr.ontimeout = (evt: any) => {\r\n callback(errorResponse(xhr, \"Request took longer than expected.\"));\r\n };\r\n\r\n if (method === \"post\" && body) {\r\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\r\n xhr.send(JSON.stringify(body));\r\n } else {\r\n xhr.send();\r\n }\r\n}\r\n\r\nexport function PromiseToEmptyCallback(promise: Promise, cb?: Callback, err?: Callback): void {\r\n if (!!promise) {\r\n promise.then((result: T): void => {\r\n try {\r\n if (!!cb) {\r\n cb();\r\n }\r\n } catch (e) {\r\n if (!!err) {\r\n err(`'Unhandled error on promise callback: ${e}'`);\r\n }\r\n }\r\n }, (reason: any) => {\r\n try {\r\n if (!!err) {\r\n err(reason);\r\n }\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n }\r\n });\r\n } else {\r\n if (!!err) {\r\n err(\"Null promise\");\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionMessage,\r\n Deferred,\r\n IStringDictionary,\r\n IWebsocketMessageFormatter,\r\n MessageType,\r\n RawWebsocketMessage,\r\n} from \"../../common/Exports\";\r\nimport { ConversationConnectionMessage } from \"./ConversationConnectionMessage\";\r\n\r\n/**\r\n * Based off WebsocketMessageFormatter. The messages for Conversation Translator have some variations from the Speech messages.\r\n */\r\nexport class ConversationWebsocketMessageFormatter implements IWebsocketMessageFormatter {\r\n\r\n /**\r\n * Format incoming messages: text (speech partial/final, IM) or binary (tts)\r\n */\r\n public toConnectionMessage = (message: RawWebsocketMessage): Promise => {\r\n const deferral = new Deferred();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const incomingMessage: ConversationConnectionMessage = new ConversationConnectionMessage(message.messageType, message.textContent, {}, message.id);\r\n deferral.resolve(incomingMessage);\r\n } else if (message.messageType === MessageType.Binary) {\r\n deferral.resolve(new ConversationConnectionMessage(message.messageType, message.binaryContent, undefined, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. Error: ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n /**\r\n * Format outgoing messages: text (commands or IM)\r\n */\r\n public fromConnectionMessage = (message: ConnectionMessage): Promise => {\r\n\r\n const deferral = new Deferred();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const payload = `${message.textBody ? message.textBody : \"\"}`;\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Text, payload, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport { ConversationManager } from \"./ConversationManager\";\r\nexport { ConversationConnectionConfig } from \"./ConversationConnectionConfig\";\r\nexport { ConversationRecognizerFactory } from \"./ConversationTranslatorRecognizer\";\r\nexport { TranscriberRecognizer } from \"./TranscriberRecognizer\";\r\nexport {\r\n ConversationReceivedTranslationEventArgs,\r\n LockRoomEventArgs,\r\n MuteAllEventArgs,\r\n ParticipantAttributeEventArgs,\r\n ParticipantEventArgs,\r\n ParticipantsListEventArgs } from \"./ConversationTranslatorEventArgs\";\r\nexport {\r\n ConversationRecognizer,\r\n ConversationTranslatorCommandTypes,\r\n ConversationTranslatorMessageTypes,\r\n IInternalConversation,\r\n IInternalParticipant,\r\n InternalParticipants} from \"./ConversationTranslatorInterfaces\";\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the payload for incoming websocket commands\r\n */\r\nexport interface ICommandResponsePayload {\r\n type: string;\r\n command?: string;\r\n id?: string; // incoming ws\r\n nickname?: string; // incoming ws\r\n participantId?: string;\r\n roomid?: string;\r\n value: boolean | number | string;\r\n}\r\n\r\nexport class CommandResponsePayload implements ICommandResponsePayload {\r\n private privCommandResponse: ICommandResponsePayload;\r\n\r\n public constructor(json: string) {\r\n this.privCommandResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): CommandResponsePayload {\r\n return new CommandResponsePayload(json);\r\n }\r\n\r\n public get type(): string {\r\n return this.privCommandResponse.type;\r\n }\r\n public get command(): string {\r\n return this.privCommandResponse.command;\r\n }\r\n public get id(): string {\r\n return this.privCommandResponse.id;\r\n }\r\n public get nickname(): string {\r\n return this.privCommandResponse.nickname;\r\n }\r\n public get participantId(): string {\r\n return this.privCommandResponse.participantId;\r\n }\r\n public get roomid(): string {\r\n return this.privCommandResponse.roomid;\r\n }\r\n public get value(): boolean | number | string {\r\n return this.privCommandResponse.value;\r\n }\r\n}\r\n","export { CommandResponsePayload } from \"./CommandResponsePayload\";\r\nexport { IParticipantsListPayloadResponse, IParticipantPayloadResponse, ParticipantsListPayloadResponse, ParticipantPayloadResponse } from \"./ParticipantResponsePayload\";\r\nexport { ITranslationResponsePayload, SpeechResponsePayload, TextResponsePayload } from \"./TranslationResponsePayload\";\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the payload for incoming list of participants\r\n */\r\nexport interface IParticipantsListPayloadResponse {\r\n roomid: string;\r\n id: string;\r\n command: string;\r\n participants: IParticipantPayloadResponse[];\r\n token: string;\r\n translateTo: string[];\r\n profanityFilter: string;\r\n roomProfanityFilter: string;\r\n roomLocked: boolean;\r\n muteAll: boolean;\r\n type: string;\r\n}\r\n\r\n/**\r\n * Defines the payload for incoming participant\r\n */\r\nexport interface IParticipantPayloadResponse {\r\n nickname: string;\r\n locale: string;\r\n usetts: boolean;\r\n ismuted: boolean;\r\n ishost: boolean;\r\n participantId: string;\r\n avatar?: string;\r\n}\r\n\r\nexport class ParticipantsListPayloadResponse implements IParticipantsListPayloadResponse {\r\n private privParticipantsPayloadResponse: IParticipantsListPayloadResponse;\r\n\r\n private constructor(json: string) {\r\n this.privParticipantsPayloadResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): ParticipantsListPayloadResponse {\r\n return new ParticipantsListPayloadResponse(json);\r\n }\r\n\r\n public get roomid(): string {\r\n return this.privParticipantsPayloadResponse.roomid;\r\n }\r\n\r\n public get id(): string {\r\n return this.privParticipantsPayloadResponse.id;\r\n }\r\n\r\n public get command(): string {\r\n return this.privParticipantsPayloadResponse.command;\r\n }\r\n\r\n public get participants(): IParticipantPayloadResponse[] {\r\n return this.privParticipantsPayloadResponse.participants;\r\n }\r\n\r\n public get token(): string {\r\n return this.privParticipantsPayloadResponse.token;\r\n }\r\n\r\n public get translateTo(): string[] {\r\n return this.privParticipantsPayloadResponse.translateTo;\r\n }\r\n\r\n public get profanityFilter(): string {\r\n return this.privParticipantsPayloadResponse.profanityFilter;\r\n }\r\n\r\n public get roomProfanityFilter(): string {\r\n return this.privParticipantsPayloadResponse.roomProfanityFilter;\r\n }\r\n\r\n public get roomLocked(): boolean {\r\n return this.privParticipantsPayloadResponse.roomLocked;\r\n }\r\n\r\n public get muteAll(): boolean {\r\n return this.privParticipantsPayloadResponse.muteAll;\r\n }\r\n\r\n public get type(): string {\r\n return this.privParticipantsPayloadResponse.type;\r\n }\r\n\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class ParticipantPayloadResponse implements IParticipantPayloadResponse {\r\n\r\n private privParticipantPayloadResponse: IParticipantPayloadResponse;\r\n\r\n private constructor(json: string) {\r\n this.privParticipantPayloadResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): ParticipantPayloadResponse {\r\n return new ParticipantPayloadResponse(json);\r\n }\r\n\r\n public get nickname(): string {\r\n return this.privParticipantPayloadResponse.nickname;\r\n }\r\n\r\n public get locale(): string {\r\n return this.privParticipantPayloadResponse.locale;\r\n }\r\n\r\n public get usetts(): boolean {\r\n return this.privParticipantPayloadResponse.usetts;\r\n }\r\n\r\n public get ismuted(): boolean {\r\n return this.privParticipantPayloadResponse.ismuted;\r\n }\r\n\r\n public get ishost(): boolean {\r\n return this.privParticipantPayloadResponse.ishost;\r\n }\r\n\r\n public get participantId(): string {\r\n return this.privParticipantPayloadResponse.participantId;\r\n }\r\n\r\n public get avatar(): string {\r\n return this.privParticipantPayloadResponse.avatar;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the payload for incoming translation messages\r\n */\r\nexport interface ITranslationResponsePayload {\r\n lang: string;\r\n translation: string;\r\n}\r\n\r\nexport interface ITranslationCommandMessage {\r\n translations: ITranslationResponsePayload[];\r\n id: string;\r\n language: string;\r\n nickname: string;\r\n participantId: string;\r\n roomid: string;\r\n timestamp: string;\r\n type: string;\r\n}\r\n\r\nexport interface ISpeechResponsePayload extends ITranslationCommandMessage {\r\n recognition: string;\r\n isFinal: boolean;\r\n}\r\n\r\nexport interface ITextResponsePayload extends ITranslationCommandMessage {\r\n originalText: string;\r\n}\r\n\r\nexport class SpeechResponsePayload implements ISpeechResponsePayload {\r\n\r\n private privSpeechResponse: ISpeechResponsePayload;\r\n\r\n private constructor(json: string) {\r\n this.privSpeechResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): SpeechResponsePayload {\r\n return new SpeechResponsePayload(json);\r\n }\r\n\r\n public get recognition(): string {\r\n return this.privSpeechResponse.recognition;\r\n }\r\n\r\n public get translations(): ITranslationResponsePayload[] {\r\n return this.privSpeechResponse.translations;\r\n }\r\n\r\n public get id(): string {\r\n return this.privSpeechResponse.id;\r\n }\r\n\r\n public get language(): string {\r\n return this.privSpeechResponse.language;\r\n }\r\n\r\n public get nickname(): string {\r\n return this.privSpeechResponse.nickname;\r\n }\r\n\r\n public get participantId(): string {\r\n return this.privSpeechResponse.participantId;\r\n }\r\n\r\n public get roomid(): string {\r\n return this.privSpeechResponse.roomid;\r\n }\r\n\r\n public get timestamp(): string {\r\n return this.privSpeechResponse.timestamp;\r\n }\r\n\r\n public get type(): string {\r\n return this.privSpeechResponse.type;\r\n }\r\n\r\n public get isFinal(): boolean {\r\n return this.privSpeechResponse.type === \"final\";\r\n }\r\n}\r\n\r\n// tslint:disable-next-line: max-classes-per-file\r\nexport class TextResponsePayload implements ITextResponsePayload {\r\n\r\n private privTextResponse: ITextResponsePayload;\r\n\r\n private constructor(json: string) {\r\n this.privTextResponse = JSON.parse(json);\r\n }\r\n\r\n public static fromJSON(json: string): TextResponsePayload {\r\n return new TextResponsePayload(json);\r\n }\r\n\r\n public get originalText(): string {\r\n return this.privTextResponse.originalText;\r\n }\r\n\r\n public get translations(): ITranslationResponsePayload[] {\r\n return this.privTextResponse.translations;\r\n }\r\n\r\n public get id(): string {\r\n return this.privTextResponse.id;\r\n }\r\n\r\n public get language(): string {\r\n return this.privTextResponse.language;\r\n }\r\n\r\n public get nickname(): string {\r\n return this.privTextResponse.nickname;\r\n }\r\n\r\n public get participantId(): string {\r\n return this.privTextResponse.participantId;\r\n }\r\n\r\n public get roomid(): string {\r\n return this.privTextResponse.roomid;\r\n }\r\n\r\n public get timestamp(): string {\r\n return this.privTextResponse.timestamp;\r\n }\r\n\r\n public get type(): string {\r\n return this.privTextResponse.type;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { marshalPromiseToCallbacks } from \"../../common/Exports\";\r\nimport { AudioConfigImpl } from \"../../sdk/Audio/AudioConfig\";\r\nimport { Contracts } from \"../../sdk/Contracts\";\r\nimport {\r\n AudioConfig,\r\n CancellationEventArgs,\r\n Conversation,\r\n ConversationInfo,\r\n ConversationTranscriber,\r\n PropertyCollection,\r\n PropertyId,\r\n Recognizer,\r\n SessionEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechTranslationConfig,\r\n SpeechTranslationConfigImpl,\r\n} from \"../../sdk/Exports\";\r\nimport {\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig,\r\n TranscriberConnectionFactory,\r\n TranscriptionServiceRecognizer,\r\n} from \"../Exports\";\r\n\r\nexport class TranscriberRecognizer extends Recognizer {\r\n private privDisposedRecognizer: boolean;\r\n private privConversation: Conversation;\r\n\r\n /**\r\n * TranscriberRecognizer constructor.\r\n * @constructor\r\n * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer\r\n */\r\n public constructor(speechTranslationConfig: SpeechTranslationConfig, audioConfig?: AudioConfig) {\r\n const speechTranslationConfigImpl: SpeechTranslationConfigImpl = speechTranslationConfig as SpeechTranslationConfigImpl;\r\n Contracts.throwIfNull(speechTranslationConfigImpl, \"speechTranslationConfig\");\r\n\r\n Contracts.throwIfNullOrWhitespace(\r\n speechTranslationConfigImpl.speechRecognitionLanguage,\r\n PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);\r\n\r\n super(audioConfig, speechTranslationConfigImpl.properties, new TranscriberConnectionFactory());\r\n this.privDisposedRecognizer = false;\r\n }\r\n\r\n public recognizing: (sender: Recognizer, event: SpeechRecognitionEventArgs) => void;\r\n\r\n public recognized: (sender: Recognizer, event: SpeechRecognitionEventArgs) => void;\r\n\r\n public canceled: (sender: Recognizer, event: CancellationEventArgs) => void;\r\n\r\n public getConversationInfo(): ConversationInfo {\r\n Contracts.throwIfNullOrUndefined(this.privConversation, \"Conversation\");\r\n return this.privConversation.conversationInfo;\r\n }\r\n\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n public set conversation(c: Conversation) {\r\n Contracts.throwIfNullOrUndefined(c, \"Conversation\");\r\n this.privConversation = c;\r\n }\r\n\r\n public get speechRecognitionLanguage(): string {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n\r\n return this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);\r\n }\r\n\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n public startContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(RecognitionMode.Conversation), cb, err);\r\n }\r\n\r\n public stopContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {\r\n marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);\r\n }\r\n\r\n public async close(): Promise {\r\n Contracts.throwIfDisposed(this.privDisposedRecognizer);\r\n await this.dispose(true);\r\n }\r\n\r\n // Push async join/leave conversation message via serviceRecognizer\r\n public async pushConversationEvent(conversationInfo: ConversationInfo, command: string): Promise {\r\n const reco = (this.privReco) as TranscriptionServiceRecognizer;\r\n Contracts.throwIfNullOrUndefined(reco, \"serviceRecognizer\");\r\n await reco.sendSpeechEventAsync(conversationInfo, command);\r\n }\r\n\r\n public connectCallbacks(transcriber: ConversationTranscriber): void {\r\n this.canceled = (s: any, e: CancellationEventArgs): void => {\r\n if (!!transcriber.canceled) {\r\n transcriber.canceled(transcriber, e);\r\n }\r\n };\r\n this.recognizing = (s: any, e: SpeechRecognitionEventArgs): void => {\r\n if (!!transcriber.transcribing) {\r\n transcriber.transcribing(transcriber, e);\r\n }\r\n };\r\n this.recognized = (s: any, e: SpeechRecognitionEventArgs): void => {\r\n if (!!transcriber.transcribed) {\r\n transcriber.transcribed(transcriber, e);\r\n }\r\n };\r\n this.sessionStarted = (s: any, e: SessionEventArgs): void => {\r\n if (!!transcriber.sessionStarted) {\r\n transcriber.sessionStarted(transcriber, e);\r\n }\r\n };\r\n this.sessionStopped = (s: any, e: SessionEventArgs): void => {\r\n if (!!transcriber.sessionStopped) {\r\n transcriber.sessionStopped(transcriber, e);\r\n }\r\n };\r\n }\r\n\r\n public disconnectCallbacks(): void {\r\n this.canceled = undefined;\r\n this.recognizing = undefined;\r\n this.recognized = undefined;\r\n this.sessionStarted = undefined;\r\n this.sessionStopped = undefined;\r\n }\r\n\r\n /**\r\n * Disposes any resources held by the object.\r\n * @member ConversationTranscriber.prototype.dispose\r\n * @function\r\n * @public\r\n * @param {boolean} disposing - true if disposing the object.\r\n */\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privDisposedRecognizer) {\r\n return;\r\n }\r\n\r\n if (disposing) {\r\n this.privDisposedRecognizer = true;\r\n await this.implRecognizerStop();\r\n }\r\n\r\n await super.dispose(disposing);\r\n }\r\n\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(\r\n speechConfig,\r\n this.properties);\r\n }\r\n\r\n protected createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n const configImpl: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n return new TranscriptionServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ProxyInfo,\r\n WebsocketConnection,\r\n} from \"../common.browser/Exports\";\r\nimport {\r\n IConnection,\r\n IStringDictionary,\r\n} from \"../common/Exports\";\r\nimport {\r\n PropertyId\r\n} from \"../sdk/Exports\";\r\nimport {\r\n ConnectionFactoryBase\r\n} from \"./ConnectionFactoryBase\";\r\nimport {\r\n AuthInfo,\r\n IConnectionFactory,\r\n RecognizerConfig,\r\n WebsocketMessageFormatter,\r\n} from \"./Exports\";\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { QueryParameterNames } from \"./QueryParameterNames\";\r\n\r\nexport class TranslationConnectionFactory extends ConnectionFactoryBase {\r\n\r\n public create = (\r\n config: RecognizerConfig,\r\n authInfo: AuthInfo,\r\n connectionId?: string): IConnection => {\r\n\r\n let endpoint: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Endpoint, undefined);\r\n if (!endpoint) {\r\n const region: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Region, undefined);\r\n const hostSuffix: string = (region && region.toLowerCase().startsWith(\"china\")) ? \".azure.cn\" : \".microsoft.com\";\r\n const host: string = config.parameters.getProperty(PropertyId.SpeechServiceConnection_Host, \"wss://\" + region + \".s2s.speech\" + hostSuffix);\r\n endpoint = host + \"/speech/translation/cognitiveservices/v1\";\r\n }\r\n\r\n const queryParams: IStringDictionary = {\r\n from: config.parameters.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage),\r\n to: config.parameters.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages),\r\n };\r\n\r\n this.setCommonUrlParams(config, queryParams, endpoint);\r\n this.setUrlParameter(\r\n PropertyId.SpeechServiceResponse_TranslationRequestStablePartialResult,\r\n QueryParameterNames.StableTranslation,\r\n config,\r\n queryParams,\r\n endpoint\r\n );\r\n\r\n const voiceName: string = \"voice\";\r\n const featureName: string = \"features\";\r\n\r\n if (config.parameters.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) {\r\n queryParams[voiceName] = config.parameters.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice);\r\n queryParams[featureName] = \"texttospeech\";\r\n }\r\n\r\n const headers: IStringDictionary = {};\r\n if (authInfo.token !== undefined && authInfo.token !== \"\") {\r\n headers[authInfo.headerName] = authInfo.token;\r\n }\r\n headers[HeaderNames.ConnectionId] = connectionId;\r\n\r\n config.parameters.setProperty(PropertyId.SpeechServiceConnection_Url, endpoint);\r\n\r\n const enableCompression: boolean = config.parameters.getProperty(\"SPEECH-EnableWebsocketCompression\", \"false\") === \"true\";\r\n return new WebsocketConnection(endpoint, queryParams, headers, new WebsocketMessageFormatter(), ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionEvent,\r\n IAudioSource,\r\n MessageType,\r\n TranslationStatus,\r\n} from \"../common/Exports\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n PropertyCollection,\r\n PropertyId,\r\n ResultReason,\r\n SpeechRecognitionResult,\r\n TranslationRecognitionCanceledEventArgs,\r\n TranslationRecognitionEventArgs,\r\n TranslationRecognitionResult,\r\n TranslationRecognizer,\r\n Translations,\r\n TranslationSynthesisEventArgs,\r\n TranslationSynthesisResult,\r\n} from \"../sdk/Exports\";\r\nimport {\r\n CancellationErrorCodePropertyName,\r\n EnumTranslation,\r\n RecognitionStatus,\r\n ServiceRecognizerBase,\r\n SynthesisStatus,\r\n TranslationHypothesis,\r\n TranslationPhrase,\r\n TranslationSynthesisEnd,\r\n} from \"./Exports\";\r\nimport { IAuthentication } from \"./IAuthentication\";\r\nimport { IConnectionFactory } from \"./IConnectionFactory\";\r\nimport { RecognizerConfig } from \"./RecognizerConfig\";\r\nimport { SpeechConnectionMessage } from \"./SpeechConnectionMessage.Internal\";\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class TranslationServiceRecognizer extends ServiceRecognizerBase {\r\n private privTranslationRecognizer: TranslationRecognizer;\r\n\r\n public constructor(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioSource: IAudioSource,\r\n recognizerConfig: RecognizerConfig,\r\n translationRecognizer: TranslationRecognizer) {\r\n\r\n super(authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer);\r\n this.privTranslationRecognizer = translationRecognizer;\r\n this.connectionEvents.attach(async (connectionEvent: ConnectionEvent): Promise => {\r\n if (connectionEvent.name === \"ConnectionEstablishedEvent\") {\r\n this.privTranslationRecognizer.onConnection();\r\n } else if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n await this.privTranslationRecognizer.onDisconnection();\r\n }\r\n });\r\n\r\n }\r\n\r\n protected async processTypeSpecificMessages(connectionMessage: SpeechConnectionMessage): Promise {\r\n\r\n const resultProps: PropertyCollection = new PropertyCollection();\r\n let processed: boolean = false;\r\n\r\n if (connectionMessage.messageType === MessageType.Text) {\r\n resultProps.setProperty(PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);\r\n }\r\n\r\n switch (connectionMessage.path.toLowerCase()) {\r\n case \"translation.hypothesis\":\r\n\r\n const result: TranslationRecognitionEventArgs = this.fireEventForResult(TranslationHypothesis.fromJSON(connectionMessage.textBody), resultProps);\r\n this.privRequestSession.onHypothesis(this.privRequestSession.currentTurnAudioOffset + result.offset);\r\n\r\n if (!!this.privTranslationRecognizer.recognizing) {\r\n try {\r\n this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer, result);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n processed = true;\r\n break;\r\n case \"translation.phrase\":\r\n const translatedPhrase: TranslationPhrase = TranslationPhrase.fromJSON(connectionMessage.textBody);\r\n\r\n this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + translatedPhrase.Offset + translatedPhrase.Duration);\r\n\r\n if (translatedPhrase.RecognitionStatus === RecognitionStatus.Success) {\r\n\r\n // OK, the recognition was successful. How'd the translation do?\r\n const result: TranslationRecognitionEventArgs = this.fireEventForResult(translatedPhrase, resultProps);\r\n if (!!this.privTranslationRecognizer.recognized) {\r\n try {\r\n this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, result);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result.result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n\r\n break;\r\n } else {\r\n const reason: ResultReason = EnumTranslation.implTranslateRecognitionResult(translatedPhrase.RecognitionStatus);\r\n\r\n const result = new TranslationRecognitionResult(\r\n undefined,\r\n this.privRequestSession.requestId,\r\n reason,\r\n translatedPhrase.Text,\r\n translatedPhrase.Duration,\r\n this.privRequestSession.currentTurnAudioOffset + translatedPhrase.Offset,\r\n undefined,\r\n connectionMessage.textBody,\r\n resultProps);\r\n\r\n if (reason === ResultReason.Canceled) {\r\n const cancelReason: CancellationReason = EnumTranslation.implTranslateCancelResult(translatedPhrase.RecognitionStatus);\r\n\r\n await this.cancelRecognitionLocal(\r\n cancelReason,\r\n EnumTranslation.implTranslateCancelErrorCode(translatedPhrase.RecognitionStatus),\r\n undefined);\r\n } else {\r\n if (!(this.privRequestSession.isSpeechEnded && reason === ResultReason.NoMatch && translatedPhrase.RecognitionStatus !== RecognitionStatus.InitialSilenceTimeout)) {\r\n const ev = new TranslationRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);\r\n\r\n if (!!this.privTranslationRecognizer.recognized) {\r\n try {\r\n this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, ev);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n }\r\n\r\n // report result to promise.\r\n if (!!this.privSuccessCallback) {\r\n try {\r\n this.privSuccessCallback(result);\r\n } catch (e) {\r\n if (!!this.privErrorCallback) {\r\n this.privErrorCallback(e);\r\n }\r\n }\r\n // Only invoke the call back once.\r\n // and if it's successful don't invoke the\r\n // error after that.\r\n this.privSuccessCallback = undefined;\r\n this.privErrorCallback = undefined;\r\n }\r\n }\r\n }\r\n processed = true;\r\n break;\r\n\r\n case \"translation.synthesis\":\r\n this.sendSynthesisAudio(connectionMessage.binaryBody, this.privRequestSession.sessionId);\r\n processed = true;\r\n break;\r\n\r\n case \"translation.synthesis.end\":\r\n const synthEnd: TranslationSynthesisEnd = TranslationSynthesisEnd.fromJSON(connectionMessage.textBody);\r\n\r\n switch (synthEnd.SynthesisStatus) {\r\n case SynthesisStatus.Error:\r\n if (!!this.privTranslationRecognizer.synthesizing) {\r\n const result = new TranslationSynthesisResult(ResultReason.Canceled, undefined);\r\n const retEvent: TranslationSynthesisEventArgs = new TranslationSynthesisEventArgs(result, this.privRequestSession.sessionId);\r\n\r\n try {\r\n this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n if (!!this.privTranslationRecognizer.canceled) {\r\n // And raise a canceled event to send the rich(er) error message back.\r\n const canceledResult: TranslationRecognitionCanceledEventArgs = new TranslationRecognitionCanceledEventArgs(\r\n this.privRequestSession.sessionId,\r\n CancellationReason.Error,\r\n synthEnd.FailureReason,\r\n CancellationErrorCode.ServiceError,\r\n null);\r\n\r\n try {\r\n this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, canceledResult);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n break;\r\n case SynthesisStatus.Success:\r\n this.sendSynthesisAudio(undefined, this.privRequestSession.sessionId);\r\n break;\r\n default:\r\n break;\r\n }\r\n processed = true;\r\n break;\r\n default:\r\n break;\r\n }\r\n return processed;\r\n }\r\n\r\n // Cancels recognition.\r\n protected cancelRecognition(\r\n sessionId: string,\r\n requestId: string,\r\n cancellationReason: CancellationReason,\r\n errorCode: CancellationErrorCode,\r\n error: string): void {\r\n\r\n const properties: PropertyCollection = new PropertyCollection();\r\n properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);\r\n\r\n if (!!this.privTranslationRecognizer.canceled) {\r\n\r\n const cancelEvent: TranslationRecognitionCanceledEventArgs = new TranslationRecognitionCanceledEventArgs(\r\n sessionId,\r\n cancellationReason,\r\n error,\r\n errorCode,\r\n undefined);\r\n\r\n try {\r\n this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, cancelEvent);\r\n /* tslint:disable:no-empty */\r\n } catch { }\r\n }\r\n\r\n if (!!this.privSuccessCallback) {\r\n const result: TranslationRecognitionResult = new TranslationRecognitionResult(\r\n undefined, // Translations\r\n requestId,\r\n ResultReason.Canceled,\r\n undefined, // Text\r\n undefined, // Druation\r\n undefined, // Offset\r\n error,\r\n undefined, // Json\r\n properties);\r\n try {\r\n this.privSuccessCallback(result);\r\n /* tslint:disable:no-empty */\r\n this.privSuccessCallback = undefined;\r\n } catch { }\r\n }\r\n }\r\n\r\n private fireEventForResult(serviceResult: TranslationHypothesis | TranslationPhrase, properties: PropertyCollection): TranslationRecognitionEventArgs {\r\n let translations: Translations;\r\n\r\n if (undefined !== serviceResult.Translation.Translations) {\r\n translations = new Translations();\r\n for (const translation of serviceResult.Translation.Translations) {\r\n translations.set(translation.Language, translation.Text);\r\n }\r\n }\r\n\r\n let resultReason: ResultReason;\r\n if (serviceResult instanceof TranslationPhrase) {\r\n if (serviceResult.Translation.TranslationStatus === TranslationStatus.Success) {\r\n resultReason = ResultReason.TranslatedSpeech;\r\n } else {\r\n resultReason = ResultReason.RecognizedSpeech;\r\n }\r\n } else {\r\n resultReason = ResultReason.TranslatingSpeech;\r\n }\r\n\r\n const offset: number = serviceResult.Offset + this.privRequestSession.currentTurnAudioOffset;\r\n\r\n const result = new TranslationRecognitionResult(\r\n translations,\r\n this.privRequestSession.requestId,\r\n resultReason,\r\n serviceResult.Text,\r\n serviceResult.Duration,\r\n offset,\r\n serviceResult.Translation.FailureReason,\r\n JSON.stringify(serviceResult),\r\n properties);\r\n\r\n const ev = new TranslationRecognitionEventArgs(result, offset, this.privRequestSession.sessionId);\r\n return ev;\r\n }\r\n\r\n private sendSynthesisAudio(audio: ArrayBuffer, sessionId: string): void {\r\n const reason = (undefined === audio) ? ResultReason.SynthesizingAudioCompleted : ResultReason.SynthesizingAudio;\r\n const result = new TranslationSynthesisResult(reason, audio);\r\n const retEvent: TranslationSynthesisEventArgs = new TranslationSynthesisEventArgs(result, sessionId);\r\n\r\n if (!!this.privTranslationRecognizer.synthesizing) {\r\n try {\r\n this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent);\r\n /* tslint:disable:no-empty */\r\n } catch (error) {\r\n // Not going to let errors in the event handler\r\n // trip things up.\r\n }\r\n }\r\n\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines translation status.\r\n * @class TranslationStatus\r\n */\r\nexport enum TranslationStatus {\r\n /**\r\n * @member TranslationStatus.Success\r\n */\r\n Success = 0,\r\n\r\n /**\r\n * @member TranslationStatus.Error\r\n */\r\n Error,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionMessage,\r\n Deferred,\r\n IStringDictionary,\r\n IWebsocketMessageFormatter,\r\n MessageType,\r\n RawWebsocketMessage,\r\n} from \"../common/Exports\";\r\n\r\nconst CRLF: string = \"\\r\\n\";\r\n\r\nexport class WebsocketMessageFormatter implements IWebsocketMessageFormatter {\r\n\r\n public toConnectionMessage = (message: RawWebsocketMessage): Promise => {\r\n const deferral = new Deferred();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const textMessage: string = message.textContent;\r\n let headers: IStringDictionary = {};\r\n let body: string = null;\r\n\r\n if (textMessage) {\r\n const headerBodySplit = textMessage.split(\"\\r\\n\\r\\n\");\r\n if (headerBodySplit && headerBodySplit.length > 0) {\r\n headers = this.parseHeaders(headerBodySplit[0]);\r\n if (headerBodySplit.length > 1) {\r\n body = headerBodySplit[1];\r\n }\r\n }\r\n }\r\n\r\n deferral.resolve(new ConnectionMessage(message.messageType, body, headers, message.id));\r\n } else if (message.messageType === MessageType.Binary) {\r\n const binaryMessage: ArrayBuffer = message.binaryContent;\r\n let headers: IStringDictionary = {};\r\n let body: ArrayBuffer = null;\r\n\r\n if (!binaryMessage || binaryMessage.byteLength < 2) {\r\n throw new Error(\"Invalid binary message format. Header length missing.\");\r\n }\r\n\r\n const dataView = new DataView(binaryMessage);\r\n const headerLength = dataView.getInt16(0);\r\n\r\n if (binaryMessage.byteLength < headerLength + 2) {\r\n throw new Error(\"Invalid binary message format. Header content missing.\");\r\n }\r\n\r\n let headersString = \"\";\r\n for (let i = 0; i < headerLength; i++) {\r\n headersString += String.fromCharCode((dataView).getInt8(i + 2));\r\n }\r\n\r\n headers = this.parseHeaders(headersString);\r\n\r\n if (binaryMessage.byteLength > headerLength + 2) {\r\n body = binaryMessage.slice(2 + headerLength);\r\n }\r\n\r\n deferral.resolve(new ConnectionMessage(message.messageType, body, headers, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. Error: ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n public fromConnectionMessage = (message: ConnectionMessage): Promise => {\r\n const deferral = new Deferred();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const payload = `${this.makeHeaders(message)}${CRLF}${message.textBody ? message.textBody : \"\"}`;\r\n\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Text, payload, message.id));\r\n\r\n } else if (message.messageType === MessageType.Binary) {\r\n const headersString = this.makeHeaders(message);\r\n const content = message.binaryBody;\r\n\r\n const headerBuffer = this.stringToArrayBuffer(headersString);\r\n const headerInt8Array = new Int8Array(headerBuffer);\r\n const headerLength = headerInt8Array.byteLength;\r\n\r\n const payloadInt8Array = new Int8Array(2 + headerLength + (content ? content.byteLength : 0));\r\n payloadInt8Array[0] = ((headerLength >> 8) & 0xff);\r\n payloadInt8Array[1] = headerLength & 0xff;\r\n payloadInt8Array.set(headerInt8Array, 2);\r\n\r\n if (content) {\r\n const bodyInt8Array = new Int8Array(content);\r\n payloadInt8Array.set(bodyInt8Array, 2 + headerLength);\r\n }\r\n\r\n const payload: ArrayBuffer = payloadInt8Array.buffer;\r\n\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Binary, payload, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n private makeHeaders = (message: ConnectionMessage): string => {\r\n let headersString: string = \"\";\r\n\r\n if (message.headers) {\r\n for (const header in message.headers) {\r\n if (header) {\r\n headersString += `${header}: ${message.headers[header]}${CRLF}`;\r\n }\r\n }\r\n }\r\n\r\n return headersString;\r\n }\r\n\r\n private parseHeaders = (headersString: string): IStringDictionary => {\r\n const headers: IStringDictionary = {};\r\n\r\n if (headersString) {\r\n const headerMatches = headersString.match(/[^\\r\\n]+/g);\r\n if (headers) {\r\n for (const header of headerMatches) {\r\n if (header) {\r\n const separatorIndex = header.indexOf(\":\");\r\n const headerName = separatorIndex > 0 ? header.substr(0, separatorIndex).trim().toLowerCase() : header;\r\n const headerValue =\r\n separatorIndex > 0 && header.length > (separatorIndex + 1) ?\r\n header.substr(separatorIndex + 1).trim() :\r\n \"\";\r\n\r\n headers[headerName] = headerValue;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return headers;\r\n }\r\n\r\n private stringToArrayBuffer = (str: string): ArrayBuffer => {\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new DataView(buffer);\r\n for (let i = 0; i < str.length; i++) {\r\n view.setUint8(i, str.charCodeAt(i));\r\n }\r\n return buffer;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { EventType, PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class AudioSourceEvent extends PlatformEvent {\r\n private privAudioSourceId: string;\r\n\r\n constructor(eventName: string, audioSourceId: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n this.privAudioSourceId = audioSourceId;\r\n }\r\n\r\n public get audioSourceId(): string {\r\n return this.privAudioSourceId;\r\n }\r\n}\r\n\r\nexport class AudioSourceInitializingEvent extends AudioSourceEvent {\r\n constructor(audioSourceId: string) {\r\n super(\"AudioSourceInitializingEvent\", audioSourceId);\r\n }\r\n}\r\n\r\nexport class AudioSourceReadyEvent extends AudioSourceEvent {\r\n constructor(audioSourceId: string) {\r\n super(\"AudioSourceReadyEvent\", audioSourceId);\r\n }\r\n}\r\n\r\nexport class AudioSourceOffEvent extends AudioSourceEvent {\r\n constructor(audioSourceId: string) {\r\n super(\"AudioSourceOffEvent\", audioSourceId);\r\n }\r\n}\r\n\r\nexport class AudioSourceErrorEvent extends AudioSourceEvent {\r\n private privError: string;\r\n\r\n constructor(audioSourceId: string, error: string) {\r\n super(\"AudioSourceErrorEvent\", audioSourceId, EventType.Error);\r\n this.privError = error;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeEvent extends AudioSourceEvent {\r\n private privAudioNodeId: string;\r\n\r\n constructor(eventName: string, audioSourceId: string, audioNodeId: string) {\r\n super(eventName, audioSourceId);\r\n this.privAudioNodeId = audioNodeId;\r\n }\r\n\r\n public get audioNodeId(): string {\r\n return this.privAudioNodeId;\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeAttachingEvent extends AudioStreamNodeEvent {\r\n constructor(audioSourceId: string, audioNodeId: string) {\r\n super(\"AudioStreamNodeAttachingEvent\", audioSourceId, audioNodeId);\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeAttachedEvent extends AudioStreamNodeEvent {\r\n constructor(audioSourceId: string, audioNodeId: string) {\r\n super(\"AudioStreamNodeAttachedEvent\", audioSourceId, audioNodeId);\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeDetachedEvent extends AudioStreamNodeEvent {\r\n constructor(audioSourceId: string, audioNodeId: string) {\r\n super(\"AudioStreamNodeDetachedEvent\", audioSourceId, audioNodeId);\r\n }\r\n}\r\n\r\nexport class AudioStreamNodeErrorEvent extends AudioStreamNodeEvent {\r\n private privError: string;\r\n\r\n constructor(audioSourceId: string, audioNodeId: string, error: string) {\r\n super(\"AudioStreamNodeErrorEvent\", audioSourceId, audioNodeId);\r\n this.privError = error;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n}\r\n","\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n EventType,\r\n PlatformEvent\r\n} from \"./Exports\";\r\n\r\nexport class BackgroundEvent extends PlatformEvent {\r\n private privError: string;\r\n\r\n constructor(error: string) {\r\n super(\"BackgroundEvent\", EventType.Error);\r\n this.privError = error;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { IStreamChunk, Stream } from \"./Exports\";\r\n\r\nexport class ChunkedArrayBufferStream extends Stream {\r\n private privTargetChunkSize: number;\r\n private privNextBufferToWrite: ArrayBuffer;\r\n private privNextBufferStartTime: number;\r\n private privNextBufferReadyBytes: number;\r\n\r\n constructor(targetChunkSize: number, streamId?: string) {\r\n super(streamId);\r\n this.privTargetChunkSize = targetChunkSize;\r\n this.privNextBufferReadyBytes = 0;\r\n }\r\n\r\n public writeStreamChunk(chunk: IStreamChunk): void {\r\n // No pending write, and the buffer is the right size so write it.\r\n if (chunk.isEnd ||\r\n (0 === this.privNextBufferReadyBytes && chunk.buffer.byteLength === this.privTargetChunkSize)) {\r\n super.writeStreamChunk(chunk);\r\n return;\r\n }\r\n\r\n let bytesCopiedFromBuffer: number = 0;\r\n\r\n while (bytesCopiedFromBuffer < chunk.buffer.byteLength) {\r\n // Fill the next buffer.\r\n if (undefined === this.privNextBufferToWrite) {\r\n this.privNextBufferToWrite = new ArrayBuffer(this.privTargetChunkSize);\r\n this.privNextBufferStartTime = chunk.timeReceived;\r\n }\r\n\r\n // Find out how many bytes we can copy into the read buffer.\r\n const bytesToCopy: number = Math.min(chunk.buffer.byteLength - bytesCopiedFromBuffer, this.privTargetChunkSize - this.privNextBufferReadyBytes);\r\n const targetView: Uint8Array = new Uint8Array(this.privNextBufferToWrite);\r\n const sourceView: Uint8Array = new Uint8Array(chunk.buffer.slice(bytesCopiedFromBuffer, bytesToCopy + bytesCopiedFromBuffer));\r\n\r\n targetView.set(sourceView, this.privNextBufferReadyBytes);\r\n this.privNextBufferReadyBytes += bytesToCopy;\r\n bytesCopiedFromBuffer += bytesToCopy;\r\n\r\n // Are we ready to write?\r\n if (this.privNextBufferReadyBytes === this.privTargetChunkSize) {\r\n super.writeStreamChunk({\r\n buffer: this.privNextBufferToWrite,\r\n isEnd: false,\r\n timeReceived: this.privNextBufferStartTime,\r\n });\r\n this.privNextBufferReadyBytes = 0;\r\n this.privNextBufferToWrite = undefined;\r\n }\r\n }\r\n }\r\n\r\n public close(): void {\r\n // Send whatever is pending, then close the base class.\r\n if (0 !== this.privNextBufferReadyBytes && !this.isClosed) {\r\n super.writeStreamChunk({\r\n buffer: this.privNextBufferToWrite.slice(0, this.privNextBufferReadyBytes),\r\n isEnd: false,\r\n timeReceived: this.privNextBufferStartTime,\r\n });\r\n }\r\n\r\n super.close();\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { ConnectionMessage } from \"./ConnectionMessage\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\nimport { EventType, PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class ServiceEvent extends PlatformEvent {\r\n private privJsonResult: string;\r\n\r\n constructor(eventName: string, jsonstring: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n this.privJsonResult = jsonstring;\r\n }\r\n\r\n public get jsonString(): string {\r\n return this.privJsonResult;\r\n }\r\n}\r\n\r\nexport class ConnectionEvent extends PlatformEvent {\r\n private privConnectionId: string;\r\n\r\n constructor(eventName: string, connectionId: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n this.privConnectionId = connectionId;\r\n }\r\n\r\n public get connectionId(): string {\r\n return this.privConnectionId;\r\n }\r\n}\r\n\r\nexport class ConnectionStartEvent extends ConnectionEvent {\r\n private privUri: string;\r\n private privHeaders: IStringDictionary;\r\n\r\n constructor(connectionId: string, uri: string, headers?: IStringDictionary) {\r\n super(\"ConnectionStartEvent\", connectionId);\r\n this.privUri = uri;\r\n this.privHeaders = headers;\r\n }\r\n\r\n public get uri(): string {\r\n return this.privUri;\r\n }\r\n\r\n public get headers(): IStringDictionary {\r\n return this.privHeaders;\r\n }\r\n}\r\n\r\nexport class ConnectionEstablishedEvent extends ConnectionEvent {\r\n constructor(connectionId: string, metadata?: IStringDictionary) {\r\n super(\"ConnectionEstablishedEvent\", connectionId);\r\n }\r\n}\r\n\r\nexport class ConnectionClosedEvent extends ConnectionEvent {\r\n private privReason: string;\r\n private privStatusCode: number;\r\n\r\n constructor(connectionId: string, statusCode: number, reason: string) {\r\n super(\"ConnectionClosedEvent\", connectionId, EventType.Debug);\r\n this.privReason = reason;\r\n this.privStatusCode = statusCode;\r\n }\r\n\r\n public get reason(): string {\r\n return this.privReason;\r\n }\r\n\r\n public get statusCode(): number {\r\n return this.privStatusCode;\r\n }\r\n}\r\n\r\nexport class ConnectionErrorEvent extends ConnectionEvent {\r\n private readonly privMessage: string;\r\n private readonly privType: string;\r\n\r\n constructor(connectionId: string, message: string, type: string) {\r\n super(\"ConnectionErrorEvent\", connectionId, EventType.Debug);\r\n this.privMessage = message;\r\n this.privType = type;\r\n }\r\n\r\n public get message(): string {\r\n return this.privMessage;\r\n }\r\n\r\n public get type(): string {\r\n return this.privType;\r\n }\r\n}\r\n\r\nexport class ConnectionEstablishErrorEvent extends ConnectionEvent {\r\n private privStatusCode: number;\r\n private privReason: string;\r\n\r\n constructor(connectionId: string, statuscode: number, reason: string) {\r\n super(\"ConnectionEstablishErrorEvent\", connectionId, EventType.Error);\r\n this.privStatusCode = statuscode;\r\n this.privReason = reason;\r\n }\r\n\r\n public get reason(): string {\r\n return this.privReason;\r\n }\r\n\r\n public get statusCode(): number {\r\n return this.privStatusCode;\r\n }\r\n}\r\n\r\nexport class ConnectionMessageReceivedEvent extends ConnectionEvent {\r\n private privNetworkReceivedTime: string;\r\n private privMessage: ConnectionMessage;\r\n\r\n constructor(connectionId: string, networkReceivedTimeISO: string, message: ConnectionMessage) {\r\n super(\"ConnectionMessageReceivedEvent\", connectionId);\r\n this.privNetworkReceivedTime = networkReceivedTimeISO;\r\n this.privMessage = message;\r\n }\r\n\r\n public get networkReceivedTime(): string {\r\n return this.privNetworkReceivedTime;\r\n }\r\n\r\n public get message(): ConnectionMessage {\r\n return this.privMessage;\r\n }\r\n}\r\n\r\nexport class ConnectionMessageSentEvent extends ConnectionEvent {\r\n private privNetworkSentTime: string;\r\n private privMessage: ConnectionMessage;\r\n\r\n constructor(connectionId: string, networkSentTimeISO: string, message: ConnectionMessage) {\r\n super(\"ConnectionMessageSentEvent\", connectionId);\r\n this.privNetworkSentTime = networkSentTimeISO;\r\n this.privMessage = message;\r\n }\r\n\r\n public get networkSentTime(): string {\r\n return this.privNetworkSentTime;\r\n }\r\n\r\n public get message(): ConnectionMessage {\r\n return this.privMessage;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError } from \"./Error\";\r\nimport { createNoDashGuid } from \"./Guid\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\n\r\nexport enum MessageType {\r\n Text,\r\n Binary,\r\n}\r\n\r\nexport class ConnectionMessage {\r\n\r\n private privMessageType: MessageType;\r\n private privHeaders: IStringDictionary;\r\n private privBody: any = null;\r\n private privSize: number;\r\n\r\n private privId: string;\r\n\r\n public constructor(\r\n messageType: MessageType,\r\n body: any,\r\n headers?: IStringDictionary,\r\n id?: string) {\r\n\r\n if (messageType === MessageType.Text && body && !(typeof (body) === \"string\")) {\r\n throw new InvalidOperationError(\"Payload must be a string\");\r\n }\r\n\r\n if (messageType === MessageType.Binary && body && !(body instanceof ArrayBuffer)) {\r\n throw new InvalidOperationError(\"Payload must be ArrayBuffer\");\r\n }\r\n\r\n this.privMessageType = messageType;\r\n this.privBody = body;\r\n this.privHeaders = headers ? headers : {};\r\n this.privId = id ? id : createNoDashGuid();\r\n switch (this.messageType) {\r\n case MessageType.Binary:\r\n this.privSize = this.binaryBody !== null ? this.binaryBody.byteLength : 0;\r\n break;\r\n case MessageType.Text:\r\n this.privSize = this.textBody.length;\r\n }\r\n }\r\n\r\n public get messageType(): MessageType {\r\n return this.privMessageType;\r\n }\r\n\r\n public get headers(): IStringDictionary {\r\n return this.privHeaders;\r\n }\r\n\r\n public get body(): any {\r\n return this.privBody;\r\n }\r\n\r\n public get textBody(): string {\r\n if (this.privMessageType === MessageType.Binary) {\r\n throw new InvalidOperationError(\"Not supported for binary message\");\r\n }\r\n\r\n return this.privBody as string;\r\n }\r\n\r\n public get binaryBody(): ArrayBuffer {\r\n if (this.privMessageType === MessageType.Text) {\r\n throw new InvalidOperationError(\"Not supported for text message\");\r\n }\r\n\r\n return this.privBody;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport class ConnectionOpenResponse {\r\n private privStatusCode: number;\r\n private privReason: string;\r\n\r\n constructor(statusCode: number, reason: string) {\r\n this.privStatusCode = statusCode;\r\n this.privReason = reason;\r\n }\r\n\r\n public get statusCode(): number {\r\n return this.privStatusCode;\r\n }\r\n\r\n public get reason(): string {\r\n return this.privReason;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { AgentConfig } from \"../common.speech/Exports\";\r\nimport { EventType, PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class DialogEvent extends PlatformEvent {\r\n\r\n constructor(eventName: string, eventType: EventType = EventType.Info) {\r\n super(eventName, eventType);\r\n }\r\n}\r\n\r\nexport class SendingAgentContextMessageEvent extends DialogEvent {\r\n private privAgentConfig: AgentConfig;\r\n\r\n constructor(agentConfig: AgentConfig) {\r\n super(\"SendingAgentContextMessageEvent\");\r\n this.privAgentConfig = agentConfig;\r\n }\r\n\r\n public get agentConfig(): AgentConfig {\r\n return this.privAgentConfig;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\n/**\r\n * The error that is thrown when an argument passed in is null.\r\n *\r\n * @export\r\n * @class ArgumentNullError\r\n * @extends {Error}\r\n */\r\nexport class ArgumentNullError extends Error {\r\n\r\n /**\r\n * Creates an instance of ArgumentNullError.\r\n *\r\n * @param {string} argumentName - Name of the argument that is null\r\n *\r\n * @memberOf ArgumentNullError\r\n */\r\n public constructor(argumentName: string) {\r\n super(argumentName);\r\n this.name = \"ArgumentNull\";\r\n this.message = argumentName;\r\n }\r\n}\r\n\r\n/**\r\n * The error that is thrown when an invalid operation is performed in the code.\r\n *\r\n * @export\r\n * @class InvalidOperationError\r\n * @extends {Error}\r\n */\r\nexport class InvalidOperationError extends Error {\r\n\r\n /**\r\n * Creates an instance of InvalidOperationError.\r\n *\r\n * @param {string} error - The error\r\n *\r\n * @memberOf InvalidOperationError\r\n */\r\n public constructor(error: string) {\r\n super(error);\r\n this.name = \"InvalidOperation\";\r\n this.message = error;\r\n }\r\n}\r\n\r\n/**\r\n * The error that is thrown when an object is disposed.\r\n *\r\n * @export\r\n * @class ObjectDisposedError\r\n * @extends {Error}\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class ObjectDisposedError extends Error {\r\n\r\n /**\r\n * Creates an instance of ObjectDisposedError.\r\n *\r\n * @param {string} objectName - The object that is disposed\r\n * @param {string} error - The error\r\n *\r\n * @memberOf ObjectDisposedError\r\n */\r\n public constructor(objectName: string, error?: string) {\r\n super(error);\r\n this.name = objectName + \"ObjectDisposed\";\r\n this.message = error;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ObjectDisposedError } from \"./Error\";\r\nimport { createNoDashGuid } from \"./Guid\";\r\nimport { IDetachable } from \"./IDetachable\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\nimport { IEventListener, IEventSource } from \"./IEventSource\";\r\nimport { PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class EventSource implements IEventSource {\r\n private privEventListeners: IStringDictionary<(event: TEvent) => void> = {};\r\n private privMetadata: IStringDictionary;\r\n private privIsDisposed: boolean = false;\r\n\r\n constructor(metadata?: IStringDictionary) {\r\n this.privMetadata = metadata;\r\n }\r\n\r\n public onEvent = (event: TEvent): void => {\r\n if (this.isDisposed()) {\r\n throw (new ObjectDisposedError(\"EventSource\"));\r\n }\r\n\r\n if (this.metadata) {\r\n for (const paramName in this.metadata) {\r\n if (paramName) {\r\n if (event.metadata) {\r\n if (!event.metadata[paramName]) {\r\n event.metadata[paramName] = this.metadata[paramName];\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n for (const eventId in this.privEventListeners) {\r\n if (eventId && this.privEventListeners[eventId]) {\r\n this.privEventListeners[eventId](event);\r\n }\r\n }\r\n }\r\n\r\n public attach = (onEventCallback: (event: TEvent) => void): IDetachable => {\r\n const id = createNoDashGuid();\r\n this.privEventListeners[id] = onEventCallback;\r\n return {\r\n detach: () => {\r\n delete this.privEventListeners[id];\r\n return Promise.resolve();\r\n },\r\n };\r\n }\r\n\r\n public attachListener = (listener: IEventListener): IDetachable => {\r\n return this.attach(listener.onEvent);\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privIsDisposed;\r\n }\r\n\r\n public dispose = (): void => {\r\n this.privEventListeners = null;\r\n this.privIsDisposed = true;\r\n }\r\n\r\n public get metadata(): IStringDictionary {\r\n return this.privMetadata;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ArgumentNullError } from \"./Error\";\r\nimport { EventSource } from \"./EventSource\";\r\nimport { IEventSource } from \"./IEventSource\";\r\nimport { PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class Events {\r\n private static privInstance: IEventSource = new EventSource();\r\n\r\n public static setEventSource = (eventSource: IEventSource): void => {\r\n if (!eventSource) {\r\n throw new ArgumentNullError(\"eventSource\");\r\n }\r\n\r\n Events.privInstance = eventSource;\r\n }\r\n\r\n public static get instance(): IEventSource {\r\n return Events.privInstance;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport * from \"./AudioSourceEvents\";\r\nexport * from \"./ConnectionEvents\";\r\nexport * from \"./ConnectionMessage\";\r\nexport * from \"./ConnectionOpenResponse\";\r\nexport * from \"./DialogEvents\";\r\nexport * from \"./Error\";\r\nexport * from \"./Events\";\r\nexport * from \"./EventSource\";\r\nexport * from \"./Guid\";\r\nexport * from \"./IAudioSource\";\r\nexport * from \"./IConnection\";\r\nexport * from \"./IDetachable\";\r\nexport * from \"./IDictionary\";\r\nexport * from \"./IDisposable\";\r\nexport * from \"./IEventSource\";\r\nexport * from \"./IErrorMessages\";\r\nexport * from \"./ITimer\";\r\nexport * from \"./IWebsocketMessageFormatter\";\r\nexport * from \"./List\";\r\nexport * from \"./PlatformEvent\";\r\nexport * from \"./Promise\";\r\nexport * from \"./Queue\";\r\nexport * from \"./RawWebsocketMessage\";\r\nexport * from \"./RiffPcmEncoder\";\r\nexport * from \"./Stream\";\r\nexport { TranslationStatus } from \"../common.speech/TranslationStatus\";\r\nexport * from \"./ChunkedArrayBufferStream\";\r\nexport * from \"./IAudioDestination\";\r\nexport * from \"./Timeout\";\r\nexport * from \"./OCSPEvents\";\r\nexport * from \"./BackgroundError\";\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { v4 as uuid } from \"uuid\";\r\n\r\nconst createGuid: () => string = (): string => {\r\n return uuid();\r\n};\r\n\r\nconst createNoDashGuid: () => string = (): string => {\r\n return createGuid().replace(new RegExp(\"-\", \"g\"), \"\").toUpperCase();\r\n};\r\n\r\nexport { createGuid, createNoDashGuid };\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ConnectionEvent } from \"./ConnectionEvents\";\r\nimport { ConnectionMessage } from \"./ConnectionMessage\";\r\nimport { ConnectionOpenResponse } from \"./ConnectionOpenResponse\";\r\nimport { EventSource } from \"./EventSource\";\r\n\r\nexport enum ConnectionState {\r\n None,\r\n Connected,\r\n Connecting,\r\n Disconnected,\r\n}\r\n\r\nexport interface IConnection {\r\n id: string;\r\n state(): ConnectionState;\r\n open(): Promise;\r\n send(message: ConnectionMessage): Promise;\r\n read(): Promise;\r\n events: EventSource;\r\n dispose(disposing?: string): Promise;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { ObjectDisposedError } from \"./Error\";\r\nimport { IDetachable } from \"./IDetachable\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\nimport { IDisposable } from \"./IDisposable\";\r\n\r\nexport interface IList extends IDisposable {\r\n get(itemIndex: number): TItem;\r\n first(): TItem;\r\n last(): TItem;\r\n\r\n add(item: TItem): void;\r\n insertAt(index: number, item: TItem): void;\r\n\r\n removeFirst(): TItem;\r\n removeLast(): TItem;\r\n removeAt(index: number): TItem;\r\n remove(index: number, count: number): TItem[];\r\n clear(): void;\r\n\r\n length(): number;\r\n\r\n onAdded(addedCallback: () => void): IDetachable;\r\n onRemoved(removedCallback: () => void): IDetachable;\r\n onDisposed(disposedCallback: () => void): IDetachable;\r\n\r\n join(seperator?: string): string;\r\n\r\n toArray(): TItem[];\r\n\r\n any(callback?: (item: TItem, index: number) => boolean): boolean;\r\n all(callback: (item: TItem) => boolean): boolean;\r\n forEach(callback: (item: TItem, index: number) => void): void;\r\n select(callback: (item: TItem, index: number) => T2): List;\r\n where(callback: (item: TItem, index: number) => boolean): List;\r\n orderBy(compareFn: (a: TItem, b: TItem) => number): List;\r\n orderByDesc(compareFn: (a: TItem, b: TItem) => number): List;\r\n clone(): List;\r\n concat(list: List): List;\r\n concatArray(array: TItem[]): List;\r\n}\r\n\r\nexport class List implements IList {\r\n private privList: TItem[];\r\n private privSubscriptionIdCounter: number = 0;\r\n private privAddSubscriptions: IStringDictionary<() => void> = {};\r\n private privRemoveSubscriptions: IStringDictionary<() => void> = {};\r\n private privDisposedSubscriptions: IStringDictionary<() => void> = {};\r\n private privDisposeReason: string = null;\r\n\r\n public constructor(list?: TItem[]) {\r\n this.privList = [];\r\n // copy the list rather than taking as is.\r\n if (list) {\r\n for (const item of list) {\r\n this.privList.push(item);\r\n }\r\n }\r\n }\r\n\r\n public get = (itemIndex: number): TItem => {\r\n this.throwIfDisposed();\r\n return this.privList[itemIndex];\r\n }\r\n\r\n public first = (): TItem => {\r\n return this.get(0);\r\n }\r\n\r\n public last = (): TItem => {\r\n return this.get(this.length() - 1);\r\n }\r\n\r\n public add = (item: TItem): void => {\r\n this.throwIfDisposed();\r\n this.insertAt(this.privList.length, item);\r\n }\r\n\r\n public insertAt = (index: number, item: TItem): void => {\r\n this.throwIfDisposed();\r\n if (index === 0) {\r\n this.privList.unshift(item);\r\n } else if (index === this.privList.length) {\r\n this.privList.push(item);\r\n } else {\r\n this.privList.splice(index, 0, item);\r\n }\r\n this.triggerSubscriptions(this.privAddSubscriptions);\r\n }\r\n\r\n public removeFirst = (): TItem => {\r\n this.throwIfDisposed();\r\n return this.removeAt(0);\r\n }\r\n\r\n public removeLast = (): TItem => {\r\n this.throwIfDisposed();\r\n return this.removeAt(this.length() - 1);\r\n }\r\n\r\n public removeAt = (index: number): TItem => {\r\n this.throwIfDisposed();\r\n return this.remove(index, 1)[0];\r\n }\r\n\r\n public remove = (index: number, count: number): TItem[] => {\r\n this.throwIfDisposed();\r\n const removedElements = this.privList.splice(index, count);\r\n this.triggerSubscriptions(this.privRemoveSubscriptions);\r\n return removedElements;\r\n }\r\n\r\n public clear = (): void => {\r\n this.throwIfDisposed();\r\n this.remove(0, this.length());\r\n }\r\n\r\n public length = (): number => {\r\n this.throwIfDisposed();\r\n return this.privList.length;\r\n }\r\n\r\n public onAdded = (addedCallback: () => void): IDetachable => {\r\n this.throwIfDisposed();\r\n const subscriptionId = this.privSubscriptionIdCounter++;\r\n\r\n this.privAddSubscriptions[subscriptionId] = addedCallback;\r\n\r\n return {\r\n detach: () => {\r\n delete this.privAddSubscriptions[subscriptionId];\r\n return Promise.resolve();\r\n },\r\n };\r\n }\r\n\r\n public onRemoved = (removedCallback: () => void): IDetachable => {\r\n this.throwIfDisposed();\r\n const subscriptionId = this.privSubscriptionIdCounter++;\r\n\r\n this.privRemoveSubscriptions[subscriptionId] = removedCallback;\r\n\r\n return {\r\n detach: () => {\r\n delete this.privRemoveSubscriptions[subscriptionId];\r\n return Promise.resolve();\r\n },\r\n };\r\n }\r\n\r\n public onDisposed = (disposedCallback: () => void): IDetachable => {\r\n this.throwIfDisposed();\r\n const subscriptionId = this.privSubscriptionIdCounter++;\r\n\r\n this.privDisposedSubscriptions[subscriptionId] = disposedCallback;\r\n\r\n return {\r\n detach: () => {\r\n delete this.privDisposedSubscriptions[subscriptionId];\r\n return Promise.resolve();\r\n },\r\n };\r\n }\r\n\r\n public join = (seperator?: string): string => {\r\n this.throwIfDisposed();\r\n return this.privList.join(seperator);\r\n }\r\n\r\n public toArray = (): TItem[] => {\r\n const cloneCopy = Array();\r\n this.privList.forEach((val: TItem) => {\r\n cloneCopy.push(val);\r\n });\r\n return cloneCopy;\r\n }\r\n\r\n public any = (callback?: (item: TItem, index: number) => boolean): boolean => {\r\n this.throwIfDisposed();\r\n if (callback) {\r\n return this.where(callback).length() > 0;\r\n } else {\r\n return this.length() > 0;\r\n }\r\n }\r\n\r\n public all = (callback: (item: TItem) => boolean): boolean => {\r\n this.throwIfDisposed();\r\n return this.where(callback).length() === this.length();\r\n }\r\n\r\n public forEach = (callback: (item: TItem, index: number) => void): void => {\r\n this.throwIfDisposed();\r\n for (let i = 0; i < this.length(); i++) {\r\n callback(this.privList[i], i);\r\n }\r\n }\r\n\r\n public select = (callback: (item: TItem, index: number) => T2): List => {\r\n this.throwIfDisposed();\r\n const selectList: T2[] = [];\r\n for (let i = 0; i < this.privList.length; i++) {\r\n selectList.push(callback(this.privList[i], i));\r\n }\r\n\r\n return new List(selectList);\r\n }\r\n\r\n public where = (callback: (item: TItem, index: number) => boolean): List => {\r\n this.throwIfDisposed();\r\n const filteredList = new List();\r\n for (let i = 0; i < this.privList.length; i++) {\r\n if (callback(this.privList[i], i)) {\r\n filteredList.add(this.privList[i]);\r\n }\r\n }\r\n return filteredList;\r\n }\r\n\r\n public orderBy = (compareFn: (a: TItem, b: TItem) => number): List => {\r\n this.throwIfDisposed();\r\n const clonedArray = this.toArray();\r\n const orderedArray = clonedArray.sort(compareFn);\r\n return new List(orderedArray);\r\n }\r\n\r\n public orderByDesc = (compareFn: (a: TItem, b: TItem) => number): List => {\r\n this.throwIfDisposed();\r\n return this.orderBy((a: TItem, b: TItem) => compareFn(b, a));\r\n }\r\n\r\n public clone = (): List => {\r\n this.throwIfDisposed();\r\n return new List(this.toArray());\r\n }\r\n\r\n public concat = (list: List): List => {\r\n this.throwIfDisposed();\r\n return new List(this.privList.concat(list.toArray()));\r\n }\r\n\r\n public concatArray = (array: TItem[]): List => {\r\n this.throwIfDisposed();\r\n return new List(this.privList.concat(array));\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privList == null;\r\n }\r\n\r\n public dispose = (reason?: string): void => {\r\n if (!this.isDisposed()) {\r\n this.privDisposeReason = reason;\r\n this.privList = null;\r\n this.privAddSubscriptions = null;\r\n this.privRemoveSubscriptions = null;\r\n this.triggerSubscriptions(this.privDisposedSubscriptions);\r\n }\r\n }\r\n\r\n private throwIfDisposed = (): void => {\r\n if (this.isDisposed()) {\r\n throw new ObjectDisposedError(\"List\", this.privDisposeReason);\r\n }\r\n }\r\n\r\n private triggerSubscriptions = (subscriptions: IStringDictionary<() => void>): void => {\r\n if (subscriptions) {\r\n for (const subscriptionId in subscriptions) {\r\n if (subscriptionId) {\r\n subscriptions[subscriptionId]();\r\n }\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { EventType, PlatformEvent } from \"./PlatformEvent\";\r\n\r\nexport class OCSPEvent extends PlatformEvent {\r\n private privSignature: string;\r\n\r\n constructor(eventName: string, eventType: EventType, signature: string) {\r\n super(eventName, eventType);\r\n\r\n this.privSignature = signature;\r\n }\r\n}\r\n\r\nexport class OCSPMemoryCacheHitEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPMemoryCacheHitEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPCacheMissEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPCacheMissEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPDiskCacheHitEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPDiskCacheHitEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPCacheUpdateNeededEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPCacheUpdateNeededEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPMemoryCacheStoreEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPMemoryCacheStoreEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPDiskCacheStoreEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPDiskCacheStoreEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPCacheUpdatehCompleteEvent extends OCSPEvent {\r\n constructor(signature: string) {\r\n super(\"OCSPCacheUpdatehCompleteEvent\", EventType.Debug, signature);\r\n }\r\n}\r\n\r\nexport class OCSPStapleReceivedEvent extends OCSPEvent {\r\n constructor() {\r\n super(\"OCSPStapleReceivedEvent\", EventType.Debug, \"\");\r\n }\r\n}\r\n\r\nexport class OCSPWSUpgradeStartedEvent extends OCSPEvent {\r\n constructor(serialNumber: string) {\r\n super(\"OCSPWSUpgradeStartedEvent\", EventType.Debug, serialNumber);\r\n }\r\n}\r\n\r\nexport class OCSPCacheEntryExpiredEvent extends OCSPEvent {\r\n private privExpireTime: number;\r\n\r\n constructor(serialNumber: string, expireTime: number) {\r\n super(\"OCSPCacheEntryExpiredEvent\", EventType.Debug, serialNumber);\r\n this.privExpireTime = expireTime;\r\n }\r\n}\r\n\r\nexport class OCSPCacheEntryNeedsRefreshEvent extends OCSPEvent {\r\n private privExpireTime: number;\r\n private privStartTime: number;\r\n\r\n constructor(serialNumber: string, startTime: number, expireTime: number) {\r\n super(\"OCSPCacheEntryNeedsRefreshEvent\", EventType.Debug, serialNumber);\r\n this.privExpireTime = expireTime;\r\n this.privStartTime = startTime;\r\n }\r\n}\r\n\r\nexport class OCSPCacheHitEvent extends OCSPEvent {\r\n private privExpireTime: number;\r\n private privStartTime: number;\r\n private privExpireTimeString: string;\r\n private privStartTimeString: string;\r\n\r\n constructor(serialNumber: string, startTime: number, expireTime: number) {\r\n super(\"OCSPCacheHitEvent\", EventType.Debug, serialNumber);\r\n this.privExpireTime = expireTime;\r\n this.privExpireTimeString = new Date(expireTime).toLocaleDateString();\r\n this.privStartTime = startTime;\r\n this.privStartTimeString = new Date(startTime).toLocaleTimeString();\r\n }\r\n}\r\n\r\nexport class OCSPVerificationFailedEvent extends OCSPEvent {\r\n private privError: string;\r\n\r\n constructor(serialNumber: string, error: string) {\r\n super(\"OCSPVerificationFailedEvent\", EventType.Debug, serialNumber);\r\n this.privError = error;\r\n }\r\n}\r\n\r\nexport class OCSPCacheFetchErrorEvent extends OCSPEvent {\r\n private privError: string;\r\n\r\n constructor(serialNumber: string, error: string) {\r\n super(\"OCSPCacheFetchErrorEvent\", EventType.Debug, serialNumber);\r\n this.privError = error;\r\n }\r\n}\r\n\r\nexport class OCSPResponseRetrievedEvent extends OCSPEvent {\r\n constructor(serialNumber: string) {\r\n super(\"OCSPResponseRetrievedEvent\", EventType.Debug, serialNumber);\r\n }\r\n}\r\n\r\nexport class OCSPCacheUpdateErrorEvent extends OCSPEvent {\r\n private privError: string;\r\n\r\n constructor(serialNumber: string, error: string) {\r\n super(\"OCSPCacheUpdateErrorEvent\", EventType.Debug, serialNumber);\r\n this.privError = error;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { createNoDashGuid } from \"./Guid\";\r\nimport { IStringDictionary } from \"./IDictionary\";\r\n\r\nexport enum EventType {\r\n Debug,\r\n Info,\r\n Warning,\r\n Error,\r\n}\r\n\r\nexport class PlatformEvent {\r\n private privName: string;\r\n private privEventId: string;\r\n private privEventTime: string;\r\n private privEventType: EventType;\r\n private privMetadata: IStringDictionary;\r\n\r\n constructor(eventName: string, eventType: EventType) {\r\n this.privName = eventName;\r\n this.privEventId = createNoDashGuid();\r\n this.privEventTime = new Date().toISOString();\r\n this.privEventType = eventType;\r\n this.privMetadata = { };\r\n }\r\n\r\n public get name(): string {\r\n return this.privName;\r\n }\r\n\r\n public get eventId(): string {\r\n return this.privEventId;\r\n }\r\n\r\n public get eventTime(): string {\r\n return this.privEventTime;\r\n }\r\n\r\n public get eventType(): EventType {\r\n return this.privEventType;\r\n }\r\n\r\n public get metadata(): IStringDictionary {\r\n return this.privMetadata;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { ArgumentNullError } from \"./Error\";\r\n\r\nexport enum PromiseState {\r\n None,\r\n Resolved,\r\n Rejected,\r\n}\r\n\r\nexport interface IDeferred {\r\n readonly promise: Promise;\r\n\r\n resolve(result: T): IDeferred;\r\n\r\n reject(error: string): IDeferred;\r\n}\r\n\r\nexport class PromiseResult {\r\n protected privIsCompleted: boolean;\r\n protected privIsError: boolean;\r\n protected privError: string;\r\n protected privResult: T;\r\n\r\n public constructor(promiseResultEventSource: PromiseResultEventSource) {\r\n promiseResultEventSource.on((result: T) => {\r\n if (!this.privIsCompleted) {\r\n this.privIsCompleted = true;\r\n this.privIsError = false;\r\n this.privResult = result;\r\n }\r\n }, (error: string) => {\r\n if (!this.privIsCompleted) {\r\n this.privIsCompleted = true;\r\n this.privIsError = true;\r\n this.privError = error;\r\n }\r\n });\r\n }\r\n\r\n public get isCompleted(): boolean {\r\n return this.privIsCompleted;\r\n }\r\n\r\n public get isError(): boolean {\r\n return this.privIsError;\r\n }\r\n\r\n public get error(): string {\r\n return this.privError;\r\n }\r\n\r\n public get result(): T {\r\n return this.privResult;\r\n }\r\n\r\n public throwIfError = (): void => {\r\n if (this.isError) {\r\n throw this.error;\r\n }\r\n }\r\n}\r\n\r\nexport class PromiseResultEventSource {\r\n\r\n private privOnSetResult: (result: T) => void;\r\n private privOnSetError: (error: string) => void;\r\n\r\n public setResult = (result: T): void => {\r\n this.privOnSetResult(result);\r\n }\r\n\r\n public setError = (error: string): void => {\r\n this.privOnSetError(error);\r\n }\r\n\r\n public on = (onSetResult: (result: T) => void, onSetError: (error: string) => void): void => {\r\n this.privOnSetResult = onSetResult;\r\n this.privOnSetError = onSetError;\r\n }\r\n}\r\n\r\nexport class Deferred implements IDeferred {\r\n private privPromise: Promise;\r\n private privResolve: (value?: T | PromiseLike) => void;\r\n private privReject: (reason?: any) => void;\r\n\r\n public constructor() {\r\n this.privPromise = new Promise((resolve: (value: T) => void, reject: (reason: any) => void) => {\r\n this.privResolve = resolve;\r\n this.privReject = reject;\r\n });\r\n }\r\n\r\n public get promise(): Promise {\r\n return this.privPromise;\r\n }\r\n\r\n public resolve = (result: T | Promise): Deferred => {\r\n this.privResolve(result);\r\n return this;\r\n }\r\n\r\n public reject = (error: string): Deferred => {\r\n this.privReject(error);\r\n return this;\r\n }\r\n}\r\n\r\nexport class Sink {\r\n private privState: PromiseState = PromiseState.None;\r\n private privPromiseResult: PromiseResult = null;\r\n private privPromiseResultEvents: PromiseResultEventSource = null;\r\n\r\n private privSuccessHandlers: ((result: T) => void)[] = [];\r\n private privErrorHandlers: ((e: string) => void)[] = [];\r\n\r\n public constructor() {\r\n this.privPromiseResultEvents = new PromiseResultEventSource();\r\n this.privPromiseResult = new PromiseResult(this.privPromiseResultEvents);\r\n }\r\n\r\n public get state(): PromiseState {\r\n return this.privState;\r\n }\r\n\r\n public get result(): PromiseResult {\r\n return this.privPromiseResult;\r\n }\r\n\r\n public resolve = (result: T): void => {\r\n if (this.privState !== PromiseState.None) {\r\n throw new Error(\"'Cannot resolve a completed promise'\");\r\n }\r\n\r\n this.privState = PromiseState.Resolved;\r\n this.privPromiseResultEvents.setResult(result);\r\n\r\n for (let i = 0; i < this.privSuccessHandlers.length; i++) {\r\n this.executeSuccessCallback(result, this.privSuccessHandlers[i], this.privErrorHandlers[i]);\r\n }\r\n\r\n this.detachHandlers();\r\n }\r\n\r\n public reject = (error: string): void => {\r\n if (this.privState !== PromiseState.None) {\r\n throw new Error(\"'Cannot reject a completed promise'\");\r\n }\r\n\r\n this.privState = PromiseState.Rejected;\r\n this.privPromiseResultEvents.setError(error);\r\n\r\n for (const errorHandler of this.privErrorHandlers) {\r\n this.executeErrorCallback(error, errorHandler);\r\n }\r\n\r\n this.detachHandlers();\r\n }\r\n\r\n public on = (\r\n successCallback: (result: T) => void,\r\n errorCallback: (error: string) => void): void => {\r\n\r\n if (successCallback == null) {\r\n successCallback = (r: T) => { return; };\r\n }\r\n\r\n if (this.privState === PromiseState.None) {\r\n this.privSuccessHandlers.push(successCallback);\r\n this.privErrorHandlers.push(errorCallback);\r\n } else {\r\n if (this.privState === PromiseState.Resolved) {\r\n this.executeSuccessCallback(this.privPromiseResult.result, successCallback, errorCallback);\r\n } else if (this.privState === PromiseState.Rejected) {\r\n this.executeErrorCallback(this.privPromiseResult.error, errorCallback);\r\n }\r\n\r\n this.detachHandlers();\r\n }\r\n }\r\n\r\n private executeSuccessCallback = (result: T, successCallback: (result: T) => void, errorCallback: (error: string) => void): void => {\r\n try {\r\n successCallback(result);\r\n } catch (e) {\r\n this.executeErrorCallback(`'Unhandled callback error: ${e}'`, errorCallback);\r\n }\r\n }\r\n\r\n private executeErrorCallback = (error: string, errorCallback: (error: string) => void): void => {\r\n if (errorCallback) {\r\n try {\r\n errorCallback(error);\r\n } catch (e) {\r\n throw new Error(`'Unhandled callback error: ${e}. InnerError: ${error}'`);\r\n }\r\n } else {\r\n throw new Error(`'Unhandled error: ${error}'`);\r\n }\r\n }\r\n\r\n private detachHandlers = (): void => {\r\n this.privErrorHandlers = [];\r\n this.privSuccessHandlers = [];\r\n }\r\n}\r\n\r\nexport function marshalPromiseToCallbacks(\r\n promise: Promise,\r\n cb?: (value: T) => void,\r\n err?: (error: string) => void): void {\r\n promise.then((val: T): void => {\r\n try {\r\n if (!!cb) {\r\n cb(val);\r\n }\r\n } catch (error) {\r\n if (!!err) {\r\n try {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n /* tslint:disable:no-empty */\r\n } catch (error) { }\r\n }\r\n }\r\n }, (error: any): void => {\r\n if (!!err) {\r\n try {\r\n if (error instanceof Error) {\r\n const typedError: Error = error as Error;\r\n err(typedError.name + \": \" + typedError.message);\r\n } else {\r\n err(error);\r\n }\r\n /* tslint:disable:no-empty */\r\n } catch (error) { }\r\n }\r\n });\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError, ObjectDisposedError } from \"./Error\";\r\nimport { IDetachable } from \"./IDetachable\";\r\nimport { IDisposable } from \"./IDisposable\";\r\nimport { List } from \"./List\";\r\nimport {\r\n Deferred,\r\n} from \"./Promise\";\r\nexport interface IQueue extends IDisposable {\r\n enqueue(item: TItem): void;\r\n enqueueFromPromise(promise: Promise): void;\r\n dequeue(): Promise;\r\n peek(): Promise;\r\n length(): number;\r\n}\r\n\r\nenum SubscriberType {\r\n Dequeue,\r\n Peek,\r\n}\r\n\r\nexport class Queue implements IQueue {\r\n private privPromiseStore: List> = new List>();\r\n private privList: List;\r\n private privDetachables: IDetachable[];\r\n private privSubscribers: List<{ type: SubscriberType, deferral: Deferred }>;\r\n private privIsDrainInProgress: boolean = false;\r\n private privIsDisposing: boolean = false;\r\n private privDisposeReason: string = null;\r\n\r\n public constructor(list?: List) {\r\n this.privList = list ? list : new List();\r\n this.privDetachables = [];\r\n this.privSubscribers = new List<{ type: SubscriberType, deferral: Deferred }>();\r\n this.privDetachables.push(this.privList.onAdded(this.drain));\r\n }\r\n\r\n public enqueue = (item: TItem): void => {\r\n this.throwIfDispose();\r\n this.enqueueFromPromise(new Promise((resolve: (value: TItem) => void, reject: (reason: any) => void) => { resolve(item); }));\r\n }\r\n\r\n public enqueueFromPromise = (promise: Promise): void => {\r\n this.throwIfDispose();\r\n promise.then((val: TItem): void => {\r\n this.privList.add(val);\r\n /* tslint:disable:no-empty */\r\n }, (error: string): void => { });\r\n }\r\n\r\n public dequeue = (): Promise => {\r\n this.throwIfDispose();\r\n const deferredSubscriber = new Deferred();\r\n\r\n if (this.privSubscribers) {\r\n this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Dequeue });\r\n this.drain();\r\n }\r\n\r\n return deferredSubscriber.promise;\r\n }\r\n\r\n public peek = (): Promise => {\r\n this.throwIfDispose();\r\n const deferredSubscriber = new Deferred();\r\n\r\n const subs = this.privSubscribers;\r\n if (subs) {\r\n this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Peek });\r\n this.drain();\r\n }\r\n\r\n return deferredSubscriber.promise;\r\n }\r\n\r\n public length = (): number => {\r\n this.throwIfDispose();\r\n return this.privList.length();\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privSubscribers == null;\r\n }\r\n\r\n public async drainAndDispose(pendingItemProcessor: (pendingItemInQueue: TItem) => void, reason?: string): Promise {\r\n if (!this.isDisposed() && !this.privIsDisposing) {\r\n this.privDisposeReason = reason;\r\n this.privIsDisposing = true;\r\n\r\n const subs = this.privSubscribers;\r\n if (subs) {\r\n while (subs.length() > 0) {\r\n const subscriber = subs.removeFirst();\r\n // TODO: this needs work (Resolve(null) instead?).\r\n subscriber.deferral.resolve(undefined);\r\n // subscriber.deferral.reject(\"Disposed\");\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privSubscribers === subs) {\r\n this.privSubscribers = subs;\r\n }\r\n }\r\n\r\n for (const detachable of this.privDetachables) {\r\n await detachable.detach();\r\n }\r\n\r\n if (this.privPromiseStore.length() > 0 && pendingItemProcessor) {\r\n const promiseArray: Promise[] = [];\r\n\r\n this.privPromiseStore.toArray().forEach((wrapper: Promise) => {\r\n promiseArray.push(wrapper);\r\n });\r\n return Promise.all(promiseArray).finally(() => {\r\n this.privSubscribers = null;\r\n this.privList.forEach((item: TItem, index: number): void => {\r\n pendingItemProcessor(item);\r\n });\r\n this.privList = null;\r\n return;\r\n }).then();\r\n } else {\r\n this.privSubscribers = null;\r\n this.privList = null;\r\n }\r\n }\r\n }\r\n\r\n public async dispose(reason?: string): Promise {\r\n await this.drainAndDispose(null, reason);\r\n }\r\n\r\n private drain = (): void => {\r\n if (!this.privIsDrainInProgress && !this.privIsDisposing) {\r\n this.privIsDrainInProgress = true;\r\n\r\n const subs = this.privSubscribers;\r\n const lists = this.privList;\r\n if (subs && lists) {\r\n while (lists.length() > 0 && subs.length() > 0 && !this.privIsDisposing) {\r\n const subscriber = subs.removeFirst();\r\n if (subscriber.type === SubscriberType.Peek) {\r\n subscriber.deferral.resolve(lists.first());\r\n } else {\r\n const dequeuedItem = lists.removeFirst();\r\n subscriber.deferral.resolve(dequeuedItem);\r\n }\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privSubscribers === subs) {\r\n this.privSubscribers = subs;\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privList === lists) {\r\n this.privList = lists;\r\n }\r\n }\r\n\r\n this.privIsDrainInProgress = false;\r\n }\r\n }\r\n\r\n private throwIfDispose = (): void => {\r\n if (this.isDisposed()) {\r\n if (this.privDisposeReason) {\r\n throw new InvalidOperationError(this.privDisposeReason);\r\n }\r\n\r\n throw new ObjectDisposedError(\"Queue\");\r\n } else if (this.privIsDisposing) {\r\n throw new InvalidOperationError(\"Queue disposing\");\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { MessageType } from \"./ConnectionMessage\";\r\nimport { ArgumentNullError, InvalidOperationError } from \"./Error\";\r\nimport { createNoDashGuid } from \"./Guid\";\r\n\r\nexport class RawWebsocketMessage {\r\n private privMessageType: MessageType;\r\n private privPayload: any = null;\r\n private privId: string;\r\n\r\n public constructor(messageType: MessageType, payload: any, id?: string) {\r\n if (!payload) {\r\n throw new ArgumentNullError(\"payload\");\r\n }\r\n\r\n if (messageType === MessageType.Binary && payload.__proto__.constructor.name !== \"ArrayBuffer\") {\r\n throw new InvalidOperationError(\"Payload must be ArrayBuffer\");\r\n }\r\n\r\n if (messageType === MessageType.Text && !(typeof (payload) === \"string\")) {\r\n throw new InvalidOperationError(\"Payload must be a string\");\r\n }\r\n\r\n this.privMessageType = messageType;\r\n this.privPayload = payload;\r\n this.privId = id ? id : createNoDashGuid();\r\n }\r\n\r\n public get messageType(): MessageType {\r\n return this.privMessageType;\r\n }\r\n\r\n public get payload(): any {\r\n return this.privPayload;\r\n }\r\n\r\n public get textContent(): string {\r\n if (this.privMessageType === MessageType.Binary) {\r\n throw new InvalidOperationError(\"Not supported for binary message\");\r\n }\r\n\r\n return this.privPayload as string;\r\n }\r\n\r\n public get binaryContent(): ArrayBuffer {\r\n if (this.privMessageType === MessageType.Text) {\r\n throw new InvalidOperationError(\"Not supported for text message\");\r\n }\r\n\r\n return this.privPayload;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport class RiffPcmEncoder {\r\n\r\n private privActualSampleRate: number;\r\n private privDesiredSampleRate: number;\r\n\r\n public constructor(actualSampleRate: number, desiredSampleRate: number) {\r\n this.privActualSampleRate = actualSampleRate;\r\n this.privDesiredSampleRate = desiredSampleRate;\r\n }\r\n\r\n public encode = (\r\n actualAudioFrame: Float32Array): ArrayBuffer => {\r\n\r\n const audioFrame = this.downSampleAudioFrame(actualAudioFrame, this.privActualSampleRate, this.privDesiredSampleRate);\r\n\r\n if (!audioFrame) {\r\n return null;\r\n }\r\n\r\n const audioLength = audioFrame.length * 2;\r\n\r\n const buffer = new ArrayBuffer(audioLength);\r\n const view = new DataView(buffer);\r\n this.floatTo16BitPCM(view, 0, audioFrame);\r\n\r\n return buffer;\r\n }\r\n\r\n private setString = (view: DataView, offset: number, str: string): void => {\r\n for (let i = 0; i < str.length; i++) {\r\n view.setUint8(offset + i, str.charCodeAt(i));\r\n }\r\n }\r\n\r\n private floatTo16BitPCM = (view: DataView, offset: number, input: Float32Array): void => {\r\n for (let i = 0; i < input.length; i++ , offset += 2) {\r\n const s = Math.max(-1, Math.min(1, input[i]));\r\n view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);\r\n }\r\n }\r\n\r\n private downSampleAudioFrame = (\r\n srcFrame: Float32Array,\r\n srcRate: number,\r\n dstRate: number): Float32Array => {\r\n\r\n if (dstRate === srcRate || dstRate > srcRate) {\r\n return srcFrame;\r\n }\r\n\r\n const ratio = srcRate / dstRate;\r\n const dstLength = Math.round(srcFrame.length / ratio);\r\n const dstFrame = new Float32Array(dstLength);\r\n let srcOffset = 0;\r\n let dstOffset = 0;\r\n while (dstOffset < dstLength) {\r\n const nextSrcOffset = Math.round((dstOffset + 1) * ratio);\r\n let accum = 0;\r\n let count = 0;\r\n while (srcOffset < nextSrcOffset && srcOffset < srcFrame.length) {\r\n accum += srcFrame[srcOffset++];\r\n count++;\r\n }\r\n dstFrame[dstOffset++] = accum / count;\r\n }\r\n\r\n return dstFrame;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError } from \"./Error\";\r\nimport { createNoDashGuid } from \"./Guid\";\r\nimport { Queue } from \"./Queue\";\r\n\r\nexport interface IStreamChunk {\r\n isEnd: boolean;\r\n buffer: TBuffer;\r\n timeReceived: number;\r\n}\r\n\r\nexport class Stream {\r\n private privId: string;\r\n private privIsWriteEnded: boolean = false;\r\n private privIsReadEnded: boolean = false;\r\n private privReaderQueue: Queue>;\r\n\r\n public constructor(streamId?: string) {\r\n this.privId = streamId ? streamId : createNoDashGuid();\r\n this.privReaderQueue = new Queue>();\r\n }\r\n\r\n public get isClosed(): boolean {\r\n return this.privIsWriteEnded;\r\n }\r\n\r\n public get isReadEnded(): boolean {\r\n return this.privIsReadEnded;\r\n }\r\n\r\n public get id(): string {\r\n return this.privId;\r\n }\r\n\r\n public close(): void {\r\n if (!this.privIsWriteEnded) {\r\n this.writeStreamChunk({\r\n buffer: null,\r\n isEnd: true,\r\n timeReceived: Date.now(),\r\n });\r\n this.privIsWriteEnded = true;\r\n }\r\n }\r\n\r\n public writeStreamChunk(streamChunk: IStreamChunk): void {\r\n this.throwIfClosed();\r\n if (!this.privReaderQueue.isDisposed()) {\r\n try {\r\n this.privReaderQueue.enqueue(streamChunk);\r\n } catch (e) {\r\n // Do nothing\r\n }\r\n }\r\n }\r\n\r\n public read = (): Promise> => {\r\n if (this.privIsReadEnded) {\r\n throw new InvalidOperationError(\"Stream read has already finished\");\r\n }\r\n\r\n return this.privReaderQueue\r\n .dequeue()\r\n .then(async (streamChunk: IStreamChunk) => {\r\n if (streamChunk === undefined || streamChunk.isEnd) {\r\n await this.privReaderQueue.dispose(\"End of stream reached\");\r\n }\r\n\r\n return streamChunk;\r\n });\r\n }\r\n public readEnded = (): void => {\r\n if (!this.privIsReadEnded) {\r\n this.privIsReadEnded = true;\r\n this.privReaderQueue = new Queue>();\r\n }\r\n }\r\n\r\n private throwIfClosed = (): void => {\r\n if (this.privIsWriteEnded) {\r\n throw new InvalidOperationError(\"Stream closed\");\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\ntype TWorkerMessage = ICallNotification | IClearResponse | IErrorNotification | IErrorResponse;\r\n\r\ninterface IClearResponse {\r\n error: null;\r\n id: number;\r\n}\r\n\r\ninterface IErrorNotification {\r\n error: {\r\n message: string;\r\n };\r\n id: null;\r\n result: null;\r\n}\r\n\r\ninterface IErrorResponse {\r\n error: {\r\n message: string;\r\n };\r\n id: number;\r\n result: null;\r\n}\r\n\r\ninterface ICallNotification {\r\n id: null;\r\n method: \"call\";\r\n params: {\r\n timerId: number;\r\n };\r\n}\r\n\r\ninterface ISetNotification {\r\n id: null;\r\n method: \"set\";\r\n params: {\r\n delay: number;\r\n now: number;\r\n timerId: number;\r\n };\r\n}\r\n\r\ninterface IClearRequest {\r\n id: number;\r\n method: \"clear\";\r\n params: {\r\n timerId: number;\r\n };\r\n}\r\n\r\ninterface IWorkerEvent extends Event {\r\n data: TWorkerMessage;\r\n}\r\n\r\ninterface IWorkerTimers {\r\n clearTimeout: (timerId: number) => void;\r\n setTimeout: (func: () => any, delay: number) => number;\r\n}\r\n\r\ndeclare type Func = () => any;\r\n\r\nexport class Timeout {\r\n\r\n private static workerTimers: null | IWorkerTimers = null;\r\n\r\n public static clearTimeout: IWorkerTimers[\"clearTimeout\"] = (timerId) => Timeout.timers().clearTimeout(timerId);\r\n\r\n public static setTimeout: IWorkerTimers[\"setTimeout\"] = (func, delay) => Timeout.timers().setTimeout(func, delay);\r\n\r\n public static load = (url: string) => {\r\n // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.\r\n const scheduledTimeoutFunctions: Map = new Map([[0, () => { }]]); // tslint:disable-line no-empty\r\n const unhandledRequests: Map = new Map();\r\n\r\n const worker = new Worker(url);\r\n\r\n worker.addEventListener(\"message\", ({ data }: IWorkerEvent) => {\r\n if (Timeout.isCallNotification(data)) {\r\n const {\r\n params: { timerId }\r\n } = data;\r\n\r\n const idOrFunc = scheduledTimeoutFunctions.get(timerId);\r\n\r\n if (typeof idOrFunc === \"number\") {\r\n const unhandledTimerId = unhandledRequests.get(idOrFunc);\r\n\r\n if (\r\n unhandledTimerId === undefined ||\r\n unhandledTimerId !== timerId\r\n ) {\r\n throw new Error(\"The timer is in an undefined state.\");\r\n }\r\n } else if (typeof idOrFunc !== \"undefined\") {\r\n idOrFunc();\r\n\r\n // A timeout can be safely deleted because it is only called once.\r\n scheduledTimeoutFunctions.delete(timerId);\r\n } else {\r\n throw new Error(\"The timer is in an undefined state.\");\r\n }\r\n } else if (Timeout.isClearResponse(data)) {\r\n const { id } = data;\r\n\r\n const unhandledTimerId = unhandledRequests.get(id);\r\n\r\n if (unhandledTimerId === undefined) {\r\n throw new Error(\"The timer is in an undefined state.\");\r\n }\r\n\r\n unhandledRequests.delete(id);\r\n\r\n scheduledTimeoutFunctions.delete(unhandledTimerId);\r\n } else {\r\n const {\r\n error: { message }\r\n } = data;\r\n\r\n throw new Error(message);\r\n }\r\n });\r\n\r\n const clearTimeout = (timerId: number) => {\r\n const id = Math.random();\r\n\r\n unhandledRequests.set(id, timerId);\r\n scheduledTimeoutFunctions.set(timerId, id);\r\n\r\n worker.postMessage({\r\n id,\r\n method: \"clear\",\r\n params: { timerId }\r\n } as IClearRequest);\r\n };\r\n\r\n const setTimeout = (func: () => void, delay: number) => {\r\n const timerId = Math.random();\r\n\r\n scheduledTimeoutFunctions.set(timerId, func);\r\n\r\n worker.postMessage({\r\n id: null,\r\n method: \"set\",\r\n params: {\r\n delay,\r\n now: performance.now(),\r\n timerId\r\n }\r\n } as ISetNotification);\r\n\r\n return timerId;\r\n };\r\n\r\n return {\r\n clearTimeout,\r\n setTimeout\r\n };\r\n }\r\n\r\n private static loadWorkerTimers = () => {\r\n const 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\r\n return () => {\r\n if (Timeout.workerTimers !== null) {\r\n return Timeout.workerTimers;\r\n }\r\n\r\n const blob = new Blob([worker], { type: \"application/javascript; charset=utf-8\" });\r\n const url = URL.createObjectURL(blob);\r\n\r\n Timeout.workerTimers = Timeout.load(url);\r\n\r\n // Edge doesn't like the URL to be revoked directly.\r\n Timeout.workerTimers.setTimeout(() => URL.revokeObjectURL(url), 0);\r\n\r\n return Timeout.workerTimers as IWorkerTimers;\r\n };\r\n }\r\n\r\n public static timers: () => IWorkerTimers = Timeout.loadWorkerTimers();\r\n\r\n private static isCallNotification = (message: TWorkerMessage): message is ICallNotification => {\r\n return (message as ICallNotification).method !== undefined && (message as ICallNotification).method === \"call\";\r\n }\r\n\r\n private static isClearResponse = (message: TWorkerMessage): message is IClearResponse => {\r\n return (message as IClearResponse).error === null && typeof message.id === \"number\";\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { PullAudioOutputStream } from \"./Audio/AudioOutputStream\";\r\n\r\n/**\r\n * Defines contents of received message/events.\r\n * @class ActivityReceivedEventArgs\r\n */\r\nexport class ActivityReceivedEventArgs {\r\n private privActivity: any;\r\n private privAudioStream: PullAudioOutputStream;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {any} activity - The activity..\r\n */\r\n public constructor(activity: any, audioStream?: PullAudioOutputStream) {\r\n this.privActivity = activity;\r\n this.privAudioStream = audioStream;\r\n }\r\n\r\n /**\r\n * Gets the received activity\r\n * @member ActivityReceivedEventArgs.prototype.activity\r\n * @function\r\n * @public\r\n * @returns {any} the received activity.\r\n */\r\n public get activity(): any {\r\n return this.privActivity;\r\n }\r\n\r\n public get audioStream(): PullAudioOutputStream {\r\n return this.privAudioStream;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport { PathLike } from \"fs\";\r\nimport {\r\n FileAudioSource,\r\n MicAudioSource,\r\n PcmRecorder,\r\n} from \"../../common.browser/Exports\";\r\nimport { ISpeechConfigAudioDevice } from \"../../common.speech/Exports\";\r\nimport {\r\n AudioSourceEvent,\r\n Deferred,\r\n EventSource,\r\n IAudioDestination,\r\n IAudioSource,\r\n IAudioStreamNode\r\n} from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n AudioInputStream,\r\n AudioOutputStream,\r\n AudioStreamFormat,\r\n IPlayer,\r\n PropertyCollection,\r\n PropertyId,\r\n PullAudioInputStreamCallback,\r\n PullAudioOutputStream,\r\n PushAudioOutputStream,\r\n PushAudioOutputStreamCallback,\r\n SpeakerAudioDestination\r\n} from \"../Exports\";\r\nimport { AudioFileWriter } from \"./AudioFileWriter\";\r\nimport { PullAudioInputStreamImpl, PushAudioInputStreamImpl } from \"./AudioInputStream\";\r\nimport { PullAudioOutputStreamImpl, PushAudioOutputStreamImpl } from \"./AudioOutputStream\";\r\nimport { AudioStreamFormatImpl } from \"./AudioStreamFormat\";\r\n\r\n/**\r\n * Represents audio input configuration used for specifying what type of input to use (microphone, file, stream).\r\n * @class AudioConfig\r\n * Updated in version 1.11.0\r\n */\r\nexport abstract class AudioConfig {\r\n /**\r\n * Creates an AudioConfig object representing the default microphone on the system.\r\n * @member AudioConfig.fromDefaultMicrophoneInput\r\n * @function\r\n * @public\r\n * @returns {AudioConfig} The audio input configuration being created.\r\n */\r\n public static fromDefaultMicrophoneInput(): AudioConfig {\r\n const pcmRecorder = new PcmRecorder();\r\n return new AudioConfigImpl(new MicAudioSource(pcmRecorder));\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing a microphone with the specified device ID.\r\n * @member AudioConfig.fromMicrophoneInput\r\n * @function\r\n * @public\r\n * @param {string | undefined} deviceId - Specifies the device ID of the microphone to be used.\r\n * Default microphone is used the value is omitted.\r\n * @returns {AudioConfig} The audio input configuration being created.\r\n */\r\n public static fromMicrophoneInput(deviceId?: string): AudioConfig {\r\n const pcmRecorder = new PcmRecorder();\r\n return new AudioConfigImpl(new MicAudioSource(pcmRecorder, deviceId));\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing the specified file.\r\n * @member AudioConfig.fromWavFileInput\r\n * @function\r\n * @public\r\n * @param {File} fileName - Specifies the audio input file. Currently, only WAV / PCM is supported.\r\n * @returns {AudioConfig} The audio input configuration being created.\r\n */\r\n public static fromWavFileInput(file: File | Buffer, name: string = \"unnamedBuffer.wav\"): AudioConfig {\r\n return new AudioConfigImpl(new FileAudioSource(file, name));\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing the specified stream.\r\n * @member AudioConfig.fromStreamInput\r\n * @function\r\n * @public\r\n * @param {AudioInputStream | PullAudioInputStreamCallback | MediaStream} audioStream - Specifies the custom audio input\r\n * stream. Currently, only WAV / PCM is supported.\r\n * @returns {AudioConfig} The audio input configuration being created.\r\n */\r\n public static fromStreamInput(audioStream: AudioInputStream | PullAudioInputStreamCallback\r\n | MediaStream): AudioConfig {\r\n if (audioStream instanceof PullAudioInputStreamCallback) {\r\n return new AudioConfigImpl(new PullAudioInputStreamImpl(audioStream as PullAudioInputStreamCallback));\r\n }\r\n\r\n if (audioStream instanceof AudioInputStream) {\r\n return new AudioConfigImpl(audioStream as PushAudioInputStreamImpl);\r\n }\r\n if (typeof MediaStream !== \"undefined\" && audioStream instanceof MediaStream) {\r\n const pcmRecorder = new PcmRecorder();\r\n return new AudioConfigImpl(new MicAudioSource(pcmRecorder, null, null, audioStream));\r\n }\r\n\r\n throw new Error(\"Not Supported Type\");\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing the default speaker.\r\n * @member AudioConfig.fromDefaultSpeakerOutput\r\n * @function\r\n * @public\r\n * @returns {AudioConfig} The audio output configuration being created.\r\n * Added in version 1.11.0\r\n */\r\n public static fromDefaultSpeakerOutput(): AudioConfig {\r\n return new AudioOutputConfigImpl(new SpeakerAudioDestination());\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing the custom IPlayer object.\r\n * You can use the IPlayer object to control pause, resume, etc.\r\n * @member AudioConfig.fromSpeakerOutput\r\n * @function\r\n * @public\r\n * @param {IPlayer} player - the IPlayer object for playback.\r\n * @returns {AudioConfig} The audio output configuration being created.\r\n * Added in version 1.12.0\r\n */\r\n public static fromSpeakerOutput(player?: IPlayer): AudioConfig {\r\n if (player === undefined) {\r\n return AudioConfig.fromDefaultSpeakerOutput();\r\n }\r\n if (player instanceof SpeakerAudioDestination) {\r\n return new AudioOutputConfigImpl(player as SpeakerAudioDestination);\r\n }\r\n\r\n throw new Error(\"Not Supported Type\");\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing a specified output audio file\r\n * @member AudioConfig.fromAudioFileOutput\r\n * @function\r\n * @public\r\n * @param {PathLike} filename - the filename of the output audio file\r\n * @returns {AudioConfig} The audio output configuration being created.\r\n * Added in version 1.11.0\r\n */\r\n public static fromAudioFileOutput(filename: PathLike): AudioConfig {\r\n return new AudioOutputConfigImpl(new AudioFileWriter(filename));\r\n }\r\n\r\n /**\r\n * Creates an AudioConfig object representing a specified audio output stream\r\n * @member AudioConfig.fromStreamOutput\r\n * @function\r\n * @public\r\n * @param {AudioOutputStream | PushAudioOutputStreamCallback} audioStream - Specifies the custom audio output\r\n * stream.\r\n * @returns {AudioConfig} The audio output configuration being created.\r\n * Added in version 1.11.0\r\n */\r\n public static fromStreamOutput(audioStream: AudioOutputStream | PushAudioOutputStreamCallback): AudioConfig {\r\n if (audioStream instanceof PushAudioOutputStreamCallback) {\r\n return new AudioOutputConfigImpl(new PushAudioOutputStreamImpl(audioStream as PushAudioOutputStreamCallback));\r\n }\r\n\r\n if (audioStream instanceof PushAudioOutputStream) {\r\n return new AudioOutputConfigImpl(audioStream as PushAudioOutputStreamImpl);\r\n }\r\n\r\n if (audioStream instanceof PullAudioOutputStream) {\r\n return new AudioOutputConfigImpl(audioStream as PullAudioOutputStreamImpl);\r\n }\r\n\r\n throw new Error(\"Not Supported Type\");\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioConfig.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n\r\n /**\r\n * Sets an arbitrary property.\r\n * @member SpeechConfig.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to set.\r\n * @param {string} value - The new value of the property.\r\n */\r\n public abstract setProperty(name: string, value: string): void;\r\n\r\n /**\r\n * Returns the current value of an arbitrary property.\r\n * @member SpeechConfig.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to query.\r\n * @param {string} def - The value to return in case the property is not known.\r\n * @returns {string} The current value, or provided default, of the given property.\r\n */\r\n public abstract getProperty(name: string, def?: string): string;\r\n\r\n}\r\n\r\n/**\r\n * Represents audio input stream used for custom audio input configurations.\r\n * @private\r\n * @class AudioConfigImpl\r\n */\r\nexport class AudioConfigImpl extends AudioConfig implements IAudioSource {\r\n private privSource: IAudioSource;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {IAudioSource} source - An audio source.\r\n */\r\n public constructor(source: IAudioSource) {\r\n super();\r\n this.privSource = source;\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): Promise {\r\n return this.privSource.format;\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, err?: (error: string) => void): void {\r\n this.privSource.turnOff().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string) => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.id\r\n * @function\r\n * @public\r\n */\r\n public id(): string {\r\n return this.privSource.id();\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.blob\r\n * @function\r\n * @public\r\n */\r\n public get blob(): Promise {\r\n return this.privSource.blob;\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.turnOn\r\n * @function\r\n * @public\r\n * @returns {Promise} A promise.\r\n */\r\n public turnOn(): Promise {\r\n return this.privSource.turnOn();\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.attach\r\n * @function\r\n * @public\r\n * @param {string} audioNodeId - The audio node id.\r\n * @returns {Promise} A promise.\r\n */\r\n public attach(audioNodeId: string): Promise {\r\n return this.privSource.attach(audioNodeId);\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.detach\r\n * @function\r\n * @public\r\n * @param {string} audioNodeId - The audio node id.\r\n */\r\n public detach(audioNodeId: string): void {\r\n return this.privSource.detach(audioNodeId);\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.turnOff\r\n * @function\r\n * @public\r\n * @returns {Promise} A promise.\r\n */\r\n public turnOff(): Promise {\r\n return this.privSource.turnOff();\r\n }\r\n\r\n /**\r\n * @member AudioConfigImpl.prototype.events\r\n * @function\r\n * @public\r\n * @returns {EventSource} An event source for audio events.\r\n */\r\n public get events(): EventSource {\r\n return this.privSource.events;\r\n }\r\n\r\n public setProperty(name: string, value: string): void {\r\n Contracts.throwIfNull(value, \"value\");\r\n\r\n if (undefined !== this.privSource.setProperty) {\r\n this.privSource.setProperty(name, value);\r\n } else {\r\n throw new Error(\"This AudioConfig instance does not support setting properties.\");\r\n }\r\n\r\n }\r\n\r\n public getProperty(name: string, def?: string): string {\r\n if (undefined !== this.privSource.getProperty) {\r\n return this.privSource.getProperty(name, def);\r\n } else {\r\n throw new Error(\"This AudioConfig instance does not support getting properties.\");\r\n }\r\n\r\n return def;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return this.privSource.deviceInfo;\r\n }\r\n}\r\n\r\nexport class AudioOutputConfigImpl extends AudioConfig implements IAudioDestination {\r\n private privDestination: IAudioDestination;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {IAudioDestination} destination - An audio destination.\r\n */\r\n public constructor(destination: IAudioDestination) {\r\n super();\r\n this.privDestination = destination;\r\n }\r\n\r\n public set format(format: AudioStreamFormat) {\r\n this.privDestination.format = format;\r\n }\r\n\r\n public write(buffer: ArrayBuffer): void {\r\n this.privDestination.write(buffer);\r\n }\r\n\r\n public close(): void {\r\n this.privDestination.close();\r\n }\r\n\r\n public id(): string {\r\n return this.privDestination.id();\r\n }\r\n\r\n public setProperty(name: string, value: string): void {\r\n throw new Error(\"This AudioConfig instance does not support setting properties.\");\r\n }\r\n\r\n public getProperty(name: string, def?: string): string {\r\n throw new Error(\"This AudioConfig instance does not support getting properties.\");\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport * as fs from \"fs\";\r\nimport { IAudioDestination } from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport { AudioStreamFormat } from \"../Exports\";\r\nimport { AudioOutputFormatImpl } from \"./AudioOutputFormat\";\r\n\r\nexport class AudioFileWriter implements IAudioDestination {\r\n private privAudioFormat: AudioOutputFormatImpl;\r\n private privFd: number;\r\n private privId: string;\r\n private privWriteStream: fs.WriteStream;\r\n\r\n public constructor(filename: fs.PathLike) {\r\n Contracts.throwIfNullOrUndefined(fs.openSync, \"\\nFile System access not available, please use Push or PullAudioOutputStream\");\r\n this.privFd = fs.openSync(filename, \"w\");\r\n }\r\n\r\n public set format(format: AudioStreamFormat) {\r\n Contracts.throwIfNotUndefined(this.privAudioFormat, \"format is already set\");\r\n this.privAudioFormat = format as AudioOutputFormatImpl;\r\n let headerOffset: number = 0;\r\n if (this.privAudioFormat.hasHeader) {\r\n headerOffset = this.privAudioFormat.header.byteLength;\r\n }\r\n if (this.privFd !== undefined) {\r\n this.privWriteStream = fs.createWriteStream(\"\", {fd: this.privFd, start: headerOffset, autoClose: false});\r\n }\r\n }\r\n\r\n public write(buffer: ArrayBuffer): void {\r\n Contracts.throwIfNullOrUndefined(this.privAudioFormat, \"must set format before writing.\");\r\n if (this.privWriteStream !== undefined) {\r\n this.privWriteStream.write(new Uint8Array(buffer.slice(0)));\r\n }\r\n }\r\n\r\n public close(): void {\r\n if (this.privFd !== undefined) {\r\n this.privWriteStream.on(\"finish\", () => {\r\n if (this.privAudioFormat.hasHeader) {\r\n this.privAudioFormat.updateHeader(this.privWriteStream.bytesWritten);\r\n fs.writeSync(this.privFd,\r\n new Int8Array(this.privAudioFormat.header),\r\n 0,\r\n this.privAudioFormat.header.byteLength,\r\n 0);\r\n }\r\n fs.closeSync(this.privFd);\r\n this.privFd = undefined;\r\n });\r\n this.privWriteStream.end();\r\n }\r\n }\r\n\r\n public id = (): string => {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n connectivity,\r\n ISpeechConfigAudioDevice,\r\n type,\r\n} from \"../../common.speech/Exports\";\r\nimport {\r\n AudioSourceEvent,\r\n AudioSourceInitializingEvent,\r\n AudioSourceReadyEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n ChunkedArrayBufferStream,\r\n Deferred,\r\n Events,\r\n EventSource,\r\n IAudioSource,\r\n IAudioStreamNode,\r\n IStreamChunk,\r\n Stream,\r\n} from \"../../common/Exports\";\r\nimport { createNoDashGuid } from \"../../common/Guid\";\r\nimport { AudioStreamFormat, PullAudioInputStreamCallback } from \"../Exports\";\r\nimport { AudioStreamFormatImpl } from \"./AudioStreamFormat\";\r\n\r\n/**\r\n * Represents audio input stream used for custom audio input configurations.\r\n * @class AudioInputStream\r\n */\r\nexport abstract class AudioInputStream {\r\n\r\n /**\r\n * Creates and initializes an instance.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Creates a memory backed PushAudioInputStream with the specified audio format.\r\n * @member AudioInputStream.createPushStream\r\n * @function\r\n * @public\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be\r\n * written to the push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM).\r\n * @returns {PushAudioInputStream} The audio input stream being created.\r\n */\r\n public static createPushStream(format?: AudioStreamFormat): PushAudioInputStream {\r\n return PushAudioInputStream.create(format);\r\n }\r\n\r\n /**\r\n * Creates a PullAudioInputStream that delegates to the specified callback interface for read()\r\n * and close() methods.\r\n * @member AudioInputStream.createPullStream\r\n * @function\r\n * @public\r\n * @param {PullAudioInputStreamCallback} callback - The custom audio input object, derived from\r\n * PullAudioInputStreamCallback\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be returned from\r\n * the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).\r\n * @returns {PullAudioInputStream} The audio input stream being created.\r\n */\r\n public static createPullStream(callback: PullAudioInputStreamCallback, format?: AudioStreamFormat): PullAudioInputStream {\r\n return PullAudioInputStream.create(callback, format);\r\n // throw new Error(\"Oops\");\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioInputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio input stream used for custom audio input configurations.\r\n * @class PushAudioInputStream\r\n */\r\nexport abstract class PushAudioInputStream extends AudioInputStream {\r\n\r\n /**\r\n * Creates a memory backed PushAudioInputStream with the specified audio format.\r\n * @member PushAudioInputStream.create\r\n * @function\r\n * @public\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be written to the\r\n * push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM).\r\n * @returns {PushAudioInputStream} The push audio input stream being created.\r\n */\r\n public static create(format?: AudioStreamFormat): PushAudioInputStream {\r\n return new PushAudioInputStreamImpl(format);\r\n }\r\n\r\n /**\r\n * Writes the audio data specified by making an internal copy of the data.\r\n * @member PushAudioInputStream.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.\r\n */\r\n public abstract write(dataBuffer: ArrayBuffer): void;\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PushAudioInputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio input stream used for custom audio input configurations.\r\n * @private\r\n * @class PushAudioInputStreamImpl\r\n */\r\nexport class PushAudioInputStreamImpl extends PushAudioInputStream implements IAudioSource {\r\n\r\n private privFormat: AudioStreamFormatImpl;\r\n private privId: string;\r\n private privEvents: EventSource;\r\n private privStream: Stream;\r\n\r\n /**\r\n * Creates and initalizes an instance with the given values.\r\n * @constructor\r\n * @param {AudioStreamFormat} format - The audio stream format.\r\n */\r\n public constructor(format?: AudioStreamFormat) {\r\n super();\r\n if (format === undefined) {\r\n this.privFormat = AudioStreamFormatImpl.getDefaultInputFormat();\r\n } else {\r\n this.privFormat = format as AudioStreamFormatImpl;\r\n }\r\n this.privEvents = new EventSource();\r\n this.privId = createNoDashGuid();\r\n this.privStream = new ChunkedArrayBufferStream(this.privFormat.avgBytesPerSec / 10);\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): Promise {\r\n return Promise.resolve(this.privFormat);\r\n }\r\n\r\n /**\r\n * Writes the audio data specified by making an internal copy of the data.\r\n * @member PushAudioInputStreamImpl.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.\r\n */\r\n public write(dataBuffer: ArrayBuffer): void {\r\n this.privStream.writeStreamChunk({\r\n buffer: dataBuffer,\r\n isEnd: false,\r\n timeReceived: Date.now()\r\n });\r\n }\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PushAudioInputStreamImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n this.privStream.close();\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n public get blob(): Promise {\r\n return this.attach(\"id\").then((audioNode: IAudioStreamNode) => {\r\n const data: ArrayBuffer[] = [];\r\n let bufferData = Buffer.from(\"\");\r\n const readCycle = (): Promise => {\r\n return audioNode.read().then((audioStreamChunk: IStreamChunk) => {\r\n if (!audioStreamChunk || audioStreamChunk.isEnd) {\r\n if (typeof (XMLHttpRequest) !== \"undefined\" && typeof (Blob) !== \"undefined\") {\r\n return Promise.resolve(new Blob(data));\r\n } else {\r\n return Promise.resolve(Buffer.from(bufferData));\r\n }\r\n } else {\r\n if (typeof (Blob) !== \"undefined\") {\r\n data.push(audioStreamChunk.buffer);\r\n } else {\r\n bufferData = Buffer.concat([bufferData, this.toBuffer(audioStreamChunk.buffer)]);\r\n }\r\n return readCycle();\r\n }\r\n });\r\n };\r\n return readCycle();\r\n });\r\n }\r\n\r\n public turnOn(): Promise {\r\n this.onEvent(new AudioSourceInitializingEvent(this.privId)); // no stream id\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n return;\r\n }\r\n\r\n public async attach(audioNodeId: string): Promise {\r\n this.onEvent(new AudioStreamNodeAttachingEvent(this.privId, audioNodeId));\r\n\r\n await this.turnOn();\r\n const stream = this.privStream;\r\n this.onEvent(new AudioStreamNodeAttachedEvent(this.privId, audioNodeId));\r\n return {\r\n detach: async () => {\r\n stream.readEnded();\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n return this.turnOff();\r\n },\r\n id: () => {\r\n return audioNodeId;\r\n },\r\n read: () => {\r\n return stream.read();\r\n },\r\n };\r\n }\r\n\r\n public detach(audioNodeId: string): void {\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n }\r\n\r\n public turnOff(): Promise {\r\n return;\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privEvents;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return Promise.resolve({\r\n bitspersample: this.privFormat.bitsPerSample,\r\n channelcount: this.privFormat.channels,\r\n connectivity: connectivity.Unknown,\r\n manufacturer: \"Speech SDK\",\r\n model: \"PushStream\",\r\n samplerate: this.privFormat.samplesPerSec,\r\n type: type.Stream,\r\n });\r\n }\r\n\r\n private onEvent = (event: AudioSourceEvent): void => {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n\r\n private toBuffer(arrayBuffer: ArrayBuffer): Buffer {\r\n const buf: Buffer = Buffer.alloc(arrayBuffer.byteLength);\r\n const view: Uint8Array = new Uint8Array(arrayBuffer);\r\n for (let i = 0; i < buf.length; ++i) {\r\n buf[i] = view[i];\r\n }\r\n return buf;\r\n }\r\n}\r\n\r\n/*\r\n * Represents audio input stream used for custom audio input configurations.\r\n * @class PullAudioInputStream\r\n */\r\nexport abstract class PullAudioInputStream extends AudioInputStream {\r\n /**\r\n * Creates and initializes and instance.\r\n * @constructor\r\n */\r\n protected constructor() { super(); }\r\n\r\n /**\r\n * Creates a PullAudioInputStream that delegates to the specified callback interface for\r\n * read() and close() methods, using the default format (16 kHz 16bit mono PCM).\r\n * @member PullAudioInputStream.create\r\n * @function\r\n * @public\r\n * @param {PullAudioInputStreamCallback} callback - The custom audio input object,\r\n * derived from PullAudioInputStreamCustomCallback\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be\r\n * returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).\r\n * @returns {PullAudioInputStream} The push audio input stream being created.\r\n */\r\n public static create(callback: PullAudioInputStreamCallback, format?: AudioStreamFormat): PullAudioInputStream {\r\n return new PullAudioInputStreamImpl(callback, format as AudioStreamFormatImpl);\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member PullAudioInputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n\r\n}\r\n\r\n/**\r\n * Represents audio input stream used for custom audio input configurations.\r\n * @private\r\n * @class PullAudioInputStreamImpl\r\n */\r\nexport class PullAudioInputStreamImpl extends PullAudioInputStream implements IAudioSource {\r\n\r\n private privCallback: PullAudioInputStreamCallback;\r\n private privFormat: AudioStreamFormatImpl;\r\n private privId: string;\r\n private privEvents: EventSource;\r\n private privIsClosed: boolean;\r\n private privBufferSize: number;\r\n\r\n /**\r\n * Creates a PullAudioInputStream that delegates to the specified callback interface for\r\n * read() and close() methods, using the default format (16 kHz 16bit mono PCM).\r\n * @constructor\r\n * @param {PullAudioInputStreamCallback} callback - The custom audio input object,\r\n * derived from PullAudioInputStreamCustomCallback\r\n * @param {AudioStreamFormat} format - The audio data format in which audio will be\r\n * returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).\r\n */\r\n public constructor(callback: PullAudioInputStreamCallback, format?: AudioStreamFormatImpl) {\r\n super();\r\n if (undefined === format) {\r\n this.privFormat = AudioStreamFormat.getDefaultInputFormat() as AudioStreamFormatImpl;\r\n } else {\r\n this.privFormat = format;\r\n }\r\n this.privEvents = new EventSource();\r\n this.privId = createNoDashGuid();\r\n this.privCallback = callback;\r\n this.privIsClosed = false;\r\n this.privBufferSize = this.privFormat.avgBytesPerSec / 10;\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): Promise {\r\n return Promise.resolve(this.privFormat);\r\n }\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioInputStreamImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n this.privIsClosed = true;\r\n this.privCallback.close();\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n public get blob(): Promise {\r\n return Promise.reject(\"Not implemented\");\r\n }\r\n\r\n public turnOn(): Promise {\r\n this.onEvent(new AudioSourceInitializingEvent(this.privId)); // no stream id\r\n this.onEvent(new AudioSourceReadyEvent(this.privId));\r\n return;\r\n }\r\n\r\n public async attach(audioNodeId: string): Promise {\r\n this.onEvent(new AudioStreamNodeAttachingEvent(this.privId, audioNodeId));\r\n\r\n await this.turnOn();\r\n this.onEvent(new AudioStreamNodeAttachedEvent(this.privId, audioNodeId));\r\n return {\r\n detach: () => {\r\n this.privCallback.close();\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n return this.turnOff();\r\n },\r\n id: () => {\r\n return audioNodeId;\r\n },\r\n read: (): Promise> => {\r\n let totalBytes: number = 0;\r\n let transmitBuff: ArrayBuffer;\r\n // Until we have the minimum number of bytes to send in a transmission, keep asking for more.\r\n while (totalBytes < this.privBufferSize) {\r\n // Sizing the read buffer to the delta between the perfect size and what's left means we won't ever get too much\r\n // data back.\r\n const readBuff: ArrayBuffer = new ArrayBuffer(this.privBufferSize - totalBytes);\r\n const pulledBytes: number = this.privCallback.read(readBuff);\r\n // If there is no return buffer yet defined, set the return buffer to the that was just populated.\r\n // This was, if we have enough data there's no copy penalty, but if we don't we have a buffer that's the\r\n // preferred size allocated.\r\n if (undefined === transmitBuff) {\r\n transmitBuff = readBuff;\r\n } else {\r\n // Not the first bite at the apple, so fill the return buffer with the data we got back.\r\n const intView: Int8Array = new Int8Array(transmitBuff);\r\n intView.set(new Int8Array(readBuff), totalBytes);\r\n }\r\n // If there are no bytes to read, just break out and be done.\r\n if (0 === pulledBytes) {\r\n break;\r\n }\r\n totalBytes += pulledBytes;\r\n }\r\n return Promise.resolve>({\r\n buffer: transmitBuff.slice(0, totalBytes),\r\n isEnd: this.privIsClosed || totalBytes === 0,\r\n timeReceived: Date.now(),\r\n });\r\n },\r\n };\r\n }\r\n\r\n public detach(audioNodeId: string): void {\r\n this.onEvent(new AudioStreamNodeDetachedEvent(this.privId, audioNodeId));\r\n }\r\n\r\n public turnOff(): Promise {\r\n return;\r\n }\r\n\r\n public get events(): EventSource {\r\n return this.privEvents;\r\n }\r\n\r\n public get deviceInfo(): Promise {\r\n return Promise.resolve({\r\n bitspersample: this.privFormat.bitsPerSample,\r\n channelcount: this.privFormat.channels,\r\n connectivity: connectivity.Unknown,\r\n manufacturer: \"Speech SDK\",\r\n model: \"PullStream\",\r\n samplerate: this.privFormat.samplesPerSec,\r\n type: type.Stream,\r\n });\r\n }\r\n\r\n private onEvent = (event: AudioSourceEvent): void => {\r\n this.privEvents.onEvent(event);\r\n Events.instance.onEvent(event);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { INumberDictionary } from \"../../common/Exports\";\r\nimport { SpeechSynthesisOutputFormat } from \"../SpeechSynthesisOutputFormat\";\r\nimport { AudioFormatTag, AudioStreamFormatImpl } from \"./AudioStreamFormat\";\r\n\r\n/**\r\n * @private\r\n * @class AudioOutputFormatImpl\r\n * Updated in version 1.17.0\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class AudioOutputFormatImpl extends AudioStreamFormatImpl {\r\n public static SpeechSynthesisOutputFormatToString: INumberDictionary = {\r\n [SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw]: \"raw-8khz-8bit-mono-mulaw\",\r\n [SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren]: \"riff-16khz-16kbps-mono-siren\",\r\n [SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren]: \"audio-16khz-16kbps-mono-siren\",\r\n [SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3]: \"audio-16khz-32kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3]: \"audio-16khz-128kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3]: \"audio-16khz-64kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3]: \"audio-24khz-48kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3]: \"audio-24khz-96kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3]: \"audio-24khz-160kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk]: \"raw-16khz-16bit-mono-truesilk\",\r\n [SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm]: \"riff-16khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm]: \"riff-8khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm]: \"riff-24khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw]: \"riff-8khz-8bit-mono-mulaw\",\r\n [SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm]: \"raw-16khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm]: \"raw-24khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm]: \"raw-8khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus]: \"ogg-16khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus]: \"ogg-24khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm]: \"raw-48khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm]: \"riff-48khz-16bit-mono-pcm\",\r\n [SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3]: \"audio-48khz-96kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3]: \"audio-48khz-192kbitrate-mono-mp3\",\r\n [SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus]: \"ogg-48khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus]: \"webm-16khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus]: \"webm-24khz-16bit-mono-opus\",\r\n [SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk]: \"raw-24khz-16bit-mono-truesilk\",\r\n [SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw]: \"raw-8khz-8bit-mono-alaw\",\r\n [SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw]: \"riff-8khz-8bit-mono-alaw\",\r\n };\r\n private priAudioFormatString: string;\r\n /**\r\n * audio format string for synthesis request, which may differ from priAudioFormatString.\r\n * e.g. for riff format, we will request raw format and add a header in SDK side.\r\n */\r\n private readonly priRequestAudioFormatString: string;\r\n private readonly priHasHeader: boolean;\r\n\r\n /**\r\n * Creates an instance with the given values.\r\n * @constructor\r\n * @param formatTag\r\n * @param {number} channels - Number of channels.\r\n * @param {number} samplesPerSec - Samples per second.\r\n * @param {number} avgBytesPerSec - Average bytes per second.\r\n * @param {number} blockAlign - Block alignment.\r\n * @param {number} bitsPerSample - Bits per sample.\r\n * @param {string} audioFormatString - Audio format string\r\n * @param {string} requestAudioFormatString - Audio format string sent to service.\r\n * @param {boolean} hasHeader - If the format has header or not.\r\n */\r\n public constructor(formatTag: AudioFormatTag,\r\n channels: number,\r\n samplesPerSec: number,\r\n avgBytesPerSec: number,\r\n blockAlign: number,\r\n bitsPerSample: number,\r\n audioFormatString: string,\r\n requestAudioFormatString: string,\r\n hasHeader: boolean) {\r\n super(samplesPerSec, bitsPerSample, channels, formatTag);\r\n this.formatTag = formatTag;\r\n this.avgBytesPerSec = avgBytesPerSec;\r\n this.blockAlign = blockAlign;\r\n this.priAudioFormatString = audioFormatString;\r\n this.priRequestAudioFormatString = requestAudioFormatString;\r\n this.priHasHeader = hasHeader;\r\n }\r\n\r\n public static fromSpeechSynthesisOutputFormat(speechSynthesisOutputFormat?: SpeechSynthesisOutputFormat): AudioOutputFormatImpl {\r\n if (speechSynthesisOutputFormat === undefined) {\r\n return AudioOutputFormatImpl.getDefaultOutputFormat();\r\n }\r\n return AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(\r\n AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString[speechSynthesisOutputFormat]);\r\n }\r\n\r\n public static fromSpeechSynthesisOutputFormatString(speechSynthesisOutputFormatString: string): AudioOutputFormatImpl {\r\n switch (speechSynthesisOutputFormatString) {\r\n case \"raw-8khz-8bit-mono-mulaw\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MuLaw,\r\n 1,\r\n 8000,\r\n 8000,\r\n 1,\r\n 8,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"riff-16khz-16kbps-mono-siren\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.Siren,\r\n 1,\r\n 16000,\r\n 2000,\r\n 40,\r\n 0,\r\n speechSynthesisOutputFormatString,\r\n \"audio-16khz-16kbps-mono-siren\",\r\n true);\r\n case \"audio-16khz-16kbps-mono-siren\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.Siren,\r\n 1,\r\n 16000,\r\n 2000,\r\n 40,\r\n 0,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-16khz-32kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 16000,\r\n 32 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-16khz-128kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 16000,\r\n 128 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-16khz-64kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 16000,\r\n 64 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-24khz-48kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 24000,\r\n 48 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-24khz-96kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 24000,\r\n 96 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-24khz-160kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 24000,\r\n 160 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"raw-16khz-16bit-mono-truesilk\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.SILKSkype,\r\n 1,\r\n 16000,\r\n 32000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n\r\n case \"riff-8khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 8000,\r\n 16000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-8khz-16bit-mono-pcm\",\r\n true);\r\n case \"riff-24khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 24000,\r\n 48000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-24khz-16bit-mono-pcm\",\r\n true);\r\n case \"riff-8khz-8bit-mono-mulaw\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MuLaw,\r\n 1,\r\n 8000,\r\n 8000,\r\n 1,\r\n 8,\r\n speechSynthesisOutputFormatString,\r\n \"raw-8khz-8bit-mono-mulaw\",\r\n true);\r\n case \"raw-16khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 16000,\r\n 32000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-16khz-16bit-mono-pcm\",\r\n false);\r\n case \"raw-24khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 24000,\r\n 48000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-24khz-16bit-mono-pcm\",\r\n false);\r\n case \"raw-8khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 8000,\r\n 16000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-8khz-16bit-mono-pcm\",\r\n false);\r\n case \"ogg-16khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.OGG_OPUS,\r\n 1,\r\n 16000,\r\n 8192,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"ogg-24khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.OGG_OPUS,\r\n 1,\r\n 24000,\r\n 8192,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"raw-48khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 48000,\r\n 96000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-48khz-16bit-mono-pcm\",\r\n false);\r\n case \"riff-48khz-16bit-mono-pcm\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 48000,\r\n 96000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n \"raw-48khz-16bit-mono-pcm\",\r\n true);\r\n case \"audio-48khz-96kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 48000,\r\n 96 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"audio-48khz-192kbitrate-mono-mp3\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.MP3,\r\n 1,\r\n 48000,\r\n 192 << 7,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"ogg-48khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.OGG_OPUS,\r\n 1,\r\n 48000,\r\n 12000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"webm-16khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.WEBM_OPUS,\r\n 1,\r\n 16000,\r\n 8000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"webm-24khz-16bit-mono-opus\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.WEBM_OPUS,\r\n 1,\r\n 24000,\r\n 8000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"raw-24khz-16bit-mono-truesilk\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.SILKSkype,\r\n 1,\r\n 24000,\r\n 48000,\r\n 2,\r\n 16,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"raw-8khz-8bit-mono-alaw\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.ALaw,\r\n 1,\r\n 8000,\r\n 8000,\r\n 1,\r\n 8,\r\n speechSynthesisOutputFormatString,\r\n speechSynthesisOutputFormatString,\r\n false);\r\n case \"riff-8khz-8bit-mono-alaw\":\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.ALaw,\r\n 1,\r\n 8000,\r\n 8000,\r\n 1,\r\n 8,\r\n speechSynthesisOutputFormatString,\r\n \"raw-8khz-8bit-mono-alaw\",\r\n true);\r\n case \"riff-16khz-16bit-mono-pcm\":\r\n default:\r\n return new AudioOutputFormatImpl(\r\n AudioFormatTag.PCM,\r\n 1,\r\n 16000,\r\n 32000,\r\n 2,\r\n 16,\r\n \"riff-16khz-16bit-mono-pcm\",\r\n \"raw-16khz-16bit-mono-pcm\",\r\n true);\r\n }\r\n }\r\n\r\n public static getDefaultOutputFormat(): AudioOutputFormatImpl {\r\n return AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(\r\n (typeof window !== \"undefined\") ? \"audio-24khz-48kbitrate-mono-mp3\" : \"riff-16khz-16bit-mono-pcm\");\r\n }\r\n\r\n /**\r\n * The format tag of the audio\r\n * @AudioFormatTag AudioOutputFormatImpl.prototype.formatTag\r\n * @function\r\n * @public\r\n */\r\n public formatTag: AudioFormatTag;\r\n\r\n /**\r\n * Specifies if this audio output format has a header\r\n * @boolean AudioOutputFormatImpl.prototype.hasHeader\r\n * @function\r\n * @public\r\n */\r\n public get hasHeader(): boolean {\r\n return this.priHasHeader;\r\n }\r\n\r\n /**\r\n * Specifies the header of this format\r\n * @ArrayBuffer AudioOutputFormatImpl.prototype.header\r\n * @function\r\n * @public\r\n */\r\n public get header(): ArrayBuffer {\r\n if (this.hasHeader) {\r\n return this.privHeader;\r\n }\r\n return undefined;\r\n }\r\n\r\n /**\r\n * Updates the header based on the audio length\r\n * @member AudioOutputFormatImpl.updateHeader\r\n * @function\r\n * @public\r\n * @param {number} audioLength - the audio length\r\n */\r\n public updateHeader(audioLength: number): void {\r\n if (this.priHasHeader) {\r\n const view = new DataView(this.privHeader);\r\n view.setUint32(40, audioLength, true);\r\n }\r\n }\r\n\r\n /**\r\n * Specifies the audio format string to be sent to the service\r\n * @string AudioOutputFormatImpl.prototype.requestAudioFormatString\r\n * @function\r\n * @public\r\n */\r\n public get requestAudioFormatString(): string {\r\n return this.priRequestAudioFormatString;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n IAudioDestination,\r\n IStreamChunk,\r\n Stream,\r\n} from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n AudioStreamFormat,\r\n PushAudioOutputStreamCallback\r\n} from \"../Exports\";\r\nimport { AudioOutputFormatImpl } from \"./AudioOutputFormat\";\r\n\r\n/**\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @class AudioOutputStream\r\n */\r\nexport abstract class AudioOutputStream {\r\n\r\n /**\r\n * Creates and initializes an instance.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Sets the format of the AudioOutputStream\r\n * Note: the format is set by the synthesizer before writing. Do not set it before passing it to AudioConfig\r\n * @member AudioOutputStream.prototype.format\r\n */\r\n public abstract set format(format: AudioStreamFormat);\r\n\r\n /**\r\n * Creates a memory backed PullAudioOutputStream with the specified audio format.\r\n * @member AudioOutputStream.createPullStream\r\n * @function\r\n * @public\r\n * @returns {PullAudioOutputStream} The audio output stream being created.\r\n */\r\n public static createPullStream(): PullAudioOutputStream {\r\n return PullAudioOutputStream.create();\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio output stream used for custom audio output configurations.\r\n * @class PullAudioOutputStream\r\n */\r\nexport abstract class PullAudioOutputStream extends AudioOutputStream {\r\n\r\n /**\r\n * Creates a memory backed PullAudioOutputStream with the specified audio format.\r\n * @member PullAudioOutputStream.create\r\n * @function\r\n * @public\r\n * @returns {PullAudioOutputStream} The push audio output stream being created.\r\n */\r\n public static create(): PullAudioOutputStream {\r\n return new PullAudioOutputStreamImpl();\r\n }\r\n\r\n /**\r\n * Reads audio data from the internal buffer.\r\n * @member PullAudioOutputStream.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.\r\n * @returns {Promise} Audio buffer length has been read.\r\n */\r\n public abstract read(dataBuffer: ArrayBuffer): Promise;\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio output stream used for custom audio output configurations.\r\n * @private\r\n * @class PullAudioOutputStreamImpl\r\n */\r\nexport class PullAudioOutputStreamImpl extends PullAudioOutputStream implements IAudioDestination {\r\n private privFormat: AudioOutputFormatImpl;\r\n private privId: string;\r\n private privStream: Stream;\r\n private privLastChunkView: Int8Array;\r\n\r\n /**\r\n * Creates and initializes an instance with the given values.\r\n * @constructor\r\n */\r\n public constructor() {\r\n super();\r\n this.privId = createNoDashGuid();\r\n this.privStream = new Stream();\r\n }\r\n\r\n /**\r\n * Sets the format information to the stream. For internal use only.\r\n * @param {AudioStreamFormat} format - the format to be set.\r\n */\r\n public set format(format: AudioStreamFormat) {\r\n if (format === undefined || format === null) {\r\n this.privFormat = AudioOutputFormatImpl.getDefaultOutputFormat();\r\n }\r\n this.privFormat = format as AudioOutputFormatImpl;\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): AudioStreamFormat {\r\n return this.privFormat;\r\n }\r\n\r\n /**\r\n * Checks if the stream is closed\r\n * @member PullAudioOutputStreamImpl.prototype.isClosed\r\n * @property\r\n * @public\r\n */\r\n public get isClosed(): boolean {\r\n return this.privStream.isClosed;\r\n }\r\n\r\n /**\r\n * Gets the id of the stream\r\n * @member PullAudioOutputStreamImpl.prototype.id\r\n * @property\r\n * @public\r\n */\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n /**\r\n * Reads audio data from the internal buffer.\r\n * @member PullAudioOutputStreamImpl.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.\r\n * @returns {Promise} - Audio buffer length has been read.\r\n */\r\n public async read(dataBuffer: ArrayBuffer): Promise {\r\n const intView: Int8Array = new Int8Array(dataBuffer);\r\n let totalBytes: number = 0;\r\n\r\n if (this.privLastChunkView !== undefined) {\r\n if (this.privLastChunkView.length > dataBuffer.byteLength) {\r\n intView.set(this.privLastChunkView.slice(0, dataBuffer.byteLength));\r\n this.privLastChunkView = this.privLastChunkView.slice(dataBuffer.byteLength);\r\n return Promise.resolve(dataBuffer.byteLength);\r\n }\r\n intView.set(this.privLastChunkView);\r\n totalBytes = this.privLastChunkView.length;\r\n this.privLastChunkView = undefined;\r\n }\r\n\r\n // Until we have the minimum number of bytes to send in a transmission, keep asking for more.\r\n while (totalBytes < dataBuffer.byteLength && !this.privStream.isReadEnded) {\r\n const chunk: IStreamChunk = await this.privStream.read();\r\n if (chunk !== undefined && !chunk.isEnd) {\r\n let tmpBuffer: ArrayBuffer;\r\n if (chunk.buffer.byteLength > dataBuffer.byteLength - totalBytes) {\r\n tmpBuffer = chunk.buffer.slice(0, dataBuffer.byteLength - totalBytes);\r\n this.privLastChunkView = new Int8Array(chunk.buffer.slice(dataBuffer.byteLength - totalBytes));\r\n } else {\r\n tmpBuffer = chunk.buffer;\r\n }\r\n intView.set(new Int8Array(tmpBuffer), totalBytes);\r\n totalBytes += tmpBuffer.byteLength;\r\n } else {\r\n await this.privStream.readEnded();\r\n }\r\n }\r\n return totalBytes;\r\n }\r\n\r\n /**\r\n * Writes the audio data specified by making an internal copy of the data.\r\n * @member PullAudioOutputStreamImpl.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.\r\n */\r\n public write(dataBuffer: ArrayBuffer): void {\r\n Contracts.throwIfNullOrUndefined(this.privStream, \"must set format before writing\");\r\n this.privStream.writeStreamChunk({\r\n buffer: dataBuffer,\r\n isEnd: false,\r\n timeReceived: Date.now()\r\n });\r\n }\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioOutputStreamImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n this.privStream.close();\r\n }\r\n}\r\n\r\n/*\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @class PushAudioOutputStream\r\n */\r\nexport abstract class PushAudioOutputStream extends AudioOutputStream {\r\n /**\r\n * Creates and initializes and instance.\r\n * @constructor\r\n */\r\n protected constructor() { super(); }\r\n\r\n /**\r\n * Creates a PushAudioOutputStream that delegates to the specified callback interface for\r\n * write() and close() methods.\r\n * @member PushAudioOutputStream.create\r\n * @function\r\n * @public\r\n * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,\r\n * derived from PushAudioOutputStreamCallback\r\n * @returns {PushAudioOutputStream} The push audio output stream being created.\r\n */\r\n public static create(callback: PushAudioOutputStreamCallback): PushAudioOutputStream {\r\n return new PushAudioOutputStreamImpl(callback);\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member PushAudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n\r\n}\r\n\r\n/**\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @private\r\n * @class PushAudioOutputStreamImpl\r\n */\r\nexport class PushAudioOutputStreamImpl extends PushAudioOutputStream implements IAudioDestination {\r\n private readonly privId: string;\r\n private privCallback: PushAudioOutputStreamCallback;\r\n\r\n /**\r\n * Creates a PushAudioOutputStream that delegates to the specified callback interface for\r\n * read() and close() methods.\r\n * @constructor\r\n * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,\r\n * derived from PushAudioOutputStreamCallback\r\n */\r\n public constructor(callback: PushAudioOutputStreamCallback) {\r\n super();\r\n this.privId = createNoDashGuid();\r\n this.privCallback = callback;\r\n }\r\n\r\n // tslint:disable-next-line:no-empty\r\n public set format(format: AudioStreamFormat) { }\r\n\r\n public write(buffer: ArrayBuffer): void {\r\n if (!!this.privCallback.write) {\r\n this.privCallback.write(buffer);\r\n }\r\n }\r\n\r\n public close(): void {\r\n if (!!this.privCallback.close) {\r\n this.privCallback.close();\r\n }\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport enum AudioFormatTag {\r\n PCM = 1,\r\n MuLaw,\r\n Siren,\r\n MP3,\r\n SILKSkype,\r\n OGG_OPUS,\r\n WEBM_OPUS,\r\n ALaw,\r\n}\r\n\r\n/**\r\n * Represents audio stream format used for custom audio input configurations.\r\n * @class AudioStreamFormat\r\n */\r\nexport abstract class AudioStreamFormat {\r\n /**\r\n * Creates an audio stream format object representing the default audio stream\r\n * format (16KHz 16bit mono PCM).\r\n * @member AudioStreamFormat.getDefaultInputFormat\r\n * @function\r\n * @public\r\n * @returns {AudioStreamFormat} The audio stream format being created.\r\n */\r\n public static getDefaultInputFormat(): AudioStreamFormat {\r\n return AudioStreamFormatImpl.getDefaultInputFormat();\r\n }\r\n\r\n /**\r\n * Creates an audio stream format object with the specified pcm waveformat characteristics.\r\n * @member AudioStreamFormat.getWaveFormatPCM\r\n * @function\r\n * @public\r\n * @param {number} samplesPerSecond - Sample rate, in samples per second (Hertz).\r\n * @param {number} bitsPerSample - Bits per sample, typically 16.\r\n * @param {number} channels - Number of channels in the waveform-audio data. Monaural data\r\n * uses one channel and stereo data uses two channels.\r\n * @returns {AudioStreamFormat} The audio stream format being created.\r\n */\r\n public static getWaveFormatPCM(samplesPerSecond: number, bitsPerSample: number, channels: number): AudioStreamFormat {\r\n return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels);\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioStreamFormat.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * @private\r\n * @class AudioStreamFormatImpl\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class AudioStreamFormatImpl extends AudioStreamFormat {\r\n protected privHeader: ArrayBuffer;\r\n\r\n /**\r\n * Creates an instance with the given values.\r\n * @constructor\r\n * @param {number} samplesPerSec - Samples per second.\r\n * @param {number} bitsPerSample - Bits per sample.\r\n * @param {number} channels - Number of channels.\r\n * @param {AudioFormatTag} format - Audio format (PCM, alaw or mulaw).\r\n */\r\n public constructor(samplesPerSec: number = 16000, bitsPerSample: number = 16, channels: number = 1, format: AudioFormatTag = AudioFormatTag.PCM) {\r\n super();\r\n /* 1 for PCM; 6 for alaw; 7 for mulaw */\r\n switch (format) {\r\n case AudioFormatTag.PCM:\r\n this.formatTag = 1;\r\n break;\r\n case AudioFormatTag.ALaw:\r\n this.formatTag = 6;\r\n break;\r\n case AudioFormatTag.MuLaw:\r\n this.formatTag = 7;\r\n break;\r\n default:\r\n }\r\n this.bitsPerSample = bitsPerSample;\r\n this.samplesPerSec = samplesPerSec;\r\n this.channels = channels;\r\n this.avgBytesPerSec = this.samplesPerSec * this.channels * (this.bitsPerSample / 8);\r\n this.blockAlign = this.channels * Math.max(this.bitsPerSample, 8);\r\n\r\n this.privHeader = new ArrayBuffer(44);\r\n\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView\r\n const view = new DataView(this.privHeader);\r\n\r\n /* RIFF identifier */\r\n this.setString(view, 0, \"RIFF\");\r\n /* file length */\r\n view.setUint32(4, 0, true);\r\n /* RIFF type & Format */\r\n this.setString(view, 8, \"WAVEfmt \");\r\n /* format chunk length */\r\n view.setUint32(16, 16, true);\r\n /* audio format */\r\n view.setUint16(20, this.formatTag, true);\r\n /* channel count */\r\n view.setUint16(22, this.channels, true);\r\n /* sample rate */\r\n view.setUint32(24, this.samplesPerSec, true);\r\n /* byte rate (sample rate * block align) */\r\n view.setUint32(28, this.avgBytesPerSec, true);\r\n /* block align (channel count * bytes per sample) */\r\n view.setUint16(32, this.channels * (this.bitsPerSample / 8), true);\r\n /* bits per sample */\r\n view.setUint16(34, this.bitsPerSample, true);\r\n /* data chunk identifier */\r\n this.setString(view, 36, \"data\");\r\n /* data chunk length */\r\n view.setUint32(40, 0, true);\r\n }\r\n\r\n /**\r\n * Retrieves the default input format.\r\n * @member AudioStreamFormatImpl.getDefaultInputFormat\r\n * @function\r\n * @public\r\n * @returns {AudioStreamFormatImpl} The default input format.\r\n */\r\n public static getDefaultInputFormat(): AudioStreamFormatImpl {\r\n return new AudioStreamFormatImpl();\r\n }\r\n\r\n /**\r\n * Creates an audio context appropriate to current browser\r\n * @member AudioStreamFormatImpl.getAudioContext\r\n * @function\r\n * @public\r\n * @returns {AudioContext} An audio context instance\r\n */\r\n public static getAudioContext(sampleRate?: number): AudioContext {\r\n // Workaround for Speech SDK bug in Safari.\r\n const AudioContext = (window as any).AudioContext // our preferred impl\r\n || (window as any).webkitAudioContext // fallback, mostly when on Safari\r\n || false; // could not find.\r\n\r\n // https://developer.mozilla.org/en-US/docs/Web/API/AudioContext\r\n if (!!AudioContext) {\r\n if (sampleRate !== undefined && navigator.mediaDevices.getSupportedConstraints().sampleRate) {\r\n return new AudioContext({ sampleRate });\r\n } else {\r\n return new AudioContext();\r\n }\r\n } else {\r\n throw new Error(\"Browser does not support Web Audio API (AudioContext is not available).\");\r\n }\r\n }\r\n\r\n /**\r\n * Closes the configuration object.\r\n * @member AudioStreamFormatImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void { return; }\r\n\r\n /**\r\n * The format of the audio, valid values: 1 (PCM)\r\n * @member AudioStreamFormatImpl.prototype.formatTag\r\n * @function\r\n * @public\r\n */\r\n public formatTag: number;\r\n\r\n /**\r\n * The number of channels, valid values: 1 (Mono).\r\n * @member AudioStreamFormatImpl.prototype.channels\r\n * @function\r\n * @public\r\n */\r\n public channels: number;\r\n\r\n /**\r\n * The sample rate, valid values: 16000.\r\n * @member AudioStreamFormatImpl.prototype.samplesPerSec\r\n * @function\r\n * @public\r\n */\r\n public samplesPerSec: number;\r\n\r\n /**\r\n * The bits per sample, valid values: 16\r\n * @member AudioStreamFormatImpl.prototype.b\r\n * @function\r\n * @public\r\n */\r\n public bitsPerSample: number;\r\n\r\n /**\r\n * Average bytes per second, usually calculated as nSamplesPerSec * nChannels * ceil(wBitsPerSample, 8).\r\n * @member AudioStreamFormatImpl.prototype.avgBytesPerSec\r\n * @function\r\n * @public\r\n */\r\n public avgBytesPerSec: number;\r\n\r\n /**\r\n * The size of a single frame, valid values: nChannels * ceil(wBitsPerSample, 8).\r\n * @member AudioStreamFormatImpl.prototype.blockAlign\r\n * @function\r\n * @public\r\n */\r\n public blockAlign: number;\r\n\r\n public get header(): ArrayBuffer {\r\n return this.privHeader;\r\n }\r\n\r\n protected setString = (view: DataView, offset: number, str: string): void => {\r\n for (let i = 0; i < str.length; i++) {\r\n view.setUint8(offset + i, str.charCodeAt(i));\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError } from \"../../common/Error\";\r\nimport { marshalPromiseToCallbacks } from \"../../common/Promise\";\r\nimport { AudioStreamFormat, PullAudioInputStreamCallback } from \"../Exports\";\r\nimport { AudioStreamFormatImpl } from \"./AudioStreamFormat\";\r\n\r\ntype AudioDataTypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array;\r\n/**\r\n * Base audio player class\r\n * TODO: Plays only PCM for now.\r\n * @class\r\n */\r\nexport class BaseAudioPlayer {\r\n\r\n private audioContext: AudioContext = null;\r\n private gainNode: GainNode = null;\r\n private audioFormat: AudioStreamFormatImpl;\r\n private autoUpdateBufferTimer: any = 0;\r\n private samples: Float32Array;\r\n private startTime: number;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {AudioStreamFormat} audioFormat audio stream format recognized by the player.\r\n */\r\n public constructor(audioFormat?: AudioStreamFormat) {\r\n if (audioFormat === undefined) {\r\n audioFormat = AudioStreamFormat.getDefaultInputFormat();\r\n }\r\n this.init(audioFormat);\r\n }\r\n\r\n /**\r\n * play Audio sample\r\n * @param newAudioData audio data to be played.\r\n */\r\n public playAudioSample(newAudioData: ArrayBuffer, cb?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks((async (): Promise => {\r\n this.ensureInitializedContext();\r\n const audioData = this.formatAudioData(newAudioData);\r\n const newSamplesData = new Float32Array(this.samples.length + audioData.length);\r\n newSamplesData.set(this.samples, 0);\r\n newSamplesData.set(audioData, this.samples.length);\r\n this.samples = newSamplesData;\r\n })(), cb, err);\r\n }\r\n\r\n /**\r\n * stops audio and clears the buffers\r\n */\r\n public stopAudio(cb?: () => void, err?: (error: string) => void): void {\r\n if (this.audioContext !== null) {\r\n this.samples = new Float32Array();\r\n clearInterval(this.autoUpdateBufferTimer);\r\n this.audioContext.close().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string) => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n this.audioContext = null;\r\n }\r\n }\r\n\r\n private init(audioFormat: AudioStreamFormat): void {\r\n this.audioFormat = audioFormat as AudioStreamFormatImpl;\r\n this.samples = new Float32Array();\r\n }\r\n\r\n private ensureInitializedContext(): void {\r\n if (this.audioContext === null) {\r\n this.createAudioContext();\r\n const timerPeriod = 200;\r\n this.autoUpdateBufferTimer = setInterval(() => {\r\n this.updateAudioBuffer();\r\n }, timerPeriod);\r\n }\r\n }\r\n\r\n private createAudioContext(): void {\r\n // new ((window as any).AudioContext || (window as any).webkitAudioContext)();\r\n this.audioContext = AudioStreamFormatImpl.getAudioContext();\r\n\r\n // TODO: Various examples shows this gain node, it does not seem to be needed unless we plan\r\n // to control the volume, not likely\r\n this.gainNode = this.audioContext.createGain();\r\n this.gainNode.gain.value = 1;\r\n this.gainNode.connect(this.audioContext.destination);\r\n this.startTime = this.audioContext.currentTime;\r\n }\r\n\r\n private formatAudioData(audioData: ArrayBuffer): Float32Array {\r\n switch (this.audioFormat.bitsPerSample) {\r\n case 8:\r\n return this.formatArrayBuffer(new Int8Array(audioData), 128);\r\n case 16:\r\n return this.formatArrayBuffer(new Int16Array(audioData), 32768);\r\n case 32:\r\n return this.formatArrayBuffer(new Int32Array(audioData), 2147483648);\r\n default:\r\n throw new InvalidOperationError(\"Only WAVE_FORMAT_PCM (8/16/32 bps) format supported at this time\");\r\n }\r\n }\r\n\r\n private formatArrayBuffer(audioData: AudioDataTypedArray, maxValue: number): Float32Array {\r\n const float32Data = new Float32Array(audioData.length);\r\n for (let i = 0; i < audioData.length; i++) {\r\n float32Data[i] = audioData[i] / maxValue;\r\n }\r\n return float32Data;\r\n }\r\n\r\n private updateAudioBuffer(): void {\r\n if (this.samples.length === 0) {\r\n return;\r\n }\r\n\r\n const channelCount = this.audioFormat.channels;\r\n const bufferSource = this.audioContext.createBufferSource();\r\n const frameCount = this.samples.length / channelCount;\r\n const audioBuffer = this.audioContext.createBuffer(channelCount, frameCount, this.audioFormat.samplesPerSec);\r\n\r\n // TODO: Should we do the conversion in the pushAudioSample instead?\r\n for (let channel = 0; channel < channelCount; channel++) {\r\n // Fill in individual channel data\r\n let channelOffset = channel;\r\n const audioData = audioBuffer.getChannelData(channel);\r\n for (let i = 0; i < this.samples.length; i++, channelOffset += channelCount) {\r\n audioData[i] = this.samples[channelOffset];\r\n }\r\n }\r\n\r\n if (this.startTime < this.audioContext.currentTime) {\r\n this.startTime = this.audioContext.currentTime;\r\n }\r\n\r\n bufferSource.buffer = audioBuffer;\r\n bufferSource.connect(this.gainNode);\r\n bufferSource.start(this.startTime);\r\n\r\n // Make sure we play the next sample after the current one.\r\n this.startTime += audioBuffer.duration;\r\n\r\n // Clear the samples for the next pushed data.\r\n this.samples = new Float32Array();\r\n }\r\n\r\n private async playAudio(audioData: ArrayBuffer): Promise {\r\n if (this.audioContext === null) {\r\n this.createAudioContext();\r\n }\r\n const source: AudioBufferSourceNode = this.audioContext.createBufferSource();\r\n const destination: AudioDestinationNode = this.audioContext.destination;\r\n await this.audioContext.decodeAudioData(audioData, (newBuffer: AudioBuffer): void => {\r\n source.buffer = newBuffer;\r\n source.connect(destination);\r\n source.start(0);\r\n });\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n /**\r\n * An abstract base class that defines callback methods (read() and close()) for\r\n * custom audio input streams).\r\n * @class PullAudioInputStreamCallback\r\n */\r\nexport abstract class PullAudioInputStreamCallback {\r\n\r\n /**\r\n * Reads data from audio input stream into the data buffer. The maximal number of bytes\r\n * to be read is determined by the size of dataBuffer.\r\n * @member PullAudioInputStreamCallback.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The byte array to store the read data.\r\n * @returns {number} the number of bytes have been read.\r\n */\r\n public abstract read(dataBuffer: ArrayBuffer): number;\r\n\r\n /**\r\n * Closes the audio input stream.\r\n * @member PullAudioInputStreamCallback.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n/**\r\n * An abstract base class that defines callback methods (write() and close()) for\r\n * custom audio output streams).\r\n * @class PushAudioOutputStreamCallback\r\n */\r\nexport abstract class PushAudioOutputStreamCallback {\r\n\r\n /**\r\n * Writes audio data into the data buffer.\r\n * @member PushAudioOutputStreamCallback.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The byte array that stores the audio data to write.\r\n */\r\n public abstract write(dataBuffer: ArrayBuffer): void;\r\n\r\n /**\r\n * Closes the audio output stream.\r\n * @member PushAudioOutputStreamCallback.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { SynthesisAdapterBase } from \"../../common.speech/Exports\";\r\nimport {\r\n BackgroundEvent,\r\n createNoDashGuid,\r\n Events,\r\n IAudioDestination,\r\n INumberDictionary\r\n} from \"../../common/Exports\";\r\nimport { AudioStreamFormat, IPlayer } from \"../Exports\";\r\nimport { AudioOutputFormatImpl } from \"./AudioOutputFormat\";\r\nimport { PullAudioOutputStreamImpl } from \"./AudioOutputStream\";\r\nimport { AudioFormatTag } from \"./AudioStreamFormat\";\r\n\r\nconst MediaDurationPlaceholderSeconds = 60 * 30;\r\n\r\nconst AudioFormatToMimeType: INumberDictionary = {\r\n [AudioFormatTag.PCM]: \"audio/wav\",\r\n [AudioFormatTag.MuLaw]: \"audio/x-wav\",\r\n [AudioFormatTag.MP3]: \"audio/mpeg\",\r\n [AudioFormatTag.OGG_OPUS]: \"audio/ogg\",\r\n [AudioFormatTag.WEBM_OPUS]: \"audio/webm; codecs=opus\",\r\n [AudioFormatTag.ALaw]: \"audio/x-wav\",\r\n};\r\n\r\n/**\r\n * Represents the speaker playback audio destination, which only works in browser.\r\n * Note: the SDK will try to use Media Source Extensions to play audio.\r\n * Mp3 format has better supports on Microsoft Edge, Chrome and Safari (desktop), so, it's better to specify mp3 format for playback.\r\n * @class SpeakerAudioDestination\r\n * Updated in version 1.17.0\r\n */\r\nexport class SpeakerAudioDestination implements IAudioDestination, IPlayer {\r\n private readonly privId: string;\r\n private privFormat: AudioOutputFormatImpl;\r\n private privAudio: HTMLAudioElement;\r\n private privMediaSource: MediaSource;\r\n private privSourceBuffer: SourceBuffer;\r\n private privPlaybackStarted: boolean = false;\r\n private privAudioBuffer: ArrayBuffer[];\r\n private privAppendingToBuffer: boolean = false;\r\n private privMediaSourceOpened: boolean = false;\r\n private privIsClosed: boolean;\r\n private privIsPaused: boolean;\r\n private privAudioOutputStream: PullAudioOutputStreamImpl;\r\n private privBytesReceived: number = 0;\r\n\r\n public constructor(audioDestinationId?: string) {\r\n this.privId = audioDestinationId ? audioDestinationId : createNoDashGuid();\r\n this.privIsPaused = false;\r\n this.privIsClosed = false;\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n public write(buffer: ArrayBuffer, cb?: () => void, err?: (error: string) => void): void {\r\n if (this.privAudioBuffer !== undefined) {\r\n this.privAudioBuffer.push(buffer);\r\n this.updateSourceBuffer().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n } else if (this.privAudioOutputStream !== undefined) {\r\n this.privAudioOutputStream.write(buffer);\r\n this.privBytesReceived += buffer.byteLength;\r\n }\r\n }\r\n\r\n public close(cb?: () => void, err?: (error: string) => void): void {\r\n this.privIsClosed = true;\r\n if (this.privSourceBuffer !== undefined) {\r\n this.handleSourceBufferUpdateEnd().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n } else if (this.privAudioOutputStream !== undefined) {\r\n if ((this.privFormat.formatTag === AudioFormatTag.PCM || this.privFormat.formatTag === AudioFormatTag.MuLaw\r\n || this.privFormat.formatTag === AudioFormatTag.ALaw) && this.privFormat.hasHeader === false) {\r\n // tslint:disable-next-line:no-console\r\n console.warn(`Play back is not supported for raw PCM, mulaw or alaw format without header.`);\r\n if (!!this.onAudioEnd) {\r\n this.onAudioEnd(this);\r\n }\r\n } else {\r\n let receivedAudio = new ArrayBuffer(this.privBytesReceived);\r\n this.privAudioOutputStream.read(receivedAudio).then((_: number): void => {\r\n receivedAudio = SynthesisAdapterBase.addHeader(receivedAudio, this.privFormat);\r\n const audioBlob = new Blob([receivedAudio], { type: AudioFormatToMimeType[this.privFormat.formatTag] });\r\n this.privAudio.src = window.URL.createObjectURL(audioBlob);\r\n this.notifyPlayback().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n }\r\n } else {\r\n // unsupported format, call onAudioEnd directly.\r\n if (!!this.onAudioEnd) {\r\n this.onAudioEnd(this);\r\n }\r\n }\r\n }\r\n\r\n set format(format: AudioStreamFormat) {\r\n if (typeof (AudioContext) !== \"undefined\" || typeof ((window as any).webkitAudioContext) !== \"undefined\") {\r\n this.privFormat = format as AudioOutputFormatImpl;\r\n const mimeType: string = AudioFormatToMimeType[this.privFormat.formatTag];\r\n if (mimeType === undefined) {\r\n // tslint:disable-next-line:no-console\r\n console.warn(\r\n `Unknown mimeType for format ${AudioFormatTag[this.privFormat.formatTag]}; playback is not supported.`);\r\n\r\n } else if (typeof (MediaSource) !== \"undefined\" && MediaSource.isTypeSupported(mimeType)) {\r\n this.privAudio = new Audio();\r\n this.privAudioBuffer = [];\r\n this.privMediaSource = new MediaSource();\r\n this.privAudio.src = URL.createObjectURL(this.privMediaSource);\r\n this.privAudio.load();\r\n this.privMediaSource.onsourceopen = (event: Event): void => {\r\n this.privMediaSourceOpened = true;\r\n this.privMediaSource.duration = MediaDurationPlaceholderSeconds;\r\n this.privSourceBuffer = this.privMediaSource.addSourceBuffer(mimeType);\r\n this.privSourceBuffer.onupdate = (_: Event) => {\r\n this.updateSourceBuffer().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n };\r\n this.privSourceBuffer.onupdateend = (_: Event) => {\r\n this.handleSourceBufferUpdateEnd().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n };\r\n this.privSourceBuffer.onupdatestart = (_: Event) => {\r\n this.privAppendingToBuffer = false;\r\n };\r\n };\r\n this.updateSourceBuffer().catch((reason: string): void => {\r\n Events.instance.onEvent(new BackgroundEvent(reason));\r\n });\r\n\r\n } else {\r\n // tslint:disable-next-line:no-console\r\n console.warn(\r\n `Format ${AudioFormatTag[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`);\r\n this.privAudioOutputStream = new PullAudioOutputStreamImpl();\r\n this.privAudioOutputStream.format = this.privFormat;\r\n this.privAudio = new Audio();\r\n }\r\n }\r\n }\r\n\r\n public get isClosed(): boolean {\r\n return this.privIsClosed;\r\n }\r\n\r\n public get currentTime(): number {\r\n if (this.privAudio !== undefined) {\r\n return this.privAudio.currentTime;\r\n }\r\n return -1;\r\n }\r\n\r\n public pause(): void {\r\n if (!this.privIsPaused && this.privAudio !== undefined) {\r\n this.privAudio.pause();\r\n this.privIsPaused = true;\r\n }\r\n }\r\n\r\n public resume(cb?: () => void, err?: (error: string) => void): void {\r\n if (this.privIsPaused && this.privAudio !== undefined) {\r\n this.privAudio.play().then(() => {\r\n if (!!cb) {\r\n cb();\r\n }\r\n }, (error: string): void => {\r\n if (!!err) {\r\n err(error);\r\n }\r\n });\r\n this.privIsPaused = false;\r\n }\r\n }\r\n\r\n public onAudioStart: (sender: IPlayer) => void;\r\n\r\n public onAudioEnd: (sender: IPlayer) => void;\r\n\r\n public get internalAudio(): HTMLAudioElement {\r\n return this.privAudio;\r\n }\r\n\r\n private async updateSourceBuffer(): Promise {\r\n if (this.privAudioBuffer !== undefined && (this.privAudioBuffer.length > 0) && this.sourceBufferAvailable()) {\r\n this.privAppendingToBuffer = true;\r\n const binary = this.privAudioBuffer.shift();\r\n try {\r\n this.privSourceBuffer.appendBuffer(binary);\r\n } catch (error) {\r\n this.privAudioBuffer.unshift(binary);\r\n // tslint:disable-next-line:no-console\r\n console.log(\r\n \"buffer filled, pausing addition of binaries until space is made\");\r\n return;\r\n }\r\n await this.notifyPlayback();\r\n } else if (this.canEndStream()) {\r\n await this.handleSourceBufferUpdateEnd();\r\n }\r\n }\r\n\r\n private async handleSourceBufferUpdateEnd(): Promise {\r\n if (this.canEndStream() && this.sourceBufferAvailable()) {\r\n this.privMediaSource.endOfStream();\r\n await this.notifyPlayback();\r\n }\r\n }\r\n\r\n private async notifyPlayback(): Promise {\r\n if (!this.privPlaybackStarted && this.privAudio !== undefined) {\r\n this.privPlaybackStarted = true;\r\n if (!!this.onAudioStart) {\r\n this.onAudioStart(this);\r\n }\r\n this.privAudio.onended = (): void => {\r\n if (!!this.onAudioEnd) {\r\n this.onAudioEnd(this);\r\n }\r\n };\r\n if (!this.privIsPaused) {\r\n await this.privAudio.play();\r\n }\r\n }\r\n }\r\n\r\n private canEndStream(): boolean {\r\n return (this.isClosed && this.privSourceBuffer !== undefined && (this.privAudioBuffer.length === 0)\r\n && this.privMediaSourceOpened && !this.privAppendingToBuffer && this.privMediaSource.readyState === \"open\");\r\n }\r\n\r\n private sourceBufferAvailable(): boolean {\r\n return (this.privSourceBuffer !== undefined && !this.privSourceBuffer.updating);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { AutoDetectSourceLanguagesOpenRangeOptionName } from \"../common.speech/Exports\";\r\nimport {Contracts} from \"./Contracts\";\r\nimport {\r\n PropertyCollection,\r\n PropertyId,\r\n SourceLanguageConfig,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Language auto detect configuration.\r\n * @class AutoDetectSourceLanguageConfig\r\n * Added in version 1.13.0.\r\n */\r\nexport class AutoDetectSourceLanguageConfig {\r\n private privProperties: PropertyCollection;\r\n\r\n private constructor() {\r\n this.privProperties = new PropertyCollection();\r\n }\r\n\r\n /**\r\n * @member AutoDetectSourceLanguageConfig.fromOpenRange\r\n * @function\r\n * @public\r\n * Only [[SpeechSynthesizer]] supports source language auto detection from open range,\r\n * for [[Recognizer]], please use AutoDetectSourceLanguageConfig with specific source languages.\r\n * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig\r\n * @summary Creates an instance of the AutoDetectSourceLanguageConfig with open range.\r\n */\r\n public static fromOpenRange(): AutoDetectSourceLanguageConfig {\r\n const config = new AutoDetectSourceLanguageConfig();\r\n config.properties.setProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, AutoDetectSourceLanguagesOpenRangeOptionName);\r\n return config;\r\n }\r\n\r\n /**\r\n * @member AutoDetectSourceLanguageConfig.fromLanguages\r\n * @function\r\n * @public\r\n * @param {string[]} languages Comma-separated string of languages (eg. \"en-US,fr-FR\") to populate properties of config.\r\n * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig\r\n * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given languages.\r\n */\r\n public static fromLanguages(languages: string[]): AutoDetectSourceLanguageConfig {\r\n Contracts.throwIfArrayEmptyOrWhitespace(languages, \"languages\");\r\n const config = new AutoDetectSourceLanguageConfig();\r\n config.properties.setProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, languages.join());\r\n return config;\r\n }\r\n\r\n /**\r\n * @member AutoDetectSourceLanguageConfig.fromSourceLanguageConfigs\r\n * @function\r\n * @public\r\n * @param {SourceLanguageConfig[]} configs SourceLanguageConfigs to populate properties of config.\r\n * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig\r\n * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given SourceLanguageConfigs.\r\n */\r\n public static fromSourceLanguageConfigs(configs: SourceLanguageConfig[]): AutoDetectSourceLanguageConfig {\r\n if (configs.length < 1) {\r\n throw new Error(\"Expected non-empty SourceLanguageConfig array.\");\r\n }\r\n const autoConfig = new AutoDetectSourceLanguageConfig();\r\n const langs: string[] = [];\r\n configs.forEach((config: SourceLanguageConfig) => {\r\n langs.push(config.language);\r\n if (config.endpointId !== undefined && config.endpointId !== \"\") {\r\n const customProperty = config.language + PropertyId.SpeechServiceConnection_EndpointId.toString();\r\n autoConfig.properties.setProperty(customProperty, config.endpointId);\r\n }\r\n });\r\n autoConfig.properties.setProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, langs.join());\r\n\r\n return autoConfig;\r\n }\r\n\r\n /**\r\n * @member AutoDetectSourceLanguageConfig.prototype.properties\r\n * @function\r\n * @public\r\n * @return {PropertyCollection} Properties of the config.\r\n * @summary Gets an auto detected language config properties\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n SpeechRecognitionResult,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Output format\r\n * @class AutoDetectSourceLanguageResult\r\n */\r\nexport class AutoDetectSourceLanguageResult {\r\n\r\n private privLanguage: string;\r\n private privLanguageDetectionConfidence: string;\r\n\r\n private constructor(language: string, languageDetectionConfidence: string) {\r\n Contracts.throwIfNullOrUndefined(language, \"language\");\r\n Contracts.throwIfNullOrUndefined(languageDetectionConfidence, \"languageDetectionConfidence\");\r\n this.privLanguage = language;\r\n this.privLanguageDetectionConfidence = languageDetectionConfidence;\r\n }\r\n\r\n /**\r\n * Creates an instance of AutoDetectSourceLanguageResult object from a SpeechRecognitionResult instance.\r\n * @member AutoDetectSourceLanguageResult.fromResult\r\n * @function\r\n * @public\r\n * @param {SpeechRecognitionResult} result - The recognition result.\r\n * @returns {AutoDetectSourceLanguageResult} AutoDetectSourceLanguageResult object being created.\r\n */\r\n public static fromResult(result: SpeechRecognitionResult): AutoDetectSourceLanguageResult {\r\n return new AutoDetectSourceLanguageResult(result.language, result.languageDetectionConfidence);\r\n }\r\n\r\n public get language(): string {\r\n return this.privLanguage;\r\n }\r\n\r\n public get languageDetectionConfidence(): string {\r\n return this.privLanguageDetectionConfidence;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport { DialogServiceConfig, DialogServiceConfigImpl } from \"./DialogServiceConfig\";\r\nimport { PropertyId } from \"./Exports\";\r\n\r\n/**\r\n * Class that defines configurations for the dialog service connector object for using a Bot Framework backend.\r\n * @class BotFrameworkConfig\r\n */\r\nexport class BotFrameworkConfig extends DialogServiceConfigImpl {\r\n\r\n /**\r\n * Creates an instance of BotFrameworkConfig.\r\n */\r\n public constructor() {\r\n super();\r\n }\r\n\r\n /**\r\n * Creates a bot framework configuration instance with the provided subscription information.\r\n * @member BotFrameworkConfig.fromSubscription\r\n * @function\r\n * @public\r\n * @param subscription Subscription key associated with the bot\r\n * @param region The region name (see the region page).\r\n * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the\r\n * resource name.\r\n * @returns {BotFrameworkConfig} A new bot framework configuration instance.\r\n */\r\n public static fromSubscription(subscription: string, region: string, botId?: string): BotFrameworkConfig {\r\n Contracts.throwIfNullOrWhitespace(subscription, \"subscription\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const botFrameworkConfig: BotFrameworkConfig = new DialogServiceConfigImpl();\r\n botFrameworkConfig.setProperty(\r\n PropertyId.Conversation_DialogType,\r\n DialogServiceConfig.DialogTypes.BotFramework);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Key, subscription);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n\r\n if (botId) {\r\n botFrameworkConfig.setProperty(PropertyId.Conversation_ApplicationId, botId);\r\n }\r\n\r\n return botFrameworkConfig;\r\n }\r\n\r\n /**\r\n * Creates a bot framework configuration instance for the specified authorization token and region.\r\n * Note: The caller must ensure that an authorization token is valid. Before an authorization token expires, the\r\n * caller must refresh it by setting the authorizationToken property on the corresponding\r\n * DialogServiceConnector instance created with this config. The contents of configuration objects are copied\r\n * when connectors are created, so setting authorizationToken on a DialogServiceConnector will not update the\r\n * original configuration's authorization token. Create a new configuration instance or set the\r\n * SpeechServiceAuthorization_Token property to update an existing instance if it will be used to create\r\n * further DialogServiceConnectors.\r\n * @member BotFrameworkConfig.fromAuthorizationToken\r\n * @function\r\n * @public\r\n * @param authorizationToken The authorization token associated with the bot\r\n * @param region The region name (see the region page).\r\n * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the\r\n * resource name.\r\n * @returns {BotFrameworkConfig} A new bot framework configuration instance.\r\n */\r\n public static fromAuthorizationToken(\r\n authorizationToken: string, region: string, botId?: string\r\n ): BotFrameworkConfig {\r\n Contracts.throwIfNullOrWhitespace(authorizationToken, \"authorizationToken\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const botFrameworkConfig: BotFrameworkConfig = new DialogServiceConfigImpl();\r\n botFrameworkConfig.setProperty(\r\n PropertyId.Conversation_DialogType,\r\n DialogServiceConfig.DialogTypes.BotFramework);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceAuthorization_Token, authorizationToken);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n\r\n if (botId) {\r\n botFrameworkConfig.setProperty(PropertyId.Conversation_ApplicationId, botId);\r\n }\r\n\r\n return botFrameworkConfig;\r\n }\r\n\r\n /**\r\n * Creates an instance of a BotFrameworkConfig.\r\n * This method is intended only for users who use a non-default service host. The standard resource path will be\r\n * assumed. For services with a non-standard resource path or no path at all, use fromEndpoint instead.\r\n * Note: Query parameters are not allowed in the host URI and must be set by other APIs.\r\n * Note: To use an authorization token with fromHost, use fromHost(URL) and then set the AuthorizationToken\r\n * property on the created BotFrameworkConfig instance.\r\n * Note: Added in version 1.15.0.\r\n * @member BotFrameworkConfig.fromHost\r\n * @function\r\n * @public\r\n * @param {URL | string} host - If a URL is provided, the fully-qualified host with protocol (e.g.\r\n * wss://your.host.com:1234) will be used. If a string is provided, it will be embedded in\r\n * wss://{host}.convai.speech.azure.us.\r\n * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization\r\n * token must be set.\r\n * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the\r\n * resource name.\r\n * @returns {BotFrameworkConfig} A new bot framework configuration instance.\r\n */\r\n public static fromHost(\r\n host: URL | string,\r\n subscriptionKey?: string,\r\n botId?: string): BotFrameworkConfig {\r\n\r\n Contracts.throwIfNullOrUndefined(host, \"host\");\r\n const resolvedHost: URL = host instanceof URL ? host : new URL(`wss://${host}.convai.speech.azure.us`);\r\n Contracts.throwIfNullOrUndefined(resolvedHost, \"resolvedHost\");\r\n\r\n const botFrameworkConfig: BotFrameworkConfig = new DialogServiceConfigImpl();\r\n botFrameworkConfig.setProperty(\r\n PropertyId.Conversation_DialogType,\r\n DialogServiceConfig.DialogTypes.BotFramework);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Host, resolvedHost.toString());\r\n\r\n if (undefined !== subscriptionKey) {\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n }\r\n\r\n return botFrameworkConfig;\r\n }\r\n\r\n /**\r\n * Creates an instance of a BotFrameworkConfig.\r\n * This method is intended only for users who use a non-standard service endpoint or parameters.\r\n * Note: The query parameters specified in the endpoint URL are not changed, even if they are set by any other APIs.\r\n * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the\r\n * fromEndpoint method, and then set authorizationToken=\"token\" on the created BotFrameworkConfig instance to\r\n * use the authorization token.\r\n * Note: Added in version 1.15.0.\r\n * @member BotFrameworkConfig.fromEndpoint\r\n * @function\r\n * @public\r\n * @param {URL} endpoint - The service endpoint to connect to.\r\n * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization\r\n * token must be set.\r\n * @returns {BotFrameworkConfig} - A new bot framework configuration instance using the provided endpoint.\r\n */\r\n public static fromEndpoint(endpoint: URL, subscriptionKey?: string): BotFrameworkConfig {\r\n Contracts.throwIfNull(endpoint, \"endpoint\");\r\n\r\n const botFrameworkConfig: BotFrameworkConfig = new DialogServiceConfigImpl();\r\n botFrameworkConfig.setProperty(\r\n PropertyId.Conversation_DialogType,\r\n DialogServiceConfig.DialogTypes.BotFramework);\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Endpoint, endpoint.toString());\r\n\r\n if (undefined !== subscriptionKey) {\r\n botFrameworkConfig.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);\r\n }\r\n\r\n return botFrameworkConfig;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { CancellationErrorCodePropertyName, EnumTranslation, SimpleSpeechPhrase } from \"../common.speech/Exports\";\r\nimport { CancellationDetailsBase } from \"./CancellationDetailsBase\";\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n RecognitionResult,\r\n SpeechSynthesisResult\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Contains detailed information about why a result was canceled.\r\n * @class CancellationDetails\r\n */\r\nexport class CancellationDetails extends CancellationDetailsBase {\r\n\r\n private constructor(reason: CancellationReason, errorDetails: string, errorCode: CancellationErrorCode) {\r\n super(reason, errorDetails, errorCode);\r\n }\r\n\r\n /**\r\n * Creates an instance of CancellationDetails object for the canceled RecognitionResult.\r\n * @member CancellationDetails.fromResult\r\n * @function\r\n * @public\r\n * @param {RecognitionResult | SpeechSynthesisResult} result - The result that was canceled.\r\n * @returns {CancellationDetails} The cancellation details object being created.\r\n */\r\n public static fromResult(result: RecognitionResult | SpeechSynthesisResult): CancellationDetails {\r\n let reason = CancellationReason.Error;\r\n let errorCode: CancellationErrorCode = CancellationErrorCode.NoError;\r\n\r\n if (result instanceof RecognitionResult && !!result.json) {\r\n const simpleSpeech: SimpleSpeechPhrase = SimpleSpeechPhrase.fromJSON(result.json);\r\n reason = EnumTranslation.implTranslateCancelResult(simpleSpeech.RecognitionStatus);\r\n }\r\n\r\n if (!!result.properties) {\r\n errorCode = (CancellationErrorCode as any)[result.properties.getProperty(CancellationErrorCodePropertyName, CancellationErrorCode[CancellationErrorCode.NoError])];\r\n }\r\n\r\n return new CancellationDetails(reason, result.errorDetails, errorCode);\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationErrorCode,\r\n CancellationReason,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Contains detailed information about why a result was canceled.\r\n * @class CancellationDetailsBase\r\n */\r\nexport class CancellationDetailsBase {\r\n private privReason: CancellationReason;\r\n private privErrorDetails: string;\r\n private privErrorCode: CancellationErrorCode;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {CancellationReason} reason - The cancellation reason.\r\n * @param {string} errorDetails - The error details, if provided.\r\n */\r\n protected constructor(reason: CancellationReason, errorDetails: string, errorCode: CancellationErrorCode) {\r\n this.privReason = reason;\r\n this.privErrorDetails = errorDetails;\r\n this.privErrorCode = errorCode;\r\n }\r\n\r\n /**\r\n * The reason the recognition was canceled.\r\n * @member CancellationDetailsBase.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {CancellationReason} Specifies the reason canceled.\r\n */\r\n public get reason(): CancellationReason {\r\n return this.privReason;\r\n }\r\n\r\n /**\r\n * In case of an unsuccessful recognition, provides details of the occurred error.\r\n * @member CancellationDetailsBase.prototype.errorDetails\r\n * @function\r\n * @public\r\n * @returns {string} A String that represents the error details.\r\n */\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n\r\n /**\r\n * The error code in case of an unsuccessful recognition.\r\n * Added in version 1.1.0.\r\n * @return An error code that represents the error reason.\r\n */\r\n public get ErrorCode(): CancellationErrorCode {\r\n return this.privErrorCode;\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines error code in case that CancellationReason is Error.\r\n * Added in version 1.1.0.\r\n */\r\nexport enum CancellationErrorCode {\r\n /**\r\n * Indicates that no error occurred during speech recognition.\r\n */\r\n NoError,\r\n\r\n /**\r\n * Indicates an authentication error.\r\n */\r\n AuthenticationFailure,\r\n\r\n /**\r\n * Indicates that one or more recognition parameters are invalid.\r\n */\r\n BadRequestParameters,\r\n\r\n /**\r\n * Indicates that the number of parallel requests exceeded the number of allowed\r\n * concurrent transcriptions for the subscription.\r\n */\r\n TooManyRequests,\r\n\r\n /**\r\n * Indicates a connection error.\r\n */\r\n ConnectionFailure,\r\n\r\n /**\r\n * Indicates a time-out error when waiting for response from service.\r\n */\r\n ServiceTimeout,\r\n\r\n /**\r\n * Indicates that an error is returned by the service.\r\n */\r\n ServiceError,\r\n\r\n /**\r\n * Indicates an unexpected runtime error.\r\n */\r\n RuntimeError,\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationErrorCode,\r\n CancellationEventArgs,\r\n CancellationReason,\r\n RecognitionEventArgs\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Defines content of a CancellationEvent.\r\n * @class CancellationEventArgsBase\r\n */\r\nexport class CancellationEventArgsBase extends RecognitionEventArgs implements CancellationEventArgs {\r\n private privReason: CancellationReason;\r\n private privErrorDetails: string;\r\n private privErrorCode: CancellationErrorCode;\r\n\r\n /**\r\n * Creates and initializes an instance of this class.\r\n * @constructor\r\n * @param {CancellationReason} reason - The cancellation reason.\r\n * @param {string} errorDetails - Error details, if provided.\r\n * @param {number} offset - The offset.\r\n * @param {string} sessionId - The session id.\r\n */\r\n public constructor(reason: CancellationReason, errorDetails: string,\r\n errorCode: CancellationErrorCode, offset?: number, sessionId?: string) {\r\n super(offset, sessionId);\r\n\r\n this.privReason = reason;\r\n this.privErrorDetails = errorDetails;\r\n this.privErrorCode = errorCode;\r\n }\r\n\r\n /**\r\n * The reason the recognition was canceled.\r\n * @member CancellationEventArgsBase.prototype.reason\r\n * @function\r\n * @public\r\n * @returns {CancellationReason} Specifies the reason canceled.\r\n */\r\n public get reason(): CancellationReason {\r\n return this.privReason;\r\n }\r\n\r\n /**\r\n * The error code in case of an unsuccessful operation.\r\n * @return An error code that represents the error reason.\r\n */\r\n public get errorCode(): CancellationErrorCode {\r\n return this.privErrorCode;\r\n }\r\n\r\n /**\r\n * In case of an unsuccessful operation, provides details of the occurred error.\r\n * @member CancellationEventArgsBase.prototype.errorDetails\r\n * @function\r\n * @public\r\n * @returns {string} A String that represents the error details.\r\n */\r\n public get errorDetails(): string {\r\n return this.privErrorDetails;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * Defines the possible reasons a recognition result might be canceled.\r\n * @class CancellationReason\r\n */\r\nexport enum CancellationReason {\r\n /**\r\n * Indicates that an error occurred during speech recognition.\r\n * @member CancellationReason.Error\r\n */\r\n Error,\r\n\r\n /**\r\n * Indicates that the end of the audio stream was reached.\r\n * @member CancellationReason.EndOfStream\r\n */\r\n EndOfStream,\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport {\r\n ServiceRecognizerBase,\r\n SynthesisAdapterBase,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n ConnectionEvent,\r\n ConnectionMessageReceivedEvent,\r\n ConnectionMessageSentEvent,\r\n IDetachable,\r\n marshalPromiseToCallbacks,\r\n ServiceEvent,\r\n} from \"../common/Exports\";\r\nimport {\r\n ConnectionMessageImpl\r\n} from \"./ConnectionMessage\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport {\r\n ConnectionEventArgs,\r\n ConnectionMessageEventArgs,\r\n Recognizer,\r\n ServiceEventArgs,\r\n SpeechSynthesizer,\r\n} from \"./Exports\";\r\n\r\n/**\r\n * Connection is a proxy class for managing connection to the speech service of the specified Recognizer.\r\n * By default, a Recognizer autonomously manages connection to service when needed.\r\n * The Connection class provides additional methods for users to explicitly open or close a connection and\r\n * to subscribe to connection status changes.\r\n * The use of Connection is optional, and mainly for scenarios where fine tuning of application\r\n * behavior based on connection status is needed. Users can optionally call Open() to manually set up a connection\r\n * in advance before starting recognition on the Recognizer associated with this Connection.\r\n * If the Recognizer needs to connect or disconnect to service, it will\r\n * setup or shutdown the connection independently. In this case the Connection will be notified by change of connection\r\n * status via Connected/Disconnected events.\r\n * Added in version 1.2.1.\r\n */\r\nexport class Connection {\r\n private privInternalData: ServiceRecognizerBase | SynthesisAdapterBase;\r\n private privEventListener: IDetachable;\r\n private privServiceEventListener: IDetachable;\r\n\r\n /**\r\n * Gets the Connection instance from the specified recognizer.\r\n * @param recognizer The recognizer associated with the connection.\r\n * @return The Connection instance of the recognizer.\r\n */\r\n public static fromRecognizer(recognizer: Recognizer): Connection {\r\n const recoBase: ServiceRecognizerBase = recognizer.internalData as ServiceRecognizerBase;\r\n\r\n const ret: Connection = new Connection();\r\n\r\n ret.privInternalData = recoBase;\r\n ret.setupEvents();\r\n return ret;\r\n }\r\n\r\n /**\r\n * Gets the Connection instance from the specified synthesizer.\r\n * @param synthesizer The synthesizer associated with the connection.\r\n * @return The Connection instance of the synthesizer.\r\n */\r\n public static fromSynthesizer(synthesizer: SpeechSynthesizer): Connection {\r\n const synthBase: SynthesisAdapterBase = synthesizer.internalData as SynthesisAdapterBase;\r\n\r\n const ret: Connection = new Connection();\r\n\r\n ret.privInternalData = synthBase;\r\n ret.setupEvents();\r\n return ret;\r\n }\r\n\r\n /**\r\n * Starts to set up connection to the service.\r\n * Users can optionally call openConnection() to manually set up a connection in advance before starting recognition on the\r\n * Recognizer associated with this Connection. After starting recognition, calling Open() will have no effect\r\n *\r\n * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to\r\n * be notified when the connection is established.\r\n */\r\n public openConnection(cb?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks(this.privInternalData.connect(), cb, err);\r\n }\r\n\r\n /**\r\n * Closes the connection the service.\r\n * Users can optionally call closeConnection() to manually shutdown the connection of the associated Recognizer.\r\n *\r\n * If closeConnection() is called during recognition, recognition will fail and cancel with an error.\r\n */\r\n public closeConnection(cb?: () => void, err?: (error: string) => void): void {\r\n if (this.privInternalData instanceof SynthesisAdapterBase) {\r\n throw new Error(\"Disconnecting a synthesizer's connection is currently not supported\");\r\n } else {\r\n marshalPromiseToCallbacks((this.privInternalData as ServiceRecognizerBase).disconnect(), cb, err);\r\n }\r\n }\r\n\r\n /**\r\n * Appends a parameter in a message to service.\r\n * Added in version 1.12.1.\r\n * @param path The path of the network message.\r\n * @param propertyName Name of the property\r\n * @param propertyValue Value of the property. This is a json string.\r\n */\r\n public setMessageProperty(path: string, propertyName: string, propertyValue: string): void {\r\n Contracts.throwIfNullOrWhitespace(propertyName, \"propertyName\");\r\n\r\n if (this.privInternalData instanceof ServiceRecognizerBase) {\r\n if (path.toLowerCase() !== \"speech.context\") {\r\n throw new Error(\"Only speech.context message property sets are currently supported for recognizer\");\r\n } else {\r\n (this.privInternalData as ServiceRecognizerBase).speechContext.setSection(propertyName, propertyValue);\r\n }\r\n } else if (this.privInternalData instanceof SynthesisAdapterBase) {\r\n if (path.toLowerCase() !== \"synthesis.context\") {\r\n throw new Error(\"Only synthesis.context message property sets are currently supported for synthesizer\");\r\n } else {\r\n (this.privInternalData as SynthesisAdapterBase).synthesisContext.setSection(propertyName, propertyValue);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Sends a message to the speech service.\r\n * Added in version 1.13.0.\r\n * @param path The WebSocket path of the message\r\n * @param payload The payload of the message. This is a json string or a ArrayBuffer.\r\n * @param success A callback to indicate success.\r\n * @param error A callback to indicate an error.\r\n */\r\n public sendMessageAsync(path: string, payload: string | ArrayBuffer, success?: () => void, error?: (error: string) => void): void {\r\n marshalPromiseToCallbacks(this.privInternalData.sendNetworkMessage(path, payload), success, error);\r\n }\r\n\r\n /**\r\n * Any message from service that is not being processed by any other top level recognizers.\r\n *\r\n * Will be removed in 2.0.\r\n */\r\n public receivedServiceMessage: (args: ServiceEventArgs) => void;\r\n\r\n /**\r\n * Any message received from the Speech Service.\r\n */\r\n public messageReceived: (args: ConnectionMessageEventArgs) => void;\r\n\r\n /**\r\n * Any message sent to the Speech Service.\r\n */\r\n public messageSent: (args: ConnectionMessageEventArgs) => void;\r\n\r\n /**\r\n * The Connected event to indicate that the recognizer is connected to service.\r\n */\r\n public connected: (args: ConnectionEventArgs) => void;\r\n\r\n /**\r\n * The Disconnected event to indicate that the recognizer is disconnected from service.\r\n */\r\n public disconnected: (args: ConnectionEventArgs) => void;\r\n\r\n /**\r\n * Dispose of associated resources.\r\n */\r\n public close(): void {\r\n /* tslint:disable:no-empty */\r\n }\r\n\r\n private setupEvents(): void {\r\n this.privEventListener = this.privInternalData.connectionEvents.attach((connectionEvent: ConnectionEvent): void => {\r\n if (connectionEvent.name === \"ConnectionEstablishedEvent\") {\r\n if (!!this.connected) {\r\n this.connected(new ConnectionEventArgs(connectionEvent.connectionId));\r\n }\r\n } else if (connectionEvent.name === \"ConnectionClosedEvent\") {\r\n if (!!this.disconnected) {\r\n this.disconnected(new ConnectionEventArgs(connectionEvent.connectionId));\r\n }\r\n } else if (connectionEvent.name === \"ConnectionMessageSentEvent\") {\r\n if (!!this.messageSent) {\r\n this.messageSent(new ConnectionMessageEventArgs(new ConnectionMessageImpl((connectionEvent as ConnectionMessageSentEvent).message)));\r\n }\r\n } else if (connectionEvent.name === \"ConnectionMessageReceivedEvent\") {\r\n if (!!this.messageReceived) {\r\n this.messageReceived(new ConnectionMessageEventArgs(new ConnectionMessageImpl((connectionEvent as ConnectionMessageReceivedEvent).message)));\r\n }\r\n }\r\n });\r\n\r\n this.privServiceEventListener = this.privInternalData.serviceEvents.attach((e: ServiceEvent): void => {\r\n if (!!this.receivedServiceMessage) {\r\n this.receivedServiceMessage(new ServiceEventArgs(e.jsonString, e.name));\r\n }\r\n });\r\n }\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport { SessionEventArgs } from \"./Exports\";\r\n\r\n/**\r\n * Defines payload for connection events like Connected/Disconnected.\r\n * Added in version 1.2.0\r\n */\r\nexport class ConnectionEventArgs extends SessionEventArgs {\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport { HeaderNames } from \"../common.speech/HeaderNames\";\r\nimport {\r\n ConnectionMessage as IntConnectionMessage,\r\n MessageType\r\n} from \"../common/Exports\";\r\nimport {\r\n PropertyCollection\r\n} from \"./PropertyCollection\";\r\nimport { PropertyId } from \"./PropertyId\";\r\n\r\n/**\r\n * ConnectionMessage represents implementation specific messages sent to and received from\r\n * the speech service. These messages are provided for debugging purposes and should not\r\n * be used for production use cases with the Azure Cognitive Services Speech Service.\r\n * Messages sent to and received from the Speech Service are subject to change without\r\n * notice. This includes message contents, headers, payloads, ordering, etc.\r\n * Added in version 1.11.0.\r\n */\r\nexport abstract class ConnectionMessage {\r\n /**\r\n * The message path.\r\n */\r\n public abstract get path(): string;\r\n\r\n /**\r\n * Checks to see if the ConnectionMessage is a text message.\r\n * See also IsBinaryMessage().\r\n */\r\n public abstract get isTextMessage(): boolean;\r\n\r\n /**\r\n * Checks to see if the ConnectionMessage is a binary message.\r\n * See also GetBinaryMessage().\r\n */\r\n public abstract get isBinaryMessage(): boolean;\r\n\r\n /**\r\n * Gets the text message payload. Typically the text message content-type is\r\n * application/json. To determine other content-types use\r\n * Properties.GetProperty(\"Content-Type\").\r\n */\r\n public abstract get TextMessage(): string;\r\n\r\n /**\r\n * Gets the binary message payload.\r\n */\r\n public abstract get binaryMessage(): ArrayBuffer;\r\n\r\n /**\r\n * A collection of properties and their values defined for this .\r\n * Message headers can be accessed via this collection (e.g. \"Content-Type\").\r\n */\r\n public abstract get properties(): PropertyCollection;\r\n\r\n /**\r\n * Returns a string that represents the connection message.\r\n */\r\n public abstract toString(): string;\r\n}\r\n\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class ConnectionMessageImpl {\r\n\r\n private privConnectionMessage: IntConnectionMessage;\r\n private privProperties: PropertyCollection;\r\n\r\n constructor(message: IntConnectionMessage) {\r\n this.privConnectionMessage = message;\r\n this.privProperties = new PropertyCollection();\r\n if (!!this.privConnectionMessage.headers[HeaderNames.ConnectionId]) {\r\n this.privProperties.setProperty(PropertyId.Speech_SessionId, this.privConnectionMessage.headers[HeaderNames.ConnectionId]);\r\n }\r\n\r\n Object.keys(this.privConnectionMessage.headers).forEach((header: string, index: number, array: string[]): void => {\r\n this.privProperties.setProperty(header, this.privConnectionMessage.headers[header]);\r\n });\r\n }\r\n\r\n /**\r\n * The message path.\r\n */\r\n public get path(): string {\r\n return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find((key: string) => key.toLowerCase() === \"path\".toLowerCase())];\r\n }\r\n\r\n /**\r\n * Checks to see if the ConnectionMessage is a text message.\r\n * See also IsBinaryMessage().\r\n */\r\n public get isTextMessage(): boolean {\r\n return this.privConnectionMessage.messageType === MessageType.Text;\r\n }\r\n\r\n /**\r\n * Checks to see if the ConnectionMessage is a binary message.\r\n * See also GetBinaryMessage().\r\n */\r\n public get isBinaryMessage(): boolean {\r\n return this.privConnectionMessage.messageType === MessageType.Binary;\r\n }\r\n\r\n /**\r\n * Gets the text message payload. Typically the text message content-type is\r\n * application/json. To determine other content-types use\r\n * Properties.GetProperty(\"Content-Type\").\r\n */\r\n public get TextMessage(): string {\r\n return this.privConnectionMessage.textBody;\r\n }\r\n\r\n /**\r\n * Gets the binary message payload.\r\n */\r\n public get binaryMessage(): ArrayBuffer {\r\n return this.privConnectionMessage.binaryBody;\r\n }\r\n\r\n /**\r\n * A collection of properties and their values defined for this .\r\n * Message headers can be accessed via this collection (e.g. \"Content-Type\").\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /**\r\n * Returns a string that represents the connection message.\r\n */\r\n public toString(): string {\r\n return \"\";\r\n }\r\n}\r\n","//\r\n// Copyright (c) Microsoft. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\r\n//\r\n\r\nimport {\r\n ConnectionMessage,\r\n SessionEventArgs\r\n} from \"./Exports\";\r\n\r\nexport class ConnectionMessageEventArgs {\r\n\r\n private privConnectionMessage: ConnectionMessage;\r\n\r\n constructor(message: ConnectionMessage) {\r\n this.privConnectionMessage = message;\r\n }\r\n\r\n /**\r\n * Gets the associated with this .\r\n */\r\n public get message(): ConnectionMessage {\r\n return this.privConnectionMessage;\r\n }\r\n\r\n /**\r\n * Returns a string that represents the connection message event.\r\n */\r\n public toString(): string {\r\n return \"Message: \" + this.privConnectionMessage.toString();\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n/**\r\n * @class Contracts\r\n * @private\r\n */\r\nexport class Contracts {\r\n public static throwIfNullOrUndefined(param: any, name: string): void {\r\n if (param === undefined || param === null) {\r\n throw new Error(\"throwIfNullOrUndefined:\" + name);\r\n }\r\n }\r\n\r\n public static throwIfNull(param: any, name: string): void {\r\n if (param === null) {\r\n throw new Error(\"throwIfNull:\" + name);\r\n }\r\n }\r\n\r\n public static throwIfNullOrWhitespace(param: string, name: string): void {\r\n Contracts.throwIfNullOrUndefined(param, name);\r\n\r\n if ((\"\" + param).trim().length < 1) {\r\n throw new Error(\"throwIfNullOrWhitespace:\" + name);\r\n }\r\n }\r\n\r\n public static throwIfDisposed(isDisposed: boolean): void {\r\n if (isDisposed) {\r\n throw new Error(\"the object is already disposed\");\r\n }\r\n }\r\n\r\n public static throwIfArrayEmptyOrWhitespace(array: string[], name: string): void {\r\n Contracts.throwIfNullOrUndefined(array, name);\r\n\r\n if (array.length === 0) {\r\n throw new Error(\"throwIfArrayEmptyOrWhitespace:\" + name);\r\n }\r\n\r\n for (const item of array) {\r\n Contracts.throwIfNullOrWhitespace(item, name);\r\n }\r\n }\r\n\r\n public static throwIfFileDoesNotExist(param: any, name: string): void {\r\n Contracts.throwIfNullOrWhitespace(param, name);\r\n\r\n // TODO check for file existence.\r\n }\r\n\r\n public static throwIfNotUndefined(param: any, name: string): void {\r\n if (param !== undefined) {\r\n throw new Error(\"throwIfNotUndefined:\" + name);\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n CancellationEventArgsBase,\r\n} from \"./CancellationEventArgsBase\";\r\n\r\n/**\r\n * Defines content of a RecognitionErrorEvent.\r\n * @class ConversationTranscriptionCanceledEventArgs\r\n */\r\nexport class ConversationTranscriptionCanceledEventArgs extends CancellationEventArgsBase {\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport { DialogServiceConfig, DialogServiceConfigImpl } from \"./DialogServiceConfig\";\r\nimport { PropertyId } from \"./Exports\";\r\n\r\n/**\r\n * Class that defines configurations for the dialog service connector object for using a CustomCommands backend.\r\n * @class CustomCommandsConfig\r\n */\r\nexport class CustomCommandsConfig extends DialogServiceConfigImpl {\r\n\r\n /**\r\n * Creates an instance of CustomCommandsConfig.\r\n */\r\n public constructor() {\r\n super();\r\n }\r\n\r\n /**\r\n * Creates an instance of the bot framework config with the specified subscription and region.\r\n * @member CustomCommandsConfig.fromSubscription\r\n * @function\r\n * @public\r\n * @param applicationId Speech Commands application id.\r\n * @param subscription Subscription key associated with the bot\r\n * @param region The region name (see the region page).\r\n * @returns {CustomCommandsConfig} A new bot framework config.\r\n */\r\n public static fromSubscription(applicationId: string, subscription: string, region: string): CustomCommandsConfig {\r\n Contracts.throwIfNullOrWhitespace(applicationId, \"applicationId\");\r\n Contracts.throwIfNullOrWhitespace(subscription, \"subscription\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const customCommandsConfig: CustomCommandsConfig = new DialogServiceConfigImpl();\r\n customCommandsConfig.setProperty(PropertyId.Conversation_DialogType, DialogServiceConfig.DialogTypes.CustomCommands);\r\n customCommandsConfig.setProperty(PropertyId.Conversation_ApplicationId, applicationId);\r\n customCommandsConfig.setProperty(PropertyId.SpeechServiceConnection_Key, subscription);\r\n customCommandsConfig.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n return customCommandsConfig;\r\n }\r\n\r\n /**\r\n * Creates an instance of the bot framework config with the specified Speech Commands application id, authorization token and region.\r\n * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token\r\n * expires, the caller needs to refresh it by calling this setter with a new valid token.\r\n * As configuration values are copied when creating a new recognizer, the new token value will not apply to recognizers that have already been created.\r\n * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer\r\n * to refresh the token. Otherwise, the recognizers will encounter errors during recognition.\r\n * @member CustomCommandsConfig.fromAuthorizationToken\r\n * @function\r\n * @public\r\n * @param applicationId Speech Commands application id.\r\n * @param authorizationToken The authorization token associated with the application.\r\n * @param region The region name (see the region page).\r\n * @returns {CustomCommandsConfig} A new speech commands config.\r\n */\r\n public static fromAuthorizationToken(applicationId: string, authorizationToken: string, region: string): CustomCommandsConfig {\r\n Contracts.throwIfNullOrWhitespace(applicationId, \"applicationId\");\r\n Contracts.throwIfNullOrWhitespace(authorizationToken, \"authorizationToken\");\r\n Contracts.throwIfNullOrWhitespace(region, \"region\");\r\n\r\n const customCommandsConfig: CustomCommandsConfig = new DialogServiceConfigImpl();\r\n customCommandsConfig.setProperty(PropertyId.Conversation_DialogType, DialogServiceConfig.DialogTypes.CustomCommands);\r\n customCommandsConfig.setProperty(PropertyId.Conversation_ApplicationId, applicationId);\r\n customCommandsConfig.setProperty(PropertyId.SpeechServiceAuthorization_Token, authorizationToken);\r\n customCommandsConfig.setProperty(PropertyId.SpeechServiceConnection_Region, region);\r\n return customCommandsConfig;\r\n }\r\n\r\n /**\r\n * Sets the corresponding backend application identifier.\r\n * @member CustomCommandsConfig.prototype.Conversation_ApplicationId\r\n * @function\r\n * @public\r\n * @param {string} value - The application identifier to set.\r\n */\r\n public set applicationId(value: string) {\r\n Contracts.throwIfNullOrWhitespace(value, \"value\");\r\n this.setProperty(PropertyId.Conversation_ApplicationId, value);\r\n }\r\n\r\n /**\r\n * Gets the corresponding backend application identifier.\r\n * @member CustomCommandsConfig.prototype.Conversation_ApplicationId\r\n * @function\r\n * @public\r\n * @param {string} value - The application identifier to get.\r\n */\r\n public get applicationId(): string {\r\n return this.getProperty(PropertyId.Conversation_ApplicationId);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { Contracts } from \"./Contracts\";\r\nimport { PropertyCollection, PropertyId, ServicePropertyChannel, SpeechConfigImpl } from \"./Exports\";\r\nimport { OutputFormat } from \"./OutputFormat\";\r\n\r\n/**\r\n * Class that defines base configurations for dialog service connector\r\n * @class DialogServiceConfig\r\n */\r\nexport abstract class DialogServiceConfig {\r\n\r\n /**\r\n * Creates an instance of DialogService config.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Sets an arbitrary property.\r\n * @member DialogServiceConfig.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to set.\r\n * @param {string} value - The new value of the property.\r\n */\r\n public abstract setProperty(name: string | PropertyId, value: string): void;\r\n\r\n /**\r\n * Returns the current value of an arbitrary property.\r\n * @member DialogServiceConfig.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {string} name - The name of the property to query.\r\n * @param {string} def - The value to return in case the property is not known.\r\n * @returns {string} The current value, or provided default, of the given property.\r\n */\r\n public abstract getProperty(name: string | PropertyId, def?: string): string;\r\n\r\n /**\r\n * @member DialogServiceConfig.prototype.setServiceProperty\r\n * @function\r\n * @public\r\n * @param {name} The name of the property.\r\n * @param {value} Value to set.\r\n * @param {channel} The channel used to pass the specified property to service.\r\n * @summary Sets a property value that will be passed to service using the specified channel.\r\n */\r\n public abstract setServiceProperty(name: string, value: string, channel: ServicePropertyChannel): void;\r\n\r\n /**\r\n * Sets the proxy configuration.\r\n * Only relevant in Node.js environments.\r\n * Added in version 1.4.0.\r\n * @param proxyHostName The host name of the proxy server.\r\n * @param proxyPort The port number of the proxy server.\r\n */\r\n public abstract setProxy(proxyHostName: string, proxyPort: number): void;\r\n\r\n /**\r\n * Sets the proxy configuration.\r\n * Only relevant in Node.js environments.\r\n * Added in version 1.4.0.\r\n * @param proxyHostName The host name of the proxy server, without the protocol scheme (http://)\r\n * @param porxyPort The port number of the proxy server.\r\n * @param proxyUserName The user name of the proxy server.\r\n * @param proxyPassword The password of the proxy server.\r\n */\r\n public abstract setProxy(proxyHostName: string, proxyPort: number, proxyUserName: string, proxyPassword: string): void;\r\n\r\n /**\r\n * Returns the configured language.\r\n * @member DialogServiceConfig.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n */\r\n public abstract get speechRecognitionLanguage(): string;\r\n\r\n /**\r\n * Gets/Sets the input language.\r\n * @member DialogServiceConfig.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The language to use for recognition.\r\n */\r\n public abstract set speechRecognitionLanguage(value: string);\r\n\r\n /**\r\n * Sets the corresponding backend application identifier.\r\n * @member DialogServiceConfig.prototype.Conversation_ApplicationId\r\n * @function\r\n * @public\r\n * @param {string} value - The application identifier to set.\r\n */\r\n // tslint:disable-next-line: no-empty\r\n public set applicationId(value: string) { }\r\n\r\n public static DialogTypes: any = class {\r\n public static BotFramework: string = \"bot_framework\";\r\n public static CustomCommands: string = \"custom_commands\";\r\n };\r\n}\r\n\r\n/**\r\n * Dialog Service configuration.\r\n * @class DialogServiceConfigImpl\r\n */\r\n// tslint:disable-next-line:max-classes-per-file\r\nexport class DialogServiceConfigImpl extends DialogServiceConfig {\r\n\r\n private privSpeechConfig: SpeechConfigImpl;\r\n\r\n /**\r\n * Creates an instance of dialogService config.\r\n */\r\n public constructor() {\r\n super();\r\n this.privSpeechConfig = new SpeechConfigImpl();\r\n }\r\n\r\n /**\r\n * Provides access to custom properties.\r\n * @member DialogServiceConfigImpl.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The properties.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privSpeechConfig.properties;\r\n }\r\n\r\n /**\r\n * Gets the speech recognition language.\r\n * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n */\r\n public get speechRecognitionLanguage(): string {\r\n return this.privSpeechConfig.speechRecognitionLanguage;\r\n }\r\n\r\n /**\r\n * Sets the speech recognition language.\r\n * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage\r\n * @function\r\n * @public\r\n * @param {string} value - The language to set.\r\n */\r\n public set speechRecognitionLanguage(value: string) {\r\n Contracts.throwIfNullOrWhitespace(value, \"value\");\r\n this.privSpeechConfig.speechRecognitionLanguage = value;\r\n }\r\n\r\n public get outputFormat(): OutputFormat {\r\n return this.privSpeechConfig.outputFormat;\r\n }\r\n\r\n public set outputFormat(value: OutputFormat) {\r\n this.privSpeechConfig.outputFormat = value;\r\n }\r\n\r\n /**\r\n * Sets a named property as value\r\n * @member DialogServiceConfigImpl.prototype.setProperty\r\n * @function\r\n * @public\r\n * @param {PropertyId | string} name - The property to set.\r\n * @param {string} value - The value.\r\n */\r\n public setProperty(name: string | PropertyId, value: string): void {\r\n this.privSpeechConfig.setProperty(name, value);\r\n }\r\n\r\n /**\r\n * Sets a named property as value\r\n * @member DialogServiceConfigImpl.prototype.getProperty\r\n * @function\r\n * @public\r\n * @param {PropertyId | string} name - The property to get.\r\n * @param {string} def - The default value to return in case the property is not known.\r\n * @returns {string} The current value, or provided default, of the given property.\r\n */\r\n public getProperty(name: string | PropertyId, def?: string): string {\r\n return this.privSpeechConfig.getProperty(name);\r\n }\r\n\r\n /**\r\n * Sets the proxy configuration.\r\n * Only relevant in Node.js environments.\r\n * Added in version 1.4.0.\r\n * @param proxyHostName The host name of the proxy server, without the protocol scheme (http://)\r\n * @param proxyPort The port number of the proxy server.\r\n * @param proxyUserName The user name of the proxy server.\r\n * @param proxyPassword The password of the proxy server.\r\n */\r\n public setProxy(proxyHostName: string, proxyPort: number, proxyUserName?: string, proxyPassword?: string): void {\r\n this.setProperty(PropertyId.SpeechServiceConnection_ProxyHostName, proxyHostName);\r\n this.setProperty(PropertyId.SpeechServiceConnection_ProxyPort, `${proxyPort}`);\r\n if (proxyUserName) {\r\n this.setProperty(PropertyId.SpeechServiceConnection_ProxyUserName, proxyUserName);\r\n }\r\n if (proxyPassword) {\r\n this.setProperty(PropertyId.SpeechServiceConnection_ProxyPassword, proxyPassword);\r\n }\r\n }\r\n\r\n public setServiceProperty(name: string, value: string, channel: ServicePropertyChannel): void {\r\n this.privSpeechConfig.setServiceProperty(name, value, channel);\r\n }\r\n\r\n /**\r\n * Dispose of associated resources.\r\n * @member DialogServiceConfigImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n return;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { DialogConnectionFactory } from \"../common.speech/DialogConnectorFactory\";\r\nimport {\r\n DialogServiceAdapter,\r\n IAgentConfig,\r\n IAuthentication,\r\n IConnectionFactory,\r\n RecognitionMode,\r\n RecognizerConfig,\r\n ServiceRecognizerBase,\r\n SpeechServiceConfig,\r\n} from \"../common.speech/Exports\";\r\nimport {\r\n Deferred,\r\n marshalPromiseToCallbacks\r\n} from \"../common/Exports\";\r\nimport { ActivityReceivedEventArgs } from \"./ActivityReceivedEventArgs\";\r\nimport { AudioConfigImpl } from \"./Audio/AudioConfig\";\r\nimport { AudioOutputFormatImpl } from \"./Audio/AudioOutputFormat\";\r\nimport { Contracts } from \"./Contracts\";\r\nimport { DialogServiceConfig, DialogServiceConfigImpl } from \"./DialogServiceConfig\";\r\nimport {\r\n AudioConfig,\r\n PropertyCollection,\r\n Recognizer,\r\n SpeechRecognitionCanceledEventArgs,\r\n SpeechRecognitionEventArgs,\r\n SpeechRecognitionResult\r\n} from \"./Exports\";\r\nimport { PropertyId } from \"./PropertyId\";\r\nimport { TurnStatusReceivedEventArgs } from \"./TurnStatusReceivedEventArgs\";\r\n\r\n/**\r\n * Dialog Service Connector\r\n * @class DialogServiceConnector\r\n */\r\nexport class DialogServiceConnector extends Recognizer {\r\n private privIsDisposed: boolean;\r\n private isTurnComplete: boolean;\r\n\r\n /**\r\n * Initializes an instance of the DialogServiceConnector.\r\n * @constructor\r\n * @param {DialogServiceConfig} dialogConfig - Set of properties to configure this recognizer.\r\n * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer\r\n */\r\n public constructor(dialogConfig: DialogServiceConfig, audioConfig?: AudioConfig) {\r\n const dialogServiceConfigImpl = dialogConfig as DialogServiceConfigImpl;\r\n Contracts.throwIfNull(dialogConfig, \"dialogConfig\");\r\n\r\n super(audioConfig, dialogServiceConfigImpl.properties, new DialogConnectionFactory());\r\n\r\n this.isTurnComplete = true;\r\n this.privIsDisposed = false;\r\n this.privProperties = dialogServiceConfigImpl.properties.clone();\r\n\r\n const agentConfig = this.buildAgentConfig();\r\n this.privReco.agentConfig.set(agentConfig);\r\n }\r\n\r\n /**\r\n * The event recognizing signals that an intermediate recognition result is received.\r\n * @member DialogServiceConnector.prototype.recognizing\r\n * @function\r\n * @public\r\n */\r\n public recognizing: (sender: DialogServiceConnector, event: SpeechRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event recognized signals that a final recognition result is received.\r\n * @member DialogServiceConfig.prototype.recognized\r\n * @function\r\n * @public\r\n */\r\n public recognized: (sender: DialogServiceConnector, event: SpeechRecognitionEventArgs) => void;\r\n\r\n /**\r\n * The event canceled signals that an error occurred during recognition.\r\n * @member DialogServiceConnector.prototype.canceled\r\n * @function\r\n * @public\r\n */\r\n public canceled: (sender: DialogServiceConnector, event: SpeechRecognitionCanceledEventArgs) => void;\r\n\r\n /**\r\n * The event activityReceived signals that an activity has been received.\r\n * @member DialogServiceConnector.prototype.activityReceived\r\n * @function\r\n * @public\r\n */\r\n public activityReceived: (sender: DialogServiceConnector, event: ActivityReceivedEventArgs) => void;\r\n\r\n /**\r\n * The event turnStatusReceived signals that a turn status message has been received. These messages are\r\n * associated with both an interaction and a conversation. They are used to notify the client in the event\r\n * of an interaction failure with the dialog backend, e.g. in the event of a network issue, timeout, crash,\r\n * or other problem.\r\n * @member DialogServiceConnector.prototype.turnStatusReceived\r\n * @function\r\n * @public\r\n */\r\n public turnStatusReceived: (sender: DialogServiceConnector, event: TurnStatusReceivedEventArgs) => void;\r\n\r\n /**\r\n * Starts a connection to the service.\r\n * Users can optionally call connect() to manually set up a connection in advance, before starting interactions.\r\n *\r\n * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to\r\n * be notified when the connection is established.\r\n * @member DialogServiceConnector.prototype.connect\r\n * @function\r\n * @public\r\n */\r\n public connect(cb?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks(this.privReco.connect(), cb, err);\r\n }\r\n\r\n /**\r\n * Closes the connection the service.\r\n * Users can optionally call disconnect() to manually shutdown the connection of the associated DialogServiceConnector.\r\n *\r\n * If disconnect() is called during a recognition, recognition will fail and cancel with an error.\r\n */\r\n public disconnect(cb?: () => void, err?: (error: string) => void): void {\r\n marshalPromiseToCallbacks(this.privReco.disconnect(), cb, err);\r\n }\r\n\r\n /**\r\n * Gets the authorization token used to communicate with the service.\r\n * @member DialogServiceConnector.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @returns {string} Authorization token.\r\n */\r\n public get authorizationToken(): string {\r\n return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);\r\n }\r\n\r\n /**\r\n * Sets the authorization token used to communicate with the service.\r\n * @member DialogServiceConnector.prototype.authorizationToken\r\n * @function\r\n * @public\r\n * @param {string} token - Authorization token.\r\n */\r\n public set authorizationToken(token: string) {\r\n Contracts.throwIfNullOrWhitespace(token, \"token\");\r\n this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token);\r\n }\r\n\r\n /**\r\n * The collection of properties and their values defined for this DialogServiceConnector.\r\n * @member DialogServiceConnector.prototype.properties\r\n * @function\r\n * @public\r\n * @returns {PropertyCollection} The collection of properties and their values defined for this DialogServiceConnector.\r\n */\r\n public get properties(): PropertyCollection {\r\n return this.privProperties;\r\n }\r\n\r\n /** Gets the template for the activity generated by service from speech.\r\n * Properties from the template will be stamped on the generated activity.\r\n * It can be empty\r\n */\r\n public get speechActivityTemplate(): string {\r\n return this.properties.getProperty(PropertyId.Conversation_Speech_Activity_Template);\r\n }\r\n\r\n /** Sets the template for the activity generated by service from speech.\r\n * Properties from the template will be stamped on the generated activity.\r\n * It can be null or empty.\r\n * Note: it has to be a valid Json object.\r\n */\r\n public set speechActivityTemplate(speechActivityTemplate: string) {\r\n this.properties.setProperty(PropertyId.Conversation_Speech_Activity_Template, speechActivityTemplate);\r\n }\r\n\r\n /**\r\n * Starts recognition and stops after the first utterance is recognized.\r\n * @member DialogServiceConnector.prototype.listenOnceAsync\r\n * @function\r\n * @public\r\n * @param cb - Callback that received the result when the reco has completed.\r\n * @param err - Callback invoked in case of an error.\r\n */\r\n public listenOnceAsync(cb?: (e: SpeechRecognitionResult) => void, err?: (e: string) => void): void {\r\n if (this.isTurnComplete) {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n const callbackHolder = async (): Promise => {\r\n await this.privReco.connect();\r\n await this.implRecognizerStop();\r\n this.isTurnComplete = false;\r\n\r\n const ret: Deferred = new Deferred();\r\n await this.privReco.recognize(RecognitionMode.Conversation, ret.resolve, ret.reject);\r\n\r\n const e: SpeechRecognitionResult = await ret.promise;\r\n await this.implRecognizerStop();\r\n\r\n return e;\r\n };\r\n\r\n const retPromise: Promise = callbackHolder();\r\n\r\n retPromise.catch(() => {\r\n // Destroy the recognizer.\r\n /* tslint:disable:no-empty */ // We've done all we can here.\r\n this.dispose(true).catch(() => { });\r\n });\r\n\r\n marshalPromiseToCallbacks(retPromise.finally((): void => {\r\n this.isTurnComplete = true;\r\n }), cb, err);\r\n }\r\n }\r\n\r\n public sendActivityAsync(activity: string, cb?: () => void, errCb?: (error: string) => void): void {\r\n marshalPromiseToCallbacks((this.privReco as DialogServiceAdapter).sendMessage(activity), cb, errCb);\r\n }\r\n\r\n /**\r\n * closes all external resources held by an instance of this class.\r\n * @member DialogServiceConnector.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(cb?: () => void, err?: (error: string) => void): void {\r\n Contracts.throwIfDisposed(this.privIsDisposed);\r\n\r\n marshalPromiseToCallbacks(this.dispose(true), cb, err);\r\n }\r\n\r\n protected async dispose(disposing: boolean): Promise {\r\n if (this.privIsDisposed) {\r\n return;\r\n }\r\n\r\n if (disposing) {\r\n this.privIsDisposed = true;\r\n await this.implRecognizerStop();\r\n await super.dispose(disposing);\r\n }\r\n }\r\n\r\n protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {\r\n return new RecognizerConfig(speechConfig, this.privProperties);\r\n }\r\n\r\n protected createServiceRecognizer(\r\n authentication: IAuthentication,\r\n connectionFactory: IConnectionFactory,\r\n audioConfig: AudioConfig,\r\n recognizerConfig: RecognizerConfig): ServiceRecognizerBase {\r\n\r\n const audioSource: AudioConfigImpl = audioConfig as AudioConfigImpl;\r\n\r\n return new DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this);\r\n }\r\n\r\n private buildAgentConfig(): IAgentConfig {\r\n const communicationType = this.properties.getProperty(\"Conversation_Communication_Type\", \"Default\");\r\n\r\n return {\r\n botInfo: {\r\n commType: communicationType,\r\n commandsCulture: undefined,\r\n connectionId: this.properties.getProperty(PropertyId.Conversation_Agent_Connection_Id),\r\n conversationId: this.properties.getProperty(PropertyId.Conversation_Conversation_Id, undefined),\r\n fromId: this.properties.getProperty(PropertyId.Conversation_From_Id, undefined),\r\n ttsAudioFormat: this.properties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)\r\n },\r\n version: 0.2\r\n };\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nexport { AudioConfig } from \"./Audio/AudioConfig\";\r\nexport { AudioStreamFormat } from \"./Audio/AudioStreamFormat\";\r\nexport { AudioInputStream, PullAudioInputStream, PushAudioInputStream } from \"./Audio/AudioInputStream\";\r\nexport { AudioOutputStream, PullAudioOutputStream, PushAudioOutputStream} from \"./Audio/AudioOutputStream\";\r\nexport { CancellationReason } from \"./CancellationReason\";\r\nexport { PullAudioInputStreamCallback } from \"./Audio/PullAudioInputStreamCallback\";\r\nexport { PushAudioOutputStreamCallback } from \"./Audio/PushAudioOutputStreamCallback\";\r\nexport { KeywordRecognitionModel } from \"./KeywordRecognitionModel\";\r\nexport { SessionEventArgs } from \"./SessionEventArgs\";\r\nexport { RecognitionEventArgs } from \"./RecognitionEventArgs\";\r\nexport { OutputFormat } from \"./OutputFormat\";\r\nexport { IntentRecognitionEventArgs } from \"./IntentRecognitionEventArgs\";\r\nexport { RecognitionResult } from \"./RecognitionResult\";\r\nexport { SpeechRecognitionResult } from \"./SpeechRecognitionResult\";\r\nexport { IntentRecognitionResult } from \"./IntentRecognitionResult\";\r\nexport { LanguageUnderstandingModel } from \"./LanguageUnderstandingModel\";\r\nexport { SpeechRecognitionEventArgs, ConversationTranscriptionEventArgs } from \"./SpeechRecognitionEventArgs\";\r\nexport { SpeechRecognitionCanceledEventArgs } from \"./SpeechRecognitionCanceledEventArgs\";\r\nexport { TranslationRecognitionEventArgs } from \"./TranslationRecognitionEventArgs\";\r\nexport { TranslationSynthesisEventArgs } from \"./TranslationSynthesisEventArgs\";\r\nexport { TranslationRecognitionResult } from \"./TranslationRecognitionResult\";\r\nexport { TranslationSynthesisResult } from \"./TranslationSynthesisResult\";\r\nexport { ResultReason } from \"./ResultReason\";\r\nexport { SpeechConfig, SpeechConfigImpl } from \"./SpeechConfig\";\r\nexport { SpeechTranslationConfig, SpeechTranslationConfigImpl } from \"./SpeechTranslationConfig\";\r\nexport { PropertyCollection } from \"./PropertyCollection\";\r\nexport { PropertyId } from \"./PropertyId\";\r\nexport { Recognizer } from \"./Recognizer\";\r\nexport { SpeechRecognizer } from \"./SpeechRecognizer\";\r\nexport { IntentRecognizer } from \"./IntentRecognizer\";\r\nexport { VoiceProfileType } from \"./VoiceProfileType\";\r\nexport { TranslationRecognizer } from \"./TranslationRecognizer\";\r\nexport { Translations } from \"./Translations\";\r\nexport { NoMatchReason } from \"./NoMatchReason\";\r\nexport { NoMatchDetails } from \"./NoMatchDetails\";\r\nexport { TranslationRecognitionCanceledEventArgs } from \"./TranslationRecognitionCanceledEventArgs\";\r\nexport { IntentRecognitionCanceledEventArgs } from \"./IntentRecognitionCanceledEventArgs\";\r\nexport { CancellationDetailsBase } from \"./CancellationDetailsBase\";\r\nexport { CancellationDetails } from \"./CancellationDetails\";\r\nexport { CancellationErrorCode } from \"./CancellationErrorCodes\";\r\nexport { ConnectionEventArgs } from \"./ConnectionEventArgs\";\r\nexport { ServiceEventArgs } from \"./ServiceEventArgs\";\r\nexport { Connection } from \"./Connection\";\r\nexport { PhraseListGrammar } from \"./PhraseListGrammar\";\r\nexport { DialogServiceConfig } from \"./DialogServiceConfig\";\r\nexport { BotFrameworkConfig } from \"./BotFrameworkConfig\";\r\nexport { CustomCommandsConfig } from \"./CustomCommandsConfig\";\r\nexport { DialogServiceConnector } from \"./DialogServiceConnector\";\r\nexport { ActivityReceivedEventArgs } from \"./ActivityReceivedEventArgs\";\r\nexport { TurnStatusReceivedEventArgs } from \"./TurnStatusReceivedEventArgs\";\r\nexport { ServicePropertyChannel } from \"./ServicePropertyChannel\";\r\nexport { ProfanityOption } from \"./ProfanityOption\";\r\nexport { BaseAudioPlayer } from \"./Audio/BaseAudioPlayer\";\r\nexport { ConnectionMessageEventArgs } from \"./ConnectionMessageEventArgs\";\r\nexport { ConnectionMessage } from \"./ConnectionMessage\";\r\nexport { VoiceProfile } from \"./VoiceProfile\";\r\nexport { VoiceProfileEnrollmentResult, VoiceProfileEnrollmentCancellationDetails } from \"./VoiceProfileEnrollmentResult\";\r\nexport { VoiceProfileResult, VoiceProfileCancellationDetails } from \"./VoiceProfileResult\";\r\nexport { VoiceProfileAuthorizationPhraseResult } from \"./VoiceProfileAuthorizationPhraseResult\";\r\nexport { VoiceProfileClient } from \"./VoiceProfileClient\";\r\nexport { SpeakerRecognizer } from \"./SpeakerRecognizer\";\r\nexport { SpeakerIdentificationModel } from \"./SpeakerIdentificationModel\";\r\nexport { SpeakerVerificationModel } from \"./SpeakerVerificationModel\";\r\nexport { AutoDetectSourceLanguageConfig } from \"./AutoDetectSourceLanguageConfig\";\r\nexport { AutoDetectSourceLanguageResult } from \"./AutoDetectSourceLanguageResult\";\r\nexport { SourceLanguageConfig } from \"./SourceLanguageConfig\";\r\nexport { SpeakerRecognitionResult, SpeakerRecognitionResultType, SpeakerRecognitionCancellationDetails } from \"./SpeakerRecognitionResult\";\r\nexport { Conversation,\r\n ConversationExpirationEventArgs,\r\n ConversationInfo,\r\n ConversationParticipantsChangedEventArgs,\r\n ConversationTranslationCanceledEventArgs,\r\n ConversationTranslationEventArgs,\r\n ConversationTranslationResult,\r\n ConversationTranslator,\r\n ConversationTranscriber,\r\n IParticipant,\r\n Participant,\r\n ParticipantChangedReason,\r\n User,\r\n VoiceSignature\r\n } from \"./Transcription/Exports\";\r\nexport { SpeechSynthesisOutputFormat } from \"./SpeechSynthesisOutputFormat\";\r\nexport { SpeechSynthesizer } from \"./SpeechSynthesizer\";\r\nexport { SpeechSynthesisResult } from \"./SpeechSynthesisResult\";\r\nexport { SpeechSynthesisEventArgs } from \"./SpeechSynthesisEventArgs\";\r\nexport { SpeechSynthesisWordBoundaryEventArgs } from \"./SpeechSynthesisWordBoundaryEventArgs\";\r\nexport { SpeechSynthesisBookmarkEventArgs } from \"./SpeechSynthesisBookmarkEventArgs\";\r\nexport { SpeechSynthesisVisemeEventArgs } from \"./SpeechSynthesisVisemeEventArgs\";\r\nexport { IPlayer } from \"./Audio/IPlayer\";\r\nexport { SpeakerAudioDestination } from \"./Audio/SpeakerAudioDestination\";\r\nexport { CancellationEventArgs } from \"./CancellationEventArgs\";\r\nexport { ConversationTranscriptionCanceledEventArgs } from \"./ConversationTranscriptionCanceledEventArgs\";\r\nexport { PronunciationAssessmentGradingSystem } from \"./PronunciationAssessmentGradingSystem\";\r\nexport { PronunciationAssessmentGranularity } from \"./PronunciationAssessmentGranularity\";\r\nexport { PronunciationAssessmentConfig } from \"./PronunciationAssessmentConfig\";\r\nexport { PronunciationAssessmentResult } from \"./PronunciationAssessmentResult\";\r\n"],"names":["safeIsNaN","Number","isNaN","value","areInputsEqual","newInputs","lastInputs","length","i","first","second","memoizeOne","resultFn","isEqual","cache","memoized","newArgs","_i","arguments","lastThis","this","lastArgs","lastResult","apply","clear","createGuid","uuid","createNoDashGuid","replace","RegExp","toUpperCase","EventType","PlatformEvent","constructor","eventName","eventType","privName","privEventId","privEventTime","Date","toISOString","privEventType","privMetadata","name","eventId","eventTime","metadata","PropertyId","RecognitionMode","SpeechResultFormat","connectivity","type","PromiseState","ArgumentNullError","Error","argumentName","super","message","InvalidOperationError","error","ObjectDisposedError","objectName","EventSource","privEventListeners","privIsDisposed","onEvent","event","isDisposed","paramName","attach","onEventCallback","id","detach","Promise","resolve","attachListener","listener","dispose","Events","instance","privInstance","setEventSource","eventSource","RiffPcmEncoder","actualSampleRate","desiredSampleRate","encode","actualAudioFrame","audioFrame","downSampleAudioFrame","privActualSampleRate","privDesiredSampleRate","audioLength","buffer","ArrayBuffer","view","DataView","floatTo16BitPCM","setString","offset","str","setUint8","charCodeAt","input","s","Math","max","min","setInt16","srcFrame","srcRate","dstRate","ratio","dstLength","round","dstFrame","Float32Array","srcOffset","dstOffset","nextSrcOffset","accum","count","PcmRecorder","record","context","mediaStream","outputStream","scriptNode","bufferSize","createScriptProcessor","audioSampleRate","sampleRate","waveStreamEncoder","needHeader","onaudioprocess","inputFrame","inputBuffer","getChannelData","isClosed","waveFrame","writeStreamChunk","isEnd","timeReceived","now","micInput","createMediaStreamSource","privSpeechProcessorScript","audioWorklet","addModule","then","workletNode","AudioWorkletNode","port","onmessage","ev","data","connect","destination","privMediaResources","scriptProcessorNode","source","stream","catch","releaseMediaResources","disconnect","getTracks","forEach","track","stop","setWorkletUrl","url","RecognizerConfig","speechServiceConfig","parameters","privRecognitionMode","Interactive","privSpeechServiceConfig","SpeechServiceConfig","Context","privParameters","privMaxRetryCount","parseInt","getProperty","recognitionMode","privRecognitionActivityTimeout","Recognition","recognitionActivityTimeout","isContinuousRecognition","autoDetectSourceLanguages","SpeechServiceConnection_AutoDetectSourceLanguages","undefined","maxRetryCount","serialize","JSON","stringify","key","replacement","k","Object","hasOwnProperty","call","charAt","toLowerCase","substring","recognition","os","system","System","version","build","lang","OS","platform","Deferred","result","privResolve","reject","privReject","privPromise","promise","marshalPromiseToCallbacks","cb","err","val","typedError","AudioSourceEvent","audioSourceId","Info","privAudioSourceId","AudioSourceInitializingEvent","AudioSourceReadyEvent","AudioSourceOffEvent","AudioSourceErrorEvent","privError","AudioStreamNodeEvent","audioNodeId","privAudioNodeId","AudioStreamNodeAttachingEvent","AudioStreamNodeAttachedEvent","AudioStreamNodeDetachedEvent","AudioStreamNodeErrorEvent","List","list","privSubscriptionIdCounter","privAddSubscriptions","privRemoveSubscriptions","privDisposedSubscriptions","privDisposeReason","get","itemIndex","throwIfDisposed","privList","last","add","item","insertAt","index","unshift","push","splice","triggerSubscriptions","removeFirst","removeAt","removeLast","remove","removedElements","onAdded","addedCallback","subscriptionId","onRemoved","removedCallback","onDisposed","disposedCallback","join","seperator","toArray","cloneCopy","Array","any","callback","where","all","select","selectList","filteredList","orderBy","compareFn","orderedArray","sort","orderByDesc","a","b","clone","concat","concatArray","array","reason","subscriptions","SubscriberType","Queue","privPromiseStore","privIsDrainInProgress","privIsDisposing","enqueue","throwIfDispose","enqueueFromPromise","dequeue","deferredSubscriber","privSubscribers","deferral","Dequeue","drain","peek","Peek","subs","lists","subscriber","dequeuedItem","privDetachables","drainAndDispose","pendingItemProcessor","detachable","promiseArray","wrapper","finally","AudioFormatTag","Stream","streamId","privIsWriteEnded","privIsReadEnded","read","privReaderQueue","streamChunk","__awaiter","readEnded","throwIfClosed","privId","isReadEnded","close","e","ChunkedArrayBufferStream","targetChunkSize","privTargetChunkSize","privNextBufferReadyBytes","chunk","byteLength","bytesCopiedFromBuffer","privNextBufferToWrite","privNextBufferStartTime","bytesToCopy","targetView","Uint8Array","sourceView","slice","set","AudioStreamFormat","getDefaultInputFormat","AudioStreamFormatImpl","getWaveFormatPCM","samplesPerSecond","bitsPerSample","channels","samplesPerSec","format","PCM","formatTag","ALaw","MuLaw","avgBytesPerSec","blockAlign","privHeader","setUint32","setUint16","getAudioContext","AudioContext","window","webkitAudioContext","navigator","mediaDevices","getSupportedConstraints","header","MicAudioSource","privRecorder","deviceId","privStreams","turnOn","privInitializeDeferral","createAudioContext","nav","getUserMedia","webkitGetUserMedia","mozGetUserMedia","msGetUserMedia","constraints","successCallback","errorCallback","next","privMediaStream","active","audio","video","errorMsg","privContext","state","resume","listen","turnOff","privOutputChunkSize","privEvents","AUDIOFORMAT","blob","destroyAudioContext","events","deviceInfo","getMicrophoneLabel","label","bitspersample","channelcount","Unknown","manufacturer","model","samplerate","Microphones","setProperty","defaultMicrophoneName","privMicrophoneLabel","microphoneDeviceId","getSettings","deferred","enumerateDevices","devices","device","hasClose","suspend","FileAudioSource","file","filename","privHeaderEnd","privFilename","lastIndexOf","upload","privSource","Blob","privAudioFormatPromise","readHeader","File","headerResult","processHeader","getWord","String","fromCharCode","getUint8","formatSize","getInt32","channelCount","getUint16","getUint32","pos","maxHeaderSize","reader","FileReader","onload","target","readAsArrayBuffer","h","byteOffset","onerror","processFile","buff","toString","fileBuffer","c","Contracts","throwIfNullOrUndefined","param","throwIfNull","throwIfNullOrWhitespace","trim","throwIfArrayEmptyOrWhitespace","throwIfFileDoesNotExist","throwIfNotUndefined","PullAudioInputStreamCallback","MessageType","ConnectionState","CancellationReason","CancellationErrorCode","ResultReason","SpeechSynthesisOutputFormat","AudioInputStream","createPushStream","PushAudioInputStream","create","createPullStream","PullAudioInputStream","PushAudioInputStreamImpl","privFormat","privStream","write","dataBuffer","audioNode","bufferData","Buffer","from","readCycle","audioStreamChunk","XMLHttpRequest","toBuffer","arrayBuffer","buf","alloc","PullAudioInputStreamImpl","privCallback","privIsClosed","privBufferSize","transmitBuff","totalBytes","readBuff","pulledBytes","Int8Array","ConnectionMessage","messageType","body","headers","privBody","Text","Binary","privMessageType","privHeaders","privSize","binaryBody","textBody","ServiceEvent","jsonstring","privJsonResult","jsonString","ConnectionEvent","connectionId","privConnectionId","ConnectionStartEvent","uri","privUri","ConnectionEstablishedEvent","ConnectionClosedEvent","statusCode","Debug","privReason","privStatusCode","ConnectionErrorEvent","privMessage","privType","ConnectionEstablishErrorEvent","statuscode","ConnectionMessageReceivedEvent","networkReceivedTimeISO","privNetworkReceivedTime","networkReceivedTime","ConnectionMessageSentEvent","networkSentTimeISO","privNetworkSentTime","networkSentTime","SpeechSynthesisEventArgs","privResult","SpeechSynthesisResult","resultId","audioData","errorDetails","properties","privResultId","privAudioData","privErrorDetails","privProperties","PropertyCollection","privKeys","privValues","def","keyToUse","n","clonedMap","mergeTo","destinationCollection","SpeechSynthesisWordBoundaryEventArgs","audioOffset","text","wordLength","textOffset","privAudioOffset","privText","privWordLength","privTextOffset","SpeechSynthesisBookmarkEventArgs","SpeechSynthesisVisemeEventArgs","visemeId","animation","privVisemeId","privAnimation","AudioOutputFormatImpl","audioFormatString","requestAudioFormatString","hasHeader","priAudioFormatString","priRequestAudioFormatString","priHasHeader","fromSpeechSynthesisOutputFormat","speechSynthesisOutputFormat","getDefaultOutputFormat","fromSpeechSynthesisOutputFormatString","SpeechSynthesisOutputFormatToString","speechSynthesisOutputFormatString","Siren","MP3","SILKSkype","OGG_OPUS","WEBM_OPUS","updateHeader","Raw8Khz8BitMonoMULaw","Riff16Khz16KbpsMonoSiren","Audio16Khz16KbpsMonoSiren","Audio16Khz32KBitRateMonoMp3","Audio16Khz128KBitRateMonoMp3","Audio16Khz64KBitRateMonoMp3","Audio24Khz48KBitRateMonoMp3","Audio24Khz96KBitRateMonoMp3","Audio24Khz160KBitRateMonoMp3","Raw16Khz16BitMonoTrueSilk","Riff16Khz16BitMonoPcm","Riff8Khz16BitMonoPcm","Riff24Khz16BitMonoPcm","Riff8Khz8BitMonoMULaw","Raw16Khz16BitMonoPcm","Raw24Khz16BitMonoPcm","Raw8Khz16BitMonoPcm","Ogg16Khz16BitMonoOpus","Ogg24Khz16BitMonoOpus","Raw48Khz16BitMonoPcm","Riff48Khz16BitMonoPcm","Audio48Khz96KBitRateMonoMp3","Audio48Khz192KBitRateMonoMp3","Ogg48Khz16BitMonoOpus","Webm16Khz16BitMonoOpus","Webm24Khz16BitMonoOpus","Raw24Khz16BitMonoTrueSilk","Raw8Khz8BitMonoALaw","Riff8Khz8BitMonoALaw","AudioOutputStream","PullAudioOutputStream","PullAudioOutputStreamImpl","intView","privLastChunkView","tmpBuffer","PushAudioOutputStream","PushAudioOutputStreamImpl","SpeechSynthesisEvent","requestId","privRequestId","SynthesisTriggeredEvent","sessionAudioDestinationId","turnAudioDestinationId","privSessionAudioDestinationId","privTurnAudioDestinationId","audioSessionDestinationId","audioTurnDestinationId","ConnectingToSynthesisServiceEvent","authFetchEventId","privAuthFetchEventId","SynthesisStartedEvent","SynthesisTurn","privIsSynthesizing","privIsSynthesisEnded","privBytesReceived","privInTurn","privNextSearchTextIndex","onPreConnectionStart","onAuthCompleted","isError","onComplete","onConnectionEstablishCompleted","onServiceResponseMessage","responseJson","response","parse","onServiceTurnEndResponse","privTurnDeferral","onServiceTurnStartResponse","privAudioOutputStream","privTurnAudioDestination","privStreamId","audioOutputFormat","privAudioOutputFormat","turnCompletionPromise","isSynthesisEnded","isSynthesizing","currentTextOffset","bytesReceived","getAllReceivedAudio","privReceivedAudio","readAllAudioFromStream","getAllReceivedAudioWithHeader","privReceivedAudioWithHeader","SynthesisAdapterBase","addHeader","startNewSynthesis","rawText","isSSML","audioDestination","privRawText","privIsSSML","privPartialVisemeAnimation","onAudioChunkReceived","onWordBoundaryEvent","updateTextOffset","onVisemeMetadataReceived","Data","AnimationChunk","onStopSynthesizing","getAndClearVisemeAnimation","indexOf","SynthesisContext","speechSynthesizer","privSpeechSynthesizer","setSection","sectionName","toJSON","synthesisSection","buildSynthesisContext","metadataOptions","bookmarkEnabled","bookmarkReached","sentenceBoundaryEnabled","visemeEnabled","visemeReceived","wordBoundaryEnabled","wordBoundary","outputFormat","language","autoDetection","autoDetectSourceLanguage","AgentConfig","toJsonString","iPrivConfig","OutputFormatPropertyName","CancellationErrorCodePropertyName","ServicePropertiesPropertyName","ForceDictationPropertyName","AutoDetectSourceLanguagesOpenRangeOptionName","MetadataType","SynthesisAudioMetadata","json","privSynthesisAudioMetadata","fromJSON","Metadata","HeaderNames","AuthKey","ConnectionId","ContentType","CustomCommandsAppId","Path","RequestId","RequestStreamId","RequestTimestamp","SpeechConnectionMessage","path","contentType","additionalHeaders","headerName","privPath","privContentType","privAdditionalHeaders","fromConnectionMessage","requestTimestamp","authentication","connectionFactory","synthesizerConfig","speakOverride","receiveMessageOverride","connectImplOverride","configConnectionOverride","sendSynthesisContext","connection","synthesisContextJson","synthesisContext","send","privSynthesisTurn","sendSpeechServiceConfig","SpeechServiceConfigJson","sendSsmlMessage","ssml","privAuthentication","privConnectionFactory","privSynthesizerConfig","privSessionAudioDestination","privConnectionEvents","privServiceEvents","privSynthesisContext","privAgentConfig","connectionEvents","connectionEvent","connectionClosedEvent","cancelSynthesisLocal","BadRequestParameters","ConnectionFailure","agentConfig","serviceEvents","activityTemplate","messagePayload","privActivityTemplate","tmp","privConnectionConfigurationPromise","connectImpl","sendNetworkMessage","payload","fetchConnection","Speak","errorCallBack","buildSsml","privSuccessCallback","privErrorCallback","synthesisStartEventArgs","SynthesizingAudioStarted","synthesisStarted","receiveMessage","cancelSynthesis","cancellationReason","errorCode","Canceled","SynthesisCanceled","cancelEvent","_a","_b","processTypeSpecificMessages","connectionMessage","privServiceHasSentMessage","synthesizing","audioWithHeader","SynthesizingAudio","metadataList","Type","WordBoundary","wordBoundaryEventArgs","Offset","Length","Bookmark","bookmarkEventArgs","Viseme","IsLastAnimation","visemeEventArgs","VisemeId","audioBuffer","SynthesizingAudioCompleted","synthesisCompleted","isUnAuthorized","privConnectionPromise","Disconnected","authPromise","fetchOnExpiry","fetch","open","SpeechServiceConnection_Endpoint","configureConnection","telemetryDataEnabled","BackgroundEvent","AudioFormatToMimeType","SpeakerAudioDestination","audioDestinationId","privPlaybackStarted","privAppendingToBuffer","privMediaSourceOpened","privIsPaused","privAudioBuffer","updateSourceBuffer","privSourceBuffer","handleSourceBufferUpdateEnd","receivedAudio","_","audioBlob","privAudio","src","URL","createObjectURL","notifyPlayback","console","warn","onAudioEnd","mimeType","MediaSource","isTypeSupported","Audio","privMediaSource","load","onsourceopen","duration","addSourceBuffer","onupdate","onupdateend","onupdatestart","currentTime","pause","play","internalAudio","sourceBufferAvailable","binary","shift","appendBuffer","log","canEndStream","endOfStream","onAudioStart","onended","readyState","updating","PushAudioOutputStreamCallback","OutputFormat","ProfanityOption","RecognitionCompletionStatus","AudioFileWriter","fs","privFd","privAudioFormat","headerOffset","privWriteStream","fd","start","autoClose","on","bytesWritten","end","AudioConfig","fromDefaultMicrophoneInput","pcmRecorder","AudioConfigImpl","fromMicrophoneInput","fromWavFileInput","fromStreamInput","audioStream","MediaStream","fromDefaultSpeakerOutput","AudioOutputConfigImpl","fromSpeakerOutput","player","fromAudioFileOutput","fromStreamOutput","privDestination","KeywordRecognitionModel","privDisposed","fromFile","fileName","fromStream","SessionEventArgs","sessionId","privSessionId","RecognitionEventArgs","privOffset","IntentRecognitionEventArgs","RecognitionResult","languageDetectionConfidence","privDuration","privLanguage","privLanguageDetectionConfidence","privJson","SpeechRecognitionResult","speakerId","privSpeakerId","IntentRecognitionResult","intentId","privIntentId","LanguageUnderstandingModel","fromEndpoint","hostname","langModelImp","LanguageUnderstandingModelImpl","firstDot","host","region","substr","lastSegment","pathname","appId","subscriptionKey","searchParams","fromAppId","fromSubscription","SpeechRecognitionEventArgs","ConversationTranscriptionEventArgs","CancellationEventArgsBase","privErrorCode","SpeechRecognitionCanceledEventArgs","TranslationRecognitionEventArgs","TranslationSynthesisEventArgs","TranslationRecognitionResult","translations","privTranslations","TranslationSynthesisResult","SpeechConfig","speechImpl","SpeechConfigImpl","SpeechServiceConnection_Region","SpeechServiceConnection_IntentRegion","SpeechServiceConnection_Key","endpoint","href","fromHost","hostName","SpeechServiceConnection_Host","protocol","fromAuthorizationToken","authorizationToken","speechRecognitionLanguage","Simple","endPoint","SpeechServiceAuthorization_Token","SpeechServiceConnection_RecoLanguage","endpointId","SpeechServiceConnection_EndpointId","setProxy","proxyHostName","proxyPort","proxyUserName","proxyPassword","SpeechServiceConnection_ProxyHostName","SpeechServiceConnection_ProxyPort","SpeechServiceConnection_ProxyUserName","SpeechServiceConnection_ProxyPassword","setServiceProperty","channel","currentProperties","setProfanity","profanity","SpeechServiceResponse_ProfanityOption","enableAudioLogging","SpeechServiceConnection_EnableAudioLogging","requestWordLevelTimestamps","SpeechServiceResponse_RequestWordLevelTimestamps","enableDictation","ret","speechSynthesisLanguage","SpeechServiceConnection_SynthLanguage","speechSynthesisVoiceName","SpeechServiceConnection_SynthVoice","voice","SpeechServiceConnection_SynthOutputFormat","SpeechTranslationConfig","SpeechTranslationConfigImpl","privSpeechProperties","addTargetLanguage","languages","targetLanguages","SpeechServiceConnection_TranslationToLanguages","split","voiceName","SpeechServiceConnection_TranslationVoice","ReplayableAudioNode","audioSource","bytesPerSecond","privBuffers","privReplayOffset","privLastShrinkOffset","privBufferStartOffset","privBufferSerial","privBufferedBytes","privReplay","privLastChunkAcquiredTime","privAudioNode","privBytesPerSecond","offsetToSeek","bytesToSeek","retVal","BufferEntry","replay","shrinkBuffers","findTimeAtOffset","startOffset","endOffset","serial","Timeout","workerTimers","clearTimeout","timerId","timers","setTimeout","func","delay","scheduledTimeoutFunctions","Map","unhandledRequests","worker","Worker","addEventListener","_ref","isCallNotification","params","idOrFunc","unhandledTimerId","delete","isClearResponse","random","postMessage","method","performance","loadWorkerTimers","revokeObjectURL","SpeechRecognitionEvent","RecognitionTriggeredEvent","ListeningStartedEvent","ConnectingToServiceEvent","authFetchEventid","privAuthFetchEventid","RecognitionStartedEvent","ServiceTelemetryListener","privListeningTriggerMetric","privMicMetric","privConnectionEstablishMetric","End","Name","Start","privMicStartTime","privConnectionStartTime","Id","getConnectionError","privReceivedMessages","getTelemetry","metrics","privPhraseLatencies","PhraseLatencyMs","privHypothesisLatencies","FirstHypothesisLatencyMs","telemetry","Metrics","ReceivedMessages","phraseReceived","audioReceivedTime","hypothesisReceived","hasTelemetry","keys","RequestSession","privIsAudioNodeDetached","privIsRecognizing","privIsSpeechEnded","privTurnStartAudioOffset","privLastRecoOffset","privHypothesisReceived","privBytesSent","privRecogNumber","privConnectionAttempts","privServiceTelemetryListener","isSpeechEnded","isRecognizing","currentTurnAudioOffset","recogNumber","numConnectionAttempts","bytesSent","listenForServiceTelemetry","startNewRecognition","onAudioSourceAttachCompleted","continuousRecognition","onHypothesis","onPhraseRecognized","onServiceRecognized","onAudioSent","onRetryConnection","onStopRecognizing","onSpeechEnded","detachAudioNode","DynamicGrammarBuilder","addPhrase","phrase","privPhrases","clearPhrases","addReferenceGrammar","grammar","privGrammars","clearGrammars","generateGrammarObject","retObj","ReferenceGrammars","retPhrases","Groups","Items","SpeechContext","dynamicGrammar","privDynamicGrammar","setPronunciationAssessmentParams","phraseDetection","enrichment","pronunciationAssessment","phraseOutput","detailed","options","dgi","SpeechDetected","privSpeechStartDetected","ServiceRecognizerBase","recognizerConfig","recognizer","privSetTimeout","privIsLiveAudio","recognizeOverride","disconnectOverride","sendSpeechContext","speechContextJson","speechContext","privRequestSession","sendPrePayloadJSONOverride","postConnectImplOverride","requestSession","privRecognizerConfig","DisableReferenceChannel","MicSpec","privMustReportEndOfStream","privAudioSource","privRecognizer","privSpeechContext","cancelRecognitionLocal","conversationTranslatorToken","token","ConversationTranslator_Token","auth","recognize","recoMode","conPromise","audioStreamNode","sessionStartEventArgs","sessionStarted","sendAudio","RuntimeError","stopRecognizing","sendFinalAudio","connectAsync","NoError","sendMessage","sendTelemetryData","telemetryData","cancelRecognition","speechStartDetected","speechStartEventArgs","speechStopDetected","speechStopEventArgs","speechEndDetected","EndOfStream","sessionStopEventArgs","sessionStopped","sendPrePayloadJSON","sendWaveHeader","retryableConnect","audioFormat","nextSendTime","fastLaneSizeMs","maxSendUnthrottledBytes","startRecogNumber","readAndUploadCycle","sendDelay","lastStatusCode","lastReason","delayMs","writeBufferToConsole","out","readView","padStart","info","AuthInfo","privHeaderName","privToken","CognitiveSubscriptionKeyAuthentication","privAuthInfo","AuthHeader","CognitiveTokenAuthentication","fetchCallback","fetchOnExpiryCallback","privFetchCallback","privFetchOnExpiryCallback","Recognizer","audioConfig","implCommonRecognizerSetup","errorCb","internalData","privReco","disposing","telemetryEnabled","enableTelemetry","enabled","osPlatform","osName","osVersion","userAgent","appVersion","createRecognizerConfig","createServiceRecognizer","getAuthFromProperties","recognizeOnceAsyncImpl","implRecognizerStop","startContinuousRecognitionAsyncImpl","stopContinuousRecognitionAsyncImpl","ConnectionOpenResponse","RawWebsocketMessage","privPayload","__proto__","textContent","binaryContent","OCSPEvent","signature","privSignature","OCSPMemoryCacheHitEvent","OCSPCacheMissEvent","OCSPDiskCacheHitEvent","OCSPCacheUpdateNeededEvent","OCSPMemoryCacheStoreEvent","OCSPDiskCacheStoreEvent","OCSPCacheUpdatehCompleteEvent","OCSPStapleReceivedEvent","OCSPCacheEntryExpiredEvent","serialNumber","expireTime","privExpireTime","OCSPCacheEntryNeedsRefreshEvent","startTime","privStartTime","OCSPCacheHitEvent","privExpireTimeString","toLocaleDateString","privStartTimeString","toLocaleTimeString","OCSPVerificationFailedEvent","OCSPCacheFetchErrorEvent","OCSPResponseRetrievedEvent","OCSPCacheUpdateErrorEvent","CertCheckAgent","proxyInfo","privProxyInfo","privDiskCache","Cache","supportBuffer","location","process","SPEECH_OCSP_CACHE_ROOT","forceReinitDiskCache","privMemCache","GetAgent","disableStapling","agent","Agent","CreateConnection","HostName","Port","GetProxyAgent","httpProxyOptions","UserName","Password","requestOCSP","HttpsProxyAgent","OCSPCheck","socketPromise","ocspRequest","stapling","resolved","socket","cork","tlsSocket","destroy","peer","getPeerCertificate","issuer","GetIssuer","ocsp","generate","raw","sig","cacheEntry","GetResponseFromCache","VerifyOCSPResponse","uncork","issuerCertificate","fetchIssuer","cachedResponse","diskCacheResponse","isCached","StoreMemoryCacheEntry","tbsData","parseResponse","tbsResponseData","responses","cachedStartTime","thisUpdate","cachedNextTime","nextUpdate","testTimeOffset","minUpdate","UpdateCache","cacheValue","ocspResponse","certID","GetOCSPResponse","request","StoreCacheEntry","req","rawResponse","StoreDiskCacheEntry","getAuthorityInfo","cert","parsedUri","assign","getResponse","enableOCSP","NODE_TLS_REJECT_UNAUTHORIZED","SPEECH_CONDUCT_OCSP_CHECK","secureEndpoint","forceDisableOCSPStapling","servername","baseAgent","tls","net","WebsocketMessageAdapter","messageFormatter","enableCompression","privConnectionState","privConnectionEstablishDeferral","privCertificateValidatedDeferral","Connecting","WebSocket","forceNpmWebSocket","perMessageDeflate","privEnableCompression","checkAgent","privWebsocketClient","ws","binaryType","privReceivingMessageQueue","privDisconnectDeferral","privSendMessageQueue","processSendQueue","onopen","Connected","privLastErrorReceived","onclose","code","onClose","rawMessage","privMessageFormatter","toConnectionMessage","messageSendStatusDeferral","messageSendDeferral","Message","sendStatusDeferral","sendRawMessage","sendItem","isWebsocketOpen","stack","None","closeReason","pendingReceiveItem","pendingSendItem","itemToSend","sendError","OPEN","WebsocketConnection","queryParameters","privConnectionMessageAdapter","queryParams","encodeURIComponent","ProxyInfo","privProxyHostName","privProxyPort","privProxyUserName","privProxyPassword","fromParameters","fromRecognizerConfig","config","QueryParameterNames","BotId","CustomSpeechDeploymentId","CustomVoiceDeploymentId","EnableAudioLogging","EnableLanguageId","EnableWordLevelTimestamps","EndSilenceTimeoutMs","Format","InitialSilenceTimeoutMs","Language","Profanity","RequestBotStatusMessages","StableIntermediateThreshold","StableTranslation","TestHooks","ConnectionFactoryBase","setCommonUrlParams","setUrlParameter","SpeechServiceConnection_InitialSilenceTimeoutMs","SpeechServiceConnection_EndSilenceTimeoutMs","SpeechServiceResponse_StablePartialResultThreshold","serviceProperties","num","propId","parameterName","search","toLocaleLowerCase","WebsocketMessageFormatter","textMessage","headerBodySplit","parseHeaders","binaryMessage","dataView","headerLength","getInt16","headersString","getInt8","makeHeaders","content","headerBuffer","stringToArrayBuffer","headerInt8Array","payloadInt8Array","bodyInt8Array","headerMatches","match","separatorIndex","headerValue","SpeechConnectionFactory","interactiveRelativeUri","conversationRelativeUri","dictationRelativeUri","authInfo","hostSuffix","startsWith","Conversation","Dictation","SpeechServiceConnection_Url","SpeechHypothesis","privSpeechHypothesis","Duration","PrimaryLanguage","LanguageDetectionConfidence","Confidence","SpeakerId","SynthesisStatus","RecognitionStatus","SimpleSpeechPhrase","privSimpleSpeechPhrase","DisplayText","EnumTranslation","implTranslateRecognitionResult","recognitionStatus","Success","RecognizedSpeech","NoMatch","InitialSilenceTimeout","BabbleTimeout","EndOfDictation","implTranslateCancelResult","implTranslateCancelErrorCode","ServiceError","TooManyRequests","DetailedSpeechPhrase","privDetailedSpeechPhrase","NBest","SpeechServiceRecognizer","speechRecognizer","privSpeechRecognizer","sourceLanguages","onSuccess","action","onUnknown","interimResults","resultType","phraseResults","resultProps","SpeechServiceResponse_JsonResult","processed","hypothesis","RecognizingSpeech","recognizing","simple","resultReason","cancelReason","Display","recognized","canceled","SpeechRecognizer","speechConfig","speechConfigImpl","privDisposedRecognizer","FromConfig","autoDetectSourceLanguageConfig","Detailed","recognizeOnceAsync","startContinuousRecognitionAsync","stopContinuousRecognitionAsync","startKeywordRecognitionAsync","stopKeywordRecognitionAsync","_super","IntentConnectionFactory","getSpeechRegionFromIntentRegion","intentRegion","AddedLmIntent","modelImpl","intentName","IntentRecognitionCanceledEventArgs","IntentResponse","privIntentResponse","query","topScoringIntent","entities","IntentServiceRecognizer","privIntentRecognizer","privIntentDataSent","setIntents","addedIntents","umbrellaIntent","privAddedLmIntents","privUmbrellaIntent","speechHypothesis","RecognizingIntent","sendEvent","privPendingIntentArgs","intentResponse","addedIntent","intent","RecognizedIntent","LanguageUnderstandingServiceResponse_JsonResult","VoiceProfileType","TranslationStatus","IntentRecognizer","configImpl","privAddedIntents","privDisposedIntentRecognizer","buildSpeechContext","Intent","addIntent","simplePhrase","addIntentWithLanguageModel","addAllIntents","refGrammers","addedLmIntent","grammer","provider","TranslationConnectionFactory","to","SpeechServiceResponse_TranslationRequestStablePartialResult","TranslationRecognitionCanceledEventArgs","sessionid","privCancelReason","Translations","privMap","TranslationHypothesis","privTranslationHypothesis","Translation","TranslationPhrase","privTranslationPhrase","TranslationSynthesisEnd","privSynthesisEnd","FailureReason","TranslationServiceRecognizer","translationRecognizer","privTranslationRecognizer","onConnection","onDisconnection","fireEventForResult","translatedPhrase","sendSynthesisAudio","synthEnd","retEvent","canceledResult","serviceResult","translation","TranslatedSpeech","TranslatingSpeech","NoMatchReason","MessageDataStreamType","TranslationRecognizer","privDisposedTranslationRecognizer","NoMatchDetails","fromResult","simpleSpeech","NotRecognized","InitialBabbleTimeout","CancellationDetailsBase","ErrorCode","CancellationDetails","ConnectionEventArgs","ServiceEventArgs","privEventName","ConnectionMessageImpl","privConnectionMessage","Speech_SessionId","find","isTextMessage","isBinaryMessage","TextMessage","ConnectionMessageEventArgs","Connection","fromRecognizer","recoBase","privInternalData","setupEvents","fromSynthesizer","synthesizer","synthBase","openConnection","closeConnection","setMessageProperty","propertyName","propertyValue","sendMessageAsync","success","privEventListener","connected","disconnected","messageSent","messageReceived","privServiceEventListener","receivedServiceMessage","PhraseListGrammar","recogBase","privGrammerBuilder","addPhrases","phrases","DialogServiceConfig","applicationId","DialogTypes","BotFramework","CustomCommands","DialogServiceConfigImpl","privSpeechConfig","BotFrameworkConfig","subscription","botId","botFrameworkConfig","Conversation_DialogType","Conversation_ApplicationId","resolvedHost","CustomCommandsConfig","customCommandsConfig","DialogConnectionFactory","dialogType","requestTurnStatus","Conversation_Request_Bot_Status_Messages","resourceInfix","Constants","BaseUrl","endsWith","ApiKey","DialogEvent","SendingAgentContextMessageEvent","ActivityReceivedEventArgs","activity","privActivity","privAudioStream","TurnStatusResponsePayload","privMessageStatusResponse","interactionId","conversationId","TurnStatusReceivedEventArgs","turnStatus","privTurnStatus","ActivityPayloadResponse","privActivityResponse","messageDataStreamType","DialogServiceTurnState","manager","privIsCompleted","privTurnManager","resetTurnEndTimeout","processActivityPayload","TextToSpeechAudio","endAudioStream","complete","privTimeoutToken","CompleteTurn","DialogServiceTurnStateManager","privTurnMap","StartTurn","has","turnState","GetTurn","SpeechKeyword","privSpeechKeyword","Status","DialogServiceAdapter","dialogServiceConnector","sendAgentConfig","agentConfigSent","botInfo","commandsCulture","agentConfigJson","sendAgentContext","guid","speechActivityTemplate","privDialogServiceConnector","Conversation_Speech_Activity_Template","agentContext","channelData","agentContextJson","handleResponseMessage","responseMessage","responsePayload","responseRequestId","activityPayload","turn","privTurnStateManager","updateAgentConfig","pullAudioOutputStream","activityReceived","turnStatusReceived","receiveDialogMessageOverride","listenOnce","dialogConnectImpl","configConnection","privDisconnect","privDialogAudioSource","privLastResult","terminateMessageLoop","interactionGuid","agentMessage","agentMessageJson","speechPhrase","args","keyword","RecognizedKeyword","audioRequestId","preAudioPromise","sendPreAudioMessages","node","privConnectionLoop","startMessageLoop","communicationCustodian","loop","turnRequestId","turnEndRequestId","addKeywordContextData","keywordPropertyValue","keywordOffsetPropertyValue","keywordDurationPropertyValue","keywords","keywordOffsets","keywordDurations","keywordDefinitionArray","definition","clientDetectedKeywords","onReject","ServicePropertyChannel","DialogServiceConnector","dialogConfig","dialogServiceConfigImpl","isTurnComplete","buildAgentConfig","listenOnceAsync","retPromise","callbackHolder","sendActivityAsync","errCb","commType","Conversation_Agent_Connection_Id","Conversation_Conversation_Id","fromId","Conversation_From_Id","ttsAudioFormat","BaseAudioPlayer","audioContext","gainNode","autoUpdateBufferTimer","init","playAudioSample","newAudioData","ensureInitializedContext","formatAudioData","newSamplesData","samples","stopAudio","clearInterval","timerPeriod","setInterval","updateAudioBuffer","createGain","gain","formatArrayBuffer","Int16Array","Int32Array","maxValue","float32Data","bufferSource","createBufferSource","frameCount","createBuffer","channelOffset","playAudio","decodeAudioData","newBuffer","VoiceProfile","profileId","profileType","privProfileType","VoiceProfileEnrollmentResult","statusText","privDetails","enrollmentStatus","EnrollingVoiceProfile","FromIdentificationProfileList","results","profiles","EnrolledVoiceProfile","getIdentificationDetails","FromVerificationProfileList","getVerificationDetails","enrollmentsCount","enrollmentsLength","enrollmentResultDetails","audioSpeechLength","speechTime","parseFloat","enrollmentSpeechTime","identificationProfileId","remainingEnrollmentSpeechLength","remainingEnrollmentSpeechTime","verificationProfileId","remainingEnrollmentsCount","remainingEnrollments","VoiceProfileEnrollmentCancellationDetails","VoiceProfileResult","VoiceProfileCancellationDetails","VoiceProfileAuthorizationPhraseResult","passPhrase","SpeakerRecognitionConfig","RestConfigBase","requestOptions","privDefaultRequestOptions","configParams","privDefaultParams","restErrors","privRestErrors","Accept","ignoreCache","timeout","authInvalidSubscriptionKey","authInvalidSubscriptionRegion","invalidArgs","invalidCreateJoinConversationResponse","invalidParticipantRequest","permissionDeniedConnect","permissionDeniedConversation","permissionDeniedParticipant","permissionDeniedSend","permissionDeniedStart","apiVersion","authorization","clientAppId","contentTypeKey","correlationId","languageCode","nickname","roomId","sessionToken","subscriptionRegion","RestRequestType","RestMessageAdapter","privTimeout","privIgnoreCache","setHeaders","responseReceivedDeferral","xhr","XHR","requestCommand","withQuery","setRequestHeader","parseXHRResult","errorResponse","ontimeout","Post","responseText","getAllResponseHeaders","ok","status","queryString","map","SpeakerIdMessageAdapter","privRestAdapter","createProfile","getOperationUri","locale","createEnrollment","profile","ignoreMinLength","verifySpeaker","voiceProfile","identifySpeaker","TextIndependentIdentification","profileIds","voiceProfileIds","getProfileStatus","Get","getProfiles","getAuthorizationPhrases","TextDependentVerification","deleteProfile","Delete","resetProfile","mode","dependency","SpeakerRecognitionResultType","VoiceProfileClient","implClientSetup","createProfileAsync","privAdapter","retrieveEnrollmentResultAsync","getAllProfilesAsync","getAuthorizationPhrasesAsync","enrollProfileAsync","deleteProfileAsync","getResult","DeletedVoiceProfile","resetProfileAsync","ResetVoiceProfile","successReason","SpeakerIdentificationModel","privVoiceProfiles","fromProfiles","SpeakerRecognitionResult","RecognizedSpeaker","Identify","privProfileId","identifiedProfile","privScore","score","recognitionResult","SpeakerRecognitionCancellationDetails","SpeakerVerificationModel","privVoiceProfile","fromProfile","SpeakerRecognizer","privAudioConfigImpl","implSRSetup","responsePromise","Verify","AutoDetectSourceLanguageConfig","fromOpenRange","fromLanguages","fromSourceLanguageConfigs","configs","autoConfig","langs","customProperty","AutoDetectSourceLanguageResult","SourceLanguageConfig","privEndpointId","fromLanguage","ConversationConnectionConfig","privHost","privApiVersion","privClientAppId","defaultLanguageCode","privDefaultLanguageCode","restPath","privRestPath","webSocketPath","privWebSocketPath","speechHost","privSpeechHost","speechPath","privSpeechPath","transcriptionEventKeys","privTranscriptionEventKeys","InternalParticipants","participants","meId","addOrUpdateParticipant","exists","getParticipantIndex","getParticipant","findIndex","p","deleteParticipant","filter","isHost","me","ConversationTranslatorMessageTypes","ConversationTranslatorCommandTypes","defaultRequestOptions","evt","ConversationManager","privRequestParams","privErrors","createOrJoin","conversationCode","ConversationTranslator_Name","endpointHost","ConversationTranslator_Host","ConversationTranslator_CorrelationId","authToken","headerKey","arr","headerMap","line","parts","extractHeaderValue","errMessageRaw","errorMessage","conversation","leave","ConversationConnectionMessage","privConversationMessageType","conversationMessageType","ConversationWebsocketMessageFormatter","incomingMessage","ConversationConnectionFactory","ConversationTranslationCanceledEventArgs","ConversationExpirationEventArgs","expirationTime","privExpirationTime","ConversationTranslationResult","participantId","originalLanguage","privOrigLang","originalLang","ConversationRequestSession","privRequestCompletionDeferral","completionPromise","MuteAllEventArgs","isMuted","privIsMuted","LockRoomEventArgs","isLocked","privIsLocked","ParticipantEventArgs","participant","privParticipant","ParticipantAttributeEventArgs","privKey","privValue","privParticipantId","ParticipantsListEventArgs","translateTo","profanityFilter","roomProfanityFilter","isRoomLocked","isMuteAll","privRoomId","privSessionToken","privTranslateTo","privProfanityFilter","privRoomProfanityFilter","privIsRoomLocked","privParticipants","privIsMuteAll","ConversationReceivedTranslationEventArgs","command","privCommand","CommandResponsePayload","privCommandResponse","roomid","ParticipantsListPayloadResponse","privParticipantsPayloadResponse","roomLocked","muteAll","ParticipantPayloadResponse","privParticipantPayloadResponse","usetts","ismuted","ishost","avatar","SpeechResponsePayload","privSpeechResponse","timestamp","isFinal","TextResponsePayload","privTextResponse","originalText","ConversationServiceAdapter","conversationServiceConnector","privLastPartialUtteranceId","noOp","privConversationServiceConnector","privConversationAuthentication","receiveConversationMessageOverride","conversationConnectImpl","privConversationRequestSession","privConversationConnectionFactory","privConversationIsDisposed","privConnectionConfigPromise","sendFinal","commandPayload","participantsPayload","participantsResult","displayName","isUsingTts","preferredLanguage","participantsListReceived","participantUpdateCommandReceived","muteAllCommandReceived","conversationExpiration","lockRoomCommandReceived","joinParticipantPayload","joiningParticipant","participantJoinCommandReceived","leavingParticipant","participantLeaveCommandReceived","speechPayload","speechResult","getTranslations","translationReceived","textPayload","textResult","messageRetrievalPromise","serviceResultTranslations","ParticipantChangedReason","ConversationRecognizerFactory","fromConfig","ConversationTranslatorRecognizer","serviceConfigImpl","privConnection","privSpeechRecognitionLanguage","sendRequest","msg","PromiseToEmptyCallback","ConversationParticipantsChangedEventArgs","ConversationTranslationEventArgs","User","userId","privUserId","Participant","privAvatar","privDisplayName","privIsHost","privIsUsingTts","privPreferredLanguage","privVoice","From","createConversationAsync","arg2","arg3","arg4","conversationImpl","ConversationImpl","privIsConnected","privConversationId","onConnected","privConversationTranslator","onDisconnected","onCanceled","r","onParticipantUpdateCommandReceived","updatedParticipant","useTts","translateToLanguages","participantsChanged","Updated","toParticipant","onLockRoomCommandReceived","onMuteAllCommandReceived","toParticipants","onParticipantJoinCommandReceived","newParticipant","JoinedConversation","onParticipantLeaveCommandReceived","ejectedParticipant","LeftConversation","onTranslationReceived","transcribed","_c","transcribing","_d","_e","textMessageReceived","_f","onParticipantsListReceived","privRoom","privIsReady","changeNicknameAsync","onConversationExpiration","privManager","Masked","hostNickname","privConfig","privTextMessageMaxLength","conversationTranslator","room","privConversationRecognizer","isMutedByHost","isConnected","handleError","handleCallback","startConversationAsync","addParticipantAsync","addParticipantImplAsync","joinConversationAsync","cognitiveSpeechAuthToken","deleteConversationAsync","deleteConversationImplAsync","endConversationAsync","endConversationImplAsync","lockConversationAsync","canSendAsHost","getLockCommand","muteAllParticipantsAsync","getMuteAllCommand","muteParticipantAsync","canSend","getMuteCommand","removeParticipantAsync","privTranscriberRecognizer","removeParticipantImplAsync","getEjectCommand","unlockConversationAsync","unmuteAllParticipantsAsync","unmuteParticipantAsync","sendTextMessageAsync","getMessageCommand","getChangeNicknameCommand","transcriberRecognizer","connectTranscriberRecognizer","conversationInfo","convId","part","props","conversationProperties","pushConversationEvent","includeHost","ConversationCommon","privAudioConfig","SpeechState","ConversationTranslationRecognizer","translator","privSpeechState","Inactive","privTranslator","tr","cancelSpeech","fireCancelEvent","newState","ConversationTranslator","privIsSpeaking","privPlaceholderKey","privPlaceholderRegion","privConversation","param1","param2","param3","privSpeechTranslationConfig","speechEndpointHost","leaveConversationAsync","startTranscribingAsync","privCTRecognizer","connectTranslatorRecognizer","canSpeak","startContinuousRecognition","stopTranscribingAsync","cognitiveSpeechRegion","TranscriberConnectionFactory","multiaudioRelativeUri","hostDefault","ConversationTranscriptionCanceledEventArgs","TranscriptionServiceRecognizer","transcriber","sendSpeechEvent","speechEventJson","sendTranscriptionStartJSON","sendSpeechEventAsync","createSpeechEventPayload","getConversationInfo","meeting","eventDict","audiorecording","TranscriberRecognizer","speechTranslationConfig","speechTranslationConfigImpl","reco","connectCallbacks","disconnectCallbacks","SynthesisServiceType","ConversationTranscriber","SpeechSynthesisConnectionFactory","synthesisUri","hostPrefix","SynthesizerConfig","privSynthesisServiceType","Standard","synthesisServiceType","PronunciationAssessmentGradingSystem","PronunciationAssessmentGranularity","SpeechSynthesizer","privSynthesizing","synthesisRequestQueue","implCommonSynthesizeSetup","languageToDefaultVoice","XMLEncode","speakTextAsync","speakImpl","speakSsmlAsync","createSynthesizerConfig","createSynthesisAdapter","IsSsml","dataStream","SynthesisRequest","adapterSpeak","PronunciationAssessmentConfig","referenceText","gradingSystem","FivePoint","granularity","Phoneme","enableMiscue","PronunciationAssessment_ReferenceText","PronunciationAssessment_GradingSystem","PronunciationAssessment_Granularity","PronunciationAssessment_EnableMiscue","PronunciationAssessment_Json","updateJson","PronunciationAssessment_Params","applyTo","paramsJson","dimension","enableMiscueString","PronunciationAssessmentResult","j","privPronJson","detailResult","accuracyScore","PronunciationAssessment","AccuracyScore","pronunciationScore","PronScore","completenessScore","CompletenessScore","fluencyScore","FluencyScore","logLevelFilter","Warning","privLogLevelFilter","debug","logFragments","EventTime","prop","valueToLog","Exports_1","require","ConsoleLoggingListener","__exportStar","exports","__importStar","agent_base_1","__importDefault","async_disk_cache_1","https_proxy_agent_1","OCSPEvents_1","default","prototype","sent","_this","e_1","cachedOcspResponse","utils","verify","__assign","baseAgent_1","Exports_2","AudioStreamFormat_1","defineProperty","stream_1","processFile_1","AudioWorkletSourceURLPropertyName","devices_1","WebsocketMessageAdapter_1","HeaderNames_1","ws_1","CertChecks_1","deferred_1","sendError_1","IAuthentication_1","QueryParameterNames_1","Exports_3","ConnectionFactoryBase_1","Exports_4","__extends","DialogEvents_1","AudioOutputFormat_1","DialogServiceTurnStateManager_1","ActivityResponsePayload_1","SpeechConnectionMessage_Internal_1","event_1","error_1","audioSessionReqId","error_3","AudioOutputStream_1","Error_1","DialogServiceTurnState_1","retPhrases_1","RecognitionEndedEvent","serviceTag","privStatus","privServiceTag","Device","RecognitionEvents_1","ServiceTelemetryListener_Internal_1","TranslationStatus_1","error_2","e_2","metadataList_1","SynthesisAdapterBase_1","SynthesisEvents_1","Contracts_1","ConversationConnectionConfig_1","ConversationWebsocketMessageFormatter_1","ConversationUtils_1","ConversationConnectionMessage_1","ConversationRequestSession_1","ConversationTranslatorEventArgs_1","ConversationTranslatorInterfaces_1","setTranslateToLanguages","setProfanityFiltering","setMute","setUseTTS","changeNickname","final","partial","instantMessage","serviceResultTranslations_1","participantCommand","translatedMessage","disconnectSession","ejectParticipant","instant_message","joinSession","leaveSession","participantList","roomExpirationWarning","setLockState","setMuteAll","ConversationConnectionFactory_1","ConversationServiceAdapter_1","withAsync","RestConfigBase_1","headerMap_1","ConversationManager_1","enumerable","ConversationTranslatorRecognizer_1","TranscriberRecognizer_1","CommandResponsePayload_1","ParticipantResponsePayload_1","TranslationResponsePayload_1","result_1","result_2","result_3","headerMatches_1","PlatformEvent_1","Guid_1","EventSource_1","uuid_1","v4","list_1","OCSPWSUpgradeStartedEvent","PromiseResult","promiseResultEventSource","throwIfError","privIsError","PromiseResultEventSource","setResult","privOnSetResult","setError","privOnSetError","onSetResult","onSetError","Sink","privState","privPromiseResult","privPromiseResultEvents","privSuccessHandlers","privErrorHandlers","Resolved","executeSuccessCallback","detachHandlers","Rejected","errorHandler","executeErrorCallback","List_1","Promise_1","promiseArray_1","ConnectionMessage_1","Queue_1","AudioFileWriter_1","AudioInputStream_1","openSync","createWriteStream","writeSync","closeSync","SpeechSynthesisOutputFormat_1","receivedAudio_1","mimeType_1","DialogServiceConfig_1","CancellationDetailsBase_1","PropertyCollection_1","PropertyId_1","array_1","DialogConnectorFactory_1","AudioConfig_1","CancellationReason_1","PullAudioInputStreamCallback_1","PushAudioOutputStreamCallback_1","KeywordRecognitionModel_1","SessionEventArgs_1","RecognitionEventArgs_1","OutputFormat_1","IntentRecognitionEventArgs_1","RecognitionResult_1","SpeechRecognitionResult_1","IntentRecognitionResult_1","LanguageUnderstandingModel_1","SpeechRecognitionEventArgs_1","SpeechRecognitionCanceledEventArgs_1","TranslationRecognitionEventArgs_1","TranslationSynthesisEventArgs_1","TranslationRecognitionResult_1","TranslationSynthesisResult_1","ResultReason_1","SpeechConfig_1","SpeechTranslationConfig_1","Recognizer_1","SpeechRecognizer_1","IntentRecognizer_1","VoiceProfileType_1","TranslationRecognizer_1","Translations_1","NoMatchReason_1","NoMatchDetails_1","TranslationRecognitionCanceledEventArgs_1","IntentRecognitionCanceledEventArgs_1","CancellationDetails_1","CancellationErrorCodes_1","ConnectionEventArgs_1","ServiceEventArgs_1","Connection_1","PhraseListGrammar_1","BotFrameworkConfig_1","CustomCommandsConfig_1","DialogServiceConnector_1","ActivityReceivedEventArgs_1","TurnStatusReceivedEventArgs_1","ServicePropertyChannel_1","ProfanityOption_1","BaseAudioPlayer_1","ConnectionMessageEventArgs_1","VoiceProfile_1","VoiceProfileEnrollmentResult_1","VoiceProfileResult_1","VoiceProfileAuthorizationPhraseResult_1","VoiceProfileClient_1","SpeakerRecognizer_1","SpeakerIdentificationModel_1","SpeakerVerificationModel_1","AutoDetectSourceLanguageConfig_1","AutoDetectSourceLanguageResult_1","SourceLanguageConfig_1","SpeakerRecognitionResult_1","SpeechSynthesizer_1","SpeechSynthesisResult_1","SpeechSynthesisEventArgs_1","SpeechSynthesisWordBoundaryEventArgs_1","SpeechSynthesisBookmarkEventArgs_1","SpeechSynthesisVisemeEventArgs_1","SpeakerAudioDestination_1","ConversationTranscriptionCanceledEventArgs_1","PronunciationAssessmentGradingSystem_1","PronunciationAssessmentGranularity_1","PronunciationAssessmentConfig_1","PronunciationAssessmentResult_1"],"sourceRoot":""}