UNPKG

speech-to-element

Version:

Add real-time speech to text functionality into your website with no effort

3 lines (2 loc) 22.4 kB
(function(m,c){typeof exports=="object"&&typeof module<"u"?module.exports=c():typeof define=="function"&&define.amd?define(c):(m=typeof globalThis<"u"?globalThis:m||self,m.iife=c())})(this,function(){"use strict";const m=class b{static capitalize(e){return e.replace(b.FIRST_CHAR_REGEX,t=>t.toUpperCase())}static lineBreak(e){return e.replace(b.DOUBLE_LINE,"<p></p>").replace(b.ONE_LINE,"<br>")}static isCharDefined(e){return e!==void 0&&e!==" "&&e!==" "&&e!==` `&&e!==""}static breakupIntoWordsArr(e){return e.split(/(\W+)/)}};m.FIRST_CHAR_REGEX=/\S/,m.DOUBLE_LINE=/\n\n/g,m.ONE_LINE=/\n/g;let c=m;class N{static translate(e,t){const i=c.breakupIntoWordsArr(e);for(let r=0;r<i.length;r+=1)t[i[r]]&&(i[r]=t[i[r]]);return i.join("")}}class L{static extract(e,t,i){let r="";for(let n=e.resultIndex;n<e.results.length;++n){let s=e.results[n][0].transcript;i&&(s=N.translate(s,i)),e.results[n].isFinal?t+=s:r+=s}return{interimTranscript:r,finalTranscript:t,newText:r||t}}static extractSafari(e,t,i){let r="";const n="";for(let s=e.resultIndex;s<e.results.length;++s){let a=e.results[s][0].transcript;i&&(a=N.translate(a,i)),r+=a}return{interimTranscript:n,finalTranscript:r,newText:n||r}}}const w=class{};w.IS_SAFARI=()=>(w._IS_SAFARI===void 0&&(w._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),w._IS_SAFARI);let I=w;const k=class h{static getElementIfFocusedOnAvailable(e,t){return Array.isArray(e)?e.find(i=>t===i):t===e?e:void 0}static keyDownWindow(e){e.element&&h.getElementIfFocusedOnAvailable(e.element,document.activeElement)&&(h.KEY_DOWN_TIMEOUT!==null&&clearTimeout(h.KEY_DOWN_TIMEOUT),h.KEY_DOWN_TIMEOUT=setTimeout(()=>{h.KEY_DOWN_TIMEOUT=null,this.resetRecording(e)},500))}static mouseDownWindow(e,t){this.mouseDownElement=h.getElementIfFocusedOnAvailable(e,t.target)}static mouseUpWindow(e){this.mouseDownElement&&this.resetRecording(e),this.mouseDownElement=void 0}static add(e,t){const i=(t==null?void 0:t.insertInCursorLocation)===void 0||(t==null?void 0:t.insertInCursorLocation);t!=null&&t.element&&i&&(e.mouseDownEvent=h.mouseDownWindow.bind(e,t.element),document.addEventListener("mousedown",e.mouseDownEvent),e.mouseUpEvent=h.mouseUpWindow.bind(e,t),document.addEventListener("mouseup",e.mouseUpEvent),e.keyDownEvent=h.keyDownWindow.bind(e,t),document.addEventListener("keydown",e.keyDownEvent))}static remove(e){document.removeEventListener("mousedown",e.mouseDownEvent),document.removeEventListener("mouseup",e.mouseUpEvent),document.removeEventListener("keydown",e.keyDownEvent)}};k.KEY_DOWN_TIMEOUT=null;let D=k;class U{static process(e,t,i,r,n){const s=r==null?void 0:r(t,i);return s?(setTimeout(()=>{s.restart?e.resetRecording(n):s.stop&&e.stop()}),(s.stop||s.restart)&&s.removeNewText):!1}}class S{static changeStateIfNeeded(e,t){t&&!e.isCursorAtEnd&&(e.endPadding="",e.scrollingSpan.innerHTML="&nbsp;")}static scrollGeneric(e,t){e.isCursorAtEnd?t.scrollTop=t.scrollHeight:e.scrollingSpan.scrollIntoView({block:"nearest"})}static scrollSafariPrimitiveToEnd(e){e.scrollLeft=e.scrollWidth,e.scrollTop=e.scrollHeight}static isElementOverflown(e){return e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth}static isRequired(e,t){return e&&S.isElementOverflown(t)}}class u{static isPrimitiveElement(e){return e.tagName==="INPUT"||e.tagName==="TEXTAREA"}static createInterimSpan(){const e=document.createElement("span");return e.style.color="grey",e.style.pointerEvents="none",e}static createGenericSpan(){const e=document.createElement("span");return e.style.pointerEvents="none",e}static appendSpans(e,t){if(e.spansPopulated=!0,e.insertInCursorLocation&&document.activeElement===t){const i=window.getSelection();if(i!=null&&i.focusNode){const r=i.getRangeAt(0);r.insertNode(e.scrollingSpan),r.insertNode(e.interimSpan),r.insertNode(e.finalSpan),r.collapse(!1),i.removeAllRanges(),i.addRange(r);return}}t.appendChild(e.finalSpan),t.appendChild(e.interimSpan),t.appendChild(e.scrollingSpan)}static applyCustomColors(e,t){t.interim&&(e.interimSpan.style.color=t.interim),t.final&&(e.finalSpan.style.color=t.final)}static isInsideShadowDOM(e){return e.getRootNode()instanceof ShadowRoot}}class l{static setOffsetForGeneric(e,t,i=0){let r=0;for(let n=0;n<e.childNodes.length;n+=1){const s=e.childNodes[n];if(s.childNodes.length>0){const a=l.setOffsetForGeneric(s,t,i);if(a===-1)return-1;i+=a}else if(s.textContent!==null){if(i+s.textContent.length>t){const a=document.createRange();a.setStart(s,t-i),a.collapse(!0);const o=window.getSelection();return o==null||o.removeAllRanges(),o==null||o.addRange(a),e.focus(),-1}i+=s.textContent.length,r+=s.textContent.length}}return r}static focusEndOfGeneric(e){const t=document.createRange();t.selectNodeContents(e),t.collapse(!1);const i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(t))}static setOffsetForSafariGeneric(e,t){const i=window.getSelection();if(i){const r=l.getGenericElementCursorOffset(e,i,!0);l.setOffsetForGeneric(e,r+t)}}static setOffsetForPrimitive(e,t,i){i&&e.blur(),e.setSelectionRange(t,t),e.focus()}static getGenericElementCursorOffset(e,t,i){let r=0;if(t.rangeCount>0){const n=t.getRangeAt(0),s=n.cloneRange();s.selectNodeContents(e),i?s.setEnd(n.startContainer,n.startOffset):s.setEnd(n.endContainer,n.endOffset),r=s.toString().length}return r}}class d{static processCommand(e,t){return(!t||!t.caseSensitive)&&(e=e.toLowerCase()),(t==null?void 0:t.substrings)===!1?c.breakupIntoWordsArr(e):e}static process(e){var i;return((i=e.settings)==null?void 0:i.caseSensitive)===!0?e:Object.keys(e).reduce((r,n)=>{const s=e[n];return r[n]=typeof s=="string"?d.processCommand(s,e.settings):s,r},{})}static toggleCommandModeOn(e){var t;e.isWaitingForCommand=!0,(t=e.onCommandModeTrigger)==null||t.call(e,!0)}static toggleCommandModeOff(e){var t;e.isWaitingForCommand&&((t=e.onCommandModeTrigger)==null||t.call(e,!1),e.isWaitingForCommand=!1)}static setText(e,t,i,r){d.toggleCommandModeOff(e),u.isPrimitiveElement(r)?(r.value=i,e.isTargetInShadow||l.setOffsetForPrimitive(r,i.length,!0),I.IS_SAFARI()&&e.autoScroll&&S.scrollSafariPrimitiveToEnd(r)):(r.textContent=i,e.isTargetInShadow||l.focusEndOfGeneric(r),setTimeout(()=>S.scrollGeneric(e,r))),e.resetRecording(t)}static checkIfMatchesSubstring(e,t){return t.includes(e)}static checkIfMatchesWord(e,t,i){const r=e;for(let n=i.length-1;n>=0;n-=1){let s=n,a=r.length-1;for(;i[s]===r[a]&&a>=0;)s-=1,a-=1;if(a<0)return!0}return!1}static execCommand(e,t,i,r,n){var x,O,z;const s=e.commands;if(!s||!r||!i)return;const a=((x=s.settings)==null?void 0:x.caseSensitive)===!0?t:t.toLowerCase(),o=c.breakupIntoWordsArr(a),g=((O=s.settings)==null?void 0:O.substrings)===!1?d.checkIfMatchesWord:d.checkIfMatchesSubstring;if(s.commandMode&&g(s.commandMode,a,o))return e.setInterimColorToFinal(),setTimeout(()=>d.toggleCommandModeOn(e)),{doNotProcessTranscription:!1};if(!(s.commandMode&&!e.isWaitingForCommand)){if(s.stop&&g(s.stop,a,o))return d.toggleCommandModeOff(e),setTimeout(()=>e.stop()),{doNotProcessTranscription:!1};if(s.pause&&g(s.pause,a,o))return d.toggleCommandModeOff(e),e.setInterimColorToFinal(),setTimeout(()=>{var K;e.isPaused=!0,(K=e.onPauseTrigger)==null||K.call(e,!0)}),{doNotProcessTranscription:!1};if(s.resume&&g(s.resume,a,o))return e.isPaused=!1,(z=e.onPauseTrigger)==null||z.call(e,!1),d.toggleCommandModeOff(e),e.resetRecording(i),{doNotProcessTranscription:!0};if(s.reset&&g(s.reset,a,o))return n!==void 0&&d.setText(e,i,n,r),{doNotProcessTranscription:!0};if(s.removeAllText&&g(s.removeAllText,a,o))return d.setText(e,i,"",r),{doNotProcessTranscription:!0}}}}class E{static setStateForPrimitive(e,t){let i,r;t.selectionStart!==null&&(i=t.selectionStart),t.selectionEnd!==null&&(r=t.selectionEnd),e.isHighlighted=i!==r}static setStateForGeneric(e,t){const i=window.getSelection();if(i!=null&&i.focusNode){const r=l.getGenericElementCursorOffset(t,i,!0),n=l.getGenericElementCursorOffset(t,i,!1);e.isHighlighted=r!==n}}static setState(e,t){document.activeElement===t&&(u.isPrimitiveElement(t)?E.setStateForPrimitive(e,t):E.setStateForGeneric(e,t))}static removeForGeneric(e,t){const i=window.getSelection();if(i){const r=l.getGenericElementCursorOffset(t,i,!0);i.deleteFromDocument(),l.setOffsetForGeneric(t,r),e.isHighlighted=!1}}static removeForPrimitive(e,t){const i=t.selectionStart,r=t.selectionEnd,n=t.value;if(i&&r){const s=n.substring(0,i)+n.substring(r);t.value=s,l.setOffsetForPrimitive(t,i,e.autoScroll)}e.isHighlighted=!1}}class C{static setStateForPrimitiveElement(e,t){if(document.activeElement===t&&t.selectionStart!==null){const r=t.selectionStart,n=t.value[r-1],s=t.selectionEnd===null?r:t.selectionEnd,a=t.value[s];c.isCharDefined(n)&&(e.startPadding=" ",e.numberOfSpacesBeforeNewText=1),c.isCharDefined(a)&&(e.endPadding=" ",e.numberOfSpacesAfterNewText=1),e.isCursorAtEnd=t.value.length===s;return}const i=t.value[t.value.length-1];c.isCharDefined(i)&&(e.startPadding=" ",e.numberOfSpacesBeforeNewText=1),e.isCursorAtEnd=!0}static setStateForGenericElement(e,t){var r,n,s;if(document.activeElement===t){const a=window.getSelection();if(a!=null&&a.focusNode){const o=l.getGenericElementCursorOffset(t,a,!0),g=(r=t.textContent)==null?void 0:r[o-1],x=l.getGenericElementCursorOffset(t,a,!1),O=(n=t.textContent)==null?void 0:n[x];c.isCharDefined(g)&&(e.startPadding=" "),c.isCharDefined(O)&&(e.endPadding=" "),e.isCursorAtEnd=((s=t.textContent)==null?void 0:s.length)===x;return}}const i=t.innerText.charAt(t.innerText.length-1);c.isCharDefined(i)&&(e.startPadding=" "),e.isCursorAtEnd=!0}static setState(e,t){u.isPrimitiveElement(t)?C.setStateForPrimitiveElement(e,t):C.setStateForGenericElement(e,t)}static adjustStateAfterRecodingPrimitiveElement(e,t){if(e.primitiveTextRecorded=!0,e.insertInCursorLocation&&document.activeElement===t&&(t.selectionEnd!==null&&(e.endPadding=e.endPadding+t.value.slice(t.selectionEnd)),t.selectionStart!==null)){e.startPadding=t.value.slice(0,t.selectionStart)+e.startPadding;return}e.startPadding=t.value+e.startPadding}static adjustSateForNoTextPrimitiveElement(e){e.numberOfSpacesBeforeNewText===1&&(e.startPadding=e.startPadding.substring(0,e.startPadding.length-1),e.numberOfSpacesBeforeNewText=0),e.numberOfSpacesAfterNewText===1&&(e.endPadding=e.endPadding.substring(1),e.numberOfSpacesAfterNewText=0)}}class M{constructor(){this.finalTranscript="",this.interimSpan=u.createInterimSpan(),this.finalSpan=u.createGenericSpan(),this.scrollingSpan=u.createGenericSpan(),this.isCursorAtEnd=!1,this.spansPopulated=!1,this.startPadding="",this.endPadding="",this.numberOfSpacesBeforeNewText=0,this.numberOfSpacesAfterNewText=0,this.isHighlighted=!1,this.primitiveTextRecorded=!1,this.recognizing=!1,this._displayInterimResults=!0,this.insertInCursorLocation=!0,this.autoScroll=!0,this.isRestarting=!1,this.isPaused=!1,this.isWaitingForCommand=!1,this.isTargetInShadow=!1,this.cannotBeStopped=!1,this.resetState()}prepareBeforeStart(e){var t,i;if(e!=null&&e.element)if(D.add(this,e),Array.isArray(e.element)){const n=e.element.find(s=>s===document.activeElement)||e.element[0];if(!n)return;this.prepare(n)}else this.prepare(e.element);(e==null?void 0:e.displayInterimResults)!==void 0&&(this._displayInterimResults=e.displayInterimResults),e!=null&&e.textColor&&(this._finalTextColor=(t=e==null?void 0:e.textColor)==null?void 0:t.final,u.applyCustomColors(this,e.textColor)),(e==null?void 0:e.insertInCursorLocation)!==void 0&&(this.insertInCursorLocation=e.insertInCursorLocation),(e==null?void 0:e.autoScroll)!==void 0&&(this.autoScroll=e.autoScroll),this._onResult=e==null?void 0:e.onResult,this._onPreResult=e==null?void 0:e.onPreResult,this._onStart=e==null?void 0:e.onStart,this._onStop=e==null?void 0:e.onStop,this._onError=e==null?void 0:e.onError,this.onCommandModeTrigger=e==null?void 0:e.onCommandModeTrigger,this.onPauseTrigger=e==null?void 0:e.onPauseTrigger,this._options=e,(i=this._options)!=null&&i.commands&&(this.commands=d.process(this._options.commands))}prepare(e){C.setState(this,e),E.setState(this,e),this.isTargetInShadow=u.isInsideShadowDOM(e),u.isPrimitiveElement(e)?(this._primitiveElement=e,this._originalText=this._primitiveElement.value):(this._genericElement=e,this._originalText=this._genericElement.textContent)}resetRecording(e){this.isRestarting=!0,this.stop(!0),this.resetState(!0),this.start(e,!0)}updateElements(e,t,i){var a;const r=c.capitalize(t);if(this.finalTranscript===r&&e==="")return;U.process(this,i,e==="",this._onPreResult,this._options)&&(e="",i="");const n=this.commands&&d.execCommand(this,i,this._options,this._primitiveElement||this._genericElement,this._originalText);if(n){if(n.doNotProcessTranscription)return;e="",i=""}if(this.isPaused||this.isWaitingForCommand)return;(a=this._onResult)==null||a.call(this,i,e===""),this.finalTranscript=r,this._displayInterimResults||(e="");const s=this.finalTranscript===""&&e==="";this._primitiveElement?this.updatePrimitiveElement(this._primitiveElement,e,s):this._genericElement&&this.updateGenericElement(this._genericElement,e,s)}updatePrimitiveElement(e,t,i){this.isHighlighted&&E.removeForPrimitive(this,e),this.primitiveTextRecorded||C.adjustStateAfterRecodingPrimitiveElement(this,e),i&&C.adjustSateForNoTextPrimitiveElement(this);const r=this.startPadding+this.finalTranscript+t;if(e.value=r+this.endPadding,!this.isTargetInShadow){const n=r.length+this.numberOfSpacesAfterNewText;l.setOffsetForPrimitive(e,n,this.autoScroll)}this.autoScroll&&I.IS_SAFARI()&&this.isCursorAtEnd&&S.scrollSafariPrimitiveToEnd(e)}updateGenericElement(e,t,i){this.isHighlighted&&E.removeForGeneric(this,e),this.spansPopulated||u.appendSpans(this,e);const r=(i?"":this.startPadding)+c.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=r;const n=S.isRequired(this.autoScroll,e);S.changeStateIfNeeded(this,n);const s=c.lineBreak(t)+(i?"":this.endPadding);this.interimSpan.innerHTML=s,I.IS_SAFARI()&&this.insertInCursorLocation&&l.setOffsetForSafariGeneric(e,r.length+s.length),n&&S.scrollGeneric(this,e),i&&(this.scrollingSpan.innerHTML="")}finalise(e){this._genericElement&&(e?(this.finalSpan=u.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=u.createInterimSpan(),this.scrollingSpan=u.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),D.remove(this)}setInterimColorToFinal(){this.interimSpan.style.color=this._finalTextColor||"black"}resetState(e){this._primitiveElement=void 0,this._genericElement=void 0,this.finalTranscript="",this.finalSpan.innerHTML="",this.interimSpan.innerHTML="",this.scrollingSpan.innerHTML="",this.startPadding="",this.endPadding="",this.isHighlighted=!1,this.primitiveTextRecorded=!1,this.numberOfSpacesBeforeNewText=0,this.numberOfSpacesAfterNewText=0,e||(this.stopTimeout=void 0)}setStateOnStart(){var e;this.recognizing=!0,this.isRestarting?this.isRestarting=!1:(e=this._onStart)==null||e.call(this)}setStateOnStop(){var e;this.recognizing=!1,this.isRestarting||(e=this._onStop)==null||e.call(this)}setStateOnError(e){var t;(t=this._onError)==null||t.call(this,e),this.recognizing=!1}}class P extends M{constructor(){super()}start(e){var t;this._extractText===void 0&&(this._extractText=I.IS_SAFARI()?L.extractSafari:L.extract),this.validate()&&(this.prepareBeforeStart(e),this.instantiateService(e),(t=this._service)==null||t.start(),this._translations=e==null?void 0:e.translations)}validate(){return P.getAPI()?!0:(this.error("Speech Recognition is unsupported"),!1)}instantiateService(e){var i;const t=P.getAPI();this._service=new t,this._service.continuous=!0,this._service.interimResults=(e==null?void 0:e.displayInterimResults)??!0,this._service.lang=((i=e==null?void 0:e.language)==null?void 0:i.trim())||"en-US",this.setEvents()}setEvents(){this._service&&(this._service.onstart=()=>{this.setStateOnStart()},this._service.onerror=e=>{I.IS_SAFARI()&&e.message==="Another request is started"||e.error==="aborted"&&this.isRestarting||e.error!=="no-speech"&&this.error(e.message||e.error)},this._service.onaudioend=()=>{this.setStateOnStop()},this._service.onend=()=>{this._stopping=!1},this._service.onresult=e=>{if(typeof e.results>"u"&&this._service)this._service.onend=null,this._service.stop();else if(this._extractText&&!this._stopping){const{interimTranscript:t,finalTranscript:i,newText:r}=this._extractText(e,this.finalTranscript,this._translations);this.updateElements(t,i,r)}})}stop(e){var t;this._stopping=!0,(t=this._service)==null||t.stop(),this.finalise(e)}static getAPI(){return window.webkitSpeechRecognition||window.SpeechRecognition}error(e){console.error(e),this.setStateOnError(e),this.stop()}}const G=class p{static doubleClickDetector(){return p.doubleClickPending?!0:(p.doubleClickPending=!0,setTimeout(()=>{p.doubleClickPending=!1},300),!1)}};G.doubleClickPending=!1;let f=G;class W{static applyPrevention(e){clearTimeout(e._manualConnectionStopPrevention),e.cannotBeStopped=!0,e._manualConnectionStopPrevention=setTimeout(()=>{e.cannotBeStopped=!1},800)}static clearPrevention(e){clearTimeout(e._manualConnectionStopPrevention),e.cannotBeStopped=!1}}const y="https://github.com/OvidijusParsiunas/speech-to-element";class _{static validateOptions(e,t){return t?!t.subscriptionKey&&!t.token&&!t.retrieveToken?(e(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${y}`),!1):t.region?!0:(e(`Please define a 'region' property - more info: ${y}`),!1):(e(`Please provide subscription details - more info: ${y}`),!1)}static async getNewSpeechConfig(e,t){if(t.region)return t.subscriptionKey?e.fromSubscription(t.subscriptionKey.trim(),t.region.trim()):t.token?e.fromAuthorizationToken(t.token.trim(),t.region.trim()):t.retrieveToken?t.retrieveToken().then(i=>t.region?e.fromAuthorizationToken((i==null?void 0:i.trim())||"",t.region.trim()):null).catch(i=>(console.error(i),null)):null}static process(e,t){t.language&&(e.speechRecognitionLanguage=t.language.trim())}static async get(e,t){const i=await _.getNewSpeechConfig(e,t);return i&&_.process(i,t),i}}const B=class F{static set(e){e.stopTimeout=setTimeout(()=>e.stop(),e.stopTimeoutMS)}static reset(e,t){e.stopTimeoutMS=t||F.DEFAULT_MS,F.stop(e),F.set(e)}static stop(e){e.stopTimeout&&clearTimeout(e.stopTimeout)}};B.DEFAULT_MS=2e4;let R=B;class H{static extract(e,t,i,r){return r&&(e=N.translate(e,r)),i?{interimTranscript:"",finalTranscript:t+e,newText:e}:{interimTranscript:e,finalTranscript:t,newText:e}}}class A extends M{constructor(){super(...arguments),this._newTextPadding=""}start(e,t){this._newTextPadding="",this.stopTimeout===void 0&&R.reset(this,e==null?void 0:e.stopAfterSilenceMs),this.prepareBeforeStart(e),this.startAsync(e),t||W.applyPrevention(this)}async startAsync(e){var t;this.validate(e)&&(await this.instantiateService(e),this._translations=e==null?void 0:e.translations,(t=this._service)==null||t.startContinuousRecognitionAsync(()=>{},this.error))}validate(e){return A.getAPI()?_.validateOptions(this.error.bind(this),e):(this.moduleNotFound(),!1)}async instantiateService(e){const t=A.getAPI(),i=t.AudioConfig.fromDefaultMicrophoneInput(),r=await _.get(t.SpeechConfig,e);if(r){let n;if(e.autoLanguage&&e.autoLanguage.languages.length>0){const{type:s,languages:a}=e.autoLanguage,o=a.slice(0,s==="Continuous"?10:4),g=t.AutoDetectSourceLanguageConfig.fromLanguages(o);s==="Continuous"&&(g.mode=1),n=t.SpeechRecognizer.FromConfig(r,g,i)}else n=new t.SpeechRecognizer(r,i);this.setEvents(n),this._service=n,e.retrieveToken&&this.retrieveTokenInterval(e.retrieveToken)}else this.error("Unable to contact Azure server")}setEvents(e){e.recognizing=this.onRecognizing.bind(this),e.recognized=this.onRecognized.bind(this),e.sessionStarted=this.onSessionStarted.bind(this),e.canceled=this.onCanceled.bind(this),e.sessionStopped=this.onSessionStopped.bind(this)}onRecognizing(e,t){if(this._stopping)return;const{interimTranscript:i,finalTranscript:r,newText:n}=H.extract(this._newTextPadding+t.result.text,this.finalTranscript,!1,this._translations);R.reset(this,this.stopTimeoutMS),this.updateElements(i,r,n)}onRecognized(e,t){const i=t.result;switch(i.reason){case window.SpeechSDK.ResultReason.Canceled:break;case window.SpeechSDK.ResultReason.RecognizedSpeech:if(i.text&&!this._stopping){const{interimTranscript:r,finalTranscript:n,newText:s}=H.extract(this._newTextPadding+i.text,this.finalTranscript,!0,this._translations);R.reset(this,this.stopTimeoutMS),this.updateElements(r,n,s),n!==""&&(this._newTextPadding=" ")}break}}onCanceled(e,t){t.reason===window.SpeechSDK.CancellationReason.Error&&this.error(t.errorDetails)}onSessionStarted(){W.clearPrevention(this),this.setStateOnStart()}onSessionStopped(){this._retrieveTokenInterval||clearInterval(this._retrieveTokenInterval),this._stopping=!1,this.setStateOnStop()}retrieveTokenInterval(e){this._retrieveTokenInterval=setInterval(()=>{e==null||e().then(t=>{this._service&&(this._service.authorizationToken=(t==null?void 0:t.trim())||"")}).catch(t=>{this.error(t)})},1e4)}stop(e){var t;!e&&this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),this._stopping=!0,(t=this._service)==null||t.stopContinuousRecognitionAsync(),R.stop(this),this.finalise(e)}static getAPI(){return window.SpeechSDK}moduleNotFound(){console.error("speech recognition module not found:"),console.error(`please install the 'microsoft-cognitiveservices-speech-sdk' npm package or add a script tag: <script src="https://aka.ms/csspeech/jsbrowserpackageraw"><\/script>`),this.setStateOnError("speech recognition module not found")}error(e){this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),console.error(e),this.setStateOnError(e),this.stop()}}class v{static toggle(e,t){var r,n;const i=e.toLocaleLowerCase().trim();(r=f.service)!=null&&r.recognizing?this.stop():i==="webspeech"?v.startWebSpeech(t):i==="azure"?v.startAzure(t):(console.error("service not found - must be either 'webspeech' or 'azure'"),(n=t==null?void 0:t.onError)==null||n.call(t,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(e){v.stop()||(f.service=new P,f.service.start(e))}static isWebSpeechSupported(){return!!P.getAPI()}static startAzure(e){var t;v.stop()||(t=f.service)!=null&&t.cannotBeStopped||(f.service=new A,f.service.start(e))}static stop(){var e;return f.doubleClickDetector()?!0:((e=f.service)!=null&&e.recognizing&&f.service.stop(),!1)}static endCommandMode(){f.service&&d.toggleCommandModeOff(f.service)}}return window.SpeechToElement=v,v});