@readium/speech 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/Fallback/fallbackEngineProvider.d.ts +21 -0
- package/build/Fallback/fallbackSpeechEngine.d.ts +68 -0
- package/build/Fallback/index.d.ts +3 -0
- package/build/Fallback/recoverableFailure.d.ts +10 -0
- package/build/SpeechServer/errors.d.ts +9 -0
- package/build/SpeechServer/speechServerEngine.d.ts +7 -2
- package/build/SpeechServer/speechServerEngineProvider.d.ts +1 -1
- package/build/WebSpeech/WebSpeechVoiceManager.d.ts +0 -32
- package/build/WebSpeech/webSpeechEngine.d.ts +2 -2
- package/build/engine.d.ts +1 -1
- package/build/index.cjs +27 -27
- package/build/index.d.ts +1 -0
- package/build/index.js +1837 -1504
- package/build/navigator.d.ts +1 -1
- package/build/provider.d.ts +1 -1
- package/build/speechNavigator.d.ts +1 -1
- package/build/utils/array.d.ts +1 -0
- package/build/utils/eventEmitter.d.ts +6 -0
- package/build/voices/languages.d.ts +6 -0
- package/build/voices/sorting.d.ts +50 -1
- package/package.json +1 -1
package/build/index.cjs
CHANGED
|
@@ -1,50 +1,50 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=t=>{if(!t)return["",void 0];const e=t.replace(/_/g,"-");try{const n=new Intl.Locale(e);return[n.language.toLowerCase(),n.region?.toUpperCase()]}catch{const n=e.split("-");return[n[0].toLowerCase(),n[1]?.toUpperCase()]}},j={ar:{defaultRegion:"SA",availableRegions:["001","AE","AS","BH","DZ","EG","IQ","JO","KW","LB","LY","MA","OM","QA","SA","SY","TN","YE"],testUtterance:"مرحبًا، اسمي {name} وأنا صوت عربي."},bg:{defaultRegion:"BG",availableRegions:["BG"],testUtterance:"Здравейте, казвам се {name} и съм български глас."},bho:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, हमार नाम {name} ह आ हम भोजपुरी आवाज हईं"},bn:{defaultRegion:"IN",availableRegions:["BD","IN"],testUtterance:"হ্যালো, আমার নাম {name} এবং আমি একজন বাংলা ভয়েস।"},ca:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Hola, em dic {name} i sóc una veu catalana"},cmn:{defaultRegion:"CN",availableRegions:["CN","CTW","TW"],testUtterance:"你好,我的名字是 {name},我是普通话配音。"},cs:{defaultRegion:"CZ",availableRegions:["CZ"],testUtterance:"Dobrý den, jmenuji se {name} a jsem český hlas."},da:{defaultRegion:"DK",availableRegions:["DK"],testUtterance:"Hej, mit navn er {name} og jeg er en dansk stemme."},de:{defaultRegion:"DE",availableRegions:["AT","CH","DE"],testUtterance:"Hallo, mein Name ist {name} und ich bin eine deutsche Stimme."},el:{defaultRegion:"GR",availableRegions:["GR"],testUtterance:"Γεια σας, με λένε {name} και είμαι ελληνική φωνή."},en:{defaultRegion:"US",availableRegions:["AU","CA","GB","HK","IE","IN","KE","NG","NZ","PH","SG","TZ","US","ZA"],testUtterance:"Hello, my name is {name} and I am an English voice."},es:{defaultRegion:"ES",availableRegions:["AR","BO","CL","CO","CR","CU","DO","EC","ES","GQ","GT","HN","MX","NI","PA","PE","PR","PY","SV","US","UY","VE"],testUtterance:"Hola, mi nombre es {name} y soy una voz española."},eu:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Kaixo, nire izena {name} da eta euskal ahotsa naiz."},fa:{defaultRegion:"IR",availableRegions:["IR"],testUtterance:"سلام اسم من {name} و صدای فارسی هستم"},fi:{defaultRegion:"FI",availableRegions:["FI"],testUtterance:"Hei, nimeni on {name} ja olen suomalainen ääni."},fr:{defaultRegion:"FR",availableRegions:["BE","CA","CH","FR"],testUtterance:"Bonjour, mon nom est {name} et je suis une voix française."},gl:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Ola, chámome {name} e son unha voz galega."},he:{defaultRegion:"IL",availableRegions:["IL"],testUtterance:"שלום, שמי {name} ואני קול עברי."},hi:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, मेरा नाम {name} है और मैं एक हिंदी आवाज़ हूँ।"},hr:{defaultRegion:"HR",availableRegions:["HR"],testUtterance:"Pozdrav, ja sam {name} i hrvatski sam glas."},hu:{defaultRegion:"HU",availableRegions:["HU"],testUtterance:"Helló, a nevem {name} és magyar hangú vagyok."},id:{defaultRegion:"ID",availableRegions:["ID"],testUtterance:"Halo, nama saya {name} dan saya suara Indonesia."},it:{defaultRegion:"IT",availableRegions:["IT"],testUtterance:"Ciao, mi chiamo {name} e sono una voce italiana."},ja:{defaultRegion:"JP",availableRegions:["JP"],testUtterance:"こんにちは。私の名前は{name}で、日本語の声を担当しています。"},kk:{defaultRegion:"KZ",availableRegions:["KZ"],testUtterance:"Sälemetsiz be, meniñ atım {name} jäne men qazaq dawısımın."},kn:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"ಹಲೋ, ನನ್ನ ಹೆಸರು {name} ಮತ್ತು ನಾನು ಕನ್ನಡ ಧ್ವನಿ."},ko:{defaultRegion:"KR",availableRegions:["KR"],testUtterance:"안녕하세요, 저는 {name}이고 한국어 음성입니다."},mr:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, माझे नाव {name} आहे आणि मी एक मराठी आवाज आहे."},ms:{defaultRegion:"MY",availableRegions:["MY"],testUtterance:"Hello, nama saya {name} dan saya suara Melayu."},nb:{defaultRegion:"NO",availableRegions:["NO"],testUtterance:"Hei, jeg heter {name} og er en norsk stemme."},nl:{defaultRegion:"NL",availableRegions:["BE","NL"],testUtterance:"Hallo, mijn naam is {name} en ik ben een Nederlandse stem."},pl:{defaultRegion:"PL",availableRegions:["PL"],testUtterance:"Cześć, nazywam się {name} i mam polski głos."},pt:{defaultRegion:"BR",availableRegions:["BR","PT"],testUtterance:"Olá, o meu nome é {name} e sou uma voz portuguesa."},ro:{defaultRegion:"RO",availableRegions:["RO"],testUtterance:"Buna ziua, ma numesc {name} si sunt o voce romaneasca."},ru:{defaultRegion:"RU",availableRegions:["RU"],testUtterance:"Здравствуйте, меня зовут {name} и я русский голос."},sk:{defaultRegion:"SK",availableRegions:["SK"],testUtterance:"Dobrý deň, volám sa {name} a som slovenský hlas."},sl:{defaultRegion:"SI",availableRegions:["SI"],testUtterance:"Pozdravljeni, moje ime je {name} in sem slovenski glas."},sv:{defaultRegion:"SE",availableRegions:["SE"],testUtterance:"Hej, jag heter {name} och jag är en svensk röst."},ta:{defaultRegion:"IN",availableRegions:["IN","LK","MY","SG"],testUtterance:"வணக்கம், என் பெயர் {name} மற்றும் நான் ஒரு தமிழ் குரல்"},te:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"హలో, నా పేరు {name} మరియు నేను తెలుగు వాణిని."},th:{defaultRegion:"TH",availableRegions:["TH"],testUtterance:"สวัสดีค่ะ ฉันชื่อ {name} และฉันเป็นคนมีเสียงภาษาไทย"},tr:{defaultRegion:"TR",availableRegions:["TR"],testUtterance:"Merhaba, adım {name} ve Türk sesiyim."},uk:{defaultRegion:"UA",availableRegions:["UA"],testUtterance:"Здравствуйте, меня зовут {name} и я украинский голос."},vi:{defaultRegion:"VN",availableRegions:["VN"],testUtterance:"Xin chào, tôi tên là {name} và tôi là giọng nói tiếng Việt."},wuu:{defaultRegion:"CN",availableRegions:["CN"],testUtterance:"你好,我的名字是 {name},我是吴语配音。"},yue:{defaultRegion:"HK",availableRegions:["HK"],testUtterance:"你好,我叫 {name},係越中文聲。"}},ut=new Map,Oi=Object.assign({"../../json/ar.json":()=>Promise.resolve().then(()=>require("./ar-BYWkyZgW.cjs")),"../../json/bg.json":()=>Promise.resolve().then(()=>require("./bg-D7xe9YTl.cjs")),"../../json/bho.json":()=>Promise.resolve().then(()=>require("./bho-UB6aO8oz.cjs")),"../../json/bn.json":()=>Promise.resolve().then(()=>require("./bn-boRZ2pl5.cjs")),"../../json/ca.json":()=>Promise.resolve().then(()=>require("./ca-DkC8kSJ8.cjs")),"../../json/cmn.json":()=>Promise.resolve().then(()=>require("./cmn-BsNLjyA4.cjs")),"../../json/cs.json":()=>Promise.resolve().then(()=>require("./cs-p05r08p7.cjs")),"../../json/da.json":()=>Promise.resolve().then(()=>require("./da-crefCup9.cjs")),"../../json/de.json":()=>Promise.resolve().then(()=>require("./de-xoW-RuhZ.cjs")),"../../json/el.json":()=>Promise.resolve().then(()=>require("./el-C025sTug.cjs")),"../../json/en.json":()=>Promise.resolve().then(()=>require("./en-CbfmLXbR.cjs")),"../../json/es.json":()=>Promise.resolve().then(()=>require("./es-DW7IPf8I.cjs")),"../../json/eu.json":()=>Promise.resolve().then(()=>require("./eu-uq15ZgwW.cjs")),"../../json/fa.json":()=>Promise.resolve().then(()=>require("./fa-CHOnwiFr.cjs")),"../../json/fi.json":()=>Promise.resolve().then(()=>require("./fi-Bxlno6Zi.cjs")),"../../json/fr.json":()=>Promise.resolve().then(()=>require("./fr-yAth5-FC.cjs")),"../../json/gl.json":()=>Promise.resolve().then(()=>require("./gl-BEgzCAO0.cjs")),"../../json/he.json":()=>Promise.resolve().then(()=>require("./he-B-CTHJPL.cjs")),"../../json/hi.json":()=>Promise.resolve().then(()=>require("./hi-C0yUjV1-.cjs")),"../../json/hr.json":()=>Promise.resolve().then(()=>require("./hr-CZvFOcdo.cjs")),"../../json/hu.json":()=>Promise.resolve().then(()=>require("./hu-_2PInItj.cjs")),"../../json/id.json":()=>Promise.resolve().then(()=>require("./id-BROcb7-t.cjs")),"../../json/it.json":()=>Promise.resolve().then(()=>require("./it-Bmc8Ycff.cjs")),"../../json/ja.json":()=>Promise.resolve().then(()=>require("./ja-B8t6WOeg.cjs")),"../../json/kk.json":()=>Promise.resolve().then(()=>require("./kk-DskO1CW8.cjs")),"../../json/kn.json":()=>Promise.resolve().then(()=>require("./kn-Cy3NH6na.cjs")),"../../json/ko.json":()=>Promise.resolve().then(()=>require("./ko-CZdQzppZ.cjs")),"../../json/mr.json":()=>Promise.resolve().then(()=>require("./mr-9hGqBYlV.cjs")),"../../json/ms.json":()=>Promise.resolve().then(()=>require("./ms-DzpBxNFZ.cjs")),"../../json/nb.json":()=>Promise.resolve().then(()=>require("./nb-BQfw9EEH.cjs")),"../../json/nl.json":()=>Promise.resolve().then(()=>require("./nl-CyM0R4Gr.cjs")),"../../json/pl.json":()=>Promise.resolve().then(()=>require("./pl-Da8XOMa1.cjs")),"../../json/pt.json":()=>Promise.resolve().then(()=>require("./pt-tubyvYaM.cjs")),"../../json/ro.json":()=>Promise.resolve().then(()=>require("./ro-C-rXDfuM.cjs")),"../../json/ru.json":()=>Promise.resolve().then(()=>require("./ru-DJocRaDd.cjs")),"../../json/sk.json":()=>Promise.resolve().then(()=>require("./sk-BvpojIXp.cjs")),"../../json/sl.json":()=>Promise.resolve().then(()=>require("./sl-D0X3JKvQ.cjs")),"../../json/sv.json":()=>Promise.resolve().then(()=>require("./sv-4lEgrHda.cjs")),"../../json/ta.json":()=>Promise.resolve().then(()=>require("./ta-CyeVPdIs.cjs")),"../../json/te.json":()=>Promise.resolve().then(()=>require("./te-DqWIZZxL.cjs")),"../../json/th.json":()=>Promise.resolve().then(()=>require("./th-BcoSVZAp.cjs")),"../../json/tr.json":()=>Promise.resolve().then(()=>require("./tr-BuafNhfw.cjs")),"../../json/uk.json":()=>Promise.resolve().then(()=>require("./uk-DkXNxnD9.cjs")),"../../json/vi.json":()=>Promise.resolve().then(()=>require("./vi-Ct2avSE6.cjs")),"../../json/wuu.json":()=>Promise.resolve().then(()=>require("./wuu-DnwGQ6c-.cjs")),"../../json/yue.json":()=>Promise.resolve().then(()=>require("./yue-j9Y48sR-.cjs"))});async function Ti(t){try{const e=t.split("-")[0],n=Oi[`../../json/${e}.json`];if(!n)throw new Error(`No voice data found for language: ${t}`);const i=(await n()).default;return{...i,voices:i.voices.map(Ni)}}catch(e){return console.warn(`Failed to load voice data for ${t}:`,e),{language:t,defaultRegion:"",testUtterance:"",voices:[]}}}function bn(t){return ut.has(t)||ut.set(t,Ti(t)),ut.get(t)}const Ri=["veryLow","low","normal","high","veryHigh"],Pi=["android","apple"],Ni=t=>({...t,quality:t.quality?.filter(e=>Ri.includes(e)),localizedName:t.localizedName&&Pi.includes(t.localizedName)?t.localizedName:void 0}),he={cmn:"cmn","cmn-CN":"cmn-CN","cmn-TW":"cmn-TW",zh:"cmn","zh-CN":"cmn-CN","zh-TW":"cmn-TW",yue:"yue","yue-HK":"yue-HK","zh-HK":"yue-HK",wuu:"wuu","wuu-CN":"wuu-CN"},$=t=>{if(!t)return"";let e=t.toLowerCase().replace(/_/g,"-");if(/\w{2,3}-\w{2,3}/.test(e)){const[n,r]=e.split("-");e=`${n.toLowerCase()}-${r.toUpperCase()}`}return he[e]||e},Rt=async t=>{if(!t)return[];try{const e=$(t);try{const r=await bn(e);if(r?.voices?.length)return r.voices}catch(r){console.warn(`Failed to load voices for ${e}:`,r)}const[n]=U(e);if(n!==e)try{const r=await bn(n);if(r?.voices?.length)return r.voices}catch(r){console.warn(`Failed to load voices for base language ${n}:`,r)}return[]}catch(e){return console.error(`Error in getVoices for ${t}:`,e),[]}},vn=t=>{if(!t)return"";try{const e=$(t),n=j[e];if(n?.testUtterance)return n.testUtterance;if(e in he){const i=he[e];if(i&&j[i]?.testUtterance)return j[i].testUtterance}const[r]=U(e);return r!==e&&j[r]?.testUtterance?j[r].testUtterance:""}catch(e){return console.error(`Error in getTestUtterance for ${t}:`,e),""}},Qe=t=>{if(!t)return"";try{const e=$(t),n=j[e];if(n?.defaultRegion)return`${e}-${n.defaultRegion}`;if(e in he){const i=he[e];if(i){const s=j[i];if(s?.defaultRegion)return`${i}-${s.defaultRegion}`}}const[r]=U(e);if(r!==e){const i=j[r];if(i?.defaultRegion)return`${r}-${i.defaultRegion}`}return""}catch(e){return console.error(`Failed to get default region for ${t}:`,e),""}},wn=t=>{if(!t?.length)return[];const e=new Set,n=new Map,r=new Map;for(const[i,s]of t.entries()){if(!s)continue;const o=$(s),[a,c]=U(o);c&&(e.add(c),r.has(c)||r.set(c,i)),n.has(a)||n.set(a,new Set),c&&n.get(a).add(c)}return Array.from(n.entries()).map(([i,s])=>{const o=new Set(j[i]?.availableRegions||[]),a=Array.from(s),c=Array.from(e).filter(d=>o.has(d)&&!a.includes(d)),l=Array.from(new Set([...a,...c])).sort((d,u)=>{const g=r.get(d)??Number.MAX_SAFE_INTEGER,f=r.get(u)??Number.MAX_SAFE_INTEGER;return g-f});if(l.length===0){const d=Qe(i),[,u]=U(d);u&&l.push(u)}return{baseLang:i,regions:l}})};async function je(t){const e=new Map;for(const r of t){if(r.source!=="json")continue;const[i]=U(r.language);e.has(i)||e.set(i,[]),e.get(i).push(r)}const n=new Map;for(const[r,i]of e.entries()){const s=new Map,o=await Rt(r),a=new Map;o.forEach((c,l)=>{a.set(c.name.toLowerCase(),l),c.altNames?.forEach(d=>{a.set(d.toLowerCase(),l)})});for(const c of i){const l=c.name.toLowerCase(),d=a.get(l);d!==void 0&&s.set(c.name,d)}s.size>0&&n.set(r,s)}return n}const Ii=[{name:"Albert",nativeID:["com.apple.speech.synthesis.voice.Albert"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bad News",nativeID:["com.apple.speech.synthesis.voice.BadNews"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Mauvaises nouvelles","Malas noticias","Brutte notizie"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bahh",nativeID:["com.apple.speech.synthesis.voice.Bahh"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bells",nativeID:["com.apple.speech.synthesis.voice.Bells"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Cloches","Campanas","Campane"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Boing",nativeID:["com.apple.speech.synthesis.voice.Boing"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bubbles",nativeID:["com.apple.speech.synthesis.voice.Bubbles"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bulles","Burbujas","Bollicine"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Cellos",nativeID:["com.apple.speech.synthesis.voice.Cellos"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Violoncelles","Violonchelos","Violoncelli"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Good News",nativeID:["com.apple.speech.synthesis.voice.GoodNews"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bonnes nouvelles","Buenas noticias","Buone notizie"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Jester",nativeID:["com.apple.speech.synthesis.voice.Hysterical"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bouffon","Bufón","Giullare"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Organ",nativeID:["com.apple.speech.synthesis.voice.Organ"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Orgue","Órgano","Organo"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Superstar",nativeID:["com.apple.speech.synthesis.voice.Princess"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Superestrella"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Trinoids",nativeID:["com.apple.speech.synthesis.voice.Trinoids"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Trinoïdes"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Whisper",nativeID:["com.apple.speech.synthesis.voice.Whisper"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Murmure","Susurro","Sussurro"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Wobble",nativeID:["com.apple.speech.synthesis.voice.Deranged"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Zarvox",nativeID:["com.apple.speech.synthesis.voice.Zarvox"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0}],Li={voices:Ii},qi=[{name:"Eddy",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Flo",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Grandma",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Grandpa",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Jacques",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Reed",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Rocko",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Sandy",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Shelley",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Fred",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Junior",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Kathy",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Ralph",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"eSpeak Arabic",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ar",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Bulgarian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"bg",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Bengali",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"bn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Catalan",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ca",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Chinese (Mandarin, latin as English)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"cmn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Czech",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"cs",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Danish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"da",os:["ChromeOS"],preloaded:!0},{name:"eSpeak German",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"de",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Greek",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"el",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Spanish (Spain)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"es",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Estonian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"et",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Finnish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"fi",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Gujarati",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"gu",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Croatian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"hr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Hungarian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"hu",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Indonesian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"id",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Italian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"it",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Kannada",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"kn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Korean",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ko",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Lithuanian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"lt",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Latvian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"lv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Malayalm",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ml",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Marathi",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"mr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Malay",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ms",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Norwegian Bokmål",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"nb",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Polish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"pl",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Portuguese (Brazil)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"pt-br",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Romanian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ro",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Russian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ru",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Slovak",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sk",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Slovenian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sl",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Serbian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Swedish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Swahili",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sw",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Tamil",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ta",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Telugu",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"te",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Turkish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"tr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Vietnamese (Northern)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"vi",os:["ChromeOS"],preloaded:!0}],Di={voices:qi},$i=Li,_i=Di,Pt=(t,e)=>$i.voices.some(n=>t.includes(n.name)||e&&n.nativeID?.some(r=>e.includes(r))||n.altNames?.some(r=>t.includes(r))),Nt=(t,e)=>_i.voices.some(n=>t.includes(n.name))||e==="veryLow",Sn=t=>t?.length?t.filter(e=>!(e.isNovelty||Pt(e.name,e.voiceURI))):[],xn=t=>t?.length?t.filter(e=>!Nt(e.name,e.quality)):[],Bi={ar:{normal:"محسن",high:"استثنائي"},ca:{normal:"millorada",high:"prèmium"},"cmn-CN":{normal:"优化音质",high:"高音质"},"cmn-TW":{normal:"增強音質",high:"高音質"},cs:{normal:"vylepšená verze",high:"prémiový"},da:{normal:"forbedret",high:"høj kvalitet"},de:{normal:"erweitert",high:"premium"},el:{normal:"βελτιωμένη",high:"υψηλής ποιότητας"},en:{normal:"Enhanced",high:"Premium"},es:{normal:"mejorada",high:"premium"},fi:{normal:"parannettu",high:"korkealaatuinen"},fr:{normal:"premium",high:"de qualité"},he:{normal:"משופר",high:"פרימיום"},hi:{normal:"बेहतर",high:"प्रीमियम"},hr:{normal:"poboljšani",high:"vrhunski"},hu:{normal:"továbbfejlesztett",high:"prémium"},id:{normal:"Ditingkatkan",high:"Premium"},it:{normal:"ottimizzata",high:"premium"},ja:{normal:"拡張",high:"プレミアム"},ko:{normal:"고품질",high:"프리미엄"},ms:{normal:"Dipertingkat",high:"Premium"},nb:{normal:"forbedret",high:"premium"},nl:{normal:"verbeterd",high:"premium"},pl:{normal:"rozszerzony",high:"premium"},pt:{normal:"melhorada",high:"premium"},ro:{normal:"îmbunătățită",high:"premium"},ru:{normal:"улучшенный",high:"высшее качество"},sk:{normal:"vylepšený",high:"prémiový"},sl:{normal:"izboljšano",high:"prvovrsten"},sv:{normal:"förbättrad",high:"premium"},th:{normal:"คุณภาพสูง",high:"คุณภาพสูง"},tr:{normal:"Geliştirilmiş",high:"Yüksek Kaliteli"},uk:{normal:"вдосконалений",high:"високої якості"},vi:{normal:"Nâng cao",high:"Cao cấp"}},Ui={quality:Bi},It={apple:Ui.quality},zi=(t,e,n)=>{if(!t)return;const r=Array.isArray(n)?n:n?[n]:[];for(const i of r)if(i&&It[i]){const s=It[i],o=U(e)[0],a=s[e]||s[o];if(a){const c=t.toLowerCase(),{normal:l,high:d}=a;if(d&&c.includes(d.toLowerCase()))return"high";if(l&&c.includes(l.toLowerCase()))return"normal"}}},ji=(t,e)=>{const n=It[e];if(n)for(const[r,{high:i,normal:s}]of Object.entries(n)){const o=i&&t.some(c=>c.includes(i)),a=s&&t.some(c=>c.includes(s));if(o&&a)return r}},Vi={low:{values:["super-compact","compact"],quality:"low"},normal:{values:["enhanced"],quality:"normal"},high:{values:["premium"],quality:"high"}},kn=t=>{if(!t)return;const n=t.toLowerCase().split(/[._-]/);for(const r of Object.values(Vi))if(r.values.some(i=>n.includes(i)))return r.quality};function Fi(t,e){if(t.name===t.originalName)return t;if(e.name===e.originalName)return e;const n=[t.originalName,...t.altNames||[]],r=[e.originalName,...e.altNames||[]],i=n.findIndex(o=>r.includes(o)),s=r.findIndex(o=>n.includes(o));return i===-1&&s===-1||i!==-1&&(s===-1||i<=s)?t:e}function Mi(t,e){if(!t.altNames&&!e.altNames)return!1;const n=t.originalName,r=e.originalName,i=t.altNames||[],s=e.altNames||[];return s.includes(n)||i.includes(r)?!0:i.filter(a=>s.includes(a)).length>0}class k{static instance;static initializationPromise=null;systemLocale;voices=[];browserVoices=[];isInitialized=!1;scopedLanguages=null;broadenPromises=new Map;constructor(){if(typeof window>"u"||!window.speechSynthesis)throw new Error("Web Speech API is not available in this environment");this.systemLocale=navigator.languages?.[0]?.split("-")[0]||"en"}static async initialize(e){if(k.instance?.isInitialized){const n=k.instance;return e?.languages&&e.languages.length>0&&await n.broadenLanguages(e.languages),n}return k.initializationPromise||(k.initializationPromise=(async()=>{try{const n=new k;k.instance=n,n.browserVoices=await n.getBrowserVoices(e?.maxTimeout,e?.interval),n.updateSystemLocale(n.browserVoices);let r=n.browserVoices;return e?.languages&&e.languages.length>0?(r=n.filterBrowserVoicesByLanguages(n.browserVoices,e.languages),n.scopedLanguages=k.toBaseLangSet(e.languages)):n.scopedLanguages=null,n.voices=await n.parseToReadiumSpeechVoices(r),n.isInitialized=!0,n}catch(n){throw k.initializationPromise=null,console.error("Failed to initialize WebSpeechVoiceManager:",n),n}})()),k.initializationPromise}filterBrowserVoicesByLanguages(e,n){if(!n?.length)return e;const r=k.toBaseLangSet(n);return e.filter(i=>{if(!i?.lang)return!1;const s=$(i.lang),[o]=k.extractLangRegionFromBCP47(s);return r.has(o)})}static toBaseLangSet(e){return new Set(e.map(n=>{const r=$(n),[i]=k.extractLangRegionFromBCP47(r);return i}))}async broadenLanguages(e){if(this.scopedLanguages===null)return;const r=[...k.toBaseLangSet(e)].filter(a=>!this.scopedLanguages.has(a));if(r.length===0)return;const i=r.filter(a=>this.broadenPromises.has(a)),s=r.filter(a=>!this.broadenPromises.has(a));let o;s.length>0&&(o=(async()=>{const a=this.filterBrowserVoicesByLanguages(this.browserVoices,s),c=await this.parseToReadiumSpeechVoices(a);this.voices=[...this.voices,...c],s.forEach(l=>this.scopedLanguages.add(l)),s.forEach(l=>this.broadenPromises.delete(l))})(),s.forEach(a=>this.broadenPromises.set(a,o))),await Promise.all([...o?[o]:[],...i.map(a=>this.broadenPromises.get(a))])}static extractLangRegionFromBCP47(e){return U(e)}static getLanguageDisplayName(e,n){try{return new Intl.DisplayNames(n?[n]:[],{type:"language",languageDisplay:"standard"}).of(e)||e.toUpperCase()}catch{return e.toUpperCase()}}cleanVoiceName(e){return e?e.replace(/\s*\([^)]*\)/g,"").replace(/[^\p{L}\p{N}\s-]/gu,"").replace(/\s+/g," ").trim():""}normalizeVoiceName(e){return this.cleanVoiceName(e.toLowerCase())}countVoiceDuplicates(e){const n=new Map;for(const r of e){if(!r?.name||!r?.lang)continue;const i=`${r.lang.toLowerCase()}_${this.normalizeVoiceName(r.name)}`;n.set(i,(n.get(i)||0)+1)}return n}updateSystemLocale(e){if(!e?.length)return;const n=e.map(i=>i.name),r=ji(n,"apple");r&&(this.systemLocale=r)}inferVoiceQuality(e,n,r){const i=e.voiceURI?kn(e.voiceURI):void 0;if(i)return i;if(n?.nativeID&&Array.isArray(n.nativeID))for(const s of n.nativeID){const o=kn(s);if(o)return o}if(n?.localizedName&&e.voiceURI&&e.lang){const s=zi(e.voiceURI,this.systemLocale,n.localizedName);if(s)return s}if(n?.quality&&n.quality.length>0){const s=Math.min(r-1,n.quality.length-1),o=n.quality[s];if(o)return o}return null}findMatchingJsonVoice(e,n){return e.find(r=>this.normalizeVoiceName(r.name)===n||r.altNames?.some(i=>this.normalizeVoiceName(i)===n))}removeDuplicates(e){const n=new Map;for(const r of e){const i=`${r.language.toLowerCase()}_${this.normalizeVoiceName(r.name)}`,s=n.get(i);if(!s)n.set(i,r);else if(Mi(r,s)){const o=Fi(r,s);n.set(i,o)}else{const o=k.getQualityValue(s.quality);k.getQualityValue(r.quality)>=o&&n.set(i,r)}}return Array.from(n.values())}getTestUtterance(e){if(!e)return"";const n=vn(e);if(n)return n;const[r]=k.extractLangRegionFromBCP47(e);if(r&&r!==e){const i=vn(r);if(i)return i}return""}getVoices(e={}){if(!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");return this.filterVoices(e,[...this.voices])}getLanguages(e,n,r){if(!r&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const i=r??this.voices,s=n?this.filterVoices(n,i):i,o=[],a=new Set;for(const c of s){const d=$(c.language).split("-")[0];if(!a.has(d)){const u=k.getLanguageDisplayName(d,e),g=s.filter(f=>$(f.language).split("-")[0]===d).length;o.push({code:d,label:u,count:g}),a.add(d)}}return r?o:o.sort((c,l)=>c.label.localeCompare(l.label))}getRegions(e,n,r){if(!r&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const i=r??this.voices,s=n?this.filterVoices(n,i):i,o=[],a=new Set,c=new Map;for(const l of s){const[,d]=k.extractLangRegionFromBCP47(l.language);d&&c.set(d,(c.get(d)||0)+1)}for(const l of s){const[,d]=k.extractLangRegionFromBCP47(l.language);if(d&&!a.has(d)){let u=l.language;try{const g=e||navigator.language;u=new Intl.DisplayNames([g],{type:"region"}).of(d)||l.language}catch(g){console.warn(`Failed to get display name for region ${d}`,g)}o.push({code:d,label:u,count:c.get(d)||0}),a.add(d)}}return r?o:o.sort((l,d)=>l.label.localeCompare(d.label))}async getDefaultVoice(e,n){if(!e)return null;const r=Array.isArray(e)?e:[e];let i=n||this.getVoices({languages:r});return i.length?(i=await this.sortVoicesByRegions(r,i),i[0]):null}getBrowserVoices(e=1e4,n=10){const r=()=>window.speechSynthesis?.getVoices()||[];if(!window.speechSynthesis)return Promise.resolve([]);const i=r();return Array.isArray(i)&&i.length?Promise.resolve(i):new Promise((s,o)=>{let a=Math.floor(e/n),c=!1;const l=()=>{if(c)return;c=!0;const d=()=>{if(a<1)return s([]);--a;const u=r();if(Array.isArray(u)&&u.length)return s(u);setTimeout(d,n)};setTimeout(d,n)};window.speechSynthesis.onvoiceschanged!==void 0?window.speechSynthesis.onvoiceschanged=()=>{const d=r();Array.isArray(d)&&d.length?s(d):l()}:l(),setTimeout(()=>s([]),e)})}async parseToReadiumSpeechVoices(e){const n=this.countVoiceDuplicates(e);return await Promise.all(e.filter(i=>i?.name&&i?.lang).map(async i=>{const s=$(i.lang),[o]=k.extractLangRegionFromBCP47(s),a=this.normalizeVoiceName(i.name),c=`${i.lang.toLowerCase()}_${a}`,l=n.get(c)||1;let d=await Rt(s);(!d||d.length===0)&&(d=await Rt(o));const u=this.findMatchingJsonVoice(d,a),g=this.inferVoiceQuality(i,u,l);return u?{...u,label:u.label??this.cleanVoiceName(i.name),source:"json",originalName:i.name,language:u.language??s,voiceURI:i.voiceURI,quality:g,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Pt(i.name,i.voiceURI),isLowQuality:Nt(i.name,g)}:{source:"browser",label:this.cleanVoiceName(i.name),name:i.name,originalName:i.name,language:s,voiceURI:i.voiceURI,quality:g,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Pt(i.name,i.voiceURI),isLowQuality:Nt(i.name,g)}}))}convertToSpeechSynthesisVoice(e){if(e)return this.browserVoices.find(n=>n.voiceURI===e.voiceURI||n.name===e.originalName||this.normalizeVoiceName(n.name)===this.normalizeVoiceName(e.name))}filterVoices(e,n){let r=n?[...n]:[...this.voices];const i={excludeNovelty:!0,excludeVeryLowQuality:!0,removeDuplicates:!0,...e};if(i.languages){const s=Array.isArray(i.languages)?i.languages:[i.languages];r=r.filter(o=>s.some(a=>{const c=a.toLowerCase(),l=o.language?.toLowerCase(),d=o.altLanguage?.toLowerCase();if(l===c||d===c)return!0;const[u]=c.split("-");return l&&l.startsWith(u)||d&&d.startsWith(u)}))}if(i.source&&(r=r.filter(s=>s.source===i.source)),i.gender&&(r=r.filter(s=>s.gender===i.gender)),i.quality){const s=Array.isArray(i.quality)?i.quality:[i.quality];r=r.filter(o=>o.quality&&s.includes(o.quality))}return i.offlineOnly&&(r=r.filter(s=>s.offlineAvailability===!0)),i.provider&&(r=r.filter(s=>s.provider?.toLowerCase()===i.provider?.toLowerCase())),i.excludeNovelty&&(r=Sn(r)),i.excludeVeryLowQuality&&(r=xn(r)),i.removeDuplicates&&(r=this.removeDuplicates(r)),r}filterOutNoveltyVoices(e){const n=e??this.voices;return Sn(n)}filterOutVeryLowQualityVoices(e){const n=e??this.voices;return xn(n)}static getQualityValue(e){return e?{veryLow:1,low:2,normal:3,high:4,veryHigh:5}[e]??0:0}static sortByQuality(e,n,r,i){const s=k.getQualityValue(e.quality),o=k.getQualityValue(n.quality);if(r&&i&&e.source==="json"&&n.source==="json"){const a=r.get(i);if(a){const c=a.get(e.name),l=a.get(n.name);if(c!==void 0&&l!==void 0)return c-l}}return o!==s?o-s:e.name.localeCompare(n.name)}async sortVoicesByQuality(e){const n=e||this.voices;if(!n?.length)return[];const r=await je(n);return[...n].sort((i,s)=>k.sortByQuality(i,s,r))}static groupVoicesByLanguage(e,n){const r=new Map(n.map(o=>[o.baseLang,o])),i=new Map,s=[];for(const o of e){const[a]=k.extractLangRegionFromBCP47(o.language);r.get(a)?(i.has(a)||i.set(a,[]),i.get(a).push(o)):s.push(o)}return{voicesByLang:i,otherLangVoices:s}}static async sortByDefaultRegion(e,n){const r=await je(e),i=Qe(n);e.sort((s,o)=>{const[,a]=k.extractLangRegionFromBCP47(s.language),[,c]=k.extractLangRegionFromBCP47(o.language),l=i&&a===i.split("-")[1],d=i&&c===i.split("-")[1];return l&&!d?-1:!l&&d?1:k.sortByQuality(s,o,r,n)})}static async sortAlphabetically(e){const n=await je(e);e.sort((r,i)=>{const[s]=k.extractLangRegionFromBCP47(r.language),[o]=k.extractLangRegionFromBCP47(i.language),a=k.getLanguageDisplayName(s).toLowerCase(),c=k.getLanguageDisplayName(o).toLowerCase(),l=a.localeCompare(c);if(l!==0)return l;if(s===o){const d=Qe(s),[,u]=k.extractLangRegionFromBCP47(r.language),[,g]=k.extractLangRegionFromBCP47(i.language),f=d&&u===d.split("-")[1],y=d&&g===d.split("-")[1];if(f&&!y)return-1;if(!f&&y)return 1;if(u&&g){const p=u.localeCompare(g);if(p!==0)return p}return u&&!g?-1:!u&&g?1:k.sortByQuality(r,i,n,s)}return k.sortByQuality(r,i,n,s)})}async sortVoicesByLanguages(e,n){const r=n||this.voices;if(!r?.length)return[];if(!e?.length){const c=[...r];return await k.sortAlphabetically(c),c}const i=wn(e),{voicesByLang:s,otherLangVoices:o}=k.groupVoicesByLanguage(r,i),a=[];for(const c of i){const l=s.get(c.baseLang);l&&(await k.sortByDefaultRegion(l,c.baseLang),a.push(...l))}return await k.sortAlphabetically(o),a.push(...o),a}static async sortByPreferredRegion(e,n){const r=await je(e);e.sort((i,s)=>{const[,o]=k.extractLangRegionFromBCP47(i.language),[,a]=k.extractLangRegionFromBCP47(s.language),c=o&&n.regions.includes(o),l=a&&n.regions.includes(a);if(c&&l){const y=n.regions.indexOf(o),p=n.regions.indexOf(a);return y===p?k.sortByQuality(i,s,r,n.baseLang):y-p}if(c)return-1;if(l)return 1;const d=Qe(n.baseLang),[,u]=k.extractLangRegionFromBCP47(d),g=o===u,f=a===u;if(g&&!f)return-1;if(!g&&f)return 1;if(o&&a){const y=o.localeCompare(a);return y!==0?y:k.sortByQuality(i,s,r,n.baseLang)}return o?-1:a?1:k.sortByQuality(i,s,r,n.baseLang)})}async sortVoicesByRegions(e,n){const r=n||this.voices;if(!r?.length)return[];const i=wn(e||[]),{voicesByLang:s,otherLangVoices:o}=k.groupVoicesByLanguage(r,i),a=[];for(const c of i){const l=s.get(c.baseLang);l&&(await k.sortByPreferredRegion(l,c),a.push(...l))}return await k.sortAlphabetically(o),a.push(...o),a}groupVoices(e,n){const r={},i=n||this.voices;for(const s of i){let o="Unknown";switch(e){case"languages":o=k.extractLangRegionFromBCP47(s.language)[0];break;case"gender":o=s.gender||"unknown";break;case"quality":o=s.quality||"unknown";break;case"region":const[,a]=k.extractLangRegionFromBCP47(s.language);o=a||"unknown";break}r[o]||(r[o]=[]),r[o].push(s)}return r}}const Hi=["webKit","moz","ms","o"],Gi=["boundary","end","error","mark","pause","resume","start"],Wi=t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`,Se=(t={},e)=>Object.hasOwnProperty.call(t,e)||e in t||!!t[e],Ki=t=>typeof window<"u"&&t in window,Ji=t=>{const e=Wi(t),n=Hi.map(i=>`${i}${e}`),r=[t,e].concat(n).find(Ki);return r&&typeof window<"u"?window[r]:void 0},Qi=()=>{const t={};["speechSynthesis","speechSynthesisUtterance","speechSynthesisVoice","speechSynthesisEvent","speechSynthesisErrorEvent"].forEach(n=>{t[n]=Ji(n)}),t.onvoiceschanged=Se(t.speechSynthesis,"onvoiceschanged"),t.speechSynthesisSpeaking=Se(t.speechSynthesis,"speaking"),t.speechSynthesisPaused=Se(t.speechSynthesis,"paused");const e=t.speechSynthesisUtterance?Se(t.speechSynthesisUtterance,"prototype"):!1;return Gi.forEach(n=>{const r=`on${n}`;t[r]=e&&t.speechSynthesisUtterance?Se(t.speechSynthesisUtterance.prototype,r):!1}),t},Xi=()=>{const e=typeof window<"u"&&(window.navigator||{}).userAgent||"",n=()=>/android/i.test(e),r=()=>/kaios/i.test(e),i=()=>typeof window.InstallTrigger<"u"?!0:/firefox/i.test(e),s=()=>typeof window.GestureEvent<"u"||/safari/i.test(e);return{isAndroid:n(),isFirefox:i()||r(),isSafari:s(),isKaiOS:r()}};function Zi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ht,Cn;function Yi(){if(Cn)return ht;Cn=1,ht=e;function t(r){return r instanceof Buffer?Buffer.from(r):new r.constructor(r.buffer.slice(),r.byteOffset,r.length)}function e(r){if(r=r||{},r.circles)return n(r);const i=new Map;if(i.set(Date,l=>new Date(l)),i.set(Map,(l,d)=>new Map(o(Array.from(l),d))),i.set(Set,(l,d)=>new Set(o(Array.from(l),d))),r.constructorHandlers)for(const l of r.constructorHandlers)i.set(l[0],l[1]);let s=null;return r.proto?c:a;function o(l,d){const u=Object.keys(l),g=new Array(u.length);for(let f=0;f<u.length;f++){const y=u[f],p=l[y];typeof p!="object"||p===null?g[y]=p:p.constructor!==Object&&(s=i.get(p.constructor))?g[y]=s(p,d):ArrayBuffer.isView(p)?g[y]=t(p):g[y]=d(p)}return g}function a(l){if(typeof l!="object"||l===null)return l;if(Array.isArray(l))return o(l,a);if(l.constructor!==Object&&(s=i.get(l.constructor)))return s(l,a);const d={};for(const u in l){if(Object.hasOwnProperty.call(l,u)===!1)continue;const g=l[u];typeof g!="object"||g===null?d[u]=g:g.constructor!==Object&&(s=i.get(g.constructor))?d[u]=s(g,a):ArrayBuffer.isView(g)?d[u]=t(g):d[u]=a(g)}return d}function c(l){if(typeof l!="object"||l===null)return l;if(Array.isArray(l))return o(l,c);if(l.constructor!==Object&&(s=i.get(l.constructor)))return s(l,c);const d={};for(const u in l){const g=l[u];typeof g!="object"||g===null?d[u]=g:g.constructor!==Object&&(s=i.get(g.constructor))?d[u]=s(g,c):ArrayBuffer.isView(g)?d[u]=t(g):d[u]=c(g)}return d}}function n(r){const i=[],s=[],o=new Map;if(o.set(Date,u=>new Date(u)),o.set(Map,(u,g)=>new Map(c(Array.from(u),g))),o.set(Set,(u,g)=>new Set(c(Array.from(u),g))),r.constructorHandlers)for(const u of r.constructorHandlers)o.set(u[0],u[1]);let a=null;return r.proto?d:l;function c(u,g){const f=Object.keys(u),y=new Array(f.length);for(let p=0;p<f.length;p++){const m=f[p],w=u[m];if(typeof w!="object"||w===null)y[m]=w;else if(w.constructor!==Object&&(a=o.get(w.constructor)))y[m]=a(w,g);else if(ArrayBuffer.isView(w))y[m]=t(w);else{const E=i.indexOf(w);E!==-1?y[m]=s[E]:y[m]=g(w)}}return y}function l(u){if(typeof u!="object"||u===null)return u;if(Array.isArray(u))return c(u,l);if(u.constructor!==Object&&(a=o.get(u.constructor)))return a(u,l);const g={};i.push(u),s.push(g);for(const f in u){if(Object.hasOwnProperty.call(u,f)===!1)continue;const y=u[f];if(typeof y!="object"||y===null)g[f]=y;else if(y.constructor!==Object&&(a=o.get(y.constructor)))g[f]=a(y,l);else if(ArrayBuffer.isView(y))g[f]=t(y);else{const p=i.indexOf(y);p!==-1?g[f]=s[p]:g[f]=l(y)}}return i.pop(),s.pop(),g}function d(u){if(typeof u!="object"||u===null)return u;if(Array.isArray(u))return c(u,d);if(u.constructor!==Object&&(a=o.get(u.constructor)))return a(u,d);const g={};i.push(u),s.push(g);for(const f in u){const y=u[f];if(typeof y!="object"||y===null)g[f]=y;else if(y.constructor!==Object&&(a=o.get(y.constructor)))g[f]=a(y,d);else if(ArrayBuffer.isView(y))g[f]=t(y);else{const p=i.indexOf(y);p!==-1?g[f]=s[p]:g[f]=d(y)}}return i.pop(),s.pop(),g}}return ht}var es=Yi();const cr=Zi(es);cr();function Lt(t){if(t==null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:!(Symbol.iterator in t)&&!(Symbol.toStringTag in t)}function ne(t){return typeof t=="string"}function ts(t){return Number.isFinite(t)}function Y(t){return Number.isSafeInteger(t)&&t>=0}function W(t){return t!=null}function ns(t,e){return Lt(t)&&ne(e)&&e in t}var rs=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,is=typeof self=="object"&&self&&self.Object===Object&&self,Xt=rs||is||Function("return this")(),de=Xt.Symbol,ur=Object.prototype,ss=ur.hasOwnProperty,as=ur.toString,xe=de?de.toStringTag:void 0;function os(t){var e=ss.call(t,xe),n=t[xe];try{t[xe]=void 0;var r=!0}catch{}var i=as.call(t);return r&&(e?t[xe]=n:delete t[xe]),i}var ls=Object.prototype,cs=ls.toString;function us(t){return cs.call(t)}var hs="[object Null]",ds="[object Undefined]",En=de?de.toStringTag:void 0;function hr(t){return t==null?t===void 0?ds:hs:En&&En in Object(t)?os(t):us(t)}function dr(t){return t!=null&&typeof t=="object"}var gs="[object Symbol]";function fs(t){return typeof t=="symbol"||dr(t)&&hr(t)==gs}function ps(t,e){for(var n=-1,r=t==null?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i}var ms=Array.isArray,An=de?de.prototype:void 0,On=An?An.toString:void 0;function Zt(t){if(typeof t=="string")return t;if(ms(t))return ps(t,Zt)+"";if(fs(t))return On?On.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}var ys=/\s/;function bs(t){for(var e=t.length;e--&&ys.test(t.charAt(e)););return e}var vs=/^\s+/;function ws(t){return t&&t.slice(0,bs(t)+1).replace(vs,"")}function gr(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function fr(t){return t}var Ss="[object AsyncFunction]",xs="[object Function]",ks="[object GeneratorFunction]",Cs="[object Proxy]";function pr(t){if(!gr(t))return!1;var e=hr(t);return e==xs||e==ks||e==Ss||e==Cs}var dt=Xt["__core-js_shared__"],Tn=(function(){var t=/[^.]+$/.exec(dt&&dt.keys&&dt.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function Es(t){return!!Tn&&Tn in t}var As=Function.prototype,Os=As.toString;function Ts(t){if(t!=null){try{return Os.call(t)}catch{}try{return t+""}catch{}}return""}var Rs=/[\\^$.*+?()[\]{}|]/g,Ps=/^\[object .+?Constructor\]$/,Ns=Function.prototype,Is=Object.prototype,Ls=Ns.toString,qs=Is.hasOwnProperty,Ds=RegExp("^"+Ls.call(qs).replace(Rs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function $s(t){if(!gr(t)||Es(t))return!1;var e=pr(t)?Ds:Ps;return e.test(Ts(t))}function _s(t,e){return t?.[e]}function Yt(t,e){var n=_s(t,e);return $s(n)?n:void 0}function Bs(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}var Us=800,zs=16,js=Date.now;function Vs(t){var e=0,n=0;return function(){var r=js(),i=zs-(r-n);if(n=r,i>0){if(++e>=Us)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function Fs(t){return function(){return t}}var Rn=(function(){try{var t=Yt(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Ms=Rn?function(t,e){return Rn(t,"toString",{configurable:!0,enumerable:!1,value:Fs(e),writable:!0})}:fr,Hs=Vs(Ms);function Gs(t,e,n,r){for(var i=t.length,s=n+-1;++s<i;)if(e(t[s],s,t))return s;return-1}function Ws(t){return t!==t}function Ks(t,e,n){for(var r=n-1,i=t.length;++r<i;)if(t[r]===e)return r;return-1}function en(t,e,n){return e===e?Ks(t,e,n):Gs(t,Ws,n)}function Js(t,e){var n=t==null?0:t.length;return!!n&&en(t,e,0)>-1}function Qs(t,e){return t===e||t!==t&&e!==e}var Pn=Math.max;function Xs(t,e,n){return e=Pn(e===void 0?t.length-1:e,0),function(){for(var r=arguments,i=-1,s=Pn(r.length-e,0),o=Array(s);++i<s;)o[i]=r[e+i];i=-1;for(var a=Array(e+1);++i<e;)a[i]=r[i];return a[e]=n(o),Bs(t,this,a)}}function Zs(t,e){return Hs(Xs(t,e,fr),t+"")}var Ys=9007199254740991;function ea(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Ys}function ta(t){return t!=null&&ea(t.length)&&!pr(t)}var Ne=Yt(Object,"create");function na(){this.__data__=Ne?Ne(null):{},this.size=0}function ra(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var ia="__lodash_hash_undefined__",sa=Object.prototype,aa=sa.hasOwnProperty;function oa(t){var e=this.__data__;if(Ne){var n=e[t];return n===ia?void 0:n}return aa.call(e,t)?e[t]:void 0}var la=Object.prototype,ca=la.hasOwnProperty;function ua(t){var e=this.__data__;return Ne?e[t]!==void 0:ca.call(e,t)}var ha="__lodash_hash_undefined__";function da(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=Ne&&e===void 0?ha:e,this}function Q(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}Q.prototype.clear=na;Q.prototype.delete=ra;Q.prototype.get=oa;Q.prototype.has=ua;Q.prototype.set=da;function ga(){this.__data__=[],this.size=0}function ot(t,e){for(var n=t.length;n--;)if(Qs(t[n][0],e))return n;return-1}var fa=Array.prototype,pa=fa.splice;function ma(t){var e=this.__data__,n=ot(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():pa.call(e,n,1),--this.size,!0}function ya(t){var e=this.__data__,n=ot(e,t);return n<0?void 0:e[n][1]}function ba(t){return ot(this.__data__,t)>-1}function va(t,e){var n=this.__data__,r=ot(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function me(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}me.prototype.clear=ga;me.prototype.delete=ma;me.prototype.get=ya;me.prototype.has=ba;me.prototype.set=va;var wa=Yt(Xt,"Map");function Sa(){this.size=0,this.__data__={hash:new Q,map:new(wa||me),string:new Q}}function xa(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function lt(t,e){var n=t.__data__;return xa(e)?n[typeof e=="string"?"string":"hash"]:n.map}function ka(t){var e=lt(this,t).delete(t);return this.size-=e?1:0,e}function Ca(t){return lt(this,t).get(t)}function Ea(t){return lt(this,t).has(t)}function Aa(t,e){var n=lt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}function ye(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}ye.prototype.clear=Sa;ye.prototype.delete=ka;ye.prototype.get=Ca;ye.prototype.has=Ea;ye.prototype.set=Aa;function Oa(t){return t==null?"":Zt(t)}function Ta(t,e,n){var r=-1,i=t.length;e<0&&(e=-e>i?0:i+e),n=n>i?i:n,n<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var s=Array(i);++r<i;)s[r]=t[r+e];return s}function Ra(t,e,n){var r=t.length;return n=n===void 0?r:n,!e&&n>=r?t:Ta(t,e,n)}var Pa="\\ud800-\\udfff",Na="\\u0300-\\u036f",Ia="\\ufe20-\\ufe2f",La="\\u20d0-\\u20ff",qa=Na+Ia+La,Da="\\ufe0e\\ufe0f",$a="\\u200d",_a=RegExp("["+$a+Pa+qa+Da+"]");function Ba(t){return _a.test(t)}function Ua(t){return t.split("")}var mr="\\ud800-\\udfff",za="\\u0300-\\u036f",ja="\\ufe20-\\ufe2f",Va="\\u20d0-\\u20ff",Fa=za+ja+Va,Ma="\\ufe0e\\ufe0f",Ha="["+mr+"]",qt="["+Fa+"]",Dt="\\ud83c[\\udffb-\\udfff]",Ga="(?:"+qt+"|"+Dt+")",yr="[^"+mr+"]",br="(?:\\ud83c[\\udde6-\\uddff]){2}",vr="[\\ud800-\\udbff][\\udc00-\\udfff]",Wa="\\u200d",wr=Ga+"?",Sr="["+Ma+"]?",Ka="(?:"+Wa+"(?:"+[yr,br,vr].join("|")+")"+Sr+wr+")*",Ja=Sr+wr+Ka,Qa="(?:"+[yr+qt+"?",qt,br,vr,Ha].join("|")+")",Xa=RegExp(Dt+"(?="+Dt+")|"+Qa+Ja,"g");function Za(t){return t.match(Xa)||[]}function Nn(t){return Ba(t)?Za(t):Ua(t)}var Ya="__lodash_hash_undefined__";function eo(t){return this.__data__.set(t,Ya),this}function to(t){return this.__data__.has(t)}function Ze(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new ye;++e<n;)this.add(t[e])}Ze.prototype.add=Ze.prototype.push=eo;Ze.prototype.has=to;function no(t,e){return t.has(e)}function ro(t){return dr(t)&&ta(t)}var io=200;function so(t,e,n,r){var i=-1,s=Js,o=!0,a=t.length,c=[],l=e.length;if(!a)return c;e.length>=io&&(s=no,o=!1,e=new Ze(e));e:for(;++i<a;){var d=t[i],u=d;if(d=d!==0?d:0,o&&u===u){for(var g=l;g--;)if(e[g]===u)continue e;c.push(d)}else s(e,u,r)||c.push(d)}return c}function ao(t,e){for(var n=t.length;n--&&en(e,t[n],0)>-1;);return n}function oo(t,e){for(var n=-1,r=t.length;++n<r&&en(e,t[n],0)>-1;);return n}function In(t,e,n){if(t=Oa(t),t&&e===void 0)return ws(t);if(!t||!(e=Zt(e)))return t;var r=Nn(t),i=Nn(e),s=oo(r,i),o=ao(r,i)+1;return Ra(r,s,o).join("")}var lo=Zs(function(t,e){return ro(t)?so(t,e):[]}),se=function(){return se=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},se.apply(this,arguments)},co="~",uo="~~";function tn(t,e){for(var n={},r={},i=t.split(uo),s=!1,o=0;i.length>o;o++){for(var a=i[o].split(co),c=0;c<a.length;c+=2){var l=a[c],d=a[c+1],u="&"+l+";";n[u]=d,s&&(n["&"+l]=d),r[d]=u}s=!0}return e?{entities:se(se({},n),e.entities),characters:se(se({},r),e.characters)}:{entities:n,characters:r}}var gt={xml:/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g,html4:/∉|&(?:nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|ucirc|uuml|yacute|thorn|yuml|quot|amp|lt|gt|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g,html5:/·|℗|⋇|⪧|⩺|⋗|⦕|⩼|⪆|⥸|⋗|⋛|⪌|≷|≳|⪦|⩹|⋖|⋋|⋉|⥶|⩻|⦖|◃|⊴|◂|∉|⋹̸|⋵̸|∉|⋷|⋶|∌|∌|⋾|⋽|∥|⊠|⨱|⨰|&(?:AElig|AMP|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|GT|Iacute|Icirc|Igrave|Iuml|LT|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|QUOT|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|amp|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|gt|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|lt|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|quot|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g},ge={};ge.xml=tn(`lt~<~gt~>~quot~"~apos~'~amp~&`);ge.html4=tn(`apos~'~OElig~Œ~oelig~œ~Scaron~Š~scaron~š~Yuml~Ÿ~circ~ˆ~tilde~˜~ensp~ ~emsp~ ~thinsp~ ~zwnj~~zwj~~lrm~~rlm~~ndash~–~mdash~—~lsquo~‘~rsquo~’~sbquo~‚~ldquo~“~rdquo~”~bdquo~„~dagger~†~Dagger~‡~permil~‰~lsaquo~‹~rsaquo~›~euro~€~fnof~ƒ~Alpha~Α~Beta~Β~Gamma~Γ~Delta~Δ~Epsilon~Ε~Zeta~Ζ~Eta~Η~Theta~Θ~Iota~Ι~Kappa~Κ~Lambda~Λ~Mu~Μ~Nu~Ν~Xi~Ξ~Omicron~Ο~Pi~Π~Rho~Ρ~Sigma~Σ~Tau~Τ~Upsilon~Υ~Phi~Φ~Chi~Χ~Psi~Ψ~Omega~Ω~alpha~α~beta~β~gamma~γ~delta~δ~epsilon~ε~zeta~ζ~eta~η~theta~θ~iota~ι~kappa~κ~lambda~λ~mu~μ~nu~ν~xi~ξ~omicron~ο~pi~π~rho~ρ~sigmaf~ς~sigma~σ~tau~τ~upsilon~υ~phi~φ~chi~χ~psi~ψ~omega~ω~thetasym~ϑ~upsih~ϒ~piv~ϖ~bull~•~hellip~…~prime~′~Prime~″~oline~‾~frasl~⁄~weierp~℘~image~ℑ~real~ℜ~trade~™~alefsym~ℵ~larr~←~uarr~↑~rarr~→~darr~↓~harr~↔~crarr~↵~lArr~⇐~uArr~⇑~rArr~⇒~dArr~⇓~hArr~⇔~forall~∀~part~∂~exist~∃~empty~∅~nabla~∇~isin~∈~notin~∉~ni~∋~prod~∏~sum~∑~minus~−~lowast~∗~radic~√~prop~∝~infin~∞~ang~∠~and~∧~or~∨~cap~∩~cup~∪~int~∫~there4~∴~sim~∼~cong~≅~asymp~≈~ne~≠~equiv~≡~le~≤~ge~≥~sub~⊂~sup~⊃~nsub~⊄~sube~⊆~supe~⊇~oplus~⊕~otimes~⊗~perp~⊥~sdot~⋅~lceil~⌈~rceil~⌉~lfloor~⌊~rfloor~⌋~lang~〈~rang~〉~loz~◊~spades~♠~clubs~♣~hearts~♥~diams~♦~~nbsp~ ~iexcl~¡~cent~¢~pound~£~curren~¤~yen~¥~brvbar~¦~sect~§~uml~¨~copy~©~ordf~ª~laquo~«~not~¬~shy~~reg~®~macr~¯~deg~°~plusmn~±~sup2~²~sup3~³~acute~´~micro~µ~para~¶~middot~·~cedil~¸~sup1~¹~ordm~º~raquo~»~frac14~¼~frac12~½~frac34~¾~iquest~¿~Agrave~À~Aacute~Á~Acirc~Â~Atilde~Ã~Auml~Ä~Aring~Å~AElig~Æ~Ccedil~Ç~Egrave~È~Eacute~É~Ecirc~Ê~Euml~Ë~Igrave~Ì~Iacute~Í~Icirc~Î~Iuml~Ï~ETH~Ð~Ntilde~Ñ~Ograve~Ò~Oacute~Ó~Ocirc~Ô~Otilde~Õ~Ouml~Ö~times~×~Oslash~Ø~Ugrave~Ù~Uacute~Ú~Ucirc~Û~Uuml~Ü~Yacute~Ý~THORN~Þ~szlig~ß~agrave~à~aacute~á~acirc~â~atilde~ã~auml~ä~aring~å~aelig~æ~ccedil~ç~egrave~è~eacute~é~ecirc~ê~euml~ë~igrave~ì~iacute~í~icirc~î~iuml~ï~eth~ð~ntilde~ñ~ograve~ò~oacute~ó~ocirc~ô~otilde~õ~ouml~ö~divide~÷~oslash~ø~ugrave~ù~uacute~ú~ucirc~û~uuml~ü~yacute~ý~thorn~þ~yuml~ÿ~quot~"~amp~&~lt~<~gt~>`);ge.html5=tn('Abreve~Ă~Acy~А~Afr~𝔄~Amacr~Ā~And~⩓~Aogon~Ą~Aopf~𝔸~ApplyFunction~~Ascr~𝒜~Assign~≔~Backslash~∖~Barv~⫧~Barwed~⌆~Bcy~Б~Because~∵~Bernoullis~ℬ~Bfr~𝔅~Bopf~𝔹~Breve~˘~Bscr~ℬ~Bumpeq~≎~CHcy~Ч~Cacute~Ć~Cap~⋒~CapitalDifferentialD~ⅅ~Cayleys~ℭ~Ccaron~Č~Ccirc~Ĉ~Cconint~∰~Cdot~Ċ~Cedilla~¸~CenterDot~·~Cfr~ℭ~CircleDot~⊙~CircleMinus~⊖~CirclePlus~⊕~CircleTimes~⊗~ClockwiseContourIntegral~∲~CloseCurlyDoubleQuote~”~CloseCurlyQuote~’~Colon~∷~Colone~⩴~Congruent~≡~Conint~∯~ContourIntegral~∮~Copf~ℂ~Coproduct~∐~CounterClockwiseContourIntegral~∳~Cross~⨯~Cscr~𝒞~Cup~⋓~CupCap~≍~DD~ⅅ~DDotrahd~⤑~DJcy~Ђ~DScy~Ѕ~DZcy~Џ~Darr~↡~Dashv~⫤~Dcaron~Ď~Dcy~Д~Del~∇~Dfr~𝔇~DiacriticalAcute~´~DiacriticalDot~˙~DiacriticalDoubleAcute~˝~DiacriticalGrave~`~DiacriticalTilde~˜~Diamond~⋄~DifferentialD~ⅆ~Dopf~𝔻~Dot~¨~DotDot~⃜~DotEqual~≐~DoubleContourIntegral~∯~DoubleDot~¨~DoubleDownArrow~⇓~DoubleLeftArrow~⇐~DoubleLeftRightArrow~⇔~DoubleLeftTee~⫤~DoubleLongLeftArrow~⟸~DoubleLongLeftRightArrow~⟺~DoubleLongRightArrow~⟹~DoubleRightArrow~⇒~DoubleRightTee~⊨~DoubleUpArrow~⇑~DoubleUpDownArrow~⇕~DoubleVerticalBar~∥~DownArrow~↓~DownArrowBar~⤓~DownArrowUpArrow~⇵~DownBreve~̑~DownLeftRightVector~⥐~DownLeftTeeVector~⥞~DownLeftVector~↽~DownLeftVectorBar~⥖~DownRightTeeVector~⥟~DownRightVector~⇁~DownRightVectorBar~⥗~DownTee~⊤~DownTeeArrow~↧~Downarrow~⇓~Dscr~𝒟~Dstrok~Đ~ENG~Ŋ~Ecaron~Ě~Ecy~Э~Edot~Ė~Efr~𝔈~Element~∈~Emacr~Ē~EmptySmallSquare~◻~EmptyVerySmallSquare~▫~Eogon~Ę~Eopf~𝔼~Equal~⩵~EqualTilde~≂~Equilibrium~⇌~Escr~ℰ~Esim~⩳~Exists~∃~ExponentialE~ⅇ~Fcy~Ф~Ffr~𝔉~FilledSmallSquare~◼~FilledVerySmallSquare~▪~Fopf~𝔽~ForAll~∀~Fouriertrf~ℱ~Fscr~ℱ~GJcy~Ѓ~Gammad~Ϝ~Gbreve~Ğ~Gcedil~Ģ~Gcirc~Ĝ~Gcy~Г~Gdot~Ġ~Gfr~𝔊~Gg~⋙~Gopf~𝔾~GreaterEqual~≥~GreaterEqualLess~⋛~GreaterFullEqual~≧~GreaterGreater~⪢~GreaterLess~≷~GreaterSlantEqual~⩾~GreaterTilde~≳~Gscr~𝒢~Gt~≫~HARDcy~Ъ~Hacek~ˇ~Hat~^~Hcirc~Ĥ~Hfr~ℌ~HilbertSpace~ℋ~Hopf~ℍ~HorizontalLine~─~Hscr~ℋ~Hstrok~Ħ~HumpDownHump~≎~HumpEqual~≏~IEcy~Е~IJlig~IJ~IOcy~Ё~Icy~И~Idot~İ~Ifr~ℑ~Im~ℑ~Imacr~Ī~ImaginaryI~ⅈ~Implies~⇒~Int~∬~Integral~∫~Intersection~⋂~InvisibleComma~~InvisibleTimes~~Iogon~Į~Iopf~𝕀~Iscr~ℐ~Itilde~Ĩ~Iukcy~І~Jcirc~Ĵ~Jcy~Й~Jfr~𝔍~Jopf~𝕁~Jscr~𝒥~Jsercy~Ј~Jukcy~Є~KHcy~Х~KJcy~Ќ~Kcedil~Ķ~Kcy~К~Kfr~𝔎~Kopf~𝕂~Kscr~𝒦~LJcy~Љ~Lacute~Ĺ~Lang~⟪~Laplacetrf~ℒ~Larr~↞~Lcaron~Ľ~Lcedil~Ļ~Lcy~Л~LeftAngleBracket~⟨~LeftArrow~←~LeftArrowBar~⇤~LeftArrowRightArrow~⇆~LeftCeiling~⌈~LeftDoubleBracket~⟦~LeftDownTeeVector~⥡~LeftDownVector~⇃~LeftDownVectorBar~⥙~LeftFloor~⌊~LeftRightArrow~↔~LeftRightVector~⥎~LeftTee~⊣~LeftTeeArrow~↤~LeftTeeVector~⥚~LeftTriangle~⊲~LeftTriangleBar~⧏~LeftTriangleEqual~⊴~LeftUpDownVector~⥑~LeftUpTeeVector~⥠~LeftUpVector~↿~LeftUpVectorBar~⥘~LeftVector~↼~LeftVectorBar~⥒~Leftarrow~⇐~Leftrightarrow~⇔~LessEqualGreater~⋚~LessFullEqual~≦~LessGreater~≶~LessLess~⪡~LessSlantEqual~⩽~LessTilde~≲~Lfr~𝔏~Ll~⋘~Lleftarrow~⇚~Lmidot~Ŀ~LongLeftArrow~⟵~LongLeftRightArrow~⟷~LongRightArrow~⟶~Longleftarrow~⟸~Longleftrightarrow~⟺~Longrightarrow~⟹~Lopf~𝕃~LowerLeftArrow~↙~LowerRightArrow~↘~Lscr~ℒ~Lsh~↰~Lstrok~Ł~Lt~≪~Map~⤅~Mcy~М~MediumSpace~ ~Mellintrf~ℳ~Mfr~𝔐~MinusPlus~∓~Mopf~𝕄~Mscr~ℳ~NJcy~Њ~Nacute~Ń~Ncaron~Ň~Ncedil~Ņ~Ncy~Н~NegativeMediumSpace~~NegativeThickSpace~~NegativeThinSpace~~NegativeVeryThinSpace~~NestedGreaterGreater~≫~NestedLessLess~≪~NewLine~\n~Nfr~𝔑~NoBreak~~NonBreakingSpace~ ~Nopf~ℕ~Not~⫬~NotCongruent~≢~NotCupCap~≭~NotDoubleVerticalBar~∦~NotElement~∉~NotEqual~≠~NotEqualTilde~≂̸~NotExists~∄~NotGreater~≯~NotGreaterEqual~≱~NotGreaterFullEqual~≧̸~NotGreaterGreater~≫̸~NotGreaterLess~≹~NotGreaterSlantEqual~⩾̸~NotGreaterTilde~≵~NotHumpDownHump~≎̸~NotHumpEqual~≏̸~NotLeftTriangle~⋪~NotLeftTriangleBar~⧏̸~NotLeftTriangleEqual~⋬~NotLess~≮~NotLessEqual~≰~NotLessGreater~≸~NotLessLess~≪̸~NotLessSlantEqual~⩽̸~NotLessTilde~≴~NotNestedGreaterGreater~⪢̸~NotNestedLessLess~⪡̸~NotPrecedes~⊀~NotPrecedesEqual~⪯̸~NotPrecedesSlantEqual~⋠~NotReverseElement~∌~NotRightTriangle~⋫~NotRightTriangleBar~⧐̸~NotRightTriangleEqual~⋭~NotSquareSubset~⊏̸~NotSquareSubsetEqual~⋢~NotSquareSuperset~⊐̸~NotSquareSupersetEqual~⋣~NotSubset~⊂⃒~NotSubsetEqual~⊈~NotSucceeds~⊁~NotSucceedsEqual~⪰̸~NotSucceedsSlantEqual~⋡~NotSucceedsTilde~≿̸~NotSuperset~⊃⃒~NotSupersetEqual~⊉~NotTilde~≁~NotTildeEqual~≄~NotTildeFullEqual~≇~NotTildeTilde~≉~NotVerticalBar~∤~Nscr~𝒩~Ocy~О~Odblac~Ő~Ofr~𝔒~Omacr~Ō~Oopf~𝕆~OpenCurlyDoubleQuote~“~OpenCurlyQuote~‘~Or~⩔~Oscr~𝒪~Otimes~⨷~OverBar~‾~OverBrace~⏞~OverBracket~⎴~OverParenthesis~⏜~PartialD~∂~Pcy~П~Pfr~𝔓~PlusMinus~±~Poincareplane~ℌ~Popf~ℙ~Pr~⪻~Precedes~≺~PrecedesEqual~⪯~PrecedesSlantEqual~≼~PrecedesTilde~≾~Product~∏~Proportion~∷~Proportional~∝~Pscr~𝒫~Qfr~𝔔~Qopf~ℚ~Qscr~𝒬~RBarr~⤐~Racute~Ŕ~Rang~⟫~Rarr~↠~Rarrtl~⤖~Rcaron~Ř~Rcedil~Ŗ~Rcy~Р~Re~ℜ~ReverseElement~∋~ReverseEquilibrium~⇋~ReverseUpEquilibrium~⥯~Rfr~ℜ~RightAngleBracket~⟩~RightArrow~→~RightArrowBar~⇥~RightArrowLeftArrow~⇄~RightCeiling~⌉~RightDoubleBracket~⟧~RightDownTeeVector~⥝~RightDownVector~⇂~RightDownVectorBar~⥕~RightFloor~⌋~RightTee~⊢~RightTeeArrow~↦~RightTeeVector~⥛~RightTriangle~⊳~RightTriangleBar~⧐~RightTriangleEqual~⊵~RightUpDownVector~⥏~RightUpTeeVector~⥜~RightUpVector~↾~RightUpVectorBar~⥔~RightVector~⇀~RightVectorBar~⥓~Rightarrow~⇒~Ropf~ℝ~RoundImplies~⥰~Rrightarrow~⇛~Rscr~ℛ~Rsh~↱~RuleDelayed~⧴~SHCHcy~Щ~SHcy~Ш~SOFTcy~Ь~Sacute~Ś~Sc~⪼~Scedil~Ş~Scirc~Ŝ~Scy~С~Sfr~𝔖~ShortDownArrow~↓~ShortLeftArrow~←~ShortRightArrow~→~ShortUpArrow~↑~SmallCircle~∘~Sopf~𝕊~Sqrt~√~Square~□~SquareIntersection~⊓~SquareSubset~⊏~SquareSubsetEqual~⊑~SquareSuperset~⊐~SquareSupersetEqual~⊒~SquareUnion~⊔~Sscr~𝒮~Star~⋆~Sub~⋐~Subset~⋐~SubsetEqual~⊆~Succeeds~≻~SucceedsEqual~⪰~SucceedsSlantEqual~≽~SucceedsTilde~≿~SuchThat~∋~Sum~∑~Sup~⋑~Superset~⊃~SupersetEqual~⊇~Supset~⋑~TRADE~™~TSHcy~Ћ~TScy~Ц~Tab~ ~Tcaron~Ť~Tcedil~Ţ~Tcy~Т~Tfr~𝔗~Therefore~∴~ThickSpace~ ~ThinSpace~ ~Tilde~∼~TildeEqual~≃~TildeFullEqual~≅~TildeTilde~≈~Topf~𝕋~TripleDot~⃛~Tscr~𝒯~Tstrok~Ŧ~Uarr~↟~Uarrocir~⥉~Ubrcy~Ў~Ubreve~Ŭ~Ucy~У~Udblac~Ű~Ufr~𝔘~Umacr~Ū~UnderBar~_~UnderBrace~⏟~UnderBracket~⎵~UnderParenthesis~⏝~Union~⋃~UnionPlus~⊎~Uogon~Ų~Uopf~𝕌~UpArrow~↑~UpArrowBar~⤒~UpArrowDownArrow~⇅~UpDownArrow~↕~UpEquilibrium~⥮~UpTee~⊥~UpTeeArrow~↥~Uparrow~⇑~Updownarrow~⇕~UpperLeftArrow~↖~UpperRightArrow~↗~Upsi~ϒ~Uring~Ů~Uscr~𝒰~Utilde~Ũ~VDash~⊫~Vbar~⫫~Vcy~В~Vdash~⊩~Vdashl~⫦~Vee~⋁~Verbar~‖~Vert~‖~VerticalBar~∣~VerticalLine~|~VerticalSeparator~❘~VerticalTilde~≀~VeryThinSpace~ ~Vfr~𝔙~Vopf~𝕍~Vscr~𝒱~Vvdash~⊪~Wcirc~Ŵ~Wedge~⋀~Wfr~𝔚~Wopf~𝕎~Wscr~𝒲~Xfr~𝔛~Xopf~𝕏~Xscr~𝒳~YAcy~Я~YIcy~Ї~YUcy~Ю~Ycirc~Ŷ~Ycy~Ы~Yfr~𝔜~Yopf~𝕐~Yscr~𝒴~ZHcy~Ж~Zacute~Ź~Zcaron~Ž~Zcy~З~Zdot~Ż~ZeroWidthSpace~~Zfr~ℨ~Zopf~ℤ~Zscr~𝒵~abreve~ă~ac~∾~acE~∾̳~acd~∿~acy~а~af~~afr~𝔞~aleph~ℵ~amacr~ā~amalg~⨿~andand~⩕~andd~⩜~andslope~⩘~andv~⩚~ange~⦤~angle~∠~angmsd~∡~angmsdaa~⦨~angmsdab~⦩~angmsdac~⦪~angmsdad~⦫~angmsdae~⦬~angmsdaf~⦭~angmsdag~⦮~angmsdah~⦯~angrt~∟~angrtvb~⊾~angrtvbd~⦝~angsph~∢~angst~Å~angzarr~⍼~aogon~ą~aopf~𝕒~ap~≈~apE~⩰~apacir~⩯~ape~≊~apid~≋~approx~≈~approxeq~≊~ascr~𝒶~ast~*~asympeq~≍~awconint~∳~awint~⨑~bNot~⫭~backcong~≌~backepsilon~϶~backprime~‵~backsim~∽~backsimeq~⋍~barvee~⊽~barwed~⌅~barwedge~⌅~bbrk~⎵~bbrktbrk~⎶~bcong~≌~bcy~б~becaus~∵~because~∵~bemptyv~⦰~bepsi~϶~bernou~ℬ~beth~ℶ~between~≬~bfr~𝔟~bigcap~⋂~bigcirc~◯~bigcup~⋃~bigodot~⨀~bigoplus~⨁~bigotimes~⨂~bigsqcup~⨆~bigstar~★~bigtriangledown~▽~bigtriangleup~△~biguplus~⨄~bigvee~⋁~bigwedge~⋀~bkarow~⤍~blacklozenge~⧫~blacksquare~▪~blacktriangle~▴~blacktriangledown~▾~blacktriangleleft~◂~blacktriangleright~▸~blank~␣~blk12~▒~blk14~░~blk34~▓~block~█~bne~=⃥~bnequiv~≡⃥~bnot~⌐~bopf~𝕓~bot~⊥~bottom~⊥~bowtie~⋈~boxDL~╗~boxDR~╔~boxDl~╖~boxDr~╓~boxH~═~boxHD~╦~boxHU~╩~boxHd~╤~boxHu~╧~boxUL~╝~boxUR~╚~boxUl~╜~boxUr~╙~boxV~║~boxVH~╬~boxVL~╣~boxVR~╠~boxVh~╫~boxVl~╢~boxVr~╟~boxbox~⧉~boxdL~╕~boxdR~╒~boxdl~┐~boxdr~┌~boxh~─~boxhD~╥~boxhU~╨~boxhd~┬~boxhu~┴~boxminus~⊟~boxplus~⊞~boxtimes~⊠~boxuL~╛~boxuR~╘~boxul~┘~boxur~└~boxv~│~boxvH~╪~boxvL~╡~boxvR~╞~boxvh~┼~boxvl~┤~boxvr~├~bprime~‵~breve~˘~bscr~𝒷~bsemi~⁏~bsim~∽~bsime~⋍~bsol~\\~bsolb~⧅~bsolhsub~⟈~bullet~•~bump~≎~bumpE~⪮~bumpe~≏~bumpeq~≏~cacute~ć~capand~⩄~capbrcup~⩉~capcap~⩋~capcup~⩇~capdot~⩀~caps~∩︀~caret~⁁~caron~ˇ~ccaps~⩍~ccaron~č~ccirc~ĉ~ccups~⩌~ccupssm~⩐~cdot~ċ~cemptyv~⦲~centerdot~·~cfr~𝔠~chcy~ч~check~✓~checkmark~✓~cir~○~cirE~⧃~circeq~≗~circlearrowleft~↺~circlearrowright~↻~circledR~®~circledS~Ⓢ~circledast~⊛~circledcirc~⊚~circleddash~⊝~cire~≗~cirfnint~⨐~cirmid~⫯~cirscir~⧂~clubsuit~♣~colon~:~colone~≔~coloneq~≔~comma~,~commat~@~comp~∁~compfn~∘~complement~∁~complexes~ℂ~congdot~⩭~conint~∮~copf~𝕔~coprod~∐~copysr~℗~cross~✗~cscr~𝒸~csub~⫏~csube~⫑~csup~⫐~csupe~⫒~ctdot~⋯~cudarrl~⤸~cudarrr~⤵~cuepr~⋞~cuesc~⋟~cularr~↶~cularrp~⤽~cupbrcap~⩈~cupcap~⩆~cupcup~⩊~cupdot~⊍~cupor~⩅~cups~∪︀~curarr~↷~curarrm~⤼~curlyeqprec~⋞~curlyeqsucc~⋟~curlyvee~⋎~curlywedge~⋏~curvearrowleft~↶~curvearrowright~↷~cuvee~⋎~cuwed~⋏~cwconint~∲~cwint~∱~cylcty~⌭~dHar~⥥~daleth~ℸ~dash~‐~dashv~⊣~dbkarow~⤏~dblac~˝~dcaron~ď~dcy~д~dd~ⅆ~ddagger~‡~ddarr~⇊~ddotseq~⩷~demptyv~⦱~dfisht~⥿~dfr~𝔡~dharl~⇃~dharr~⇂~diam~⋄~diamond~⋄~diamondsuit~♦~die~¨~digamma~ϝ~disin~⋲~div~÷~divideontimes~⋇~divonx~⋇~djcy~ђ~dlcorn~⌞~dlcrop~⌍~dollar~$~dopf~𝕕~dot~˙~doteq~≐~doteqdot~≑~dotminus~∸~dotplus~∔~dotsquare~⊡~doublebarwedge~⌆~downarrow~↓~downdownarrows~⇊~downharpoonleft~⇃~downharpoonright~⇂~drbkarow~⤐~drcorn~⌟~drcrop~⌌~dscr~𝒹~dscy~ѕ~dsol~⧶~dstrok~đ~dtdot~⋱~dtri~▿~dtrif~▾~duarr~⇵~duhar~⥯~dwangle~⦦~dzcy~џ~dzigrarr~⟿~eDDot~⩷~eDot~≑~easter~⩮~ecaron~ě~ecir~≖~ecolon~≕~ecy~э~edot~ė~ee~ⅇ~efDot~≒~efr~𝔢~eg~⪚~egs~⪖~egsdot~⪘~el~⪙~elinters~⏧~ell~ℓ~els~⪕~elsdot~⪗~emacr~ē~emptyset~∅~emptyv~∅~emsp13~ ~emsp14~ ~eng~ŋ~eogon~ę~eopf~𝕖~epar~⋕~eparsl~⧣~eplus~⩱~epsi~ε~epsiv~ϵ~eqcirc~≖~eqcolon~≕~eqsim~≂~eqslantgtr~⪖~eqslantless~⪕~equals~=~equest~≟~equivDD~⩸~eqvparsl~⧥~erDot~≓~erarr~⥱~escr~ℯ~esdot~≐~esim~≂~excl~!~expectation~ℰ~exponentiale~ⅇ~fallingdotseq~≒~fcy~ф~female~♀~ffilig~ffi~fflig~ff~ffllig~ffl~ffr~𝔣~filig~fi~fjlig~fj~flat~♭~fllig~fl~fltns~▱~fopf~𝕗~fork~⋔~forkv~⫙~fpartint~⨍~frac13~⅓~frac15~⅕~frac16~⅙~frac18~⅛~frac23~⅔~frac25~⅖~frac35~⅗~frac38~⅜~frac45~⅘~frac56~⅚~frac58~⅝~frac78~⅞~frown~⌢~fscr~𝒻~gE~≧~gEl~⪌~gacute~ǵ~gammad~ϝ~gap~⪆~gbreve~ğ~gcirc~ĝ~gcy~г~gdot~ġ~gel~⋛~geq~≥~geqq~≧~geqslant~⩾~ges~⩾~gescc~⪩~gesdot~⪀~gesdoto~⪂~gesdotol~⪄~gesl~⋛︀~gesles~⪔~gfr~𝔤~gg~≫~ggg~⋙~gimel~ℷ~gjcy~ѓ~gl~≷~glE~⪒~gla~⪥~glj~⪤~gnE~≩~gnap~⪊~gnapprox~⪊~gne~⪈~gneq~⪈~gneqq~≩~gnsim~⋧~gopf~𝕘~grave~`~gscr~ℊ~gsim~≳~gsime~⪎~gsiml~⪐~gtcc~⪧~gtcir~⩺~gtdot~⋗~gtlPar~⦕~gtquest~⩼~gtrapprox~⪆~gtrarr~⥸~gtrdot~⋗~gtreqless~⋛~gtreqqless~⪌~gtrless~≷~gtrsim~≳~gvertneqq~≩︀~gvnE~≩︀~hairsp~ ~half~½~hamilt~ℋ~hardcy~ъ~harrcir~⥈~harrw~↭~hbar~ℏ~hcirc~ĥ~heartsuit~♥~hercon~⊹~hfr~𝔥~hksearow~⤥~hkswarow~⤦~hoarr~⇿~homtht~∻~hookleftarrow~↩~hookrightarrow~↪~hopf~𝕙~horbar~―~hscr~𝒽~hslash~ℏ~hstrok~ħ~hybull~⁃~hyphen~‐~ic~~icy~и~iecy~е~iff~⇔~ifr~𝔦~ii~ⅈ~iiiint~⨌~iiint~∭~iinfin~⧜~iiota~℩~ijlig~ij~imacr~ī~imagline~ℐ~imagpart~ℑ~imath~ı~imof~⊷~imped~Ƶ~in~∈~incare~℅~infintie~⧝~inodot~ı~intcal~⊺~integers~ℤ~intercal~⊺~intlarhk~⨗~intprod~⨼~iocy~ё~iogon~į~iopf~𝕚~iprod~⨼~iscr~𝒾~isinE~⋹~isindot~⋵~isins~⋴~isinsv~⋳~isinv~∈~it~~itilde~ĩ~iukcy~і~jcirc~ĵ~jcy~й~jfr~𝔧~jmath~ȷ~jopf~𝕛~jscr~𝒿~jsercy~ј~jukcy~є~kappav~ϰ~kcedil~ķ~kcy~к~kfr~𝔨~kgreen~ĸ~khcy~х~kjcy~ќ~kopf~𝕜~kscr~𝓀~lAarr~⇚~lAtail~⤛~lBarr~⤎~lE~≦~lEg~⪋~lHar~⥢~lacute~ĺ~laemptyv~⦴~lagran~ℒ~langd~⦑~langle~⟨~lap~⪅~larrb~⇤~larrbfs~⤟~larrfs~⤝~larrhk~↩~larrlp~↫~larrpl~⤹~larrsim~⥳~larrtl~↢~lat~⪫~latail~⤙~late~⪭~lates~⪭︀~lbarr~⤌~lbbrk~❲~lbrace~{~lbrack~[~lbrke~⦋~lbrksld~⦏~lbrkslu~⦍~lcaron~ľ~lcedil~ļ~lcub~{~lcy~л~ldca~⤶~ldquor~„~ldrdhar~⥧~ldrushar~⥋~ldsh~↲~leftarrow~←~leftarrowtail~↢~leftharpoondown~↽~leftharpoonup~↼~leftleftarrows~⇇~leftrightarrow~↔~leftrightarrows~⇆~leftrightharpoons~⇋~leftrightsquigarrow~↭~leftthreetimes~⋋~leg~⋚~leq~≤~leqq~≦~leqslant~⩽~les~⩽~lescc~⪨~lesdot~⩿~lesdoto~⪁~lesdotor~⪃~lesg~⋚︀~lesges~⪓~lessapprox~⪅~lessdot~⋖~lesseqgtr~⋚~lesseqqgtr~⪋~lessgtr~≶~lesssim~≲~lfisht~⥼~lfr~𝔩~lg~≶~lgE~⪑~lhard~↽~lharu~↼~lharul~⥪~lhblk~▄~ljcy~љ~ll~≪~llarr~⇇~llcorner~⌞~llhard~⥫~lltri~◺~lmidot~ŀ~lmoust~⎰~lmoustache~⎰~lnE~≨~lnap~⪉~lnapprox~⪉~lne~⪇~lneq~⪇~lneqq~≨~lnsim~⋦~loang~⟬~loarr~⇽~lobrk~⟦~longleftarrow~⟵~longleftrightarrow~⟷~longmapsto~⟼~longrightarrow~⟶~looparrowleft~↫~looparrowright~↬~lopar~⦅~lopf~𝕝~loplus~⨭~lotimes~⨴~lowbar~_~lozenge~◊~lozf~⧫~lpar~(~lparlt~⦓~lrarr~⇆~lrcorner~⌟~lrhar~⇋~lrhard~⥭~lrtri~⊿~lscr~𝓁~lsh~↰~lsim~≲~lsime~⪍~lsimg~⪏~lsqb~[~lsquor~‚~lstrok~ł~ltcc~⪦~ltcir~⩹~ltdot~⋖~lthree~⋋~ltimes~⋉~ltlarr~⥶~ltquest~⩻~ltrPar~⦖~ltri~◃~ltrie~⊴~ltrif~◂~lurdshar~⥊~luruhar~⥦~lvertneqq~≨︀~lvnE~≨︀~mDDot~∺~male~♂~malt~✠~maltese~✠~map~↦~mapsto~↦~mapstodown~↧~mapstoleft~↤~mapstoup~↥~marker~▮~mcomma~⨩~mcy~м~measuredangle~∡~mfr~𝔪~mho~℧~mid~∣~midast~*~midcir~⫰~minusb~⊟~minusd~∸~minusdu~⨪~mlcp~⫛~mldr~…~mnplus~∓~models~⊧~mopf~𝕞~mp~∓~mscr~𝓂~mstpos~∾~multimap~⊸~mumap~⊸~nGg~⋙̸~nGt~≫⃒~nGtv~≫̸~nLeftarrow~⇍~nLeftrightarrow~⇎~nLl~⋘̸~nLt~≪⃒~nLtv~≪̸~nRightarrow~⇏~nVDash~⊯~nVdash~⊮~nacute~ń~nang~∠⃒~nap~≉~napE~⩰̸~napid~≋̸~napos~ʼn~napprox~≉~natur~♮~natural~♮~naturals~ℕ~nbump~≎̸~nbumpe~≏̸~ncap~⩃~ncaron~ň~ncedil~ņ~ncong~≇~ncongdot~⩭̸~ncup~⩂~ncy~н~neArr~⇗~nearhk~⤤~nearr~↗~nearrow~↗~nedot~≐̸~nequiv~≢~nesear~⤨~nesim~≂̸~nexist~∄~nexists~∄~nfr~𝔫~ngE~≧̸~nge~≱~ngeq~≱~ngeqq~≧̸~ngeqslant~⩾̸~nges~⩾̸~ngsim~≵~ngt~≯~ngtr~≯~nhArr~⇎~nharr~↮~nhpar~⫲~nis~⋼~nisd~⋺~niv~∋~njcy~њ~nlArr~⇍~nlE~≦̸~nlarr~↚~nldr~‥~nle~≰~nleftarrow~↚~nleftrightarrow~↮~nleq~≰~nleqq~≦̸~nleqslant~⩽̸~nles~⩽̸~nless~≮~nlsim~≴~nlt~≮~nltri~⋪~nltrie~⋬~nmid~∤~nopf~𝕟~notinE~⋹̸~notindot~⋵̸~notinva~∉~notinvb~⋷~notinvc~⋶~notni~∌~notniva~∌~notnivb~⋾~notnivc~⋽~npar~∦~nparallel~∦~nparsl~⫽⃥~npart~∂̸~npolint~⨔~npr~⊀~nprcue~⋠~npre~⪯̸~nprec~⊀~npreceq~⪯̸~nrArr~⇏~nrarr~↛~nrarrc~⤳̸~nrarrw~↝̸~nrightarrow~↛~nrtri~⋫~nrtrie~⋭~nsc~⊁~nsccue~⋡~nsce~⪰̸~nscr~𝓃~nshortmid~∤~nshortparallel~∦~nsim~≁~nsime~≄~nsimeq~≄~nsmid~∤~nspar~∦~nsqsube~⋢~nsqsupe~⋣~nsubE~⫅̸~nsube~⊈~nsubset~⊂⃒~nsubseteq~⊈~nsubseteqq~⫅̸~nsucc~⊁~nsucceq~⪰̸~nsup~⊅~nsupE~⫆̸~nsupe~⊉~nsupset~⊃⃒~nsupseteq~⊉~nsupseteqq~⫆̸~ntgl~≹~ntlg~≸~ntriangleleft~⋪~ntrianglelefteq~⋬~ntriangleright~⋫~ntrianglerighteq~⋭~num~#~numero~№~numsp~ ~nvDash~⊭~nvHarr~⤄~nvap~≍⃒~nvdash~⊬~nvge~≥⃒~nvgt~>⃒~nvinfin~⧞~nvlArr~⤂~nvle~≤⃒~nvlt~<⃒~nvltrie~⊴⃒~nvrArr~⤃~nvrtrie~⊵⃒~nvsim~∼⃒~nwArr~⇖~nwarhk~⤣~nwarr~↖~nwarrow~↖~nwnear~⤧~oS~Ⓢ~oast~⊛~ocir~⊚~ocy~о~odash~⊝~odblac~ő~odiv~⨸~odot~⊙~odsold~⦼~ofcir~⦿~ofr~𝔬~ogon~˛~ogt~⧁~ohbar~⦵~ohm~Ω~oint~∮~olarr~↺~olcir~⦾~olcross~⦻~olt~⧀~omacr~ō~omid~⦶~ominus~⊖~oopf~𝕠~opar~⦷~operp~⦹~orarr~↻~ord~⩝~order~ℴ~orderof~ℴ~origof~⊶~oror~⩖~orslope~⩗~orv~⩛~oscr~ℴ~osol~⊘~otimesas~⨶~ovbar~⌽~par~∥~parallel~∥~parsim~⫳~parsl~⫽~pcy~п~percnt~%~period~.~pertenk~‱~pfr~𝔭~phiv~ϕ~phmmat~ℳ~phone~☎~pitchfork~⋔~planck~ℏ~planckh~ℎ~plankv~ℏ~plus~+~plusacir~⨣~plusb~⊞~pluscir~⨢~plusdo~∔~plusdu~⨥~pluse~⩲~plussim~⨦~plustwo~⨧~pm~±~pointint~⨕~popf~𝕡~pr~≺~prE~⪳~prap~⪷~prcue~≼~pre~⪯~prec~≺~precapprox~⪷~preccurlyeq~≼~preceq~⪯~precnapprox~⪹~precneqq~⪵~precnsim~⋨~precsim~≾~primes~ℙ~prnE~⪵~prnap~⪹~prnsim~⋨~profalar~⌮~profline~⌒~profsurf~⌓~propto~∝~prsim~≾~prurel~⊰~pscr~𝓅~puncsp~ ~qfr~𝔮~qint~⨌~qopf~𝕢~qprime~⁗~qscr~𝓆~quaternions~ℍ~quatint~⨖~quest~?~questeq~≟~rAarr~⇛~rAtail~⤜~rBarr~⤏~rHar~⥤~race~∽̱~racute~ŕ~raemptyv~⦳~rangd~⦒~range~⦥~rangle~⟩~rarrap~⥵~rarrb~⇥~rarrbfs~⤠~rarrc~⤳~rarrfs~⤞~rarrhk~↪~rarrlp~↬~rarrpl~⥅~rarrsim~⥴~rarrtl~↣~rarrw~↝~ratail~⤚~ratio~∶~rationals~ℚ~rbarr~⤍~rbbrk~❳~rbrace~}~rbrack~]~rbrke~⦌~rbrksld~⦎~rbrkslu~⦐~rcaron~ř~rcedil~ŗ~rcub~}~rcy~р~rdca~⤷~rdldhar~⥩~rdquor~”~rdsh~↳~realine~ℛ~realpart~ℜ~reals~ℝ~rect~▭~rfisht~⥽~rfr~𝔯~rhard~⇁~rharu~⇀~rharul~⥬~rhov~ϱ~rightarrow~→~rightarrowtail~↣~rightharpoondown~⇁~rightharpoonup~⇀~rightleftarrows~⇄~rightleftharpoons~⇌~rightrightarrows~⇉~rightsquigarrow~↝~rightthreetimes~⋌~ring~˚~risingdotseq~≓~rlarr~⇄~rlhar~⇌~rmoust~⎱~rmoustache~⎱~rnmid~⫮~roang~⟭~roarr~⇾~robrk~⟧~ropar~⦆~ropf~𝕣~roplus~⨮~rotimes~⨵~rpar~)~rpargt~⦔~rppolint~⨒~rrarr~⇉~rscr~𝓇~rsh~↱~rsqb~]~rsquor~’~rthree~⋌~rtimes~⋊~rtri~▹~rtrie~⊵~rtrif~▸~rtriltri~⧎~ruluhar~⥨~rx~℞~sacute~ś~sc~≻~scE~⪴~scap~⪸~sccue~≽~sce~⪰~scedil~ş~scirc~ŝ~scnE~⪶~scnap~⪺~scnsim~⋩~scpolint~⨓~scsim~≿~scy~с~sdotb~⊡~sdote~⩦~seArr~⇘~searhk~⤥~searr~↘~searrow~↘~semi~;~seswar~⤩~setminus~∖~setmn~∖~sext~✶~sfr~𝔰~sfrown~⌢~sharp~♯~shchcy~щ~shcy~ш~shortmid~∣~shortparallel~∥~sigmav~ς~simdot~⩪~sime~≃~simeq~≃~simg~⪞~simgE~⪠~siml~⪝~simlE~⪟~simne~≆~simplus~⨤~simrarr~⥲~slarr~←~smallsetminus~∖~smashp~⨳~smeparsl~⧤~smid~∣~smile~⌣~smt~⪪~smte~⪬~smtes~⪬︀~softcy~ь~sol~/~solb~⧄~solbar~⌿~sopf~𝕤~spadesuit~♠~spar~∥~sqcap~⊓~sqcaps~⊓︀~sqcup~⊔~sqcups~⊔︀~sqsub~⊏~sqsube~⊑~sqsubset~⊏~sqsubseteq~⊑~sqsup~⊐~sqsupe~⊒~sqsupset~⊐~sqsupseteq~⊒~squ~□~square~□~squarf~▪~squf~▪~srarr~→~sscr~𝓈~ssetmn~∖~ssmile~⌣~sstarf~⋆~star~☆~starf~★~straightepsilon~ϵ~straightphi~ϕ~strns~¯~subE~⫅~subdot~⪽~subedot~⫃~submult~⫁~subnE~⫋~subne~⊊~subplus~⪿~subrarr~⥹~subset~⊂~subseteq~⊆~subseteqq~⫅~subsetneq~⊊~subsetneqq~⫋~subsim~⫇~subsub~⫕~subsup~⫓~succ~≻~succapprox~⪸~succcurlyeq~≽~succeq~⪰~succnapprox~⪺~succneqq~⪶~succnsim~⋩~succsim~≿~sung~♪~supE~⫆~supdot~⪾~supdsub~⫘~supedot~⫄~suphsol~⟉~suphsub~⫗~suplarr~⥻~supmult~⫂~supnE~⫌~supne~⊋~supplus~⫀~supset~⊃~supseteq~⊇~supseteqq~⫆~supsetneq~⊋~supsetneqq~⫌~supsim~⫈~supsub~⫔~supsup~⫖~swArr~⇙~swarhk~⤦~swarr~↙~swarrow~↙~swnwar~⤪~target~⌖~tbrk~⎴~tcaron~ť~tcedil~ţ~tcy~т~tdot~⃛~telrec~⌕~tfr~𝔱~therefore~∴~thetav~ϑ~thickapprox~≈~thicksim~∼~thkap~≈~thksim~∼~timesb~⊠~timesbar~⨱~timesd~⨰~tint~∭~toea~⤨~top~⊤~topbot~⌶~topcir~⫱~topf~𝕥~topfork~⫚~tosa~⤩~tprime~‴~triangle~▵~triangledown~▿~triangleleft~◃~trianglelefteq~⊴~triangleq~≜~triangleright~▹~trianglerighteq~⊵~tridot~◬~trie~≜~triminus~⨺~triplus~⨹~trisb~⧍~tritime~⨻~trpezium~⏢~tscr~𝓉~tscy~ц~tshcy~ћ~tstrok~ŧ~twixt~≬~twoheadleftarrow~↞~twoheadrightarrow~↠~uHar~⥣~ubrcy~ў~ubreve~ŭ~ucy~у~udarr~⇅~udblac~ű~udhar~⥮~ufisht~⥾~ufr~𝔲~uharl~↿~uharr~↾~uhblk~▀~ulcorn~⌜~ulcorner~⌜~ulcrop~⌏~ultri~◸~umacr~ū~uogon~ų~uopf~𝕦~uparrow~↑~updownarrow~↕~upharpoonleft~↿~upharpoonright~↾~uplus~⊎~upsi~υ~upuparrows~⇈~urcorn~⌝~urcorner~⌝~urcrop~⌎~uring~ů~urtri~◹~uscr~𝓊~utdot~⋰~utilde~ũ~utri~▵~utrif~▴~uuarr~⇈~uwangle~⦧~vArr~⇕~vBar~⫨~vBarv~⫩~vDash~⊨~vangrt~⦜~varepsilon~ϵ~varkappa~ϰ~varnothing~∅~varphi~ϕ~varpi~ϖ~varpropto~∝~varr~↕~varrho~ϱ~varsigma~ς~varsubsetneq~⊊︀~varsubsetneqq~⫋︀~varsupsetneq~⊋︀~varsupsetneqq~⫌︀~vartheta~ϑ~vartriangleleft~⊲~vartriangleright~⊳~vcy~в~vdash~⊢~vee~∨~veebar~⊻~veeeq~≚~vellip~⋮~verbar~|~vert~|~vfr~𝔳~vltri~⊲~vnsub~⊂⃒~vnsup~⊃⃒~vopf~𝕧~vprop~∝~vrtri~⊳~vscr~𝓋~vsubnE~⫋︀~vsubne~⊊︀~vsupnE~⫌︀~vsupne~⊋︀~vzigzag~⦚~wcirc~ŵ~wedbar~⩟~wedge~∧~wedgeq~≙~wfr~𝔴~wopf~𝕨~wp~℘~wr~≀~wreath~≀~wscr~𝓌~xcap~⋂~xcirc~◯~xcup~⋃~xdtri~▽~xfr~𝔵~xhArr~⟺~xharr~⟷~xlArr~⟸~xlarr~⟵~xmap~⟼~xnis~⋻~xodot~⨀~xopf~𝕩~xoplus~⨁~xotime~⨂~xrArr~⟹~xrarr~⟶~xscr~𝓍~xsqcup~⨆~xuplus~⨄~xutri~△~xvee~⋁~xwedge~⋀~yacy~я~ycirc~ŷ~ycy~ы~yfr~𝔶~yicy~ї~yopf~𝕪~yscr~𝓎~yucy~ю~zacute~ź~zcaron~ž~zcy~з~zdot~ż~zeetrf~ℨ~zfr~𝔷~zhcy~ж~zigrarr~⇝~zopf~𝕫~zscr~𝓏~~AMP~&~COPY~©~GT~>~LT~<~QUOT~"~REG~®',ge.html4);var ho={0:65533,128:8364,130:8218,131:402,132:8222,133:8230,134:8224,135:8225,136:710,137:8240,138:352,139:8249,140:338,142:381,145:8216,146:8217,147:8220,148:8221,149:8226,150:8211,151:8212,152:732,153:8482,154:353,155:8250,156:339,158:382,159:376},go=String.fromCodePoint||function(t){return String.fromCharCode(Math.floor((t-65536)/1024)+55296,(t-65536)%1024+56320)},fe=function(){return fe=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},fe.apply(this,arguments)},fo=fe(fe({},ge),{all:ge.html5}),po={scope:"body",level:"all"},ft=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g,pt=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g,Ln={xml:{strict:ft,attribute:pt,body:gt.xml},html4:{strict:ft,attribute:pt,body:gt.html4},html5:{strict:ft,attribute:pt,body:gt.html5}},mo=fe(fe({},Ln),{all:Ln.html5}),xr=String.fromCharCode,yo=xr(65533);function bo(t,e,n,r){var i=t,s=t[t.length-1];if(n&&s==="=")i=t;else if(r&&s!==";")i=t;else{var o=e[t];if(o)i=o;else if(t[0]==="&"&&t[1]==="#"){var a=t[2],c=a=="x"||a=="X"?parseInt(t.substr(3),16):parseInt(t.substr(2));i=c>=1114111?yo:c>65535?go(c):xr(ho[c]||c)}}return i}function qn(t,e){var n=e===void 0?po:e,r=n.level,i=r===void 0?"all":r,s=n.scope,o=s===void 0?i==="xml"?"strict":"body":s;if(!t)return"";var a=mo[i][o],c=fo[i].entities,l=o==="attribute",d=o==="strict";return t.replace(a,function(u){return bo(u,c,l,d)})}var vo={strictlyTwoElementsInRangeArrays:!1,progressFn:null};function Ye(t,e){if(!Array.isArray(t)||!t.length)return t;let n={...vo,...e},r,i;if(n.strictlyTwoElementsInRangeArrays&&!t.every((a,c)=>!Array.isArray(a)||a.length!==2?(r=c,i=a.length,!1):!0))throw new TypeError(`ranges-sort: [THROW_ID_03] The first argument should be an array and must consist of arrays which are natural number indexes representing TWO string index ranges. However, ${r}th range (${JSON.stringify(t[r],null,4)}) has not two but ${i} elements!`);if(!t.every((a,c)=>!Array.isArray(a)||!Number.isInteger(a[0])||a[0]<0||!Number.isInteger(a[1])||a[1]<0?(r=c,!1):!0))throw new TypeError(`ranges-sort: [THROW_ID_04] The first argument should be an array and must consist of arrays which are natural number indexes representing string index ranges. However, ${r}th range (${JSON.stringify(t[r],null,4)}) does not consist of only natural numbers!`);let s=t.length**2,o=0;return Array.from(t).sort((a,c)=>(n.progressFn&&(o+=1,n.progressFn(Math.floor(o*100/s))),a[0]===c[0]?a[1]<c[1]?-1:a[1]>c[1]?1:0:a[0]<c[0]?-1:1))}var Dn={mergeType:1,progressFn:null,joinRangesThatTouchEdges:!0};function wo(t,e){function n(l){return!!l&&typeof l=="object"&&!Array.isArray(l)}if(!Array.isArray(t)||!t.length)return null;let r;if(e)if(n(e)){if(r={...Dn,...e},r.progressFn&&n(r.progressFn)&&!Object.keys(r.progressFn).length)r.progressFn=null;else if(r.progressFn&&typeof r.progressFn!="function")throw new Error(`ranges-merge: [THROW_ID_01] opts.progressFn must be a function! It was given of a type: "${typeof r.progressFn}", equal to ${JSON.stringify(r.progressFn,null,4)}`);if(![1,2,"1","2"].includes(r.mergeType))throw new Error(`ranges-merge: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof r.mergeType}", equal to ${JSON.stringify(r.mergeType,null,4)}`);if(typeof r.joinRangesThatTouchEdges!="boolean")throw new Error(`ranges-merge: [THROW_ID_04] opts.joinRangesThatTouchEdges was customised to a wrong thing! It was given of a type: "${typeof r.joinRangesThatTouchEdges}", equal to ${JSON.stringify(r.joinRangesThatTouchEdges,null,4)}`)}else throw new Error(`emlint: [THROW_ID_03] the second input argument must be a plain object. It was given as:
|
|
2
|
-
${JSON.stringify(e,null,4)} (type ${typeof e})`);else
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=t=>{if(!t)return["",void 0];const e=t.replace(/_/g,"-");try{const r=new Intl.Locale(e);return[r.language.toLowerCase(),r.region?.toUpperCase()]}catch{const r=e.split("-");return[r[0].toLowerCase(),r[1]?.toUpperCase()]}},z={ar:{defaultRegion:"SA",availableRegions:["001","AE","AS","BH","DZ","EG","IQ","JO","KW","LB","LY","MA","OM","QA","SA","SY","TN","YE"],testUtterance:"مرحبًا، اسمي {name} وأنا صوت عربي."},bg:{defaultRegion:"BG",availableRegions:["BG"],testUtterance:"Здравейте, казвам се {name} и съм български глас."},bho:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, हमार नाम {name} ह आ हम भोजपुरी आवाज हईं"},bn:{defaultRegion:"IN",availableRegions:["BD","IN"],testUtterance:"হ্যালো, আমার নাম {name} এবং আমি একজন বাংলা ভয়েস।"},ca:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Hola, em dic {name} i sóc una veu catalana"},cmn:{defaultRegion:"CN",availableRegions:["CN","CTW","TW"],testUtterance:"你好,我的名字是 {name},我是普通话配音。"},cs:{defaultRegion:"CZ",availableRegions:["CZ"],testUtterance:"Dobrý den, jmenuji se {name} a jsem český hlas."},da:{defaultRegion:"DK",availableRegions:["DK"],testUtterance:"Hej, mit navn er {name} og jeg er en dansk stemme."},de:{defaultRegion:"DE",availableRegions:["AT","CH","DE"],testUtterance:"Hallo, mein Name ist {name} und ich bin eine deutsche Stimme."},el:{defaultRegion:"GR",availableRegions:["GR"],testUtterance:"Γεια σας, με λένε {name} και είμαι ελληνική φωνή."},en:{defaultRegion:"US",availableRegions:["AU","CA","GB","HK","IE","IN","KE","NG","NZ","PH","SG","TZ","US","ZA"],testUtterance:"Hello, my name is {name} and I am an English voice."},es:{defaultRegion:"ES",availableRegions:["AR","BO","CL","CO","CR","CU","DO","EC","ES","GQ","GT","HN","MX","NI","PA","PE","PR","PY","SV","US","UY","VE"],testUtterance:"Hola, mi nombre es {name} y soy una voz española."},eu:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Kaixo, nire izena {name} da eta euskal ahotsa naiz."},fa:{defaultRegion:"IR",availableRegions:["IR"],testUtterance:"سلام اسم من {name} و صدای فارسی هستم"},fi:{defaultRegion:"FI",availableRegions:["FI"],testUtterance:"Hei, nimeni on {name} ja olen suomalainen ääni."},fr:{defaultRegion:"FR",availableRegions:["BE","CA","CH","FR"],testUtterance:"Bonjour, mon nom est {name} et je suis une voix française."},gl:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Ola, chámome {name} e son unha voz galega."},he:{defaultRegion:"IL",availableRegions:["IL"],testUtterance:"שלום, שמי {name} ואני קול עברי."},hi:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, मेरा नाम {name} है और मैं एक हिंदी आवाज़ हूँ।"},hr:{defaultRegion:"HR",availableRegions:["HR"],testUtterance:"Pozdrav, ja sam {name} i hrvatski sam glas."},hu:{defaultRegion:"HU",availableRegions:["HU"],testUtterance:"Helló, a nevem {name} és magyar hangú vagyok."},id:{defaultRegion:"ID",availableRegions:["ID"],testUtterance:"Halo, nama saya {name} dan saya suara Indonesia."},it:{defaultRegion:"IT",availableRegions:["IT"],testUtterance:"Ciao, mi chiamo {name} e sono una voce italiana."},ja:{defaultRegion:"JP",availableRegions:["JP"],testUtterance:"こんにちは。私の名前は{name}で、日本語の声を担当しています。"},kk:{defaultRegion:"KZ",availableRegions:["KZ"],testUtterance:"Sälemetsiz be, meniñ atım {name} jäne men qazaq dawısımın."},kn:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"ಹಲೋ, ನನ್ನ ಹೆಸರು {name} ಮತ್ತು ನಾನು ಕನ್ನಡ ಧ್ವನಿ."},ko:{defaultRegion:"KR",availableRegions:["KR"],testUtterance:"안녕하세요, 저는 {name}이고 한국어 음성입니다."},mr:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, माझे नाव {name} आहे आणि मी एक मराठी आवाज आहे."},ms:{defaultRegion:"MY",availableRegions:["MY"],testUtterance:"Hello, nama saya {name} dan saya suara Melayu."},nb:{defaultRegion:"NO",availableRegions:["NO"],testUtterance:"Hei, jeg heter {name} og er en norsk stemme."},nl:{defaultRegion:"NL",availableRegions:["BE","NL"],testUtterance:"Hallo, mijn naam is {name} en ik ben een Nederlandse stem."},pl:{defaultRegion:"PL",availableRegions:["PL"],testUtterance:"Cześć, nazywam się {name} i mam polski głos."},pt:{defaultRegion:"BR",availableRegions:["BR","PT"],testUtterance:"Olá, o meu nome é {name} e sou uma voz portuguesa."},ro:{defaultRegion:"RO",availableRegions:["RO"],testUtterance:"Buna ziua, ma numesc {name} si sunt o voce romaneasca."},ru:{defaultRegion:"RU",availableRegions:["RU"],testUtterance:"Здравствуйте, меня зовут {name} и я русский голос."},sk:{defaultRegion:"SK",availableRegions:["SK"],testUtterance:"Dobrý deň, volám sa {name} a som slovenský hlas."},sl:{defaultRegion:"SI",availableRegions:["SI"],testUtterance:"Pozdravljeni, moje ime je {name} in sem slovenski glas."},sv:{defaultRegion:"SE",availableRegions:["SE"],testUtterance:"Hej, jag heter {name} och jag är en svensk röst."},ta:{defaultRegion:"IN",availableRegions:["IN","LK","MY","SG"],testUtterance:"வணக்கம், என் பெயர் {name} மற்றும் நான் ஒரு தமிழ் குரல்"},te:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"హలో, నా పేరు {name} మరియు నేను తెలుగు వాణిని."},th:{defaultRegion:"TH",availableRegions:["TH"],testUtterance:"สวัสดีค่ะ ฉันชื่อ {name} และฉันเป็นคนมีเสียงภาษาไทย"},tr:{defaultRegion:"TR",availableRegions:["TR"],testUtterance:"Merhaba, adım {name} ve Türk sesiyim."},uk:{defaultRegion:"UA",availableRegions:["UA"],testUtterance:"Здравствуйте, меня зовут {name} и я украинский голос."},vi:{defaultRegion:"VN",availableRegions:["VN"],testUtterance:"Xin chào, tôi tên là {name} và tôi là giọng nói tiếng Việt."},wuu:{defaultRegion:"CN",availableRegions:["CN"],testUtterance:"你好,我的名字是 {name},我是吴语配音。"},yue:{defaultRegion:"HK",availableRegions:["HK"],testUtterance:"你好,我叫 {name},係越中文聲。"}},mt=new Map,zi=Object.assign({"../../json/ar.json":()=>Promise.resolve().then(()=>require("./ar-BYWkyZgW.cjs")),"../../json/bg.json":()=>Promise.resolve().then(()=>require("./bg-D7xe9YTl.cjs")),"../../json/bho.json":()=>Promise.resolve().then(()=>require("./bho-UB6aO8oz.cjs")),"../../json/bn.json":()=>Promise.resolve().then(()=>require("./bn-boRZ2pl5.cjs")),"../../json/ca.json":()=>Promise.resolve().then(()=>require("./ca-DkC8kSJ8.cjs")),"../../json/cmn.json":()=>Promise.resolve().then(()=>require("./cmn-BsNLjyA4.cjs")),"../../json/cs.json":()=>Promise.resolve().then(()=>require("./cs-p05r08p7.cjs")),"../../json/da.json":()=>Promise.resolve().then(()=>require("./da-crefCup9.cjs")),"../../json/de.json":()=>Promise.resolve().then(()=>require("./de-xoW-RuhZ.cjs")),"../../json/el.json":()=>Promise.resolve().then(()=>require("./el-C025sTug.cjs")),"../../json/en.json":()=>Promise.resolve().then(()=>require("./en-CbfmLXbR.cjs")),"../../json/es.json":()=>Promise.resolve().then(()=>require("./es-DW7IPf8I.cjs")),"../../json/eu.json":()=>Promise.resolve().then(()=>require("./eu-uq15ZgwW.cjs")),"../../json/fa.json":()=>Promise.resolve().then(()=>require("./fa-CHOnwiFr.cjs")),"../../json/fi.json":()=>Promise.resolve().then(()=>require("./fi-Bxlno6Zi.cjs")),"../../json/fr.json":()=>Promise.resolve().then(()=>require("./fr-yAth5-FC.cjs")),"../../json/gl.json":()=>Promise.resolve().then(()=>require("./gl-BEgzCAO0.cjs")),"../../json/he.json":()=>Promise.resolve().then(()=>require("./he-B-CTHJPL.cjs")),"../../json/hi.json":()=>Promise.resolve().then(()=>require("./hi-C0yUjV1-.cjs")),"../../json/hr.json":()=>Promise.resolve().then(()=>require("./hr-CZvFOcdo.cjs")),"../../json/hu.json":()=>Promise.resolve().then(()=>require("./hu-_2PInItj.cjs")),"../../json/id.json":()=>Promise.resolve().then(()=>require("./id-BROcb7-t.cjs")),"../../json/it.json":()=>Promise.resolve().then(()=>require("./it-Bmc8Ycff.cjs")),"../../json/ja.json":()=>Promise.resolve().then(()=>require("./ja-B8t6WOeg.cjs")),"../../json/kk.json":()=>Promise.resolve().then(()=>require("./kk-DskO1CW8.cjs")),"../../json/kn.json":()=>Promise.resolve().then(()=>require("./kn-Cy3NH6na.cjs")),"../../json/ko.json":()=>Promise.resolve().then(()=>require("./ko-CZdQzppZ.cjs")),"../../json/mr.json":()=>Promise.resolve().then(()=>require("./mr-9hGqBYlV.cjs")),"../../json/ms.json":()=>Promise.resolve().then(()=>require("./ms-DzpBxNFZ.cjs")),"../../json/nb.json":()=>Promise.resolve().then(()=>require("./nb-BQfw9EEH.cjs")),"../../json/nl.json":()=>Promise.resolve().then(()=>require("./nl-CyM0R4Gr.cjs")),"../../json/pl.json":()=>Promise.resolve().then(()=>require("./pl-Da8XOMa1.cjs")),"../../json/pt.json":()=>Promise.resolve().then(()=>require("./pt-tubyvYaM.cjs")),"../../json/ro.json":()=>Promise.resolve().then(()=>require("./ro-C-rXDfuM.cjs")),"../../json/ru.json":()=>Promise.resolve().then(()=>require("./ru-DJocRaDd.cjs")),"../../json/sk.json":()=>Promise.resolve().then(()=>require("./sk-BvpojIXp.cjs")),"../../json/sl.json":()=>Promise.resolve().then(()=>require("./sl-D0X3JKvQ.cjs")),"../../json/sv.json":()=>Promise.resolve().then(()=>require("./sv-4lEgrHda.cjs")),"../../json/ta.json":()=>Promise.resolve().then(()=>require("./ta-CyeVPdIs.cjs")),"../../json/te.json":()=>Promise.resolve().then(()=>require("./te-DqWIZZxL.cjs")),"../../json/th.json":()=>Promise.resolve().then(()=>require("./th-BcoSVZAp.cjs")),"../../json/tr.json":()=>Promise.resolve().then(()=>require("./tr-BuafNhfw.cjs")),"../../json/uk.json":()=>Promise.resolve().then(()=>require("./uk-DkXNxnD9.cjs")),"../../json/vi.json":()=>Promise.resolve().then(()=>require("./vi-Ct2avSE6.cjs")),"../../json/wuu.json":()=>Promise.resolve().then(()=>require("./wuu-DnwGQ6c-.cjs")),"../../json/yue.json":()=>Promise.resolve().then(()=>require("./yue-j9Y48sR-.cjs"))});async function ji(t){try{const e=t.split("-")[0],r=zi[`../../json/${e}.json`];if(!r)throw new Error(`No voice data found for language: ${t}`);const i=(await r()).default;return{...i,voices:i.voices.map(Hi)}}catch(e){return console.warn(`Failed to load voice data for ${t}:`,e),{language:t,defaultRegion:"",testUtterance:"",voices:[]}}}function Or(t){return mt.has(t)||mt.set(t,ji(t)),mt.get(t)}const Mi=["veryLow","low","normal","high","veryHigh"],Fi=["android","apple"],Hi=t=>({...t,quality:t.quality?.filter(e=>Mi.includes(e)),localizedName:t.localizedName&&Fi.includes(t.localizedName)?t.localizedName:void 0}),de={cmn:"cmn","cmn-CN":"cmn-CN","cmn-TW":"cmn-TW",zh:"cmn","zh-CN":"cmn-CN","zh-TW":"cmn-TW",yue:"yue","yue-HK":"yue-HK","zh-HK":"yue-HK",wuu:"wuu","wuu-CN":"wuu-CN"},$=t=>{if(!t)return"";let e=t.toLowerCase().replace(/_/g,"-");if(/\w{2,3}-\w{2,3}/.test(e)){const[r,n]=e.split("-");e=`${r.toLowerCase()}-${n.toUpperCase()}`}return de[e]||e},_t=async t=>{if(!t)return[];try{const e=$(t);try{const n=await Or(e);if(n?.voices?.length)return n.voices}catch(n){console.warn(`Failed to load voices for ${e}:`,n)}const[r]=L(e);if(r!==e)try{const n=await Or(r);if(n?.voices?.length)return n.voices}catch(n){console.warn(`Failed to load voices for base language ${r}:`,n)}return[]}catch(e){return console.error(`Error in getVoices for ${t}:`,e),[]}},Dt=(t,e)=>{try{return new Intl.DisplayNames(e?[e]:[],{type:"language",languageDisplay:"standard"}).of(t)||t.toUpperCase()}catch{return t.toUpperCase()}},Rr=t=>{if(!t)return"";try{const e=$(t),r=z[e];if(r?.testUtterance)return r.testUtterance;if(e in de){const i=de[e];if(i&&z[i]?.testUtterance)return z[i].testUtterance}const[n]=L(e);return n!==e&&z[n]?.testUtterance?z[n].testUtterance:""}catch(e){return console.error(`Error in getTestUtterance for ${t}:`,e),""}},ct=t=>{if(!t)return"";try{const e=$(t),r=z[e];if(r?.defaultRegion)return`${e}-${r.defaultRegion}`;if(e in de){const i=de[e];if(i){const s=z[i];if(s?.defaultRegion)return`${i}-${s.defaultRegion}`}}const[n]=L(e);if(n!==e){const i=z[n];if(i?.defaultRegion)return`${n}-${i.defaultRegion}`}return""}catch(e){return console.error(`Failed to get default region for ${t}:`,e),""}},ut=t=>{if(!t?.length)return[];const e=new Set,r=new Map,n=new Map;for(const[i,s]of t.entries()){if(!s)continue;const o=$(s),[a,c]=L(o);c&&(e.add(c),n.has(c)||n.set(c,i)),r.has(a)||r.set(a,new Set),c&&r.get(a).add(c)}return Array.from(r.entries()).map(([i,s])=>{const o=new Set(z[i]?.availableRegions||[]),a=Array.from(s),c=Array.from(e).filter(d=>o.has(d)&&!a.includes(d)),l=Array.from(new Set([...a,...c])).sort((d,u)=>{const g=n.get(d)??Number.MAX_SAFE_INTEGER,f=n.get(u)??Number.MAX_SAFE_INTEGER;return g-f});if(l.length===0){const d=ct(i),[,u]=L(d);u&&l.push(u)}return{baseLang:i,regions:l}})},ge=async t=>{const e=new Map;for(const n of t){if(n.source!=="json")continue;const[i]=L(n.language);e.has(i)||e.set(i,[]),e.get(i).push(n)}const r=new Map;for(const[n,i]of e.entries()){const s=new Map,o=await _t(n),a=new Map;o.forEach((c,l)=>{a.set(c.name.toLowerCase(),l),c.altNames?.forEach(d=>{a.set(d.toLowerCase(),l)})});for(const c of i){const l=c.name.toLowerCase(),d=a.get(l);d!==void 0&&s.set(c.name,d)}s.size>0&&r.set(n,s)}return r},Wi={veryLow:1,low:2,normal:3,high:4,veryHigh:5},Ye=t=>t?Wi[t]??0:0,Q=(t,e,r,n)=>{const i=Ye(t.quality),s=Ye(e.quality);if(r&&n&&t.source==="json"&&e.source==="json"){const o=r.get(n);if(o){const a=o.get(t.name),c=o.get(e.name);if(a!==void 0&&c!==void 0)return a-c}}return s!==i?s-i:t.name.localeCompare(e.name)},ht=(t,e)=>{const r=new Map(e.map(s=>[s.baseLang,s])),n=new Map,i=[];for(const s of t){const[o]=L(s.language);r.get(o)?(n.has(o)||n.set(o,[]),n.get(o).push(s)):i.push(s)}return{voicesByLang:n,otherLangVoices:i}},bn=(t,e,r,n)=>{const[,i]=L(t.language),[,s]=L(e.language),o=i&&r.regions.includes(i),a=s&&r.regions.includes(s);if(o&&a){const g=r.regions.indexOf(i),f=r.regions.indexOf(s);return g===f?Q(t,e,n,r.baseLang):g-f}if(o)return-1;if(a)return 1;const c=ct(r.baseLang),[,l]=L(c),d=!!l&&i===l,u=!!l&&s===l;if(d&&!u)return-1;if(!d&&u)return 1;if(i&&s){const g=i.localeCompare(s);return g!==0?g:Q(t,e,n,r.baseLang)}return i?-1:s?1:Q(t,e,n,r.baseLang)},Gi=async(t,e,r)=>{const n=r??await ge(t);t.sort((i,s)=>bn(i,s,e,n))},wn=(t,e,r)=>{const[n]=L(t.language),[i]=L(e.language),s=Dt(n).toLowerCase(),o=Dt(i).toLowerCase(),a=s.localeCompare(o);if(a!==0)return a;if(n===i){const c=ct(n),[,l]=L(t.language),[,d]=L(e.language),u=c&&l===c.split("-")[1],g=c&&d===c.split("-")[1];if(u&&!g)return-1;if(!u&&g)return 1;if(l&&d){const f=l.localeCompare(d);if(f!==0)return f}return l&&!d?-1:!l&&d?1:Q(t,e,r,n)}return Q(t,e,r,n)},$t=async(t,e)=>{const r=e??await ge(t);t.sort((n,i)=>wn(n,i,r))},Ki=async(t,e)=>{if(!e?.length)return[];const r=ut(t||[]),{voicesByLang:n,otherLangVoices:i}=ht(e,r),s=await ge(e),o=[];for(const a of r){const c=n.get(a.baseLang);c&&(await Gi(c,a,s),o.push(...c))}return await $t(i,s),o.push(...i),o},Ji=async(t,e)=>{if(!e.length)return null;const[r]=ut([t]),{voicesByLang:n,otherLangVoices:i}=ht(e,[r]),s=n.get(r.baseLang),o=s?.length?s:i,a=await ge(e),c=s?.length?(l,d)=>bn(l,d,r,a):(l,d)=>wn(l,d,a);return o.reduce((l,d)=>c(d,l)<0?d:l)},Qi=[{name:"Albert",nativeID:["com.apple.speech.synthesis.voice.Albert"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bad News",nativeID:["com.apple.speech.synthesis.voice.BadNews"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Mauvaises nouvelles","Malas noticias","Brutte notizie"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bahh",nativeID:["com.apple.speech.synthesis.voice.Bahh"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bells",nativeID:["com.apple.speech.synthesis.voice.Bells"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Cloches","Campanas","Campane"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Boing",nativeID:["com.apple.speech.synthesis.voice.Boing"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bubbles",nativeID:["com.apple.speech.synthesis.voice.Bubbles"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bulles","Burbujas","Bollicine"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Cellos",nativeID:["com.apple.speech.synthesis.voice.Cellos"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Violoncelles","Violonchelos","Violoncelli"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Good News",nativeID:["com.apple.speech.synthesis.voice.GoodNews"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bonnes nouvelles","Buenas noticias","Buone notizie"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Jester",nativeID:["com.apple.speech.synthesis.voice.Hysterical"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bouffon","Bufón","Giullare"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Organ",nativeID:["com.apple.speech.synthesis.voice.Organ"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Orgue","Órgano","Organo"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Superstar",nativeID:["com.apple.speech.synthesis.voice.Princess"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Superestrella"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Trinoids",nativeID:["com.apple.speech.synthesis.voice.Trinoids"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Trinoïdes"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Whisper",nativeID:["com.apple.speech.synthesis.voice.Whisper"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Murmure","Susurro","Sussurro"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Wobble",nativeID:["com.apple.speech.synthesis.voice.Deranged"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Zarvox",nativeID:["com.apple.speech.synthesis.voice.Zarvox"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0}],Xi={voices:Qi},Zi=[{name:"Eddy",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Flo",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Grandma",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Grandpa",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Jacques",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Reed",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Rocko",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Sandy",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Shelley",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Fred",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Junior",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Kathy",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Ralph",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"eSpeak Arabic",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ar",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Bulgarian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"bg",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Bengali",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"bn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Catalan",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ca",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Chinese (Mandarin, latin as English)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"cmn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Czech",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"cs",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Danish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"da",os:["ChromeOS"],preloaded:!0},{name:"eSpeak German",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"de",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Greek",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"el",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Spanish (Spain)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"es",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Estonian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"et",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Finnish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"fi",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Gujarati",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"gu",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Croatian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"hr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Hungarian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"hu",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Indonesian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"id",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Italian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"it",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Kannada",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"kn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Korean",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ko",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Lithuanian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"lt",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Latvian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"lv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Malayalm",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ml",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Marathi",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"mr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Malay",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ms",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Norwegian Bokmål",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"nb",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Polish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"pl",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Portuguese (Brazil)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"pt-br",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Romanian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ro",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Russian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ru",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Slovak",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sk",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Slovenian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sl",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Serbian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Swedish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Swahili",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sw",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Tamil",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ta",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Telugu",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"te",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Turkish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"tr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Vietnamese (Northern)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"vi",os:["ChromeOS"],preloaded:!0}],Yi={voices:Zi},es=Xi,ts=Yi,Ut=(t,e)=>es.voices.some(r=>t.includes(r.name)||e&&r.nativeID?.some(n=>e.includes(n))||r.altNames?.some(n=>t.includes(n))),Bt=(t,e)=>ts.voices.some(r=>t.includes(r.name))||e==="veryLow",Pr=t=>t?.length?t.filter(e=>!(e.isNovelty||Ut(e.name,e.voiceURI))):[],Ir=t=>t?.length?t.filter(e=>!Bt(e.name,e.quality)):[],rs={ar:{normal:"محسن",high:"استثنائي"},ca:{normal:"millorada",high:"prèmium"},"cmn-CN":{normal:"优化音质",high:"高音质"},"cmn-TW":{normal:"增強音質",high:"高音質"},cs:{normal:"vylepšená verze",high:"prémiový"},da:{normal:"forbedret",high:"høj kvalitet"},de:{normal:"erweitert",high:"premium"},el:{normal:"βελτιωμένη",high:"υψηλής ποιότητας"},en:{normal:"Enhanced",high:"Premium"},es:{normal:"mejorada",high:"premium"},fi:{normal:"parannettu",high:"korkealaatuinen"},fr:{normal:"premium",high:"de qualité"},he:{normal:"משופר",high:"פרימיום"},hi:{normal:"बेहतर",high:"प्रीमियम"},hr:{normal:"poboljšani",high:"vrhunski"},hu:{normal:"továbbfejlesztett",high:"prémium"},id:{normal:"Ditingkatkan",high:"Premium"},it:{normal:"ottimizzata",high:"premium"},ja:{normal:"拡張",high:"プレミアム"},ko:{normal:"고품질",high:"프리미엄"},ms:{normal:"Dipertingkat",high:"Premium"},nb:{normal:"forbedret",high:"premium"},nl:{normal:"verbeterd",high:"premium"},pl:{normal:"rozszerzony",high:"premium"},pt:{normal:"melhorada",high:"premium"},ro:{normal:"îmbunătățită",high:"premium"},ru:{normal:"улучшенный",high:"высшее качество"},sk:{normal:"vylepšený",high:"prémiový"},sl:{normal:"izboljšano",high:"prvovrsten"},sv:{normal:"förbättrad",high:"premium"},th:{normal:"คุณภาพสูง",high:"คุณภาพสูง"},tr:{normal:"Geliştirilmiş",high:"Yüksek Kaliteli"},uk:{normal:"вдосконалений",high:"високої якості"},vi:{normal:"Nâng cao",high:"Cao cấp"}},ns={quality:rs},Vt={apple:ns.quality},is=(t,e,r)=>{if(!t)return;const n=Array.isArray(r)?r:r?[r]:[];for(const i of n)if(i&&Vt[i]){const s=Vt[i],o=L(e)[0],a=s[e]||s[o];if(a){const c=t.toLowerCase(),{normal:l,high:d}=a;if(d&&c.includes(d.toLowerCase()))return"high";if(l&&c.includes(l.toLowerCase()))return"normal"}}},ss=(t,e)=>{const r=Vt[e];if(r)for(const[n,{high:i,normal:s}]of Object.entries(r)){const o=i&&t.some(c=>c.includes(i)),a=s&&t.some(c=>c.includes(s));if(o&&a)return n}},as={low:{values:["super-compact","compact"],quality:"low"},normal:{values:["enhanced"],quality:"normal"},high:{values:["premium"],quality:"high"}},Nr=t=>{if(!t)return;const r=t.toLowerCase().split(/[._-]/);for(const n of Object.values(as))if(n.values.some(i=>r.includes(i)))return n.quality};function os(t,e){if(t.name===t.originalName)return t;if(e.name===e.originalName)return e;const r=[t.originalName,...t.altNames||[]],n=[e.originalName,...e.altNames||[]],i=r.findIndex(o=>n.includes(o)),s=n.findIndex(o=>r.includes(o));return i===-1&&s===-1||i!==-1&&(s===-1||i<=s)?t:e}function ls(t,e){if(!t.altNames&&!e.altNames)return!1;const r=t.originalName,n=e.originalName,i=t.altNames||[],s=e.altNames||[];return s.includes(r)||i.includes(n)?!0:i.filter(a=>s.includes(a)).length>0}class P{static instance;static initializationPromise=null;systemLocale;voices=[];browserVoices=[];isInitialized=!1;scopedLanguages=null;broadenPromises=new Map;constructor(){if(typeof window>"u"||!window.speechSynthesis)throw new Error("Web Speech API is not available in this environment");this.systemLocale=navigator.languages?.[0]?.split("-")[0]||"en"}static async initialize(e){if(P.instance?.isInitialized){const r=P.instance;return e?.languages&&e.languages.length>0&&await r.broadenLanguages(e.languages),r}return P.initializationPromise||(P.initializationPromise=(async()=>{try{const r=new P;P.instance=r,r.browserVoices=await r.getBrowserVoices(e?.maxTimeout,e?.interval),r.updateSystemLocale(r.browserVoices);let n=r.browserVoices;return e?.languages&&e.languages.length>0?(n=r.filterBrowserVoicesByLanguages(r.browserVoices,e.languages),r.scopedLanguages=P.toBaseLangSet(e.languages)):r.scopedLanguages=null,r.voices=await r.parseToReadiumSpeechVoices(n),r.isInitialized=!0,r}catch(r){throw P.initializationPromise=null,console.error("Failed to initialize WebSpeechVoiceManager:",r),r}})()),P.initializationPromise}filterBrowserVoicesByLanguages(e,r){if(!r?.length)return e;const n=P.toBaseLangSet(r);return e.filter(i=>{if(!i?.lang)return!1;const s=$(i.lang),[o]=P.extractLangRegionFromBCP47(s);return n.has(o)})}static toBaseLangSet(e){return new Set(e.map(r=>{const n=$(r),[i]=P.extractLangRegionFromBCP47(n);return i}))}async broadenLanguages(e){if(this.scopedLanguages===null)return;const n=[...P.toBaseLangSet(e)].filter(a=>!this.scopedLanguages.has(a));if(n.length===0)return;const i=n.filter(a=>this.broadenPromises.has(a)),s=n.filter(a=>!this.broadenPromises.has(a));let o;s.length>0&&(o=(async()=>{const a=this.filterBrowserVoicesByLanguages(this.browserVoices,s),c=await this.parseToReadiumSpeechVoices(a);this.voices=[...this.voices,...c],s.forEach(l=>this.scopedLanguages.add(l)),s.forEach(l=>this.broadenPromises.delete(l))})(),s.forEach(a=>this.broadenPromises.set(a,o))),await Promise.all([...o?[o]:[],...i.map(a=>this.broadenPromises.get(a))])}static extractLangRegionFromBCP47(e){return L(e)}cleanVoiceName(e){return e?e.replace(/\s*\([^)]*\)/g,"").replace(/[^\p{L}\p{N}\s-]/gu,"").replace(/\s+/g," ").trim():""}normalizeVoiceName(e){return this.cleanVoiceName(e.toLowerCase())}countVoiceDuplicates(e){const r=new Map;for(const n of e){if(!n?.name||!n?.lang)continue;const i=`${n.lang.toLowerCase()}_${this.normalizeVoiceName(n.name)}`;r.set(i,(r.get(i)||0)+1)}return r}updateSystemLocale(e){if(!e?.length)return;const r=e.map(i=>i.name),n=ss(r,"apple");n&&(this.systemLocale=n)}inferVoiceQuality(e,r,n){const i=e.voiceURI?Nr(e.voiceURI):void 0;if(i)return i;if(r?.nativeID&&Array.isArray(r.nativeID))for(const s of r.nativeID){const o=Nr(s);if(o)return o}if(r?.localizedName&&e.voiceURI&&e.lang){const s=is(e.voiceURI,this.systemLocale,r.localizedName);if(s)return s}if(r?.quality&&r.quality.length>0){const s=Math.min(n-1,r.quality.length-1),o=r.quality[s];if(o)return o}return null}findMatchingJsonVoice(e,r){return e.find(n=>this.normalizeVoiceName(n.name)===r||n.altNames?.some(i=>this.normalizeVoiceName(i)===r))}removeDuplicates(e){const r=new Map;for(const n of e){const i=`${n.language.toLowerCase()}_${this.normalizeVoiceName(n.name)}`,s=r.get(i);if(!s)r.set(i,n);else if(ls(n,s)){const o=os(n,s);r.set(i,o)}else{const o=Ye(s.quality);Ye(n.quality)>=o&&r.set(i,n)}}return Array.from(r.values())}getTestUtterance(e){if(!e)return"";const r=Rr(e);if(r)return r;const[n]=P.extractLangRegionFromBCP47(e);if(n&&n!==e){const i=Rr(n);if(i)return i}return""}getVoices(e={}){if(!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");return this.filterVoices(e,[...this.voices])}getLanguages(e,r,n){if(!n&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const i=n??this.voices,s=r?this.filterVoices(r,i):i,o=[],a=new Set;for(const c of s){const d=$(c.language).split("-")[0];if(!a.has(d)){const u=Dt(d,e),g=s.filter(f=>$(f.language).split("-")[0]===d).length;o.push({code:d,label:u,count:g}),a.add(d)}}return n?o:o.sort((c,l)=>c.label.localeCompare(l.label))}getRegions(e,r,n){if(!n&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const i=n??this.voices,s=r?this.filterVoices(r,i):i,o=[],a=new Set,c=new Map;for(const l of s){const[,d]=P.extractLangRegionFromBCP47(l.language);d&&c.set(d,(c.get(d)||0)+1)}for(const l of s){const[,d]=P.extractLangRegionFromBCP47(l.language);if(d&&!a.has(d)){let u=l.language;try{const g=e||navigator.language;u=new Intl.DisplayNames([g],{type:"region"}).of(d)||l.language}catch(g){console.warn(`Failed to get display name for region ${d}`,g)}o.push({code:d,label:u,count:c.get(d)||0}),a.add(d)}}return n?o:o.sort((l,d)=>l.label.localeCompare(d.label))}async getDefaultVoice(e,r){if(!e)return null;const n=Array.isArray(e)?e:[e];let i=r||this.getVoices({languages:n});return i.length?(i=await this.sortVoicesByRegions(n,i),i[0]):null}getBrowserVoices(e=1e4,r=10){const n=()=>window.speechSynthesis?.getVoices()||[];if(!window.speechSynthesis)return Promise.resolve([]);const i=n();return Array.isArray(i)&&i.length?Promise.resolve(i):new Promise((s,o)=>{let a=Math.floor(e/r),c=!1;const l=()=>{if(c)return;c=!0;const d=()=>{if(a<1)return s([]);--a;const u=n();if(Array.isArray(u)&&u.length)return s(u);setTimeout(d,r)};setTimeout(d,r)};window.speechSynthesis.onvoiceschanged!==void 0?window.speechSynthesis.onvoiceschanged=()=>{const d=n();Array.isArray(d)&&d.length?s(d):l()}:l(),setTimeout(()=>s([]),e)})}async parseToReadiumSpeechVoices(e){const r=this.countVoiceDuplicates(e);return await Promise.all(e.filter(i=>i?.name&&i?.lang).map(async i=>{const s=$(i.lang),[o]=P.extractLangRegionFromBCP47(s),a=this.normalizeVoiceName(i.name),c=`${i.lang.toLowerCase()}_${a}`,l=r.get(c)||1;let d=await _t(s);(!d||d.length===0)&&(d=await _t(o));const u=this.findMatchingJsonVoice(d,a),g=this.inferVoiceQuality(i,u,l);return u?{...u,label:u.label??this.cleanVoiceName(i.name),source:"json",originalName:i.name,language:u.language??s,voiceURI:i.voiceURI,quality:g,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Ut(i.name,i.voiceURI),isLowQuality:Bt(i.name,g)}:{source:"browser",label:this.cleanVoiceName(i.name),name:i.name,originalName:i.name,language:s,voiceURI:i.voiceURI,quality:g,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Ut(i.name,i.voiceURI),isLowQuality:Bt(i.name,g)}}))}convertToSpeechSynthesisVoice(e){if(e)return this.browserVoices.find(r=>r.voiceURI===e.voiceURI||r.name===e.originalName||this.normalizeVoiceName(r.name)===this.normalizeVoiceName(e.name))}filterVoices(e,r){let n=r?[...r]:[...this.voices];const i={excludeNovelty:!0,excludeVeryLowQuality:!0,removeDuplicates:!0,...e};if(i.languages){const s=Array.isArray(i.languages)?i.languages:[i.languages];n=n.filter(o=>s.some(a=>{const c=a.toLowerCase(),l=o.language?.toLowerCase(),d=o.altLanguage?.toLowerCase();if(l===c||d===c)return!0;const[u]=c.split("-");return l&&l.startsWith(u)||d&&d.startsWith(u)}))}if(i.source&&(n=n.filter(s=>s.source===i.source)),i.gender&&(n=n.filter(s=>s.gender===i.gender)),i.quality){const s=Array.isArray(i.quality)?i.quality:[i.quality];n=n.filter(o=>o.quality&&s.includes(o.quality))}return i.offlineOnly&&(n=n.filter(s=>s.offlineAvailability===!0)),i.provider&&(n=n.filter(s=>s.provider?.toLowerCase()===i.provider?.toLowerCase())),i.excludeNovelty&&(n=Pr(n)),i.excludeVeryLowQuality&&(n=Ir(n)),i.removeDuplicates&&(n=this.removeDuplicates(n)),n}filterOutNoveltyVoices(e){const r=e??this.voices;return Pr(r)}filterOutVeryLowQualityVoices(e){const r=e??this.voices;return Ir(r)}async sortVoicesByQuality(e){const r=e||this.voices;if(!r?.length)return[];const n=await ge(r);return[...r].sort((i,s)=>Q(i,s,n))}static async sortByDefaultRegion(e,r){const n=await ge(e),i=ct(r);e.sort((s,o)=>{const[,a]=P.extractLangRegionFromBCP47(s.language),[,c]=P.extractLangRegionFromBCP47(o.language),l=i&&a===i.split("-")[1],d=i&&c===i.split("-")[1];return l&&!d?-1:!l&&d?1:Q(s,o,n,r)})}async sortVoicesByLanguages(e,r){const n=r||this.voices;if(!n?.length)return[];if(!e?.length){const c=[...n];return await $t(c),c}const i=ut(e),{voicesByLang:s,otherLangVoices:o}=ht(n,i),a=[];for(const c of i){const l=s.get(c.baseLang);l&&(await P.sortByDefaultRegion(l,c.baseLang),a.push(...l))}return await $t(o),a.push(...o),a}async sortVoicesByRegions(e,r){return Ki(e,r||this.voices)}groupVoices(e,r){const n={},i=r||this.voices;for(const s of i){let o="Unknown";switch(e){case"languages":o=P.extractLangRegionFromBCP47(s.language)[0];break;case"gender":o=s.gender||"unknown";break;case"quality":o=s.quality||"unknown";break;case"region":const[,a]=P.extractLangRegionFromBCP47(s.language);o=a||"unknown";break}n[o]||(n[o]=[]),n[o].push(s)}return n}}const cs=["webKit","moz","ms","o"],us=["boundary","end","error","mark","pause","resume","start"],hs=t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`,Ee=(t={},e)=>Object.hasOwnProperty.call(t,e)||e in t||!!t[e],ds=t=>typeof window<"u"&&t in window,gs=t=>{const e=hs(t),r=cs.map(i=>`${i}${e}`),n=[t,e].concat(r).find(ds);return n&&typeof window<"u"?window[n]:void 0},fs=()=>{const t={};["speechSynthesis","speechSynthesisUtterance","speechSynthesisVoice","speechSynthesisEvent","speechSynthesisErrorEvent"].forEach(r=>{t[r]=gs(r)}),t.onvoiceschanged=Ee(t.speechSynthesis,"onvoiceschanged"),t.speechSynthesisSpeaking=Ee(t.speechSynthesis,"speaking"),t.speechSynthesisPaused=Ee(t.speechSynthesis,"paused");const e=t.speechSynthesisUtterance?Ee(t.speechSynthesisUtterance,"prototype"):!1;return us.forEach(r=>{const n=`on${r}`;t[n]=e&&t.speechSynthesisUtterance?Ee(t.speechSynthesisUtterance.prototype,n):!1}),t},ps=()=>{const e=typeof window<"u"&&(window.navigator||{}).userAgent||"",r=()=>/android/i.test(e),n=()=>/kaios/i.test(e),i=()=>typeof window.InstallTrigger<"u"?!0:/firefox/i.test(e),s=()=>typeof window.GestureEvent<"u"||/safari/i.test(e);return{isAndroid:r(),isFirefox:i()||n(),isSafari:s(),isKaiOS:n()}};class dt{listeners=new Map;on(e,r){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(r),()=>{const n=this.listeners.get(e);if(n){const i=n.indexOf(r);i>-1&&n.splice(i,1)}}}emit(e,r){const n=this.listeners.get(e);n&&[...n].forEach(i=>{try{i(r)}catch(s){console.error(`Error in "${String(e)}" listener:`,s)}})}clear(){this.listeners.clear()}}const Xe=(t,e)=>Math.min(Math.max(t,0),Math.max(e-1,0));function ms(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var yt,Lr;function ys(){if(Lr)return yt;Lr=1,yt=e;function t(n){return n instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function e(n){if(n=n||{},n.circles)return r(n);const i=new Map;if(i.set(Date,l=>new Date(l)),i.set(Map,(l,d)=>new Map(o(Array.from(l),d))),i.set(Set,(l,d)=>new Set(o(Array.from(l),d))),n.constructorHandlers)for(const l of n.constructorHandlers)i.set(l[0],l[1]);let s=null;return n.proto?c:a;function o(l,d){const u=Object.keys(l),g=new Array(u.length);for(let f=0;f<u.length;f++){const y=u[f],m=l[y];typeof m!="object"||m===null?g[y]=m:m.constructor!==Object&&(s=i.get(m.constructor))?g[y]=s(m,d):ArrayBuffer.isView(m)?g[y]=t(m):g[y]=d(m)}return g}function a(l){if(typeof l!="object"||l===null)return l;if(Array.isArray(l))return o(l,a);if(l.constructor!==Object&&(s=i.get(l.constructor)))return s(l,a);const d={};for(const u in l){if(Object.hasOwnProperty.call(l,u)===!1)continue;const g=l[u];typeof g!="object"||g===null?d[u]=g:g.constructor!==Object&&(s=i.get(g.constructor))?d[u]=s(g,a):ArrayBuffer.isView(g)?d[u]=t(g):d[u]=a(g)}return d}function c(l){if(typeof l!="object"||l===null)return l;if(Array.isArray(l))return o(l,c);if(l.constructor!==Object&&(s=i.get(l.constructor)))return s(l,c);const d={};for(const u in l){const g=l[u];typeof g!="object"||g===null?d[u]=g:g.constructor!==Object&&(s=i.get(g.constructor))?d[u]=s(g,c):ArrayBuffer.isView(g)?d[u]=t(g):d[u]=c(g)}return d}}function r(n){const i=[],s=[],o=new Map;if(o.set(Date,u=>new Date(u)),o.set(Map,(u,g)=>new Map(c(Array.from(u),g))),o.set(Set,(u,g)=>new Set(c(Array.from(u),g))),n.constructorHandlers)for(const u of n.constructorHandlers)o.set(u[0],u[1]);let a=null;return n.proto?d:l;function c(u,g){const f=Object.keys(u),y=new Array(f.length);for(let m=0;m<f.length;m++){const p=f[m],w=u[p];if(typeof w!="object"||w===null)y[p]=w;else if(w.constructor!==Object&&(a=o.get(w.constructor)))y[p]=a(w,g);else if(ArrayBuffer.isView(w))y[p]=t(w);else{const E=i.indexOf(w);E!==-1?y[p]=s[E]:y[p]=g(w)}}return y}function l(u){if(typeof u!="object"||u===null)return u;if(Array.isArray(u))return c(u,l);if(u.constructor!==Object&&(a=o.get(u.constructor)))return a(u,l);const g={};i.push(u),s.push(g);for(const f in u){if(Object.hasOwnProperty.call(u,f)===!1)continue;const y=u[f];if(typeof y!="object"||y===null)g[f]=y;else if(y.constructor!==Object&&(a=o.get(y.constructor)))g[f]=a(y,l);else if(ArrayBuffer.isView(y))g[f]=t(y);else{const m=i.indexOf(y);m!==-1?g[f]=s[m]:g[f]=l(y)}}return i.pop(),s.pop(),g}function d(u){if(typeof u!="object"||u===null)return u;if(Array.isArray(u))return c(u,d);if(u.constructor!==Object&&(a=o.get(u.constructor)))return a(u,d);const g={};i.push(u),s.push(g);for(const f in u){const y=u[f];if(typeof y!="object"||y===null)g[f]=y;else if(y.constructor!==Object&&(a=o.get(y.constructor)))g[f]=a(y,d);else if(ArrayBuffer.isView(y))g[f]=t(y);else{const m=i.indexOf(y);m!==-1?g[f]=s[m]:g[f]=d(y)}}return i.pop(),s.pop(),g}}return yt}var vs=ys();const Sn=ms(vs);Sn();function zt(t){if(t==null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:!(Symbol.iterator in t)&&!(Symbol.toStringTag in t)}function ne(t){return typeof t=="string"}function bs(t){return Number.isFinite(t)}function ee(t){return Number.isSafeInteger(t)&&t>=0}function G(t){return t!=null}function ws(t,e){return zt(t)&&ne(e)&&e in t}var Ss=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,ks=typeof self=="object"&&self&&self.Object===Object&&self,sr=Ss||ks||Function("return this")(),fe=sr.Symbol,kn=Object.prototype,xs=kn.hasOwnProperty,Es=kn.toString,Ce=fe?fe.toStringTag:void 0;function Cs(t){var e=xs.call(t,Ce),r=t[Ce];try{t[Ce]=void 0;var n=!0}catch{}var i=Es.call(t);return n&&(e?t[Ce]=r:delete t[Ce]),i}var As=Object.prototype,Ts=As.toString;function Os(t){return Ts.call(t)}var Rs="[object Null]",Ps="[object Undefined]",qr=fe?fe.toStringTag:void 0;function xn(t){return t==null?t===void 0?Ps:Rs:qr&&qr in Object(t)?Cs(t):Os(t)}function En(t){return t!=null&&typeof t=="object"}var Is="[object Symbol]";function Ns(t){return typeof t=="symbol"||En(t)&&xn(t)==Is}function Ls(t,e){for(var r=-1,n=t==null?0:t.length,i=Array(n);++r<n;)i[r]=e(t[r],r,t);return i}var qs=Array.isArray,_r=fe?fe.prototype:void 0,Dr=_r?_r.toString:void 0;function ar(t){if(typeof t=="string")return t;if(qs(t))return Ls(t,ar)+"";if(Ns(t))return Dr?Dr.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}var _s=/\s/;function Ds(t){for(var e=t.length;e--&&_s.test(t.charAt(e)););return e}var $s=/^\s+/;function Us(t){return t&&t.slice(0,Ds(t)+1).replace($s,"")}function Cn(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function An(t){return t}var Bs="[object AsyncFunction]",Vs="[object Function]",zs="[object GeneratorFunction]",js="[object Proxy]";function Tn(t){if(!Cn(t))return!1;var e=xn(t);return e==Vs||e==zs||e==Bs||e==js}var vt=sr["__core-js_shared__"],$r=(function(){var t=/[^.]+$/.exec(vt&&vt.keys&&vt.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function Ms(t){return!!$r&&$r in t}var Fs=Function.prototype,Hs=Fs.toString;function Ws(t){if(t!=null){try{return Hs.call(t)}catch{}try{return t+""}catch{}}return""}var Gs=/[\\^$.*+?()[\]{}|]/g,Ks=/^\[object .+?Constructor\]$/,Js=Function.prototype,Qs=Object.prototype,Xs=Js.toString,Zs=Qs.hasOwnProperty,Ys=RegExp("^"+Xs.call(Zs).replace(Gs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ea(t){if(!Cn(t)||Ms(t))return!1;var e=Tn(t)?Ys:Ks;return e.test(Ws(t))}function ta(t,e){return t?.[e]}function or(t,e){var r=ta(t,e);return ea(r)?r:void 0}function ra(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var na=800,ia=16,sa=Date.now;function aa(t){var e=0,r=0;return function(){var n=sa(),i=ia-(n-r);if(r=n,i>0){if(++e>=na)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function oa(t){return function(){return t}}var Ur=(function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch{}})(),la=Ur?function(t,e){return Ur(t,"toString",{configurable:!0,enumerable:!1,value:oa(e),writable:!0})}:An,ca=aa(la);function ua(t,e,r,n){for(var i=t.length,s=r+-1;++s<i;)if(e(t[s],s,t))return s;return-1}function ha(t){return t!==t}function da(t,e,r){for(var n=r-1,i=t.length;++n<i;)if(t[n]===e)return n;return-1}function lr(t,e,r){return e===e?da(t,e,r):ua(t,ha,r)}function ga(t,e){var r=t==null?0:t.length;return!!r&&lr(t,e,0)>-1}function fa(t,e){return t===e||t!==t&&e!==e}var Br=Math.max;function pa(t,e,r){return e=Br(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,s=Br(n.length-e,0),o=Array(s);++i<s;)o[i]=n[e+i];i=-1;for(var a=Array(e+1);++i<e;)a[i]=n[i];return a[e]=r(o),ra(t,this,a)}}function ma(t,e){return ca(pa(t,e,An),t+"")}var ya=9007199254740991;function va(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=ya}function ba(t){return t!=null&&va(t.length)&&!Tn(t)}var qe=or(Object,"create");function wa(){this.__data__=qe?qe(null):{},this.size=0}function Sa(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var ka="__lodash_hash_undefined__",xa=Object.prototype,Ea=xa.hasOwnProperty;function Ca(t){var e=this.__data__;if(qe){var r=e[t];return r===ka?void 0:r}return Ea.call(e,t)?e[t]:void 0}var Aa=Object.prototype,Ta=Aa.hasOwnProperty;function Oa(t){var e=this.__data__;return qe?e[t]!==void 0:Ta.call(e,t)}var Ra="__lodash_hash_undefined__";function Pa(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=qe&&e===void 0?Ra:e,this}function X(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}X.prototype.clear=wa;X.prototype.delete=Sa;X.prototype.get=Ca;X.prototype.has=Oa;X.prototype.set=Pa;function Ia(){this.__data__=[],this.size=0}function gt(t,e){for(var r=t.length;r--;)if(fa(t[r][0],e))return r;return-1}var Na=Array.prototype,La=Na.splice;function qa(t){var e=this.__data__,r=gt(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():La.call(e,r,1),--this.size,!0}function _a(t){var e=this.__data__,r=gt(e,t);return r<0?void 0:e[r][1]}function Da(t){return gt(this.__data__,t)>-1}function $a(t,e){var r=this.__data__,n=gt(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function be(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}be.prototype.clear=Ia;be.prototype.delete=qa;be.prototype.get=_a;be.prototype.has=Da;be.prototype.set=$a;var Ua=or(sr,"Map");function Ba(){this.size=0,this.__data__={hash:new X,map:new(Ua||be),string:new X}}function Va(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function ft(t,e){var r=t.__data__;return Va(e)?r[typeof e=="string"?"string":"hash"]:r.map}function za(t){var e=ft(this,t).delete(t);return this.size-=e?1:0,e}function ja(t){return ft(this,t).get(t)}function Ma(t){return ft(this,t).has(t)}function Fa(t,e){var r=ft(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function we(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}we.prototype.clear=Ba;we.prototype.delete=za;we.prototype.get=ja;we.prototype.has=Ma;we.prototype.set=Fa;function Ha(t){return t==null?"":ar(t)}function Wa(t,e,r){var n=-1,i=t.length;e<0&&(e=-e>i?0:i+e),r=r>i?i:r,r<0&&(r+=i),i=e>r?0:r-e>>>0,e>>>=0;for(var s=Array(i);++n<i;)s[n]=t[n+e];return s}function Ga(t,e,r){var n=t.length;return r=r===void 0?n:r,!e&&r>=n?t:Wa(t,e,r)}var Ka="\\ud800-\\udfff",Ja="\\u0300-\\u036f",Qa="\\ufe20-\\ufe2f",Xa="\\u20d0-\\u20ff",Za=Ja+Qa+Xa,Ya="\\ufe0e\\ufe0f",eo="\\u200d",to=RegExp("["+eo+Ka+Za+Ya+"]");function ro(t){return to.test(t)}function no(t){return t.split("")}var On="\\ud800-\\udfff",io="\\u0300-\\u036f",so="\\ufe20-\\ufe2f",ao="\\u20d0-\\u20ff",oo=io+so+ao,lo="\\ufe0e\\ufe0f",co="["+On+"]",jt="["+oo+"]",Mt="\\ud83c[\\udffb-\\udfff]",uo="(?:"+jt+"|"+Mt+")",Rn="[^"+On+"]",Pn="(?:\\ud83c[\\udde6-\\uddff]){2}",In="[\\ud800-\\udbff][\\udc00-\\udfff]",ho="\\u200d",Nn=uo+"?",Ln="["+lo+"]?",go="(?:"+ho+"(?:"+[Rn,Pn,In].join("|")+")"+Ln+Nn+")*",fo=Ln+Nn+go,po="(?:"+[Rn+jt+"?",jt,Pn,In,co].join("|")+")",mo=RegExp(Mt+"(?="+Mt+")|"+po+fo,"g");function yo(t){return t.match(mo)||[]}function Vr(t){return ro(t)?yo(t):no(t)}var vo="__lodash_hash_undefined__";function bo(t){return this.__data__.set(t,vo),this}function wo(t){return this.__data__.has(t)}function et(t){var e=-1,r=t==null?0:t.length;for(this.__data__=new we;++e<r;)this.add(t[e])}et.prototype.add=et.prototype.push=bo;et.prototype.has=wo;function So(t,e){return t.has(e)}function ko(t){return En(t)&&ba(t)}var xo=200;function Eo(t,e,r,n){var i=-1,s=ga,o=!0,a=t.length,c=[],l=e.length;if(!a)return c;e.length>=xo&&(s=So,o=!1,e=new et(e));e:for(;++i<a;){var d=t[i],u=d;if(d=d!==0?d:0,o&&u===u){for(var g=l;g--;)if(e[g]===u)continue e;c.push(d)}else s(e,u,n)||c.push(d)}return c}function Co(t,e){for(var r=t.length;r--&&lr(e,t[r],0)>-1;);return r}function Ao(t,e){for(var r=-1,n=t.length;++r<n&&lr(e,t[r],0)>-1;);return r}function zr(t,e,r){if(t=Ha(t),t&&e===void 0)return Us(t);if(!t||!(e=ar(e)))return t;var n=Vr(t),i=Vr(e),s=Ao(n,i),o=Co(n,i)+1;return Ga(n,s,o).join("")}var To=ma(function(t,e){return ko(t)?Eo(t,e):[]}),ae=function(){return ae=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},ae.apply(this,arguments)},Oo="~",Ro="~~";function cr(t,e){for(var r={},n={},i=t.split(Ro),s=!1,o=0;i.length>o;o++){for(var a=i[o].split(Oo),c=0;c<a.length;c+=2){var l=a[c],d=a[c+1],u="&"+l+";";r[u]=d,s&&(r["&"+l]=d),n[d]=u}s=!0}return e?{entities:ae(ae({},r),e.entities),characters:ae(ae({},n),e.characters)}:{entities:r,characters:n}}var bt={xml:/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g,html4:/∉|&(?:nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|ucirc|uuml|yacute|thorn|yuml|quot|amp|lt|gt|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g,html5:/·|℗|⋇|⪧|⩺|⋗|⦕|⩼|⪆|⥸|⋗|⋛|⪌|≷|≳|⪦|⩹|⋖|⋋|⋉|⥶|⩻|⦖|◃|⊴|◂|∉|⋹̸|⋵̸|∉|⋷|⋶|∌|∌|⋾|⋽|∥|⊠|⨱|⨰|&(?:AElig|AMP|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|GT|Iacute|Icirc|Igrave|Iuml|LT|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|QUOT|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|amp|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|gt|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|lt|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|quot|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g},pe={};pe.xml=cr(`lt~<~gt~>~quot~"~apos~'~amp~&`);pe.html4=cr(`apos~'~OElig~Œ~oelig~œ~Scaron~Š~scaron~š~Yuml~Ÿ~circ~ˆ~tilde~˜~ensp~ ~emsp~ ~thinsp~ ~zwnj~~zwj~~lrm~~rlm~~ndash~–~mdash~—~lsquo~‘~rsquo~’~sbquo~‚~ldquo~“~rdquo~”~bdquo~„~dagger~†~Dagger~‡~permil~‰~lsaquo~‹~rsaquo~›~euro~€~fnof~ƒ~Alpha~Α~Beta~Β~Gamma~Γ~Delta~Δ~Epsilon~Ε~Zeta~Ζ~Eta~Η~Theta~Θ~Iota~Ι~Kappa~Κ~Lambda~Λ~Mu~Μ~Nu~Ν~Xi~Ξ~Omicron~Ο~Pi~Π~Rho~Ρ~Sigma~Σ~Tau~Τ~Upsilon~Υ~Phi~Φ~Chi~Χ~Psi~Ψ~Omega~Ω~alpha~α~beta~β~gamma~γ~delta~δ~epsilon~ε~zeta~ζ~eta~η~theta~θ~iota~ι~kappa~κ~lambda~λ~mu~μ~nu~ν~xi~ξ~omicron~ο~pi~π~rho~ρ~sigmaf~ς~sigma~σ~tau~τ~upsilon~υ~phi~φ~chi~χ~psi~ψ~omega~ω~thetasym~ϑ~upsih~ϒ~piv~ϖ~bull~•~hellip~…~prime~′~Prime~″~oline~‾~frasl~⁄~weierp~℘~image~ℑ~real~ℜ~trade~™~alefsym~ℵ~larr~←~uarr~↑~rarr~→~darr~↓~harr~↔~crarr~↵~lArr~⇐~uArr~⇑~rArr~⇒~dArr~⇓~hArr~⇔~forall~∀~part~∂~exist~∃~empty~∅~nabla~∇~isin~∈~notin~∉~ni~∋~prod~∏~sum~∑~minus~−~lowast~∗~radic~√~prop~∝~infin~∞~ang~∠~and~∧~or~∨~cap~∩~cup~∪~int~∫~there4~∴~sim~∼~cong~≅~asymp~≈~ne~≠~equiv~≡~le~≤~ge~≥~sub~⊂~sup~⊃~nsub~⊄~sube~⊆~supe~⊇~oplus~⊕~otimes~⊗~perp~⊥~sdot~⋅~lceil~⌈~rceil~⌉~lfloor~⌊~rfloor~⌋~lang~〈~rang~〉~loz~◊~spades~♠~clubs~♣~hearts~♥~diams~♦~~nbsp~ ~iexcl~¡~cent~¢~pound~£~curren~¤~yen~¥~brvbar~¦~sect~§~uml~¨~copy~©~ordf~ª~laquo~«~not~¬~shy~~reg~®~macr~¯~deg~°~plusmn~±~sup2~²~sup3~³~acute~´~micro~µ~para~¶~middot~·~cedil~¸~sup1~¹~ordm~º~raquo~»~frac14~¼~frac12~½~frac34~¾~iquest~¿~Agrave~À~Aacute~Á~Acirc~Â~Atilde~Ã~Auml~Ä~Aring~Å~AElig~Æ~Ccedil~Ç~Egrave~È~Eacute~É~Ecirc~Ê~Euml~Ë~Igrave~Ì~Iacute~Í~Icirc~Î~Iuml~Ï~ETH~Ð~Ntilde~Ñ~Ograve~Ò~Oacute~Ó~Ocirc~Ô~Otilde~Õ~Ouml~Ö~times~×~Oslash~Ø~Ugrave~Ù~Uacute~Ú~Ucirc~Û~Uuml~Ü~Yacute~Ý~THORN~Þ~szlig~ß~agrave~à~aacute~á~acirc~â~atilde~ã~auml~ä~aring~å~aelig~æ~ccedil~ç~egrave~è~eacute~é~ecirc~ê~euml~ë~igrave~ì~iacute~í~icirc~î~iuml~ï~eth~ð~ntilde~ñ~ograve~ò~oacute~ó~ocirc~ô~otilde~õ~ouml~ö~divide~÷~oslash~ø~ugrave~ù~uacute~ú~ucirc~û~uuml~ü~yacute~ý~thorn~þ~yuml~ÿ~quot~"~amp~&~lt~<~gt~>`);pe.html5=cr('Abreve~Ă~Acy~А~Afr~𝔄~Amacr~Ā~And~⩓~Aogon~Ą~Aopf~𝔸~ApplyFunction~~Ascr~𝒜~Assign~≔~Backslash~∖~Barv~⫧~Barwed~⌆~Bcy~Б~Because~∵~Bernoullis~ℬ~Bfr~𝔅~Bopf~𝔹~Breve~˘~Bscr~ℬ~Bumpeq~≎~CHcy~Ч~Cacute~Ć~Cap~⋒~CapitalDifferentialD~ⅅ~Cayleys~ℭ~Ccaron~Č~Ccirc~Ĉ~Cconint~∰~Cdot~Ċ~Cedilla~¸~CenterDot~·~Cfr~ℭ~CircleDot~⊙~CircleMinus~⊖~CirclePlus~⊕~CircleTimes~⊗~ClockwiseContourIntegral~∲~CloseCurlyDoubleQuote~”~CloseCurlyQuote~’~Colon~∷~Colone~⩴~Congruent~≡~Conint~∯~ContourIntegral~∮~Copf~ℂ~Coproduct~∐~CounterClockwiseContourIntegral~∳~Cross~⨯~Cscr~𝒞~Cup~⋓~CupCap~≍~DD~ⅅ~DDotrahd~⤑~DJcy~Ђ~DScy~Ѕ~DZcy~Џ~Darr~↡~Dashv~⫤~Dcaron~Ď~Dcy~Д~Del~∇~Dfr~𝔇~DiacriticalAcute~´~DiacriticalDot~˙~DiacriticalDoubleAcute~˝~DiacriticalGrave~`~DiacriticalTilde~˜~Diamond~⋄~DifferentialD~ⅆ~Dopf~𝔻~Dot~¨~DotDot~⃜~DotEqual~≐~DoubleContourIntegral~∯~DoubleDot~¨~DoubleDownArrow~⇓~DoubleLeftArrow~⇐~DoubleLeftRightArrow~⇔~DoubleLeftTee~⫤~DoubleLongLeftArrow~⟸~DoubleLongLeftRightArrow~⟺~DoubleLongRightArrow~⟹~DoubleRightArrow~⇒~DoubleRightTee~⊨~DoubleUpArrow~⇑~DoubleUpDownArrow~⇕~DoubleVerticalBar~∥~DownArrow~↓~DownArrowBar~⤓~DownArrowUpArrow~⇵~DownBreve~̑~DownLeftRightVector~⥐~DownLeftTeeVector~⥞~DownLeftVector~↽~DownLeftVectorBar~⥖~DownRightTeeVector~⥟~DownRightVector~⇁~DownRightVectorBar~⥗~DownTee~⊤~DownTeeArrow~↧~Downarrow~⇓~Dscr~𝒟~Dstrok~Đ~ENG~Ŋ~Ecaron~Ě~Ecy~Э~Edot~Ė~Efr~𝔈~Element~∈~Emacr~Ē~EmptySmallSquare~◻~EmptyVerySmallSquare~▫~Eogon~Ę~Eopf~𝔼~Equal~⩵~EqualTilde~≂~Equilibrium~⇌~Escr~ℰ~Esim~⩳~Exists~∃~ExponentialE~ⅇ~Fcy~Ф~Ffr~𝔉~FilledSmallSquare~◼~FilledVerySmallSquare~▪~Fopf~𝔽~ForAll~∀~Fouriertrf~ℱ~Fscr~ℱ~GJcy~Ѓ~Gammad~Ϝ~Gbreve~Ğ~Gcedil~Ģ~Gcirc~Ĝ~Gcy~Г~Gdot~Ġ~Gfr~𝔊~Gg~⋙~Gopf~𝔾~GreaterEqual~≥~GreaterEqualLess~⋛~GreaterFullEqual~≧~GreaterGreater~⪢~GreaterLess~≷~GreaterSlantEqual~⩾~GreaterTilde~≳~Gscr~𝒢~Gt~≫~HARDcy~Ъ~Hacek~ˇ~Hat~^~Hcirc~Ĥ~Hfr~ℌ~HilbertSpace~ℋ~Hopf~ℍ~HorizontalLine~─~Hscr~ℋ~Hstrok~Ħ~HumpDownHump~≎~HumpEqual~≏~IEcy~Е~IJlig~IJ~IOcy~Ё~Icy~И~Idot~İ~Ifr~ℑ~Im~ℑ~Imacr~Ī~ImaginaryI~ⅈ~Implies~⇒~Int~∬~Integral~∫~Intersection~⋂~InvisibleComma~~InvisibleTimes~~Iogon~Į~Iopf~𝕀~Iscr~ℐ~Itilde~Ĩ~Iukcy~І~Jcirc~Ĵ~Jcy~Й~Jfr~𝔍~Jopf~𝕁~Jscr~𝒥~Jsercy~Ј~Jukcy~Є~KHcy~Х~KJcy~Ќ~Kcedil~Ķ~Kcy~К~Kfr~𝔎~Kopf~𝕂~Kscr~𝒦~LJcy~Љ~Lacute~Ĺ~Lang~⟪~Laplacetrf~ℒ~Larr~↞~Lcaron~Ľ~Lcedil~Ļ~Lcy~Л~LeftAngleBracket~⟨~LeftArrow~←~LeftArrowBar~⇤~LeftArrowRightArrow~⇆~LeftCeiling~⌈~LeftDoubleBracket~⟦~LeftDownTeeVector~⥡~LeftDownVector~⇃~LeftDownVectorBar~⥙~LeftFloor~⌊~LeftRightArrow~↔~LeftRightVector~⥎~LeftTee~⊣~LeftTeeArrow~↤~LeftTeeVector~⥚~LeftTriangle~⊲~LeftTriangleBar~⧏~LeftTriangleEqual~⊴~LeftUpDownVector~⥑~LeftUpTeeVector~⥠~LeftUpVector~↿~LeftUpVectorBar~⥘~LeftVector~↼~LeftVectorBar~⥒~Leftarrow~⇐~Leftrightarrow~⇔~LessEqualGreater~⋚~LessFullEqual~≦~LessGreater~≶~LessLess~⪡~LessSlantEqual~⩽~LessTilde~≲~Lfr~𝔏~Ll~⋘~Lleftarrow~⇚~Lmidot~Ŀ~LongLeftArrow~⟵~LongLeftRightArrow~⟷~LongRightArrow~⟶~Longleftarrow~⟸~Longleftrightarrow~⟺~Longrightarrow~⟹~Lopf~𝕃~LowerLeftArrow~↙~LowerRightArrow~↘~Lscr~ℒ~Lsh~↰~Lstrok~Ł~Lt~≪~Map~⤅~Mcy~М~MediumSpace~ ~Mellintrf~ℳ~Mfr~𝔐~MinusPlus~∓~Mopf~𝕄~Mscr~ℳ~NJcy~Њ~Nacute~Ń~Ncaron~Ň~Ncedil~Ņ~Ncy~Н~NegativeMediumSpace~~NegativeThickSpace~~NegativeThinSpace~~NegativeVeryThinSpace~~NestedGreaterGreater~≫~NestedLessLess~≪~NewLine~\n~Nfr~𝔑~NoBreak~~NonBreakingSpace~ ~Nopf~ℕ~Not~⫬~NotCongruent~≢~NotCupCap~≭~NotDoubleVerticalBar~∦~NotElement~∉~NotEqual~≠~NotEqualTilde~≂̸~NotExists~∄~NotGreater~≯~NotGreaterEqual~≱~NotGreaterFullEqual~≧̸~NotGreaterGreater~≫̸~NotGreaterLess~≹~NotGreaterSlantEqual~⩾̸~NotGreaterTilde~≵~NotHumpDownHump~≎̸~NotHumpEqual~≏̸~NotLeftTriangle~⋪~NotLeftTriangleBar~⧏̸~NotLeftTriangleEqual~⋬~NotLess~≮~NotLessEqual~≰~NotLessGreater~≸~NotLessLess~≪̸~NotLessSlantEqual~⩽̸~NotLessTilde~≴~NotNestedGreaterGreater~⪢̸~NotNestedLessLess~⪡̸~NotPrecedes~⊀~NotPrecedesEqual~⪯̸~NotPrecedesSlantEqual~⋠~NotReverseElement~∌~NotRightTriangle~⋫~NotRightTriangleBar~⧐̸~NotRightTriangleEqual~⋭~NotSquareSubset~⊏̸~NotSquareSubsetEqual~⋢~NotSquareSuperset~⊐̸~NotSquareSupersetEqual~⋣~NotSubset~⊂⃒~NotSubsetEqual~⊈~NotSucceeds~⊁~NotSucceedsEqual~⪰̸~NotSucceedsSlantEqual~⋡~NotSucceedsTilde~≿̸~NotSuperset~⊃⃒~NotSupersetEqual~⊉~NotTilde~≁~NotTildeEqual~≄~NotTildeFullEqual~≇~NotTildeTilde~≉~NotVerticalBar~∤~Nscr~𝒩~Ocy~О~Odblac~Ő~Ofr~𝔒~Omacr~Ō~Oopf~𝕆~OpenCurlyDoubleQuote~“~OpenCurlyQuote~‘~Or~⩔~Oscr~𝒪~Otimes~⨷~OverBar~‾~OverBrace~⏞~OverBracket~⎴~OverParenthesis~⏜~PartialD~∂~Pcy~П~Pfr~𝔓~PlusMinus~±~Poincareplane~ℌ~Popf~ℙ~Pr~⪻~Precedes~≺~PrecedesEqual~⪯~PrecedesSlantEqual~≼~PrecedesTilde~≾~Product~∏~Proportion~∷~Proportional~∝~Pscr~𝒫~Qfr~𝔔~Qopf~ℚ~Qscr~𝒬~RBarr~⤐~Racute~Ŕ~Rang~⟫~Rarr~↠~Rarrtl~⤖~Rcaron~Ř~Rcedil~Ŗ~Rcy~Р~Re~ℜ~ReverseElement~∋~ReverseEquilibrium~⇋~ReverseUpEquilibrium~⥯~Rfr~ℜ~RightAngleBracket~⟩~RightArrow~→~RightArrowBar~⇥~RightArrowLeftArrow~⇄~RightCeiling~⌉~RightDoubleBracket~⟧~RightDownTeeVector~⥝~RightDownVector~⇂~RightDownVectorBar~⥕~RightFloor~⌋~RightTee~⊢~RightTeeArrow~↦~RightTeeVector~⥛~RightTriangle~⊳~RightTriangleBar~⧐~RightTriangleEqual~⊵~RightUpDownVector~⥏~RightUpTeeVector~⥜~RightUpVector~↾~RightUpVectorBar~⥔~RightVector~⇀~RightVectorBar~⥓~Rightarrow~⇒~Ropf~ℝ~RoundImplies~⥰~Rrightarrow~⇛~Rscr~ℛ~Rsh~↱~RuleDelayed~⧴~SHCHcy~Щ~SHcy~Ш~SOFTcy~Ь~Sacute~Ś~Sc~⪼~Scedil~Ş~Scirc~Ŝ~Scy~С~Sfr~𝔖~ShortDownArrow~↓~ShortLeftArrow~←~ShortRightArrow~→~ShortUpArrow~↑~SmallCircle~∘~Sopf~𝕊~Sqrt~√~Square~□~SquareIntersection~⊓~SquareSubset~⊏~SquareSubsetEqual~⊑~SquareSuperset~⊐~SquareSupersetEqual~⊒~SquareUnion~⊔~Sscr~𝒮~Star~⋆~Sub~⋐~Subset~⋐~SubsetEqual~⊆~Succeeds~≻~SucceedsEqual~⪰~SucceedsSlantEqual~≽~SucceedsTilde~≿~SuchThat~∋~Sum~∑~Sup~⋑~Superset~⊃~SupersetEqual~⊇~Supset~⋑~TRADE~™~TSHcy~Ћ~TScy~Ц~Tab~ ~Tcaron~Ť~Tcedil~Ţ~Tcy~Т~Tfr~𝔗~Therefore~∴~ThickSpace~ ~ThinSpace~ ~Tilde~∼~TildeEqual~≃~TildeFullEqual~≅~TildeTilde~≈~Topf~𝕋~TripleDot~⃛~Tscr~𝒯~Tstrok~Ŧ~Uarr~↟~Uarrocir~⥉~Ubrcy~Ў~Ubreve~Ŭ~Ucy~У~Udblac~Ű~Ufr~𝔘~Umacr~Ū~UnderBar~_~UnderBrace~⏟~UnderBracket~⎵~UnderParenthesis~⏝~Union~⋃~UnionPlus~⊎~Uogon~Ų~Uopf~𝕌~UpArrow~↑~UpArrowBar~⤒~UpArrowDownArrow~⇅~UpDownArrow~↕~UpEquilibrium~⥮~UpTee~⊥~UpTeeArrow~↥~Uparrow~⇑~Updownarrow~⇕~UpperLeftArrow~↖~UpperRightArrow~↗~Upsi~ϒ~Uring~Ů~Uscr~𝒰~Utilde~Ũ~VDash~⊫~Vbar~⫫~Vcy~В~Vdash~⊩~Vdashl~⫦~Vee~⋁~Verbar~‖~Vert~‖~VerticalBar~∣~VerticalLine~|~VerticalSeparator~❘~VerticalTilde~≀~VeryThinSpace~ ~Vfr~𝔙~Vopf~𝕍~Vscr~𝒱~Vvdash~⊪~Wcirc~Ŵ~Wedge~⋀~Wfr~𝔚~Wopf~𝕎~Wscr~𝒲~Xfr~𝔛~Xopf~𝕏~Xscr~𝒳~YAcy~Я~YIcy~Ї~YUcy~Ю~Ycirc~Ŷ~Ycy~Ы~Yfr~𝔜~Yopf~𝕐~Yscr~𝒴~ZHcy~Ж~Zacute~Ź~Zcaron~Ž~Zcy~З~Zdot~Ż~ZeroWidthSpace~~Zfr~ℨ~Zopf~ℤ~Zscr~𝒵~abreve~ă~ac~∾~acE~∾̳~acd~∿~acy~а~af~~afr~𝔞~aleph~ℵ~amacr~ā~amalg~⨿~andand~⩕~andd~⩜~andslope~⩘~andv~⩚~ange~⦤~angle~∠~angmsd~∡~angmsdaa~⦨~angmsdab~⦩~angmsdac~⦪~angmsdad~⦫~angmsdae~⦬~angmsdaf~⦭~angmsdag~⦮~angmsdah~⦯~angrt~∟~angrtvb~⊾~angrtvbd~⦝~angsph~∢~angst~Å~angzarr~⍼~aogon~ą~aopf~𝕒~ap~≈~apE~⩰~apacir~⩯~ape~≊~apid~≋~approx~≈~approxeq~≊~ascr~𝒶~ast~*~asympeq~≍~awconint~∳~awint~⨑~bNot~⫭~backcong~≌~backepsilon~϶~backprime~‵~backsim~∽~backsimeq~⋍~barvee~⊽~barwed~⌅~barwedge~⌅~bbrk~⎵~bbrktbrk~⎶~bcong~≌~bcy~б~becaus~∵~because~∵~bemptyv~⦰~bepsi~϶~bernou~ℬ~beth~ℶ~between~≬~bfr~𝔟~bigcap~⋂~bigcirc~◯~bigcup~⋃~bigodot~⨀~bigoplus~⨁~bigotimes~⨂~bigsqcup~⨆~bigstar~★~bigtriangledown~▽~bigtriangleup~△~biguplus~⨄~bigvee~⋁~bigwedge~⋀~bkarow~⤍~blacklozenge~⧫~blacksquare~▪~blacktriangle~▴~blacktriangledown~▾~blacktriangleleft~◂~blacktriangleright~▸~blank~␣~blk12~▒~blk14~░~blk34~▓~block~█~bne~=⃥~bnequiv~≡⃥~bnot~⌐~bopf~𝕓~bot~⊥~bottom~⊥~bowtie~⋈~boxDL~╗~boxDR~╔~boxDl~╖~boxDr~╓~boxH~═~boxHD~╦~boxHU~╩~boxHd~╤~boxHu~╧~boxUL~╝~boxUR~╚~boxUl~╜~boxUr~╙~boxV~║~boxVH~╬~boxVL~╣~boxVR~╠~boxVh~╫~boxVl~╢~boxVr~╟~boxbox~⧉~boxdL~╕~boxdR~╒~boxdl~┐~boxdr~┌~boxh~─~boxhD~╥~boxhU~╨~boxhd~┬~boxhu~┴~boxminus~⊟~boxplus~⊞~boxtimes~⊠~boxuL~╛~boxuR~╘~boxul~┘~boxur~└~boxv~│~boxvH~╪~boxvL~╡~boxvR~╞~boxvh~┼~boxvl~┤~boxvr~├~bprime~‵~breve~˘~bscr~𝒷~bsemi~⁏~bsim~∽~bsime~⋍~bsol~\\~bsolb~⧅~bsolhsub~⟈~bullet~•~bump~≎~bumpE~⪮~bumpe~≏~bumpeq~≏~cacute~ć~capand~⩄~capbrcup~⩉~capcap~⩋~capcup~⩇~capdot~⩀~caps~∩︀~caret~⁁~caron~ˇ~ccaps~⩍~ccaron~č~ccirc~ĉ~ccups~⩌~ccupssm~⩐~cdot~ċ~cemptyv~⦲~centerdot~·~cfr~𝔠~chcy~ч~check~✓~checkmark~✓~cir~○~cirE~⧃~circeq~≗~circlearrowleft~↺~circlearrowright~↻~circledR~®~circledS~Ⓢ~circledast~⊛~circledcirc~⊚~circleddash~⊝~cire~≗~cirfnint~⨐~cirmid~⫯~cirscir~⧂~clubsuit~♣~colon~:~colone~≔~coloneq~≔~comma~,~commat~@~comp~∁~compfn~∘~complement~∁~complexes~ℂ~congdot~⩭~conint~∮~copf~𝕔~coprod~∐~copysr~℗~cross~✗~cscr~𝒸~csub~⫏~csube~⫑~csup~⫐~csupe~⫒~ctdot~⋯~cudarrl~⤸~cudarrr~⤵~cuepr~⋞~cuesc~⋟~cularr~↶~cularrp~⤽~cupbrcap~⩈~cupcap~⩆~cupcup~⩊~cupdot~⊍~cupor~⩅~cups~∪︀~curarr~↷~curarrm~⤼~curlyeqprec~⋞~curlyeqsucc~⋟~curlyvee~⋎~curlywedge~⋏~curvearrowleft~↶~curvearrowright~↷~cuvee~⋎~cuwed~⋏~cwconint~∲~cwint~∱~cylcty~⌭~dHar~⥥~daleth~ℸ~dash~‐~dashv~⊣~dbkarow~⤏~dblac~˝~dcaron~ď~dcy~д~dd~ⅆ~ddagger~‡~ddarr~⇊~ddotseq~⩷~demptyv~⦱~dfisht~⥿~dfr~𝔡~dharl~⇃~dharr~⇂~diam~⋄~diamond~⋄~diamondsuit~♦~die~¨~digamma~ϝ~disin~⋲~div~÷~divideontimes~⋇~divonx~⋇~djcy~ђ~dlcorn~⌞~dlcrop~⌍~dollar~$~dopf~𝕕~dot~˙~doteq~≐~doteqdot~≑~dotminus~∸~dotplus~∔~dotsquare~⊡~doublebarwedge~⌆~downarrow~↓~downdownarrows~⇊~downharpoonleft~⇃~downharpoonright~⇂~drbkarow~⤐~drcorn~⌟~drcrop~⌌~dscr~𝒹~dscy~ѕ~dsol~⧶~dstrok~đ~dtdot~⋱~dtri~▿~dtrif~▾~duarr~⇵~duhar~⥯~dwangle~⦦~dzcy~џ~dzigrarr~⟿~eDDot~⩷~eDot~≑~easter~⩮~ecaron~ě~ecir~≖~ecolon~≕~ecy~э~edot~ė~ee~ⅇ~efDot~≒~efr~𝔢~eg~⪚~egs~⪖~egsdot~⪘~el~⪙~elinters~⏧~ell~ℓ~els~⪕~elsdot~⪗~emacr~ē~emptyset~∅~emptyv~∅~emsp13~ ~emsp14~ ~eng~ŋ~eogon~ę~eopf~𝕖~epar~⋕~eparsl~⧣~eplus~⩱~epsi~ε~epsiv~ϵ~eqcirc~≖~eqcolon~≕~eqsim~≂~eqslantgtr~⪖~eqslantless~⪕~equals~=~equest~≟~equivDD~⩸~eqvparsl~⧥~erDot~≓~erarr~⥱~escr~ℯ~esdot~≐~esim~≂~excl~!~expectation~ℰ~exponentiale~ⅇ~fallingdotseq~≒~fcy~ф~female~♀~ffilig~ffi~fflig~ff~ffllig~ffl~ffr~𝔣~filig~fi~fjlig~fj~flat~♭~fllig~fl~fltns~▱~fopf~𝕗~fork~⋔~forkv~⫙~fpartint~⨍~frac13~⅓~frac15~⅕~frac16~⅙~frac18~⅛~frac23~⅔~frac25~⅖~frac35~⅗~frac38~⅜~frac45~⅘~frac56~⅚~frac58~⅝~frac78~⅞~frown~⌢~fscr~𝒻~gE~≧~gEl~⪌~gacute~ǵ~gammad~ϝ~gap~⪆~gbreve~ğ~gcirc~ĝ~gcy~г~gdot~ġ~gel~⋛~geq~≥~geqq~≧~geqslant~⩾~ges~⩾~gescc~⪩~gesdot~⪀~gesdoto~⪂~gesdotol~⪄~gesl~⋛︀~gesles~⪔~gfr~𝔤~gg~≫~ggg~⋙~gimel~ℷ~gjcy~ѓ~gl~≷~glE~⪒~gla~⪥~glj~⪤~gnE~≩~gnap~⪊~gnapprox~⪊~gne~⪈~gneq~⪈~gneqq~≩~gnsim~⋧~gopf~𝕘~grave~`~gscr~ℊ~gsim~≳~gsime~⪎~gsiml~⪐~gtcc~⪧~gtcir~⩺~gtdot~⋗~gtlPar~⦕~gtquest~⩼~gtrapprox~⪆~gtrarr~⥸~gtrdot~⋗~gtreqless~⋛~gtreqqless~⪌~gtrless~≷~gtrsim~≳~gvertneqq~≩︀~gvnE~≩︀~hairsp~ ~half~½~hamilt~ℋ~hardcy~ъ~harrcir~⥈~harrw~↭~hbar~ℏ~hcirc~ĥ~heartsuit~♥~hercon~⊹~hfr~𝔥~hksearow~⤥~hkswarow~⤦~hoarr~⇿~homtht~∻~hookleftarrow~↩~hookrightarrow~↪~hopf~𝕙~horbar~―~hscr~𝒽~hslash~ℏ~hstrok~ħ~hybull~⁃~hyphen~‐~ic~~icy~и~iecy~е~iff~⇔~ifr~𝔦~ii~ⅈ~iiiint~⨌~iiint~∭~iinfin~⧜~iiota~℩~ijlig~ij~imacr~ī~imagline~ℐ~imagpart~ℑ~imath~ı~imof~⊷~imped~Ƶ~in~∈~incare~℅~infintie~⧝~inodot~ı~intcal~⊺~integers~ℤ~intercal~⊺~intlarhk~⨗~intprod~⨼~iocy~ё~iogon~į~iopf~𝕚~iprod~⨼~iscr~𝒾~isinE~⋹~isindot~⋵~isins~⋴~isinsv~⋳~isinv~∈~it~~itilde~ĩ~iukcy~і~jcirc~ĵ~jcy~й~jfr~𝔧~jmath~ȷ~jopf~𝕛~jscr~𝒿~jsercy~ј~jukcy~є~kappav~ϰ~kcedil~ķ~kcy~к~kfr~𝔨~kgreen~ĸ~khcy~х~kjcy~ќ~kopf~𝕜~kscr~𝓀~lAarr~⇚~lAtail~⤛~lBarr~⤎~lE~≦~lEg~⪋~lHar~⥢~lacute~ĺ~laemptyv~⦴~lagran~ℒ~langd~⦑~langle~⟨~lap~⪅~larrb~⇤~larrbfs~⤟~larrfs~⤝~larrhk~↩~larrlp~↫~larrpl~⤹~larrsim~⥳~larrtl~↢~lat~⪫~latail~⤙~late~⪭~lates~⪭︀~lbarr~⤌~lbbrk~❲~lbrace~{~lbrack~[~lbrke~⦋~lbrksld~⦏~lbrkslu~⦍~lcaron~ľ~lcedil~ļ~lcub~{~lcy~л~ldca~⤶~ldquor~„~ldrdhar~⥧~ldrushar~⥋~ldsh~↲~leftarrow~←~leftarrowtail~↢~leftharpoondown~↽~leftharpoonup~↼~leftleftarrows~⇇~leftrightarrow~↔~leftrightarrows~⇆~leftrightharpoons~⇋~leftrightsquigarrow~↭~leftthreetimes~⋋~leg~⋚~leq~≤~leqq~≦~leqslant~⩽~les~⩽~lescc~⪨~lesdot~⩿~lesdoto~⪁~lesdotor~⪃~lesg~⋚︀~lesges~⪓~lessapprox~⪅~lessdot~⋖~lesseqgtr~⋚~lesseqqgtr~⪋~lessgtr~≶~lesssim~≲~lfisht~⥼~lfr~𝔩~lg~≶~lgE~⪑~lhard~↽~lharu~↼~lharul~⥪~lhblk~▄~ljcy~љ~ll~≪~llarr~⇇~llcorner~⌞~llhard~⥫~lltri~◺~lmidot~ŀ~lmoust~⎰~lmoustache~⎰~lnE~≨~lnap~⪉~lnapprox~⪉~lne~⪇~lneq~⪇~lneqq~≨~lnsim~⋦~loang~⟬~loarr~⇽~lobrk~⟦~longleftarrow~⟵~longleftrightarrow~⟷~longmapsto~⟼~longrightarrow~⟶~looparrowleft~↫~looparrowright~↬~lopar~⦅~lopf~𝕝~loplus~⨭~lotimes~⨴~lowbar~_~lozenge~◊~lozf~⧫~lpar~(~lparlt~⦓~lrarr~⇆~lrcorner~⌟~lrhar~⇋~lrhard~⥭~lrtri~⊿~lscr~𝓁~lsh~↰~lsim~≲~lsime~⪍~lsimg~⪏~lsqb~[~lsquor~‚~lstrok~ł~ltcc~⪦~ltcir~⩹~ltdot~⋖~lthree~⋋~ltimes~⋉~ltlarr~⥶~ltquest~⩻~ltrPar~⦖~ltri~◃~ltrie~⊴~ltrif~◂~lurdshar~⥊~luruhar~⥦~lvertneqq~≨︀~lvnE~≨︀~mDDot~∺~male~♂~malt~✠~maltese~✠~map~↦~mapsto~↦~mapstodown~↧~mapstoleft~↤~mapstoup~↥~marker~▮~mcomma~⨩~mcy~м~measuredangle~∡~mfr~𝔪~mho~℧~mid~∣~midast~*~midcir~⫰~minusb~⊟~minusd~∸~minusdu~⨪~mlcp~⫛~mldr~…~mnplus~∓~models~⊧~mopf~𝕞~mp~∓~mscr~𝓂~mstpos~∾~multimap~⊸~mumap~⊸~nGg~⋙̸~nGt~≫⃒~nGtv~≫̸~nLeftarrow~⇍~nLeftrightarrow~⇎~nLl~⋘̸~nLt~≪⃒~nLtv~≪̸~nRightarrow~⇏~nVDash~⊯~nVdash~⊮~nacute~ń~nang~∠⃒~nap~≉~napE~⩰̸~napid~≋̸~napos~ʼn~napprox~≉~natur~♮~natural~♮~naturals~ℕ~nbump~≎̸~nbumpe~≏̸~ncap~⩃~ncaron~ň~ncedil~ņ~ncong~≇~ncongdot~⩭̸~ncup~⩂~ncy~н~neArr~⇗~nearhk~⤤~nearr~↗~nearrow~↗~nedot~≐̸~nequiv~≢~nesear~⤨~nesim~≂̸~nexist~∄~nexists~∄~nfr~𝔫~ngE~≧̸~nge~≱~ngeq~≱~ngeqq~≧̸~ngeqslant~⩾̸~nges~⩾̸~ngsim~≵~ngt~≯~ngtr~≯~nhArr~⇎~nharr~↮~nhpar~⫲~nis~⋼~nisd~⋺~niv~∋~njcy~њ~nlArr~⇍~nlE~≦̸~nlarr~↚~nldr~‥~nle~≰~nleftarrow~↚~nleftrightarrow~↮~nleq~≰~nleqq~≦̸~nleqslant~⩽̸~nles~⩽̸~nless~≮~nlsim~≴~nlt~≮~nltri~⋪~nltrie~⋬~nmid~∤~nopf~𝕟~notinE~⋹̸~notindot~⋵̸~notinva~∉~notinvb~⋷~notinvc~⋶~notni~∌~notniva~∌~notnivb~⋾~notnivc~⋽~npar~∦~nparallel~∦~nparsl~⫽⃥~npart~∂̸~npolint~⨔~npr~⊀~nprcue~⋠~npre~⪯̸~nprec~⊀~npreceq~⪯̸~nrArr~⇏~nrarr~↛~nrarrc~⤳̸~nrarrw~↝̸~nrightarrow~↛~nrtri~⋫~nrtrie~⋭~nsc~⊁~nsccue~⋡~nsce~⪰̸~nscr~𝓃~nshortmid~∤~nshortparallel~∦~nsim~≁~nsime~≄~nsimeq~≄~nsmid~∤~nspar~∦~nsqsube~⋢~nsqsupe~⋣~nsubE~⫅̸~nsube~⊈~nsubset~⊂⃒~nsubseteq~⊈~nsubseteqq~⫅̸~nsucc~⊁~nsucceq~⪰̸~nsup~⊅~nsupE~⫆̸~nsupe~⊉~nsupset~⊃⃒~nsupseteq~⊉~nsupseteqq~⫆̸~ntgl~≹~ntlg~≸~ntriangleleft~⋪~ntrianglelefteq~⋬~ntriangleright~⋫~ntrianglerighteq~⋭~num~#~numero~№~numsp~ ~nvDash~⊭~nvHarr~⤄~nvap~≍⃒~nvdash~⊬~nvge~≥⃒~nvgt~>⃒~nvinfin~⧞~nvlArr~⤂~nvle~≤⃒~nvlt~<⃒~nvltrie~⊴⃒~nvrArr~⤃~nvrtrie~⊵⃒~nvsim~∼⃒~nwArr~⇖~nwarhk~⤣~nwarr~↖~nwarrow~↖~nwnear~⤧~oS~Ⓢ~oast~⊛~ocir~⊚~ocy~о~odash~⊝~odblac~ő~odiv~⨸~odot~⊙~odsold~⦼~ofcir~⦿~ofr~𝔬~ogon~˛~ogt~⧁~ohbar~⦵~ohm~Ω~oint~∮~olarr~↺~olcir~⦾~olcross~⦻~olt~⧀~omacr~ō~omid~⦶~ominus~⊖~oopf~𝕠~opar~⦷~operp~⦹~orarr~↻~ord~⩝~order~ℴ~orderof~ℴ~origof~⊶~oror~⩖~orslope~⩗~orv~⩛~oscr~ℴ~osol~⊘~otimesas~⨶~ovbar~⌽~par~∥~parallel~∥~parsim~⫳~parsl~⫽~pcy~п~percnt~%~period~.~pertenk~‱~pfr~𝔭~phiv~ϕ~phmmat~ℳ~phone~☎~pitchfork~⋔~planck~ℏ~planckh~ℎ~plankv~ℏ~plus~+~plusacir~⨣~plusb~⊞~pluscir~⨢~plusdo~∔~plusdu~⨥~pluse~⩲~plussim~⨦~plustwo~⨧~pm~±~pointint~⨕~popf~𝕡~pr~≺~prE~⪳~prap~⪷~prcue~≼~pre~⪯~prec~≺~precapprox~⪷~preccurlyeq~≼~preceq~⪯~precnapprox~⪹~precneqq~⪵~precnsim~⋨~precsim~≾~primes~ℙ~prnE~⪵~prnap~⪹~prnsim~⋨~profalar~⌮~profline~⌒~profsurf~⌓~propto~∝~prsim~≾~prurel~⊰~pscr~𝓅~puncsp~ ~qfr~𝔮~qint~⨌~qopf~𝕢~qprime~⁗~qscr~𝓆~quaternions~ℍ~quatint~⨖~quest~?~questeq~≟~rAarr~⇛~rAtail~⤜~rBarr~⤏~rHar~⥤~race~∽̱~racute~ŕ~raemptyv~⦳~rangd~⦒~range~⦥~rangle~⟩~rarrap~⥵~rarrb~⇥~rarrbfs~⤠~rarrc~⤳~rarrfs~⤞~rarrhk~↪~rarrlp~↬~rarrpl~⥅~rarrsim~⥴~rarrtl~↣~rarrw~↝~ratail~⤚~ratio~∶~rationals~ℚ~rbarr~⤍~rbbrk~❳~rbrace~}~rbrack~]~rbrke~⦌~rbrksld~⦎~rbrkslu~⦐~rcaron~ř~rcedil~ŗ~rcub~}~rcy~р~rdca~⤷~rdldhar~⥩~rdquor~”~rdsh~↳~realine~ℛ~realpart~ℜ~reals~ℝ~rect~▭~rfisht~⥽~rfr~𝔯~rhard~⇁~rharu~⇀~rharul~⥬~rhov~ϱ~rightarrow~→~rightarrowtail~↣~rightharpoondown~⇁~rightharpoonup~⇀~rightleftarrows~⇄~rightleftharpoons~⇌~rightrightarrows~⇉~rightsquigarrow~↝~rightthreetimes~⋌~ring~˚~risingdotseq~≓~rlarr~⇄~rlhar~⇌~rmoust~⎱~rmoustache~⎱~rnmid~⫮~roang~⟭~roarr~⇾~robrk~⟧~ropar~⦆~ropf~𝕣~roplus~⨮~rotimes~⨵~rpar~)~rpargt~⦔~rppolint~⨒~rrarr~⇉~rscr~𝓇~rsh~↱~rsqb~]~rsquor~’~rthree~⋌~rtimes~⋊~rtri~▹~rtrie~⊵~rtrif~▸~rtriltri~⧎~ruluhar~⥨~rx~℞~sacute~ś~sc~≻~scE~⪴~scap~⪸~sccue~≽~sce~⪰~scedil~ş~scirc~ŝ~scnE~⪶~scnap~⪺~scnsim~⋩~scpolint~⨓~scsim~≿~scy~с~sdotb~⊡~sdote~⩦~seArr~⇘~searhk~⤥~searr~↘~searrow~↘~semi~;~seswar~⤩~setminus~∖~setmn~∖~sext~✶~sfr~𝔰~sfrown~⌢~sharp~♯~shchcy~щ~shcy~ш~shortmid~∣~shortparallel~∥~sigmav~ς~simdot~⩪~sime~≃~simeq~≃~simg~⪞~simgE~⪠~siml~⪝~simlE~⪟~simne~≆~simplus~⨤~simrarr~⥲~slarr~←~smallsetminus~∖~smashp~⨳~smeparsl~⧤~smid~∣~smile~⌣~smt~⪪~smte~⪬~smtes~⪬︀~softcy~ь~sol~/~solb~⧄~solbar~⌿~sopf~𝕤~spadesuit~♠~spar~∥~sqcap~⊓~sqcaps~⊓︀~sqcup~⊔~sqcups~⊔︀~sqsub~⊏~sqsube~⊑~sqsubset~⊏~sqsubseteq~⊑~sqsup~⊐~sqsupe~⊒~sqsupset~⊐~sqsupseteq~⊒~squ~□~square~□~squarf~▪~squf~▪~srarr~→~sscr~𝓈~ssetmn~∖~ssmile~⌣~sstarf~⋆~star~☆~starf~★~straightepsilon~ϵ~straightphi~ϕ~strns~¯~subE~⫅~subdot~⪽~subedot~⫃~submult~⫁~subnE~⫋~subne~⊊~subplus~⪿~subrarr~⥹~subset~⊂~subseteq~⊆~subseteqq~⫅~subsetneq~⊊~subsetneqq~⫋~subsim~⫇~subsub~⫕~subsup~⫓~succ~≻~succapprox~⪸~succcurlyeq~≽~succeq~⪰~succnapprox~⪺~succneqq~⪶~succnsim~⋩~succsim~≿~sung~♪~supE~⫆~supdot~⪾~supdsub~⫘~supedot~⫄~suphsol~⟉~suphsub~⫗~suplarr~⥻~supmult~⫂~supnE~⫌~supne~⊋~supplus~⫀~supset~⊃~supseteq~⊇~supseteqq~⫆~supsetneq~⊋~supsetneqq~⫌~supsim~⫈~supsub~⫔~supsup~⫖~swArr~⇙~swarhk~⤦~swarr~↙~swarrow~↙~swnwar~⤪~target~⌖~tbrk~⎴~tcaron~ť~tcedil~ţ~tcy~т~tdot~⃛~telrec~⌕~tfr~𝔱~therefore~∴~thetav~ϑ~thickapprox~≈~thicksim~∼~thkap~≈~thksim~∼~timesb~⊠~timesbar~⨱~timesd~⨰~tint~∭~toea~⤨~top~⊤~topbot~⌶~topcir~⫱~topf~𝕥~topfork~⫚~tosa~⤩~tprime~‴~triangle~▵~triangledown~▿~triangleleft~◃~trianglelefteq~⊴~triangleq~≜~triangleright~▹~trianglerighteq~⊵~tridot~◬~trie~≜~triminus~⨺~triplus~⨹~trisb~⧍~tritime~⨻~trpezium~⏢~tscr~𝓉~tscy~ц~tshcy~ћ~tstrok~ŧ~twixt~≬~twoheadleftarrow~↞~twoheadrightarrow~↠~uHar~⥣~ubrcy~ў~ubreve~ŭ~ucy~у~udarr~⇅~udblac~ű~udhar~⥮~ufisht~⥾~ufr~𝔲~uharl~↿~uharr~↾~uhblk~▀~ulcorn~⌜~ulcorner~⌜~ulcrop~⌏~ultri~◸~umacr~ū~uogon~ų~uopf~𝕦~uparrow~↑~updownarrow~↕~upharpoonleft~↿~upharpoonright~↾~uplus~⊎~upsi~υ~upuparrows~⇈~urcorn~⌝~urcorner~⌝~urcrop~⌎~uring~ů~urtri~◹~uscr~𝓊~utdot~⋰~utilde~ũ~utri~▵~utrif~▴~uuarr~⇈~uwangle~⦧~vArr~⇕~vBar~⫨~vBarv~⫩~vDash~⊨~vangrt~⦜~varepsilon~ϵ~varkappa~ϰ~varnothing~∅~varphi~ϕ~varpi~ϖ~varpropto~∝~varr~↕~varrho~ϱ~varsigma~ς~varsubsetneq~⊊︀~varsubsetneqq~⫋︀~varsupsetneq~⊋︀~varsupsetneqq~⫌︀~vartheta~ϑ~vartriangleleft~⊲~vartriangleright~⊳~vcy~в~vdash~⊢~vee~∨~veebar~⊻~veeeq~≚~vellip~⋮~verbar~|~vert~|~vfr~𝔳~vltri~⊲~vnsub~⊂⃒~vnsup~⊃⃒~vopf~𝕧~vprop~∝~vrtri~⊳~vscr~𝓋~vsubnE~⫋︀~vsubne~⊊︀~vsupnE~⫌︀~vsupne~⊋︀~vzigzag~⦚~wcirc~ŵ~wedbar~⩟~wedge~∧~wedgeq~≙~wfr~𝔴~wopf~𝕨~wp~℘~wr~≀~wreath~≀~wscr~𝓌~xcap~⋂~xcirc~◯~xcup~⋃~xdtri~▽~xfr~𝔵~xhArr~⟺~xharr~⟷~xlArr~⟸~xlarr~⟵~xmap~⟼~xnis~⋻~xodot~⨀~xopf~𝕩~xoplus~⨁~xotime~⨂~xrArr~⟹~xrarr~⟶~xscr~𝓍~xsqcup~⨆~xuplus~⨄~xutri~△~xvee~⋁~xwedge~⋀~yacy~я~ycirc~ŷ~ycy~ы~yfr~𝔶~yicy~ї~yopf~𝕪~yscr~𝓎~yucy~ю~zacute~ź~zcaron~ž~zcy~з~zdot~ż~zeetrf~ℨ~zfr~𝔷~zhcy~ж~zigrarr~⇝~zopf~𝕫~zscr~𝓏~~AMP~&~COPY~©~GT~>~LT~<~QUOT~"~REG~®',pe.html4);var Po={0:65533,128:8364,130:8218,131:402,132:8222,133:8230,134:8224,135:8225,136:710,137:8240,138:352,139:8249,140:338,142:381,145:8216,146:8217,147:8220,148:8221,149:8226,150:8211,151:8212,152:732,153:8482,154:353,155:8250,156:339,158:382,159:376},Io=String.fromCodePoint||function(t){return String.fromCharCode(Math.floor((t-65536)/1024)+55296,(t-65536)%1024+56320)},me=function(){return me=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},me.apply(this,arguments)},No=me(me({},pe),{all:pe.html5}),Lo={scope:"body",level:"all"},wt=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g,St=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g,jr={xml:{strict:wt,attribute:St,body:bt.xml},html4:{strict:wt,attribute:St,body:bt.html4},html5:{strict:wt,attribute:St,body:bt.html5}},qo=me(me({},jr),{all:jr.html5}),qn=String.fromCharCode,_o=qn(65533);function Do(t,e,r,n){var i=t,s=t[t.length-1];if(r&&s==="=")i=t;else if(n&&s!==";")i=t;else{var o=e[t];if(o)i=o;else if(t[0]==="&"&&t[1]==="#"){var a=t[2],c=a=="x"||a=="X"?parseInt(t.substr(3),16):parseInt(t.substr(2));i=c>=1114111?_o:c>65535?Io(c):qn(Po[c]||c)}}return i}function Mr(t,e){var r=e===void 0?Lo:e,n=r.level,i=n===void 0?"all":n,s=r.scope,o=s===void 0?i==="xml"?"strict":"body":s;if(!t)return"";var a=qo[i][o],c=No[i].entities,l=o==="attribute",d=o==="strict";return t.replace(a,function(u){return Do(u,c,l,d)})}var $o={strictlyTwoElementsInRangeArrays:!1,progressFn:null};function tt(t,e){if(!Array.isArray(t)||!t.length)return t;let r={...$o,...e},n,i;if(r.strictlyTwoElementsInRangeArrays&&!t.every((a,c)=>!Array.isArray(a)||a.length!==2?(n=c,i=a.length,!1):!0))throw new TypeError(`ranges-sort: [THROW_ID_03] The first argument should be an array and must consist of arrays which are natural number indexes representing TWO string index ranges. However, ${n}th range (${JSON.stringify(t[n],null,4)}) has not two but ${i} elements!`);if(!t.every((a,c)=>!Array.isArray(a)||!Number.isInteger(a[0])||a[0]<0||!Number.isInteger(a[1])||a[1]<0?(n=c,!1):!0))throw new TypeError(`ranges-sort: [THROW_ID_04] The first argument should be an array and must consist of arrays which are natural number indexes representing string index ranges. However, ${n}th range (${JSON.stringify(t[n],null,4)}) does not consist of only natural numbers!`);let s=t.length**2,o=0;return Array.from(t).sort((a,c)=>(r.progressFn&&(o+=1,r.progressFn(Math.floor(o*100/s))),a[0]===c[0]?a[1]<c[1]?-1:a[1]>c[1]?1:0:a[0]<c[0]?-1:1))}var Fr={mergeType:1,progressFn:null,joinRangesThatTouchEdges:!0};function Uo(t,e){function r(l){return!!l&&typeof l=="object"&&!Array.isArray(l)}if(!Array.isArray(t)||!t.length)return null;let n;if(e)if(r(e)){if(n={...Fr,...e},n.progressFn&&r(n.progressFn)&&!Object.keys(n.progressFn).length)n.progressFn=null;else if(n.progressFn&&typeof n.progressFn!="function")throw new Error(`ranges-merge: [THROW_ID_01] opts.progressFn must be a function! It was given of a type: "${typeof n.progressFn}", equal to ${JSON.stringify(n.progressFn,null,4)}`);if(![1,2,"1","2"].includes(n.mergeType))throw new Error(`ranges-merge: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof n.mergeType}", equal to ${JSON.stringify(n.mergeType,null,4)}`);if(typeof n.joinRangesThatTouchEdges!="boolean")throw new Error(`ranges-merge: [THROW_ID_04] opts.joinRangesThatTouchEdges was customised to a wrong thing! It was given of a type: "${typeof n.joinRangesThatTouchEdges}", equal to ${JSON.stringify(n.joinRangesThatTouchEdges,null,4)}`)}else throw new Error(`emlint: [THROW_ID_03] the second input argument must be a plain object. It was given as:
|
|
2
|
+
${JSON.stringify(e,null,4)} (type ${typeof e})`);else n={...Fr};let i=t.filter(l=>Array.isArray(l)).map(l=>[...l]).filter(l=>l[2]!==void 0||l[0]!==l[1]),s,o,a;n.progressFn?s=tt(i,{progressFn:l=>{a=Math.floor(l/5),a!==o&&(o=a,n.progressFn(a))}}):s=tt(i);let c=s.length-1;for(let l=c;l>0;l--)n.progressFn&&(a=Math.floor((1-l/c)*78)+21,a!==o&&a>o&&(o=a,n.progressFn(a))),(s[l][0]<=s[l-1][0]||!n.joinRangesThatTouchEdges&&s[l][0]<s[l-1][1]||n.joinRangesThatTouchEdges&&s[l][0]<=s[l-1][1])&&(s[l-1][0]=Math.min(s[l][0],s[l-1][0]),s[l-1][1]=Math.max(s[l][1],s[l-1][1]),s[l][2]!==void 0&&(s[l-1][0]>=s[l][0]||s[l-1][1]<=s[l][1])&&s[l-1][2]!==null&&(s[l][2]===null&&s[l-1][2]!==null?s[l-1][2]=null:s[l-1][2]!=null?+n.mergeType==2&&s[l-1][0]===s[l][0]?s[l-1][2]=s[l][2]:s[l-1][2]+=s[l][2]:s[l-1][2]=s[l][2]),s.splice(l,1),l=s.length);return s.length?s:null}var Bo={},Vo=Bo.NODE_ENV==="production",Hr="Invariant failed";function zo(t,e){if(!t){if(Vo)throw new Error(Hr);var r=Hr;throw new Error(r)}}function jo(t,e,r){if(arguments.length===0)throw new Error("ranges-apply: [THROW_ID_01] inputs missing!");if(typeof t!="string")throw new TypeError(`ranges-apply: [THROW_ID_02] first input argument must be a string! Currently it's: ${typeof t}, equal to: ${JSON.stringify(t,null,4)}`);if(e&&!Array.isArray(e))throw new TypeError(`ranges-apply: [THROW_ID_03] second input argument must be an array (or null)! Currently it's: ${typeof e}, equal to: ${JSON.stringify(e,null,4)}`);if(!e?.filter(o=>o).length)return t;let n;Array.isArray(e)&&Number.isInteger(e[0])&&Number.isInteger(e[1])?n=[Array.from(e)]:n=Array.from(e),n.length,n.filter(o=>o).forEach((o,a)=>{if(!Array.isArray(o))throw new TypeError(`ranges-apply: [THROW_ID_05] ranges array, second input arg., has ${a}th element not an array: ${JSON.stringify(o,null,4)}, which is ${typeof o}`);if(!Number.isInteger(o[0])){if(!Number.isInteger(+o[0])||+o[0]<0)throw new TypeError(`ranges-apply: [THROW_ID_06] ranges array, second input arg. has ${a}th element, array ${JSON.stringify(o,null,0)}. Its first element is not an integer, string index, but ${typeof o[0]}, equal to: ${JSON.stringify(o[0],null,4)}.`);n[a][0]=+n[a][0]}if(!Number.isInteger(o[1])){if(!Number.isInteger(+o[1])||+o[1]<0)throw new TypeError(`ranges-apply: [THROW_ID_07] ranges array, second input arg. has ${a}th element, array ${JSON.stringify(o,null,0)}. Its second element is not an integer, string index, but ${typeof o[1]}, equal to: ${JSON.stringify(o[1],null,4)}.`);n[a][1]=+n[a][1]}});let i=Uo(n,{progressFn:o=>{}});zo(i);let s=i.length;if(s>0){let o=t.slice(i[s-1][1]);t=i.reduce((a,c,l,d)=>{let u=l===0?0:d[l-1][1],g=d[l][0];return`${a}${t.slice(u,g)}${d[l][2]||""}`},""),t+=o}return t}function kt(t,e=1){let r=" ";function n(s){return Array.from(s).reverse().join("")}function i(s,o,a){let c=a?`
|
|
3
3
|
`:"\r",l=a?"\r":`
|
|
4
4
|
`;if(!s)return s;let d=0,u="";for(let g=0,f=s.length;g<f;g++)(s[g]===c||s[g]===l&&s[g-1]!==c)&&d++,`\r
|
|
5
|
-
`.includes(s[g])||s[g]===
|
|
6
|
-
${JSON.stringify(e,null,4)} (type ${typeof e})`);else
|
|
7
|
-
${JSON.stringify(
|
|
8
|
-
\r`.includes(t[e+1])||
|
|
9
|
-
\r`.includes(t[e+2])||
|
|
10
|
-
\r`.includes(t[i])||
|
|
11
|
-
`)&&
|
|
12
|
-
`:
|
|
5
|
+
`.includes(s[g])||s[g]===r?s[g]===r?u+=s[g]:s[g]===c?d<=o&&(u+=s[g],s[g+1]===l&&(u+=s[g+1],g++)):s[g]===l&&s?.[g-1]!==c&&d<=o&&(u+=s[g]):!s[g+1]&&!d&&(u+=" ");return u}if(typeof t=="string"&&t.length){let s=1;typeof+e=="number"&&Number.isInteger(+e)&&+e>=0&&(s=+e);let o="",a="";if(!t.trim())o=t;else if(!t[0].trim()){for(let c=0,l=t.length;c<l;c++)if(t[c].trim()){o=t.slice(0,c);break}}if(t.trim()&&(t.slice(-1).trim()===""||t.slice(-1)===r)){for(let c=t.length;c--;)if(t[c].trim()){a=t.slice(c+1);break}}return`${i(o,s,!1)}${t.trim()}${n(i(n(a),s,!0))}`}return t}var Wr={mergeType:1,progressFn:null,joinRangesThatTouchEdges:!0};function Mo(t,e){function r(l){return!!l&&typeof l=="object"&&!Array.isArray(l)}if(!Array.isArray(t)||!t.length)return null;let n;if(e)if(r(e)){if(n={...Wr,...e},n.progressFn&&r(n.progressFn)&&!Object.keys(n.progressFn).length)n.progressFn=null;else if(n.progressFn&&typeof n.progressFn!="function")throw new Error(`ranges-merge: [THROW_ID_01] resolvedOpts.progressFn must be a function! It was given of a type: "${typeof n.progressFn}", equal to ${JSON.stringify(n.progressFn,null,4)}`);if(![1,2,"1","2"].includes(n.mergeType))throw new Error(`ranges-merge: [THROW_ID_02] resolvedOpts.mergeType was customised to a wrong thing! It was given of a type: "${typeof n.mergeType}", equal to ${JSON.stringify(n.mergeType,null,4)}`);if(typeof n.joinRangesThatTouchEdges!="boolean")throw new Error(`ranges-merge: [THROW_ID_04] resolvedOpts.joinRangesThatTouchEdges was customised to a wrong thing! It was given of a type: "${typeof n.joinRangesThatTouchEdges}", equal to ${JSON.stringify(n.joinRangesThatTouchEdges,null,4)}`)}else throw new Error(`ranges-merge: [THROW_ID_03] the second input argument must be a plain object. It was given as:
|
|
6
|
+
${JSON.stringify(e,null,4)} (type ${typeof e})`);else n={...Wr};let i=t.filter(l=>Array.isArray(l)).map(l=>[...l]).filter(l=>l[2]!==void 0||l[0]!==l[1]),s,o,a;n.progressFn?s=tt(i,{progressFn:l=>{a=Math.floor(l/5),a!==o&&(o=a,n.progressFn!=null&&n.progressFn(a))}}):s=tt(i);let c=s.length-1;for(let l=c;l>0;l--)n.progressFn&&(a=Math.floor((1-l/c)*78)+21,a!==o&&a>o&&(o=a,n.progressFn(a))),(s[l][0]<=s[l-1][0]||!n.joinRangesThatTouchEdges&&s[l][0]<s[l-1][1]||n.joinRangesThatTouchEdges&&s[l][0]<=s[l-1][1])&&(s[l-1][0]=Math.min(s[l][0],s[l-1][0]),s[l-1][1]=Math.max(s[l][1],s[l-1][1]),s[l][2]!==void 0&&(s[l-1][0]>=s[l][0]||s[l-1][1]<=s[l][1])&&s[l-1][2]!==null&&(s[l][2]===null&&s[l-1][2]!==null?s[l-1][2]=null:s[l-1][2]!=null?+(n||{})?.mergeType==2&&s[l-1][0]===s[l][0]?s[l-1][2]=s[l][2]:s[l-1][2]+=s[l][2]:s[l-1][2]=s[l][2]),s.splice(l,1),l=s.length);return s.length?s:null}var Fo={limitToBeAddedWhitespace:!1,limitLinebreaksCount:1,mergeType:1},Ho=class{constructor(e){let r={...Fo,...e};if(r.mergeType&&r.mergeType!==1&&r.mergeType!==2)if(ne(r.mergeType)&&r.mergeType.trim()==="1")r.mergeType=1;else if(ne(r.mergeType)&&r.mergeType.trim()==="2")r.mergeType=2;else throw new Error(`ranges-push: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof r.mergeType}", equal to ${JSON.stringify(r.mergeType,null,4)}`);this.opts=r,this.ranges=[]}ranges;opts;add(e,r,n){if(e==null&&r==null)return;if(G(e)&&!G(r)){if(Array.isArray(e)){if(e.length){if(e.some(o=>Array.isArray(o))){e.forEach(o=>{Array.isArray(o)&&this.add(...o)});return}e.length&&ee(+e[0])&&ee(+e[1])&&this.add(...e)}return}throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_12] the first input argument, "from" is set (${JSON.stringify(e,null,0)}) but second-one, "to" is not (${JSON.stringify(r,null,0)})`)}else if(!G(e)&&G(r))throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_13] the second input argument, "to" is set (${JSON.stringify(r,null,0)}) but first-one, "from" is not (${JSON.stringify(e,null,0)})`);let i=+e,s=+r;if(ee(i)&&ee(s)){if(G(n)&&!ne(n)&&!bs(n))throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_08] The third argument, the value to add, was given not as string but ${typeof n}, equal to:
|
|
7
|
+
${JSON.stringify(n,null,4)}`);if(G(this.ranges)&&Array.isArray(this.last())&&i===this.last()[1]){if(this.last()[1]=s,this.last()[2],this.last()[2]!==null&&G(n)){let o=this.last()[2]&&this.last()[2].length&&(!this.opts?.mergeType||this.opts.mergeType===1)?`${this.last()[2]}${n}`:n;this.opts.limitToBeAddedWhitespace&&(o=kt(o,this.opts.limitLinebreaksCount)),ne(o)&&!o.length||(this.last()[2]=o)}}else{this.ranges||(this.ranges=[]);let o=n!==void 0&&!(ne(n)&&!n.length)?[i,s,n&&this.opts.limitToBeAddedWhitespace?kt(n,this.opts.limitLinebreaksCount):n]:[i,s];this.ranges.push(o)}}else throw ee(i)&&i>=0?new TypeError(`ranges-push/Ranges/add(): [THROW_ID_10] "to" value, the second input argument, must be a natural number or zero! Currently it's of a type "${typeof s}" equal to: ${JSON.stringify(s,null,4)}`):new TypeError(`ranges-push/Ranges/add(): [THROW_ID_09] "from" value, the first input argument, must be a natural number or zero! Currently it's of a type "${typeof i}" equal to: ${JSON.stringify(i,null,4)}`)}push(e,r,n){this.add(e,r,n)}current(){return Array.isArray(this.ranges)&&this.ranges.length?(this.ranges=Mo(this.ranges,{mergeType:this.opts.mergeType}),this.ranges&&this.opts.limitToBeAddedWhitespace?this.ranges.map(e=>G(e[2])?[e[0],e[1],kt(e[2],this.opts.limitLinebreaksCount)]:e):this.ranges):null}wipe(){this.ranges=[]}replace(e){if(Array.isArray(e)&&e.length)if(Array.isArray(e[0])&&ee(e[0][0]))this.ranges=Array.from(e);else throw new Error(`ranges-push/Ranges/replace(): [THROW_ID_11] Single range was given but we expected array of arrays! The first element, ${JSON.stringify(e[0],null,4)} should be an array and its first element should be an integer, a string index.`);else this.ranges=[]}last(){return Array.isArray(this.ranges)&&this.ranges.length?this.ranges[this.ranges.length-1]:null}};Sn();var xt=" ";function Wo({str:t,idx:e=0,stopAtNewlines:r=!1,stopAtRawNbsp:n=!1}){if(typeof t!="string"||!t.length||((!e||typeof e!="number")&&(e=0),!t[e+1]))return null;if(t[e+1]&&(t[e+1].trim()||r&&`
|
|
8
|
+
\r`.includes(t[e+1])||n&&t[e+1]===xt))return e+1;if(t[e+2]&&(t[e+2].trim()||r&&`
|
|
9
|
+
\r`.includes(t[e+2])||n&&t[e+2]===xt))return e+2;for(let i=e+1,s=t.length;i<s;i++)if(t[i].trim()||r&&`
|
|
10
|
+
\r`.includes(t[i])||n&&t[i]===xt)return i;return null}function B(t,e=0){return Wo({str:t,idx:e,stopAtNewlines:!1,stopAtRawNbsp:!1})}function Go(t){return/[-_A-Za-z0-9]/.test(t)}function Gr(t,e){if(!t)return[];if(Array.isArray(t))return t.filter(r=>typeof r=="string"&&r.trim());if(typeof t=="string")return t.trim()?[t]:[];throw new TypeError(`string-strip-html/stripHtml(): [THROW_ID_05] ${e} must be array containing zero or more strings or something falsey. Currently it's equal to: ${t}, that a type of ${typeof t}.`)}function Me(t,e,r,n){for(let i=e,s=t.length;i<s;i++){if(t.startsWith(r,i))return!0;if(t.startsWith(n,i))return!1}return!1}function Kr(t,e,r){return t?.quotes,t?.quotes?.value&&Me(e,r+1,t.quotes.value,">"),t?.quotes?.next,Me(e,t?.quotes?.next-1,t?.quotes?.value,">"),!t?.quotes||!Me(e,r+1,t.quotes.value,">")&&t?.quotes?.next!==-1&&Me(e,t?.quotes?.next-1,t?.quotes?.value,">")}function Ko(t,e){return(e.match(new RegExp(t,"g"))||[]).length}var Ae=new Set(["!doctype","abbr","address","area","article","aside","audio","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","doctype","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","math","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","param","picture","pre","progress","rb","rp","rt","rtc","ruby","samp","script","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","ul","var","video","wbr","xml"]),Et=new Set(["a","b","i","p","q","s","u"]),Ct=new Set([".",",",";","!","?"]),Jr=new Set([".",",","?",";",")","…",'"',"»"]),Jo=new Set(["a","abbr","acronym","audio","b","bdi","bdo","big","button","canvas","cite","code","data","datalist","del","dfn","em","embed","i","iframe","input","ins","kbd","label","map","mark","meter","noscript","object","output","picture","progress","q","ruby","s","samp","select","slot","small","span","strong","sub","sup","svg","template","textarea","time","u","tt","var","video","wbr"]),Qr={ignoreTags:[],ignoreTagsWithTheirContents:[],onlyStripTags:[],stripTogetherWithTheirContents:["script","style","xml"],skipHtmlDecoding:!1,trimOnlySpaces:!1,stripRecognisedHTMLOnly:!1,dumpLinkHrefsNearby:{enabled:!1,putOnNewLine:!1,wrapHeads:"",wrapTails:""},ignoreIndentations:!1,cb:null,reportProgressFunc:null,reportProgressFuncFrom:0,reportProgressFuncTo:100};function _n(t,e){let r=Date.now(),n=[],i=[],s=[],o=[],a={};function c(){a={attributes:[]}}c();let l=null,d=null,u=null,g=!1,f={},y={tagName:"",hrefValue:"",openingTagEnds:void 0},m="",p=!1,w=null,E=!0;function x(h,b,k){if(Array.isArray(b.stripTogetherWithTheirContents)&&(b.stripTogetherWithTheirContents.includes(a.name)||b.stripTogetherWithTheirContents.includes("*")))if(a.slashPresent&&Array.isArray(n)&&n.some(S=>S.name===a.name)){for(let S=n.length;S--;)if(n[S].name===a.name){o=o.filter(([T,N])=>(T<n[S].lastOpeningBracketAt||T>=h+1)&&(N<=n[S].lastOpeningBracketAt||N>h+1));let O=h+1;a.lastClosingBracketAt&&(O=a.lastClosingBracketAt+1),o.push([n[S].lastOpeningBracketAt,O]),Jr.has(t[h])&&b.cb?b.cb({tag:a,deleteFrom:n[S].lastOpeningBracketAt,deleteTo:h+1,insert:null,rangesArr:k,proposedReturn:[n[S].lastOpeningBracketAt,h,null]}):b.cb&&b.cb({tag:a,deleteFrom:n[S].lastOpeningBracketAt,deleteTo:h,insert:"",rangesArr:k,proposedReturn:[n[S].lastOpeningBracketAt,h,""]}),n.splice(S,1);break}}else a.slashPresent||n.push(a);else Array.isArray(b.ignoreTagsWithTheirContents)&&Se(h,b,a)&&(E=!1)}function R(h,b,k,S,O,T){if(Array.isArray(A.current())&&typeof k=="number"&&A.current()[0][0]===0&&A.current()[0][1]>=k)return"";if(t.length===S&&T&&!v?.dumpLinkHrefsNearby?.enabled)return null;let N="";if(Number.isInteger(k)&&k<O&&(N+=h.slice(k,O)),Number.isInteger(S)&&S>T+1){let V=h.slice(T+1,S);S&&!B(t,S-1)&&(V=V.trimEnd()),V.includes(`
|
|
11
|
+
`)&&q(S,h)?N+=" ":N+=V}let Y=!Jr.has(h[b]),Ar=h[S-1]!==">"||!h[k].trim(),Tr=!['"',"("].includes(h[O-1]),Vi=![";",".",":","!"].includes(h[b]);if((Y||Ar&&Tr&&Vi)&&(Ar||Tr)&&h[b]!=="!"&&(!Jo.has(a.name)||typeof k=="number"&&k<O||typeof S=="number"&&S>T+1)){let V=N.match(/\n/g);return Array.isArray(V)&&V.length?V.length===1?`
|
|
12
|
+
`:V.length===2?`
|
|
13
13
|
|
|
14
14
|
`:`
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
`:" "}return""}function I(h,
|
|
17
|
+
`:" "}return""}function I(h,b){if(h.dumpLinkHrefsNearby?.enabled&&y.tagName&&y.tagName===a.name&&a.lastOpeningBracketAt&&(y.openingTagEnds&&a.lastOpeningBracketAt>y.openingTagEnds||!y.openingTagEnds)&&(p=!0),p){let k=h.dumpLinkHrefsNearby?.putOnNewLine?`
|
|
18
18
|
|
|
19
|
-
`:"";
|
|
20
|
-
${JSON.stringify(t,null,4)}`);if(e)if(
|
|
21
|
-
${JSON.stringify(e,null,4)}`);function
|
|
22
|
-
`.includes(t[h])){let
|
|
19
|
+
`:"";m=`${k}${y.hrefValue}`,(typeof b!="number"||B(t,b-1))&&(m+=k)}}function q(h,b){return b?b[h]==="<"&&b[h+1]!=="%":t[h]==="<"&&t[h+1]!=="%"}function U(h){return t[h]===">"&&t[h-1]!=="%"}function Se(h,b,k){if(b.ignoreTagsWithTheirContents.includes("*"))return!0;let S=t.indexOf(`<${k.name}`,h),O=t.indexOf(`</${k.name}`,h);return!k.slashPresent&&O===-1||k.slashPresent&&!i.some(T=>T.name===k.name)||O>-1&&S>-1&&S<O?!1:b.ignoreTagsWithTheirContents.includes(k.name)}if(typeof t!="string")throw new TypeError(`string-strip-html/stripHtml(): [THROW_ID_01] Input must be string! Currently it's: ${(typeof t).toLowerCase()}, equal to:
|
|
20
|
+
${JSON.stringify(t,null,4)}`);if(e)if(zt(e)){if(e.reportProgressFunc&&typeof e.reportProgressFunc!="function")throw new Error(`string-strip-html/stripHtml(): [THROW_ID_03] The Optional Options Object's key reportProgressFunc, callback function, should be a function but it was given as type ${typeof e.reportProgressFunc}, equal to ${JSON.stringify(e.reportProgressFunc,null,4)}`);if(typeof e.dumpLinkHrefsNearby=="boolean"&&e.dumpLinkHrefsNearby!=null)throw new Error(`string-strip-html/stripHtml(): [THROW_ID_04] The Optional Options Object's key should be a plain object but it was given as type ${typeof e.dumpLinkHrefsNearby}, equal to ${JSON.stringify(e.dumpLinkHrefsNearby,null,4)}`)}else throw new TypeError(`string-strip-html/stripHtml(): [THROW_ID_02] Optional Options Object must be a plain object! Currently it's: ${(typeof e).toLowerCase()}, equal to:
|
|
21
|
+
${JSON.stringify(e,null,4)}`);function ke(){p&&(y={tagName:"",hrefValue:"",openingTagEnds:void 0},p=!1)}let v={...Qr,...e,dumpLinkHrefsNearby:Object.assign({},Qr.dumpLinkHrefsNearby,e?.dumpLinkHrefsNearby)};if(ws(v,"returnRangesOnly"))throw new TypeError("string-strip-html/stripHtml(): [THROW_ID_05] The Optional Options Object's key returnRangesOnly has been removed from the API since v.5 release.");if(v.reportProgressFunc){if(typeof v.reportProgressFuncFrom!="number")throw new Error(`string-strip-html/stripHtml(): [THROW_ID_06] The Optional Options Object's key reportProgressFuncFrom, callback function's "from" range, should be a number but it was given as type ${typeof v.reportProgressFuncFrom}, equal to ${JSON.stringify(v.reportProgressFuncFrom,null,4)}`);if(typeof v.reportProgressFuncTo!="number")throw new Error(`string-strip-html/stripHtml(): [THROW_ID_07] The Optional Options Object's key reportProgressFuncTo, callback function's "to" range, should be a number but it was given as type ${typeof v.reportProgressFuncTo}, equal to ${JSON.stringify(v.reportProgressFuncTo,null,4)}`)}v.ignoreTags=Gr(v.ignoreTags,"resolvedOpts.ignoreTags"),v.onlyStripTags=Gr(v.onlyStripTags,"resolvedOpts.onlyStripTags");let Er=!!v.onlyStripTags.length;v.onlyStripTags.length&&v.ignoreTags.length&&(v.onlyStripTags=To(v.onlyStripTags,...v.ignoreTags)),v.stripTogetherWithTheirContents?typeof v.stripTogetherWithTheirContents=="string"&&v.stripTogetherWithTheirContents.length&&(v.stripTogetherWithTheirContents=[v.stripTogetherWithTheirContents]):v.stripTogetherWithTheirContents=[];let xe={};if(v.stripTogetherWithTheirContents&&Array.isArray(v.stripTogetherWithTheirContents)&&v.stripTogetherWithTheirContents.length&&!v.stripTogetherWithTheirContents.every((h,b)=>typeof h!="string"?(xe.el=h,xe.i=b,!1):!0))throw new TypeError(`string-strip-html/stripHtml(): [THROW_ID_08] Optional Options Object's key stripTogetherWithTheirContents was set to contain not just string elements! For example, element at index ${xe.i} has a value ${xe.el} which is not string but ${(typeof xe.el).toLowerCase()}.`);v.cb||(v.cb=({rangesArr:h,proposedReturn:b})=>{b&&h.push(...b)});let A=new Ho({limitToBeAddedWhitespace:!0,limitLinebreaksCount:2});if(!v.skipHtmlDecoding)for(;t!==Mr(t,{scope:"strict"});)t=Mr(t,{scope:"strict"});let J=!1,H=!1,je=0,Cr=0,D=t.length,Bi=Math.floor(D/2);for(let h=0;h<D;h++){if(v.reportProgressFunc&&(D>1e3&&D<2e3?h===Bi&&v.reportProgressFunc(Math.floor((v.reportProgressFuncTo-v.reportProgressFuncFrom)/2)):D>=2e3&&(je=v.reportProgressFuncFrom+Math.floor(h/D*(v.reportProgressFuncTo-v.reportProgressFuncFrom)),je!==Cr&&(Cr=je,v.reportProgressFunc(je)))),Object.keys(a).length>1&&a.lastClosingBracketAt&&a.lastClosingBracketAt<h&&t[h]!==" "&&w===null&&(w=h),!J&&t[h]==="%"&&t[h-1]==="{"&&t.includes("%}",h+1)){u=null;let b=t.indexOf("%}",h)-1;if(b>h){h=b;continue}}if(!J&&U(h)&&(!a||Object.keys(a).length<2)&&h>1){for(let b=h;b--;)if(t[b-1]===void 0||U(b)){let k=t[b-1]===void 0?b:b+1,S=t.slice(k,h+1)||"";if((S.includes("/>")||S.includes("/ >")||S.includes('="')||S.includes("='"))&&t!==`<${zr(S.trim(),"/>")}>`&&[...Ae].some(O=>zr(S.trim().split(/\s+/).filter(T=>T.trim()).filter((T,N)=>N===0),"/>").toLowerCase()===O)&&_n(`<${S.trim()}>`,v).result===""){(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([k,h+1]),(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([k,h+1]);let O=R(t,h,k,h+1,k,h+1),T=h+1;if(t[T]&&!t[T].trim()){for(let N=T;N<D;N++)if(t[N].trim()){T=N;break}}v.cb({tag:a,deleteFrom:k,deleteTo:T,insert:O,rangesArr:A,proposedReturn:[k,T,O]})}break}}if(!H&&t[h]==="/"&&!a.quotes?.value&&Number.isInteger(a.lastOpeningBracketAt)&&!Number.isInteger(a.lastClosingBracketAt)&&(a.slashPresent=h),t[h]==='"'||t[h]==="'")if(!H&&a.nameStarts&&a?.quotes?.value===t[h])if(f.valueStarts===void 0)f={},delete a.quotes;else{f.valueEnds=h,f.value=t.slice(f.valueStarts,h),a.attributes.push(f),f={},delete a.quotes;let b;v.dumpLinkHrefsNearby?.enabled&&!n.length&&a.attributes.some(k=>{if(typeof k.name=="string"&&k.name.toLowerCase()==="href")return b=`${v.dumpLinkHrefsNearby?.wrapHeads||""}${k.value}${v.dumpLinkHrefsNearby?.wrapTails||""}`,!0})&&(y={tagName:a.name,hrefValue:b,openingTagEnds:void 0})}else!H&&!a.quotes&&a.nameStarts&&(a.quotes={},a.quotes.value=t[h],a.quotes.start=h,a.quotes.next=t.indexOf(t[h],h+1),f.nameStarts&&f.nameEnds&&f.nameEnds<h&&f.nameStarts<h&&!f.valueStarts&&(f.name=t.slice(f.nameStarts,f.nameEnds)));if(a.nameStarts!==void 0&&a.nameEnds===void 0&&(!t[h].trim()||!Go(t[h]))){if(a.nameEnds=h,a.name=t.slice(a.nameStarts,a.nameEnds+(!U(h)&&t[h]!=="/"&&t[h+1]===void 0?1:0)),t[a.nameStarts-1]!=="!"&&!a.name.replace(/-/g,"").length||/^\d+$/.test(a.name[0])){a={};continue}if(typeof a.name=="string"&&a.name.toLowerCase()==="doctype"&&(H=!0),q(h)){I(v);let b=R(t,h,a.leftOuterWhitespace,h,a.lastOpeningBracketAt,h);(v.stripTogetherWithTheirContents.includes(a.name)||v.stripTogetherWithTheirContents.includes("*"))&&(o=o.filter(([k,S])=>!(k===a.leftOuterWhitespace&&S===h))),v.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:h,insert:`${b}${m}${b}`,rangesArr:A,proposedReturn:[a.leftOuterWhitespace,h,`${b}${m}${b}`]}),ke(),x(h,v,A)}}if(a.quotes?.start&&a.quotes.start<h&&!a.quotes.end&&f.nameEnds&&f.equalsAt&&!f.valueStarts&&(f.valueStarts=h),!a.quotes&&f.nameEnds&&t[h]==="="&&!f.valueStarts&&!f.equalsAt&&(f.equalsAt=h),!a.quotes&&f.nameStarts&&f.nameEnds&&!f.valueStarts&&t[h].trim()&&t[h]!=="="&&(a.attributes.push(f),f={}),!a.quotes&&f.nameStarts&&!f.nameEnds&&(H&&`'"`.includes(t[f.nameStarts])?f.nameStarts<h&&t[h]===t[f.nameStarts]&&(f.nameEnds=h+1,f.name=t.slice(f.nameStarts,f.nameEnds)):t[h].trim()?t[h]==="="?f.equalsAt||(f.nameEnds=h,f.equalsAt=h,f.name=t.slice(f.nameStarts,f.nameEnds)):t[h]==="/"||U(h)?(f.nameEnds=h,f.name=t.slice(f.nameStarts,f.nameEnds),a.attributes.push(f),f={}):q(h)&&(f.nameEnds=h,f.name=t.slice(f.nameStarts,f.nameEnds),a.attributes.push(f),f={}):(f.nameEnds=h,f.name=t.slice(f.nameStarts,f.nameEnds))),!a.quotes&&a.nameEnds<h&&!t[h-1].trim()&&t[h].trim()&&!"<>/!".includes(t[h])&&!f.nameStarts&&!a.lastClosingBracketAt&&(f.nameStarts=h),a.lastOpeningBracketAt!==null&&a.lastOpeningBracketAt<h&&t[h]==="/"&&a.onlyPlausible&&(a.onlyPlausible=!1),a.lastOpeningBracketAt!==null&&a.lastOpeningBracketAt<h&&t[h]!=="/"&&(a.onlyPlausible===void 0&&((!t[h].trim()||q(h))&&!a.slashPresent?a.onlyPlausible=!0:a.onlyPlausible=!1),t[h].trim()&&a.nameStarts===void 0&&!q(h)&&t[h]!=="/"&&!U(h)&&t[h]!=="!"&&(a.nameStarts=h,a.nameContainsLetters=!1)),a.nameStarts&&!a.quotes&&typeof t[h]=="string"&&t[h].toLowerCase()!==t[h].toUpperCase()&&(a.nameContainsLetters=!0),U(h)&&(Kr(a,t,h)||a.quotes.value&&typeof a.lastOpeningBracketAt=="number"&&Ko(a.quotes.value,t.slice(a.lastOpeningBracketAt,h))%2===1&&!t.slice(a.lastOpeningBracketAt+1,h).includes("<")&&!t.slice(a.lastOpeningBracketAt+1,h).includes(">"))&&a.lastOpeningBracketAt!==void 0&&(a.lastClosingBracketAt=h,w=null,Object.keys(f).length&&(a.attributes.push(f),f={}),v.dumpLinkHrefsNearby?.enabled&&y.tagName&&!y.openingTagEnds&&(y.openingTagEnds=h)),(!H||t[h]===">")&&a.lastOpeningBracketAt!==void 0){if(a.lastClosingBracketAt===void 0){if(a.lastOpeningBracketAt<h&&!q(h)&&(t[h+1]===void 0||q(h+1)&&!a?.quotes?.value)&&a.nameContainsLetters&&typeof a.nameStarts=="number"){if(a.name=t.slice(a.nameStarts,a.nameEnds||h+1).toLowerCase(),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,h+1]),v.ignoreTags.includes(a.name)||Se(h,v,a)||!Ae.has(a.name)&&(a.onlyPlausible||v.stripRecognisedHTMLOnly)){a={},f={};continue}if((Ae.has(a.name)||Et.has(a.name))&&(a.onlyPlausible===!1||a.onlyPlausible===!0&&a.attributes.length)||t[h+1]===void 0){I(v);let b=R(t,h,a.leftOuterWhitespace,h+1,a.lastOpeningBracketAt,a.lastClosingBracketAt);J&&a.name==="script"&&a.slashPresent&&(J=!1);let k;b===null||m===null?k=null:k=`${b}${m}${b}`,v.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:h+1,insert:k,rangesArr:A,proposedReturn:[a.leftOuterWhitespace,h+1,k]}),ke(),x(h,v,A)}if(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt&&o[o.length-1][1]!==h+1)if(v.stripTogetherWithTheirContents.includes(a.name)||v.stripTogetherWithTheirContents.includes("*")){let b;for(let k=n.length;k--;)n[k].name===a.name&&(b=n[k]);b?(o=o.filter(([k])=>k!==b.lastOpeningBracketAt),o.push([b.lastOpeningBracketAt,h+1])):o.push([a.lastOpeningBracketAt,h+1])}else o.push([a.lastOpeningBracketAt,h+1])}}else if(h>a.lastClosingBracketAt&&t[h].trim()||t[h+1]===void 0||v.ignoreIndentations&&`\r
|
|
22
|
+
`.includes(t[h])){let b=a.lastClosingBracketAt===h?h+1:h;v.trimOnlySpaces&&b===D-1&&w!==null&&w<h&&(b=w),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,a.lastClosingBracketAt+1]);let k=v.ignoreTags.includes(a.name),S=Se(h,v,a);if(!E||v.stripRecognisedHTMLOnly&&typeof a.name=="string"&&!Ae.has(a.name.toLowerCase())&&!Et.has(a.name.toLowerCase())||!Er&&(k||S)||Er&&!v.onlyStripTags.includes(a.name)||v.ignoreTagsWithTheirContents.includes(a.name)){if(S)if(a.slashPresent){for(let O=i.length;O--;)if(i[O].name===a.name){i.splice(O,1);break}i.length||(E=!0)}else E&&(E=!1),i.push(a);v.cb({tag:a,deleteFrom:null,deleteTo:null,insert:null,rangesArr:A,proposedReturn:null}),a={},f={}}else if(!a.onlyPlausible||a.attributes.length===0&&a.name&&(Ae.has(a.name.toLowerCase())||Et.has(a.name.toLowerCase()))||a.attributes?.some(O=>O.equalsAt)){(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([a.lastOpeningBracketAt,a.lastClosingBracketAt+1]);let O=R(t,h,a.leftOuterWhitespace,b,a.lastOpeningBracketAt,a.lastClosingBracketAt);m="",p=!1,I(v,b);let T;typeof m=="string"&&m.length?(T=`${O}${m}${O===`
|
|
23
23
|
|
|
24
24
|
`?`
|
|
25
|
-
`:
|
|
26
|
-
`)?N+=
|
|
27
|
-
`||t[h]==="\r")&&(u=h,g&&(g=!1))):(l!==null&&(!a.quotes&&f.equalsAt>l-1&&f.nameEnds&&f.equalsAt>f.nameEnds&&t[h]!=='"'&&t[h]!=="'"&&(Lt(f)&&a.attributes.push(f),f={},a.equalsSpottedAt=void 0),l=null),g||(g=!0,E&&!J&&typeof u=="number"&&h&&u<h-1&&(t.slice(u+1,h).trim()?u=null:b.ignoreIndentations||O.push([u+1,h])))),t[h]===" "?d===null&&(d=h):d!==null&&(d=null),a.name==="script"&&(J=!a.slashPresent)}if(t&&!b.ignoreIndentations&&(b.trimOnlySpaces&&t[0]===" "||!b.trimOnlySpaces&&!t[0].trim()))for(let h=0;h<D;h++)if(b.trimOnlySpaces&&t[h]!==" "||!b.trimOnlySpaces&&t[h].trim()){O.push([0,h]);break}else t[h+1]||O.push([0,h+1]);if(t&&(b.trimOnlySpaces&&t[~-t.length]===" "||!b.trimOnlySpaces&&!t[~-t.length].trim())){for(let h=t.length;h--;)if(b.trimOnlySpaces&&t[h]!==" "||!b.trimOnlySpaces&&t[h].trim()){O.push([h+1,D]);break}}let G=O.current();if(!e?.cb&&G&&(G[0]&&!G[0][0]&&(G[0][1],O.ranges[0]=[O.ranges[0][0],O.ranges[0][1]]),G[G.length-1]?.[1]===t.length&&(G[G.length-1][0],O.ranges))){let h=O.ranges[O.ranges.length-1][0];t[h-1]&&(b.trimOnlySpaces&&t[h-1]===" "||!b.trimOnlySpaces&&!t[h-1].trim())&&(h-=1);let v=O.ranges[O.ranges.length-1][2];O.ranges[O.ranges.length-1]=[h,O.ranges[O.ranges.length-1][1]],v?.trim()&&O.ranges[O.ranges.length-1].push(v.trimEnd())}return{log:{timeTakenInMilliseconds:Date.now()-n},result:Co(t,O.current()),ranges:O.current(),allTagLocations:s,filteredTagLocations:o}}class $t{speechSynthesis;speechSynthesisUtterance;currentVoice=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";eventListeners=new Map;voiceManager=null;voices=[];defaultVoice=null;speakInContentLanguage=!1;languageVoiceCache=new Map;warmingLanguages=new Map;speakGeneration=0;resumeInfinityTimer;isSpeakingInternal=!1;isPausedInternal=!1;isAndroidPaused=!1;pausedAtUtteranceIndex=null;initialized=!1;maxLengthExceeded="warn";utterancesBeingCancelled=!1;rate=1;pitch=1;volume=1;features;patches;constructor(){if(this.features=Qi(),this.patches=Xi(),!this.features.speechSynthesis||!this.features.speechSynthesisUtterance)throw new Error("Web Speech API is not available in this environment");this.speechSynthesis=this.features.speechSynthesis,this.speechSynthesisUtterance=this.features.speechSynthesisUtterance}shouldUseResumeInfinity(){const e=this.currentVoice,n=!!(e?.name&&typeof e.name=="string"&&e.name.toLocaleLowerCase().includes("(natural)"));return this.patches.isAndroid!==!0&&!this.patches.isFirefox&&!this.patches.isSafari&&!n}createUtterance(e){return new this.speechSynthesisUtterance(e)}async initialize(e={}){const{languages:n,maxTimeout:r,interval:i,maxLengthExceeded:s="warn"}=e;if(this.initialized)return!1;this.maxLengthExceeded=s;try{this.voiceManager=await k.initialize({languages:n,maxTimeout:r,interval:i}),this.voices=this.voiceManager.getVoices();const o=n||[...navigator.languages||["en"]];return this.defaultVoice=await this.voiceManager.getDefaultVoice(o,this.voices),this.initialized=!0,!0}catch(o){return console.error("Failed to initialize WebSpeechEngine:",o),this.initialized=!1,!1}}validateText(e){if(new TextEncoder().encode(e).length>4096){const r="Text exceeds max length of 4096 bytes, which may not work with some voices.";switch(this.maxLengthExceeded){case"none":break;case"error":throw new Error(`WebSpeechEngine: ${r}`);default:console.warn(`WebSpeechEngine: ${r}`)}}}getCurrentVoiceForUtterance(e){return e&&typeof e=="object"?e:typeof e=="string"?this.voices.find(n=>n.name===e||n.language===e)||null:this.currentVoice||this.defaultVoice}voiceMatchesLanguage(e,n){const[r,i]=U(n),[s,o]=U(e.language);return s===r&&(!i||o===i)}voiceForUtteranceSync(e){const n=this.getCurrentVoiceForUtterance(this.currentVoice);if(!this.speakInContentLanguage||!e.language)return n;const r=$(e.language);if(n&&this.voiceMatchesLanguage(n,r))return n;if(this.languageVoiceCache.has(r))return this.languageVoiceCache.get(r)??n}async voiceForUtterance(e){const n=this.voiceForUtteranceSync(e);return n!==void 0?n:(await this.warmLanguageVoiceCache([e]),this.voiceForUtteranceSync(e)??this.getCurrentVoiceForUtterance(this.currentVoice))}async warmLanguageVoiceCache(e){if(!this.speakInContentLanguage||!this.voiceManager)return;const n=new Set(e.map(o=>o.language).filter(o=>!!o).map(o=>$(o)).filter(o=>!this.languageVoiceCache.has(o))),r=[...n].filter(o=>this.warmingLanguages.has(o)),s=[...n].filter(o=>!this.warmingLanguages.has(o)).map(o=>{const a=(async()=>{await k.initialize({languages:[o]}),this.voices=this.voiceManager.getVoices();const c=this.voices.filter(u=>this.voiceMatchesLanguage(u,o)),d=(await this.voiceManager.sortVoicesByQuality(c))[0]??null;this.languageVoiceCache.set(o,d),d||this.emitEvent({type:"languagefallback",detail:{language:o,reason:"no-matching-voice"}})})();return this.warmingLanguages.set(o,a.finally(()=>this.warmingLanguages.delete(o))),this.warmingLanguages.get(o)});await Promise.all([...s,...r.map(o=>this.warmingLanguages.get(o))])}getCurrentVoice(){return this.currentVoice}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,e&&this.warmLanguageVoiceCache(this.currentUtterances)}getSpeakInContentLanguage(){return this.speakInContentLanguage}toPlainText(e){return e.map(n=>({...n,plain:n.plain??(n.ssml?kr(n.ssml).result:"")}))}loadUtterances(e){this.currentUtterances=this.toPlainText(e),this.currentUtteranceIndex=0,this.warmLanguageVoiceCache(this.currentUtterances),this.setState("ready"),this.emitEvent({type:"ready"})}async setVoice(e){const n=this.currentVoice;if(typeof e=="string"){const r=this.voices.find(i=>i.name===e||i.language===e);r?(this.currentVoice=r,n&&n.name!==r.name&&(this.currentUtteranceIndex=0)):console.warn(`Voice "${e}" not found`)}else this.currentVoice=e,n&&n.name!==e.name&&(this.currentUtteranceIndex=0);this.voiceManager&&this.defaultVoice&&this.currentVoice&&this.currentVoice.language!==this.defaultVoice.language&&(this.defaultVoice=await this.voiceManager.getDefaultVoice([this.currentVoice.language],this.voices))}async getAvailableVoices(){if(this.voices.length>0)return this.voices;try{return await this.initialize(),this.voices}catch{return[]}}speak(e){if(e!==void 0){if(e<0||e>=this.currentUtterances.length)throw new Error("Invalid utterance index");this.currentUtteranceIndex=e}if(this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.cancelCurrentSpeech();const n=++this.speakGeneration;this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.emitEvent({type:"start"}),this.stopResumeInfinity(),this.currentUtteranceIndex=e??0,this.currentUtteranceIndex>=this.currentUtterances.length&&(this.currentUtteranceIndex=0),this.speakCurrentUtterance(n)}cancelCurrentSpeech(){this.patches.isFirefox&&this.speechSynthesis.speaking&&(this.utterancesBeingCancelled=!0,setTimeout(()=>{this.utterancesBeingCancelled=!1},100)),this.speechSynthesis.cancel()}async speakCurrentUtterance(e){if(this.currentUtteranceIndex>=this.currentUtterances.length){this.setState("idle"),this.emitEvent({type:"end"});return}const n=this.currentUtterances[this.currentUtteranceIndex],r=n.plain??"";this.validateText(r);const i=this.createUtterance(r),s=await this.voiceForUtterance(n);if(e===this.speakGeneration){if(s&&this.voiceManager){const o=this.voiceManager.convertToSpeechSynthesisVoice(s);o&&(i.voice=o,i.lang=o.lang)}n.language&&(i.lang=n.language),i.rate=this.rate,i.pitch=this.pitch,i.volume=this.volume,i.onstart=()=>{this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.emitEvent({type:"start"}),this.patches.isAndroid&&this.isAndroidPaused&&(this.isAndroidPaused=!1),this.shouldUseResumeInfinity()&&this.startResumeInfinity(i)},i.onend=()=>{if(this.utterancesBeingCancelled){this.utterancesBeingCancelled=!1;return}this.playbackState!=="idle"&&(this.isSpeakingInternal=!1,this.isPausedInternal=!1,this.stopResumeInfinity(),this.currentUtteranceIndex>=this.currentUtterances.length-1&&this.setState("idle"),this.emitEvent({type:"end"}))},i.onerror=o=>{if(o.error==="interrupted"&&this.patches.isAndroid&&this.isAndroidPaused)return;this.isSpeakingInternal=!1,this.isPausedInternal=!1,this.stopResumeInfinity(),this.setState("idle"),["synthesis-unavailable","audio-hardware","voice-unavailable"].includes(o.error)&&(console.log("[ENGINE] fatal error detected, resetting index to 0"),this.currentUtteranceIndex=0),o.error==="interrupted"||o.error==="canceled"?this.emitEvent({type:"stop"}):this.emitEvent({type:"error",detail:{error:o.error,message:`Speech synthesis error: ${o.error}`}})},i.onpause=()=>{this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.emitEvent({type:"pause"})},i.onresume=()=>{this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.emitEvent({type:"resume"})},i.onboundary=o=>{this.emitEvent({type:"boundary",detail:{charIndex:o.charIndex,charLength:o.charLength,elapsedTime:o.elapsedTime,name:o.name}})},i.onmark=o=>{this.emitEvent({type:"mark",detail:{name:o.name}})},this.speechSynthesis.speak(i)}}startResumeInfinity(e){this.shouldUseResumeInfinity()&&(this.resumeInfinityTimer=window.setTimeout(()=>{if(e){const{paused:r,speaking:i}=this.speechSynthesis,s=i||this.isSpeakingInternal,o=r||this.isPausedInternal;s&&!o&&(this.speechSynthesis.pause(),this.speechSynthesis.resume())}this.startResumeInfinity(e)},5e3))}stopResumeInfinity(){this.resumeInfinityTimer&&(clearTimeout(this.resumeInfinityTimer),this.resumeInfinityTimer=void 0)}pause(){this.playbackState==="playing"&&(this.pausedAtUtteranceIndex=this.currentUtteranceIndex,this.patches.isAndroid?(this.isAndroidPaused=!0,this.speechSynthesis.cancel()):this.speechSynthesis.pause(),this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.currentUtteranceIndex<this.currentUtterances.length&&(this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.setState("playing"),this.emitEvent({type:"resume"}),this.patches.isAndroid||this.pausedAtUtteranceIndex!==this.currentUtteranceIndex?this.speak(this.currentUtteranceIndex):this.speechSynthesis.resume(),this.pausedAtUtteranceIndex=null)}stop(){this.speechSynthesis.cancel(),this.speakGeneration++,this.currentUtteranceIndex=0,this.patches.isAndroid&&(this.isAndroidPaused=!1),this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){this.rate=Math.max(.1,Math.min(10,e))}getRate(){return this.rate}setPitch(e){this.pitch=Math.max(0,Math.min(2,e))}getPitch(){return this.pitch}setVolume(e){this.volume=Math.max(0,Math.min(1,e))}getVolume(){return this.volume}getState(){return this.playbackState}getCurrentUtteranceIndex(){return this.currentUtteranceIndex}setCurrentUtteranceIndex(e,n){if(e<0||e>=this.currentUtterances.length){n?.(!1);return}e!==this.currentUtteranceIndex&&(!this.isPausedInternal&&this.isSpeakingInternal&&this.cancelCurrentSpeech(),this.currentUtteranceIndex=e,n?.(!0))}getUtteranceCount(){return this.currentUtterances.length}on(e,n){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(n),()=>{const r=this.eventListeners.get(e);if(r){const i=r.indexOf(n);i>-1&&r.splice(i,1)}}}emitEvent(e){const n=this.eventListeners.get(e.type);n&&n.forEach(r=>r(e))}setState(e){const n=this.playbackState;if(this.playbackState=e,n!==e)switch(e){case"idle":this.emitEvent({type:"idle"});break;case"loading":this.emitEvent({type:"loading"});break;case"ready":this.emitEvent({type:"ready"});break}}async destroy(){this.stop(),this.stopResumeInfinity(),this.eventListeners.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[],this.defaultVoice=null,this.languageVoiceCache.clear(),this.warmingLanguages.clear(),this.initialized=!1}}class Io{id="webspeech";name="Web Speech API";voiceEngine=null;async getVoices(){return this.voiceEngine||(this.voiceEngine=new $t,await this.voiceEngine.initialize()),this.voiceEngine.getAvailableVoices()}async createEngine(e){const n=new $t;return await n.initialize(),e&&await n.setVoice(e),n}async destroy(){this.voiceEngine&&(await this.voiceEngine.destroy(),this.voiceEngine=null)}}const oe="\\p{Pe}\\p{Pf}.,;:!?,。、;:!?،؛؟",_t="\\p{Ps}\\p{Pi}¿¡",Lo=new RegExp(`^[${oe}]`,"u"),qo=new RegExp(`^[${_t}]`,"u");function ct(t){return Lo.test(t)}function Do(t){return qo.test(t)}function Cr(t,e){const n=[];let r=-1,i=-1;const s=()=>{r!==-1&&(n.push({text:$o(t,r,i),offset:t[r].offset}),r=-1,i=-1)};for(let o=0;o<t.length;o++){const a=t[o];if(a.text.length>e){s(),n.push({text:a.text,offset:a.offset});continue}const c=a.offset+a.text.length,l=r===-1?a.text.length:c-t[r].offset;r!==-1&&l>e&&s(),r===-1&&(r=o),i=o}return s(),n}function $o(t,e,n){const r=t[e],i=t[n];return r===i?r.text:t.slice(e,n+1).map(s=>s.text).join("")}const Er=new RegExp(`[^${oe}]*[${oe}]+\\s*|[^${oe}]+$`,"gu"),_o=/\S+\s*|\s+/g;function nn(t,e,n){const r=[];for(const i of t.matchAll(n))i[0].length!==0&&r.push({text:i[0],offset:e+i.index,atomic:!1});return r}function rn(t,e){if(t.text.length<=e||t.atomic)return[t];const n=nn(t.text,t.offset,_o);if(n.length>1)return n.flatMap(o=>rn(o,e));const r=[];let i=t.offset,s="";for(const o of t.text)s.length>0&&s.length+o.length>e&&(r.push({text:s,offset:i,atomic:!1}),i+=s.length,s=""),s+=o;return s.length>0&&r.push({text:s,offset:i,atomic:!1}),r}function Ar(t,e){if(t.length<=e)return[{text:t,offset:0}];const r=nn(t,0,Er).flatMap(i=>rn(i,e));return Cr(r,e)}const Bo=/<([a-zA-Z][\w-]*)\b[^>]*>[\s\S]*?<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function Or(t,e){if(t.length<=e)return[{text:t,offset:0}];const n=[];for(const i of t.matchAll(Bo))i[0][0]==="<"?n.push({text:i[0],offset:i.index,atomic:!0}):n.push(...nn(i[0],i.index,Er));const r=n.flatMap(i=>rn(i,e));return Cr(r,e)}const Uo={wav:"audio/wav",mp3:"audio/mpeg",opus:"audio/ogg",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",m4a:"audio/mp4"};function Tr(t){return Uo[t]??`audio/${t}`}const zo=["flac","wav","opus","aac","ogg","webm","mp3"],jo=["opus","aac","webm","ogg","mp3","wav","flac"];function Rr(t,e,n){const r=a=>n(Tr(a))!=="",i=t.formats.filter(r);if(e.preferredFormat&&i.includes(e.preferredFormat))return e.preferredFormat;const s=e.strategy==="bandwidth"?jo:zo,o=[...s,...i.filter(a=>!s.includes(a))];for(const a of o)if(i.includes(a))return a;return t.default}const Vo=new Set(["wav","flac"]),Fo={mp3:48e3,opus:24e3,aac:48e3,ogg:48e3,webm:32e3};function Pr(t,e,n){return Vo.has(t)||!e||!n?void 0:n.saveData===!0||/2g/.test(n.effectiveType??"")?Fo[t]:void 0}function sn(t,e){return{source:"server",label:t.name,name:t.name,originalName:t.originalName,language:t.language,otherLanguages:t.otherLanguages,gender:t.gender??void 0,quality:t.quality,provider:t.provider,identifier:t.identifier,controls:e}}class Ie extends Error{status;type;title;instance;constructor(e,n){super(e),this.name="SpeechServerError",this.status=n.status,this.type=n.type,this.title=n.title,this.instance=n.instance}}async function le(t){if((t.headers.get("content-type")??"").includes("application/problem+json"))try{const n=await t.json();return new Ie(n.detail||n.title||`Request failed with status ${t.status}`,{status:n.status??t.status,type:n.type,title:n.title,instance:n.instance})}catch{}return new Ie(`Request failed with status ${t.status}`,{status:t.status})}const Mo=3,Ho=400;function Go(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n.buffer}function Wo(t){return Math.max(.25,Math.min(4,t))}function Fe(t){return t?.plain??t?.ssml??void 0}function Vn(t){return t instanceof Ie?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance}:t instanceof Error?{message:t.message}:{message:String(t)}}class Nr{endpoints;fetchImpl;currentVoice=null;voices=[];serviceInfo=null;serviceInfoPromise=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";eventListeners=new Map;speakInContentLanguage=!1;speakGeneration=0;loadGeneration=0;prefetchWindow;readyBufferChars;overLengthText;formatOptions;canPlayType;prefetchCache=new Map;prefetchChainTail=Promise.resolve();audioContext=null;masterGain=null;scheduledChunks=[];boundaryRafHandle=null;rate=1;pitch=1;volume=1;constructor(e){this.endpoints=e.endpoints,this.fetchImpl=e.fetch??fetch.bind(globalThis),this.prefetchWindow=e.prefetchWindow??Mo,this.readyBufferChars=e.readyBufferChars??Ho,this.overLengthText=e.overLengthText??"split",this.formatOptions=e.format??{},this.canPlayType=typeof Audio<"u"?n=>new Audio().canPlayType(n):()=>""}setAvailableVoices(e){this.voices=e}loadUtterances(e){this.clearPrefetchCache(),this.currentUtterances=e,this.currentUtteranceIndex=0,this.setState("loading"),this.bufferUntilReady(++this.loadGeneration)}async bufferUntilReady(e){const n=Math.min(this.indexCoveringChars(this.readyBufferChars),this.prefetchWindow),r=[];for(let i=0;i<=n;i++){this.queuePrefetch(i);const s=this.prefetchCache.get(i);s&&r.push(s.then(o=>o[0]))}try{await Promise.all(r)}catch{}e!==this.loadGeneration||this.playbackState!=="loading"||(this.setState("ready"),this.emitEvent({type:"ready"}))}indexCoveringChars(e){if(this.currentUtterances.length===0)return-1;let n=0;for(let r=0;r<this.currentUtterances.length;r++)if(n+=(Fe(this.currentUtterances[r])??"").length,n>=e)return r;return this.currentUtterances.length-1}setVoice(e){if(typeof e=="string"){const n=this.voices.find(r=>r.identifier===e||r.name===e);n?this.currentVoice=n:(this.currentVoice={source:"server",label:e,name:e,originalName:e,language:"",identifier:e},this.getAvailableVoices().then(r=>{if(this.currentVoice?.identifier!==e)return;const i=r.find(s=>s.identifier===e||s.name===e);i&&(this.currentVoice=i)}).catch(()=>{}))}else this.currentVoice=e;this.clearPrefetchCache()}getCurrentVoice(){return this.currentVoice}async getAvailableVoices(){if(this.voices.length>0)return this.voices;const[e,n]=await Promise.all([this.fetchImpl(this.endpoints.voices),this.getServiceInfo()]);if(!e.ok)throw await le(e);const r=await e.json(),i=new Map(n.providers.map(s=>[s.id,s.controls]));return this.voices=r.map(s=>sn(s,i.get(s.provider))),this.voices}async getServiceInfo(){return this.serviceInfo?this.serviceInfo:(this.serviceInfoPromise||(this.serviceInfoPromise=this.fetchServiceInfo().catch(e=>{throw this.serviceInfoPromise=null,e})),this.serviceInfo=await this.serviceInfoPromise,this.serviceInfo)}async fetchServiceInfo(){const e=await this.fetchImpl(this.endpoints.service);if(!e.ok)throw await le(e);return e.json()}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,this.clearPrefetchCache()}getSpeakInContentLanguage(){return this.speakInContentLanguage}speak(e){if(e!==void 0){if(e<0||e>=this.currentUtterances.length)throw new Error("Invalid utterance index");this.currentUtteranceIndex=e}if(this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.stopAudio();const n=++this.speakGeneration;this.setState("loading"),this.synthesizeAndPlay(n)}async synthesizeAndPlay(e){const n=this.currentUtteranceIndex;try{const r=await this.resolveSynthesisStream(n);if(e!==this.speakGeneration)return;await this.scheduleChunksStreaming(r,e),this.fillPrefetchWindow(n)}catch(r){if(e!==this.speakGeneration)return;this.setState("idle"),this.emitEvent({type:"error",detail:Vn(r)})}}async resolveSynthesisStream(e){const n=this.prefetchCache.get(e);if(n){this.prefetchCache.delete(e);try{return await n}catch{}}return this.synthesizeStream(e)}fillPrefetchWindow(e){const n=Math.min(e+this.prefetchWindow,this.currentUtterances.length-1);for(let r=e+1;r<=n;r++)this.queuePrefetch(r)}queuePrefetch(e){if(this.prefetchCache.has(e))return;const n=this.prefetchChainTail.then(()=>this.synthesizeStream(e));this.prefetchCache.set(e,n),this.prefetchChainTail=n.then(r=>Promise.all(r)).then(()=>{},()=>{}),n.catch(()=>{}),n.then(r=>r.forEach(i=>i.catch(()=>{}))).catch(()=>{})}clearPrefetchCache(){this.prefetchCache.clear()}async synthesizeStream(e){const n=this.currentUtterances[e],r=!n.plain&&!!n.ssml,i=this.speakInContentLanguage?n.language:void 0,s=Fe(n)??"",o=Fe(this.currentUtterances[e-1]),a=Fe(this.currentUtterances[e+1]),c=await this.getServiceInfo(),l=Rr(c.output,this.formatOptions,this.canPlayType),d=navigator.connection,u=Pr(l,this.formatOptions.adaptBitrateToNetwork??!1,d);if(s.length<=c.limits.maxTextLength)return[this.synthesizeChunk(n,s,0,r,i,o,a,l,u)];if(this.overLengthText==="error")throw new Ie(`Text exceeds this server's maximum length of ${c.limits.maxTextLength} characters`,{status:413,type:"https://readium.org/speech-server/error#payload_too_large",title:"Payload Too Large"});const g=Math.min(c.limits.maxTextLength,this.readyBufferChars),f=r?Or(s,g):Ar(s,g),y=[];let p=Promise.resolve();for(let m=0;m<f.length;m++){const w=m===0?o:f[m-1].text,E=m===f.length-1?a:f[m+1].text,C=f[m],P=p.then(()=>this.synthesizeChunk(n,C.text,C.offset,r,i,w,E,l,u));y.push(P),p=P}return y}async synthesizeChunk(e,n,r,i,s,o,a,c,l){const d=await this.fetchImpl(this.endpoints.synthesize,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e.id,text:n,ssml:i,language:s,voice:this.currentVoice?.identifier??this.currentVoice?.name,prev_utterance:o,next_utterance:a,boundary:!0,output:{format:c,bitrate:l,speed:this.rate,pitch:this.pitch}})});if(!d.ok)throw await le(d);const u=await d.json(),g=Go(u.audio);let f;try{f=await this.ensureAudioContext().decodeAudioData(g)}catch{throw new Error("Audio playback failed")}return{audioBuffer:f,format:u.format,boundaries:u.boundaries,textOffset:r}}ensureAudioContext(){return this.audioContext||(this.audioContext=new AudioContext,this.masterGain=this.audioContext.createGain(),this.masterGain.gain.value=this.volume,this.masterGain.connect(this.audioContext.destination)),this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.audioContext}async scheduleChunksStreaming(e,n){const r=await e[0];if(n!==this.speakGeneration)return;const i=this.ensureAudioContext(),s=this.masterGain,a=this.currentVoice?.controls?.speed===!0?1:Wo(this.rate);this.scheduledChunks=[],this.setState("playing"),this.emitEvent({type:"start"});let c=i.currentTime,l=null;const d=u=>{const g=i.createBufferSource();g.buffer=u.audioBuffer,g.playbackRate.value=a,g.connect(s),g.start(c),l&&(l.onended=null),g.onended=()=>this.handleUtteranceEnded(n),l=g,this.scheduledChunks.push({chunk:u,startTime:c,node:g,nextBoundaryIndex:0,rate:a}),c+=u.audioBuffer.duration/a};d(r),this.startBoundaryPolling(n);for(let u=1;u<e.length;u++){let g;try{g=await e[u]}catch(f){n===this.speakGeneration&&this.emitEvent({type:"error",detail:Vn(f)});return}if(n!==this.speakGeneration)return;d(g)}}handleUtteranceEnded(e){e===this.speakGeneration&&(this.checkBoundaries(),this.stopBoundaryPolling(),this.currentUtteranceIndex>=this.currentUtterances.length-1&&this.setState("idle"),this.emitEvent({type:"end"}))}startBoundaryPolling(e){const n=()=>{e===this.speakGeneration&&(this.checkBoundaries(),this.boundaryRafHandle=requestAnimationFrame(n))};this.boundaryRafHandle=requestAnimationFrame(n)}stopBoundaryPolling(){this.boundaryRafHandle!==null&&(cancelAnimationFrame(this.boundaryRafHandle),this.boundaryRafHandle=null)}checkBoundaries(){if(!this.audioContext)return;const e=this.audioContext.currentTime;for(const n of this.scheduledChunks){const r=n.chunk.boundaries??[];for(;n.nextBoundaryIndex<r.length&&e>=n.startTime+r[n.nextBoundaryIndex].elapsedTime/n.rate;){const i=r[n.nextBoundaryIndex];this.emitEvent({type:"boundary",detail:{name:i.name,charIndex:i.charIndex+n.chunk.textOffset,charLength:i.charLength,elapsedTime:i.elapsedTime}}),n.nextBoundaryIndex++}}}stopAudio(){this.stopBoundaryPolling();for(const e of this.scheduledChunks){e.node.onended=null;try{e.node.stop()}catch{}e.node.disconnect()}this.scheduledChunks=[]}pause(){this.playbackState==="playing"&&this.audioContext&&(this.audioContext.suspend().catch(()=>{}),this.stopBoundaryPolling(),this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.audioContext&&(this.audioContext.resume().catch(()=>{}),this.startBoundaryPolling(this.speakGeneration),this.setState("playing"),this.emitEvent({type:"resume"}))}stop(){this.speakGeneration++,this.loadGeneration++,this.stopAudio(),this.clearPrefetchCache(),this.currentUtteranceIndex=0,this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){this.rate=Math.max(.1,Math.min(10,e)),this.clearPrefetchCache()}getRate(){return this.rate}setPitch(e){this.pitch=Math.max(0,Math.min(2,e)),this.clearPrefetchCache()}getPitch(){return this.pitch}setVolume(e){this.volume=Math.max(0,Math.min(1,e)),this.masterGain&&(this.masterGain.gain.value=this.volume)}getVolume(){return this.volume}getState(){return this.playbackState}getCurrentUtteranceIndex(){return this.currentUtteranceIndex}setCurrentUtteranceIndex(e,n){if(e<0||e>=this.currentUtterances.length){n?.(!1);return}if(e===this.currentUtteranceIndex){n?.(!0);return}this.stopAudio(),this.currentUtteranceIndex=e,n?.(!0)}getUtteranceCount(){return this.currentUtterances.length}on(e,n){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(n),()=>{const r=this.eventListeners.get(e);if(r){const i=r.indexOf(n);i>-1&&r.splice(i,1)}}}emitEvent(e){const n=this.eventListeners.get(e.type);n&&n.forEach(r=>r(e))}setState(e){const n=this.playbackState;if(this.playbackState=e,n!==e)switch(e){case"idle":this.emitEvent({type:"idle"});break;case"loading":this.emitEvent({type:"loading"});break;case"ready":this.emitEvent({type:"ready"});break}}async destroy(){this.stop(),await this.audioContext?.close(),this.audioContext=null,this.masterGain=null,this.eventListeners.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[]}}class Ko{id="speech-server";name="Readium Speech Server";options;fetchImpl;voices=[];constructor(e){this.options=e,this.fetchImpl=e.fetch??fetch.bind(globalThis)}async getVoices(){if(this.voices.length>0)return this.voices;const[e,n]=await Promise.all([this.fetchImpl(this.options.endpoints.voices),this.fetchImpl(this.options.endpoints.service)]);if(!e.ok)throw await le(e);if(!n.ok)throw await le(n);const r=await e.json(),i=await n.json(),s=new Map(i.providers.map(o=>[o.id,o.controls]));return this.voices=r.map(o=>sn(o,s.get(o.provider))),this.voices}async createEngine(e){const n=new Nr(this.options);return this.voices.length>0&&n.setAvailableVoices(this.voices),e&&n.setVoice(e),n}async destroy(){this.voices=[]}}let Jo=class{};function Qo(t){return(t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode)==="vertical-lr"}function Xo(t){const e=t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode;return e==="vertical-rl"||e==="vertical-lr"}function Ce(t){const e=Xo(t),n=e&&Qo(t),r=t.innerWidth,i=t.innerHeight,s=t.document.scrollingElement,o=s.scrollLeft,a=s.scrollTop,c=parseInt(t.getComputedStyle(t.document.documentElement).getPropertyValue("column-count")),l=e&&!n?s.scrollWidth-r+o:o,d=a;return{isVertical:e,isVertLR:n,viewportInlineSize:e?i:r,viewportBlockSize:e?r:i,pageInlineSize:e?i:r/(c||1),xDocOffset:l,yDocOffset:d,inlineScrollOffset:e?d:l,blockScrollOffset:e?l:d,inlineStart:u=>e?u.top:u.left,blockStart:u=>e?u.left:u.top,inlineSize:u=>e?u.height:u.width,blockSize:u=>e?u.width:u.height,applyPosition(u,g,f,y,p,m){u.style.position="absolute",e?(u.style.top=`${g*m}px`,u.style.left=`${f*m}px`,u.style.height=`${y*m}px`,u.style.width=`${p*m}px`):(u.style.left=`${g*m}px`,u.style.top=`${f*m}px`,u.style.width=`${y*m}px`,u.style.height=`${p*m}px`)},toRect(u,g,f,y){return e?new DOMRect(g,u,y,f):new DOMRect(u,g,f,y)}}}function Fn(t,e){return t.document.documentElement.style.getPropertyValue(e)}function Zo(t){return t&&Array.isArray(t)?t:void 0}function Yo(t){return t&&typeof t=="string"?[t]:Zo(t)}function wt(t){return isNaN(t)?void 0:t}function Me(t){return t.otherLocations?.get("cssSelector")}let Ee=class Ir{constructor(e){this.fragments=e.fragments?e.fragments:new Array,this.progression=e.progression,this.totalProgression=e.totalProgression,this.position=e.position,this.otherLocations=e.otherLocations}static deserialize(e){if(!e)return;const n=wt(e.progression),r=wt(e.totalProgression),i=wt(e.position),s=new Map,o=new Set(["fragment","fragments","progression","totalProgression","position","otherLocations"]);return Object.entries(e).forEach(([a,c])=>{o.has(a)||s.set(a,c)}),e.otherLocations instanceof Map&&e.otherLocations.forEach((a,c)=>s.set(c,a)),new Ir({fragments:Yo(e.fragments||e.fragment),progression:n!==void 0&&n>=0&&n<=1?n:void 0,totalProgression:r!==void 0&&r>=0&&r<=1?r:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:s.size===0?void 0:s})}serialize(){const e={};return this.fragments&&(e.fragments=this.fragments),this.progression!==void 0&&(e.progression=this.progression),this.totalProgression!==void 0&&(e.totalProgression=this.totalProgression),this.position!==void 0&&(e.position=this.position),this.otherLocations&&this.otherLocations.forEach((n,r)=>e[r]=n),e}},el=class Lr{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new Lr({after:e.after,before:e.before,highlight:e.highlight})}serialize(){const e={};return this.after!==void 0&&(e.after=this.after),this.before!==void 0&&(e.before=this.before),this.highlight!==void 0&&(e.highlight=this.highlight),e}},tl=class Bt{constructor(e){const n=e.href.indexOf("#"),r=n>=0?e.href.slice(n+1):void 0;this.href=n>=0?e.href.slice(0,n):e.href,this.type=e.type,this.title=e.title;const i=e.locations?.fragments,s=r&&(!i||i.length===0);this.locations=e.locations?s?new Ee({...e.locations,fragments:[r]}):e.locations:r?new Ee({fragments:[r]}):new Ee({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new Bt({href:e.href,type:e.type,title:e.title,locations:Ee.deserialize(e.locations),text:el.deserialize(e.text)})}serialize(){const e={href:this.href,type:this.type};return this.title!==void 0&&(e.title=this.title),this.locations&&(e.locations=this.locations.serialize()),this.text&&(e.text=this.text.serialize()),e}copyWithLocations(e){return new Bt({href:this.href,type:this.type,title:this.title,text:this.text,locations:new Ee({...this.locations,...e})})}};function Mn(t){return t.split("").reverse().join("")}function nl(t,e,n){const r=Mn(e);return n.map(i=>{const s=Math.max(0,i.end-e.length-i.errors),o=Mn(t.slice(s,i.end));return{start:qr(o,r,i.errors).reduce((a,c)=>i.end-c.end<a?i.end-c.end:a,i.end),end:i.end,errors:i.errors}})}function St(t){return(t|-t)>>31&1}function Hn(t,e,n,r){let i=t.P[n],s=t.M[n];const o=r>>>31,a=e[n]|o,c=a|s,l=(a&i)+i^i|a;let d=s|~(l|i),u=i&l;const g=St(d&t.lastRowMask[n])-St(u&t.lastRowMask[n]);return d<<=1,u<<=1,u|=o,d|=St(r)-o,i=u|~(c|d),s=d&c,t.P[n]=i,t.M[n]=s,g}function qr(t,e,n){if(e.length===0)return[];n=Math.min(n,e.length);const r=[],i=32,s=Math.ceil(e.length/i)-1,o={P:new Uint32Array(s+1),M:new Uint32Array(s+1),lastRowMask:new Uint32Array(s+1)};o.lastRowMask.fill(1<<31),o.lastRowMask[s]=1<<(e.length-1)%i;const a=new Uint32Array(s+1),c=new Map,l=[];for(let g=0;g<256;g++)l.push(a);for(let g=0;g<e.length;g+=1){const f=e.charCodeAt(g);if(c.has(f))continue;const y=new Uint32Array(s+1);c.set(f,y),f<l.length&&(l[f]=y);for(let p=0;p<=s;p+=1){y[p]=0;for(let m=0;m<i;m+=1){const w=p*i+m;w>=e.length||e.charCodeAt(w)===f&&(y[p]|=1<<m)}}}let d=Math.max(0,Math.ceil(n/i)-1);const u=new Uint32Array(s+1);for(let g=0;g<=d;g+=1)u[g]=(g+1)*i;u[s]=e.length;for(let g=0;g<=d;g+=1)o.P[g]=-1,o.M[g]=0;for(let g=0;g<t.length;g+=1){const f=t.charCodeAt(g);let y;f<l.length?y=l[f]:(y=c.get(f),typeof y>"u"&&(y=a));let p=0;for(let m=0;m<=d;m+=1)p=Hn(o,y,m,p),u[m]+=p;if(u[d]-p<=n&&d<s&&(y[d+1]&1||p<0)){d+=1,o.P[d]=-1,o.M[d]=0;let m;if(d===s){const w=e.length%i;m=w===0?i:w}else m=i;u[d]=u[d-1]+m-p+Hn(o,y,d,p)}else for(;d>0&&u[d]>=n+i;)d-=1;d===s&&u[d]<=n&&(u[d]<n&&r.splice(0,r.length),r.push({start:-1,end:g+1,errors:u[d]}),n=u[d])}return r}function rl(t,e,n){const r=qr(t,e,n);return nl(t,e,r)}function Dr(t,e,n){let r=0;const i=[];for(;r!==-1;)r=t.indexOf(e,r),r!==-1&&(i.push({start:r,end:r+e.length,errors:0}),r+=1);return i.length>0?i:rl(t,e,n)}function Gn(t,e){return e.length===0||t.length===0?0:1-Dr(t,e,e.length)[0].errors/e.length}function il(t,e,n={}){if(e.length===0)return null;const r=Math.min(256,e.length/2),i=Dr(t,e,r);if(i.length===0)return null;const s=a=>{const c=1-a.errors/e.length,l=n.prefix?Gn(t.slice(Math.max(0,a.start-n.prefix.length),a.start),n.prefix):1,d=n.suffix?Gn(t.slice(a.end,a.end+n.suffix.length),n.suffix):1;let u=1;return typeof n.hint=="number"&&(u=1-Math.abs(a.start-n.hint)/t.length),(50*c+20*l+20*d+2*u)/92},o=i.map(a=>({start:a.start,end:a.end,score:s(a)}));return o.sort((a,c)=>c.score-a.score),o[0]}function Ut(t,e,n){const r=n===1?e:e-1;if(t.charAt(r).trim()!=="")return e;let i,s;if(n===2?(i=t.substring(0,e),s=i.trimEnd()):(i=t.substring(e),s=i.trimStart()),!s.length)return-1;const o=i.length-s.length;return n===2?e-o:e+o}function Wn(t,e){const n=t.commonAncestorContainer.ownerDocument.createNodeIterator(t.commonAncestorContainer,NodeFilter.SHOW_TEXT),r=e===1?t.startContainer:t.endContainer,i=e===1?t.endContainer:t.startContainer;let s=n.nextNode();for(;s&&s!==r;)s=n.nextNode();e===2&&(s=n.previousNode());let o=-1;const a=()=>{if(s=e===1?n.nextNode():n.previousNode(),s){const c=s.textContent,l=e===1?0:c.length;o=Ut(c,l,e)}};for(;s&&o===-1&&s!==i;)a();if(s&&o>=0)return{node:s,offset:o};throw new RangeError("No text nodes with non-whitespace text found in range")}function sl(t){if(!t.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(t.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(t.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=t.cloneRange();let n=!1,r=!1;const i={start:Ut(t.startContainer.textContent,t.startOffset,1),end:Ut(t.endContainer.textContent,t.endOffset,2)};if(i.start>=0&&(e.setStart(t.startContainer,i.start),n=!0),i.end>0&&(e.setEnd(t.endContainer,i.end),r=!0),n&&r)return e;if(!n){const{node:s,offset:o}=Wn(e,1);s&&o>=0&&e.setStart(s,o)}if(!r){const{node:s,offset:o}=Wn(e,2);s&&o>0&&e.setEnd(s,o)}return e}function $r(t){switch(t.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return t.textContent?.length??0;default:return 0}}function Kn(t){let e=t.previousSibling,n=0;for(;e;)n+=$r(e),e=e.previousSibling;return n}function _r(t,...e){let n=e.shift();const r=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),i=[];let s=r.nextNode(),o,a=0;for(;n!==void 0&&s;)o=s,a+o.data.length>n?(i.push({node:o,offset:n-a}),n=e.shift()):(s=r.nextNode(),a+=o.data.length);for(;n!==void 0&&o&&a===n;)i.push({node:o,offset:o.data.length}),n=e.shift();if(n!==void 0)throw new RangeError("Offset exceeds text length");return i}let He=class re{constructor(e,n){if(n<0)throw new Error("Offset is invalid");this.element=e,this.offset=n}relativeTo(e){if(!e.contains(this.element))throw new Error("Parent is not an ancestor of current element");let n=this.element,r=this.offset;for(;n!==e;)r+=Kn(n),n=n.parentElement;return new re(n,r)}resolve(e={}){try{return _r(this.element,this.offset)[0]}catch(n){if(this.offset===0&&e.direction!==void 0){const r=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);r.currentNode=this.element;const i=e.direction===1,s=i?r.nextNode():r.previousNode();if(!s)throw n;return{node:s,offset:i?0:s.data.length}}else throw n}}static fromCharOffset(e,n){switch(e.nodeType){case Node.TEXT_NODE:return re.fromPoint(e,n);case Node.ELEMENT_NODE:return new re(e,n);default:throw new Error("Node is not an element or text node")}}static fromPoint(e,n){switch(e.nodeType){case Node.TEXT_NODE:{if(n<0||n>e.data.length)throw new Error("Text node offset is out of range");if(!e.parentElement)throw new Error("Text node has no parent");const r=Kn(e)+n;return new re(e.parentElement,r)}case Node.ELEMENT_NODE:{if(n<0||n>e.childNodes.length)throw new Error("Child node offset is out of range");let r=0;for(let i=0;i<n;i++)r+=$r(e.childNodes[i]);return new re(e,r)}default:throw new Error("Point is not in an element or text node")}}},zt=class Oe{constructor(e,n){this.start=e,this.end=n}relativeTo(e){return new Oe(this.start.relativeTo(e),this.end.relativeTo(e))}toRange(){let e,n;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[e,n]=_r(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),n=this.end.resolve({direction:2}));const r=new Range;return r.setStart(e.node,e.offset),r.setEnd(n.node,n.offset),r}static fromRange(e){const n=He.fromPoint(e.startContainer,e.startOffset),r=He.fromPoint(e.endContainer,e.endOffset);return new Oe(n,r)}static fromOffsets(e,n,r){return new Oe(new He(e,n),new He(e,r))}static trimmedRange(e){return sl(Oe.fromRange(e).toRange())}},al=class jt{constructor(e,n,r){this.root=e,this.start=n,this.end=r}static fromRange(e,n){const r=zt.fromRange(n).relativeTo(e);return new jt(e,r.start.offset,r.end.offset)}static fromSelector(e,n){return new jt(e,n.start,n.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return zt.fromOffsets(this.root,this.start,this.end).toRange()}},ol=class Vt{constructor(e,n,r={}){this.root=e,this.exact=n,this.context=r}static fromRange(e,n){const r=e.textContent,i=zt.fromRange(n).relativeTo(e),s=i.start.offset,o=i.end.offset,a=32;return new Vt(e,r.slice(s,o),{prefix:r.slice(Math.max(0,s-a),s),suffix:r.slice(o,Math.min(r.length,o+a))})}static fromSelector(e,n){const{prefix:r,suffix:i}=n;return new Vt(e,n.exact,{prefix:r,suffix:i})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(e={}){return this.toPositionAnchor(e).toRange()}toPositionAnchor(e={}){const n=this.root.textContent,r=il(n,this.exact,{...this.context,hint:e.hint});if(!r)throw new Error("Quote not found");return new al(this.root,r.start,r.end)}};function ll(t){const e=t.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function cl(t,e){try{const n=e.locations,r=e.text;if(r&&r.highlight){let i;n&&Me(n)&&(i=t.querySelector(Me(n))),i||(i=t.body);const s=new ol(i,r.highlight,{prefix:r.before,suffix:r.after});try{return s.toRange()}catch{return console.warn("Quote not found:",s),null}}if(n){let i=null;if(!i&&Me(n)&&(i=t.querySelector(Me(n))),!i&&n.fragments){for(const s of n.fragments)if(i=t.getElementById(s),i)break}if(i){const s=t.createRange();return i.childNodes.length===0||ll(i)?(s.selectNode(i),s):(s.setStartBefore(i),s.setEndAfter(i),s)}}}catch(n){console.error(n)}return null}function ul(t,e){const n=e.map(c=>c.toUpperCase()),r=[],i=t.commonAncestorContainer,s=i.nodeType===Node.TEXT_NODE?i.parentNode:i,o=t.startContainer.ownerDocument.createTreeWalker(s,NodeFilter.SHOW_TEXT);let a=o.nextNode();for(;a;){if(t.intersectsNode(a)){let c=a.parentNode,l=!1;for(;c;){if(c.nodeType===Node.ELEMENT_NODE&&n.includes(c.tagName.toUpperCase())){l=!0;break}c=c.parentNode}if(!l){const d=t.cloneRange();d.selectNode(a),d.compareBoundaryPoints(Range.START_TO_START,t)<0&&d.setStart(t.startContainer,t.startOffset),d.compareBoundaryPoints(Range.END_TO_END,t)>0&&d.setEnd(t.endContainer,t.endOffset);for(const u of d.getClientRects())r.push({left:u.left,right:u.right,top:u.top,bottom:u.bottom,width:u.width,height:u.height})}}a=o.nextNode()}return r}function Ge(t,e,n=!1,r=0){let i;if(Array.isArray(t))i=t;else{let l=t.getClientRects();l.length||t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(l=t.commonAncestorContainer.getClientRects()),i=[];for(const d of l)i.push({bottom:d.bottom,height:d.height,left:d.left,right:d.right,top:d.top,width:d.width})}if(r)for(const l of i)l.left-=r,l.top-=r,l.right+=r,l.bottom+=r,l.width+=r*2,l.height+=r*2;const s=Br(i,1,e,n),o=dl(s,1),a=Ur(o),c=4;for(let l=a.length-1;l>=0;l--){const d=a[l];if(!(d.width*d.height>c))if(a.length>1)a.splice(l,1);else break}return a}function Br(t,e,n,r=!1){for(let i=0;i<t.length;i++)for(let s=i+1;s<t.length;s++){const o=t[i],a=t[s];if(o===a)continue;const c=q(o.top,a.top,e)&&q(o.bottom,a.bottom,e),l=q(o.left,a.left,e)&&q(o.right,a.right,e);if((l&&!n&&!r||c&&!l)&&zr(o,a,e)){const d=t.filter(g=>g!==o&&g!==a),u=hl(o,a);return d.push(u),Br(d,e,n,r)}}return t}function hl(t,e){const n=Math.min(t.left,e.left),r=Math.max(t.right,e.right),i=Math.min(t.top,e.top),s=Math.max(t.bottom,e.bottom);return{bottom:s,height:s-i,left:n,right:r,top:i,width:r-n}}function dl(t,e){const n=new Set(t);for(const r of t){if(!(r.width>1&&r.height>1)){n.delete(r);continue}for(const i of t)if(r!==i&&n.has(i)&&gl(i,r,e)){n.delete(r);break}}return Array.from(n)}function gl(t,e,n){return K(t,e.left,e.top,n)&&K(t,e.right,e.top,n)&&K(t,e.left,e.bottom,n)&&K(t,e.right,e.bottom,n)}function K(t,e,n,r){return(t.left<e||q(t.left,e,r))&&(t.right>e||q(t.right,e,r))&&(t.top<n||q(t.top,n,r))&&(t.bottom>n||q(t.bottom,n,r))}function Ur(t){for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){const r=t[e],i=t[n];if(r!==i&&zr(r,i,-1)){let s=[],o;const a=Jn(r,i);if(a.length===1)s=a,o=r;else{const l=Jn(i,r);a.length<l.length?(s=a,o=r):(s=l,o=i)}const c=t.filter(l=>l!==o);return Array.prototype.push.apply(c,s),Ur(c)}}return t}function Jn(t,e){const n=fl(e,t);if(n.height===0||n.width===0)return[t];const r=[];{const i={bottom:t.bottom,height:0,left:t.left,right:n.left,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{const i={bottom:n.top,height:0,left:n.left,right:n.right,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{const i={bottom:t.bottom,height:0,left:n.left,right:n.right,top:n.bottom,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{const i={bottom:t.bottom,height:0,left:n.right,right:t.right,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}return r}function fl(t,e){const n=Math.max(t.left,e.left),r=Math.min(t.right,e.right),i=Math.max(t.top,e.top),s=Math.min(t.bottom,e.bottom);return{bottom:s,height:Math.max(0,s-i),left:n,right:r,top:i,width:Math.max(0,r-n)}}function zr(t,e,n){return(t.left<e.right||n>=0&&q(t.left,e.right,n))&&(e.left<t.right||n>=0&&q(e.left,t.right,n))&&(t.top<e.bottom||n>=0&&q(t.top,e.bottom,n))&&(e.top<t.bottom||n>=0&&q(e.top,t.bottom,n))}function q(t,e,n){return Math.abs(t-e)<=n}let We=null,xt=null,Ae=0;const ie={r:255,g:255,b:255,a:1},ee=new Map,pl=()=>{if(!We)if(typeof OffscreenCanvas<"u")We=new OffscreenCanvas(5,5),xt=We.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const t=document.createElement("canvas");t.width=5,t.height=5,We=t,xt=t.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return xt},ml=t=>{if(!t)return!0;const e=t.trim().toLowerCase();return e.startsWith("var(")||["transparent","currentcolor","inherit","initial","revert","unset","revert-layer"].includes(e)?!0:["linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"].some(n=>e.includes(n))},Ke=(t,e)=>{console.warn(`[Decorator] Could not parse color: "${t}". ${e} Falling back to ${JSON.stringify(ie)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},X=(t,e=null)=>{const n=e?`${t}|${e}`:t,r=ee.get(n);if(r!==void 0)return r??ie;if(ml(t))return Ke(t,"Unsupported color format or special value."),ee.set(n,null),ie;const i=pl();if(!i)return Ke(t,"Could not get canvas context."),ee.set(n,null),ie;try{Ae===0&&i.clearRect(0,0,5,5);const s=Ae%5,o=Math.floor(Ae/5);i.clearRect(s,o,1,1),e&&(i.fillStyle=e,i.fillRect(s,o,1,1)),i.fillStyle=t,i.fillRect(s,o,1,1);const a=i.getImageData(s,o,1,1);Ae=(Ae+1)%25;const[c,l,d,u]=a.data;if(u===0)return Ke(t,"Fully transparent color."),ee.set(n,null),ie;const g={r:c,g:l,b:d,a:u/255};return ee.set(n,g),g}catch(s){return Ke(t,`Error: ${s instanceof Error?s.message:String(s)}`),ee.set(n,null),ie}},kt=t=>{const e=t/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},Ft=t=>{const e=kt(t.r),n=kt(t.g),r=kt(t.b);return .2126*e+.7152*n+.0722*r},et=(t,e)=>{const n=typeof t=="string"?X(t):t,r=typeof e=="string"?X(e):e,i=Ft(n),s=Ft(r),o=Math.max(i,s),a=Math.min(i,s);return(o+.05)/(a+.05)},jr=(t,e=null)=>{const n=X(t,e),r=et(n,{r:255,g:255,b:255,a:1}),i=et(n,{r:0,g:0,b:0,a:1});return r>i},Qn=(t,e=null)=>jr(t,e)?"white":"black",yl=t=>{const e=t.a!==void 0?t.a:1;return`rgba(${Math.round(t.r)}, ${Math.round(t.g)}, ${Math.round(t.b)}, ${e})`},bl=(t,e)=>({r:Math.min(255,t.r+(255-t.r)*e),g:Math.min(255,t.g+(255-t.g)*e),b:Math.min(255,t.b+(255-t.b)*e),a:t.a??1}),vl=(t,e)=>({r:Math.max(0,t.r*(1-e)),g:Math.max(0,t.g*(1-e)),b:Math.max(0,t.b*(1-e)),a:t.a??1}),te=(t,e=null,n=3)=>{const r=X(t),i=e?X(e):{r:255,g:255,b:255,a:1};let s=et(r,i);if(s>=n)return t;const o=Ft(i)<.5;let a={...r,a:r.a??1};const c=20,l=.1;for(let d=0;d<c&&(o?a=bl(a,l):a=vl(a,l),s=et(a,i),!(s>=n));d++);return yl(a)},Vr=()=>typeof navigator>"u"?"":navigator.userAgent||"",Fr=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;let Mr=class{constructor(){const e=Fr(),n=Vr(),r=s=>(typeof s=="string"||typeof s=="number")&&s?String(s).replace(/_/g,".").split(".").map(o=>parseInt(o)||0):[],i=(s="")=>{if(!s)return[];const o=new RegExp("^.*"+s+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return o.test(n)?r(n.replace(o,"$1")):[]};this.OS=(s=>(/(macOS|Mac OS X)/.test(n)?(/\(iP(hone|od touch);/.test(n)&&(s.iOS=i("CPU (?:iPhone )?OS ")),/\(iPad;/.test(n)?s.iOS=s.iPadOS=i("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(n)&&(document.ontouchend!==void 0?s.iOS=s.iPadOS=i():s.macOS=i("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(n)?s.Windows=(o=>o[0]!==6||!o[1]?o:o[1]===1?[7]:o[1]===2?[8]:[8,1])(i("Windows(?: NT)?")):/Android \d/.test(n)?s.Android=i("Android"):/CrOS/.test(n)?s.ChromeOS=i():/X11;/.test(n)&&(s.Linux=i()),s))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(s=>(o=>{const a=s.platform,c=s.platformVersion;if(!(!a||!c)){if(/^i(OS|P(hone|od touch))$/.test(a))o.iOS=r(c);else if(/^iPad(OS)?$/.test(a))o.iOS=o.iPadOS=r(c);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(a))document.ontouchend!==void 0?o.iOS=o.iPadOS=r():o.macOS=r(c);else if(/^(Microsoft )?Windows$/.test(a))o.Windows=r(c);else if(/^(Google )?Android$/.test(a))o.Android=r(c);else if(/^((Google )?Chrome OS|CrOS)$/.test(a))o.ChromeOS=r(c);else if(/^(Linux|Ubuntu|X11)$/.test(a))o.Linux=r(c);else return;Object.keys(this.OS).forEach(l=>delete this.OS[l]),Object.assign(this.OS,o)}})({})),this.UA=(s=>{let o=!1;if(e&&Array.isArray(e.brands)){const a=e.brands.reduce((c,l)=>(c[l.brand]=[l.version*1],c),{});a["Google Chrome"]?(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Chrome=a["Google Chrome"]):a["Microsoft Edge"]?(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Edge=a["Microsoft Edge"]):a.Opera&&(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Opera=a.Opera)}return o||(/ Gecko\/\d/.test(n)?(s.Gecko=i("rv"),/ Waterfox\/\d/.test(n)?s.Waterfox=i("Waterfox"):/ Firefox\/\d/.test(n)&&(s.Firefox=i("Firefox"))):/ Edge\/\d/.test(n)?(s.EdgeHTML=i("Edge"),s.Edge=s.EdgeHTML):/ Chrom(ium|e)\/\d/.test(n)?(s.Blink=s.Chromium=(a=>a[0]?a:i("Chrome"))(i("Chromium")),/ EdgA?\/\d/.test(n)?s.Edge=(a=>a[0]?a:i("Edg"))(i("EdgA")):/ OPR\/\d/.test(n)?s.Opera=i("OPR"):/ Vivaldi\/\d/.test(n)?s.Vivaldi=i("Vivaldi"):/ Silk\/\d/.test(n)?s.Silk=i("Silk"):/ UCBrowser\/\d/.test(n)?s.UCBrowser=i("UCBrowser"):/ Phoebe\/\d/.test(n)?s.Phoebe=i("Phoebe"):s.Chrome=(a=>a[0]?a:s.Chromium)(i("Chrome"))):/ AppleWebKit\/\d/.test(n)?(s.WebKit=i("AppleWebKit"),/ CriOS \d/.test(n)?s.Chrome=i("CriOS"):/ FxiOS \d/.test(n)?s.Firefox=i("FxiOS"):/ EdgiOS\/\d/.test(n)?s.Edge=i("EdgiOS"):/ Version\/\d/.test(n)&&(s.Safari=i("Version"))):/ Trident\/\d/.test(n)&&(s.Trident=i("Trident"),s.InternetExplorer=(a=>a[0]?a:i("MSIE"))(i("rv")))),/[\[; ]FB(AN|_IAB)\//.test(n)&&(s.Facebook=i("FBAV")),/ Line\/\d/.test(n)&&(s.LINE=i("Line")),s})({}),this.Env={get:()=>[this.OS,this.UA].reduce((s,o)=>{for(const a in o)o[a]&&s.push(a);return s},[])}}};class wl extends Mr{get iOSRequest(){const e=Fr(),n=Vr();if(this.OS.iOS&&!this.OS.iPadOS)return"mobile";if(this.OS.iPadOS)return/\(iPad;/.test(n)||e&&/^iPad(OS)?$/.test(e.platform)?"mobile":"desktop"}}const Sl=new Mr;new wl;const Xn=["div","span","p","br","hr","b","i","em","strong","s","u","mark","small","sub","sup","abbr","cite","code","data","dfn","kbd","q","samp","time","var","blockquote","pre","svg","g","path","circle","ellipse","rect","line","polygon","polyline","text","tspan","defs","use"],xl=/^on/i,kl=new Set(["href","src","action","formaction","xlink:href"]),Cl=/^\s*(javascript|data):/i;function El(t,e){const n=t.document.createElement("div");if("Sanitizer"in t&&typeof n.setHTML=="function")try{const i=new t.Sanitizer({allowElements:Xn});return n.setHTML(e,{sanitizer:i}),n.firstElementChild}catch{}const r=t.document.implementation.createHTMLDocument("");for(r.body.innerHTML=e,Al(r.body,new Set(Xn));r.body.firstChild;)n.appendChild(t.document.adoptNode(r.body.firstChild));return n.firstElementChild}function Al(t,e){const n=Array.from(t.querySelectorAll("*")).reverse();for(const r of n){if(!e.has(r.localName)){r.replaceWith(...Array.from(r.childNodes));continue}for(const{name:i,value:s}of Array.from(r.attributes))(xl.test(i)||kl.has(i)&&Cl.test(s))&&r.removeAttribute(i)}}function Ct(t){switch(t){case A.Mask:return"rgba(255, 255, 255, 0.5)";case A.Highlight:case A.HighlightUnderline:return"#FFFF00";default:return"#FF0000"}}const A={Highlight:"highlight",HighlightUnderline:"highlightUnderline",Underline:"underline",Strikethrough:"strikethrough",Outline:"outline",TextColor:"textColor",Mask:"mask",Template:"template"};var Hr=(t=>(t.Wrap="wrap",t.Viewport="viewport",t.Bounds="bounds",t.Page="page",t))(Hr||{}),Gr=(t=>(t.Boxes="boxes",t.Bounds="bounds",t))(Gr||{});const Ol=()=>"Highlight"in window,Zn=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Tl{constructor(e,n,r,i){this.wnd=e,this.comms=n,this.id=r,this.name=i,this.items=[],this.lastItemId=0,this.container=void 0,this._activatable=!1,this._hoverable=!1,this.hoveredItem=void 0,this.experimentalHighlights=!1,this._tintSubKeys=new Map,this._subKeyCounter=0,this.maskSvg=void 0,this.shadowHost=void 0,this.shadowRoot=void 0,this.currentRender=0,Ol()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map),this.activationHandler=this.handleActivation.bind(this),this.wnd.document.addEventListener("pointerup",this.activationHandler),this.hoverHandler=this.handleHover.bind(this),this.wnd.document.addEventListener("pointermove",this.hoverHandler)}get activatable(){return this._activatable}set activatable(e){this._activatable=e}get hoverable(){return this._hoverable}set hoverable(e){if(this._hoverable=e,!e&&this.hoveredItem){const n=this.hoveredItem.range.getBoundingClientRect(),r=this.wnd.devicePixelRatio;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:{top:n.top*r,left:n.left*r,width:n.width*r,height:n.height*r}}),this.hoveredItem=void 0}}add(e){const n=`${this.id}-${this.lastItemId++}`,r=cl(this.wnd.document,e.locator);if(!r){this.comms.log("Can't locate DOM range for decoration",e);return}const i=r.commonAncestorContainer;if(i.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(Zn.includes(i.nodeName.toUpperCase())&&this.notTextFlag?.set(n,!0),r.cloneContents().querySelector(Zn.join(", ").toLowerCase())&&this.notTextFlag?.set(n,!0),(i.textContent?.trim()||"").length===0&&this.notTextFlag?.set(n,!0)),this.experimentalHighlights&&!this.notTextFlag?.has(n)){const o=a=>{for(;a&&a.nodeType===Node.ELEMENT_NODE;){if(a.namespaceURI?.includes("svg"))return!0;a=a.parentNode}return!1};(o(r.startContainer)||o(r.endContainer))&&this.notTextFlag?.set(n,!0)}if(this.experimentalHighlights){const{type:o}=e.style,{layout:a,width:c,expand:l}=e.style;o!==A.TextColor&&(o===A.Outline||o===A.Template||o===A.Mask||a!==void 0&&a!=="boxes"||c!==void 0&&c!=="wrap"||l)&&this.notTextFlag?.set(n,!0)}const s={decoration:e,id:n,range:r,hitRects:[],clickableElements:void 0,container:void 0};this.items.push(s),this.layout(s),s.hitRects=this.clientRectsToDocCoords(Ge(s.range,!1,!1,(s.decoration.style.expand??0)+this.hitGap())),this.renderLayout([s])}remove(e){const n=this.items.findIndex(s=>s.decoration.id===e);if(n<0)return;const r=this.items[n],i=r.decoration.style?.type===A.Mask;if(this.items.splice(n,1),r.clickableElements=void 0,r.container&&(r.container.remove(),r.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(r.id)&&r.highlightSubKey){const s=this.wnd.CSS.highlights;s.get(r.highlightSubKey)?.delete(r.range),this.items.some(a=>a.highlightSubKey===r.highlightSubKey)||s.delete(r.highlightSubKey);const o=this.wnd.document.getElementById(`${this.id}-style`);o&&this._rebuildHighlightStylesheet(o)}this.notTextFlag?.delete(r.id),this.hoveredItem===r&&(this.hoveredItem=void 0),i&&this.updateSharedMask()}update(e){this.remove(e.id),this.add(e)}clear(){this.clearContainer(),this.items.length=0,this.notTextFlag?.clear(),this.hoveredItem=void 0,this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowHost&&(this.shadowHost.remove(),this.shadowHost=void 0,this.shadowRoot=void 0)}destroy(){this.clear(),this.wnd.document.removeEventListener("pointerup",this.activationHandler),this.wnd.document.removeEventListener("pointermove",this.hoverHandler)}clientRectsToDocCoords(e){const n=Ce(this.wnd),r=n.xDocOffset,i=n.yDocOffset;return r===0&&i===0?e:e.map(s=>({left:s.left+r,top:s.top+i,right:s.right+r,bottom:s.bottom+i,width:s.width,height:s.height}))}pointerToDocCoords(e){const n=Ce(this.wnd);return{docX:e.clientX+n.xDocOffset,docY:e.clientY+n.yDocOffset}}effectiveZoom(){if(!Sl.UA.Blink)return 1;const e=parseFloat(this.wnd.getComputedStyle(this.wnd.document.documentElement).zoom),n=parseFloat(this.wnd.getComputedStyle(this.wnd.document.body).zoom);return(e||1)*(n||1)}hitGap(){return 2*this.effectiveZoom()}handleActivation(e){if(!this._activatable)return;const{docX:n,docY:r}=this.pointerToDocCoords(e),i=this.wnd.devicePixelRatio;for(const s of this.items){let o;if(s.decoration.style.type===A.Template)for(const a of s.clickableElements??[]){const c=a.getBoundingClientRect();if(K(c,e.clientX,e.clientY,0)){o=c;break}}else for(const a of s.hitRects)if(K(a,n,r,0)){o=s.range.getBoundingClientRect();break}if(o){this.comms.send("decoration_activated",{decorationId:s.decoration.id,group:this.name,rect:{top:o.top*i,left:o.left*i,width:o.width*i,height:o.height*i},point:{x:e.clientX*i,y:e.clientY*i}});return}}}handleHover(e){if(!this._hoverable)return;const{docX:n,docY:r}=this.pointerToDocCoords(e),i=this.wnd.devicePixelRatio;let s,o;for(const a of this.items){if(a.decoration.style.type===A.Template)for(const c of a.clickableElements??[]){const l=c.getBoundingClientRect();if(K(l,e.clientX,e.clientY,0)){s=a,o=l;break}}else for(const c of a.hitRects)if(K(c,n,r,0)){s=a,o=a.range.getBoundingClientRect();break}if(s)break}if(s!==this.hoveredItem){if(this.hoveredItem){const a=this.hoveredItem.range.commonAncestorContainer.isConnected?this.hoveredItem.range.getBoundingClientRect():null;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:a?{top:a.top*i,left:a.left*i,width:a.width*i,height:a.height*i}:void 0,point:{x:e.clientX*i,y:e.clientY*i}})}this.hoveredItem=s,s&&o&&this.comms.send("decoration_pointer_enter",{decorationId:s.decoration.id,group:this.name,rect:{top:o.top*i,left:o.left*i,width:o.width*i,height:o.height*i},point:{x:e.clientX*i,y:e.clientY*i}})}}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.wnd.document.fonts.ready.then(()=>{this.currentRender=this.wnd.requestAnimationFrame(()=>{this.items.forEach(e=>{this.layout(e),e.hitRects=this.clientRectsToDocCoords(Ge(e.range,!1,!1,(e.decoration.style.expand??0)+this.hitGap()))}),this.renderLayout(this.items),this.updateSharedMask()})})}experimentalLayout(e){const n=this.requireContainer(!0),r=this.wnd.CSS.highlights,i=e.decoration.style,s=i.type??A.Highlight,o=i.tint??Ct(s),a=i.width,c=i.layout,l=this._getSubKey(s,o);e.highlightSubKey&&(r.get(e.highlightSubKey)?.delete(e.range),e.highlightSubKey!==l&&!this.items.some(p=>p!==e&&p.highlightSubKey===e.highlightSubKey)&&r.delete(e.highlightSubKey)),e.highlightSubKey=l;let d;r.has(l)?d=r.get(l):(d=new this.wnd.Highlight,r.set(l,d));const u=(p,m)=>this.wnd.document.caretPositionFromPoint?.(p,m)??null;if(s===A.TextColor&&(c==="bounds"||a==="bounds"||a==="page")){const p=Ce(this.wnd);if(p.isVertical)console.warn("Vertical writing detected: caretPositionFromPoint has known bugs, falling back to original range"),d.add(e.range);else{const m=e.range.getBoundingClientRect();let w,E;a==="page"?(w=Math.floor(p.inlineStart(m)/p.pageInlineSize)*p.pageInlineSize,E=p.pageInlineSize):(w=p.inlineStart(m),E=p.inlineSize(m));const C=u(w,p.blockStart(m)+1),P=u(w+E,p.blockStart(m)+p.blockSize(m)-1);if(C&&P){const I=this.wnd.document.createRange();I.setStart(C.offsetNode,C.offset),I.setEnd(P.offsetNode,P.offset),d.add(I),e.range=I}else d.add(e.range)}}else d.add(e.range);const g=this.getBackgroundColor(),f=i.enforceContrast!==!1?te(o,g):o;let y;switch(s){case A.Underline:y=`::highlight(${l}) {
|
|
25
|
+
`:O}`,b===a.lastClosingBracketAt+1&&(!t[b]||!Ct.has(t[b]))&&(T+=" "),a.leftOuterWhitespace===a.lastOpeningBracketAt&&A.last()&&A.last()[1]<a.lastOpeningBracketAt&&(!v?.dumpLinkHrefsNearby?.putOnNewLine||!Ct.has(t[b]))&&(T=" "+T)):T=O,T!==null&&(a.leftOuterWhitespace===0||!B(t,b-1))&&(!v.dumpLinkHrefsNearby?.enabled||a.name!=="a")&&(T=void 0);let N=0;if(p&&Ct.has(t[b])){v.dumpLinkHrefsNearby?.putOnNewLine&&(T=`${t[b]}${T||""}`);let Y=B(t,b);Y&&T?.endsWith(`
|
|
26
|
+
`)?N+=Y-h:(!Y||Y>h)&&N++}v.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:b+N,insert:T,rangesArr:A,proposedReturn:[a.leftOuterWhitespace,b+N,T]}),ke(),x(h,v,A)}else a={};U(h)||(a={})}H&&(H=!1)}if((!J||t[h]==="<"&&B(t,B(t,h))&&t[B(t,h)]==="/"&&t.startsWith("script",B(t,B(t,h))))&&q(h)&&!q(h-1)&&!`'"`.includes(t[h+1])&&(!`'"`.includes(t[h+2])||/\w/.test(t[h+1]))&&!(t[h+1]==="c"&&t[h+2]===":")&&!(t[h+1]==="f"&&t[h+2]==="m"&&t[h+3]==="t"&&t[h+4]===":")&&!(t[h+1]==="s"&&t[h+2]==="q"&&t[h+3]==="l"&&t[h+4]===":")&&!(t[h+1]==="x"&&t[h+2]===":")&&!(t[h+1]==="f"&&t[h+2]==="n"&&t[h+3]===":")&&Kr(a,t,h)){if(U(B(t,h)))continue;if(a.nameEnds&&a.nameEnds<h&&!a.lastClosingBracketAt&&(a.onlyPlausible===!0&&a.attributes?.length||a.onlyPlausible===!1)){let b=R(t,h,a.leftOuterWhitespace,h,a.lastOpeningBracketAt,h);v.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:h,insert:b,rangesArr:A,proposedReturn:[a.leftOuterWhitespace,h,b]}),x(h,v,A),a={},f={}}if(a.lastOpeningBracketAt!==void 0&&a.onlyPlausible&&a.name&&!a.quotes&&(a.lastOpeningBracketAt=void 0,a.name=void 0,a.onlyPlausible=!1),(a.lastOpeningBracketAt===void 0||!a.onlyPlausible)&&!a.quotes&&(a.lastOpeningBracketAt=h,a.slashPresent=!1,a.attributes=[],l===null?a.leftOuterWhitespace=h:v.trimOnlySpaces&&l===0?a.leftOuterWhitespace=d||h:a.leftOuterWhitespace=l,`${t[h+1]}${t[h+2]}${t[h+3]}`=="!--"||`${t[h+1]}${t[h+2]}${t[h+3]}${t[h+4]}${t[h+5]}${t[h+6]}${t[h+7]}${t[h+8]}`=="![CDATA[")){let b=!0;t[h+2]==="-"&&(b=!1);let k;for(let S=h;S<D;S++)if((!k&&b&&`${t[S-2]}${t[S-1]}${t[S]}`=="]]>"||!b&&`${t[S-2]}${t[S-1]}${t[S]}`=="-->")&&(k=S),k&&(k<S&&t[S].trim()||t[S+1]===void 0)){let O=S;(t[S+1]===void 0&&!t[S].trim()||t[S]===">")&&(O+=1),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,k+1]),(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([a.lastOpeningBracketAt,k+1]);let T=R(t,S,a.leftOuterWhitespace,O,a.lastOpeningBracketAt,k);v.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:O,insert:T,rangesArr:A,proposedReturn:[a.leftOuterWhitespace,O,T]}),h=S-1,t[S]===">"&&(h=S),a={},f={};break}}}!t[h].trim()||t[h].charCodeAt(0)===847?(l===null&&(l=h,a.lastOpeningBracketAt!==void 0&&a.lastOpeningBracketAt<h&&a.nameStarts&&a.nameStarts<a.lastOpeningBracketAt&&h===a.lastOpeningBracketAt+1&&!n.some(b=>b.name===a.name)&&(a.onlyPlausible=!0,a.name=void 0,a.nameStarts=void 0)),(t[h]===`
|
|
27
|
+
`||t[h]==="\r")&&(u=h,g&&(g=!1))):(l!==null&&(!a.quotes&&f.equalsAt>l-1&&f.nameEnds&&f.equalsAt>f.nameEnds&&t[h]!=='"'&&t[h]!=="'"&&(zt(f)&&a.attributes.push(f),f={},a.equalsSpottedAt=void 0),l=null),g||(g=!0,E&&!J&&typeof u=="number"&&h&&u<h-1&&(t.slice(u+1,h).trim()?u=null:v.ignoreIndentations||A.push([u+1,h])))),t[h]===" "?d===null&&(d=h):d!==null&&(d=null),a.name==="script"&&(J=!a.slashPresent)}if(t&&!v.ignoreIndentations&&(v.trimOnlySpaces&&t[0]===" "||!v.trimOnlySpaces&&!t[0].trim()))for(let h=0;h<D;h++)if(v.trimOnlySpaces&&t[h]!==" "||!v.trimOnlySpaces&&t[h].trim()){A.push([0,h]);break}else t[h+1]||A.push([0,h+1]);if(t&&(v.trimOnlySpaces&&t[~-t.length]===" "||!v.trimOnlySpaces&&!t[~-t.length].trim())){for(let h=t.length;h--;)if(v.trimOnlySpaces&&t[h]!==" "||!v.trimOnlySpaces&&t[h].trim()){A.push([h+1,D]);break}}let W=A.current();if(!e?.cb&&W&&(W[0]&&!W[0][0]&&(W[0][1],A.ranges[0]=[A.ranges[0][0],A.ranges[0][1]]),W[W.length-1]?.[1]===t.length&&(W[W.length-1][0],A.ranges))){let h=A.ranges[A.ranges.length-1][0];t[h-1]&&(v.trimOnlySpaces&&t[h-1]===" "||!v.trimOnlySpaces&&!t[h-1].trim())&&(h-=1);let b=A.ranges[A.ranges.length-1][2];A.ranges[A.ranges.length-1]=[h,A.ranges[A.ranges.length-1][1]],b?.trim()&&A.ranges[A.ranges.length-1].push(b.trimEnd())}return{log:{timeTakenInMilliseconds:Date.now()-r},result:jo(t,A.current()),ranges:A.current(),allTagLocations:s,filteredTagLocations:o}}class Ft{speechSynthesis;speechSynthesisUtterance;currentVoice=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new dt;voiceManager=null;voices=[];defaultVoice=null;speakInContentLanguage=!1;languageVoiceCache=new Map;warmingLanguages=new Map;speakGeneration=0;resumeInfinityTimer;isSpeakingInternal=!1;isPausedInternal=!1;isAndroidPaused=!1;pausedAtUtteranceIndex=null;initialized=!1;maxLengthExceeded="warn";utterancesBeingCancelled=!1;rate=1;pitch=1;volume=1;features;patches;constructor(){if(this.features=fs(),this.patches=ps(),!this.features.speechSynthesis||!this.features.speechSynthesisUtterance)throw new Error("Web Speech API is not available in this environment");this.speechSynthesis=this.features.speechSynthesis,this.speechSynthesisUtterance=this.features.speechSynthesisUtterance}shouldUseResumeInfinity(){const e=this.currentVoice,r=!!(e?.name&&typeof e.name=="string"&&e.name.toLocaleLowerCase().includes("(natural)"));return this.patches.isAndroid!==!0&&!this.patches.isFirefox&&!this.patches.isSafari&&!r}createUtterance(e){return new this.speechSynthesisUtterance(e)}async initialize(e={}){const{languages:r,maxTimeout:n,interval:i,maxLengthExceeded:s="warn"}=e;if(this.initialized)return!1;this.maxLengthExceeded=s;try{this.voiceManager=await P.initialize({languages:r,maxTimeout:n,interval:i}),this.voices=this.voiceManager.getVoices();const o=r||[...navigator.languages||["en"]];return this.defaultVoice=await this.voiceManager.getDefaultVoice(o,this.voices),this.initialized=!0,!0}catch(o){return console.error("Failed to initialize WebSpeechEngine:",o),this.initialized=!1,!1}}validateText(e){if(new TextEncoder().encode(e).length>4096){const n="Text exceeds max length of 4096 bytes, which may not work with some voices.";switch(this.maxLengthExceeded){case"none":break;case"error":throw new Error(`WebSpeechEngine: ${n}`);default:console.warn(`WebSpeechEngine: ${n}`)}}}getCurrentVoiceForUtterance(e){return e&&typeof e=="object"?e:typeof e=="string"?this.voices.find(r=>r.name===e||r.language===e)||null:this.currentVoice||this.defaultVoice}voiceMatchesLanguage(e,r){const[n,i]=L(r),[s,o]=L(e.language);return s===n&&(!i||o===i)}voiceForUtteranceSync(e){const r=this.getCurrentVoiceForUtterance(this.currentVoice);if(!this.speakInContentLanguage||!e.language)return r;const n=$(e.language);if(r&&this.voiceMatchesLanguage(r,n))return r;if(this.languageVoiceCache.has(n))return this.languageVoiceCache.get(n)??r}async voiceForUtterance(e){const r=this.voiceForUtteranceSync(e);return r!==void 0?r:(await this.warmLanguageVoiceCache([e]),this.voiceForUtteranceSync(e)??this.getCurrentVoiceForUtterance(this.currentVoice))}async warmLanguageVoiceCache(e){if(!this.speakInContentLanguage||!this.voiceManager)return;const r=new Set(e.map(o=>o.language).filter(o=>!!o).map(o=>$(o)).filter(o=>!this.languageVoiceCache.has(o))),n=[...r].filter(o=>this.warmingLanguages.has(o)),s=[...r].filter(o=>!this.warmingLanguages.has(o)).map(o=>{const a=(async()=>{await P.initialize({languages:[o]}),this.voices=this.voiceManager.getVoices();const c=this.voices.filter(u=>this.voiceMatchesLanguage(u,o)),d=(await this.voiceManager.sortVoicesByQuality(c))[0]??null;this.languageVoiceCache.set(o,d),d||this.emitEvent({type:"languagefallback",detail:{language:o,reason:"no-matching-voice"}})})();return this.warmingLanguages.set(o,a.finally(()=>this.warmingLanguages.delete(o))),this.warmingLanguages.get(o)});await Promise.all([...s,...n.map(o=>this.warmingLanguages.get(o))])}getCurrentVoice(){return this.currentVoice}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,e&&this.warmLanguageVoiceCache(this.currentUtterances)}getSpeakInContentLanguage(){return this.speakInContentLanguage}toPlainText(e){return e.map(r=>({...r,plain:r.plain??(r.ssml?_n(r.ssml).result:"")}))}loadUtterances(e,r){this.currentUtterances=this.toPlainText(e),this.currentUtteranceIndex=Xe(r??0,e.length),this.warmLanguageVoiceCache(this.currentUtterances),this.playbackState="ready",this.emitEvent({type:"ready"})}async setVoice(e){const r=this.currentVoice;if(typeof e=="string"){const n=this.voices.find(i=>i.name===e||i.language===e);n?(this.currentVoice=n,r&&r.name!==n.name&&(this.currentUtteranceIndex=0)):console.warn(`Voice "${e}" not found`)}else this.currentVoice=e,r&&r.name!==e.name&&(this.currentUtteranceIndex=0);this.voiceManager&&this.defaultVoice&&this.currentVoice&&this.currentVoice.language!==this.defaultVoice.language&&(this.defaultVoice=await this.voiceManager.getDefaultVoice([this.currentVoice.language],this.voices))}async getAvailableVoices(){if(this.voices.length>0)return this.voices;try{return await this.initialize(),this.voices}catch{return[]}}speak(e){if(e!==void 0){if(e<0||e>=this.currentUtterances.length)throw new Error("Invalid utterance index");this.currentUtteranceIndex=e}if(this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.cancelCurrentSpeech();const r=++this.speakGeneration;this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.emitEvent({type:"start"}),this.stopResumeInfinity(),this.currentUtteranceIndex>=this.currentUtterances.length&&(this.currentUtteranceIndex=0),this.speakCurrentUtterance(r)}cancelCurrentSpeech(){this.patches.isFirefox&&this.speechSynthesis.speaking&&(this.utterancesBeingCancelled=!0,setTimeout(()=>{this.utterancesBeingCancelled=!1},100)),this.speechSynthesis.cancel()}async speakCurrentUtterance(e){if(this.currentUtteranceIndex>=this.currentUtterances.length){this.setState("idle"),this.emitEvent({type:"end"});return}const r=this.currentUtterances[this.currentUtteranceIndex],n=r.plain??"";this.validateText(n);const i=this.createUtterance(n),s=await this.voiceForUtterance(r);if(e===this.speakGeneration){if(s&&this.voiceManager){const o=this.voiceManager.convertToSpeechSynthesisVoice(s);o&&(i.voice=o,i.lang=o.lang)}r.language&&(i.lang=r.language),i.rate=this.rate,i.pitch=this.pitch,i.volume=this.volume,i.onstart=()=>{this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.emitEvent({type:"start"}),this.patches.isAndroid&&this.isAndroidPaused&&(this.isAndroidPaused=!1),this.shouldUseResumeInfinity()&&this.startResumeInfinity(i)},i.onend=()=>{if(this.utterancesBeingCancelled){this.utterancesBeingCancelled=!1;return}this.playbackState!=="idle"&&(this.isSpeakingInternal=!1,this.isPausedInternal=!1,this.stopResumeInfinity(),this.currentUtteranceIndex>=this.currentUtterances.length-1&&this.setState("idle"),this.emitEvent({type:"end"}))},i.onerror=o=>{if(o.error==="interrupted"&&this.patches.isAndroid&&this.isAndroidPaused)return;this.isSpeakingInternal=!1,this.isPausedInternal=!1,this.stopResumeInfinity(),this.setState("idle"),["synthesis-unavailable","audio-hardware","voice-unavailable"].includes(o.error)&&(console.log("[ENGINE] fatal error detected, resetting index to 0"),this.currentUtteranceIndex=0),o.error==="interrupted"||o.error==="canceled"?this.emitEvent({type:"stop"}):this.emitEvent({type:"error",detail:{error:o.error,message:`Speech synthesis error: ${o.error}`}})},i.onpause=()=>{this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.emitEvent({type:"pause"})},i.onresume=()=>{this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.emitEvent({type:"resume"})},i.onboundary=o=>{this.emitEvent({type:"boundary",detail:{charIndex:o.charIndex,charLength:o.charLength,elapsedTime:o.elapsedTime,name:o.name}})},i.onmark=o=>{this.emitEvent({type:"mark",detail:{name:o.name}})},this.speechSynthesis.speak(i)}}startResumeInfinity(e){this.shouldUseResumeInfinity()&&(this.resumeInfinityTimer=window.setTimeout(()=>{if(e){const{paused:n,speaking:i}=this.speechSynthesis,s=i||this.isSpeakingInternal,o=n||this.isPausedInternal;s&&!o&&(this.speechSynthesis.pause(),this.speechSynthesis.resume())}this.startResumeInfinity(e)},5e3))}stopResumeInfinity(){this.resumeInfinityTimer&&(clearTimeout(this.resumeInfinityTimer),this.resumeInfinityTimer=void 0)}pause(){this.playbackState==="playing"&&(this.pausedAtUtteranceIndex=this.currentUtteranceIndex,this.patches.isAndroid?(this.isAndroidPaused=!0,this.speechSynthesis.cancel()):this.speechSynthesis.pause(),this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.currentUtteranceIndex<this.currentUtterances.length&&(this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.setState("playing"),this.emitEvent({type:"resume"}),this.patches.isAndroid||this.pausedAtUtteranceIndex!==this.currentUtteranceIndex?this.speak(this.currentUtteranceIndex):this.speechSynthesis.resume(),this.pausedAtUtteranceIndex=null)}stop(){this.speechSynthesis.cancel(),this.speakGeneration++,this.currentUtteranceIndex=0,this.patches.isAndroid&&(this.isAndroidPaused=!1),this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){this.rate=Math.max(.1,Math.min(10,e))}getRate(){return this.rate}setPitch(e){this.pitch=Math.max(0,Math.min(2,e))}getPitch(){return this.pitch}setVolume(e){this.volume=Math.max(0,Math.min(1,e))}getVolume(){return this.volume}getState(){return this.playbackState}getCurrentUtteranceIndex(){return this.currentUtteranceIndex}setCurrentUtteranceIndex(e,r){if(e<0||e>=this.currentUtterances.length){r?.(!1);return}e!==this.currentUtteranceIndex&&(!this.isPausedInternal&&this.isSpeakingInternal&&this.cancelCurrentSpeech(),this.currentUtteranceIndex=e,r?.(!0))}getUtteranceCount(){return this.currentUtterances.length}on(e,r){return this.events.on(e,r)}emitEvent(e){this.events.emit(e.type,e)}setState(e){const r=this.playbackState;if(this.playbackState=e,r!==e)switch(e){case"idle":this.emitEvent({type:"idle"});break;case"loading":this.emitEvent({type:"loading"});break;case"ready":this.emitEvent({type:"ready"});break}}async destroy(){this.stop(),this.stopResumeInfinity(),this.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[],this.defaultVoice=null,this.languageVoiceCache.clear(),this.warmingLanguages.clear(),this.initialized=!1}}class Qo{id="webspeech";name="Web Speech API";voiceEngine=null;async getVoices(){return this.voiceEngine||(this.voiceEngine=new Ft,await this.voiceEngine.initialize()),this.voiceEngine.getAvailableVoices()}async createEngine(e){const r=new Ft;return await r.initialize(),e&&await r.setVoice(e),r}async destroy(){this.voiceEngine&&(await this.voiceEngine.destroy(),this.voiceEngine=null)}}const le="\\p{Pe}\\p{Pf}.,;:!?,。、;:!?،؛؟",Ht="\\p{Ps}\\p{Pi}¿¡",Xo=new RegExp(`^[${le}]`,"u"),Zo=new RegExp(`^[${Ht}]`,"u");function pt(t){return Xo.test(t)}function Yo(t){return Zo.test(t)}function Dn(t,e){const r=[];let n=-1,i=-1;const s=()=>{n!==-1&&(r.push({text:el(t,n,i),offset:t[n].offset}),n=-1,i=-1)};for(let o=0;o<t.length;o++){const a=t[o];if(a.text.length>e){s(),r.push({text:a.text,offset:a.offset});continue}const c=a.offset+a.text.length,l=n===-1?a.text.length:c-t[n].offset;n!==-1&&l>e&&s(),n===-1&&(n=o),i=o}return s(),r}function el(t,e,r){const n=t[e],i=t[r];return n===i?n.text:t.slice(e,r+1).map(s=>s.text).join("")}const $n=new RegExp(`[^${le}]*[${le}]+\\s*|[^${le}]+$`,"gu"),tl=/\S+\s*|\s+/g;function ur(t,e,r){const n=[];for(const i of t.matchAll(r))i[0].length!==0&&n.push({text:i[0],offset:e+i.index,atomic:!1});return n}function hr(t,e){if(t.text.length<=e||t.atomic)return[t];const r=ur(t.text,t.offset,tl);if(r.length>1)return r.flatMap(o=>hr(o,e));const n=[];let i=t.offset,s="";for(const o of t.text)s.length>0&&s.length+o.length>e&&(n.push({text:s,offset:i,atomic:!1}),i+=s.length,s=""),s+=o;return s.length>0&&n.push({text:s,offset:i,atomic:!1}),n}function Un(t,e){if(t.length<=e)return[{text:t,offset:0}];const n=ur(t,0,$n).flatMap(i=>hr(i,e));return Dn(n,e)}const rl=/<([a-zA-Z][\w-]*)\b[^>]*>[\s\S]*?<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function Bn(t,e){if(t.length<=e)return[{text:t,offset:0}];const r=[];for(const i of t.matchAll(rl))i[0][0]==="<"?r.push({text:i[0],offset:i.index,atomic:!0}):r.push(...ur(i[0],i.index,$n));const n=r.flatMap(i=>hr(i,e));return Dn(n,e)}const nl={wav:"audio/wav",mp3:"audio/mpeg",opus:"audio/ogg",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",m4a:"audio/mp4"};function Vn(t){return nl[t]??`audio/${t}`}const il=["flac","wav","opus","aac","ogg","webm","mp3"],sl=["opus","aac","webm","ogg","mp3","wav","flac"];function zn(t,e,r){const n=a=>r(Vn(a))!=="",i=t.formats.filter(n);if(e.preferredFormat&&i.includes(e.preferredFormat))return e.preferredFormat;const s=e.strategy==="bandwidth"?sl:il,o=[...s,...i.filter(a=>!s.includes(a))];for(const a of o)if(i.includes(a))return a;return t.default}const al=new Set(["wav","flac"]),ol={mp3:48e3,opus:24e3,aac:48e3,ogg:48e3,webm:32e3};function jn(t,e,r){return al.has(t)||!e||!r?void 0:r.saveData===!0||/2g/.test(r.effectiveType??"")?ol[t]:void 0}function dr(t,e){return{source:"server",label:t.name,name:t.name,originalName:t.originalName,language:t.language,otherLanguages:t.otherLanguages,gender:t.gender??void 0,quality:t.quality,provider:t.provider,identifier:t.identifier,controls:e}}class ye extends Error{status;type;title;instance;constructor(e,r){super(e),this.name="SpeechServerError",this.status=r.status,this.type=r.type,this.title=r.title,this.instance=r.instance}}class gr extends ye{constructor(e){super(e,{status:408,type:"https://readium.org/speech-server/error#stall",title:"Synthesis Stalled"}),this.name="SpeechServerStallError"}}class fr extends Error{constructor(e){super(e),this.name="SpeechServerAudioDecodeError"}}class pr extends Error{constructor(e){super(e),this.name="SpeechServerNetworkError"}}async function ce(t){if((t.headers.get("content-type")??"").includes("application/problem+json"))try{const r=await t.json();return new ye(r.detail||r.title||`Request failed with status ${t.status}`,{status:r.status??t.status,type:r.type,title:r.title,instance:r.instance})}catch{}return new ye(`Request failed with status ${t.status}`,{status:t.status})}const ll=3,cl=400;function ul(t){const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r.buffer}function hl(t){return Math.max(.25,Math.min(4,t))}function Fe(t){return t?.plain??t?.ssml??void 0}function Xr(t){return t instanceof gr?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance,recoverable:!0}:t instanceof ye?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance,recoverable:!1}:t instanceof fr?{message:t.message,recoverable:!1}:t instanceof pr?{message:t.message,recoverable:!0}:t instanceof Error?{message:t.message,recoverable:!1}:{message:String(t),recoverable:!1}}class Mn{endpoints;fetchImpl;currentVoice=null;voices=[];serviceInfo=null;serviceInfoPromise=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new dt;speakInContentLanguage=!1;speakGeneration=0;loadGeneration=0;prefetchWindow;readyBufferChars;overLengthText;timeoutMs;formatOptions;canPlayType;prefetchCache=new Map;prefetchChainTail=Promise.resolve();activeControllers=new Set;audioContext=null;masterGain=null;scheduledChunks=[];boundaryRafHandle=null;rate=1;pitch=1;volume=1;constructor(e){this.endpoints=e.endpoints,this.fetchImpl=e.fetch??fetch.bind(globalThis),this.prefetchWindow=e.prefetchWindow??ll,this.readyBufferChars=e.readyBufferChars??cl,this.overLengthText=e.overLengthText??"split",this.timeoutMs=e.timeoutMs,this.formatOptions=e.format??{},this.canPlayType=typeof Audio<"u"?r=>new Audio().canPlayType(r):()=>""}setAvailableVoices(e){this.voices=e}async fetchNetwork(e,r){try{return await this.fetchImpl(e,r)}catch(n){throw n instanceof TypeError?new pr(n.message):n}}loadUtterances(e,r){this.clearPrefetchCache(),this.currentUtterances=e,this.currentUtteranceIndex=Xe(r??0,e.length),this.setState("loading"),this.bufferUntilReady(++this.loadGeneration)}async bufferUntilReady(e){const r=Xe(this.currentUtteranceIndex,this.currentUtterances.length),n=Math.min(this.indexCoveringChars(this.readyBufferChars,r),r+this.prefetchWindow),i=[];for(let s=r;s<=n;s++){this.queuePrefetch(s);const o=this.prefetchCache.get(s);o&&i.push(o.then(a=>a[0].promise))}try{await Promise.all(i)}catch{}e!==this.loadGeneration||this.playbackState!=="loading"||this.setState("ready")}indexCoveringChars(e,r){if(this.currentUtterances.length===0)return-1;const n=Xe(r,this.currentUtterances.length);let i=0;for(let s=n;s<this.currentUtterances.length;s++)if(i+=(Fe(this.currentUtterances[s])??"").length,i>=e)return s;return this.currentUtterances.length-1}setVoice(e){if(typeof e=="string"){const r=this.voices.find(n=>n.identifier===e||n.name===e);r?this.currentVoice=r:(this.currentVoice={source:"server",label:e,name:e,originalName:e,language:"",identifier:e},this.getAvailableVoices().then(n=>{if(this.currentVoice?.identifier!==e)return;const i=n.find(s=>s.identifier===e||s.name===e);i&&(this.currentVoice=i)}).catch(()=>{}))}else this.currentVoice=e;this.clearPrefetchCache()}getCurrentVoice(){return this.currentVoice}async getAvailableVoices(){if(this.voices.length>0)return this.voices;const[e,r]=await Promise.all([this.fetchNetwork(this.endpoints.voices),this.getServiceInfo()]);if(!e.ok)throw await ce(e);const n=await e.json(),i=new Map(r.providers.map(s=>[s.id,s.controls]));return this.voices=n.map(s=>dr(s,i.get(s.provider))),this.voices}async getServiceInfo(){return this.serviceInfo?this.serviceInfo:(this.serviceInfoPromise||(this.serviceInfoPromise=this.fetchServiceInfo().catch(e=>{throw this.serviceInfoPromise=null,e})),this.serviceInfo=await this.serviceInfoPromise,this.serviceInfo)}async fetchServiceInfo(){const e=await this.fetchNetwork(this.endpoints.service);if(!e.ok)throw await ce(e);return e.json()}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,this.clearPrefetchCache()}getSpeakInContentLanguage(){return this.speakInContentLanguage}speak(e){if(e!==void 0){if(e<0||e>=this.currentUtterances.length)throw new Error("Invalid utterance index");this.currentUtteranceIndex=e}if(this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.stopAudio();const r=++this.speakGeneration;this.setState("loading"),this.synthesizeAndPlay(r)}async synthesizeAndPlay(e){const r=this.currentUtteranceIndex;try{const n=await this.resolveSynthesisStream(r);if(e!==this.speakGeneration)return;await this.scheduleChunksStreaming(n,e),this.fillPrefetchWindow(r)}catch(n){if(e!==this.speakGeneration)return;this.setState("idle"),this.emitEvent({type:"error",detail:Xr(n)})}}async resolveSynthesisStream(e){const r=this.prefetchCache.get(e);if(r){this.prefetchCache.delete(e);try{return await r}catch{}}return this.synthesizeStream(e)}fillPrefetchWindow(e){const r=Math.min(e+this.prefetchWindow,this.currentUtterances.length-1);for(let n=e+1;n<=r;n++)this.queuePrefetch(n)}queuePrefetch(e){if(this.prefetchCache.has(e))return;const r=this.prefetchChainTail.then(()=>this.synthesizeStream(e));this.prefetchCache.set(e,r),this.prefetchChainTail=r.then(n=>Promise.all(n.map(i=>i.promise))).then(()=>{},()=>{}),r.catch(()=>{}),r.then(n=>n.forEach(i=>i.promise.catch(()=>{}))).catch(()=>{})}clearPrefetchCache(){this.prefetchCache.clear(),this.activeControllers.forEach(e=>e.abort()),this.activeControllers.clear()}async synthesizeStream(e){const r=this.currentUtterances[e],n=!r.plain&&!!r.ssml,i=this.speakInContentLanguage?r.language:void 0,s=Fe(r)??"",o=Fe(this.currentUtterances[e-1]),a=Fe(this.currentUtterances[e+1]),c=await this.getServiceInfo(),l=zn(c.output,this.formatOptions,this.canPlayType),d=navigator.connection,u=jn(l,this.formatOptions.adaptBitrateToNetwork??!1,d);if(s.length<=c.limits.maxTextLength){const p=new AbortController;return this.activeControllers.add(p),[{promise:this.synthesizeChunk(r,s,0,n,i,o,a,l,u,p),controller:p}]}if(this.overLengthText==="error")throw new ye(`Text exceeds this server's maximum length of ${c.limits.maxTextLength} characters`,{status:413,type:"https://readium.org/speech-server/error#payload_too_large",title:"Payload Too Large"});const g=Math.min(c.limits.maxTextLength,this.readyBufferChars),f=n?Bn(s,g):Un(s,g),y=[];let m=Promise.resolve();for(let p=0;p<f.length;p++){const w=p===0?o:f[p-1].text,E=p===f.length-1?a:f[p+1].text,x=f[p],R=new AbortController;this.activeControllers.add(R);const I=m.then(()=>this.synthesizeChunk(r,x.text,x.offset,n,i,w,E,l,u,R));y.push({promise:I,controller:R}),m=I}return y}async synthesizeChunk(e,r,n,i,s,o,a,c,l,d){try{const u=await this.fetchNetwork(this.endpoints.synthesize,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e.id,text:r,ssml:i,language:s,voice:this.currentVoice?.identifier??this.currentVoice?.name,prev_utterance:o,next_utterance:a,boundary:!0,output:{format:c,bitrate:l,speed:this.rate,pitch:this.pitch}}),signal:d.signal});if(!u.ok)throw await ce(u);const g=await u.json(),f=ul(g.audio);let y;try{y=await this.ensureAudioContext().decodeAudioData(f)}catch{throw new fr("Audio playback failed")}return{audioBuffer:y,format:g.format,boundaries:g.boundaries,textOffset:n}}finally{this.activeControllers.delete(d)}}ensureAudioContext(){return this.audioContext||(this.audioContext=new AudioContext,this.masterGain=this.audioContext.createGain(),this.masterGain.gain.value=this.volume,this.masterGain.connect(this.audioContext.destination)),this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.audioContext}awaitWithStallDeadline(e,r,n){if(this.timeoutMs===void 0)return e;const i=n+this.timeoutMs;return new Promise((s,o)=>{const a=setTimeout(()=>{r.abort(),o(new gr(`No audio chunk arrived within ${i.toFixed(0)}ms of the playback buffer running dry`))},i);e.then(c=>{clearTimeout(a),s(c)},c=>{clearTimeout(a),o(c)})})}async scheduleChunksStreaming(e,r){const n=await this.awaitWithStallDeadline(e[0].promise,e[0].controller,0);if(r!==this.speakGeneration)return;const i=this.ensureAudioContext(),s=this.masterGain,a=this.currentVoice?.controls?.speed===!0?1:hl(this.rate);this.scheduledChunks=[],this.setState("playing"),this.emitEvent({type:"start"});let c=i.currentTime,l=null;const d=u=>{const g=i.createBufferSource();g.buffer=u.audioBuffer,g.playbackRate.value=a,g.connect(s),g.start(c),l&&(l.onended=null),g.onended=()=>this.handleUtteranceEnded(r),l=g,this.scheduledChunks.push({chunk:u,startTime:c,node:g,nextBoundaryIndex:0,rate:a}),c+=u.audioBuffer.duration/a};d(n),this.startBoundaryPolling(r);for(let u=1;u<e.length;u++){let g;try{const f=Math.max(0,(c-i.currentTime)*1e3);g=await this.awaitWithStallDeadline(e[u].promise,e[u].controller,f)}catch(f){r===this.speakGeneration&&this.emitEvent({type:"error",detail:Xr(f)});return}if(r!==this.speakGeneration)return;d(g)}}handleUtteranceEnded(e){e===this.speakGeneration&&(this.checkBoundaries(),this.stopBoundaryPolling(),this.currentUtteranceIndex>=this.currentUtterances.length-1&&this.setState("idle"),this.emitEvent({type:"end"}))}startBoundaryPolling(e){const r=()=>{e===this.speakGeneration&&(this.checkBoundaries(),this.boundaryRafHandle=requestAnimationFrame(r))};this.boundaryRafHandle=requestAnimationFrame(r)}stopBoundaryPolling(){this.boundaryRafHandle!==null&&(cancelAnimationFrame(this.boundaryRafHandle),this.boundaryRafHandle=null)}checkBoundaries(){if(!this.audioContext)return;const e=this.audioContext.currentTime;for(const r of this.scheduledChunks){const n=r.chunk.boundaries??[];for(;r.nextBoundaryIndex<n.length&&e>=r.startTime+n[r.nextBoundaryIndex].elapsedTime/r.rate;){const i=n[r.nextBoundaryIndex];this.emitEvent({type:"boundary",detail:{name:i.name,charIndex:i.charIndex+r.chunk.textOffset,charLength:i.charLength,elapsedTime:i.elapsedTime}}),r.nextBoundaryIndex++}}}stopAudio(){this.stopBoundaryPolling();for(const e of this.scheduledChunks){e.node.onended=null;try{e.node.stop()}catch{}e.node.disconnect()}this.scheduledChunks=[]}pause(){this.playbackState==="playing"&&this.audioContext&&(this.audioContext.suspend().catch(()=>{}),this.stopBoundaryPolling(),this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.audioContext&&(this.audioContext.resume().catch(()=>{}),this.startBoundaryPolling(this.speakGeneration),this.setState("playing"),this.emitEvent({type:"resume"}))}stop(){this.speakGeneration++,this.loadGeneration++,this.stopAudio(),this.clearPrefetchCache(),this.currentUtteranceIndex=0,this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){this.rate=Math.max(.1,Math.min(10,e)),this.clearPrefetchCache()}getRate(){return this.rate}setPitch(e){this.pitch=Math.max(0,Math.min(2,e)),this.clearPrefetchCache()}getPitch(){return this.pitch}setVolume(e){this.volume=Math.max(0,Math.min(1,e)),this.masterGain&&(this.masterGain.gain.value=this.volume)}getVolume(){return this.volume}getState(){return this.playbackState}getCurrentUtteranceIndex(){return this.currentUtteranceIndex}setCurrentUtteranceIndex(e,r){if(e<0||e>=this.currentUtterances.length){r?.(!1);return}if(e===this.currentUtteranceIndex){r?.(!0);return}this.stopAudio(),this.currentUtteranceIndex=e,r?.(!0)}getUtteranceCount(){return this.currentUtterances.length}on(e,r){return this.events.on(e,r)}emitEvent(e){this.events.emit(e.type,e)}setState(e){const r=this.playbackState;if(this.playbackState=e,r!==e)switch(e){case"idle":this.emitEvent({type:"idle"});break;case"loading":this.emitEvent({type:"loading"});break;case"ready":this.emitEvent({type:"ready"});break}}async destroy(){this.stop(),await this.audioContext?.close(),this.audioContext=null,this.masterGain=null,this.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[]}}class dl{id="speech-server";name="Readium Speech Server";options;fetchImpl;voices=[];constructor(e){this.options=e,this.fetchImpl=e.fetch??fetch.bind(globalThis)}async getVoices(e){if(this.voices.length>0&&!e)return this.voices;const[r,n]=await Promise.all([this.fetchImpl(this.options.endpoints.voices),this.fetchImpl(this.options.endpoints.service)]);if(!r.ok)throw await ce(r);if(!n.ok)throw await ce(n);const i=await r.json(),s=await n.json(),o=new Map(s.providers.map(a=>[a.id,a.controls]));return this.voices=i.map(a=>dr(a,o.get(a.provider))),this.voices}async createEngine(e){const r=new Mn(this.options);return this.voices.length>0&&r.setAvailableVoices(this.voices),e&&r.setVoice(e),r}async destroy(){this.voices=[]}}function Fn(t){return t.detail?.recoverable===!0}const gl=3e4,fl=["start","pause","resume","end","stop","skip","boundary","mark","idle","loading","ready","voiceschanged","languagefallback"];class Hn{activeEngine;primaryProvider;fallbackProvider;onFailure;healthCheckIntervalMs;hasFallenBack=!1;healthCheckTimer=null;primaryReachable=!1;currentUtterances=[];lastVoiceRequest;desiredIndex=0;desiredPlaying=!1;engineStarted=!0;swapInFlight=!1;teardownEpoch=0;loadToken=0;events=new dt;unbindActiveEngine=null;constructor(e){this.activeEngine=e.primaryEngine,this.primaryProvider=e.primaryProvider,this.fallbackProvider=e.fallbackProvider,this.onFailure=e.onFailure??"fallback",this.healthCheckIntervalMs=e.healthCheckIntervalMs??gl,this.lastVoiceRequest=e.primaryEngine.getCurrentVoice()??void 0,this.bindActiveEngine()}async initialize(){return this.activeEngine.initialize?.()}loadUtterances(e,r){this.loadToken++,this.currentUtterances=e,this.desiredIndex=r??0,this.desiredPlaying=!1,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.loadUtterances(e,r))}setVoice(e){this.lastVoiceRequest=e,this.activeEngine.setVoice(e)}getCurrentVoice(){return this.activeEngine.getCurrentVoice()}getAvailableVoices(){return this.activeEngine.getAvailableVoices()}setSpeakInContentLanguage(e){this.activeEngine.setSpeakInContentLanguage(e)}getSpeakInContentLanguage(){return this.activeEngine.getSpeakInContentLanguage()}speak(e){if(this.desiredIndex=e??this.desiredIndex,this.desiredPlaying=!0,!this.swapInFlight){if(this.hasFallenBack&&this.primaryReachable&&this.activeEngine.getState()!=="playing"){this.recoverToPrimary();return}this.engineStarted=!0,this.activeEngine.speak(this.desiredIndex)}}pause(){this.desiredPlaying=!1,this.isEngineTrusted()&&this.activeEngine.pause()}resume(){if(this.desiredPlaying=!0,!this.swapInFlight){if(!this.engineStarted){this.engineStarted=!0,this.activeEngine.speak(this.desiredIndex);return}this.activeEngine.resume()}}stop(){this.desiredPlaying=!1,this.desiredIndex=0,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.stop())}setRate(e){this.activeEngine.setRate(e)}getRate(){return this.activeEngine.getRate()}setPitch(e){this.activeEngine.setPitch(e)}getPitch(){return this.activeEngine.getPitch()}setVolume(e){this.activeEngine.setVolume(e)}getVolume(){return this.activeEngine.getVolume()}isEngineTrusted(){return!this.swapInFlight&&this.engineStarted}getState(){return this.isEngineTrusted()?this.activeEngine.getState():this.desiredPlaying?"loading":"paused"}getCurrentUtteranceIndex(){return this.isEngineTrusted()?this.activeEngine.getCurrentUtteranceIndex():this.desiredIndex}setCurrentUtteranceIndex(e,r){if(this.desiredIndex=e,!this.isEngineTrusted()){r?.(!0);return}this.activeEngine.setCurrentUtteranceIndex(e,r)}getUtteranceCount(){return this.activeEngine.getUtteranceCount()}on(e,r){return this.events.on(e,r)}emitEvent(e){this.events.emit(e.type,e)}bindActiveEngine(){const e=this.activeEngine,r=fl.map(n=>e.on(n,i=>{this.emitEvent(i),this.maybeRecoverNow()}));r.push(e.on("error",n=>this.handleError(n))),this.unbindActiveEngine=()=>r.forEach(n=>n())}handleError(e){if(this.hasFallenBack||this.swapInFlight||this.onFailure==="error"||!Fn(e)){this.emitEvent(e);return}this.swapToFallback(e)}copyPlaybackParameters(e,r){r.setRate(e.getRate()),r.setPitch(e.getPitch()),r.setVolume(e.getVolume()),r.setSpeakInContentLanguage(e.getSpeakInContentLanguage())}startEngineWhenReady(e){const r=this.loadToken,n=e.on("ready",()=>{n(),r===this.loadToken&&(this.desiredPlaying?(this.engineStarted=!0,e.speak(this.desiredIndex)):this.engineStarted=!1)})}startHealthCheck(){this.healthCheckTimer===null&&(this.healthCheckTimer=setTimeout(async()=>{this.healthCheckTimer=null;try{await this.primaryProvider.getVoices(!0),this.primaryReachable=!0,this.maybeRecoverNow()}catch{this.startHealthCheck()}},this.healthCheckIntervalMs))}maybeRecoverNow(){!this.hasFallenBack||!this.primaryReachable||this.swapInFlight||this.activeEngine.getState()!=="playing"&&this.recoverToPrimary()}async swapToFallback(e){let r=null;await this.performSwap(async()=>{const i=this.activeEngine.getCurrentVoice()??(typeof this.lastVoiceRequest=="object"?this.lastVoiceRequest:null),s=i?.language||this.currentUtterances[this.desiredIndex]?.language||(typeof navigator<"u"?navigator.language:"en");return r=await this.pickBestFallbackVoice(s,i?.gender),this.fallbackProvider.createEngine(r??void 0)},()=>(this.hasFallenBack=!0,this.onFailure==="fallbackAndRecover"&&this.startHealthCheck(),{type:"enginefallback",detail:{reason:e.detail,voice:r}}),()=>{this.hasFallenBack=!0,this.emitEvent(e)})}async recoverToPrimary(){await this.performSwap(()=>this.primaryProvider.createEngine(this.lastVoiceRequest),e=>(this.hasFallenBack=!1,this.primaryReachable=!1,{type:"enginerecovered",detail:{voice:e.getCurrentVoice()}}),()=>{this.primaryReachable=!1,this.startHealthCheck()})}async performSwap(e,r,n){this.swapInFlight=!0;const i=this.teardownEpoch,s=this.activeEngine;let o;try{o=await e()}catch{this.swapInFlight=!1,n();return}if(i!==this.teardownEpoch){this.swapInFlight=!1,await o.destroy();return}this.copyPlaybackParameters(s,o),this.unbindActiveEngine?.(),this.activeEngine=o,this.engineStarted=!1,this.swapInFlight=!1,this.bindActiveEngine(),this.emitEvent(r(o)),this.startEngineWhenReady(o),o.loadUtterances(this.currentUtterances,this.desiredIndex),await s.destroy()}async pickBestFallbackVoice(e,r){const n=await this.fallbackProvider.getVoices(),[i]=ut([e]),{voicesByLang:s}=ht(n,[i]),o=s.get(i.baseLang)??[],a=o.length>0?o:n,c=r?a.filter(d=>d.gender===r):[],l=c.length>0?c:a;return Ji(e,l)}async destroy(){this.teardownEpoch++,this.healthCheckTimer!==null&&(clearTimeout(this.healthCheckTimer),this.healthCheckTimer=null),this.unbindActiveEngine?.(),this.events.clear(),await this.activeEngine.destroy()}}class pl{id="fallback";name="Fallback";primary;fallback;onFailure;healthCheckIntervalMs;constructor(e){this.primary=e.primary,this.fallback=e.fallback,this.onFailure=e.onFailure??"fallback",this.healthCheckIntervalMs=e.healthCheckIntervalMs}async getVoices(e){try{return await this.primary.getVoices(e)}catch(r){if(this.onFailure==="error")throw r;return this.fallback.getVoices(e)}}async createEngine(e){let r;try{r=await this.primary.createEngine(e)}catch(n){if(this.onFailure==="error")throw n;return this.fallback.createEngine(e)}return new Hn({primaryEngine:r,primaryProvider:this.primary,fallbackProvider:this.fallback,onFailure:this.onFailure,healthCheckIntervalMs:this.healthCheckIntervalMs})}async destroy(){await Promise.all([this.primary.destroy(),this.fallback.destroy()])}}let ml=class{};function yl(t){return(t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode)==="vertical-lr"}function vl(t){const e=t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode;return e==="vertical-rl"||e==="vertical-lr"}function Te(t){const e=vl(t),r=e&&yl(t),n=t.innerWidth,i=t.innerHeight,s=t.document.scrollingElement,o=s.scrollLeft,a=s.scrollTop,c=parseInt(t.getComputedStyle(t.document.documentElement).getPropertyValue("column-count")),l=e&&!r?s.scrollWidth-n+o:o,d=a;return{isVertical:e,isVertLR:r,viewportInlineSize:e?i:n,viewportBlockSize:e?n:i,pageInlineSize:e?i:n/(c||1),xDocOffset:l,yDocOffset:d,inlineScrollOffset:e?d:l,blockScrollOffset:e?l:d,inlineStart:u=>e?u.top:u.left,blockStart:u=>e?u.left:u.top,inlineSize:u=>e?u.height:u.width,blockSize:u=>e?u.width:u.height,applyPosition(u,g,f,y,m,p){u.style.position="absolute",e?(u.style.top=`${g*p}px`,u.style.left=`${f*p}px`,u.style.height=`${y*p}px`,u.style.width=`${m*p}px`):(u.style.left=`${g*p}px`,u.style.top=`${f*p}px`,u.style.width=`${y*p}px`,u.style.height=`${m*p}px`)},toRect(u,g,f,y){return e?new DOMRect(g,u,y,f):new DOMRect(u,g,f,y)}}}function Zr(t,e){return t.document.documentElement.style.getPropertyValue(e)}function bl(t){return t&&Array.isArray(t)?t:void 0}function wl(t){return t&&typeof t=="string"?[t]:bl(t)}function At(t){return isNaN(t)?void 0:t}function He(t){return t.otherLocations?.get("cssSelector")}let Oe=class Wn{constructor(e){this.fragments=e.fragments?e.fragments:new Array,this.progression=e.progression,this.totalProgression=e.totalProgression,this.position=e.position,this.otherLocations=e.otherLocations}static deserialize(e){if(!e)return;const r=At(e.progression),n=At(e.totalProgression),i=At(e.position),s=new Map,o=new Set(["fragment","fragments","progression","totalProgression","position","otherLocations"]);return Object.entries(e).forEach(([a,c])=>{o.has(a)||s.set(a,c)}),e.otherLocations instanceof Map&&e.otherLocations.forEach((a,c)=>s.set(c,a)),new Wn({fragments:wl(e.fragments||e.fragment),progression:r!==void 0&&r>=0&&r<=1?r:void 0,totalProgression:n!==void 0&&n>=0&&n<=1?n:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:s.size===0?void 0:s})}serialize(){const e={};return this.fragments&&(e.fragments=this.fragments),this.progression!==void 0&&(e.progression=this.progression),this.totalProgression!==void 0&&(e.totalProgression=this.totalProgression),this.position!==void 0&&(e.position=this.position),this.otherLocations&&this.otherLocations.forEach((r,n)=>e[n]=r),e}},Sl=class Gn{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new Gn({after:e.after,before:e.before,highlight:e.highlight})}serialize(){const e={};return this.after!==void 0&&(e.after=this.after),this.before!==void 0&&(e.before=this.before),this.highlight!==void 0&&(e.highlight=this.highlight),e}},kl=class Wt{constructor(e){const r=e.href.indexOf("#"),n=r>=0?e.href.slice(r+1):void 0;this.href=r>=0?e.href.slice(0,r):e.href,this.type=e.type,this.title=e.title;const i=e.locations?.fragments,s=n&&(!i||i.length===0);this.locations=e.locations?s?new Oe({...e.locations,fragments:[n]}):e.locations:n?new Oe({fragments:[n]}):new Oe({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new Wt({href:e.href,type:e.type,title:e.title,locations:Oe.deserialize(e.locations),text:Sl.deserialize(e.text)})}serialize(){const e={href:this.href,type:this.type};return this.title!==void 0&&(e.title=this.title),this.locations&&(e.locations=this.locations.serialize()),this.text&&(e.text=this.text.serialize()),e}copyWithLocations(e){return new Wt({href:this.href,type:this.type,title:this.title,text:this.text,locations:new Oe({...this.locations,...e})})}};function Yr(t){return t.split("").reverse().join("")}function xl(t,e,r){const n=Yr(e);return r.map(i=>{const s=Math.max(0,i.end-e.length-i.errors),o=Yr(t.slice(s,i.end));return{start:Kn(o,n,i.errors).reduce((a,c)=>i.end-c.end<a?i.end-c.end:a,i.end),end:i.end,errors:i.errors}})}function Tt(t){return(t|-t)>>31&1}function en(t,e,r,n){let i=t.P[r],s=t.M[r];const o=n>>>31,a=e[r]|o,c=a|s,l=(a&i)+i^i|a;let d=s|~(l|i),u=i&l;const g=Tt(d&t.lastRowMask[r])-Tt(u&t.lastRowMask[r]);return d<<=1,u<<=1,u|=o,d|=Tt(n)-o,i=u|~(c|d),s=d&c,t.P[r]=i,t.M[r]=s,g}function Kn(t,e,r){if(e.length===0)return[];r=Math.min(r,e.length);const n=[],i=32,s=Math.ceil(e.length/i)-1,o={P:new Uint32Array(s+1),M:new Uint32Array(s+1),lastRowMask:new Uint32Array(s+1)};o.lastRowMask.fill(1<<31),o.lastRowMask[s]=1<<(e.length-1)%i;const a=new Uint32Array(s+1),c=new Map,l=[];for(let g=0;g<256;g++)l.push(a);for(let g=0;g<e.length;g+=1){const f=e.charCodeAt(g);if(c.has(f))continue;const y=new Uint32Array(s+1);c.set(f,y),f<l.length&&(l[f]=y);for(let m=0;m<=s;m+=1){y[m]=0;for(let p=0;p<i;p+=1){const w=m*i+p;w>=e.length||e.charCodeAt(w)===f&&(y[m]|=1<<p)}}}let d=Math.max(0,Math.ceil(r/i)-1);const u=new Uint32Array(s+1);for(let g=0;g<=d;g+=1)u[g]=(g+1)*i;u[s]=e.length;for(let g=0;g<=d;g+=1)o.P[g]=-1,o.M[g]=0;for(let g=0;g<t.length;g+=1){const f=t.charCodeAt(g);let y;f<l.length?y=l[f]:(y=c.get(f),typeof y>"u"&&(y=a));let m=0;for(let p=0;p<=d;p+=1)m=en(o,y,p,m),u[p]+=m;if(u[d]-m<=r&&d<s&&(y[d+1]&1||m<0)){d+=1,o.P[d]=-1,o.M[d]=0;let p;if(d===s){const w=e.length%i;p=w===0?i:w}else p=i;u[d]=u[d-1]+p-m+en(o,y,d,m)}else for(;d>0&&u[d]>=r+i;)d-=1;d===s&&u[d]<=r&&(u[d]<r&&n.splice(0,n.length),n.push({start:-1,end:g+1,errors:u[d]}),r=u[d])}return n}function El(t,e,r){const n=Kn(t,e,r);return xl(t,e,n)}function Jn(t,e,r){let n=0;const i=[];for(;n!==-1;)n=t.indexOf(e,n),n!==-1&&(i.push({start:n,end:n+e.length,errors:0}),n+=1);return i.length>0?i:El(t,e,r)}function tn(t,e){return e.length===0||t.length===0?0:1-Jn(t,e,e.length)[0].errors/e.length}function Cl(t,e,r={}){if(e.length===0)return null;const n=Math.min(256,e.length/2),i=Jn(t,e,n);if(i.length===0)return null;const s=a=>{const c=1-a.errors/e.length,l=r.prefix?tn(t.slice(Math.max(0,a.start-r.prefix.length),a.start),r.prefix):1,d=r.suffix?tn(t.slice(a.end,a.end+r.suffix.length),r.suffix):1;let u=1;return typeof r.hint=="number"&&(u=1-Math.abs(a.start-r.hint)/t.length),(50*c+20*l+20*d+2*u)/92},o=i.map(a=>({start:a.start,end:a.end,score:s(a)}));return o.sort((a,c)=>c.score-a.score),o[0]}function Gt(t,e,r){const n=r===1?e:e-1;if(t.charAt(n).trim()!=="")return e;let i,s;if(r===2?(i=t.substring(0,e),s=i.trimEnd()):(i=t.substring(e),s=i.trimStart()),!s.length)return-1;const o=i.length-s.length;return r===2?e-o:e+o}function rn(t,e){const r=t.commonAncestorContainer.ownerDocument.createNodeIterator(t.commonAncestorContainer,NodeFilter.SHOW_TEXT),n=e===1?t.startContainer:t.endContainer,i=e===1?t.endContainer:t.startContainer;let s=r.nextNode();for(;s&&s!==n;)s=r.nextNode();e===2&&(s=r.previousNode());let o=-1;const a=()=>{if(s=e===1?r.nextNode():r.previousNode(),s){const c=s.textContent,l=e===1?0:c.length;o=Gt(c,l,e)}};for(;s&&o===-1&&s!==i;)a();if(s&&o>=0)return{node:s,offset:o};throw new RangeError("No text nodes with non-whitespace text found in range")}function Al(t){if(!t.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(t.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(t.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=t.cloneRange();let r=!1,n=!1;const i={start:Gt(t.startContainer.textContent,t.startOffset,1),end:Gt(t.endContainer.textContent,t.endOffset,2)};if(i.start>=0&&(e.setStart(t.startContainer,i.start),r=!0),i.end>0&&(e.setEnd(t.endContainer,i.end),n=!0),r&&n)return e;if(!r){const{node:s,offset:o}=rn(e,1);s&&o>=0&&e.setStart(s,o)}if(!n){const{node:s,offset:o}=rn(e,2);s&&o>0&&e.setEnd(s,o)}return e}function Qn(t){switch(t.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return t.textContent?.length??0;default:return 0}}function nn(t){let e=t.previousSibling,r=0;for(;e;)r+=Qn(e),e=e.previousSibling;return r}function Xn(t,...e){let r=e.shift();const n=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),i=[];let s=n.nextNode(),o,a=0;for(;r!==void 0&&s;)o=s,a+o.data.length>r?(i.push({node:o,offset:r-a}),r=e.shift()):(s=n.nextNode(),a+=o.data.length);for(;r!==void 0&&o&&a===r;)i.push({node:o,offset:o.data.length}),r=e.shift();if(r!==void 0)throw new RangeError("Offset exceeds text length");return i}let We=class ie{constructor(e,r){if(r<0)throw new Error("Offset is invalid");this.element=e,this.offset=r}relativeTo(e){if(!e.contains(this.element))throw new Error("Parent is not an ancestor of current element");let r=this.element,n=this.offset;for(;r!==e;)n+=nn(r),r=r.parentElement;return new ie(r,n)}resolve(e={}){try{return Xn(this.element,this.offset)[0]}catch(r){if(this.offset===0&&e.direction!==void 0){const n=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);n.currentNode=this.element;const i=e.direction===1,s=i?n.nextNode():n.previousNode();if(!s)throw r;return{node:s,offset:i?0:s.data.length}}else throw r}}static fromCharOffset(e,r){switch(e.nodeType){case Node.TEXT_NODE:return ie.fromPoint(e,r);case Node.ELEMENT_NODE:return new ie(e,r);default:throw new Error("Node is not an element or text node")}}static fromPoint(e,r){switch(e.nodeType){case Node.TEXT_NODE:{if(r<0||r>e.data.length)throw new Error("Text node offset is out of range");if(!e.parentElement)throw new Error("Text node has no parent");const n=nn(e)+r;return new ie(e.parentElement,n)}case Node.ELEMENT_NODE:{if(r<0||r>e.childNodes.length)throw new Error("Child node offset is out of range");let n=0;for(let i=0;i<r;i++)n+=Qn(e.childNodes[i]);return new ie(e,n)}default:throw new Error("Point is not in an element or text node")}}},Kt=class Pe{constructor(e,r){this.start=e,this.end=r}relativeTo(e){return new Pe(this.start.relativeTo(e),this.end.relativeTo(e))}toRange(){let e,r;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[e,r]=Xn(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),r=this.end.resolve({direction:2}));const n=new Range;return n.setStart(e.node,e.offset),n.setEnd(r.node,r.offset),n}static fromRange(e){const r=We.fromPoint(e.startContainer,e.startOffset),n=We.fromPoint(e.endContainer,e.endOffset);return new Pe(r,n)}static fromOffsets(e,r,n){return new Pe(new We(e,r),new We(e,n))}static trimmedRange(e){return Al(Pe.fromRange(e).toRange())}},Tl=class Jt{constructor(e,r,n){this.root=e,this.start=r,this.end=n}static fromRange(e,r){const n=Kt.fromRange(r).relativeTo(e);return new Jt(e,n.start.offset,n.end.offset)}static fromSelector(e,r){return new Jt(e,r.start,r.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return Kt.fromOffsets(this.root,this.start,this.end).toRange()}},Ol=class Qt{constructor(e,r,n={}){this.root=e,this.exact=r,this.context=n}static fromRange(e,r){const n=e.textContent,i=Kt.fromRange(r).relativeTo(e),s=i.start.offset,o=i.end.offset,a=32;return new Qt(e,n.slice(s,o),{prefix:n.slice(Math.max(0,s-a),s),suffix:n.slice(o,Math.min(n.length,o+a))})}static fromSelector(e,r){const{prefix:n,suffix:i}=r;return new Qt(e,r.exact,{prefix:n,suffix:i})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(e={}){return this.toPositionAnchor(e).toRange()}toPositionAnchor(e={}){const r=this.root.textContent,n=Cl(r,this.exact,{...this.context,hint:e.hint});if(!n)throw new Error("Quote not found");return new Tl(this.root,n.start,n.end)}};function Rl(t){const e=t.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function Pl(t,e){try{const r=e.locations,n=e.text;if(n&&n.highlight){let i;r&&He(r)&&(i=t.querySelector(He(r))),i||(i=t.body);const s=new Ol(i,n.highlight,{prefix:n.before,suffix:n.after});try{return s.toRange()}catch{return console.warn("Quote not found:",s),null}}if(r){let i=null;if(!i&&He(r)&&(i=t.querySelector(He(r))),!i&&r.fragments){for(const s of r.fragments)if(i=t.getElementById(s),i)break}if(i){const s=t.createRange();return i.childNodes.length===0||Rl(i)?(s.selectNode(i),s):(s.setStartBefore(i),s.setEndAfter(i),s)}}}catch(r){console.error(r)}return null}function Il(t,e){const r=e.map(c=>c.toUpperCase()),n=[],i=t.commonAncestorContainer,s=i.nodeType===Node.TEXT_NODE?i.parentNode:i,o=t.startContainer.ownerDocument.createTreeWalker(s,NodeFilter.SHOW_TEXT);let a=o.nextNode();for(;a;){if(t.intersectsNode(a)){let c=a.parentNode,l=!1;for(;c;){if(c.nodeType===Node.ELEMENT_NODE&&r.includes(c.tagName.toUpperCase())){l=!0;break}c=c.parentNode}if(!l){const d=t.cloneRange();d.selectNode(a),d.compareBoundaryPoints(Range.START_TO_START,t)<0&&d.setStart(t.startContainer,t.startOffset),d.compareBoundaryPoints(Range.END_TO_END,t)>0&&d.setEnd(t.endContainer,t.endOffset);for(const u of d.getClientRects())n.push({left:u.left,right:u.right,top:u.top,bottom:u.bottom,width:u.width,height:u.height})}}a=o.nextNode()}return n}function Ge(t,e,r=!1,n=0){let i;if(Array.isArray(t))i=t;else{let l=t.getClientRects();l.length||t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(l=t.commonAncestorContainer.getClientRects()),i=[];for(const d of l)i.push({bottom:d.bottom,height:d.height,left:d.left,right:d.right,top:d.top,width:d.width})}if(n)for(const l of i)l.left-=n,l.top-=n,l.right+=n,l.bottom+=n,l.width+=n*2,l.height+=n*2;const s=Zn(i,1,e,r),o=Ll(s,1),a=Yn(o),c=4;for(let l=a.length-1;l>=0;l--){const d=a[l];if(!(d.width*d.height>c))if(a.length>1)a.splice(l,1);else break}return a}function Zn(t,e,r,n=!1){for(let i=0;i<t.length;i++)for(let s=i+1;s<t.length;s++){const o=t[i],a=t[s];if(o===a)continue;const c=_(o.top,a.top,e)&&_(o.bottom,a.bottom,e),l=_(o.left,a.left,e)&&_(o.right,a.right,e);if((l&&!r&&!n||c&&!l)&&ei(o,a,e)){const d=t.filter(g=>g!==o&&g!==a),u=Nl(o,a);return d.push(u),Zn(d,e,r,n)}}return t}function Nl(t,e){const r=Math.min(t.left,e.left),n=Math.max(t.right,e.right),i=Math.min(t.top,e.top),s=Math.max(t.bottom,e.bottom);return{bottom:s,height:s-i,left:r,right:n,top:i,width:n-r}}function Ll(t,e){const r=new Set(t);for(const n of t){if(!(n.width>1&&n.height>1)){r.delete(n);continue}for(const i of t)if(n!==i&&r.has(i)&&ql(i,n,e)){r.delete(n);break}}return Array.from(r)}function ql(t,e,r){return K(t,e.left,e.top,r)&&K(t,e.right,e.top,r)&&K(t,e.left,e.bottom,r)&&K(t,e.right,e.bottom,r)}function K(t,e,r,n){return(t.left<e||_(t.left,e,n))&&(t.right>e||_(t.right,e,n))&&(t.top<r||_(t.top,r,n))&&(t.bottom>r||_(t.bottom,r,n))}function Yn(t){for(let e=0;e<t.length;e++)for(let r=e+1;r<t.length;r++){const n=t[e],i=t[r];if(n!==i&&ei(n,i,-1)){let s=[],o;const a=sn(n,i);if(a.length===1)s=a,o=n;else{const l=sn(i,n);a.length<l.length?(s=a,o=n):(s=l,o=i)}const c=t.filter(l=>l!==o);return Array.prototype.push.apply(c,s),Yn(c)}}return t}function sn(t,e){const r=_l(e,t);if(r.height===0||r.width===0)return[t];const n=[];{const i={bottom:t.bottom,height:0,left:t.left,right:r.left,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:r.top,height:0,left:r.left,right:r.right,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:t.bottom,height:0,left:r.left,right:r.right,top:r.bottom,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:t.bottom,height:0,left:r.right,right:t.right,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}return n}function _l(t,e){const r=Math.max(t.left,e.left),n=Math.min(t.right,e.right),i=Math.max(t.top,e.top),s=Math.min(t.bottom,e.bottom);return{bottom:s,height:Math.max(0,s-i),left:r,right:n,top:i,width:Math.max(0,n-r)}}function ei(t,e,r){return(t.left<e.right||r>=0&&_(t.left,e.right,r))&&(e.left<t.right||r>=0&&_(e.left,t.right,r))&&(t.top<e.bottom||r>=0&&_(t.top,e.bottom,r))&&(e.top<t.bottom||r>=0&&_(e.top,t.bottom,r))}function _(t,e,r){return Math.abs(t-e)<=r}let Ke=null,Ot=null,Re=0;const se={r:255,g:255,b:255,a:1},te=new Map,Dl=()=>{if(!Ke)if(typeof OffscreenCanvas<"u")Ke=new OffscreenCanvas(5,5),Ot=Ke.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const t=document.createElement("canvas");t.width=5,t.height=5,Ke=t,Ot=t.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return Ot},$l=t=>{if(!t)return!0;const e=t.trim().toLowerCase();return e.startsWith("var(")||["transparent","currentcolor","inherit","initial","revert","unset","revert-layer"].includes(e)?!0:["linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"].some(r=>e.includes(r))},Je=(t,e)=>{console.warn(`[Decorator] Could not parse color: "${t}". ${e} Falling back to ${JSON.stringify(se)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},Z=(t,e=null)=>{const r=e?`${t}|${e}`:t,n=te.get(r);if(n!==void 0)return n??se;if($l(t))return Je(t,"Unsupported color format or special value."),te.set(r,null),se;const i=Dl();if(!i)return Je(t,"Could not get canvas context."),te.set(r,null),se;try{Re===0&&i.clearRect(0,0,5,5);const s=Re%5,o=Math.floor(Re/5);i.clearRect(s,o,1,1),e&&(i.fillStyle=e,i.fillRect(s,o,1,1)),i.fillStyle=t,i.fillRect(s,o,1,1);const a=i.getImageData(s,o,1,1);Re=(Re+1)%25;const[c,l,d,u]=a.data;if(u===0)return Je(t,"Fully transparent color."),te.set(r,null),se;const g={r:c,g:l,b:d,a:u/255};return te.set(r,g),g}catch(s){return Je(t,`Error: ${s instanceof Error?s.message:String(s)}`),te.set(r,null),se}},Rt=t=>{const e=t/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},Xt=t=>{const e=Rt(t.r),r=Rt(t.g),n=Rt(t.b);return .2126*e+.7152*r+.0722*n},rt=(t,e)=>{const r=typeof t=="string"?Z(t):t,n=typeof e=="string"?Z(e):e,i=Xt(r),s=Xt(n),o=Math.max(i,s),a=Math.min(i,s);return(o+.05)/(a+.05)},ti=(t,e=null)=>{const r=Z(t,e),n=rt(r,{r:255,g:255,b:255,a:1}),i=rt(r,{r:0,g:0,b:0,a:1});return n>i},an=(t,e=null)=>ti(t,e)?"white":"black",Ul=t=>{const e=t.a!==void 0?t.a:1;return`rgba(${Math.round(t.r)}, ${Math.round(t.g)}, ${Math.round(t.b)}, ${e})`},Bl=(t,e)=>({r:Math.min(255,t.r+(255-t.r)*e),g:Math.min(255,t.g+(255-t.g)*e),b:Math.min(255,t.b+(255-t.b)*e),a:t.a??1}),Vl=(t,e)=>({r:Math.max(0,t.r*(1-e)),g:Math.max(0,t.g*(1-e)),b:Math.max(0,t.b*(1-e)),a:t.a??1}),re=(t,e=null,r=3)=>{const n=Z(t),i=e?Z(e):{r:255,g:255,b:255,a:1};let s=rt(n,i);if(s>=r)return t;const o=Xt(i)<.5;let a={...n,a:n.a??1};const c=20,l=.1;for(let d=0;d<c&&(o?a=Bl(a,l):a=Vl(a,l),s=rt(a,i),!(s>=r));d++);return Ul(a)},ri=()=>typeof navigator>"u"?"":navigator.userAgent||"",ni=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;let ii=class{constructor(){const e=ni(),r=ri(),n=s=>(typeof s=="string"||typeof s=="number")&&s?String(s).replace(/_/g,".").split(".").map(o=>parseInt(o)||0):[],i=(s="")=>{if(!s)return[];const o=new RegExp("^.*"+s+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return o.test(r)?n(r.replace(o,"$1")):[]};this.OS=(s=>(/(macOS|Mac OS X)/.test(r)?(/\(iP(hone|od touch);/.test(r)&&(s.iOS=i("CPU (?:iPhone )?OS ")),/\(iPad;/.test(r)?s.iOS=s.iPadOS=i("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(r)&&(document.ontouchend!==void 0?s.iOS=s.iPadOS=i():s.macOS=i("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(r)?s.Windows=(o=>o[0]!==6||!o[1]?o:o[1]===1?[7]:o[1]===2?[8]:[8,1])(i("Windows(?: NT)?")):/Android \d/.test(r)?s.Android=i("Android"):/CrOS/.test(r)?s.ChromeOS=i():/X11;/.test(r)&&(s.Linux=i()),s))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(s=>(o=>{const a=s.platform,c=s.platformVersion;if(!(!a||!c)){if(/^i(OS|P(hone|od touch))$/.test(a))o.iOS=n(c);else if(/^iPad(OS)?$/.test(a))o.iOS=o.iPadOS=n(c);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(a))document.ontouchend!==void 0?o.iOS=o.iPadOS=n():o.macOS=n(c);else if(/^(Microsoft )?Windows$/.test(a))o.Windows=n(c);else if(/^(Google )?Android$/.test(a))o.Android=n(c);else if(/^((Google )?Chrome OS|CrOS)$/.test(a))o.ChromeOS=n(c);else if(/^(Linux|Ubuntu|X11)$/.test(a))o.Linux=n(c);else return;Object.keys(this.OS).forEach(l=>delete this.OS[l]),Object.assign(this.OS,o)}})({})),this.UA=(s=>{let o=!1;if(e&&Array.isArray(e.brands)){const a=e.brands.reduce((c,l)=>(c[l.brand]=[l.version*1],c),{});a["Google Chrome"]?(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Chrome=a["Google Chrome"]):a["Microsoft Edge"]?(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Edge=a["Microsoft Edge"]):a.Opera&&(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Opera=a.Opera)}return o||(/ Gecko\/\d/.test(r)?(s.Gecko=i("rv"),/ Waterfox\/\d/.test(r)?s.Waterfox=i("Waterfox"):/ Firefox\/\d/.test(r)&&(s.Firefox=i("Firefox"))):/ Edge\/\d/.test(r)?(s.EdgeHTML=i("Edge"),s.Edge=s.EdgeHTML):/ Chrom(ium|e)\/\d/.test(r)?(s.Blink=s.Chromium=(a=>a[0]?a:i("Chrome"))(i("Chromium")),/ EdgA?\/\d/.test(r)?s.Edge=(a=>a[0]?a:i("Edg"))(i("EdgA")):/ OPR\/\d/.test(r)?s.Opera=i("OPR"):/ Vivaldi\/\d/.test(r)?s.Vivaldi=i("Vivaldi"):/ Silk\/\d/.test(r)?s.Silk=i("Silk"):/ UCBrowser\/\d/.test(r)?s.UCBrowser=i("UCBrowser"):/ Phoebe\/\d/.test(r)?s.Phoebe=i("Phoebe"):s.Chrome=(a=>a[0]?a:s.Chromium)(i("Chrome"))):/ AppleWebKit\/\d/.test(r)?(s.WebKit=i("AppleWebKit"),/ CriOS \d/.test(r)?s.Chrome=i("CriOS"):/ FxiOS \d/.test(r)?s.Firefox=i("FxiOS"):/ EdgiOS\/\d/.test(r)?s.Edge=i("EdgiOS"):/ Version\/\d/.test(r)&&(s.Safari=i("Version"))):/ Trident\/\d/.test(r)&&(s.Trident=i("Trident"),s.InternetExplorer=(a=>a[0]?a:i("MSIE"))(i("rv")))),/[\[; ]FB(AN|_IAB)\//.test(r)&&(s.Facebook=i("FBAV")),/ Line\/\d/.test(r)&&(s.LINE=i("Line")),s})({}),this.Env={get:()=>[this.OS,this.UA].reduce((s,o)=>{for(const a in o)o[a]&&s.push(a);return s},[])}}};class zl extends ii{get iOSRequest(){const e=ni(),r=ri();if(this.OS.iOS&&!this.OS.iPadOS)return"mobile";if(this.OS.iPadOS)return/\(iPad;/.test(r)||e&&/^iPad(OS)?$/.test(e.platform)?"mobile":"desktop"}}const jl=new ii;new zl;const on=["div","span","p","br","hr","b","i","em","strong","s","u","mark","small","sub","sup","abbr","cite","code","data","dfn","kbd","q","samp","time","var","blockquote","pre","svg","g","path","circle","ellipse","rect","line","polygon","polyline","text","tspan","defs","use"],Ml=/^on/i,Fl=new Set(["href","src","action","formaction","xlink:href"]),Hl=/^\s*(javascript|data):/i;function Wl(t,e){const r=t.document.createElement("div");if("Sanitizer"in t&&typeof r.setHTML=="function")try{const i=new t.Sanitizer({allowElements:on});return r.setHTML(e,{sanitizer:i}),r.firstElementChild}catch{}const n=t.document.implementation.createHTMLDocument("");for(n.body.innerHTML=e,Gl(n.body,new Set(on));n.body.firstChild;)r.appendChild(t.document.adoptNode(n.body.firstChild));return r.firstElementChild}function Gl(t,e){const r=Array.from(t.querySelectorAll("*")).reverse();for(const n of r){if(!e.has(n.localName)){n.replaceWith(...Array.from(n.childNodes));continue}for(const{name:i,value:s}of Array.from(n.attributes))(Ml.test(i)||Fl.has(i)&&Hl.test(s))&&n.removeAttribute(i)}}function Pt(t){switch(t){case C.Mask:return"rgba(255, 255, 255, 0.5)";case C.Highlight:case C.HighlightUnderline:return"#FFFF00";default:return"#FF0000"}}const C={Highlight:"highlight",HighlightUnderline:"highlightUnderline",Underline:"underline",Strikethrough:"strikethrough",Outline:"outline",TextColor:"textColor",Mask:"mask",Template:"template"};var si=(t=>(t.Wrap="wrap",t.Viewport="viewport",t.Bounds="bounds",t.Page="page",t))(si||{}),ai=(t=>(t.Boxes="boxes",t.Bounds="bounds",t))(ai||{});const Kl=()=>"Highlight"in window,ln=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Jl{constructor(e,r,n,i){this.wnd=e,this.comms=r,this.id=n,this.name=i,this.items=[],this.lastItemId=0,this.container=void 0,this._activatable=!1,this._hoverable=!1,this.hoveredItem=void 0,this.experimentalHighlights=!1,this._tintSubKeys=new Map,this._subKeyCounter=0,this.maskSvg=void 0,this.shadowHost=void 0,this.shadowRoot=void 0,this.currentRender=0,Kl()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map),this.activationHandler=this.handleActivation.bind(this),this.wnd.document.addEventListener("pointerup",this.activationHandler),this.hoverHandler=this.handleHover.bind(this),this.wnd.document.addEventListener("pointermove",this.hoverHandler)}get activatable(){return this._activatable}set activatable(e){this._activatable=e}get hoverable(){return this._hoverable}set hoverable(e){if(this._hoverable=e,!e&&this.hoveredItem){const r=this.hoveredItem.range.getBoundingClientRect(),n=this.wnd.devicePixelRatio;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:{top:r.top*n,left:r.left*n,width:r.width*n,height:r.height*n}}),this.hoveredItem=void 0}}add(e){const r=`${this.id}-${this.lastItemId++}`,n=Pl(this.wnd.document,e.locator);if(!n){this.comms.log("Can't locate DOM range for decoration",e);return}const i=n.commonAncestorContainer;if(i.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(ln.includes(i.nodeName.toUpperCase())&&this.notTextFlag?.set(r,!0),n.cloneContents().querySelector(ln.join(", ").toLowerCase())&&this.notTextFlag?.set(r,!0),(i.textContent?.trim()||"").length===0&&this.notTextFlag?.set(r,!0)),this.experimentalHighlights&&!this.notTextFlag?.has(r)){const o=a=>{for(;a&&a.nodeType===Node.ELEMENT_NODE;){if(a.namespaceURI?.includes("svg"))return!0;a=a.parentNode}return!1};(o(n.startContainer)||o(n.endContainer))&&this.notTextFlag?.set(r,!0)}if(this.experimentalHighlights){const{type:o}=e.style,{layout:a,width:c,expand:l}=e.style;o!==C.TextColor&&(o===C.Outline||o===C.Template||o===C.Mask||a!==void 0&&a!=="boxes"||c!==void 0&&c!=="wrap"||l)&&this.notTextFlag?.set(r,!0)}const s={decoration:e,id:r,range:n,hitRects:[],clickableElements:void 0,container:void 0};this.items.push(s),this.layout(s),s.hitRects=this.clientRectsToDocCoords(Ge(s.range,!1,!1,(s.decoration.style.expand??0)+this.hitGap())),this.renderLayout([s])}remove(e){const r=this.items.findIndex(s=>s.decoration.id===e);if(r<0)return;const n=this.items[r],i=n.decoration.style?.type===C.Mask;if(this.items.splice(r,1),n.clickableElements=void 0,n.container&&(n.container.remove(),n.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(n.id)&&n.highlightSubKey){const s=this.wnd.CSS.highlights;s.get(n.highlightSubKey)?.delete(n.range),this.items.some(a=>a.highlightSubKey===n.highlightSubKey)||s.delete(n.highlightSubKey);const o=this.wnd.document.getElementById(`${this.id}-style`);o&&this._rebuildHighlightStylesheet(o)}this.notTextFlag?.delete(n.id),this.hoveredItem===n&&(this.hoveredItem=void 0),i&&this.updateSharedMask()}update(e){this.remove(e.id),this.add(e)}clear(){this.clearContainer(),this.items.length=0,this.notTextFlag?.clear(),this.hoveredItem=void 0,this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowHost&&(this.shadowHost.remove(),this.shadowHost=void 0,this.shadowRoot=void 0)}destroy(){this.clear(),this.wnd.document.removeEventListener("pointerup",this.activationHandler),this.wnd.document.removeEventListener("pointermove",this.hoverHandler)}clientRectsToDocCoords(e){const r=Te(this.wnd),n=r.xDocOffset,i=r.yDocOffset;return n===0&&i===0?e:e.map(s=>({left:s.left+n,top:s.top+i,right:s.right+n,bottom:s.bottom+i,width:s.width,height:s.height}))}pointerToDocCoords(e){const r=Te(this.wnd);return{docX:e.clientX+r.xDocOffset,docY:e.clientY+r.yDocOffset}}effectiveZoom(){if(!jl.UA.Blink)return 1;const e=parseFloat(this.wnd.getComputedStyle(this.wnd.document.documentElement).zoom),r=parseFloat(this.wnd.getComputedStyle(this.wnd.document.body).zoom);return(e||1)*(r||1)}hitGap(){return 2*this.effectiveZoom()}handleActivation(e){if(!this._activatable)return;const{docX:r,docY:n}=this.pointerToDocCoords(e),i=this.wnd.devicePixelRatio;for(const s of this.items){let o;if(s.decoration.style.type===C.Template)for(const a of s.clickableElements??[]){const c=a.getBoundingClientRect();if(K(c,e.clientX,e.clientY,0)){o=c;break}}else for(const a of s.hitRects)if(K(a,r,n,0)){o=s.range.getBoundingClientRect();break}if(o){this.comms.send("decoration_activated",{decorationId:s.decoration.id,group:this.name,rect:{top:o.top*i,left:o.left*i,width:o.width*i,height:o.height*i},point:{x:e.clientX*i,y:e.clientY*i}});return}}}handleHover(e){if(!this._hoverable)return;const{docX:r,docY:n}=this.pointerToDocCoords(e),i=this.wnd.devicePixelRatio;let s,o;for(const a of this.items){if(a.decoration.style.type===C.Template)for(const c of a.clickableElements??[]){const l=c.getBoundingClientRect();if(K(l,e.clientX,e.clientY,0)){s=a,o=l;break}}else for(const c of a.hitRects)if(K(c,r,n,0)){s=a,o=a.range.getBoundingClientRect();break}if(s)break}if(s!==this.hoveredItem){if(this.hoveredItem){const a=this.hoveredItem.range.commonAncestorContainer.isConnected?this.hoveredItem.range.getBoundingClientRect():null;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:a?{top:a.top*i,left:a.left*i,width:a.width*i,height:a.height*i}:void 0,point:{x:e.clientX*i,y:e.clientY*i}})}this.hoveredItem=s,s&&o&&this.comms.send("decoration_pointer_enter",{decorationId:s.decoration.id,group:this.name,rect:{top:o.top*i,left:o.left*i,width:o.width*i,height:o.height*i},point:{x:e.clientX*i,y:e.clientY*i}})}}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.wnd.document.fonts.ready.then(()=>{this.currentRender=this.wnd.requestAnimationFrame(()=>{this.items.forEach(e=>{this.layout(e),e.hitRects=this.clientRectsToDocCoords(Ge(e.range,!1,!1,(e.decoration.style.expand??0)+this.hitGap()))}),this.renderLayout(this.items),this.updateSharedMask()})})}experimentalLayout(e){const r=this.requireContainer(!0),n=this.wnd.CSS.highlights,i=e.decoration.style,s=i.type??C.Highlight,o=i.tint??Pt(s),a=i.width,c=i.layout,l=this._getSubKey(s,o);e.highlightSubKey&&(n.get(e.highlightSubKey)?.delete(e.range),e.highlightSubKey!==l&&!this.items.some(m=>m!==e&&m.highlightSubKey===e.highlightSubKey)&&n.delete(e.highlightSubKey)),e.highlightSubKey=l;let d;n.has(l)?d=n.get(l):(d=new this.wnd.Highlight,n.set(l,d));const u=(m,p)=>this.wnd.document.caretPositionFromPoint?.(m,p)??null;if(s===C.TextColor&&(c==="bounds"||a==="bounds"||a==="page")){const m=Te(this.wnd);if(m.isVertical)console.warn("Vertical writing detected: caretPositionFromPoint has known bugs, falling back to original range"),d.add(e.range);else{const p=e.range.getBoundingClientRect();let w,E;a==="page"?(w=Math.floor(m.inlineStart(p)/m.pageInlineSize)*m.pageInlineSize,E=m.pageInlineSize):(w=m.inlineStart(p),E=m.inlineSize(p));const x=u(w,m.blockStart(p)+1),R=u(w+E,m.blockStart(p)+m.blockSize(p)-1);if(x&&R){const I=this.wnd.document.createRange();I.setStart(x.offsetNode,x.offset),I.setEnd(R.offsetNode,R.offset),d.add(I),e.range=I}else d.add(e.range)}}else d.add(e.range);const g=this.getBackgroundColor(),f=i.enforceContrast!==!1?re(o,g):o;let y;switch(s){case C.Underline:y=`::highlight(${l}) {
|
|
28
28
|
text-decoration: underline;
|
|
29
29
|
text-decoration-color: ${f};
|
|
30
30
|
text-decoration-thickness: 0.1em;
|
|
31
|
-
}`;break;case
|
|
31
|
+
}`;break;case C.Strikethrough:y=`::highlight(${l}) {
|
|
32
32
|
text-decoration: line-through;
|
|
33
33
|
text-decoration-color: ${f};
|
|
34
34
|
text-decoration-thickness: 0.1em;
|
|
35
|
-
}`;break;case
|
|
35
|
+
}`;break;case C.Outline:y=`::highlight(${l}) {
|
|
36
36
|
outline: 2px solid ${f};
|
|
37
37
|
outline-offset: 1px;
|
|
38
|
-
}`;break;case
|
|
38
|
+
}`;break;case C.TextColor:y=`::highlight(${l}) {
|
|
39
39
|
color: ${f};
|
|
40
|
-
}`;break;case
|
|
41
|
-
color: ${
|
|
40
|
+
}`;break;case C.HighlightUnderline:{const{r:m,g:p,b:w}=Z(f),E=`rgba(${m}, ${p}, ${w}, 0.3)`;y=`::highlight(${l}) {
|
|
41
|
+
color: ${an(f,g)};
|
|
42
42
|
background-color: ${E};
|
|
43
43
|
text-decoration: underline;
|
|
44
44
|
text-decoration-color: ${f};
|
|
45
45
|
text-decoration-thickness: 0.1em;
|
|
46
|
-
}`;break}case
|
|
47
|
-
color: ${
|
|
46
|
+
}`;break}case C.Highlight:default:y=`::highlight(${l}) {
|
|
47
|
+
color: ${an(f,g)};
|
|
48
48
|
background-color: ${f};
|
|
49
|
-
}`}e.highlightCSS=y,this._rebuildHighlightStylesheet(
|
|
50
|
-
`)}layout(e){if(this.experimentalHighlights&&!this.notTextFlag?.has(e.id))return this.experimentalLayout(e);const n=this.wnd.document.createElement("div");n.setAttribute("id",e.id),n.dataset.highlightId=e.decoration.id,n.style.setProperty("pointer-events","none");const r=Ce(this.wnd),i=1/this.effectiveZoom(),s=e.decoration.style.expand??0,o=(u,g,f,y=0)=>{const p=e.decoration?.style?.width,m=g;switch(p){case"viewport":{const w=Math.floor(r.inlineStart(m)/r.viewportInlineSize)*r.viewportInlineSize;r.applyPosition(u,w+r.inlineScrollOffset+y,r.blockStart(m)+r.blockScrollOffset,r.viewportInlineSize-2*y,r.blockSize(m),i);break}case"page":{const w=Math.floor(r.inlineStart(m)/r.pageInlineSize)*r.pageInlineSize;r.applyPosition(u,w+r.inlineScrollOffset+y,r.blockStart(m)+r.blockScrollOffset,r.pageInlineSize-2*y,r.blockSize(m),i);break}case"bounds":{r.applyPosition(u,r.inlineStart(f)+r.inlineScrollOffset,r.blockStart(m)+r.blockScrollOffset,r.inlineSize(f),r.blockSize(m),i);break}default:r.applyPosition(u,r.inlineStart(m)+r.inlineScrollOffset,r.blockStart(m)+r.blockScrollOffset,r.inlineSize(m),r.blockSize(m),i)}},a=e.range.getBoundingClientRect(),c=e.decoration.style,l=(()=>{if(c.type!==A.Outline)return 0;const u=c.width;return u==="page"||u==="viewport"?3:0})();let d;if(c.type===A.Template){c.stylesheet&&this.injectCustomStylesheet(c.stylesheet);const u=El(this.wnd,c.element);if(!u){e.container=n,e.clickableElements=[];return}u.style.setProperty("pointer-events","none"),d=u}else{const u=c,g=u.type??A.Highlight,f=u.tint??Ct(g);if(g===A.TextColor){e.container=n,e.clickableElements=[];return}if(g===A.Mask){e.container=n,e.clickableElements=[],this.updateSharedMask();return}const y=this.getCurrentDarkMode(),p=this.getBackgroundColor(),m=u.enforceContrast!==!1,w=(()=>{switch(g){case A.Underline:{const C=m?te(f,p):f,P=u.layout==="bounds",[I,L]=r.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[P?`${L}: 0.1em solid ${C} !important`:null,`${I}: 0.1em solid ${C} !important`,"background-color: transparent !important","box-sizing: border-box !important"].filter(Boolean).join("; ")}case A.Strikethrough:{const C=m?te(f,p):f;return u.layout==="bounds"?[`background: repeating-linear-gradient(-45deg, transparent, transparent 19px, ${C} 19px, ${C} 20px) !important`,"background-color: transparent !important","box-sizing: border-box !important"].join("; "):[`background-color: ${C} !important`,"box-sizing: border-box !important"].join("; ")}case A.Outline:return[`outline: 2px solid ${m?te(f,p):f} !important`,"outline-offset: 1px !important","background-color: transparent !important","box-sizing: border-box !important"].join("; ");case A.HighlightUnderline:{const C=m?te(f,p):f,{r:P,g:I,b:L}=X(C),_=`rgba(${P}, ${I}, ${L}, 0.3)`,be=u.layout==="bounds",[ve,b]=r.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[`background-color: ${_} !important`,be?`${b}: 0.1em solid ${C} !important`:null,`${ve}: 0.1em solid ${C} !important`,"box-sizing: border-box !important"].filter(Boolean).join("; ")}case A.Highlight:default:return[`background-color: ${m?te(f,p):f} !important`,`mix-blend-mode: ${y?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important"].join("; ")}})(),E=this.wnd.document.createElement("template");E.innerHTML=`<div data-readium="true" class="readium-${g}" style="${w}"></div>`.trim(),d=E.content.firstElementChild}if(e.decoration?.style?.layout==="bounds"){const u=d.cloneNode(!0);u.style.setProperty("pointer-events","none");const g=s?{left:a.left-s,right:a.right+s,top:a.top-s,bottom:a.bottom+s,width:a.width+s*2,height:a.height+s*2}:a;o(u,g,a,l),n.append(u)}else{const u=c.type,g=u===A.Underline||u===A.Strikethrough,f=u===A.Strikethrough,y=g?ul(e.range,["rt","rp"]):e.range;let p=Ge(y,!0,r.isVertical,g?0:s);p=p.sort((m,w)=>r.isVertical?(r.isVertLR?1:-1)*(m.left-w.left):m.top-w.top);for(let m of p){const w=d.cloneNode(!0);w.style.setProperty("pointer-events","none");let E=m;if(f){const C=r.blockSize(m)*.1,P=r.blockStart(m)+r.blockSize(m)/2-C/2;E=r.isVertical?{left:P,right:P+C,top:m.top,bottom:m.bottom,width:C,height:m.height}:{top:P,bottom:P+C,left:m.left,right:m.right,height:C,width:m.width}}s&&g&&(E=r.isVertical?{...E,top:E.top-s,bottom:E.bottom+s,height:E.height+s*2}:{...E,left:E.left-s,right:E.right+s,width:E.width+s*2}),o(w,E,a,l),n.append(w)}}e.container=n,e.clickableElements=Array.from(n.querySelectorAll("[data-activable='1']")),e.clickableElements.length||(e.clickableElements=Array.from(n.children))}renderLayout(e){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{e=e.filter(n=>!this.experimentalHighlights||!!this.notTextFlag?.has(n.id)),!(!e||e.length===0)&&this.requireContainer().append(...e.map(n=>n.container).filter(n=>!!n))})}requireContainer(e=!1){if(e){let n;return this.wnd.document.getElementById(`${this.id}-style`)?n=this.wnd.document.getElementById(`${this.id}-style`):(n=this.wnd.document.createElement("style"),n.dataset.readium="true",n.id=`${this.id}-style`,this.wnd.document.head.appendChild(n)),n}return this.container||(this.shadowRoot||(this.shadowHost=this.wnd.document.createElement("div"),this.shadowHost.style.cssText="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none",this.wnd.document.body.appendChild(this.shadowHost),this.shadowRoot=this.shadowHost.attachShadow({mode:"open"})),this.container=this.wnd.document.createElement("div"),this.container.setAttribute("id",this.id),this.container.dataset.group=this.name,this.container.dataset.readium="true",this.container.style.setProperty("pointer-events","none"),this.container.style.display="contents",this.shadowRoot.appendChild(this.container)),this.container}getCurrentDarkMode(){return Fn(this.wnd,"--USER__appearance")==="readium-night-on"||jr(this.getBackgroundColor())}getBackgroundColor(){return Fn(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color")}updateSharedMask(){const e=this.items.filter(g=>g.decoration.style?.type===A.Mask);if(e.length===0){this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowRoot&&(this.shadowRoot.innerHTML="");return}const n=Ce(this.wnd),r=1/this.effectiveZoom(),i=this.wnd.document.documentElement,s=i.scrollWidth,o=i.scrollHeight,a=[];for(const g of e){const f=g.decoration.style,y=f.layout??"boxes",p=f.width??"wrap",m=f.expand??0,w=g.range.getBoundingClientRect(),E=y==="bounds"?[m?{left:w.left-m,top:w.top-m,right:w.right+m,bottom:w.bottom+m,width:w.width+m*2,height:w.height+m*2}:w]:Ge(g.range,!1,!1,m);for(const C of E){let P;switch(p){case"viewport":{const I=Math.floor(n.inlineStart(C)/n.viewportInlineSize)*n.viewportInlineSize;P=n.toRect(I,n.blockStart(C),n.viewportInlineSize,n.blockSize(C));break}case"page":{const I=Math.floor(n.inlineStart(C)/n.pageInlineSize)*n.pageInlineSize;P=n.toRect(I,n.blockStart(C),n.pageInlineSize,n.blockSize(C));break}case"bounds":{P=n.toRect(n.inlineStart(w),n.blockStart(C),n.inlineSize(w),n.blockSize(C));break}default:P=n.toRect(n.inlineStart(C),n.blockStart(C),n.inlineSize(C),n.blockSize(C))}a.push(P)}}const c=[`M0 0 H${s} V${o} H0 Z`,...a.map(g=>{const f=(g.left+n.xDocOffset)*r,y=(g.top+n.yDocOffset)*r,p=(g.right+n.xDocOffset)*r,m=(g.bottom+n.yDocOffset)*r;return`M${f} ${y} H${p} V${m} H${f} Z`})].join(" "),l="http://www.w3.org/2000/svg";if(!this.maskSvg){this.shadowRoot||(this.shadowHost=this.wnd.document.createElement("div"),this.shadowHost.style.cssText="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none",this.wnd.document.body.appendChild(this.shadowHost),this.shadowRoot=this.shadowHost.attachShadow({mode:"open"})),this.maskSvg=this.wnd.document.createElementNS(l,"svg"),this.maskSvg.style.cssText=`position:absolute;top:0;left:0;width:${s}px;height:${o}px;pointer-events:none;z-index:9999`,this.maskSvg.dataset.readium="true";const g=this.wnd.document.createElementNS(l,"defs"),f=this.wnd.document.createElementNS(l,"clipPath"),y=`${this.id}-mask-clip`;f.setAttribute("id",y),f.setAttribute("clipPathUnits","userSpaceOnUse");const p=this.wnd.document.createElementNS(l,"path");p.setAttribute("clip-rule","evenodd"),f.appendChild(p),g.appendChild(f),this.maskSvg.appendChild(g);const m=this.wnd.document.createElementNS(l,"rect");m.setAttribute("id",`${this.id}-mask-rect`),m.setAttribute("clip-path",`url(#${y})`),m.style.pointerEvents="none",this.maskSvg.appendChild(m),this.shadowRoot.appendChild(this.maskSvg)}this.maskSvg.style.width=`${s}px`,this.maskSvg.style.height=`${o}px`;const d=this.maskSvg.querySelector("path");d&&d.setAttribute("d",c);const u=this.maskSvg.querySelector("rect");if(u){const g=e[0].decoration.style.tint,f=g??this.getBackgroundColor()??Ct(A.Mask),y=g?"1":"0.5";u.setAttribute("x","0"),u.setAttribute("y","0"),u.setAttribute("width",String(s)),u.setAttribute("height",String(o)),u.setAttribute("fill",f),u.setAttribute("fill-opacity",y)}}injectCustomStylesheet(e){const n=`${this.id}-custom-style`;let r=this.wnd.document.getElementById(n);r||(r=this.wnd.document.createElement("style"),r.id=n,r.dataset.readium="true",this.wnd.document.head.appendChild(r)),r.innerHTML=e}clearContainer(){if(this.experimentalHighlights){const e=this.wnd.CSS.highlights;for(const n of this._tintSubKeys.values())e.delete(n);this._tintSubKeys.clear(),this._subKeyCounter=0}this.wnd.document.getElementById(`${this.id}-custom-style`)?.remove(),this.container&&(this.container.remove(),this.container=void 0)}}const Wr=class Te extends Jo{constructor(){super(...arguments),this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this)}cleanup(){this.groups.forEach(e=>e.destroy()),this.groups.clear()}updateHighlightStyles(){this.groups.forEach(e=>{e.requestLayout()})}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(e=>{e.experimentalHighlights||e.requestLayout()})},50)}mount(e,n){return this.wnd=e,n.register("decorate",Te.moduleName,(r,i)=>{const s=r;(s.action==="add"||s.action==="update")&&s.decoration.locator&&(s.decoration.locator=tl.deserialize(s.decoration.locator)),this.groups.has(s.group)||this.groups.set(s.group,new Tl(e,n,`readium-decoration-${this.lastGroupId++}`,s.group));const o=this.groups.get(s.group);switch(s.action){case"add":o?.add(s.decoration);break;case"remove":o?.remove(s.decoration.id);break;case"clear":o?.clear();break;case"update":o?.update(s.decoration);break}i(!0)}),n.register("decoration_activatable",Te.moduleName,(r,i)=>{const s=r,o=this.groups.get(s.group);o&&(o.activatable=s.activatable),i(!0)}),n.register("decoration_hoverable",Te.moduleName,(r,i)=>{const s=r,o=this.groups.get(s.group);o&&(o.hoverable=s.hoverable),i(!0)}),this.resizeObserver=new ResizeObserver(()=>e.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(e.document.documentElement),e.addEventListener("orientationchange",this.handleResizer),e.addEventListener("resize",this.handleResizer),this.styleObserver=new MutationObserver(r=>{r.some(i=>i.type==="attributes"&&i.attributeName==="style"&&i.oldValue!==i.target.getAttribute("style"))&&this.updateHighlightStyles()}),this.styleObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"],attributeOldValue:!0}),n.log("Decorator Mounted"),!0}unmount(e,n){return e.removeEventListener("orientationchange",this.handleResizer),e.removeEventListener("resize",this.handleResizer),n.unregisterAll(Te.moduleName),this.resizeObserver.disconnect(),this.styleObserver.disconnect(),this.cleanup(),n.log("Decorator Unmounted"),!0}};Wr.moduleName="decorator";let Kr=Wr;const Jr=new Set(Object.values(A));function Qr(t,e){return t===A.TextColor?typeof window<"u"&&"Highlight"in window:Jr.has(t)?!0:!!e?.[t]}function Mt(t,e){const{style:n}=t;if(n.type===A.Template){const r=n;return{...t,style:{...r,element:Yn(r,t)}}}if(n.type&&e?.[n.type]){const r=e[n.type];return{...t,style:{type:A.Template,layout:r.layout,width:r.width,stylesheet:r.stylesheet,element:Yn(r,t)}}}return t}function Yn(t,e){return typeof t.element=="function"?t.element(e):t.element}function Rl(t,e){if(t.type!==e.type)return!1;if(t.type===A.Template){const i=t,s=e;return i.layout===s.layout&&i.width===s.width&&i.stylesheet===s.stylesheet}const n=t,r=e;return n.tint===r.tint&&n.layout===r.layout&&n.width===r.width&&(n.enforceContrast??!0)===(r.enforceContrast??!0)&&(n.expand??0)===(r.expand??0)}function Xr(t,e){return t.locator.href===e.locator.href&&JSON.stringify(t.locator.locations?.serialize?.()??t.locator.locations)===JSON.stringify(e.locator.locations?.serialize?.()??e.locator.locations)&&JSON.stringify(t.locator.text??null)===JSON.stringify(e.locator.text??null)&&Rl(t.style,e.style)&&JSON.stringify(t.extras??null)===JSON.stringify(e.extras??null)}let Zr=class{constructor(){this.queue=[],this.channel=typeof MessageChannel<"u"?new MessageChannel:void 0,this.channel&&(this.channel.port1.onmessage=()=>this.flush())}push(e){const n=this.queue.length===0;this.queue.push(e),n&&(this.channel?this.channel.port2.postMessage(null):setTimeout(()=>this.flush(),0))}flush(){const e=this.queue;this.queue=[],e.forEach(n=>n())}clear(){this.queue=[]}};class Yr{constructor(){this.frame=new ei(this),this.host=new ti(this)}}let ei=class{constructor(e){this.channel=e,this.registrar=new Map,this.outbox=new Zr,this.ready=!0}register(e,n,r){(Array.isArray(e)?e:[e]).forEach(i=>{const s=this.registrar.get(i)??[];if(s.find(o=>o.module===n))throw new Error(`Duplicate callback for "${i}" in module "${n}"`);s.push({module:n,cb:r}),this.registrar.set(i,s)})}unregister(e,n){(Array.isArray(e)?e:[e]).forEach(r=>{const i=this.registrar.get(r);i&&this.registrar.set(r,i.filter(s=>s.module!==n))})}unregisterAll(e){this.registrar.forEach((n,r)=>{this.registrar.set(r,n.filter(i=>i.module!==e))})}_dispatch(e,n,r){const i=this.registrar.get(e);if(!i?.length){r(!1);return}i.forEach(s=>s.cb(n,r))}send(e,n){this.outbox.push(()=>this.channel.host._receive(e,n))}log(...e){this.outbox.push(()=>this.channel.host._receive("log",e))}destroy(){this.registrar.clear(),this.outbox.clear()}};class ti{constructor(e){this.channel=e,this.listeners=new Map,this.outbox=new Zr,this.ready=!0}send(e,n,r){this.outbox.push(()=>this.channel.frame._dispatch(e,n,r??(()=>{})))}on(e,n){const r=this.listeners.get(e)??[];r.push(n),this.listeners.set(e,r)}off(e,n){const r=this.listeners.get(e);r&&this.listeners.set(e,r.filter(i=>i!==n))}_receive(e,n){this.listeners.get(e)?.forEach(r=>r(n))}}class ni{constructor(e,n={}){this.host=e,this._decorations=new Map,this._activationState=new Map,this._hoverState=new Map,this._observers=new Map,this._hoveredDecorations=new Map,this._config=n,e.on("decoration_activated",r=>{const i=r,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId);s&&this._observers.get(i.group)?.forEach(o=>o.onDecorationActivated?.({group:i.group,decoration:s,rect:i.rect,point:i.point}))}),e.on("decoration_pointer_enter",r=>{const i=r,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId);s&&(this._hoveredDecorations.set(i.group,s),this._observers.get(i.group)?.forEach(o=>o.onDecorationPointerEnter?.({group:i.group,decoration:s,rect:i.rect,point:i.point})))}),e.on("decoration_pointer_leave",r=>{const i=r,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId)??this._hoveredDecorations.get(i.group);this._hoveredDecorations.delete(i.group),s&&this._observers.get(i.group)?.forEach(o=>o.onDecorationPointerLeave?.({group:i.group,decoration:s,rect:i.rect,point:i.point}))})}supportsDecorationStyle(e){return Qr(e,this._config.decorationTemplates)}applyDecorations(e,n){const r=this._decorations.get(n)??[],i=new Map(r.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id,c]));for(const[c,l]of i){const d=s.get(c);d?Xr(l,d)||this.host.send("decorate",{group:n,action:"update",decoration:Mt(d,this._config.decorationTemplates)}):this.host.send("decorate",{group:n,action:"remove",decoration:{id:c}})}for(const[c,l]of s)i.has(c)||this.host.send("decorate",{group:n,action:"add",decoration:Mt(l,this._config.decorationTemplates)});this._decorations.set(n,e);const o=this._activationState.get(n);o!==void 0&&this.host.send("decoration_activatable",{group:n,activatable:o});const a=this._hoverState.get(n);a!==void 0&&this.host.send("decoration_hoverable",{group:n,hoverable:a})}registerDecorationObserver(e,n){this._observers.has(e)||this._observers.set(e,new Set),this._observers.get(e).add(n),n.onDecorationActivated&&(this._activationState.set(e,!0),this.host.send("decoration_activatable",{group:e,activatable:!0})),(n.onDecorationPointerEnter||n.onDecorationPointerLeave)&&(this._hoverState.set(e,!0),this.host.send("decoration_hoverable",{group:e,hoverable:!0}))}unregisterDecorationObserver(e){this._observers.forEach((n,r)=>{if(!n.has(e))return;n.delete(e);const i=[...n].some(o=>o.onDecorationActivated);this._activationState.has(r)&&!i&&(this._activationState.delete(r),this.host.send("decoration_activatable",{group:r,activatable:!1}));const s=[...n].some(o=>o.onDecorationPointerEnter||o.onDecorationPointerLeave);this._hoverState.has(r)&&!s&&(this._hoverState.delete(r),this.host.send("decoration_hoverable",{group:r,hoverable:!1}))})}destroy(){this._decorations.clear(),this._activationState.clear(),this._hoverState.clear(),this._observers.clear(),this._hoveredDecorations.clear()}}function Pl(t){return t&&Array.isArray(t)?t:void 0}function Nl(t){return t&&typeof t=="string"?[t]:Pl(t)}function Et(t){return isNaN(t)?void 0:t}class V{constructor(e){this.fragments=e.fragments?e.fragments:new Array,this.progression=e.progression,this.totalProgression=e.totalProgression,this.position=e.position,this.otherLocations=e.otherLocations}static deserialize(e){if(!e)return;const n=Et(e.progression),r=Et(e.totalProgression),i=Et(e.position),s=new Map,o=new Set(["fragment","fragments","progression","totalProgression","position","otherLocations"]);return Object.entries(e).forEach(([a,c])=>{o.has(a)||s.set(a,c)}),e.otherLocations instanceof Map&&e.otherLocations.forEach((a,c)=>s.set(c,a)),new V({fragments:Nl(e.fragments||e.fragment),progression:n!==void 0&&n>=0&&n<=1?n:void 0,totalProgression:r!==void 0&&r>=0&&r<=1?r:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:s.size===0?void 0:s})}serialize(){const e={};return this.fragments&&(e.fragments=this.fragments),this.progression!==void 0&&(e.progression=this.progression),this.totalProgression!==void 0&&(e.totalProgression=this.totalProgression),this.position!==void 0&&(e.position=this.position),this.otherLocations&&this.otherLocations.forEach((n,r)=>e[r]=n),e}}class _e{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new _e({after:e.after,before:e.before,highlight:e.highlight})}serialize(){const e={};return this.after!==void 0&&(e.after=this.after),this.before!==void 0&&(e.before=this.before),this.highlight!==void 0&&(e.highlight=this.highlight),e}}class Le{constructor(e){const n=e.href.indexOf("#"),r=n>=0?e.href.slice(n+1):void 0;this.href=n>=0?e.href.slice(0,n):e.href,this.type=e.type,this.title=e.title;const i=e.locations?.fragments,s=r&&(!i||i.length===0);this.locations=e.locations?s?new V({...e.locations,fragments:[r]}):e.locations:r?new V({fragments:[r]}):new V({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new Le({href:e.href,type:e.type,title:e.title,locations:V.deserialize(e.locations),text:_e.deserialize(e.text)})}serialize(){const e={href:this.href,type:this.type};return this.title!==void 0&&(e.title=this.title),this.locations&&(e.locations=this.locations.serialize()),this.text&&(e.text=this.text.serialize()),e}copyWithLocations(e){return new Le({href:this.href,type:this.type,title:this.title,text:this.text,locations:new V({...this.locations,...e})})}}function ri(t,e=window){const{highlight:n,before:r,after:i,selector:s,fragment:o}=t,c=n!==void 0||r!==void 0||i!==void 0?new _e({highlight:n,before:r,after:i}):void 0,l=s?new Map([["cssSelector",s]]):void 0,u=l!==void 0||o!==void 0?new V({fragments:o?[o]:void 0,otherLocations:l}):void 0;return new Le({href:e.location.href,type:"text/html",text:c,locations:u})}class ii extends ni{constructor(e,n,r,i={}){super(e.host,i),this.channel=e,this.wnd=n,this.decorator=r}decorate(e,n){this.applyDecorations(e.map(({id:r,style:i,...s})=>({id:r,style:i,locator:ri(s,this.wnd)})),n)}destroy(){super.destroy(),this.decorator.unmount(this.wnd,this.channel.frame),this.channel.frame.destroy()}}function Il(t=window,e={}){const n=new Yr,r=new Kr;return r.mount(t,n.frame),new ii(n,t,r,e)}class Ll{providers=new Map;register(e){if(this.providers.has(e.id))throw new Error(`A provider is already registered under id "${e.id}"`);this.providers.set(e.id,e)}unregister(e){this.providers.delete(e)}get(e){return this.providers.get(e)}list(){return[...this.providers.values()]}async getVoices(e){return this.require(e).getVoices()}async getAllVoices(){return Promise.all(this.list().map(async e=>({providerId:e.id,voices:await e.getVoices()})))}async createEngine(e,n){return this.require(e).createEngine(n)}async destroy(){await Promise.all(this.list().map(e=>e.destroy())),this.providers.clear()}require(e){const n=this.providers.get(e);if(!n)throw new Error(`No provider registered under id "${e}"`);return n}}const tt={range:[0,5e3],step:100},nt={range:[.1,10],step:.1},rt={range:[0,2],step:.1},it={range:[0,1],step:.05},an=["none","few","some","most","custom"],on=["none","block-level","always"],ln=["plain","ssml"],cn=["none","utterance","block"],er=["format","inlineContextualization","verbosity","skip","contextualize","language"];function un(t){return t==null||typeof t=="boolean"?t:void 0}function F(t,e){return t==null||e.includes(t)?t:void 0}function M(t,e){if(t==null)return t;if(typeof t!="number"||Number.isNaN(t))return;const n=Math.min(...e),r=Math.max(...e);return t>=n&&t<=r?t:void 0}function qe(t){return t==null||Array.isArray(t)&&t.every(e=>typeof e=="string")?t:void 0}class si{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=F(e.format,ln)??"plain",this.inlineContextualization=un(e.inlineContextualization)??!1,this.verbosity=F(e.verbosity,an)??"few",this.skip=qe(e.skip)??[],this.contextualize=qe(e.contextualize)??[],this.language=F(e.language,on)??"block-level",this.pauseDuration=M(e.pauseDuration,tt.range)??300,this.autoPause=F(e.autoPause,cn)??"none",this.rate=M(e.rate,nt.range)??1,this.pitch=M(e.pitch,rt.range)??1,this.volume=M(e.volume,it.range)??1}}class pe{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=F(e.format,ln),this.inlineContextualization=un(e.inlineContextualization),this.verbosity=F(e.verbosity,an),this.skip=qe(e.skip),this.contextualize=qe(e.contextualize),this.language=F(e.language,on),this.pauseDuration=M(e.pauseDuration,tt.range),this.autoPause=F(e.autoPause,cn),this.rate=M(e.rate,nt.range),this.pitch=M(e.pitch,rt.range),this.volume=M(e.volume,it.range)}merging(e){const n={...this};for(const r of Object.keys(e))e[r]!==void 0&&(n[r]=e[r]);return new pe(n)}}class Be{_value;_effectiveValue;_isEffective;_onChange;constructor({initialValue:e=null,effectiveValue:n,isEffective:r,onChange:i}){this._value=e,this._effectiveValue=n,this._isEffective=r,this._onChange=i}set value(e){this._value=e,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null,this._onChange(this._value)}}class Re extends Be{_supportedValues;constructor({initialValue:e=null,effectiveValue:n,isEffective:r,onChange:i,supportedValues:s}){super({initialValue:e,effectiveValue:n,isEffective:r,onChange:i}),this._supportedValues=s}set value(e){if(e!=null&&F(e,this._supportedValues)===void 0)throw new Error(`Value '${String(e)}' is not in the supported values for this preference.`);this._value=e,this._onChange(this._value)}get value(){return this._value}get supportedValues(){return this._supportedValues}}class ai extends Be{set value(e){if(e!=null&&un(e)===void 0)throw new Error(`Value '${String(e)}' is not a boolean.`);this._value=e,this._onChange(this._value)}get value(){return this._value}}class Ht extends Be{set value(e){if(e!=null&&qe(e)===void 0)throw new Error(`Value '${String(e)}' is not an array of strings.`);this._value=e,this._onChange(this._value)}get value(){return this._value}}class Pe extends Be{_supportedRange;_step;_decimals;constructor({initialValue:e=null,effectiveValue:n,isEffective:r,onChange:i,supportedRange:s,step:o}){super({initialValue:e,effectiveValue:n,isEffective:r,onChange:i}),this._supportedRange=s,this._step=o,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(e){if(e!=null&&M(e,this._supportedRange)===void 0)throw new Error(`Value '${String(e)}' is out of the supported range for this preference.`);this._value=e,this._onChange(this._value)}get value(){return this._value}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value!=null&&this._value<this._supportedRange[1]&&(this._value=Math.min(Math.round((this._value+this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[1]),this._onChange(this._value))}decrement(){this._value!=null&&this._value>this._supportedRange[0]&&(this._value=Math.max(Math.round((this._value-this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[0]),this._onChange(this._value))}format(e){return e.toString()}}class Gt{preferences;settings;constructor(e,n){this.preferences=new pe({...e}),this.settings=n}clear(){this.preferences=new pe({format:null,inlineContextualization:null,verbosity:null,skip:null,contextualize:null,language:null,pauseDuration:null,autoPause:null,rate:null,pitch:null,volume:null})}updatePreference(e,n){this.preferences[e]=n}get format(){return new Re({initialValue:this.preferences.format,effectiveValue:this.settings.format,isEffective:this.preferences.format!=null,onChange:e=>this.updatePreference("format",e??null),supportedValues:ln})}get inlineContextualization(){return new ai({initialValue:this.preferences.inlineContextualization,effectiveValue:this.settings.inlineContextualization,isEffective:this.preferences.inlineContextualization!=null,onChange:e=>this.updatePreference("inlineContextualization",e??null)})}get verbosity(){return new Re({initialValue:this.preferences.verbosity,effectiveValue:this.settings.verbosity,isEffective:this.preferences.verbosity!=null,onChange:e=>this.updatePreference("verbosity",e??null),supportedValues:an})}get skip(){return new Ht({initialValue:this.preferences.skip,effectiveValue:this.settings.skip,isEffective:this.preferences.skip!=null,onChange:e=>this.updatePreference("skip",e??null)})}get contextualize(){return new Ht({initialValue:this.preferences.contextualize,effectiveValue:this.settings.contextualize,isEffective:this.preferences.contextualize!=null,onChange:e=>this.updatePreference("contextualize",e??null)})}get language(){return new Re({initialValue:this.preferences.language,effectiveValue:this.settings.language,isEffective:this.preferences.language!=null,onChange:e=>this.updatePreference("language",e??null),supportedValues:on})}get pauseDuration(){return new Pe({initialValue:this.preferences.pauseDuration,effectiveValue:this.settings.pauseDuration,isEffective:this.preferences.pauseDuration!=null,onChange:e=>this.updatePreference("pauseDuration",e??null),supportedRange:tt.range,step:tt.step})}get autoPause(){return new Re({initialValue:this.preferences.autoPause,effectiveValue:this.settings.autoPause,isEffective:this.preferences.autoPause!=null,onChange:e=>this.updatePreference("autoPause",e??null),supportedValues:cn})}get rate(){return new Pe({initialValue:this.preferences.rate,effectiveValue:this.settings.rate,isEffective:this.preferences.rate!=null,onChange:e=>this.updatePreference("rate",e??null),supportedRange:nt.range,step:nt.step})}get pitch(){return new Pe({initialValue:this.preferences.pitch,effectiveValue:this.settings.pitch,isEffective:this.preferences.pitch!=null,onChange:e=>this.updatePreference("pitch",e??null),supportedRange:rt.range,step:rt.step})}get volume(){return new Pe({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!=null,onChange:e=>this.updatePreference("volume",e??null),supportedRange:it.range,step:it.step})}}const oi=["audio","figure","image","math","table","video"],li=[...oi,"blockquote","cell","chapter","columnheader","cover","details","notice","part","preformatted","qna","row","rowheader","subtitle","tip"],ql=[...li,"abstract","acknowledgments","afterword","appendix","aside","bibliography","caption","colophon","complementary","conclusion","credit","credits","dedication","definition","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","heading1","heading2","heading3","heading4","heading5","heading6","index","introduction","list","listItem","pagebreak","pagelist","preface","prologue","pullquote","separator","summary","term"],ci={none:new Set(["aside","bibliography","endnotes","footnote","noteref","pullquote","pagebreak","details","columnheader","rowheader","row","cell","audio","image","figure","video","table","landmarks","loa","loi","lot","lov","toc"]),few:new Set(["aside","bibliography","endnotes","footnote","noteref","pullquote","pagebreak","details","columnheader","rowheader","row","cell","landmarks","loa","loi","lot","lov","toc"]),some:new Set(["aside","bibliography","endnotes","footnote","noteref","pullquote","pagebreak","landmarks","loa","loi","lot","lov","toc"]),most:new Set(["landmarks","loa","loi","lot","lov","toc"])},ui={none:new Set,few:new Set(oi),some:new Set(li),most:new Set(ql)};class Wt{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e,n){this.format=e.format??n.format,this.inlineContextualization=e.inlineContextualization??n.inlineContextualization,this.verbosity=e.verbosity??n.verbosity,this.verbosity==="custom"?(this.skip=e.skip??n.skip,this.contextualize=e.contextualize??n.contextualize):(this.skip=[...ci[this.verbosity]],this.contextualize=[...ui[this.verbosity]]),this.language=e.language??n.language,this.pauseDuration=e.pauseDuration??n.pauseDuration,this.autoPause=e.autoPause??n.autoPause,this.rate=e.rate??n.rate,this.pitch=e.pitch??n.pitch,this.volume=e.volume??n.volume}}function Ue(t){return t.plain===""&&t.ssml===""&&t.language===""}function Dl(t){if(!t||Ue(t))return;if(t.ssml===""&&t.language==="")return t.plain;const e={language:t.language};return t.plain!==""&&(e.plain=t.plain),t.ssml!==""&&(e.ssml=t.ssml),e}function $l(t,e){if(t.lang!==e.lang||t.tag!==e.tag)return!1;const n=Object.entries(t.attrs??{}),r=Object.entries(e.attrs??{});return n.length!==r.length?!1:n.every(([i,s])=>e.attrs?.[i]===s)}const st=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),At=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),_l=/[\u00A0\u2007\u202F]/;function Bl(t){return _l.test(t)}function De(t,e){let n="",r=!1,i=!1;for(const s of t)if(Bl(s))n+=s,r=!1,i=!0;else if(/\s/.test(s)){if(e&&!i||r)continue;n+=" ",r=!0}else s!==""&&s!==""&&(n+=s,r=!1,i=!0);return n}const hi={footnote:{start:"Start of the footnote.",end:"End of the footnote."},part:{start:"Start of the part.",end:"End of the part."},chapter:{start:"Start of the chapter.",end:"End of the chapter."},prologue:{start:"Start of the prologue.",end:"End of the prologue."},preface:{start:"Start of the preface.",end:"End of the preface."},introduction:{start:"Start of the introduction.",end:"End of the introduction."},conclusion:{start:"Start of the conclusion.",end:"End of the conclusion."},epilogue:{start:"Start of the epilogue.",end:"End of the epilogue."},afterword:{start:"Start of the afterword.",end:"End of the afterword."},appendix:{start:"Start of the appendix.",end:"End of the appendix."},acknowledgments:{start:"Start of the acknowledgments.",end:"End of the acknowledgments."},endnotes:{start:"Start of the endnotes.",end:"End of the endnotes."},glossary:{start:"Start of the glossary.",end:"End of the glossary."},bibliography:{start:"Start of the bibliography.",end:"End of the bibliography."},index:{start:"Start of the index.",end:"End of the index."},toc:{start:"Start of the table of contents.",end:"End of the table of contents."},pagelist:{start:"Start of the page list.",end:"End of the page list."},landmarks:{start:"Start of the landmarks.",end:"End of the landmarks."},loa:{start:"Start of the list of audio clips.",end:"End of the list of audio clips."},loi:{start:"Start of the list of illustrations.",end:"End of the list of illustrations."},lot:{start:"Start of the list of tables.",end:"End of the list of tables."},lov:{start:"Start of the list of video clips.",end:"End of the list of video clips."},qna:{start:"Start of the questions and answers.",end:"End of the questions and answers."},table:{start:"Start of the table.",end:"End of the table."},figure:{start:"Start of the figure.",end:"End of the figure."},aside:{start:"Start of the aside.",end:"End of the aside."},details:{start:"Start of the details.",end:"End of the details."},credits:{start:"Start of the credits.",end:"End of the credits."},blockquote:{start:"Start of the quote.",end:"End of the quote."},list:{start:"Start of the list.",end:"End of the list."},preformatted:{start:"Start of the preformatted text.",end:"End of the preformatted text."},row:{start:"Start of the row.",end:"End of the row."},complementary:{start:"Start of the complementary content.",end:"End of the complementary content."},pagebreak:"Pagebreak.",heading1:"Heading level 1.",heading2:"Heading level 2.",heading3:"Heading level 3.",heading4:"Heading level 4.",heading5:"Heading level 5.",heading6:"Heading level 6.",subtitle:"Subtitle.",epigraph:"Epigraph.",abstract:"Abstract.",colophon:"Colophon.",dedication:"Dedication.",cover:"Cover.",errata:"Errata.",notice:"Notice.",example:"Example.",tip:"Tip.",pullquote:"Pull quote.",credit:"Credit.",image:"Image.",audio:"Audio.",video:"Video.",caption:"Caption.",listItem:"List item.",cell:"Cell.",columnheader:"Column header.",rowheader:"Row header.",term:"Term.",summary:"Summary.",separator:"Separator."},Ul=/<lang xml:lang="[^"]*">([\s\S]*?)<\/lang>/g;function di(t){return t.replace(Ul,"$1")}const zl=/\s*<readium:[a-zA-Z][\w-]*\s+id="[^"]*"\s*\/>\s*/g;function jl(t){return t.replace(zl,(n,r,i)=>{const s=i.slice(r+n.length);return s.length===0||ct(s)?"":" "}).replace(/ {2,}/g," ").trim()}function Vl(t){return t.includes("<")}function gi(t){if(t===void 0)return;if(typeof t=="string")return{plain:t};const e={language:t.language};if(t.ssml){const n=jl(t.ssml);Vl(n)&&(e.ssml=n)}return t.plain&&(e.plain=t.plain),e.plain||e.ssml?e:void 0}function hn(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ").trim()}const fi=/<lang xml:lang="([^"]*)">([\s\S]*?)<\/lang>/g;function pi(t){return new RegExp(fi).test(t)}function tr(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ")}const Fl=new RegExp(`\\s+|[${_t}]+|[${oe}]+|[^\\s${_t}${oe}]+`,"gu");function Ot(t){const e=[];for(const[n]of t.matchAll(Fl))/^\s/.test(n)?e.push({kind:"space"}):Do(n)?e.push({kind:"open",text:n}):ct(n)?e.push({kind:"close",text:n}):e.push({kind:"word",text:n});return e}function Ml(t){let e="",n=!1;for(const r of t){if(r.kind==="space"){e&&(n=!0);continue}n&&(e+=" "),e+=r.text,n=!1}return e}function Hl(t){let e=t.length;for(;e>0&&(t[e-1].kind==="space"||t[e-1].kind==="open");)e--;return t.slice(e).some(n=>n.kind==="open")?t.splice(e):[]}function Gl(t){let e=0;for(;e<t.length&&(t[e].kind==="space"||t[e].kind==="close");)e++;return t.slice(0,e).some(n=>n.kind==="close")?t.splice(0,e):[]}function mi(t,e){const n=[];let r=0;for(const s of t.matchAll(fi))n.push({tokens:Ot(tr(t.slice(r,s.index))),language:e,tagged:!1}),n.push({tokens:Ot(hn(s[2])),language:s[1],tagged:!0}),r=s.index+s[0].length;n.push({tokens:Ot(tr(t.slice(r))),language:e,tagged:!1});for(let s=0;s<n.length-1;s++)!n[s].tagged&&n[s+1].tagged?n[s+1].tokens.unshift(...Hl(n[s].tokens)):n[s].tagged&&!n[s+1].tagged&&n[s].tokens.push(...Gl(n[s+1].tokens));const i=[];for(const s of n){const o=Ml(s.tokens);o&&i.push({plain:o,language:s.language})}return i}const yi=/<readium:[a-zA-Z][\w-]*\s+id="([^"]*)"\s*\/>/g;function Wl(t){return new RegExp(yi).test(t)}function Kl(t){const e=[];let n=0;for(const i of t.matchAll(yi)){const s=t.slice(n,i.index).trim();s&&e.push({ssml:s}),e.push({placeholderId:i[1]}),n=i.index+i[0].length}const r=t.slice(n).trim();return r&&e.push({ssml:r}),e}function at(t){return typeof t=="object"}const Jl=["aside","bibliography","details","endnotes","footnote","noteref","pullquote","landmarks","loa","loi","lot","lov","pagebreak","toc"],bi=["heading1","heading2","heading3","heading4","heading5","heading6","paragraph","blockquote","preformatted","pullquote","list","listItem","table","row","cell","columnheader","rowheader","audio","video","figure","image","math","abstract","acknowledgments","afterword","appendix","article","aside","bibliography","chapter","colophon","conclusion","dedication","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","index","introduction","notice","part","preface","prologue","qna","section","summary","tip"],Ql=new Set(bi);function $e(t,e){return typeof t=="function"?t(e):t}function ce(t,e){return e==="ssml"?{ssml:st(t)}:{plain:t}}function ue(t,e,n,r){t.push(...r);for(let i=0;i<r.length;i++)e.push(n)}function vi(t,e,n,r,i,s,o){o?(i.some(a=>n.blockStarts.has(a))&&n.blockStarts.add(o),ue(t,e,s[0]??r,[o])):(t.push(...i),e.push(...s))}function nr(t,e,n,r,i,s,o){if(!r.contextualize.has(i))return;const a=r.announcements[i];if(a!==void 0){if(at(a)){const c=s==="before"?a.start:a.end;ue(t,e,n,[ce($e(c,o),r.format)]);return}s==="before"&&ue(t,e,n,[ce($e(a,o),r.format)])}}function rr(t,e){return e.size>0&&t.some(n=>e.has(n))}function dn(t,e){let n,r=!1;const i=[];for(const a of t){const c=e==="ssml"?a.ssml:a.plain;if(c&&(i.push(c),a.language!==void 0)){if(r&&a.language!==n)return;n=a.language,r=!0}}if(i.length===0)return;let s="";for(const a of i)a.length===1&&s.endsWith(a)||(s&&!ct(a)&&(s+=" "),s+=a);const o=e==="ssml"?{ssml:s}:{plain:s};return n&&(o.language=n),o}function Xl(t,e){const n=gi(t.text),r=n?wi(n,e.format,e.language):[];if(!e.contextualize.has("pagebreak"))return r;const i=e.announcements.pagebreak;if(i===void 0)return r;const s=ce($e(at(i)?i.start:i),e.format);if(r.length===0)return[s];const o=dn([s,...r],e.format);return o?(o.plain!==void 0&&(o.plain+="."),o.ssml!==void 0&&(o.ssml+="."),[o]):[s,...r]}function wi(t,e,n){if(e==="plain"&&n!=="block-level"&&n!=="none"&&t.ssml&&pi(t.ssml))return mi(t.ssml,t.language).map(i=>{const s={plain:i.plain};return i.language&&(s.language=i.language),s});const r={};return t.language&&(r.language=t.language),e==="ssml"?r.ssml=t.ssml??st(t.plain??""):r.plain=t.plain??hn(t.ssml??""),(n==="block-level"||n==="none")&&(r.ssml&&(r.ssml=di(r.ssml)),n==="none"&&delete r.language),[r]}function Zl(t,e,n,r,i,s){const o=typeof t.text=="object"?t.text.language:void 0,a=new Map((t.children??[]).map(u=>[u.id,u])),c=[],l=[];for(const u of Kl(e)){if(u.placeholderId!==void 0){const f=a.get(u.placeholderId);f&&Si(f,c,l,i,s);continue}if(!u.ssml)continue;if(i.format==="plain"&&i.language!=="block-level"&&i.language!=="none"&&pi(u.ssml)){for(const f of mi(u.ssml,o)){const y={plain:f.plain};f.language&&(y.language=f.language),c.push(y),l.push(t)}continue}const g={};o&&(g.language=o),i.format==="ssml"?g.ssml=u.ssml:g.plain=hn(u.ssml),(i.language==="block-level"||i.language==="none")&&(g.ssml&&(g.ssml=di(g.ssml)),i.language==="none"&&delete g.language),c.push(g),l.push(t)}const d=c.length>1?dn(c,i.format):void 0;vi(n,r,i,t,c,l,d)}function Si(t,e,n,r,i){const s=t.role??[];if(rr(s,r.skip))return;const o=s.some(u=>Ql.has(u)),a=o&&!i,c=e.length,l=s.includes("footnote"),d=s.filter(u=>!(l&&(u==="footnote"||u==="aside"))&&u!=="pagebreak");for(const u of d)nr(e,n,t,r,u,"before");if(s.includes("noteref"))for(const u of t.children??[]){const g=u.role??[];if(!rr(g,r.skip))if(g.includes("footnote")){const f=[],y=[];ae([u],f,y,r,i);const p=r.contextualize.has("footnote")?r.announcements.footnote:void 0,m=[],w=[];if(p!==void 0){const C=at(p)?p.start:p;m.push(ce($e(C),r.format)),w.push(u)}m.push(...f),w.push(...y),p!==void 0&&at(p)&&(m.push(ce($e(p.end),r.format)),w.push(u));const E=p!==void 0&&m.length>1?dn(m,r.format):void 0;vi(e,n,r,u,m,w,E)}else ae([u],e,n,r,i)}else{const u=typeof t.text=="object"?t.text.ssml:void 0;if(r.inlineContextualization&&u&&Wl(u))Zl(t,u,e,n,r,i);else if(s.includes("pagebreak")){if(ue(e,n,t,Xl(t,r)),t.children){const g=i||o&&e.length>c;ae(t.children,e,n,r,g)}}else{const g=gi(t.text);if(g&&ue(e,n,t,wi(g,r.format,r.language)),t.children){const f=i||o&&e.length>c;ae(t.children,e,n,r,f)}}}a&&e.length>c&&r.blockStarts.add(e[c]),t.description!==void 0&&ue(e,n,t,[ce(t.description,r.format)]);for(const u of d)nr(e,n,t,r,u,"after")}function ae(t,e,n,r,i){t.forEach((s,o)=>Si(s,e,n,r,o===0?i:!1))}function xi(t){return{announcements:{...hi,...t.announcements},skip:new Set(t.skip??[]),contextualize:new Set(t.contextualize??[]),format:t.format??"plain",inlineContextualization:t.inlineContextualization??!1,language:t.language,blockStarts:new Set}}function Yl(t,e){const n=[];return ae(t,n,[],xi(e),!1),n}function ec(t,e){const n=[],r=[],i=xi(e);ae(t,n,r,i,!1);const s=n.map(o=>i.blockStarts.has(o));return{utterances:n,sources:r,blockStarts:s}}class tc{engine;contentQueue=[];eventListeners=new Map;navigatorState="idle";pendingAdvanceTimeout=null;_defaults;_preferences;_settings;_preferencesEditor=null;source;contentSources=[];contentBlockStarts=[];pendingResumeIndex=null;pendingResumeState=null;pendingAutoPauseIndex=null;constructor(e,n={}){this.engine=e,this._defaults=new si(n.defaults),this._preferences=new pe(n.preferences),this._settings=new Wt(this._preferences,this._defaults),this.setupEngineListeners(),this.applyEngineParameters(),this.initializeEngine()}applyEngineParameters(){this.engine.setRate(this._settings.rate),this.engine.setPitch(this._settings.pitch),this.engine.setVolume(this._settings.volume)}async initializeEngine(){try{await this.engine.initialize?.()}catch(e){console.warn("Failed to initialize speech engine:",e)}}setupEngineListeners(){this.engine.on("start",()=>{this.setNavigatorState("playing"),this.emitEvent({type:"start"})}),this.engine.on("end",()=>{const e=this.engine.getCurrentUtteranceIndex(),n=this.engine.getUtteranceCount();if(e<n-1){const r=this._settings.autoPause==="utterance"||this.contentBlockStarts[e+1]===!0;this._settings.autoPause!=="none"&&r?(this.pendingAutoPauseIndex=e+1,this.setNavigatorState("paused"),this.emitEvent({type:"pause"})):this.pendingAdvanceTimeout=setTimeout(()=>{this.pendingAdvanceTimeout=null,this.engine.speak(e+1)},this._settings.pauseDuration)}else this.setNavigatorState("idle");this.emitEvent({type:"end"})}),this.engine.on("pause",()=>{this.setNavigatorState("paused"),this.emitEvent({type:"pause"})}),this.engine.on("resume",()=>{this.setNavigatorState("playing"),this.emitEvent({type:"resume"})}),this.engine.on("stop",()=>{this.setNavigatorState("idle"),this.emitEvent({type:"stop"})}),this.engine.on("error",e=>{this.setNavigatorState("idle"),this.emitEvent(e)}),this.engine.on("ready",()=>{if(this.contentQueue.length===0)return;const e=this.pendingResumeIndex,n=this.pendingResumeState;if(this.pendingResumeIndex=null,this.pendingResumeState=null,this.navigatorState==="loading"){if(n==="playing"){this.setNavigatorState("playing"),this.engine.speak(e??0);return}if(n==="paused"){const r=e??0;r>0?this.engine.setCurrentUtteranceIndex(r,()=>this.setNavigatorState("paused")):this.setNavigatorState("paused");return}this.setNavigatorState("ready"),this.emitEvent({type:"ready"})}}),this.engine.on("boundary",e=>{this.emitEvent(e)}),this.engine.on("mark",e=>{this.emitEvent(e)}),this.engine.on("voiceschanged",()=>{this.emitEvent({type:"voiceschanged"})}),this.engine.on("languagefallback",e=>{this.emitEvent(e)})}setNavigatorState(e){this.navigatorState=e}async getVoices(){return this.engine.getAvailableVoices()}setVoice(e){this.engine.setVoice(e)}getCurrentVoice(){return this.engine.getCurrentVoice()}setSpeakInContentLanguage(e){this.engine.setSpeakInContentLanguage(e)}getSpeakInContentLanguage(){return this.engine.getSpeakInContentLanguage()}loadContent(e){if(this.source)throw new Error("loadContent() cannot be used after loadGndContent() — the two are exclusive. Create a new navigator instance to switch content sources.");this.setContentQueue(e)}loadGndContent(e){this.source=e,this.reextract()}setContentQueue(e,n=null,r=null){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,(this.navigatorState==="playing"||this.navigatorState==="paused")&&this.engine.stop();const i=Array.isArray(e)?e:[e];this.contentQueue=[...i],this.pendingResumeIndex=n,this.pendingResumeState=r,this.setNavigatorState("loading"),this.emitEvent({type:"loading"}),this.engine.loadUtterances(i),this.emitContentChangeEvent({content:i})}reextract(){if(!this.source)return;const e=this.navigatorState==="playing"||this.navigatorState==="paused"?this.navigatorState:null,n=this.contentSources,r=this.getCurrentUtteranceIndex(),{utterances:i,sources:s,blockStarts:o}=ec(this.source,{format:this._settings.format,inlineContextualization:this._settings.inlineContextualization,skip:this._settings.skip,contextualize:this._settings.contextualize,language:this._settings.language});this.contentSources=s,this.contentBlockStarts=o;const a=e?this.resolveResumeIndex(n,r,s):null;this.setContentQueue(i,a,e)}resolveResumeIndex(e,n,r){for(let i=Math.min(n,e.length-1);i>=0;i--){const s=e[i];if(s===void 0)continue;const o=r.indexOf(s);if(o!==-1)return o}return null}getCurrentContent(){const e=this.getCurrentUtteranceIndex();return e<this.contentQueue.length?this.contentQueue[e]:null}getContentQueue(){return[...this.contentQueue]}getCurrentUtteranceIndex(){return this.engine.getCurrentUtteranceIndex()}play(){if(this.navigatorState==="paused")if(this.setNavigatorState("playing"),this.pendingAutoPauseIndex!==null){const e=this.pendingAutoPauseIndex;this.pendingAutoPauseIndex=null,this.engine.speak(e)}else this.engine.resume();else if(this.navigatorState==="ready"||this.navigatorState==="idle")this.setNavigatorState("playing"),this.engine.speak();else if(this.navigatorState==="playing")return}pause(){this.navigatorState==="playing"&&(this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,this.setNavigatorState("paused"),this.engine.pause())}stop(){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,this.setNavigatorState("idle"),this.engine.stop(),this.emitEvent({type:"stop"})}clearPendingAdvance(){this.pendingAdvanceTimeout!==null&&(clearTimeout(this.pendingAdvanceTimeout),this.pendingAdvanceTimeout=null)}skipToPosition(e,n=!1){const r=this.getCurrentUtteranceIndex();return e<0||e>=this.contentQueue.length?!1:(e===r||(this.clearPendingAdvance(),this.navigatorState==="paused"&&!n?(this.pendingAutoPauseIndex!==null&&(this.pendingAutoPauseIndex=e),this.engine.setCurrentUtteranceIndex(e,i=>{i&&this.emitEvent({type:"skip",detail:{position:e}})})):(this.pendingAutoPauseIndex=null,this.setNavigatorState("playing"),this.engine.speak(e))),!0)}next(e=!1){const n=this.getCurrentUtteranceIndex();return this.skipToPosition(n+1,e)}previous(e=!1){const n=this.getCurrentUtteranceIndex();return this.skipToPosition(n-1,e)}jumpTo(e,n=!1){return this.skipToPosition(e,n)}getState(){return this.navigatorState}on(e,n){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(n),()=>{const r=this.eventListeners.get(e);if(r){const i=r.indexOf(n);i>-1&&r.splice(i,1)}}}emitEvent(e){const n=this.eventListeners.get(e.type);n&&n.forEach(r=>r(e))}emitContentChangeEvent(e){const n=this.eventListeners.get("contentchange");n&&n.forEach(r=>r({type:"contentchange",detail:e}))}get settings(){return this._settings}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new Gt(this._preferences,this.settings)),this._preferencesEditor}submitPreferences(e){!this.source&&er.some(n=>e[n]!==void 0)&&console.warn("submitPreferences(): extraction-affecting preferences (format, inlineContextualization, verbosity, skip, contextualize, language) have no effect on content loaded via loadContent() — use loadGndContent() to re-extract on submission."),this._preferences=this._preferences.merging(e),this.applyPreferences()}applyPreferences(){const e=this._settings;this._settings=new Wt(this._preferences,this._defaults),this.applyEngineParameters(),this._preferencesEditor!==null&&(this._preferencesEditor=new Gt(this._preferences,this._settings)),er.some(n=>!this.sameSettingValue(e[n],this._settings[n]))&&this.reextract()}sameSettingValue(e,n){return Array.isArray(e)&&Array.isArray(n)?e.length===n.length&&e.every(r=>n.includes(r)):e===n}async destroy(){this.clearPendingAdvance(),this.eventListeners.clear(),await this.engine.destroy()}}const nc=["heading1","heading2","heading3","heading4","heading5","heading6"],ir={"doc-abstract":"abstract","doc-acknowledgments":"acknowledgments","doc-afterword":"afterword","doc-appendix":"appendix",article:"article","doc-backlink":"backlink","doc-biblioentry":"listItem","doc-bibliography":"bibliography","doc-biblioref":"biblioref",blockquote:"blockquote",caption:"caption",cell:"cell","doc-chapter":"chapter","doc-colophon":"colophon",columnheader:"columnheader",complementary:"complementary","doc-conclusion":"conclusion","doc-cover":"cover","doc-credit":"credit","doc-credits":"credits","doc-dedication":"dedication",definition:"definition","doc-endnote":"footnote","doc-endnotes":"endnotes","doc-epigraph":"epigraph","doc-epilogue":"epilogue","doc-errata":"errata","doc-example":"example",figure:"figure","doc-footnote":"footnote","doc-foreword":"foreword","doc-glossary":"glossary","doc-glossref":"glossref",img:"image",image:"image","doc-index":"index","doc-introduction":"introduction",list:"list",listitem:"listItem",main:"main",math:"math",navigation:"navigation","doc-noteref":"noteref","doc-notice":"notice","doc-pagebreak":"pagebreak","doc-pagelist":"pagelist",paragraph:"paragraph","doc-part":"part","doc-preface":"preface","doc-prologue":"prologue","doc-pullquote":"pullquote",presentation:"presentation",none:"presentation","doc-qna":"qna",qna:"qna",region:"region",row:"row",rowheader:"rowheader",separator:"separator","doc-subtitle":"subtitle",table:"table",term:"term","doc-tip":"tip","doc-toc":"toc"},rc={abstract:"abstract",acknowledgments:"acknowledgments",afterword:"afterword",appendix:"appendix",aside:"aside",backlink:"backlink",biblioentry:"listItem",bibliography:"bibliography",biblioref:"biblioref","table-cell":"cell",chapter:"chapter",colophon:"colophon",conclusion:"conclusion",cover:"cover",credit:"credit",credits:"credits",dedication:"dedication",glossdef:"definition",endnote:"footnote",endnotes:"endnotes",rearnote:"footnote",rearnotes:"endnotes",epigraph:"epigraph",epilogue:"epilogue",errata:"errata",example:"example",figure:"figure",footnote:"footnote",foreword:"foreword",glossary:"glossary",glossref:"glossref",index:"index",introduction:"introduction",landmarks:"landmarks",list:"list","list-item":"listItem",loa:"loa",loi:"loi",lot:"lot",lov:"lov",noteref:"noteref",notice:"notice",pagebreak:"pagebreak","page-list":"pagelist",pagelist:"pagelist",part:"part",preface:"preface",prologue:"prologue",pullquote:"pullquote",qna:"qna","table-row":"row",subtitle:"subtitle",table:"table",glossterm:"term",tip:"tip",toc:"toc"},ic={article:"article",aside:"aside",audio:"audio",blockquote:"blockquote",caption:"caption",figcaption:"caption",td:"cell",dd:"definition",details:"details",figure:"figure",header:"header",h1:"heading1",h2:"heading2",h3:"heading3",h4:"heading4",h5:"heading5",h6:"heading6",img:"image",ul:"list",ol:"list",li:"listItem",main:"main",math:"math",nav:"navigation",p:"paragraph",pre:"preformatted",tr:"row",section:"section",hr:"separator",summary:"summary",table:"table",dfn:"term",dt:"term",video:"video",svg:"image"};function Tt(t){const e=[],n=c=>{e.includes(c)||e.push(c)},r=[];let i=!1;const s=t.getAttribute("role");if(s)for(const c of s.split(/\s+/).filter(Boolean))if((c==="presentation"||c==="none")&&(i=!0),c==="heading"){let l=2;const d=parseInt(t.getAttribute("aria-level")??"",10);Number.isFinite(d)&&d>=1&&(l=Math.min(d,6)),r.push(nc[l-1])}else ir[c]&&r.push(ir[c]);const o=t.getAttribute("epub:type");if(o)for(const c of o.split(/\s+/).filter(Boolean)){const l=rc[c];l&&r.push(l)}if(i)return["presentation"];const a=t.tagName.toLowerCase();if(a==="body")n("body");else if(a==="th")switch(t.getAttribute("scope")){case"col":n("columnheader");break;case"row":n("rowheader");break;default:n("cell")}else{const c=ic[a];c&&n(c)}for(const c of r)n(c);return e}function sr(t){return!!(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))}function Kt(t){let e="";const n=r=>{r.nodeType===3&&(e+=r.nodeValue??"");for(let i=r.firstChild;i;i=i.nextSibling)n(i)};return n(t),e}function Xe(t){return De(Kt(t),!0).trim()}function sc(t){if(sr(t))return[null,!1];const e=(t.getAttribute("aria-labelledby")??"").trim();if(e){const s=[...new Set(e.split(/\s+/).filter(Boolean))],o=t.ownerDocument,a=s.map(c=>o.getElementById(c)).filter(c=>c!==null);if(a.length>0){let c="";a.forEach((d,u)=>{if(sr(d))return;const g=d.getAttribute("aria-label");c+=g||Kt(d),u<a.length-1&&(c+=" ")});const l=De(c,!0).trim();if(l!=="")return[{language:"",plain:l},!0]}}const n=(t.getAttribute("aria-label")??"").trim();if(n)return[{language:"",plain:n},!0];const r=(t.getAttribute("aria-describedby")??"").trim();if(r){const o=[...new Set(r.split(/\s+/).filter(Boolean))].map(a=>t.ownerDocument.getElementById(a)).filter(a=>a!==null);if(o.length>0){const a=o.map(l=>Kt(l)).join(" "),c=De(a,!0).trim();if(c!=="")return[{language:"",plain:c},!0]}}const i=t.tagName.toLowerCase();if(i==="img"){const s=(t.getAttribute("alt")??"").trim();if(s)return[{language:"",plain:s},!0];const o=(t.getAttribute("title")??"").trim();if(o)return[{language:"",plain:o},!0]}else if(i==="svg"){const s=t.querySelector(":scope > title");if(s){const o=Xe(s);if(o)return[{language:"",plain:o},!0]}}else if(i==="math"){const s=(t.getAttribute("alttext")??"").trim();if(s)return[{language:"",plain:s},!0]}return[null,!0]}const ac={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function oc(t){return ac[t]??["",void 0]}const lc=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]);function Jt(t){return!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||Ue(t.text))&&!(t.children&&t.children.length>0)&&!t.description}function cc(t){return!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||Ue(t.text))&&!!(t.children&&t.children.length>0)&&!(t.role&&t.role.length>0)&&!t.id}function uc(t){return!(t.role&&t.role.length>0)&&!t.id}class Je{el;object={};children=[];noText=!1;finalize(){const e=this.object,n=[];for(const r of this.children){const i=r.finalize();if(!Jt(i)){if(cc(i)){n.push(...i.children??[]);continue}n.push(i)}}if(n.length>0&&(e.children=n),(!e.text||Ue(e.text))&&e.children?.length===1){const r=e.children[0];uc(r)&&(r.text&&(e.text=r.text),r.textref&&(e.textref=r.textref),r.imgref&&(e.imgref=r.imgref),r.audioref&&(e.audioref=r.audioref),r.videoref&&(e.videoref=r.videoref),e.children=r.children)}return e}}function Qt(t){const e={};t.id&&(e.id=t.id),t.textref&&(e.textref=t.textref),t.imgref&&(e.imgref=t.imgref),t.audioref&&(e.audioref=t.audioref),t.videoref&&(e.videoref=t.videoref);const n=Dl(t.text);return n!==void 0&&(e.text=n),t.role&&t.role.length>0&&(e.role=t.role),t.children&&t.children.length>0&&(e.children=t.children.map(Qt)),t.description&&(e.description=t.description),e}function ki(t){const e={};return t.id&&(e.id=t.id),t.textref&&(e.textref=t.textref),t.imgref&&(e.imgref=t.imgref),t.audioref&&(e.audioref=t.audioref),t.videoref&&(e.videoref=t.videoref),t.role&&(e.role=t.role),t.description&&(e.description=t.description),typeof t.text=="string"?e.text={plain:t.text,ssml:"",language:""}:t.text&&(e.text={plain:t.text.plain??"",ssml:t.text.ssml??"",language:t.text.language}),t.children&&(e.children=t.children.map(ki)),e}const hc=1;function ar(t){for(let e=t;e;e=e.parentElement){const n=e.getAttribute("xml:lang");if(n)return n;const r=e.getAttribute("lang");if(r)return r}return""}function dc(t){for(let e=t.firstChild;e;e=e.nextSibling)if(e.nodeType===hc)return!0;return!1}function or(t,e){for(let n=e;n;n=n.parentElement)if(n===t)return!0;return!1}function gc(t){const e=t.slice(0,500);return/<\?xml\b/.test(e)||/xmlns:epub=/.test(e)||/DOCTYPE\s+html\s+PUBLIC\s+"-\/\/W3C\/\/DTD XHTML/i.test(e)?"application/xhtml+xml":"text/html"}const fc=3,pc=1,mc=new Set(["object","base","font","tt","i","b","u","big","small","em","strong","dfn","code","samp","kbd","var","cite","abbr","time","acronym","mark","ruby","rt","rp","rtc","a","img","br","wbr","map","q","sub","sup","bdo","iframe","embed","span","input","select","textarea","label","button","optgroup","option","legend","datalist","keygen","output","progress","meter","area","param","source","track","summary","command","basefont","bgsound","menuitem","data","bdi","s","strike","nobr","rb"]),yc=new Set(["summary","dfn","span"]);function lr(t,e){return yc.has(t)&&e.length>0?!0:!mc.has(t)}class gn{xmlParsed;ids=new Map;suppressed=new Set;idAlloc={claimed:new Set,counters:new Map};noterefDepth=0;allowNode=null;root=new Je;current=this.root;segments=[];textAcc="";currentCtx={lang:"",tag:""};flowEndsWithSpace=!0;pendingChildren=[];constructor(e){this.xmlParsed=e}allocateId(e){for(;;){const n=(this.idAlloc.counters.get(e)??0)+1;this.idAlloc.counters.set(e,n);const r=`${e}${n}`;if(!(this.ids.has(r)||this.idAlloc.claimed.has(r)))return this.idAlloc.claimed.add(r),r}}claimId(e){return this.idAlloc.claimed.has(e)?!1:(this.idAlloc.claimed.add(e),!0)}prescan(e){const n=[],r=(i,s)=>{const o=i.getAttribute("id");if(o&&!this.ids.has(o)&&this.ids.set(o,i),s=s||i.getAttribute("aria-hidden")==="true"||i.hasAttribute("hidden"),!s&&i.tagName.toLowerCase()==="a"&&Tt(i).includes("noteref")){const c=i.getAttribute("href")??"";c.startsWith("#")&&n.push({id:c.slice(1),ref:i})}for(let a=i.firstElementChild;a;a=a.nextElementSibling)r(a,s)};r(e,!1);for(const i of n){const s=this.ids.get(i.id);s&&(or(s,i.ref)||this.suppressed.add(s))}}convert(e){this.prescan(e),this.walk(e)}convertChildren(e){this.prescan(e);for(let n=e.firstChild;n;n=n.nextSibling)this.walk(n);this.flushText()}result(){const e=this.root.finalize();return!e.children||e.children.length===0?Jt(e)?[]:[Qt(e)]:e.children.map(Qt)}descend(e){const n=new Je;n.el=e,n.noText=this.current.noText,this.current.children.push(n),this.current=n}appendChild(e){e.noText=this.current.noText,this.current.children.push(e)}walk(e){if(e.nodeType===fc){this.text(e);return}if(e.nodeType!==pc)return;const n=e,r=this.current,i=this.head(n);if(!i)for(let s=n.firstChild;s;s=s.nextSibling)this.walk(s);this.tail(n,i,r)}head(e){const n=e.tagName.toLowerCase();if(lc.has(n)||this.suppressed.has(e)&&e!==this.allowNode)return!0;const[r,i]=sc(e);if(!i&&e!==this.allowNode)return!0;const s=Tt(e);if((n==="img"||n==="svg")&&(s.includes("presentation")||r===null&&e.hasAttribute("alt")&&e.getAttribute("alt").trim()===""))return!0;if(n==="br")return this.current.noText||(this.closeSegment(),this.segments.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(s.includes("pagebreak"))return!this.pagebreak(e,r,s);if(n==="a"&&s.includes("noteref")&&e.getAttribute("href"))return this.noteref(e,s),!0;if(n==="a"&&e.getAttribute("href"))return this.link(e,s),!0;if(n==="img"){const c={role:s},l=e.getAttribute("src");return l&&(c.imgref=l),r&&(c.description=r.plain),this.placeholder(e,"image",c),!0}if(n==="audio"||n==="video"){const c={role:s};let l=e.getAttribute("src");if(!l){const d=e.querySelector(":scope > source[src]");d&&(l=d.getAttribute("src"))}return n==="audio"?l&&(c.audioref=l):l&&(c.videoref=l),r&&(c.description=r.plain),this.placeholder(e,n,c),!0}if(s.includes("image")||s.includes("math")){const c={role:s};return r&&(c.description=r.plain),this.placeholder(e,s.includes("math")?"math":"image",c),!0}if(!lr(n,s))return!1;this.flushText(),this.descend(e);const o=this.current.object;s.length>0&&(o.role=s),r&&(o.description=r.plain,s.includes("figure")&&(this.current.noText=!0));const a=e.getAttribute("id");return a&&(o.id=a),!1}tail(e,n,r){if(n)return;const i=e.tagName.toLowerCase(),s=Tt(e);lr(i,s)&&(this.flushText(),this.current=r)}text(e){if(this.current.noText)return;const n=e.nodeValue??"";if(/^\s*$/.test(n)){(this.textAcc.length>0||this.segments.length>0)&&(this.textAcc+=De(n,this.flowEndsWithSpace),this.updateFlowSpace());return}const r=this.textContext(e);$l(r,this.currentCtx)||(this.closeSegment(),this.currentCtx=r),this.textAcc+=De(n,this.flowEndsWithSpace),this.updateFlowSpace()}textContext(e){const n={lang:ar(e.parentElement),tag:""};for(let r=e.parentElement;r&&r!==this.current.el;r=r.parentElement){const[i,s]=oc(r.tagName.toLowerCase());if(i&&i!=="break"){n.tag=i,n.attrs=s;break}}return n}updateFlowSpace(){this.textAcc.length>0&&(this.flowEndsWithSpace=this.textAcc.endsWith(" "))}closeSegment(){this.textAcc.length!==0&&(this.segments.push({kind:"text",text:this.textAcc,ctx:this.currentCtx}),this.textAcc="")}resetFlow(){this.segments=[],this.textAcc="",this.currentCtx={lang:"",tag:""},this.flowEndsWithSpace=!0,this.pendingChildren=[]}placeholder(e,n,r,i){if(Jt(r))return;const s=new Je;if(s.el=e,s.object=r,this.current.noText){this.appendChild(s);return}this.closeSegment(),this.pendingChildren.push(s),this.segments.push({kind:"placeholder",tag:n,child:s,candidateID:i??e.getAttribute("id")??void 0}),this.flowEndsWithSpace=!1}pagebreak(e,n,r){const i={role:r},s=(e.getAttribute("title")??"").trim();s?i.text={plain:s,ssml:"",language:""}:n&&(i.text={plain:n.plain??"",ssml:n.ssml??"",language:n.language});const o=!!(i.text&&!Ue(i.text)),a=!this.xmlParsed&&(dc(e)||o&&e.firstChild!==null);if(!o&&!a){const l=Xe(e);l&&(i.text={plain:l,ssml:"",language:""})}const c=e.getAttribute("id");return c&&(i.textref=`#${c}`),this.placeholder(e,"pagebreak",i),a}noteref(e,n){const r={role:n},i=Xe(e);i&&(r.text={plain:i,ssml:"",language:""});const s=e.getAttribute("href")??"";let o=e.getAttribute("id")??"";if(!o&&s.startsWith("#")&&(o=s.slice(1)),s.startsWith("#")){const a=s.slice(1),c=this.ids.get(a);if(c&&!or(c,e)&&this.noterefDepth<3){const l=new gn(this.xmlParsed);l.ids=this.ids,l.suppressed=this.suppressed,l.idAlloc=this.idAlloc,l.noterefDepth=this.noterefDepth+1,l.allowNode=c,l.convert(c);const d=l.result();d.length>0&&(r.children=d.map(u=>{const g=ki(u);return delete g.id,g}))}}!r.children&&s&&(r.children=[{textref:s}]),this.placeholder(e,"noteref",r,o||void 0)}link(e,n){const r={};n.length>0&&(r.role=n);const i=Xe(e);i&&(r.text={plain:i,ssml:"",language:""});const s=e.getAttribute("href");s&&(r.textref=s),this.placeholder(e,n[0]??"link",r)}flushText(){this.closeSegment();let e=this.segments;const n=this.pendingChildren;if(this.resetFlow(),e.length===0)return;for(;e.length>0;){const p=e[0];if(p.kind==="break"){e=e.slice(1);continue}if(p.kind==="text"){const m=p.text.replace(/^\s+/,"");if(m===""){e=e.slice(1);continue}e=[{...p,text:m},...e.slice(1)]}break}for(;e.length>0;){const p=e[e.length-1];if(p.kind==="break"){e=e.slice(0,-1);continue}if(p.kind==="text"){const m=p.text.replace(/\s+$/,"");if(m===""){e=e.slice(0,-1);continue}e=[...e.slice(0,-1),{...p,text:m}]}break}if(!e.some(p=>p.kind==="text"&&p.text.trim()!=="")){for(const p of n)this.appendChild(p);return}const i=[];for(const p of e)if(p.kind==="text"&&p.text.trim()!==""){const m=p.ctx.lang;i.includes(m)||i.push(m)}let s=ar(this.current.el??null);i.length===1&&i[0]!==""&&(s=i[0]);let o=!1;for(const p of e)if(p.kind!=="text"||p.ctx.tag!==""||p.ctx.lang!==s){o=!0;break}if(o&&s===""&&(s="en"),o)for(const p of e){if(p.kind!=="placeholder")continue;let m=p.candidateID;(!m||!this.claimId(m))&&(m=this.allocateId(p.tag)),p.child.object.id=m}let a="",c=!1,l=!1,d=!1,u=!1;for(const p of e)if(p.kind==="text"){const m=p.text.startsWith(" "),w=p.text.replace(/^ +| +$/g,"");if(w===""){u=!0;continue}let E=!1;if(a.length>0){const C=c||u||m;l?E=!0:d?E=C&&!ct(w):E=C}E&&(a+=" "),a+=w,c=p.text.endsWith(" "),l=!1,d=!1,u=!1}else p.kind==="break"?l=!0:p.kind==="placeholder"&&(d=!0);const g=e.some(p=>p.kind==="placeholder"),f={plain:o&&!g?"":a.trim(),ssml:"",language:s};if(o){let p="";for(const m of e)if(m.kind==="text"){let w=m.ctx.tag,E=m.ctx.attrs;if(m.ctx.lang!==s&&m.ctx.lang!==""&&(w="lang",E=void 0),w){p+=`<${w}`;for(const[C,P]of Object.entries(E??{}))p+=` ${C}="${At(P)}"`;m.ctx.lang!==s&&m.ctx.lang!==""&&(p+=` xml:lang="${At(m.ctx.lang)}"`),p+=`>${st(m.text)}</${w}>`}else p+=st(m.text)}else m.kind==="break"?p+="<break/>":m.kind==="placeholder"&&(p+=`<readium:${m.tag} id="${At(m.child.object.id)}" />`);f.ssml=p}const y=new Je;y.object={text:f};for(const p of n)y.children.push(p);this.appendChild(y)}}const bc=/<body[\s>]/i;function Ci(t,e){const n=e??gc(t),r=new DOMParser().parseFromString(t,n),i=new gn(n==="application/xhtml+xml"),s=r.querySelector("body");return s&&!bc.test(t)?i.convertChildren(s):i.convert(s??r.documentElement),i.result()}function vc(t,e){return{guided:Ci(t,e)}}exports.BUILTIN_DECORATION_TYPES=Jr;exports.BooleanPreference=ai;exports.DecorationController=ni;exports.DecorationLayout=Gr;exports.DecorationStyleType=A;exports.DecorationWidth=Hr;exports.Decorator=Kr;exports.DirectCommsChannel=Yr;exports.DirectCommsFrame=ei;exports.DirectCommsHost=ti;exports.EnumPreference=Re;exports.Locator=Le;exports.LocatorLocations=V;exports.LocatorText=_e;exports.Preference=Be;exports.RangePreference=Pe;exports.ReadiumSpeechDecorationController=ii;exports.ReadiumSpeechNavigator=tc;exports.ReadiumSpeechProviderRegistry=Ll;exports.SpeechDefaults=si;exports.SpeechPreferences=pe;exports.SpeechPreferencesEditor=Gt;exports.SpeechServerEngine=Nr;exports.SpeechServerEngineProvider=Ko;exports.SpeechServerError=Ie;exports.SpeechSettings=Wt;exports.StringArrayPreference=Ht;exports.WebSpeechEngine=$t;exports.WebSpeechEngineProvider=Io;exports.WebSpeechVoiceManager=k;exports.blockLevelRoles=bi;exports.chineseVariantMap=he;exports.chunkPlainText=Ar;exports.chunkSsmlText=Or;exports.contextualizedAtVerbosity=ui;exports.createLocator=ri;exports.decorationsEqual=Xr;exports.defaultAnnouncements=hi;exports.extractUtterances=Yl;exports.makeGnd=vc;exports.mapServerVoice=sn;exports.mimeTypeForFormat=Tr;exports.parseMarkup=Ci;exports.resolveDecorationForWire=Mt;exports.selectBitrate=Pr;exports.selectFormat=Rr;exports.setupDecorations=Il;exports.skippableAtVerbosity=ci;exports.skippableRoles=Jl;exports.supportsDecorationStyle=Qr;exports.toSpeechServerError=le;
|
|
49
|
+
}`}e.highlightCSS=y,this._rebuildHighlightStylesheet(r)}_getSubKey(e,r){const n=`${e}::${r}`;let i=this._tintSubKeys.get(n);return i||(i=`${this.id}--${this._subKeyCounter++}`,this._tintSubKeys.set(n,i)),i}_rebuildHighlightStylesheet(e){const r=new Set,n=[];for(const i of this.items)i.highlightSubKey&&i.highlightCSS&&!r.has(i.highlightSubKey)&&(r.add(i.highlightSubKey),n.push(i.highlightCSS));e.innerHTML=n.join(`
|
|
50
|
+
`)}layout(e){if(this.experimentalHighlights&&!this.notTextFlag?.has(e.id))return this.experimentalLayout(e);const r=this.wnd.document.createElement("div");r.setAttribute("id",e.id),r.dataset.highlightId=e.decoration.id,r.style.setProperty("pointer-events","none");const n=Te(this.wnd),i=1/this.effectiveZoom(),s=e.decoration.style.expand??0,o=(u,g,f,y=0)=>{const m=e.decoration?.style?.width,p=g;switch(m){case"viewport":{const w=Math.floor(n.inlineStart(p)/n.viewportInlineSize)*n.viewportInlineSize;n.applyPosition(u,w+n.inlineScrollOffset+y,n.blockStart(p)+n.blockScrollOffset,n.viewportInlineSize-2*y,n.blockSize(p),i);break}case"page":{const w=Math.floor(n.inlineStart(p)/n.pageInlineSize)*n.pageInlineSize;n.applyPosition(u,w+n.inlineScrollOffset+y,n.blockStart(p)+n.blockScrollOffset,n.pageInlineSize-2*y,n.blockSize(p),i);break}case"bounds":{n.applyPosition(u,n.inlineStart(f)+n.inlineScrollOffset,n.blockStart(p)+n.blockScrollOffset,n.inlineSize(f),n.blockSize(p),i);break}default:n.applyPosition(u,n.inlineStart(p)+n.inlineScrollOffset,n.blockStart(p)+n.blockScrollOffset,n.inlineSize(p),n.blockSize(p),i)}},a=e.range.getBoundingClientRect(),c=e.decoration.style,l=(()=>{if(c.type!==C.Outline)return 0;const u=c.width;return u==="page"||u==="viewport"?3:0})();let d;if(c.type===C.Template){c.stylesheet&&this.injectCustomStylesheet(c.stylesheet);const u=Wl(this.wnd,c.element);if(!u){e.container=r,e.clickableElements=[];return}u.style.setProperty("pointer-events","none"),d=u}else{const u=c,g=u.type??C.Highlight,f=u.tint??Pt(g);if(g===C.TextColor){e.container=r,e.clickableElements=[];return}if(g===C.Mask){e.container=r,e.clickableElements=[],this.updateSharedMask();return}const y=this.getCurrentDarkMode(),m=this.getBackgroundColor(),p=u.enforceContrast!==!1,w=(()=>{switch(g){case C.Underline:{const x=p?re(f,m):f,R=u.layout==="bounds",[I,q]=n.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[R?`${q}: 0.1em solid ${x} !important`:null,`${I}: 0.1em solid ${x} !important`,"background-color: transparent !important","box-sizing: border-box !important"].filter(Boolean).join("; ")}case C.Strikethrough:{const x=p?re(f,m):f;return u.layout==="bounds"?[`background: repeating-linear-gradient(-45deg, transparent, transparent 19px, ${x} 19px, ${x} 20px) !important`,"background-color: transparent !important","box-sizing: border-box !important"].join("; "):[`background-color: ${x} !important`,"box-sizing: border-box !important"].join("; ")}case C.Outline:return[`outline: 2px solid ${p?re(f,m):f} !important`,"outline-offset: 1px !important","background-color: transparent !important","box-sizing: border-box !important"].join("; ");case C.HighlightUnderline:{const x=p?re(f,m):f,{r:R,g:I,b:q}=Z(x),U=`rgba(${R}, ${I}, ${q}, 0.3)`,Se=u.layout==="bounds",[ke,v]=n.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[`background-color: ${U} !important`,Se?`${v}: 0.1em solid ${x} !important`:null,`${ke}: 0.1em solid ${x} !important`,"box-sizing: border-box !important"].filter(Boolean).join("; ")}case C.Highlight:default:return[`background-color: ${p?re(f,m):f} !important`,`mix-blend-mode: ${y?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important"].join("; ")}})(),E=this.wnd.document.createElement("template");E.innerHTML=`<div data-readium="true" class="readium-${g}" style="${w}"></div>`.trim(),d=E.content.firstElementChild}if(e.decoration?.style?.layout==="bounds"){const u=d.cloneNode(!0);u.style.setProperty("pointer-events","none");const g=s?{left:a.left-s,right:a.right+s,top:a.top-s,bottom:a.bottom+s,width:a.width+s*2,height:a.height+s*2}:a;o(u,g,a,l),r.append(u)}else{const u=c.type,g=u===C.Underline||u===C.Strikethrough,f=u===C.Strikethrough,y=g?Il(e.range,["rt","rp"]):e.range;let m=Ge(y,!0,n.isVertical,g?0:s);m=m.sort((p,w)=>n.isVertical?(n.isVertLR?1:-1)*(p.left-w.left):p.top-w.top);for(let p of m){const w=d.cloneNode(!0);w.style.setProperty("pointer-events","none");let E=p;if(f){const x=n.blockSize(p)*.1,R=n.blockStart(p)+n.blockSize(p)/2-x/2;E=n.isVertical?{left:R,right:R+x,top:p.top,bottom:p.bottom,width:x,height:p.height}:{top:R,bottom:R+x,left:p.left,right:p.right,height:x,width:p.width}}s&&g&&(E=n.isVertical?{...E,top:E.top-s,bottom:E.bottom+s,height:E.height+s*2}:{...E,left:E.left-s,right:E.right+s,width:E.width+s*2}),o(w,E,a,l),r.append(w)}}e.container=r,e.clickableElements=Array.from(r.querySelectorAll("[data-activable='1']")),e.clickableElements.length||(e.clickableElements=Array.from(r.children))}renderLayout(e){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{e=e.filter(r=>!this.experimentalHighlights||!!this.notTextFlag?.has(r.id)),!(!e||e.length===0)&&this.requireContainer().append(...e.map(r=>r.container).filter(r=>!!r))})}requireContainer(e=!1){if(e){let r;return this.wnd.document.getElementById(`${this.id}-style`)?r=this.wnd.document.getElementById(`${this.id}-style`):(r=this.wnd.document.createElement("style"),r.dataset.readium="true",r.id=`${this.id}-style`,this.wnd.document.head.appendChild(r)),r}return this.container||(this.shadowRoot||(this.shadowHost=this.wnd.document.createElement("div"),this.shadowHost.style.cssText="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none",this.wnd.document.body.appendChild(this.shadowHost),this.shadowRoot=this.shadowHost.attachShadow({mode:"open"})),this.container=this.wnd.document.createElement("div"),this.container.setAttribute("id",this.id),this.container.dataset.group=this.name,this.container.dataset.readium="true",this.container.style.setProperty("pointer-events","none"),this.container.style.display="contents",this.shadowRoot.appendChild(this.container)),this.container}getCurrentDarkMode(){return Zr(this.wnd,"--USER__appearance")==="readium-night-on"||ti(this.getBackgroundColor())}getBackgroundColor(){return Zr(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color")}updateSharedMask(){const e=this.items.filter(g=>g.decoration.style?.type===C.Mask);if(e.length===0){this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowRoot&&(this.shadowRoot.innerHTML="");return}const r=Te(this.wnd),n=1/this.effectiveZoom(),i=this.wnd.document.documentElement,s=i.scrollWidth,o=i.scrollHeight,a=[];for(const g of e){const f=g.decoration.style,y=f.layout??"boxes",m=f.width??"wrap",p=f.expand??0,w=g.range.getBoundingClientRect(),E=y==="bounds"?[p?{left:w.left-p,top:w.top-p,right:w.right+p,bottom:w.bottom+p,width:w.width+p*2,height:w.height+p*2}:w]:Ge(g.range,!1,!1,p);for(const x of E){let R;switch(m){case"viewport":{const I=Math.floor(r.inlineStart(x)/r.viewportInlineSize)*r.viewportInlineSize;R=r.toRect(I,r.blockStart(x),r.viewportInlineSize,r.blockSize(x));break}case"page":{const I=Math.floor(r.inlineStart(x)/r.pageInlineSize)*r.pageInlineSize;R=r.toRect(I,r.blockStart(x),r.pageInlineSize,r.blockSize(x));break}case"bounds":{R=r.toRect(r.inlineStart(w),r.blockStart(x),r.inlineSize(w),r.blockSize(x));break}default:R=r.toRect(r.inlineStart(x),r.blockStart(x),r.inlineSize(x),r.blockSize(x))}a.push(R)}}const c=[`M0 0 H${s} V${o} H0 Z`,...a.map(g=>{const f=(g.left+r.xDocOffset)*n,y=(g.top+r.yDocOffset)*n,m=(g.right+r.xDocOffset)*n,p=(g.bottom+r.yDocOffset)*n;return`M${f} ${y} H${m} V${p} H${f} Z`})].join(" "),l="http://www.w3.org/2000/svg";if(!this.maskSvg){this.shadowRoot||(this.shadowHost=this.wnd.document.createElement("div"),this.shadowHost.style.cssText="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none",this.wnd.document.body.appendChild(this.shadowHost),this.shadowRoot=this.shadowHost.attachShadow({mode:"open"})),this.maskSvg=this.wnd.document.createElementNS(l,"svg"),this.maskSvg.style.cssText=`position:absolute;top:0;left:0;width:${s}px;height:${o}px;pointer-events:none;z-index:9999`,this.maskSvg.dataset.readium="true";const g=this.wnd.document.createElementNS(l,"defs"),f=this.wnd.document.createElementNS(l,"clipPath"),y=`${this.id}-mask-clip`;f.setAttribute("id",y),f.setAttribute("clipPathUnits","userSpaceOnUse");const m=this.wnd.document.createElementNS(l,"path");m.setAttribute("clip-rule","evenodd"),f.appendChild(m),g.appendChild(f),this.maskSvg.appendChild(g);const p=this.wnd.document.createElementNS(l,"rect");p.setAttribute("id",`${this.id}-mask-rect`),p.setAttribute("clip-path",`url(#${y})`),p.style.pointerEvents="none",this.maskSvg.appendChild(p),this.shadowRoot.appendChild(this.maskSvg)}this.maskSvg.style.width=`${s}px`,this.maskSvg.style.height=`${o}px`;const d=this.maskSvg.querySelector("path");d&&d.setAttribute("d",c);const u=this.maskSvg.querySelector("rect");if(u){const g=e[0].decoration.style.tint,f=g??this.getBackgroundColor()??Pt(C.Mask),y=g?"1":"0.5";u.setAttribute("x","0"),u.setAttribute("y","0"),u.setAttribute("width",String(s)),u.setAttribute("height",String(o)),u.setAttribute("fill",f),u.setAttribute("fill-opacity",y)}}injectCustomStylesheet(e){const r=`${this.id}-custom-style`;let n=this.wnd.document.getElementById(r);n||(n=this.wnd.document.createElement("style"),n.id=r,n.dataset.readium="true",this.wnd.document.head.appendChild(n)),n.innerHTML=e}clearContainer(){if(this.experimentalHighlights){const e=this.wnd.CSS.highlights;for(const r of this._tintSubKeys.values())e.delete(r);this._tintSubKeys.clear(),this._subKeyCounter=0}this.wnd.document.getElementById(`${this.id}-custom-style`)?.remove(),this.container&&(this.container.remove(),this.container=void 0)}}const oi=class Ie extends ml{constructor(){super(...arguments),this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this)}cleanup(){this.groups.forEach(e=>e.destroy()),this.groups.clear()}updateHighlightStyles(){this.groups.forEach(e=>{e.requestLayout()})}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(e=>{e.experimentalHighlights||e.requestLayout()})},50)}mount(e,r){return this.wnd=e,r.register("decorate",Ie.moduleName,(n,i)=>{const s=n;(s.action==="add"||s.action==="update")&&s.decoration.locator&&(s.decoration.locator=kl.deserialize(s.decoration.locator)),this.groups.has(s.group)||this.groups.set(s.group,new Jl(e,r,`readium-decoration-${this.lastGroupId++}`,s.group));const o=this.groups.get(s.group);switch(s.action){case"add":o?.add(s.decoration);break;case"remove":o?.remove(s.decoration.id);break;case"clear":o?.clear();break;case"update":o?.update(s.decoration);break}i(!0)}),r.register("decoration_activatable",Ie.moduleName,(n,i)=>{const s=n,o=this.groups.get(s.group);o&&(o.activatable=s.activatable),i(!0)}),r.register("decoration_hoverable",Ie.moduleName,(n,i)=>{const s=n,o=this.groups.get(s.group);o&&(o.hoverable=s.hoverable),i(!0)}),this.resizeObserver=new ResizeObserver(()=>e.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(e.document.documentElement),e.addEventListener("orientationchange",this.handleResizer),e.addEventListener("resize",this.handleResizer),this.styleObserver=new MutationObserver(n=>{n.some(i=>i.type==="attributes"&&i.attributeName==="style"&&i.oldValue!==i.target.getAttribute("style"))&&this.updateHighlightStyles()}),this.styleObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"],attributeOldValue:!0}),r.log("Decorator Mounted"),!0}unmount(e,r){return e.removeEventListener("orientationchange",this.handleResizer),e.removeEventListener("resize",this.handleResizer),r.unregisterAll(Ie.moduleName),this.resizeObserver.disconnect(),this.styleObserver.disconnect(),this.cleanup(),r.log("Decorator Unmounted"),!0}};oi.moduleName="decorator";let li=oi;const ci=new Set(Object.values(C));function ui(t,e){return t===C.TextColor?typeof window<"u"&&"Highlight"in window:ci.has(t)?!0:!!e?.[t]}function Zt(t,e){const{style:r}=t;if(r.type===C.Template){const n=r;return{...t,style:{...n,element:cn(n,t)}}}if(r.type&&e?.[r.type]){const n=e[r.type];return{...t,style:{type:C.Template,layout:n.layout,width:n.width,stylesheet:n.stylesheet,element:cn(n,t)}}}return t}function cn(t,e){return typeof t.element=="function"?t.element(e):t.element}function Ql(t,e){if(t.type!==e.type)return!1;if(t.type===C.Template){const i=t,s=e;return i.layout===s.layout&&i.width===s.width&&i.stylesheet===s.stylesheet}const r=t,n=e;return r.tint===n.tint&&r.layout===n.layout&&r.width===n.width&&(r.enforceContrast??!0)===(n.enforceContrast??!0)&&(r.expand??0)===(n.expand??0)}function hi(t,e){return t.locator.href===e.locator.href&&JSON.stringify(t.locator.locations?.serialize?.()??t.locator.locations)===JSON.stringify(e.locator.locations?.serialize?.()??e.locator.locations)&&JSON.stringify(t.locator.text??null)===JSON.stringify(e.locator.text??null)&&Ql(t.style,e.style)&&JSON.stringify(t.extras??null)===JSON.stringify(e.extras??null)}let di=class{constructor(){this.queue=[],this.channel=typeof MessageChannel<"u"?new MessageChannel:void 0,this.channel&&(this.channel.port1.onmessage=()=>this.flush())}push(e){const r=this.queue.length===0;this.queue.push(e),r&&(this.channel?this.channel.port2.postMessage(null):setTimeout(()=>this.flush(),0))}flush(){const e=this.queue;this.queue=[],e.forEach(r=>r())}clear(){this.queue=[]}};class gi{constructor(){this.frame=new fi(this),this.host=new pi(this)}}let fi=class{constructor(e){this.channel=e,this.registrar=new Map,this.outbox=new di,this.ready=!0}register(e,r,n){(Array.isArray(e)?e:[e]).forEach(i=>{const s=this.registrar.get(i)??[];if(s.find(o=>o.module===r))throw new Error(`Duplicate callback for "${i}" in module "${r}"`);s.push({module:r,cb:n}),this.registrar.set(i,s)})}unregister(e,r){(Array.isArray(e)?e:[e]).forEach(n=>{const i=this.registrar.get(n);i&&this.registrar.set(n,i.filter(s=>s.module!==r))})}unregisterAll(e){this.registrar.forEach((r,n)=>{this.registrar.set(n,r.filter(i=>i.module!==e))})}_dispatch(e,r,n){const i=this.registrar.get(e);if(!i?.length){n(!1);return}i.forEach(s=>s.cb(r,n))}send(e,r){this.outbox.push(()=>this.channel.host._receive(e,r))}log(...e){this.outbox.push(()=>this.channel.host._receive("log",e))}destroy(){this.registrar.clear(),this.outbox.clear()}};class pi{constructor(e){this.channel=e,this.listeners=new Map,this.outbox=new di,this.ready=!0}send(e,r,n){this.outbox.push(()=>this.channel.frame._dispatch(e,r,n??(()=>{})))}on(e,r){const n=this.listeners.get(e)??[];n.push(r),this.listeners.set(e,n)}off(e,r){const n=this.listeners.get(e);n&&this.listeners.set(e,n.filter(i=>i!==r))}_receive(e,r){this.listeners.get(e)?.forEach(n=>n(r))}}class mi{constructor(e,r={}){this.host=e,this._decorations=new Map,this._activationState=new Map,this._hoverState=new Map,this._observers=new Map,this._hoveredDecorations=new Map,this._config=r,e.on("decoration_activated",n=>{const i=n,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId);s&&this._observers.get(i.group)?.forEach(o=>o.onDecorationActivated?.({group:i.group,decoration:s,rect:i.rect,point:i.point}))}),e.on("decoration_pointer_enter",n=>{const i=n,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId);s&&(this._hoveredDecorations.set(i.group,s),this._observers.get(i.group)?.forEach(o=>o.onDecorationPointerEnter?.({group:i.group,decoration:s,rect:i.rect,point:i.point})))}),e.on("decoration_pointer_leave",n=>{const i=n,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId)??this._hoveredDecorations.get(i.group);this._hoveredDecorations.delete(i.group),s&&this._observers.get(i.group)?.forEach(o=>o.onDecorationPointerLeave?.({group:i.group,decoration:s,rect:i.rect,point:i.point}))})}supportsDecorationStyle(e){return ui(e,this._config.decorationTemplates)}applyDecorations(e,r){const n=this._decorations.get(r)??[],i=new Map(n.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id,c]));for(const[c,l]of i){const d=s.get(c);d?hi(l,d)||this.host.send("decorate",{group:r,action:"update",decoration:Zt(d,this._config.decorationTemplates)}):this.host.send("decorate",{group:r,action:"remove",decoration:{id:c}})}for(const[c,l]of s)i.has(c)||this.host.send("decorate",{group:r,action:"add",decoration:Zt(l,this._config.decorationTemplates)});this._decorations.set(r,e);const o=this._activationState.get(r);o!==void 0&&this.host.send("decoration_activatable",{group:r,activatable:o});const a=this._hoverState.get(r);a!==void 0&&this.host.send("decoration_hoverable",{group:r,hoverable:a})}registerDecorationObserver(e,r){this._observers.has(e)||this._observers.set(e,new Set),this._observers.get(e).add(r),r.onDecorationActivated&&(this._activationState.set(e,!0),this.host.send("decoration_activatable",{group:e,activatable:!0})),(r.onDecorationPointerEnter||r.onDecorationPointerLeave)&&(this._hoverState.set(e,!0),this.host.send("decoration_hoverable",{group:e,hoverable:!0}))}unregisterDecorationObserver(e){this._observers.forEach((r,n)=>{if(!r.has(e))return;r.delete(e);const i=[...r].some(o=>o.onDecorationActivated);this._activationState.has(n)&&!i&&(this._activationState.delete(n),this.host.send("decoration_activatable",{group:n,activatable:!1}));const s=[...r].some(o=>o.onDecorationPointerEnter||o.onDecorationPointerLeave);this._hoverState.has(n)&&!s&&(this._hoverState.delete(n),this.host.send("decoration_hoverable",{group:n,hoverable:!1}))})}destroy(){this._decorations.clear(),this._activationState.clear(),this._hoverState.clear(),this._observers.clear(),this._hoveredDecorations.clear()}}function Xl(t){return t&&Array.isArray(t)?t:void 0}function Zl(t){return t&&typeof t=="string"?[t]:Xl(t)}function It(t){return isNaN(t)?void 0:t}class j{constructor(e){this.fragments=e.fragments?e.fragments:new Array,this.progression=e.progression,this.totalProgression=e.totalProgression,this.position=e.position,this.otherLocations=e.otherLocations}static deserialize(e){if(!e)return;const r=It(e.progression),n=It(e.totalProgression),i=It(e.position),s=new Map,o=new Set(["fragment","fragments","progression","totalProgression","position","otherLocations"]);return Object.entries(e).forEach(([a,c])=>{o.has(a)||s.set(a,c)}),e.otherLocations instanceof Map&&e.otherLocations.forEach((a,c)=>s.set(c,a)),new j({fragments:Zl(e.fragments||e.fragment),progression:r!==void 0&&r>=0&&r<=1?r:void 0,totalProgression:n!==void 0&&n>=0&&n<=1?n:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:s.size===0?void 0:s})}serialize(){const e={};return this.fragments&&(e.fragments=this.fragments),this.progression!==void 0&&(e.progression=this.progression),this.totalProgression!==void 0&&(e.totalProgression=this.totalProgression),this.position!==void 0&&(e.position=this.position),this.otherLocations&&this.otherLocations.forEach((r,n)=>e[n]=r),e}}class Be{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new Be({after:e.after,before:e.before,highlight:e.highlight})}serialize(){const e={};return this.after!==void 0&&(e.after=this.after),this.before!==void 0&&(e.before=this.before),this.highlight!==void 0&&(e.highlight=this.highlight),e}}class _e{constructor(e){const r=e.href.indexOf("#"),n=r>=0?e.href.slice(r+1):void 0;this.href=r>=0?e.href.slice(0,r):e.href,this.type=e.type,this.title=e.title;const i=e.locations?.fragments,s=n&&(!i||i.length===0);this.locations=e.locations?s?new j({...e.locations,fragments:[n]}):e.locations:n?new j({fragments:[n]}):new j({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new _e({href:e.href,type:e.type,title:e.title,locations:j.deserialize(e.locations),text:Be.deserialize(e.text)})}serialize(){const e={href:this.href,type:this.type};return this.title!==void 0&&(e.title=this.title),this.locations&&(e.locations=this.locations.serialize()),this.text&&(e.text=this.text.serialize()),e}copyWithLocations(e){return new _e({href:this.href,type:this.type,title:this.title,text:this.text,locations:new j({...this.locations,...e})})}}function yi(t,e=window){const{highlight:r,before:n,after:i,selector:s,fragment:o}=t,c=r!==void 0||n!==void 0||i!==void 0?new Be({highlight:r,before:n,after:i}):void 0,l=s?new Map([["cssSelector",s]]):void 0,u=l!==void 0||o!==void 0?new j({fragments:o?[o]:void 0,otherLocations:l}):void 0;return new _e({href:e.location.href,type:"text/html",text:c,locations:u})}class vi extends mi{constructor(e,r,n,i={}){super(e.host,i),this.channel=e,this.wnd=r,this.decorator=n}decorate(e,r){this.applyDecorations(e.map(({id:n,style:i,...s})=>({id:n,style:i,locator:yi(s,this.wnd)})),r)}destroy(){super.destroy(),this.decorator.unmount(this.wnd,this.channel.frame),this.channel.frame.destroy()}}function Yl(t=window,e={}){const r=new gi,n=new li;return n.mount(t,r.frame),new vi(r,t,n,e)}class ec{providers=new Map;register(e){if(this.providers.has(e.id))throw new Error(`A provider is already registered under id "${e.id}"`);this.providers.set(e.id,e)}unregister(e){this.providers.delete(e)}get(e){return this.providers.get(e)}list(){return[...this.providers.values()]}async getVoices(e){return this.require(e).getVoices()}async getAllVoices(){return Promise.all(this.list().map(async e=>({providerId:e.id,voices:await e.getVoices()})))}async createEngine(e,r){return this.require(e).createEngine(r)}async destroy(){await Promise.all(this.list().map(e=>e.destroy())),this.providers.clear()}require(e){const r=this.providers.get(e);if(!r)throw new Error(`No provider registered under id "${e}"`);return r}}const nt={range:[0,5e3],step:100},it={range:[.1,10],step:.1},st={range:[0,2],step:.1},at={range:[0,1],step:.05},mr=["none","few","some","most","custom"],yr=["none","block-level","always"],vr=["plain","ssml"],br=["none","utterance","block"],un=["format","inlineContextualization","verbosity","skip","contextualize","language"];function wr(t){return t==null||typeof t=="boolean"?t:void 0}function M(t,e){return t==null||e.includes(t)?t:void 0}function F(t,e){if(t==null)return t;if(typeof t!="number"||Number.isNaN(t))return;const r=Math.min(...e),n=Math.max(...e);return t>=r&&t<=n?t:void 0}function De(t){return t==null||Array.isArray(t)&&t.every(e=>typeof e=="string")?t:void 0}class bi{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=M(e.format,vr)??"plain",this.inlineContextualization=wr(e.inlineContextualization)??!1,this.verbosity=M(e.verbosity,mr)??"few",this.skip=De(e.skip)??[],this.contextualize=De(e.contextualize)??[],this.language=M(e.language,yr)??"block-level",this.pauseDuration=F(e.pauseDuration,nt.range)??300,this.autoPause=M(e.autoPause,br)??"none",this.rate=F(e.rate,it.range)??1,this.pitch=F(e.pitch,st.range)??1,this.volume=F(e.volume,at.range)??1}}class ve{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=M(e.format,vr),this.inlineContextualization=wr(e.inlineContextualization),this.verbosity=M(e.verbosity,mr),this.skip=De(e.skip),this.contextualize=De(e.contextualize),this.language=M(e.language,yr),this.pauseDuration=F(e.pauseDuration,nt.range),this.autoPause=M(e.autoPause,br),this.rate=F(e.rate,it.range),this.pitch=F(e.pitch,st.range),this.volume=F(e.volume,at.range)}merging(e){const r={...this};for(const n of Object.keys(e))e[n]!==void 0&&(r[n]=e[n]);return new ve(r)}}class Ve{_value;_effectiveValue;_isEffective;_onChange;constructor({initialValue:e=null,effectiveValue:r,isEffective:n,onChange:i}){this._value=e,this._effectiveValue=r,this._isEffective=n,this._onChange=i}set value(e){this._value=e,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null,this._onChange(this._value)}}class Ne extends Ve{_supportedValues;constructor({initialValue:e=null,effectiveValue:r,isEffective:n,onChange:i,supportedValues:s}){super({initialValue:e,effectiveValue:r,isEffective:n,onChange:i}),this._supportedValues=s}set value(e){if(e!=null&&M(e,this._supportedValues)===void 0)throw new Error(`Value '${String(e)}' is not in the supported values for this preference.`);this._value=e,this._onChange(this._value)}get value(){return this._value}get supportedValues(){return this._supportedValues}}class wi extends Ve{set value(e){if(e!=null&&wr(e)===void 0)throw new Error(`Value '${String(e)}' is not a boolean.`);this._value=e,this._onChange(this._value)}get value(){return this._value}}class Yt extends Ve{set value(e){if(e!=null&&De(e)===void 0)throw new Error(`Value '${String(e)}' is not an array of strings.`);this._value=e,this._onChange(this._value)}get value(){return this._value}}class Le extends Ve{_supportedRange;_step;_decimals;constructor({initialValue:e=null,effectiveValue:r,isEffective:n,onChange:i,supportedRange:s,step:o}){super({initialValue:e,effectiveValue:r,isEffective:n,onChange:i}),this._supportedRange=s,this._step=o,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(e){if(e!=null&&F(e,this._supportedRange)===void 0)throw new Error(`Value '${String(e)}' is out of the supported range for this preference.`);this._value=e,this._onChange(this._value)}get value(){return this._value}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value!=null&&this._value<this._supportedRange[1]&&(this._value=Math.min(Math.round((this._value+this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[1]),this._onChange(this._value))}decrement(){this._value!=null&&this._value>this._supportedRange[0]&&(this._value=Math.max(Math.round((this._value-this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[0]),this._onChange(this._value))}format(e){return e.toString()}}class er{preferences;settings;constructor(e,r){this.preferences=new ve({...e}),this.settings=r}clear(){this.preferences=new ve({format:null,inlineContextualization:null,verbosity:null,skip:null,contextualize:null,language:null,pauseDuration:null,autoPause:null,rate:null,pitch:null,volume:null})}updatePreference(e,r){this.preferences[e]=r}get format(){return new Ne({initialValue:this.preferences.format,effectiveValue:this.settings.format,isEffective:this.preferences.format!=null,onChange:e=>this.updatePreference("format",e??null),supportedValues:vr})}get inlineContextualization(){return new wi({initialValue:this.preferences.inlineContextualization,effectiveValue:this.settings.inlineContextualization,isEffective:this.preferences.inlineContextualization!=null,onChange:e=>this.updatePreference("inlineContextualization",e??null)})}get verbosity(){return new Ne({initialValue:this.preferences.verbosity,effectiveValue:this.settings.verbosity,isEffective:this.preferences.verbosity!=null,onChange:e=>this.updatePreference("verbosity",e??null),supportedValues:mr})}get skip(){return new Yt({initialValue:this.preferences.skip,effectiveValue:this.settings.skip,isEffective:this.preferences.skip!=null,onChange:e=>this.updatePreference("skip",e??null)})}get contextualize(){return new Yt({initialValue:this.preferences.contextualize,effectiveValue:this.settings.contextualize,isEffective:this.preferences.contextualize!=null,onChange:e=>this.updatePreference("contextualize",e??null)})}get language(){return new Ne({initialValue:this.preferences.language,effectiveValue:this.settings.language,isEffective:this.preferences.language!=null,onChange:e=>this.updatePreference("language",e??null),supportedValues:yr})}get pauseDuration(){return new Le({initialValue:this.preferences.pauseDuration,effectiveValue:this.settings.pauseDuration,isEffective:this.preferences.pauseDuration!=null,onChange:e=>this.updatePreference("pauseDuration",e??null),supportedRange:nt.range,step:nt.step})}get autoPause(){return new Ne({initialValue:this.preferences.autoPause,effectiveValue:this.settings.autoPause,isEffective:this.preferences.autoPause!=null,onChange:e=>this.updatePreference("autoPause",e??null),supportedValues:br})}get rate(){return new Le({initialValue:this.preferences.rate,effectiveValue:this.settings.rate,isEffective:this.preferences.rate!=null,onChange:e=>this.updatePreference("rate",e??null),supportedRange:it.range,step:it.step})}get pitch(){return new Le({initialValue:this.preferences.pitch,effectiveValue:this.settings.pitch,isEffective:this.preferences.pitch!=null,onChange:e=>this.updatePreference("pitch",e??null),supportedRange:st.range,step:st.step})}get volume(){return new Le({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!=null,onChange:e=>this.updatePreference("volume",e??null),supportedRange:at.range,step:at.step})}}const Si=["audio","figure","image","math","table","video"],ki=[...Si,"blockquote","cell","chapter","columnheader","cover","details","notice","part","preformatted","qna","row","rowheader","subtitle","tip"],tc=[...ki,"abstract","acknowledgments","afterword","appendix","aside","bibliography","caption","colophon","complementary","conclusion","credit","credits","dedication","definition","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","heading1","heading2","heading3","heading4","heading5","heading6","index","introduction","list","listItem","pagebreak","pagelist","preface","prologue","pullquote","separator","summary","term"],xi={none:new Set(["aside","bibliography","endnotes","footnote","noteref","pullquote","pagebreak","details","columnheader","rowheader","row","cell","audio","image","figure","video","table","landmarks","loa","loi","lot","lov","toc"]),few:new Set(["aside","bibliography","endnotes","footnote","noteref","pullquote","pagebreak","details","columnheader","rowheader","row","cell","landmarks","loa","loi","lot","lov","toc"]),some:new Set(["aside","bibliography","endnotes","footnote","noteref","pullquote","pagebreak","landmarks","loa","loi","lot","lov","toc"]),most:new Set(["landmarks","loa","loi","lot","lov","toc"])},Ei={none:new Set,few:new Set(Si),some:new Set(ki),most:new Set(tc)};class tr{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e,r){this.format=e.format??r.format,this.inlineContextualization=e.inlineContextualization??r.inlineContextualization,this.verbosity=e.verbosity??r.verbosity,this.verbosity==="custom"?(this.skip=e.skip??r.skip,this.contextualize=e.contextualize??r.contextualize):(this.skip=[...xi[this.verbosity]],this.contextualize=[...Ei[this.verbosity]]),this.language=e.language??r.language,this.pauseDuration=e.pauseDuration??r.pauseDuration,this.autoPause=e.autoPause??r.autoPause,this.rate=e.rate??r.rate,this.pitch=e.pitch??r.pitch,this.volume=e.volume??r.volume}}function ze(t){return t.plain===""&&t.ssml===""&&t.language===""}function rc(t){if(!t||ze(t))return;if(t.ssml===""&&t.language==="")return t.plain;const e={language:t.language};return t.plain!==""&&(e.plain=t.plain),t.ssml!==""&&(e.ssml=t.ssml),e}function nc(t,e){if(t.lang!==e.lang||t.tag!==e.tag)return!1;const r=Object.entries(t.attrs??{}),n=Object.entries(e.attrs??{});return r.length!==n.length?!1:r.every(([i,s])=>e.attrs?.[i]===s)}const ot=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Nt=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),ic=/[\u00A0\u2007\u202F]/;function sc(t){return ic.test(t)}function $e(t,e){let r="",n=!1,i=!1;for(const s of t)if(sc(s))r+=s,n=!1,i=!0;else if(/\s/.test(s)){if(e&&!i||n)continue;r+=" ",n=!0}else s!==""&&s!==""&&(r+=s,n=!1,i=!0);return r}const Ci={footnote:{start:"Start of the footnote.",end:"End of the footnote."},part:{start:"Start of the part.",end:"End of the part."},chapter:{start:"Start of the chapter.",end:"End of the chapter."},prologue:{start:"Start of the prologue.",end:"End of the prologue."},preface:{start:"Start of the preface.",end:"End of the preface."},introduction:{start:"Start of the introduction.",end:"End of the introduction."},conclusion:{start:"Start of the conclusion.",end:"End of the conclusion."},epilogue:{start:"Start of the epilogue.",end:"End of the epilogue."},afterword:{start:"Start of the afterword.",end:"End of the afterword."},appendix:{start:"Start of the appendix.",end:"End of the appendix."},acknowledgments:{start:"Start of the acknowledgments.",end:"End of the acknowledgments."},endnotes:{start:"Start of the endnotes.",end:"End of the endnotes."},glossary:{start:"Start of the glossary.",end:"End of the glossary."},bibliography:{start:"Start of the bibliography.",end:"End of the bibliography."},index:{start:"Start of the index.",end:"End of the index."},toc:{start:"Start of the table of contents.",end:"End of the table of contents."},pagelist:{start:"Start of the page list.",end:"End of the page list."},landmarks:{start:"Start of the landmarks.",end:"End of the landmarks."},loa:{start:"Start of the list of audio clips.",end:"End of the list of audio clips."},loi:{start:"Start of the list of illustrations.",end:"End of the list of illustrations."},lot:{start:"Start of the list of tables.",end:"End of the list of tables."},lov:{start:"Start of the list of video clips.",end:"End of the list of video clips."},qna:{start:"Start of the questions and answers.",end:"End of the questions and answers."},table:{start:"Start of the table.",end:"End of the table."},figure:{start:"Start of the figure.",end:"End of the figure."},aside:{start:"Start of the aside.",end:"End of the aside."},details:{start:"Start of the details.",end:"End of the details."},credits:{start:"Start of the credits.",end:"End of the credits."},blockquote:{start:"Start of the quote.",end:"End of the quote."},list:{start:"Start of the list.",end:"End of the list."},preformatted:{start:"Start of the preformatted text.",end:"End of the preformatted text."},row:{start:"Start of the row.",end:"End of the row."},complementary:{start:"Start of the complementary content.",end:"End of the complementary content."},pagebreak:"Pagebreak.",heading1:"Heading level 1.",heading2:"Heading level 2.",heading3:"Heading level 3.",heading4:"Heading level 4.",heading5:"Heading level 5.",heading6:"Heading level 6.",subtitle:"Subtitle.",epigraph:"Epigraph.",abstract:"Abstract.",colophon:"Colophon.",dedication:"Dedication.",cover:"Cover.",errata:"Errata.",notice:"Notice.",example:"Example.",tip:"Tip.",pullquote:"Pull quote.",credit:"Credit.",image:"Image.",audio:"Audio.",video:"Video.",caption:"Caption.",listItem:"List item.",cell:"Cell.",columnheader:"Column header.",rowheader:"Row header.",term:"Term.",summary:"Summary.",separator:"Separator."},ac=/<lang xml:lang="[^"]*">([\s\S]*?)<\/lang>/g;function Ai(t){return t.replace(ac,"$1")}const oc=/\s*<readium:[a-zA-Z][\w-]*\s+id="[^"]*"\s*\/>\s*/g;function lc(t){return t.replace(oc,(r,n,i)=>{const s=i.slice(n+r.length);return s.length===0||pt(s)?"":" "}).replace(/ {2,}/g," ").trim()}function cc(t){return t.includes("<")}function Ti(t){if(t===void 0)return;if(typeof t=="string")return{plain:t};const e={language:t.language};if(t.ssml){const r=lc(t.ssml);cc(r)&&(e.ssml=r)}return t.plain&&(e.plain=t.plain),e.plain||e.ssml?e:void 0}function Sr(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ").trim()}const Oi=/<lang xml:lang="([^"]*)">([\s\S]*?)<\/lang>/g;function Ri(t){return new RegExp(Oi).test(t)}function hn(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ")}const uc=new RegExp(`\\s+|[${Ht}]+|[${le}]+|[^\\s${Ht}${le}]+`,"gu");function Lt(t){const e=[];for(const[r]of t.matchAll(uc))/^\s/.test(r)?e.push({kind:"space"}):Yo(r)?e.push({kind:"open",text:r}):pt(r)?e.push({kind:"close",text:r}):e.push({kind:"word",text:r});return e}function hc(t){let e="",r=!1;for(const n of t){if(n.kind==="space"){e&&(r=!0);continue}r&&(e+=" "),e+=n.text,r=!1}return e}function dc(t){let e=t.length;for(;e>0&&(t[e-1].kind==="space"||t[e-1].kind==="open");)e--;return t.slice(e).some(r=>r.kind==="open")?t.splice(e):[]}function gc(t){let e=0;for(;e<t.length&&(t[e].kind==="space"||t[e].kind==="close");)e++;return t.slice(0,e).some(r=>r.kind==="close")?t.splice(0,e):[]}function Pi(t,e){const r=[];let n=0;for(const s of t.matchAll(Oi))r.push({tokens:Lt(hn(t.slice(n,s.index))),language:e,tagged:!1}),r.push({tokens:Lt(Sr(s[2])),language:s[1],tagged:!0}),n=s.index+s[0].length;r.push({tokens:Lt(hn(t.slice(n))),language:e,tagged:!1});for(let s=0;s<r.length-1;s++)!r[s].tagged&&r[s+1].tagged?r[s+1].tokens.unshift(...dc(r[s].tokens)):r[s].tagged&&!r[s+1].tagged&&r[s].tokens.push(...gc(r[s+1].tokens));const i=[];for(const s of r){const o=hc(s.tokens);o&&i.push({plain:o,language:s.language})}return i}const Ii=/<readium:[a-zA-Z][\w-]*\s+id="([^"]*)"\s*\/>/g;function fc(t){return new RegExp(Ii).test(t)}function pc(t){const e=[];let r=0;for(const i of t.matchAll(Ii)){const s=t.slice(r,i.index).trim();s&&e.push({ssml:s}),e.push({placeholderId:i[1]}),r=i.index+i[0].length}const n=t.slice(r).trim();return n&&e.push({ssml:n}),e}function lt(t){return typeof t=="object"}const mc=["aside","bibliography","details","endnotes","footnote","noteref","pullquote","landmarks","loa","loi","lot","lov","pagebreak","toc"],Ni=["heading1","heading2","heading3","heading4","heading5","heading6","paragraph","blockquote","preformatted","pullquote","list","listItem","table","row","cell","columnheader","rowheader","audio","video","figure","image","math","abstract","acknowledgments","afterword","appendix","article","aside","bibliography","chapter","colophon","conclusion","dedication","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","index","introduction","notice","part","preface","prologue","qna","section","summary","tip"],yc=new Set(Ni);function Ue(t,e){return typeof t=="function"?t(e):t}function ue(t,e){return e==="ssml"?{ssml:ot(t)}:{plain:t}}function he(t,e,r,n){t.push(...n);for(let i=0;i<n.length;i++)e.push(r)}function Li(t,e,r,n,i,s,o){o?(i.some(a=>r.blockStarts.has(a))&&r.blockStarts.add(o),he(t,e,s[0]??n,[o])):(t.push(...i),e.push(...s))}function dn(t,e,r,n,i,s,o){if(!n.contextualize.has(i))return;const a=n.announcements[i];if(a!==void 0){if(lt(a)){const c=s==="before"?a.start:a.end;he(t,e,r,[ue(Ue(c,o),n.format)]);return}s==="before"&&he(t,e,r,[ue(Ue(a,o),n.format)])}}function gn(t,e){return e.size>0&&t.some(r=>e.has(r))}function kr(t,e){let r,n=!1;const i=[];for(const a of t){const c=e==="ssml"?a.ssml:a.plain;if(c&&(i.push(c),a.language!==void 0)){if(n&&a.language!==r)return;r=a.language,n=!0}}if(i.length===0)return;let s="";for(const a of i)a.length===1&&s.endsWith(a)||(s&&!pt(a)&&(s+=" "),s+=a);const o=e==="ssml"?{ssml:s}:{plain:s};return r&&(o.language=r),o}function vc(t,e){const r=Ti(t.text),n=r?qi(r,e.format,e.language):[];if(!e.contextualize.has("pagebreak"))return n;const i=e.announcements.pagebreak;if(i===void 0)return n;const s=ue(Ue(lt(i)?i.start:i),e.format);if(n.length===0)return[s];const o=kr([s,...n],e.format);return o?(o.plain!==void 0&&(o.plain+="."),o.ssml!==void 0&&(o.ssml+="."),[o]):[s,...n]}function qi(t,e,r){if(e==="plain"&&r!=="block-level"&&r!=="none"&&t.ssml&&Ri(t.ssml))return Pi(t.ssml,t.language).map(i=>{const s={plain:i.plain};return i.language&&(s.language=i.language),s});const n={};return t.language&&(n.language=t.language),e==="ssml"?n.ssml=t.ssml??ot(t.plain??""):n.plain=t.plain??Sr(t.ssml??""),(r==="block-level"||r==="none")&&(n.ssml&&(n.ssml=Ai(n.ssml)),r==="none"&&delete n.language),[n]}function bc(t,e,r,n,i,s){const o=typeof t.text=="object"?t.text.language:void 0,a=new Map((t.children??[]).map(u=>[u.id,u])),c=[],l=[];for(const u of pc(e)){if(u.placeholderId!==void 0){const f=a.get(u.placeholderId);f&&_i(f,c,l,i,s);continue}if(!u.ssml)continue;if(i.format==="plain"&&i.language!=="block-level"&&i.language!=="none"&&Ri(u.ssml)){for(const f of Pi(u.ssml,o)){const y={plain:f.plain};f.language&&(y.language=f.language),c.push(y),l.push(t)}continue}const g={};o&&(g.language=o),i.format==="ssml"?g.ssml=u.ssml:g.plain=Sr(u.ssml),(i.language==="block-level"||i.language==="none")&&(g.ssml&&(g.ssml=Ai(g.ssml)),i.language==="none"&&delete g.language),c.push(g),l.push(t)}const d=c.length>1?kr(c,i.format):void 0;Li(r,n,i,t,c,l,d)}function _i(t,e,r,n,i){const s=t.role??[];if(gn(s,n.skip))return;const o=s.some(u=>yc.has(u)),a=o&&!i,c=e.length,l=s.includes("footnote"),d=s.filter(u=>!(l&&(u==="footnote"||u==="aside"))&&u!=="pagebreak");for(const u of d)dn(e,r,t,n,u,"before");if(s.includes("noteref"))for(const u of t.children??[]){const g=u.role??[];if(!gn(g,n.skip))if(g.includes("footnote")){const f=[],y=[];oe([u],f,y,n,i);const m=n.contextualize.has("footnote")?n.announcements.footnote:void 0,p=[],w=[];if(m!==void 0){const x=lt(m)?m.start:m;p.push(ue(Ue(x),n.format)),w.push(u)}p.push(...f),w.push(...y),m!==void 0&<(m)&&(p.push(ue(Ue(m.end),n.format)),w.push(u));const E=m!==void 0&&p.length>1?kr(p,n.format):void 0;Li(e,r,n,u,p,w,E)}else oe([u],e,r,n,i)}else{const u=typeof t.text=="object"?t.text.ssml:void 0;if(n.inlineContextualization&&u&&fc(u))bc(t,u,e,r,n,i);else if(s.includes("pagebreak")){if(he(e,r,t,vc(t,n)),t.children){const g=i||o&&e.length>c;oe(t.children,e,r,n,g)}}else{const g=Ti(t.text);if(g&&he(e,r,t,qi(g,n.format,n.language)),t.children){const f=i||o&&e.length>c;oe(t.children,e,r,n,f)}}}a&&e.length>c&&n.blockStarts.add(e[c]),t.description!==void 0&&he(e,r,t,[ue(t.description,n.format)]);for(const u of d)dn(e,r,t,n,u,"after")}function oe(t,e,r,n,i){t.forEach((s,o)=>_i(s,e,r,n,o===0?i:!1))}function Di(t){return{announcements:{...Ci,...t.announcements},skip:new Set(t.skip??[]),contextualize:new Set(t.contextualize??[]),format:t.format??"plain",inlineContextualization:t.inlineContextualization??!1,language:t.language,blockStarts:new Set}}function wc(t,e){const r=[];return oe(t,r,[],Di(e),!1),r}function Sc(t,e){const r=[],n=[],i=Di(e);oe(t,r,n,i,!1);const s=r.map(o=>i.blockStarts.has(o));return{utterances:r,sources:n,blockStarts:s}}class kc{engine;contentQueue=[];events=new dt;navigatorState="idle";pendingAdvanceTimeout=null;_defaults;_preferences;_settings;_preferencesEditor=null;source;contentSources=[];contentBlockStarts=[];pendingResumeIndex=null;pendingResumeState=null;pendingAutoPauseIndex=null;constructor(e,r={}){this.engine=e,this._defaults=new bi(r.defaults),this._preferences=new ve(r.preferences),this._settings=new tr(this._preferences,this._defaults),this.setupEngineListeners(),this.applyEngineParameters(),this.initializeEngine()}applyEngineParameters(){this.engine.setRate(this._settings.rate),this.engine.setPitch(this._settings.pitch),this.engine.setVolume(this._settings.volume)}async initializeEngine(){try{await this.engine.initialize?.()}catch(e){console.warn("Failed to initialize speech engine:",e)}}setupEngineListeners(){this.engine.on("start",()=>{this.setNavigatorState("playing"),this.emitEvent({type:"start"})}),this.engine.on("end",()=>{const e=this.engine.getCurrentUtteranceIndex(),r=this.engine.getUtteranceCount();if(e<r-1){const n=this._settings.autoPause==="utterance"||this.contentBlockStarts[e+1]===!0;this._settings.autoPause!=="none"&&n?(this.pendingAutoPauseIndex=e+1,this.setNavigatorState("paused"),this.emitEvent({type:"pause"})):this.pendingAdvanceTimeout=setTimeout(()=>{this.pendingAdvanceTimeout=null,this.engine.speak(e+1)},this._settings.pauseDuration)}else this.engine.setCurrentUtteranceIndex(0),this.setNavigatorState("idle");this.emitEvent({type:"end"})}),this.engine.on("pause",()=>{this.setNavigatorState("paused"),this.emitEvent({type:"pause"})}),this.engine.on("resume",()=>{this.setNavigatorState("playing"),this.emitEvent({type:"resume"})}),this.engine.on("stop",()=>{this.setNavigatorState("idle"),this.emitEvent({type:"stop"})}),this.engine.on("error",e=>{this.setNavigatorState("idle"),this.emitEvent(e)}),this.engine.on("ready",()=>{if(this.contentQueue.length===0)return;const e=this.pendingResumeIndex,r=this.pendingResumeState;if(this.pendingResumeIndex=null,this.pendingResumeState=null,this.navigatorState==="loading"){if(r==="playing"){this.setNavigatorState("playing"),this.engine.speak(e??0);return}if(r==="paused"){const n=e??0;n>0?this.engine.setCurrentUtteranceIndex(n,()=>this.setNavigatorState("paused")):this.setNavigatorState("paused");return}this.setNavigatorState("ready"),this.emitEvent({type:"ready"})}}),this.engine.on("boundary",e=>{this.emitEvent(e)}),this.engine.on("mark",e=>{this.emitEvent(e)}),this.engine.on("voiceschanged",()=>{this.emitEvent({type:"voiceschanged"})}),this.engine.on("languagefallback",e=>{this.emitEvent(e)}),this.engine.on("enginefallback",e=>{this.emitEvent(e)}),this.engine.on("enginerecovered",e=>{this.emitEvent(e)})}setNavigatorState(e){this.navigatorState=e}async getVoices(){return this.engine.getAvailableVoices()}setVoice(e){this.engine.setVoice(e)}getCurrentVoice(){return this.engine.getCurrentVoice()}setSpeakInContentLanguage(e){this.engine.setSpeakInContentLanguage(e)}getSpeakInContentLanguage(){return this.engine.getSpeakInContentLanguage()}loadContent(e){if(this.source)throw new Error("loadContent() cannot be used after loadGndContent() — the two are exclusive. Create a new navigator instance to switch content sources.");this.setContentQueue(e)}loadGndContent(e){this.source=e,this.reextract()}setContentQueue(e,r=null,n=null){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,(this.navigatorState==="playing"||this.navigatorState==="paused")&&this.engine.stop();const i=Array.isArray(e)?e:[e];this.contentQueue=[...i],this.pendingResumeIndex=r,this.pendingResumeState=n,this.setNavigatorState("loading"),this.emitEvent({type:"loading"}),this.engine.loadUtterances(i,r??void 0),this.emitContentChangeEvent({content:i})}reextract(){if(!this.source)return;const e=this.navigatorState==="playing"||this.navigatorState==="paused"?this.navigatorState:null,r=this.contentSources,n=this.getCurrentUtteranceIndex(),{utterances:i,sources:s,blockStarts:o}=Sc(this.source,{format:this._settings.format,inlineContextualization:this._settings.inlineContextualization,skip:this._settings.skip,contextualize:this._settings.contextualize,language:this._settings.language});this.contentSources=s,this.contentBlockStarts=o;const a=e?this.resolveResumeIndex(r,n,s):null;this.setContentQueue(i,a,e)}resolveResumeIndex(e,r,n){for(let i=Math.min(r,e.length-1);i>=0;i--){const s=e[i];if(s===void 0)continue;const o=n.indexOf(s);if(o!==-1)return o}return null}getCurrentContent(){const e=this.getCurrentUtteranceIndex();return e<this.contentQueue.length?this.contentQueue[e]:null}getContentQueue(){return[...this.contentQueue]}getCurrentUtteranceIndex(){return this.engine.getCurrentUtteranceIndex()}play(){if(this.navigatorState==="paused")if(this.setNavigatorState("playing"),this.pendingAutoPauseIndex!==null){const e=this.pendingAutoPauseIndex;this.pendingAutoPauseIndex=null,this.engine.speak(e)}else this.engine.resume();else if(this.navigatorState==="ready"||this.navigatorState==="idle")this.setNavigatorState("playing"),this.engine.speak();else if(this.navigatorState==="playing")return}pause(){this.navigatorState==="playing"&&(this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,this.setNavigatorState("paused"),this.engine.pause())}stop(){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,this.setNavigatorState("idle"),this.engine.stop(),this.emitEvent({type:"stop"})}clearPendingAdvance(){this.pendingAdvanceTimeout!==null&&(clearTimeout(this.pendingAdvanceTimeout),this.pendingAdvanceTimeout=null)}skipToPosition(e,r=!1){const n=this.getCurrentUtteranceIndex();return e<0||e>=this.contentQueue.length?!1:(e===n||(this.clearPendingAdvance(),this.navigatorState==="paused"&&!r?(this.pendingAutoPauseIndex!==null&&(this.pendingAutoPauseIndex=e),this.engine.setCurrentUtteranceIndex(e,i=>{i&&this.emitEvent({type:"skip",detail:{position:e}})})):(this.pendingAutoPauseIndex=null,this.setNavigatorState("playing"),this.engine.speak(e))),!0)}next(e=!1){const r=this.getCurrentUtteranceIndex();return this.skipToPosition(r+1,e)}previous(e=!1){const r=this.getCurrentUtteranceIndex();return this.skipToPosition(r-1,e)}jumpTo(e,r=!1){return this.skipToPosition(e,r)}getState(){return this.navigatorState}on(e,r){return this.events.on(e,r)}emitEvent(e){this.events.emit(e.type,e)}emitContentChangeEvent(e){this.events.emit("contentchange",{type:"contentchange",detail:e})}get settings(){return this._settings}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new er(this._preferences,this.settings)),this._preferencesEditor}submitPreferences(e){!this.source&&un.some(r=>e[r]!==void 0)&&console.warn("submitPreferences(): extraction-affecting preferences (format, inlineContextualization, verbosity, skip, contextualize, language) have no effect on content loaded via loadContent() — use loadGndContent() to re-extract on submission."),this._preferences=this._preferences.merging(e),this.applyPreferences()}applyPreferences(){const e=this._settings;this._settings=new tr(this._preferences,this._defaults),this.applyEngineParameters(),this._preferencesEditor!==null&&(this._preferencesEditor=new er(this._preferences,this._settings)),un.some(r=>!this.sameSettingValue(e[r],this._settings[r]))&&this.reextract()}sameSettingValue(e,r){return Array.isArray(e)&&Array.isArray(r)?e.length===r.length&&e.every(n=>r.includes(n)):e===r}async destroy(){this.clearPendingAdvance(),this.events.clear(),await this.engine.destroy()}}const xc=["heading1","heading2","heading3","heading4","heading5","heading6"],fn={"doc-abstract":"abstract","doc-acknowledgments":"acknowledgments","doc-afterword":"afterword","doc-appendix":"appendix",article:"article","doc-backlink":"backlink","doc-biblioentry":"listItem","doc-bibliography":"bibliography","doc-biblioref":"biblioref",blockquote:"blockquote",caption:"caption",cell:"cell","doc-chapter":"chapter","doc-colophon":"colophon",columnheader:"columnheader",complementary:"complementary","doc-conclusion":"conclusion","doc-cover":"cover","doc-credit":"credit","doc-credits":"credits","doc-dedication":"dedication",definition:"definition","doc-endnote":"footnote","doc-endnotes":"endnotes","doc-epigraph":"epigraph","doc-epilogue":"epilogue","doc-errata":"errata","doc-example":"example",figure:"figure","doc-footnote":"footnote","doc-foreword":"foreword","doc-glossary":"glossary","doc-glossref":"glossref",img:"image",image:"image","doc-index":"index","doc-introduction":"introduction",list:"list",listitem:"listItem",main:"main",math:"math",navigation:"navigation","doc-noteref":"noteref","doc-notice":"notice","doc-pagebreak":"pagebreak","doc-pagelist":"pagelist",paragraph:"paragraph","doc-part":"part","doc-preface":"preface","doc-prologue":"prologue","doc-pullquote":"pullquote",presentation:"presentation",none:"presentation","doc-qna":"qna",qna:"qna",region:"region",row:"row",rowheader:"rowheader",separator:"separator","doc-subtitle":"subtitle",table:"table",term:"term","doc-tip":"tip","doc-toc":"toc"},Ec={abstract:"abstract",acknowledgments:"acknowledgments",afterword:"afterword",appendix:"appendix",aside:"aside",backlink:"backlink",biblioentry:"listItem",bibliography:"bibliography",biblioref:"biblioref","table-cell":"cell",chapter:"chapter",colophon:"colophon",conclusion:"conclusion",cover:"cover",credit:"credit",credits:"credits",dedication:"dedication",glossdef:"definition",endnote:"footnote",endnotes:"endnotes",rearnote:"footnote",rearnotes:"endnotes",epigraph:"epigraph",epilogue:"epilogue",errata:"errata",example:"example",figure:"figure",footnote:"footnote",foreword:"foreword",glossary:"glossary",glossref:"glossref",index:"index",introduction:"introduction",landmarks:"landmarks",list:"list","list-item":"listItem",loa:"loa",loi:"loi",lot:"lot",lov:"lov",noteref:"noteref",notice:"notice",pagebreak:"pagebreak","page-list":"pagelist",pagelist:"pagelist",part:"part",preface:"preface",prologue:"prologue",pullquote:"pullquote",qna:"qna","table-row":"row",subtitle:"subtitle",table:"table",glossterm:"term",tip:"tip",toc:"toc"},Cc={article:"article",aside:"aside",audio:"audio",blockquote:"blockquote",caption:"caption",figcaption:"caption",td:"cell",dd:"definition",details:"details",figure:"figure",header:"header",h1:"heading1",h2:"heading2",h3:"heading3",h4:"heading4",h5:"heading5",h6:"heading6",img:"image",ul:"list",ol:"list",li:"listItem",main:"main",math:"math",nav:"navigation",p:"paragraph",pre:"preformatted",tr:"row",section:"section",hr:"separator",summary:"summary",table:"table",dfn:"term",dt:"term",video:"video",svg:"image"};function qt(t){const e=[],r=c=>{e.includes(c)||e.push(c)},n=[];let i=!1;const s=t.getAttribute("role");if(s)for(const c of s.split(/\s+/).filter(Boolean))if((c==="presentation"||c==="none")&&(i=!0),c==="heading"){let l=2;const d=parseInt(t.getAttribute("aria-level")??"",10);Number.isFinite(d)&&d>=1&&(l=Math.min(d,6)),n.push(xc[l-1])}else fn[c]&&n.push(fn[c]);const o=t.getAttribute("epub:type");if(o)for(const c of o.split(/\s+/).filter(Boolean)){const l=Ec[c];l&&n.push(l)}if(i)return["presentation"];const a=t.tagName.toLowerCase();if(a==="body")r("body");else if(a==="th")switch(t.getAttribute("scope")){case"col":r("columnheader");break;case"row":r("rowheader");break;default:r("cell")}else{const c=Cc[a];c&&r(c)}for(const c of n)r(c);return e}function pn(t){return!!(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))}function rr(t){let e="";const r=n=>{n.nodeType===3&&(e+=n.nodeValue??"");for(let i=n.firstChild;i;i=i.nextSibling)r(i)};return r(t),e}function Ze(t){return $e(rr(t),!0).trim()}function Ac(t){if(pn(t))return[null,!1];const e=(t.getAttribute("aria-labelledby")??"").trim();if(e){const s=[...new Set(e.split(/\s+/).filter(Boolean))],o=t.ownerDocument,a=s.map(c=>o.getElementById(c)).filter(c=>c!==null);if(a.length>0){let c="";a.forEach((d,u)=>{if(pn(d))return;const g=d.getAttribute("aria-label");c+=g||rr(d),u<a.length-1&&(c+=" ")});const l=$e(c,!0).trim();if(l!=="")return[{language:"",plain:l},!0]}}const r=(t.getAttribute("aria-label")??"").trim();if(r)return[{language:"",plain:r},!0];const n=(t.getAttribute("aria-describedby")??"").trim();if(n){const o=[...new Set(n.split(/\s+/).filter(Boolean))].map(a=>t.ownerDocument.getElementById(a)).filter(a=>a!==null);if(o.length>0){const a=o.map(l=>rr(l)).join(" "),c=$e(a,!0).trim();if(c!=="")return[{language:"",plain:c},!0]}}const i=t.tagName.toLowerCase();if(i==="img"){const s=(t.getAttribute("alt")??"").trim();if(s)return[{language:"",plain:s},!0];const o=(t.getAttribute("title")??"").trim();if(o)return[{language:"",plain:o},!0]}else if(i==="svg"){const s=t.querySelector(":scope > title");if(s){const o=Ze(s);if(o)return[{language:"",plain:o},!0]}}else if(i==="math"){const s=(t.getAttribute("alttext")??"").trim();if(s)return[{language:"",plain:s},!0]}return[null,!0]}const Tc={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function Oc(t){return Tc[t]??["",void 0]}const Rc=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]);function nr(t){return!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||ze(t.text))&&!(t.children&&t.children.length>0)&&!t.description}function Pc(t){return!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||ze(t.text))&&!!(t.children&&t.children.length>0)&&!(t.role&&t.role.length>0)&&!t.id}function Ic(t){return!(t.role&&t.role.length>0)&&!t.id}class Qe{el;object={};children=[];noText=!1;finalize(){const e=this.object,r=[];for(const n of this.children){const i=n.finalize();if(!nr(i)){if(Pc(i)){r.push(...i.children??[]);continue}r.push(i)}}if(r.length>0&&(e.children=r),(!e.text||ze(e.text))&&e.children?.length===1){const n=e.children[0];Ic(n)&&(n.text&&(e.text=n.text),n.textref&&(e.textref=n.textref),n.imgref&&(e.imgref=n.imgref),n.audioref&&(e.audioref=n.audioref),n.videoref&&(e.videoref=n.videoref),e.children=n.children)}return e}}function ir(t){const e={};t.id&&(e.id=t.id),t.textref&&(e.textref=t.textref),t.imgref&&(e.imgref=t.imgref),t.audioref&&(e.audioref=t.audioref),t.videoref&&(e.videoref=t.videoref);const r=rc(t.text);return r!==void 0&&(e.text=r),t.role&&t.role.length>0&&(e.role=t.role),t.children&&t.children.length>0&&(e.children=t.children.map(ir)),t.description&&(e.description=t.description),e}function $i(t){const e={};return t.id&&(e.id=t.id),t.textref&&(e.textref=t.textref),t.imgref&&(e.imgref=t.imgref),t.audioref&&(e.audioref=t.audioref),t.videoref&&(e.videoref=t.videoref),t.role&&(e.role=t.role),t.description&&(e.description=t.description),typeof t.text=="string"?e.text={plain:t.text,ssml:"",language:""}:t.text&&(e.text={plain:t.text.plain??"",ssml:t.text.ssml??"",language:t.text.language}),t.children&&(e.children=t.children.map($i)),e}const Nc=1;function mn(t){for(let e=t;e;e=e.parentElement){const r=e.getAttribute("xml:lang");if(r)return r;const n=e.getAttribute("lang");if(n)return n}return""}function Lc(t){for(let e=t.firstChild;e;e=e.nextSibling)if(e.nodeType===Nc)return!0;return!1}function yn(t,e){for(let r=e;r;r=r.parentElement)if(r===t)return!0;return!1}function qc(t){const e=t.slice(0,500);return/<\?xml\b/.test(e)||/xmlns:epub=/.test(e)||/DOCTYPE\s+html\s+PUBLIC\s+"-\/\/W3C\/\/DTD XHTML/i.test(e)?"application/xhtml+xml":"text/html"}const _c=3,Dc=1,$c=new Set(["object","base","font","tt","i","b","u","big","small","em","strong","dfn","code","samp","kbd","var","cite","abbr","time","acronym","mark","ruby","rt","rp","rtc","a","img","br","wbr","map","q","sub","sup","bdo","iframe","embed","span","input","select","textarea","label","button","optgroup","option","legend","datalist","keygen","output","progress","meter","area","param","source","track","summary","command","basefont","bgsound","menuitem","data","bdi","s","strike","nobr","rb"]),Uc=new Set(["summary","dfn","span"]);function vn(t,e){return Uc.has(t)&&e.length>0?!0:!$c.has(t)}class xr{xmlParsed;ids=new Map;suppressed=new Set;idAlloc={claimed:new Set,counters:new Map};noterefDepth=0;allowNode=null;root=new Qe;current=this.root;segments=[];textAcc="";currentCtx={lang:"",tag:""};flowEndsWithSpace=!0;pendingChildren=[];constructor(e){this.xmlParsed=e}allocateId(e){for(;;){const r=(this.idAlloc.counters.get(e)??0)+1;this.idAlloc.counters.set(e,r);const n=`${e}${r}`;if(!(this.ids.has(n)||this.idAlloc.claimed.has(n)))return this.idAlloc.claimed.add(n),n}}claimId(e){return this.idAlloc.claimed.has(e)?!1:(this.idAlloc.claimed.add(e),!0)}prescan(e){const r=[],n=(i,s)=>{const o=i.getAttribute("id");if(o&&!this.ids.has(o)&&this.ids.set(o,i),s=s||i.getAttribute("aria-hidden")==="true"||i.hasAttribute("hidden"),!s&&i.tagName.toLowerCase()==="a"&&qt(i).includes("noteref")){const c=i.getAttribute("href")??"";c.startsWith("#")&&r.push({id:c.slice(1),ref:i})}for(let a=i.firstElementChild;a;a=a.nextElementSibling)n(a,s)};n(e,!1);for(const i of r){const s=this.ids.get(i.id);s&&(yn(s,i.ref)||this.suppressed.add(s))}}convert(e){this.prescan(e),this.walk(e)}convertChildren(e){this.prescan(e);for(let r=e.firstChild;r;r=r.nextSibling)this.walk(r);this.flushText()}result(){const e=this.root.finalize();return!e.children||e.children.length===0?nr(e)?[]:[ir(e)]:e.children.map(ir)}descend(e){const r=new Qe;r.el=e,r.noText=this.current.noText,this.current.children.push(r),this.current=r}appendChild(e){e.noText=this.current.noText,this.current.children.push(e)}walk(e){if(e.nodeType===_c){this.text(e);return}if(e.nodeType!==Dc)return;const r=e,n=this.current,i=this.head(r);if(!i)for(let s=r.firstChild;s;s=s.nextSibling)this.walk(s);this.tail(r,i,n)}head(e){const r=e.tagName.toLowerCase();if(Rc.has(r)||this.suppressed.has(e)&&e!==this.allowNode)return!0;const[n,i]=Ac(e);if(!i&&e!==this.allowNode)return!0;const s=qt(e);if((r==="img"||r==="svg")&&(s.includes("presentation")||n===null&&e.hasAttribute("alt")&&e.getAttribute("alt").trim()===""))return!0;if(r==="br")return this.current.noText||(this.closeSegment(),this.segments.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(s.includes("pagebreak"))return!this.pagebreak(e,n,s);if(r==="a"&&s.includes("noteref")&&e.getAttribute("href"))return this.noteref(e,s),!0;if(r==="a"&&e.getAttribute("href"))return this.link(e,s),!0;if(r==="img"){const c={role:s},l=e.getAttribute("src");return l&&(c.imgref=l),n&&(c.description=n.plain),this.placeholder(e,"image",c),!0}if(r==="audio"||r==="video"){const c={role:s};let l=e.getAttribute("src");if(!l){const d=e.querySelector(":scope > source[src]");d&&(l=d.getAttribute("src"))}return r==="audio"?l&&(c.audioref=l):l&&(c.videoref=l),n&&(c.description=n.plain),this.placeholder(e,r,c),!0}if(s.includes("image")||s.includes("math")){const c={role:s};return n&&(c.description=n.plain),this.placeholder(e,s.includes("math")?"math":"image",c),!0}if(!vn(r,s))return!1;this.flushText(),this.descend(e);const o=this.current.object;s.length>0&&(o.role=s),n&&(o.description=n.plain,s.includes("figure")&&(this.current.noText=!0));const a=e.getAttribute("id");return a&&(o.id=a),!1}tail(e,r,n){if(r)return;const i=e.tagName.toLowerCase(),s=qt(e);vn(i,s)&&(this.flushText(),this.current=n)}text(e){if(this.current.noText)return;const r=e.nodeValue??"";if(/^\s*$/.test(r)){(this.textAcc.length>0||this.segments.length>0)&&(this.textAcc+=$e(r,this.flowEndsWithSpace),this.updateFlowSpace());return}const n=this.textContext(e);nc(n,this.currentCtx)||(this.closeSegment(),this.currentCtx=n),this.textAcc+=$e(r,this.flowEndsWithSpace),this.updateFlowSpace()}textContext(e){const r={lang:mn(e.parentElement),tag:""};for(let n=e.parentElement;n&&n!==this.current.el;n=n.parentElement){const[i,s]=Oc(n.tagName.toLowerCase());if(i&&i!=="break"){r.tag=i,r.attrs=s;break}}return r}updateFlowSpace(){this.textAcc.length>0&&(this.flowEndsWithSpace=this.textAcc.endsWith(" "))}closeSegment(){this.textAcc.length!==0&&(this.segments.push({kind:"text",text:this.textAcc,ctx:this.currentCtx}),this.textAcc="")}resetFlow(){this.segments=[],this.textAcc="",this.currentCtx={lang:"",tag:""},this.flowEndsWithSpace=!0,this.pendingChildren=[]}placeholder(e,r,n,i){if(nr(n))return;const s=new Qe;if(s.el=e,s.object=n,this.current.noText){this.appendChild(s);return}this.closeSegment(),this.pendingChildren.push(s),this.segments.push({kind:"placeholder",tag:r,child:s,candidateID:i??e.getAttribute("id")??void 0}),this.flowEndsWithSpace=!1}pagebreak(e,r,n){const i={role:n},s=(e.getAttribute("title")??"").trim();s?i.text={plain:s,ssml:"",language:""}:r&&(i.text={plain:r.plain??"",ssml:r.ssml??"",language:r.language});const o=!!(i.text&&!ze(i.text)),a=!this.xmlParsed&&(Lc(e)||o&&e.firstChild!==null);if(!o&&!a){const l=Ze(e);l&&(i.text={plain:l,ssml:"",language:""})}const c=e.getAttribute("id");return c&&(i.textref=`#${c}`),this.placeholder(e,"pagebreak",i),a}noteref(e,r){const n={role:r},i=Ze(e);i&&(n.text={plain:i,ssml:"",language:""});const s=e.getAttribute("href")??"";let o=e.getAttribute("id")??"";if(!o&&s.startsWith("#")&&(o=s.slice(1)),s.startsWith("#")){const a=s.slice(1),c=this.ids.get(a);if(c&&!yn(c,e)&&this.noterefDepth<3){const l=new xr(this.xmlParsed);l.ids=this.ids,l.suppressed=this.suppressed,l.idAlloc=this.idAlloc,l.noterefDepth=this.noterefDepth+1,l.allowNode=c,l.convert(c);const d=l.result();d.length>0&&(n.children=d.map(u=>{const g=$i(u);return delete g.id,g}))}}!n.children&&s&&(n.children=[{textref:s}]),this.placeholder(e,"noteref",n,o||void 0)}link(e,r){const n={};r.length>0&&(n.role=r);const i=Ze(e);i&&(n.text={plain:i,ssml:"",language:""});const s=e.getAttribute("href");s&&(n.textref=s),this.placeholder(e,r[0]??"link",n)}flushText(){this.closeSegment();let e=this.segments;const r=this.pendingChildren;if(this.resetFlow(),e.length===0)return;for(;e.length>0;){const m=e[0];if(m.kind==="break"){e=e.slice(1);continue}if(m.kind==="text"){const p=m.text.replace(/^\s+/,"");if(p===""){e=e.slice(1);continue}e=[{...m,text:p},...e.slice(1)]}break}for(;e.length>0;){const m=e[e.length-1];if(m.kind==="break"){e=e.slice(0,-1);continue}if(m.kind==="text"){const p=m.text.replace(/\s+$/,"");if(p===""){e=e.slice(0,-1);continue}e=[...e.slice(0,-1),{...m,text:p}]}break}if(!e.some(m=>m.kind==="text"&&m.text.trim()!=="")){for(const m of r)this.appendChild(m);return}const i=[];for(const m of e)if(m.kind==="text"&&m.text.trim()!==""){const p=m.ctx.lang;i.includes(p)||i.push(p)}let s=mn(this.current.el??null);i.length===1&&i[0]!==""&&(s=i[0]);let o=!1;for(const m of e)if(m.kind!=="text"||m.ctx.tag!==""||m.ctx.lang!==s){o=!0;break}if(o&&s===""&&(s="en"),o)for(const m of e){if(m.kind!=="placeholder")continue;let p=m.candidateID;(!p||!this.claimId(p))&&(p=this.allocateId(m.tag)),m.child.object.id=p}let a="",c=!1,l=!1,d=!1,u=!1;for(const m of e)if(m.kind==="text"){const p=m.text.startsWith(" "),w=m.text.replace(/^ +| +$/g,"");if(w===""){u=!0;continue}let E=!1;if(a.length>0){const x=c||u||p;l?E=!0:d?E=x&&!pt(w):E=x}E&&(a+=" "),a+=w,c=m.text.endsWith(" "),l=!1,d=!1,u=!1}else m.kind==="break"?l=!0:m.kind==="placeholder"&&(d=!0);const g=e.some(m=>m.kind==="placeholder"),f={plain:o&&!g?"":a.trim(),ssml:"",language:s};if(o){let m="";for(const p of e)if(p.kind==="text"){let w=p.ctx.tag,E=p.ctx.attrs;if(p.ctx.lang!==s&&p.ctx.lang!==""&&(w="lang",E=void 0),w){m+=`<${w}`;for(const[x,R]of Object.entries(E??{}))m+=` ${x}="${Nt(R)}"`;p.ctx.lang!==s&&p.ctx.lang!==""&&(m+=` xml:lang="${Nt(p.ctx.lang)}"`),m+=`>${ot(p.text)}</${w}>`}else m+=ot(p.text)}else p.kind==="break"?m+="<break/>":p.kind==="placeholder"&&(m+=`<readium:${p.tag} id="${Nt(p.child.object.id)}" />`);f.ssml=m}const y=new Qe;y.object={text:f};for(const m of r)y.children.push(m);this.appendChild(y)}}const Bc=/<body[\s>]/i;function Ui(t,e){const r=e??qc(t),n=new DOMParser().parseFromString(t,r),i=new xr(r==="application/xhtml+xml"),s=n.querySelector("body");return s&&!Bc.test(t)?i.convertChildren(s):i.convert(s??n.documentElement),i.result()}function Vc(t,e){return{guided:Ui(t,e)}}exports.BUILTIN_DECORATION_TYPES=ci;exports.BooleanPreference=wi;exports.DecorationController=mi;exports.DecorationLayout=ai;exports.DecorationStyleType=C;exports.DecorationWidth=si;exports.Decorator=li;exports.DirectCommsChannel=gi;exports.DirectCommsFrame=fi;exports.DirectCommsHost=pi;exports.EnumPreference=Ne;exports.FallbackEngineProvider=pl;exports.FallbackSpeechEngine=Hn;exports.Locator=_e;exports.LocatorLocations=j;exports.LocatorText=Be;exports.Preference=Ve;exports.RangePreference=Le;exports.ReadiumSpeechDecorationController=vi;exports.ReadiumSpeechNavigator=kc;exports.ReadiumSpeechProviderRegistry=ec;exports.SpeechDefaults=bi;exports.SpeechPreferences=ve;exports.SpeechPreferencesEditor=er;exports.SpeechServerAudioDecodeError=fr;exports.SpeechServerEngine=Mn;exports.SpeechServerEngineProvider=dl;exports.SpeechServerError=ye;exports.SpeechServerNetworkError=pr;exports.SpeechServerStallError=gr;exports.SpeechSettings=tr;exports.StringArrayPreference=Yt;exports.WebSpeechEngine=Ft;exports.WebSpeechEngineProvider=Qo;exports.WebSpeechVoiceManager=P;exports.blockLevelRoles=Ni;exports.chineseVariantMap=de;exports.chunkPlainText=Un;exports.chunkSsmlText=Bn;exports.contextualizedAtVerbosity=Ei;exports.createLocator=yi;exports.decorationsEqual=hi;exports.defaultAnnouncements=Ci;exports.extractUtterances=wc;exports.isRecoverableFailure=Fn;exports.makeGnd=Vc;exports.mapServerVoice=dr;exports.mimeTypeForFormat=Vn;exports.parseMarkup=Ui;exports.resolveDecorationForWire=Zt;exports.selectBitrate=jn;exports.selectFormat=zn;exports.setupDecorations=Yl;exports.skippableAtVerbosity=xi;exports.skippableRoles=mc;exports.supportsDecorationStyle=ui;exports.toSpeechServerError=ce;
|