UNPKG

js-tts-wrapper

Version:

A JavaScript/TypeScript library that provides a unified API for working with multiple cloud-based Text-to-Speech (TTS) services

1 lines 192 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("path")):"function"==typeof define&&define.amd?define(["exports","path"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).JSTTSWrapper={},e.require$$0)}(this,(function(e,t){"use strict";function r(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}class n{constructor(){this.ssml=""}add(e){return e.trim().startsWith("<speak")?this.ssml=e:this.ssml=`<speak>${e}</speak>`,this.ssml}addBreak(e="500ms"){return this.ssml=this.ssml.replace("</speak>",`<break time="${e}"/></speak>`),this}addProsody(e,t,r,n){let i="";t&&(i+=` rate="${t}"`),r&&(i+=` pitch="${r}"`),n&&(i+=` volume="${n}"`);const s=`<prosody${i}>${e}</prosody>`;return this.ssml.includes("<speak>")?this.ssml=this.ssml.replace("<speak>",`<speak>${s}`):this.ssml=`<speak>${s}</speak>`,this}wrapWithSpeak(e){return e.trim().startsWith("<speak")?e:`<speak>${e}</speak>`}clearSSML(){this.ssml=""}toString(){return this.ssml}}class i{static normalize(e,t){try{let r,n;if(e.startsWith("mms_")&&(e=e.substring(4)),e.includes("-")){const t=e.split("-");r=t[0].toLowerCase(),n=t[1].toUpperCase()}else r=e.toLowerCase(),n=null==t?void 0:t.toUpperCase();const s=i.iso1To3[r]||r,o=n?`${r}-${n}`:r;let a=i.languageNames[r]||r;return n&&i.regionNames[n]?a+=` (${i.regionNames[n]})`:n&&(a+=` (${n})`),{iso639_3:s,bcp47:o,display:a,countryCode:n}}catch(e){return{iso639_3:"und",bcp47:"und",display:"Unknown"}}}static getDisplayName(e){return i.normalize(e).display}static getISO639_3(e){return i.normalize(e).iso639_3}static getBCP47(e,t){return i.normalize(e,t).bcp47}}i.languageNames={en:"English",fr:"French",es:"Spanish",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese",ru:"Russian",pt:"Portuguese",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",fi:"Finnish",no:"Norwegian",da:"Danish",pl:"Polish",tr:"Turkish",cs:"Czech",hu:"Hungarian",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",ro:"Romanian",sk:"Slovak",uk:"Ukrainian",bg:"Bulgarian",hr:"Croatian",lt:"Lithuanian",lv:"Latvian",et:"Estonian",sl:"Slovenian",sr:"Serbian"},i.regionNames={US:"United States",GB:"United Kingdom",AU:"Australia",CA:"Canada",IN:"India",IE:"Ireland",ZA:"South Africa",NZ:"New Zealand",FR:"France",DE:"Germany",IT:"Italy",ES:"Spain",MX:"Mexico",JP:"Japan",KR:"Korea",CN:"China",TW:"Taiwan",HK:"Hong Kong",BR:"Brazil",PT:"Portugal",RU:"Russia"},i.iso1To3={ar:"ara",bg:"bul",ca:"cat",cs:"ces",da:"dan",de:"deu",el:"ell",en:"eng",es:"spa",et:"est",fi:"fin",fr:"fra",he:"heb",hi:"hin",hr:"hrv",hu:"hun",id:"ind",it:"ita",ja:"jpn",ko:"kor",lt:"lit",lv:"lav",ms:"msa",nl:"nld",no:"nor",pl:"pol",pt:"por",ro:"ron",ru:"rus",sk:"slk",sl:"slv",sr:"srp",sv:"swe",th:"tha",tr:"tur",uk:"ukr",vi:"vie",zh:"zho"};const s={sapi:{supportsSSML:!0,supportLevel:"full",supportedTags:["speak","prosody","break","emphasis","voice","phoneme","say-as","sub","p","s"],unsupportedTags:[],requiresNamespace:!1,requiresVersion:!0},witai:{supportsSSML:!0,supportLevel:"full",supportedTags:["speak","prosody","break","emphasis","voice","phoneme","say-as","sub","p","s"],unsupportedTags:[],requiresNamespace:!1,requiresVersion:!1},watson:{supportsSSML:!0,supportLevel:"full",supportedTags:["speak","prosody","break","emphasis","voice","phoneme","say-as","sub","p","s"],unsupportedTags:[],requiresNamespace:!1,requiresVersion:!1},azure:{supportsSSML:!0,supportLevel:"full",supportedTags:["speak","prosody","break","emphasis","voice","phoneme","say-as","sub","p","s","mstts:express-as"],unsupportedTags:[],requiresNamespace:!0,requiresVersion:!0},polly:{supportsSSML:!0,supportLevel:"limited",supportedTags:["speak","prosody","break","voice","phoneme","say-as","sub","p","s","mark","lang"],unsupportedTags:[],requiresNamespace:!0,requiresVersion:!1},google:{supportsSSML:!0,supportLevel:"limited",supportedTags:["speak","prosody","break","emphasis","voice","phoneme","say-as","sub","p","s","mark","lang","audio"],unsupportedTags:[],requiresNamespace:!1,requiresVersion:!1},elevenlabs:{supportsSSML:!1,supportLevel:"none",supportedTags:[],unsupportedTags:["*"],requiresNamespace:!1,requiresVersion:!1},openai:{supportsSSML:!1,supportLevel:"none",supportedTags:[],unsupportedTags:["*"],requiresNamespace:!1,requiresVersion:!1},playht:{supportsSSML:!1,supportLevel:"none",supportedTags:[],unsupportedTags:["*"],requiresNamespace:!1,requiresVersion:!1},upliftai:{supportsSSML:!1,supportLevel:"none",supportedTags:[],unsupportedTags:["*"],requiresNamespace:!1,requiresVersion:!1},sherpaonnx:{supportsSSML:!1,supportLevel:"none",supportedTags:[],unsupportedTags:["*"],requiresNamespace:!1,requiresVersion:!1},"sherpaonnx-wasm":{supportsSSML:!1,supportLevel:"none",supportedTags:[],unsupportedTags:["*"],requiresNamespace:!1,requiresVersion:!1},espeak:{supportsSSML:!0,supportLevel:"limited",supportedTags:["speak","prosody","break","emphasis","p","s"],unsupportedTags:["voice","phoneme","say-as","sub"],requiresNamespace:!1,requiresVersion:!1},"espeak-wasm":{supportsSSML:!0,supportLevel:"limited",supportedTags:["speak","prosody","break","emphasis","p","s"],unsupportedTags:["voice","phoneme","say-as","sub"],requiresNamespace:!1,requiresVersion:!1}},o={polly:{standard:{supportLevel:"full",unsupportedTags:[]},"long-form":{supportLevel:"full",unsupportedTags:[]},neural:{supportLevel:"limited",unsupportedTags:["emphasis","amazon:auto-breaths","amazon:effect"]},generative:{supportLevel:"limited",unsupportedTags:["emphasis","amazon:auto-breaths","amazon:effect","mark"]}},google:{standard:{supportLevel:"full",unsupportedTags:[]},wavenet:{supportLevel:"full",unsupportedTags:[]},neural2:{supportLevel:"limited",unsupportedTags:["mark"]},journey:{supportLevel:"none",unsupportedTags:["*"]},studio:{supportLevel:"none",unsupportedTags:["*"]}}};class a{static getCapabilities(e,t){const r=s[e];if(!r)return{supportsSSML:!1,supportLevel:"none",supportedTags:[],unsupportedTags:["*"],requiresNamespace:!1,requiresVersion:!1};if(t&&o[e]){const n=a.getVoiceSpecificCapabilities(e,t);if(n)return{...r,supportLevel:n.supportLevel,unsupportedTags:n.unsupportedTags}}return r}static getVoiceSpecificCapabilities(e,t){const r=o[e];if(!r)return null;return r[a.detectVoiceType(e,t)]||null}static detectVoiceType(e,t){const r=t.toLowerCase();switch(e){case"polly":return r.includes("neural")?"neural":r.includes("generative")?"generative":r.includes("long-form")?"long-form":"standard";case"google":return r.includes("neural2")?"neural2":r.includes("journey")?"journey":r.includes("studio")?"studio":r.includes("wavenet")?"wavenet":(r.includes("standard"),"standard");default:return"default"}}static validateSSML(e,t,r){const n=a.getCapabilities(t,r),i=[],s=[];if(e.trim().startsWith("<speak")&&e.trim().endsWith("</speak>")||i.push("SSML must be wrapped in <speak> tags"),!n.supportsSSML)return s.push(`Engine '${t}' does not support SSML. Tags will be stripped.`),{isValid:!0,errors:i,warnings:s};if(n.unsupportedTags.includes("*"))s.push(`Engine '${t}' does not support any SSML tags. All tags will be stripped.`);else for(const r of n.unsupportedTags){new RegExp(`<${r}[^>]*>`,"gi").test(e)&&s.push(`Tag '<${r}>' is not supported by engine '${t}' and will be removed.`)}return n.requiresNamespace&&!e.includes("xmlns=")&&s.push(`Engine '${t}' requires xmlns attribute in <speak> tag.`),n.requiresVersion&&!e.includes("version=")&&s.push(`Engine '${t}' requires version attribute in <speak> tag.`),{isValid:0===i.length,errors:i,warnings:s}}static processSSMLForEngine(e,t,r){const n=a.getCapabilities(t,r);if(!n.supportsSSML)return a.stripAllSSMLTags(e);let i=e;if(n.unsupportedTags.includes("*"))return a.stripAllSSMLTags(e);for(const e of n.unsupportedTags)i=a.removeSSMLTag(i,e);return i=a.addRequiredAttributes(i,n),i}static stripAllSSMLTags(e){let t=e;t=t.replace(/<speak[^>]*>/gi,""),t=t.replace(/<\/speak>/gi,""),t=t.replace(/<break[^>]*\/?>/gi," ");let r="";for(;t!==r;)r=t,t=t.replace(/<emphasis[^>]*>(.*?)<\/emphasis>/gis,"$1"),t=t.replace(/<prosody[^>]*>(.*?)<\/prosody>/gis,"$1"),t=t.replace(/<voice[^>]*>(.*?)<\/voice>/gis,"$1"),t=t.replace(/<say-as[^>]*>(.*?)<\/say-as>/gis,"$1"),t=t.replace(/<phoneme[^>]*>(.*?)<\/phoneme>/gis,"$1"),t=t.replace(/<sub[^>]*>(.*?)<\/sub>/gis,"$1"),t=t.replace(/<p[^>]*>(.*?)<\/p>/gis,"$1 "),t=t.replace(/<s[^>]*>(.*?)<\/s>/gis,"$1 "),t=t.replace(/<lang[^>]*>(.*?)<\/lang>/gis,"$1"),t=t.replace(/<audio[^>]*>(.*?)<\/audio>/gis,"$1"),t=t.replace(/<mark[^>]*\/?>/gi,""),t=t.replace(/<[^>]+>/g,"");return t=t.replace(/\s+/g," ").trim(),t}static removeSSMLTag(e,t){let r=e;const n=new RegExp(`<${t}[^>]*\\/>`,"gi");r=r.replace(n,"");const i=new RegExp(`<${t}[^>]*>(.*?)<\\/${t}>`,"gi");return r=r.replace(i,"$1"),r}static addRequiredAttributes(e,t){let r=e;return t.requiresNamespace&&!e.includes("xmlns=")&&(r=r.replace(/<speak([^>]*)>/i,'<speak$1 xmlns="http://www.w3.org/2001/10/synthesis">')),t.requiresVersion&&!e.includes("version=")&&(r=r.replace(/<speak([^>]*)>/i,'<speak version="1.0"$1>')),r}}function l(e){return e.trim().startsWith("<speak")&&e.trim().endsWith("</speak>")}function c(e,t,r){return a.validateSSML(e,t,r)}function d(e,t,r){return a.processSSMLForEngine(e,t,r)}function u(e){return e.replace(/<speak.*?>/g,"").replace(/<\/speak>/g,"").replace(/<break.*?\/>/g," ").replace(/<emphasis.*?>(.*?)<\/emphasis>/g,"$1").replace(/<prosody.*?>(.*?)<\/prosody>/g,"$1").replace(/<voice.*?>(.*?)<\/voice>/g,"$1").replace(/<say-as.*?>(.*?)<\/say-as>/g,"$1").replace(/<phoneme.*?>(.*?)<\/phoneme>/g,"$1").replace(/<sub.*?>(.*?)<\/sub>/g,"$1").replace(/<p>(.*?)<\/p>/g,"$1 ").replace(/<s>(.*?)<\/s>/g,"$1 ").replace(/\s+/g," ").trim()}function h(e){return l(e)?e:`<speak>${e}</speak>`}const p="undefined"!=typeof window,m=!p&&"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node,f=e=>{if(m){return new Function("n","return require(n)")("node:fs").readFileSync(e,"utf-8")}throw new Error("Synchronous file reading is not supported in browsers")},g=e=>{if(m){return new Function("n","return require(n)")("node:fs").existsSync(e)}throw new Error("Synchronous file existence check is not supported in browsers")},y=(...e)=>{if(m){return new Function("n","return require(n)")("node:path").join(...e)}return e.join("/").replace(/\/+/g,"/")};async function w(e){const t=[];let r=0;if("getReader"in e&&"function"==typeof e.getReader){const n=e.getReader();try{for(;;){const{done:e,value:i}=await n.read();if(e)break;i&&(t.push(i),r+=i.length)}}finally{n.releaseLock()}if(m){const e=t.map((e=>Buffer.from(e)));return Buffer.concat(e,r)}const i=new Uint8Array(r);let s=0;for(const e of t)i.set(e,s),s+=e.length;return i}if("function"==typeof e.on)return new Promise(((n,i)=>{const s=e;s.on("data",(e=>{const n=Buffer.isBuffer(e)?e:Buffer.from(e);t.push(n),r+=n.length})),s.on("end",(()=>{n(Buffer.concat(t,r))})),s.on("error",(e=>{i(e)}))}));throw new Error("Unsupported stream type provided to streamToBuffer")}function v(e){const t=[e.text,e.filename,e.audioBytes,e.audioStream].filter(Boolean).length;if(0===t)throw new Error("No input provided. Please provide text, filename, audioBytes, or audioStream.");if(t>1)throw new Error("Multiple input sources provided. Please provide only one of: text, filename, audioBytes, or audioStream.")}function b(e){switch(e.toLowerCase().split(".").pop()){case"mp3":return"audio/mpeg";case"wav":default:return"audio/wav";case"ogg":return"audio/ogg";case"opus":return"audio/opus";case"aac":return"audio/aac";case"flac":return"audio/flac"}}function T(e){if(e.length<4)return"audio/wav";const t=Array.from(e.slice(0,12));return 73===t[0]&&68===t[1]&&51===t[2]||255===t[0]&&!(224&~t[1])?"audio/mpeg":82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]&&87===t[8]&&65===t[9]&&86===t[10]&&69===t[11]?"audio/wav":79===t[0]&&103===t[1]&&103===t[2]&&83===t[3]?"audio/ogg":102===t[0]&&76===t[1]&&97===t[2]&&67===t[3]?"audio/flac":"audio/wav"}async function S(e){if(!m)throw new Error("File reading is only supported in Node.js environment");try{const t=await new Function("m","return import(m)")("node:fs/promises"),r=await t.readFile(e);return new Uint8Array(r)}catch(t){throw new Error(`Failed to read audio file "${e}": ${t instanceof Error?t.message:String(t)}`)}}async function x(e){const t=await w(e);return t instanceof Buffer?new Uint8Array(t):t}var k=Object.freeze({__proto__:null,detectAudioFormat:T,getAudioFormatFromFilename:b,processAudioInput:async function(e){if(v(e),e.audioBytes)return{audioBytes:e.audioBytes,mimeType:T(e.audioBytes)};if(e.audioStream){const t=await x(e.audioStream);return{audioBytes:t,mimeType:T(t)}}if(e.filename){return{audioBytes:await S(e.filename),mimeType:b(e.filename)}}throw new Error("No valid audio input provided")},readAudioFile:S,streamToBytes:x,validateSpeakInput:v});class M{constructor(e){this.credentials=e,this.voiceId=null,this.lang="en-US",this.callbacks={},this.properties={volume:100,rate:"medium",pitch:"medium"},this.timings=[],this.capabilities={browserSupported:!0,nodeSupported:!0,needsWasm:!1},this.sampleRate=24e3,this.ssml=new n,this.audio={isPlaying:!1,isPaused:!1,audioElement:null,position:0,duration:0}}async synthToBytesWithFormat(e,t){return this.synthToBytesWithConversion(e,t)}async synthToBytesWithConversion(e,t){const r=await this.synthToBytes(e,t);if(!(null==t?void 0:t.format))return r;const n=t.format,i=this.detectNativeFormat(r);if(i===n)return r;if(!m)return console.warn(`Audio format conversion not available in browser. Returning native format (${i}) instead of requested format (${n})`),r;try{const{isAudioConversionAvailable:e,convertAudioFormat:t}=await new Function("m","return import(m)")("../utils/audio-converter");if(e())try{return(await t(r,n)).audioBytes}catch(e){console.warn(`Audio format conversion failed: ${e instanceof Error?e.message:String(e)}`),console.warn(`Returning native format (${i}) instead of requested format (${n})`)}else console.warn(`Audio format conversion not available. Returning native format (${i}) instead of requested format (${n})`)}catch(e){console.warn(`Audio converter not available at runtime; returning native format (${i})`)}return r}detectNativeFormat(e){switch(T(e)){case"audio/mpeg":return"mp3";case"audio/ogg":return"ogg";default:return"wav"}}async getVoices(){const e=await this._getVoices();return(await this._mapVoicesToUnified(e)).map((e=>{const t=e.languageCodes.map((e=>{const t=i.normalize(e.bcp47);return{bcp47:t.bcp47,iso639_3:t.iso639_3,display:t.display}}));return{...e,languageCodes:t}}))}async _mapVoicesToUnified(e){return e}async speak(e,t){this.emit("start");try{let r,n;if("string"==typeof e)r=await this.synthToBytesWithConversion(e,t),n=T(r);else{const{processAudioInput:t}=await Promise.resolve().then((function(){return k})),i=await t(e);r=i.audioBytes,n=i.mimeType}if(p){const t=new ArrayBuffer(r.byteLength);new Uint8Array(t).set(r);const i=new Blob([t],{type:n}),s=URL.createObjectURL(i),o=new Audio;o.oncanplay=async()=>{try{this.audio.audioElement=o,this.audio.isPlaying=!0,this.audio.isPaused=!1,"string"==typeof e&&this._createEstimatedWordTimings(e),await o.play()}catch(e){console.error("Error playing audio:",e),this.emit("end")}},o.onerror=e=>{console.error("Audio playback error:",e),this.emit("end"),URL.revokeObjectURL(s)},o.onended=()=>{this.emit("end"),this.audio.isPlaying=!1,URL.revokeObjectURL(s)},o.src=s}else if(m)try{const{isNodeAudioAvailable:t,playAudioInNode:n}=await new Function("m","return import(m)")("../utils/node-audio"),i=await t();"string"==typeof e&&this._createEstimatedWordTimings(e),i?(this.emit("start"),this._scheduleWordBoundaryCallbacks(),await n(r,this.sampleRate,this.constructor.name.replace("TTSClient","").toLowerCase()),this.emit("end")):(console.log("Audio playback in Node.js requires the sound-play package."),console.log("Install it with: npm install js-tts-wrapper[node-audio]"),console.log("Or use synthToFile() to save audio to a file and play it with an external player."),this._fireWordBoundaryCallbacks(),this.emit("end"))}catch(e){console.error("Error playing audio in Node.js:",e),this._fireWordBoundaryCallbacks(),this.emit("end")}else console.log("Audio playback is not supported in this environment."),console.log("Use synthToFile() to save audio to a file and play it with an external player."),this.emit("end")}catch(e){throw console.error("Error in speak method:",e),this.emit("end"),e}}async speakStreamed(e,t){this.emit("start");try{let r,n,i=[],s="";if("string"==typeof e){s=e;const o=await this.synthToBytestream(s,t),a=o.audioStream;i=o.wordBoundaries;const l=a.getReader(),c=[];let d=await l.read();for(;!d.done;)c.push(d.value),d=await l.read();const u=c.reduce(((e,t)=>e+t.length),0);r=new Uint8Array(u);let h=0;for(const e of c)r.set(e,h),h+=e.length;if(null==t?void 0:t.format)if(m)try{const{isAudioConversionAvailable:e,convertAudioFormat:i}=await new Function("m","return import(m)")("../utils/audio-converter");if(e()){const e=await i(r,t.format);r=e.audioBytes,n=e.mimeType}else n=T(r)}catch(e){console.warn(`Streaming format conversion failed: ${e instanceof Error?e.message:String(e)}`),n=T(r)}else n=T(r);else n=T(r)}else{const{processAudioInput:t}=await Promise.resolve().then((function(){return k})),i=await t(e);r=i.audioBytes,n=i.mimeType,s=""}if(i.length>0?this.timings=i.map((e=>[e.offset/1e4,(e.offset+e.duration)/1e4,e.text])):s?this._createEstimatedWordTimings(s):this.timings=[],p){const e=new ArrayBuffer(r.byteLength);new Uint8Array(e).set(r);const t=new Blob([e],{type:n}),i=URL.createObjectURL(t),s=new Audio;s.oncanplay=async()=>{try{this.audio.audioElement=s,this.audio.isPlaying=!0,this.audio.isPaused=!1,await s.play()}catch(e){console.error("Error playing audio:",e),this.emit("end")}},s.onerror=e=>{console.error("Audio playback error:",e),this.emit("end"),URL.revokeObjectURL(i)},s.onended=()=>{this.emit("end"),this.audio.isPlaying=!1,URL.revokeObjectURL(i)},s.src=i}else if(m){console.log("🔍 Taking Node.js audio path");try{const{isNodeAudioAvailable:e,playAudioInNode:t}=await new Function("m","return import(m)")("../utils/node-audio"),n=await e();console.log(`🔍 Audio available: ${n}`),s&&(console.log(`🔍 Creating estimated word timings for: "${s}"`),this._createEstimatedWordTimings(s),console.log(`🔍 Created ${this.timings.length} timings`)),n?(console.log("🔍 Audio available - scheduling word boundary callbacks"),this._scheduleWordBoundaryCallbacks(),await t(r,this.sampleRate,this.constructor.name.replace("TTSClient","").toLowerCase()),this.emit("end")):(console.log("Audio playback in Node.js requires the sound-play package."),console.log("Install it with: npm install js-tts-wrapper[node-audio]"),console.log("Or use synthToFile() to save audio to a file and play it with an external player."),this._fireWordBoundaryCallbacks(),this.emit("end"))}catch(e){console.error("Error playing audio in Node.js:",e),this._fireWordBoundaryCallbacks(),this.emit("end")}}else console.log("Audio playback is not supported in this environment."),console.log("Use synthToFile() to save audio to a file and play it with an external player."),s&&this._createEstimatedWordTimings(s),setTimeout((()=>{this._fireWordBoundaryCallbacks(),this.emit("end")}),100)}catch(e){throw console.error("Error in streaming synthesis:",e),this.emit("end"),e}}async synthToFile(e,t,r="wav",n){const i=await this.synthToBytesWithConversion(e,{...n,format:r});if(p){const e="mp3"===r?"audio/mpeg":"audio/wav",n=new ArrayBuffer(i.byteLength);new Uint8Array(n).set(i);const s=new Blob([n],{type:e}),o=URL.createObjectURL(s),a=document.createElement("a");a.href=o,a.download=t.endsWith(`.${r}`)?t:`${t}.${r}`,document.body.appendChild(a),a.click(),requestAnimationFrame((()=>{var e;(null===(e=null===document||void 0===document?void 0:document.body)||void 0===e?void 0:e.contains(a))&&document.body.removeChild(a),URL.revokeObjectURL(o)}))}else if(m){const e=t.endsWith(`.${r}`)?t:`${t}.${r}`;(await new Function("m","return import(m)")("node:fs")).writeFileSync(e,Buffer.from(i))}else console.warn("File saving not implemented for this environment.")}setVoice(e,t){this.voiceId=e,t&&(this.lang=t)}pause(){if(p)this.audio.audioElement&&this.audio.isPlaying&&!this.audio.isPaused&&(this.audio.audioElement.pause(),this.audio.isPaused=!0);else if(m)try{Promise.resolve().then((function(){return Ne})).then((e=>{e.pauseAudioPlayback()&&(this.audio.isPaused=!0)})).catch((e=>{console.error("Error importing node-audio-control:",e)}))}catch(e){console.error("Error pausing audio in Node.js:",e)}}resume(){if(p)this.audio.audioElement&&this.audio.isPlaying&&this.audio.isPaused&&(this.audio.audioElement.play(),this.audio.isPaused=!1);else if(m)try{Promise.resolve().then((function(){return Ne})).then((e=>{e.resumeAudioPlayback()&&(this.audio.isPaused=!1)})).catch((e=>{console.error("Error importing node-audio-control:",e)}))}catch(e){console.error("Error resuming audio in Node.js:",e)}}stop(){if(p)this.audio.audioElement&&(this.audio.audioElement.pause(),this.audio.audioElement.currentTime=0,this.audio.isPlaying=!1,this.audio.isPaused=!1);else if(m)try{Promise.resolve().then((function(){return Ne})).then((e=>{e.stopAudioPlayback()&&(this.audio.isPlaying=!1,this.audio.isPaused=!1)})).catch((e=>{console.error("Error importing node-audio-control:",e)}))}catch(e){console.error("Error stopping audio in Node.js:",e)}}_createEstimatedWordTimings(e){const t=(this._isSSML(e)?this._stripSSML(e):e).split(/\s+/).filter((e=>e.length>0));if(!t.length)return;const r=.3*t.length/t.length;this.timings=[];for(let e=0;e<t.length;e++){const n=e*r,i=(e+1)*r;this.timings.push([n,i,t[e]])}}_fireWordBoundaryCallbacks(){if(this.timings.length)for(const[e,t,r]of this.timings)this.emit("boundary",{text:r,offset:Math.round(1e4*e),duration:Math.round(1e4*(t-e))})}_scheduleWordBoundaryCallbacks(){if(this.timings.length)for(const[e,t,r]of this.timings){const n={text:r,offset:Math.round(1e4*e),duration:Math.round(1e4*(t-e))};setTimeout((()=>{this.emit("boundary",n)}),1e3*e)}}_isSSML(e){return l(e)}_stripSSML(e){return u(e)}on(e,t){this.callbacks[e]=this.callbacks[e]||[],this.callbacks[e].push(t)}emit(e,...t){for(const r of this.callbacks[e]||[])r(...t)}async startPlaybackWithCallbacks(e,t,r){await this.speak(e,r);for(const[e,r,n]of this.timings)setTimeout((()=>{t(n,e,r)}),1e3*e)}connect(e,t){"onStart"===e?this.on("start",t):"onEnd"===e&&this.on("end",t)}getProperty(e){return this.properties[e]}setProperty(e,t){this.properties[e]=t}constructProsodyTag(e){const t=[];return this.properties.rate&&t.push(`rate="${this.properties.rate}"`),this.properties.pitch&&t.push(`pitch="${this.properties.pitch}"`),this.properties.volume&&t.push(`volume="${this.properties.volume}%"`),0===t.length?e:`<prosody ${t.join(" ")}>${e}</prosody>`}async checkCredentials(){try{return(await this._getVoices()).length>0}catch(e){return console.error("Error checking credentials:",e),!1}}async checkCredentialsDetailed(){try{const e=await this._getVoices();return{success:e.length>0,voiceCount:e.length}}catch(e){return console.error("Error checking credentials:",e),{success:!1,error:e instanceof Error?e.message:String(e)}}}async getCredentialStatus(){const e="undefined"!=typeof window,t=this.constructor.name.replace("TTSClient","").toLowerCase();try{const r=await this.checkCredentials(),n=this.getRequiredCredentials().length>0;let i=[];if(r&&n)try{i=await this._getVoices()}catch(e){console.warn("getCredentialStatus: _getVoices() failed; continuing without voices",e),i=[]}return{valid:r,engine:t,environment:e?"browser":"node",requiresCredentials:n,credentialTypes:this.getRequiredCredentials(),message:r?`${t} credentials are valid and ${i.length} voices are available`:`${t} credentials are invalid or service is unavailable`,details:{voiceCount:i.length,hasCredentials:Object.keys(this.credentials||{}).length>0}}}catch(r){return{valid:!1,engine:t,environment:e?"browser":"node",requiresCredentials:this.getRequiredCredentials().length>0,credentialTypes:this.getRequiredCredentials(),message:`Error validating ${t} credentials`,error:r instanceof Error?r.message:String(r)}}}getRequiredCredentials(){return[]}async getVoicesByLanguage(e){const t=i.normalize(e);return(await this.getVoices()).filter((e=>e.languageCodes.some((e=>e.bcp47===t.bcp47||e.iso639_3===t.iso639_3))))}}function A(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var E,_,O={},P={},C={},L={},U={};function I(){if(E)return U;E=1,Object.defineProperty(U,"__esModule",{value:!0}),U.FormatterBase=void 0;var e=function(){function e(e){this.options=e,this.options=e}return e.prototype.addArray=function(e,t){for(var r=0,n=e;r<n.length;r++){var i=n[r];this.formatFromAst(i,t)}return t},e.prototype.processAst=function(e,t){e instanceof Array?this.addArray(e,t):this.formatFromAst(e,t)},e}();return U.FormatterBase=e,U}var j,$,B={},F={};function N(){if(j)return F;j=1;var e,t=F&&F.__extends||(e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)},function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}),r=F&&F.__assign||function(){return r=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},n=F&&F.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(F,"__esModule",{value:!0}),F.SsmlFormatterBase=F.TagsObject=void 0;var i=I(),s=function(){function e(e){this.base=e,this.tags={},this.text=""}return e.prototype.tag=function(e,t,n){void 0===n&&(n=!1);var i=this.base.ssmlTagSortOrder.indexOf(e);this.tags[e]||(this.tags[e]={sortId:i,attrs:null}),this.tags[e].attrs=n?r(r({},this.tags[e].attrs),t):t},e.prototype.voiceTagNamed=function(e,t){var r=this,n=e&&e[t];return!!n&&("object"!=typeof n&&(n={voice:{name:t}}),Object.keys(n).forEach((function(e){var t=n[e];r.tag(e,t)})),!0)},e.prototype.voiceTag=function(e,t){var r=this.base.sentenceCase(t||"device");this.voiceTagNamed(this.base.options&&this.base.options.voices,r)||this.voiceTagNamed(this.base.validVoices,r)},e}();F.TagsObject=s;var o=function(e){function r(t){var r=e.call(this,t)||this;return r.options=t,r.validVoices={},r.sectionTags=[],r.modifierKeyMappings={chars:"characters",cardinal:"number",digits:"characters",bleep:"expletive",phone:"telephone",vol:"volume"},r.ssmlTagSortOrder=["emphasis","say-as","prosody","amazon:domain","amazon:effect","amazon:emotion","voice","lang","sub","phoneme"],r.modifierKeyToSsmlTagMappings={emphasis:"emphasis",address:"say-as",number:"say-as",characters:"say-as",expletive:"say-as",fraction:"say-as",interjection:"say-as",ordinal:"say-as",telephone:"say-as",unit:"say-as",time:"say-as",date:"say-as",whisper:null,sub:"sub",ipa:"phoneme",rate:"prosody",pitch:"prosody",volume:"prosody",drc:null,timbre:null,lang:null,voice:null,dj:null,defaults:null,newscaster:null,excited:null,disappointed:null},r}var i;return t(r,e),r.prototype.format=function(e){return this.formatFromAst(e,[]).join("")},r.prototype.addSectionStartTag=function(e,t,r){this.sectionTags=n([],e,!0).reverse();for(var i=0;i<e.length;i++){var s=e[i],o=t.tags[s].attrs;r.push("\n"),r.push(this.startTag(s,o,!1))}},r.prototype.addSectionEndTag=function(e){if(this.sectionTags.length>0)for(var t=0;t<this.sectionTags.length;t++){var r=this.sectionTags[t];e.push(this.endTag(r,!1)),e.push("\n")}},r.prototype.addTag=function(e,t,r,n,i,s){return s.push(this.startTag(e,i,r)),this.processAst(t,s),s.push(this.endTag(e,r)),n&&s.push("\n"),s},r.prototype.addSpeakTag=function(e,t,r,n,i){return i.push(this.startTag("speak",n,t)),this.processAst(e,i),this.addSectionEndTag(i),i.push(this.endTag("speak",t)),r&&i.push("\n"),i},r.prototype.addComment=function(e,t){return t.push("\x3c!-- ".concat(e," --\x3e\n")),t},r.prototype.startTag=function(e,t,r){void 0===r&&(r=!1);var n="";return t&&(n=" "+Object.keys(t).map((function(e){return e+'="'+t[e]+'"'})).join(" ")),"<"+e+n+">"+(r?"\n":"")},r.prototype.endTag=function(e,t){return void 0===t&&(t=!1),(t?"\n":"")+"</"+e+">"},r.prototype.voidTag=function(e,t){var r="";return t&&(r=" "+Object.keys(t).map((function(e){return e+'="'+t[e]+'"'})).join(" ")),"<"+e+r+"/>"},r.prototype.addTagWithAttrs=function(e,t,r,n,i){return void 0===i&&(i=!1),t||i?(e.push(this.startTag(r,n)),t&&e.push(t),e.push(this.endTag(r,!1))):e.push(this.voidTag(r,n)),e},r.prototype.getTagWithAttrs=function(e,t,r){var n=[];return e?(n.push(this.startTag(t,r)),n.push(e),n.push(this.endTag(t,!1))):n.push(this.voidTag(t,r)),n.join("")},r.prototype.sentenceCase=function(e){return e.replace(/[a-z]/i,(function(e){return e.toUpperCase()})).trim()},r.prototype.escapeXmlCharacters=function(e){var t="".concat(Object.keys(r.XML_UNESCAPE_MAPPING).join("|"),"]"),n=e.replace(new RegExp(t,"g"),(function(e){return r.XML_UNESCAPE_MAPPING[e]})),i="[".concat(Object.keys(r.XML_ESCAPE_MAPPING).join(""),"]");return n.replace(new RegExp(i,"g"),(function(e){return r.XML_ESCAPE_MAPPING[e]}))},r.XML_ESCAPE_MAPPING={"<":"&lt;",">":"&gt;","&":"&amp;",'"':"&quot;","'":"&apos;"},r.XML_UNESCAPE_MAPPING=(i=r.XML_ESCAPE_MAPPING,Object.keys(i).reduce((function(e,t){return e[i[t]]=t,e}),{})),r}(i.FormatterBase);return F.SsmlFormatterBase=o,F}var W,R={};var z,K={};var V,q={};var D,G={};var H,J,X={};function Q(){if(J)return C;J=1,Object.defineProperty(C,"__esModule",{value:!0}),C.createTextFormatter=C.createFormatter=void 0;var e=function(){if(_)return L;_=1;var e,t=L&&L.__extends||(e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)},function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)});Object.defineProperty(L,"__esModule",{value:!0}),L.TextFormatter=void 0;var r=function(e){function r(t){var r=e.call(this,t)||this;return r.options=t,r}return t(r,e),r.prototype.format=function(e){var t=this.formatFromAst(e,[]).join("").trim();return t.replace(/ +/g," ")},r.prototype.formatFromAst=function(e,t){switch(void 0===t&&(t=[]),e.name){case"document":case"paragraph":case"simpleLine":default:return this.processAst(e.children,t),t;case"lineEnd":case"plainText":case"plainTextSpecialChars":case"plainTextEmphasis":case"plainTextPhone":case"plainTextModifier":return t.push(e.allText),t;case"emptyLine":return this.options.preserveEmptyLines&&t.push(e.allText),t;case"audio":return t}},r}(I().FormatterBase);return L.TextFormatter=r,L}(),t=function(){if($)return B;$=1;var e,t=B&&B.__extends||(e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)},function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)});Object.defineProperty(B,"__esModule",{value:!0}),B.AmazonAlexaSsmlFormatter=void 0;var r=N(),n=function(e){function n(t){var r=e.call(this,t)||this;return r.options=t,r.validVoices={Ivy:"en-US",Joanna:"en-US",Joey:"en-US",Justin:"en-US",Kendra:"en-US",Kimberly:"en-US",Matthew:"en-US",Salli:"en-US",Nicole:"en-AU",Russell:"en-AU",Amy:"en-GB",Brian:"en-GB",Emma:"en-GB",Aditi:"en-IN",Raveena:"en-IN",Hans:"de-DE",Marlene:"de-DE",Vicki:"de-DE",Conchita:"es-ES",Enrique:"es-ES",Carla:"it-IT",Giorgio:"it-IT",Mizuki:"ja-JP",Takumi:"ja-JP",Celine:"fr-FR",Lea:"fr-FR",Mathieu:"fr-FR"},r.validEmotionIntensity=["low","medium","high"],r.modifierKeyToSsmlTagMappings.whisper="amazon:effect",r.modifierKeyToSsmlTagMappings.lang="lang",r.modifierKeyToSsmlTagMappings.voice="voice",r.modifierKeyToSsmlTagMappings.dj="amazon:domain",r.modifierKeyToSsmlTagMappings.newscaster="amazon:domain",r.modifierKeyToSsmlTagMappings.excited="amazon:emotion",r.modifierKeyToSsmlTagMappings.disappointed="amazon:emotion",r}return t(n,e),n.prototype.getTextModifierObject=function(e){for(var t=new r.TagsObject(this),n=0;n<e.children.length;n++){var i=e.children[n];switch(i.name){case"plainText":case"plainTextSpecialChars":case"plainTextEmphasis":case"plainTextPhone":case"plainTextModifier":t.text=i.allText;break;case"textModifierKeyOptionalValue":var s=i.children[0].allText;s=this.modifierKeyMappings[s]||s;var o=2===i.children.length?i.children[1].allText:"",a=this.modifierKeyToSsmlTagMappings[s];switch(s){case"emphasis":t.tag(a,{level:o||"moderate"});break;case"address":case"characters":case"expletive":case"fraction":case"interjection":case"number":case"ordinal":case"telephone":case"unit":t.tag(a,{"interpret-as":s});break;case"date":t.tag(a,{"interpret-as":s,format:o||"ymd"});break;case"time":t.tag(a,{"interpret-as":s,format:o||"hms12"});break;case"whisper":t.tag(a,{name:"whispered"});break;case"ipa":t.tag(a,{alphabet:s,ph:o});break;case"sub":t.tag(a,{alias:o});break;case"volume":case"rate":case"pitch":var l={};l[s]=o||"medium",t.tag(a,l,!0);break;case"lang":t.tag(a,{"xml:lang":o});break;case"voice":t.voiceTag(s,o);break;case"excited":case"disappointed":var c=(o||"medium").toLowerCase();if(this.validEmotionIntensity.includes(c)){t.tag(a,{name:s,intensity:c});break}}}}return t},n.prototype.getSectionObject=function(e){for(var t=new r.TagsObject(this),n=0;n<e.children.length;n++){var i=e.children[n];if("sectionModifierKeyOptionalValue"===i.name){var s=i.children[0].allText,o=2===i.children.length?i.children[1].allText:"",a=this.modifierKeyToSsmlTagMappings[s];switch(s){case"lang":t.tag(a,{"xml:lang":o});break;case"voice":t.voiceTag(s,o);break;case"dj":t.tag(a,{name:"music"});break;case"newscaster":t.tag(a,{name:"news"});break;case"defaults":break;case"excited":case"disappointed":var l=(o||"medium").toLowerCase();if(this.validEmotionIntensity.includes(l)){t.tag(a,{name:s,intensity:l});break}}}}return t},n.prototype.formatFromAst=function(e,t){switch(void 0===t&&(t=[]),e.name){case"document":return this.options.includeFormatterComment&&this.addComment("Converted from Speech Markdown to SSML for Amazon Alexa",t),this.options.includeSpeakTag?this.addSpeakTag(e.children,!0,!1,null,t):(this.processAst(e.children,t),t);case"paragraph":return this.options.includeParagraphTag?this.addTag("p",e.children,!0,!1,null,t):(this.processAst(e.children,t),t);case"shortBreak":var r=e.children[0].allText;return this.addTagWithAttrs(t,null,"break",{time:r});case"break":var n=e.children[0].allText,i={};switch(e.children[0].children[0].name){case"breakStrengthValue":i={strength:n};break;case"time":i={time:n}}return this.addTagWithAttrs(t,null,"break",i);case"shortEmphasisModerate":var s=e.children[0].allText;return this.addTagWithAttrs(t,s,"emphasis",{level:"moderate"});case"shortEmphasisStrong":return s=e.children[0].allText,this.addTagWithAttrs(t,s,"emphasis",{level:"strong"});case"shortEmphasisNone":return s=e.children[0].allText,this.addTagWithAttrs(t,s,"emphasis",{level:"none"});case"shortEmphasisReduced":return s=e.children[0].allText,this.addTagWithAttrs(t,s,"emphasis",{level:"reduced"});case"textModifier":for(var o=this.getTextModifierObject(e),a=Object.keys(o.tags).sort((function(e,t){return o.tags[t].sortId-o.tags[e].sortId})),l=o.text,c=0;c<a.length;c++){var d=a[c];i=o.tags[d].attrs,l=this.getTagWithAttrs(l,d,i)}return t.push(l),t;case"section":var u=this.getSectionObject(e),h=Object.keys(u.tags).sort((function(e,t){return u.tags[e].sortId-u.tags[t].sortId}));return this.addSectionEndTag(t),this.addSectionStartTag(h,u,t),t;case"audio":c=2===e.children.length?1:0;var p=e.children[c].allText.replace(/&/g,"&amp;");return this.addTagWithAttrs(t,null,"audio",{src:p});case"simpleLine":default:return this.processAst(e.children,t),t;case"lineEnd":return t.push(e.allText),t;case"emptyLine":return this.options.preserveEmptyLines&&t.push(e.allText),t;case"plainText":case"plainTextSpecialChars":return s=this.options.escapeXmlSymbols?this.escapeXmlCharacters(e.allText):e.allText,t.push(s),t}},n}(r.SsmlFormatterBase);return B.AmazonAlexaSsmlFormatter=n,B}(),r=function(){if(W)return R;W=1;var e,t=R&&R.__extends||(e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)},function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)});Object.defineProperty(R,"__esModule",{value:!0}),R.AmazonPollySsmlFormatter=void 0;var r=N(),n=function(e){function n(t){var r=e.call(this,t)||this;return r.options=t,r.modifierKeyToSsmlTagMappings.whisper="amazon:effect",r.modifierKeyToSsmlTagMappings.timbre="amazon:effect",r.modifierKeyToSsmlTagMappings.cardinal="say-as",r.modifierKeyToSsmlTagMappings.digits="say-as",r.modifierKeyToSsmlTagMappings.drc="amazon:effect",r.modifierKeyToSsmlTagMappings.lang="lang",r.modifierKeyMappings.digits="digits",r.modifierKeyMappings.cardinal="cardinal",r}return t(n,e),n.prototype.getTextModifierObject=function(e){for(var t=new r.TagsObject(this),n=0;n<e.children.length;n++){var i=e.children[n];switch(i.name){case"plainText":case"plainTextSpecialChars":case"plainTextEmphasis":case"plainTextPhone":case"plainTextModifier":t.text=i.allText;break;case"textModifierKeyOptionalValue":var s=i.children[0].allText;s=this.modifierKeyMappings[s]||s;var o=2===i.children.length?i.children[1].allText:"",a=this.modifierKeyToSsmlTagMappings[s];switch(s){case"emphasis":t.tag(a,{level:o||"moderate"});break;case"address":case"cardinal":case"characters":case"digits":case"expletive":case"fraction":case"number":case"ordinal":case"telephone":case"unit":t.tag(a,{"interpret-as":s});break;case"date":t.tag(a,{"interpret-as":s,format:o||"ymd"});break;case"time":t.tag(a,{"interpret-as":s,format:o||"hms12"});break;case"whisper":t.tag(a,{name:"whispered"});break;case"ipa":t.tag(a,{alphabet:s,ph:o});break;case"sub":t.tag(a,{alias:o});break;case"volume":case"rate":case"pitch":var l={};l[s]=o||"medium",t.tag(a,l,!0);break;case"timbre":t.tag(a,{"vocal-tract-length":o});break;case"lang":t.tag(a,{"xml:lang":o});break;case"drc":t.tag(a,{name:s})}}}return t},n.prototype.getSectionObject=function(e){for(var t=new r.TagsObject(this),n=0;n<e.children.length;n++){var i=e.children[n];if("sectionModifierKeyOptionalValue"===i.name){var s=i.children[0].allText,o=2===i.children.length?i.children[1].allText:"",a=this.modifierKeyToSsmlTagMappings[s];"lang"===s&&t.tag(a,{"xml:lang":o})}}return t},n.prototype.formatFromAst=function(e,t){switch(void 0===t&&(t=[]),e.name){case"document":return this.options.includeFormatterComment&&this.addComment("Converted from Speech Markdown to SSML for Amazon Alexa",t),this.options.includeSpeakTag?this.addSpeakTag(e.children,!0,!1,null,t):(this.processAst(e.children,t),t);case"paragraph":return this.options.includeParagraphTag?this.addTag("p",e.children,!0,!1,null,t):(this.processAst(e.children,t),t);case"shortBreak":var r=e.children[0].allText;return this.addTagWithAttrs(t,null,"break",{time:r});case"break":var n=e.children[0].allText,i={};switch(e.children[0].children[0].name){case"breakStrengthValue":i={strength:n};break;case"time":i={time:n}}return this.addTagWithAttrs(t,null,"break",i);case"markTag":var s=e.children[0].allText;return this.addTagWithAttrs(t,null,"mark",{name:s});case"shortEmphasisModerate":var o=e.children[0].allText;return this.addTagWithAttrs(t,o,"emphasis",{level:"moderate"});case"shortEmphasisStrong":return o=e.children[0].allText,this.addTagWithAttrs(t,o,"emphasis",{level:"strong"});case"shortEmphasisNone":return o=e.children[0].allText,this.addTagWithAttrs(t,o,"emphasis",{level:"none"});case"shortEmphasisReduced":return o=e.children[0].allText,this.addTagWithAttrs(t,o,"emphasis",{level:"reduced"});case"textModifier":for(var a=this.getTextModifierObject(e),l=Object.keys(a.tags).sort((function(e,t){return a.tags[t].sortId-a.tags[e].sortId})),c=a.text,d=0;d<l.length;d++){var u=l[d];i=a.tags[u].attrs,c=this.getTagWithAttrs(c,u,i)}return t.push(c),t;case"section":var h=this.getSectionObject(e),p=Object.keys(h.tags).sort((function(e,t){return h.tags[e].sortId-h.tags[t].sortId}));return this.addSectionEndTag(t),this.addSectionStartTag(p,h,t),t;case"simpleLine":default:return this.processAst(e.children,t),t;case"lineEnd":case"plainText":case"plainTextSpecialChars":return t.push(e.allText),t;case"emptyLine":return this.options.preserveEmptyLines&&t.push(e.allText),t}},n}(r.SsmlFormatterBase);return R.AmazonPollySsmlFormatter=n,R}(),n=function(){if(z)return K;z=1;var e,t=K&&K.__extends||(e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)},function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)});Object.defineProperty(K,"__esModule",{value:!0}),K.AmazonPollyNeuralSsmlFormatter=void 0;var r=N(),n=function(e){function n(t){var r=e.call(this,t)||this;return r.options=t,r.modifierKeyToSsmlTagMappings.cardinal="say-as",r.modifierKeyToSsmlTagMappings.digits="say-as",r.modifierKeyToSsmlTagMappings.drc="amazon:effect",r.modifierKeyToSsmlTagMappings.lang="lang",r.modifierKeyToSsmlTagMappings.newscaster="amazon:domain",r.modifierKeyMappings.digits="digits",r.modifierKeyMappings.cardinal="cardinal",r}return t(n,e),n.prototype.getTextModifierObject=function(e){for(var t=new r.TagsObject(this),n=0;n<e.children.length;n++){var i=e.children[n];switch(i.name){case"plainText":case"plainTextSpecialChars":case"plainTextEmphasis":case"plainTextPhone":case"plainTextModifier":t.text=i.allText;break;case"textModifierKeyOptionalValue":var s=i.children[0].allText;s=this.modifierKeyMappings[s]||s;var o=2===i.children.length?i.children[1].allText:"",a=this.modifierKeyToSsmlTagMappings[s];switch(s){case"address":case"cardinal":case"characters":case"digits":case"expletive":case"fraction":case"number":case"ordinal":case"telephone":case"unit":t.tag(a,{"interpret-as":s});break;case"date":t.tag(a,{"interpret-as":s,format:o||"ymd"});break;case"time":t.tag(a,{"interpret-as":s,format:o||"hms12"});break;case"ipa":t.tag(a,{alphabet:s,ph:o});break;case"sub":t.tag(a,{alias:o});break;case"volume":case"rate":var l={};l[s]=o||"medium",t.tag(a,l,!0);break;case"lang":t.tag(a,{"xml:lang":o});break;case"drc":t.tag(a,{name:s})}}}return t},n.prototype.getSectionObject=function(e){for(var t=new r.TagsObject(this),n=0;n<e.children.length;n++){var i=e.children[n];if("sectionModifierKeyOptionalValue"===i.name){var s=i.children[0].allText,o=2===i.children.length?i.children[1].allText:"",a=this.modifierKeyToSsmlTagMappings[s];switch(s){case"lang":t.tag(a,{"xml:lang":o});break;case"newscaster":t.tag(a,{name:"news"})}}}return t},n.prototype.formatFromAst=function(e,t){switch(void 0===t&&(t=[]),e.name){case"document":return this.options.includeFormatterComment&&this.addComment("Converted from Speech Markdown to SSML for Amazon Polly",t),this.options.includeSpeakTag?this.addSpeakTag(e.children,!0,!1,null,t):(this.processAst(e.children,t),t);case"paragraph":return this.options.includeParagraphTag?this.addTag("p",e.children,!0,!1,null,t):(this.processAst(e.children,t),t);case"shortBreak":var r=e.children[0].allText;return this.addTagWithAttrs(t,null,"break",{time:r});case"break":var n=e.children[0].allText,i={};switch(e.children[0].children[0].name){case"breakStrengthValue":i={strength:n};break;case"time":i={time:n}}return this.addTagWithAttrs(t,null,"break",i);case"markTag":var s=e.children[0].allText;return this.addTagWithAttrs(t,null,"mark",{name:s});case"textModifier":for(var o=this.getTextModifierObject(e),a=Object.keys(o.tags).sort((function(e,t){return o.tags[t].sortId-o.tags[e].sortId})),l=o.text,c=0;c<a.length;c++){var d=a[c];i=o.tags[d].attrs,l=this.getTagWithAttrs(l,d,i)}return t.push(l),t;case"section":var u=this.getSectionObject(e),h=Object.keys(u.tags).sort((function(e,t){return u.tags[e].sortId-u.tags[t].sortId}));return this.addSectionEndTag(t),this.addSectionStartTag(h,u,t),t;case"simpleLine":default:return this.processAst(e.children,t),t;case"lineEnd":case"plainText":case"plainTextSpecialChars":return t.push(e.allText),t;case"emptyLine":return this.options.preserveEmptyLines&&t.push(e.allText),t;case"shortEmphasisModerate":case"shortEmphasisStrong":case"shortEmphasisNone":case"shortEmphasisReduced":return t.push(e.allText.replace(/\+/g,"")),t}},n}(r.SsmlFormatterBase);return K.AmazonPollyNeuralSsmlFormatter=n,K}(),i=function(){if(V)return q;V=1;var e,t=q&&q.__extends||(e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)},function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)});Object.defineProperty(q,"__esModule",{value:!0}),q.GoogleAssistantSsmlFormatter=void 0;var r=N(),n=function(e){function n(t){var r=e.call(this,t)||this;return r.options=t,r.validVoices={Ivy:{voice:{gender:"female",variant:1,language:"en-US"}},Joanna:{voice:{gender:"female",variant:2,language:"en-US"}},Joey:{voice:{gender:"male",variant:1,language:"en-US"}},Justin:{voice:{gender:"male",variant:2,language:"en-US"}},Kendra:{voice:{gender:"female",variant:3,language:"en-US"}},Kimberly:{voice:{gender:"female",variant:4,language:"en-US"}},Matthew:{voice:{gender:"male",variant:3,language:"en-US"}},Salli:{voice:{gender:"male",variant:4,language:"en-US"}},Nicole:{voice:{gender:"female",variant:1,language:"en-AU"}},Russell:{voice:{gender:"male",variant:1,language:"en-AU"}},Amy:{voice:{gender:"female",variant:1,language:"en-GB"}},Brian:{voice:{gender:"male",variant:1,language:"en-GB"}},Emma:{voice:{gender:"female",variant:2,language:"en-GB"}},Aditi:{voice:{gender:"female",variant:1,language:"en-IN"}},Raveena:{voice:{gender:"female",variant:2,language:"en-IN"}},Hans:{voice:{gender:"male",variant:1,language:"de-DE"}},Marlene:{voice:{gender:"female",variant:1,language:"de-DE"}},Vicki:{voice:{gender:"female",variant:2,language:"de-DE"}},Conchita:{voice:{gender:"female",variant:1,language:"es-ES"}},Enrique:{voice:{gender:"male",variant:1,language:"es-ES"}},Carla:{voice:{gender:"female",variant:1,language:"it-IT"}},Giorgio:{voice:{gender:"male",variant:1,language:"it-IT"}},Mizuki:{voice:{gender:"female",variant:1,language:"ja-JP"}},Takumi:{voice:{gender:"male",variant:1,language:"ja-JP"}},Celine:{voice:{gender:"female",variant:1,language:"fr-FR"}},Lea:{voice:{gender:"female",variant:2,language:"fr-FR"}},Mathieu:{voice:{gender:"male",variant:1,language:"fr-FR"}}},r.modifierKeyToSsmlTagMappings.interjection=null,r.modifierKeyToSsmlTagMappings.whisper="prosody",r.modifierKeyToSsmlTagMappings.lang="lang",r}return t(n,e),n.prototype.getTextModifierObject=function(e){for(var t=new r.TagsObject(this),n=0;n<e.children.length;n++){var i=e.children[n];switch(i.name){case"plainText":case"plainTextSpecialChars":case"plainTextEmphasis":case"plainTextPhone":case"plainTextModifier":t.text=i.allText;break;case"textModifierKeyOptionalValue":var s=i.children[0].allText;s=this.modifierKeyMappings[s]||s;var o=2===i.children.length?i.children[1].allText:"",a=this.modifierKeyToSsmlTagMappings[s];switch(s){case"emphasis":t.tag(a,{level:o||"moderate"});break;case"address":case"characters":case"expletive":case"fraction":case"number":case"ordinal":case"telephone":case"unit":t.tag(a,{"interpret-as":s});break;case"date":t.tag(a,{"interpret-as":s,format:o||"ymd"});break;case"time":t.tag(a,{"interpret-as":s,format:o||"hms12"});break;case"whisper":t.tag(a,{volume:"x-soft",rate:"slow"});break;case"ipa":t.tag(a,{alphabet:s,ph:o});break;case"sub":t.tag(a,{alias:o});break;case"volume":case"rate":case"pitch":var l={};l[s]=o||"medium",t.tag(a,l,!0);break;case"lang":t.tag(a,{"xml:lang":o});break;case"voice":t.voiceTag(s,o)}}}return t},n.prototype.getSectionObject=function(e){for(var t=new r.TagsObject(this),n=0;n<e.children.length;n++){var i=e.children[n];if("sectionModifierKeyOptionalValue"===i.name){var s=i.children[0].allText,o=2===i.children.length?i.children[1].allText:"",a=this.modifierKeyToSsmlTagMappings[s];switch(s){case"lang":t.tag(a,{"xml:lang":o});break;case"voice":t.voiceTag(s,o)}}}return t},n.prototype.formatFromAst=function(e,t){switch(void 0===t&&(t=[]),e.name){case"document":return this.options.includeFormatterComment&&this.addComment("Converted from Speech Markdown to SSML for Google Assistant",t),this.options.includeSpeakTag?this.addSpeakTag(e.children,!0,!1,null,t):(this.processAst(e.children,t),t);case"paragraph":return this.options.includeParagraphTag?this.addTag("p",e.children,!0,!1,null,t):(this.processAst(e.children,t),t);case"shortBreak