@readium/speech 0.9.0 → 0.9.2
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/index.cjs +23 -23
- package/build/index.js +697 -684
- 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 q=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()]}},ne={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},係越中文聲。"}},sn=new Map,yo=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 bo(t){try{const e=t.split("-")[0],n=yo[`../../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(wo)}}catch(e){return console.warn(`Failed to load voice data for ${t}:`,e),{language:t,defaultRegion:"",testUtterance:"",voices:[]}}}function $r(t){return sn.has(t)||sn.set(t,bo(t)),sn.get(t)}const So=["veryLow","low","normal","high","veryHigh"],vo=["android","apple"],wo=t=>({...t,quality:t.quality?.filter(e=>So.includes(e)),localizedName:t.localizedName&&vo.includes(t.localizedName)?t.localizedName:void 0}),Pe={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"},J=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 Pe[e]||e},On=async t=>{if(!t)return[];try{const e=J(t);try{const r=await $r(e);if(r?.voices?.length)return r.voices}catch(r){console.warn(`Failed to load voices for ${e}:`,r)}const[n]=q(e);if(n!==e)try{const r=await $r(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),[]}},An=(t,e)=>{try{return new Intl.DisplayNames(e?[e]:[],{type:"language",languageDisplay:"standard"}).of(t)||t.toUpperCase()}catch{return t.toUpperCase()}},_r=t=>{if(!t)return"";try{const e=J(t),n=ne[e];if(n?.testUtterance)return n.testUtterance;if(e in Pe){const i=Pe[e];if(i&&ne[i]?.testUtterance)return ne[i].testUtterance}const[r]=q(e);return r!==e&&ne[r]?.testUtterance?ne[r].testUtterance:""}catch(e){return console.error(`Error in getTestUtterance for ${t}:`,e),""}},Wt=t=>{if(!t)return"";try{const e=J(t),n=ne[e];if(n?.defaultRegion)return`${e}-${n.defaultRegion}`;if(e in Pe){const i=Pe[e];if(i){const s=ne[i];if(s?.defaultRegion)return`${i}-${s.defaultRegion}`}}const[r]=q(e);if(r!==e){const i=ne[r];if(i?.defaultRegion)return`${r}-${i.defaultRegion}`}return""}catch(e){return console.error(`Failed to get default region for ${t}:`,e),""}},Gt=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=J(s),[a,c]=q(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(ne[i]?.availableRegions||[]),a=Array.from(s),c=Array.from(e).filter(u=>o.has(u)&&!a.includes(u)),l=Array.from(new Set([...a,...c])).sort((u,h)=>{const d=r.get(u)??Number.MAX_SAFE_INTEGER,g=r.get(h)??Number.MAX_SAFE_INTEGER;return d-g});if(l.length===0){const u=Wt(i),[,h]=q(u);h&&l.push(h)}return{baseLang:i,regions:l}})},Le=async t=>{const e=new Map;for(const r of t){if(r.source!=="json")continue;const[i]=q(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 On(r),a=new Map;o.forEach((c,l)=>{a.set(c.name.toLowerCase(),l),c.altNames?.forEach(u=>{a.set(u.toLowerCase(),l)})});for(const c of i){const l=c.name.toLowerCase(),u=a.get(l);u!==void 0&&s.set(c.name,u)}s.size>0&&n.set(r,s)}return n},xo={veryLow:1,low:2,normal:3,high:4,veryHigh:5},Nt=t=>t?xo[t]??0:0,pe=(t,e,n,r)=>{const i=Nt(t.quality),s=Nt(e.quality);if(n&&r&&t.source==="json"&&e.source==="json"){const o=n.get(r);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)},Kt=(t,e)=>{const n=new Map(e.map(s=>[s.baseLang,s])),r=new Map,i=[];for(const s of t){const[o]=q(s.language);n.get(o)?(r.has(o)||r.set(o,[]),r.get(o).push(s)):i.push(s)}return{voicesByLang:r,otherLangVoices:i}},rs=(t,e,n,r)=>{const[,i]=q(t.language),[,s]=q(e.language),o=i&&n.regions.includes(i),a=s&&n.regions.includes(s);if(o&&a){const d=n.regions.indexOf(i),g=n.regions.indexOf(s);return d===g?pe(t,e,r,n.baseLang):d-g}if(o)return-1;if(a)return 1;const c=Wt(n.baseLang),[,l]=q(c),u=!!l&&i===l,h=!!l&&s===l;if(u&&!h)return-1;if(!u&&h)return 1;if(i&&s){const d=i.localeCompare(s);return d!==0?d:pe(t,e,r,n.baseLang)}return i?-1:s?1:pe(t,e,r,n.baseLang)},Eo=async(t,e,n)=>{const r=n??await Le(t);t.sort((i,s)=>rs(i,s,e,r))},is=(t,e,n)=>{const[r]=q(t.language),[i]=q(e.language),s=An(r).toLowerCase(),o=An(i).toLowerCase(),a=s.localeCompare(o);if(a!==0)return a;if(r===i){const c=Wt(r),[,l]=q(t.language),[,u]=q(e.language),h=c&&l===c.split("-")[1],d=c&&u===c.split("-")[1];if(h&&!d)return-1;if(!h&&d)return 1;if(l&&u){const g=l.localeCompare(u);if(g!==0)return g}return l&&!u?-1:!l&&u?1:pe(t,e,n,r)}return pe(t,e,n,r)},Tn=async(t,e)=>{const n=e??await Le(t);t.sort((r,i)=>is(r,i,n))},Co=async(t,e)=>{if(!e?.length)return[];const n=Gt(t||[]),{voicesByLang:r,otherLangVoices:i}=Kt(e,n),s=await Le(e),o=[];for(const a of n){const c=r.get(a.baseLang);c&&(await Eo(c,a,s),o.push(...c))}return await Tn(i,s),o.push(...i),o},ko=async(t,e)=>{if(!e.length)return null;const[n]=Gt([t]),{voicesByLang:r,otherLangVoices:i}=Kt(e,[n]),s=r.get(n.baseLang),o=s?.length?s:i,a=await Le(e),c=s?.length?(l,u)=>rs(l,u,n,a):(l,u)=>is(l,u,a);return o.reduce((l,u)=>c(u,l)<0?u:l)},Oo=[{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}],Ao={voices:Oo},To=[{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}],Ro={voices:To},No=Ao,Do=Ro,Rn=(t,e)=>No.voices.some(n=>t.includes(n.name)||e&&n.nativeID?.some(r=>e.includes(r))||n.altNames?.some(r=>t.includes(r))),Nn=(t,e)=>Do.voices.some(n=>t.includes(n.name))||e==="veryLow",Br=t=>t?.length?t.filter(e=>!(e.isNovelty||Rn(e.name,e.voiceURI))):[],qr=t=>t?.length?t.filter(e=>!Nn(e.name,e.quality)):[],Fo={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"}},Io={quality:Fo},Dn={apple:Io.quality},Po=(t,e,n)=>{if(!t)return;const r=Array.isArray(n)?n:n?[n]:[];for(const i of r)if(i&&Dn[i]){const s=Dn[i],o=q(e)[0],a=s[e]||s[o];if(a){const c=t.toLowerCase(),{normal:l,high:u}=a;if(u&&c.includes(u.toLowerCase()))return"high";if(l&&c.includes(l.toLowerCase()))return"normal"}}},Lo=(t,e)=>{const n=Dn[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}},$o={low:{values:["super-compact","compact"],quality:"low"},normal:{values:["enhanced"],quality:"normal"},high:{values:["premium"],quality:"high"}},Ur=t=>{if(!t)return;const n=t.toLowerCase().split(/[._-]/);for(const r of Object.values($o))if(r.values.some(i=>n.includes(i)))return r.quality};function _o(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 Bo(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 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 n=P.instance;return e?.languages&&e.languages.length>0&&await n.broadenLanguages(e.languages),n}return P.initializationPromise||(P.initializationPromise=(async()=>{try{const n=new P;P.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=P.toBaseLangSet(e.languages)):n.scopedLanguages=null,n.voices=await n.parseToReadiumSpeechVoices(r),n.isInitialized=!0,n}catch(n){throw P.initializationPromise=null,console.error("Failed to initialize WebSpeechVoiceManager:",n),n}})()),P.initializationPromise}filterBrowserVoicesByLanguages(e,n){if(!n?.length)return e;const r=P.toBaseLangSet(n);return e.filter(i=>{if(!i?.lang)return!1;const s=J(i.lang),[o]=P.extractLangRegionFromBCP47(s);return r.has(o)})}static toBaseLangSet(e){return new Set(e.map(n=>{const r=J(n),[i]=P.extractLangRegionFromBCP47(r);return i}))}async broadenLanguages(e){if(this.scopedLanguages===null)return;const r=[...P.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 q(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 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=Lo(n,"apple");r&&(this.systemLocale=r)}inferVoiceQuality(e,n,r){const i=e.voiceURI?Ur(e.voiceURI):void 0;if(i)return i;if(n?.nativeID&&Array.isArray(n.nativeID))for(const s of n.nativeID){const o=Ur(s);if(o)return o}if(n?.localizedName&&e.voiceURI&&e.lang){const s=Po(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(Bo(r,s)){const o=_o(r,s);n.set(i,o)}else{const o=Nt(s.quality);Nt(r.quality)>=o&&n.set(i,r)}}return Array.from(n.values())}getTestUtterance(e){if(!e)return"";const n=_r(e);if(n)return n;const[r]=P.extractLangRegionFromBCP47(e);if(r&&r!==e){const i=_r(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 u=J(c.language).split("-")[0];if(!a.has(u)){const h=An(u,e),d=s.filter(g=>J(g.language).split("-")[0]===u).length;o.push({code:u,label:h,count:d}),a.add(u)}}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[,u]=P.extractLangRegionFromBCP47(l.language);u&&c.set(u,(c.get(u)||0)+1)}for(const l of s){const[,u]=P.extractLangRegionFromBCP47(l.language);if(u&&!a.has(u)){let h=l.language;try{const d=e||navigator.language;h=new Intl.DisplayNames([d],{type:"region"}).of(u)||l.language}catch(d){console.warn(`Failed to get display name for region ${u}`,d)}o.push({code:u,label:h,count:c.get(u)||0}),a.add(u)}}return r?o:o.sort((l,u)=>l.label.localeCompare(u.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 u=()=>{if(a<1)return s([]);--a;const h=r();if(Array.isArray(h)&&h.length)return s(h);setTimeout(u,n)};setTimeout(u,n)};window.speechSynthesis.onvoiceschanged!==void 0?window.speechSynthesis.onvoiceschanged=()=>{const u=r();Array.isArray(u)&&u.length?s(u):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=J(i.lang),[o]=P.extractLangRegionFromBCP47(s),a=this.normalizeVoiceName(i.name),c=`${i.lang.toLowerCase()}_${a}`,l=n.get(c)||1;let u=await On(s);(!u||u.length===0)&&(u=await On(o));const h=this.findMatchingJsonVoice(u,a),d=this.inferVoiceQuality(i,h,l);return h?{...h,label:h.label??this.cleanVoiceName(i.name),source:"json",originalName:i.name,language:h.language??s,voiceURI:i.voiceURI,quality:d,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Rn(i.name,i.voiceURI),isLowQuality:Nn(i.name,d)}:{source:"browser",label:this.cleanVoiceName(i.name),name:i.name,originalName:i.name,language:s,voiceURI:i.voiceURI,quality:d,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Rn(i.name,i.voiceURI),isLowQuality:Nn(i.name,d)}}))}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(),u=o.altLanguage?.toLowerCase();if(l===c||u===c)return!0;const[h]=c.split("-");return l&&l.startsWith(h)||u&&u.startsWith(h)}))}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=Br(r)),i.excludeVeryLowQuality&&(r=qr(r)),i.removeDuplicates&&(r=this.removeDuplicates(r)),r}filterOutNoveltyVoices(e){const n=e??this.voices;return Br(n)}filterOutVeryLowQualityVoices(e){const n=e??this.voices;return qr(n)}async sortVoicesByQuality(e){const n=e||this.voices;if(!n?.length)return[];const r=await Le(n);return[...n].sort((i,s)=>pe(i,s,r))}static async sortByDefaultRegion(e,n){const r=await Le(e),i=Wt(n);e.sort((s,o)=>{const[,a]=P.extractLangRegionFromBCP47(s.language),[,c]=P.extractLangRegionFromBCP47(o.language),l=i&&a===i.split("-")[1],u=i&&c===i.split("-")[1];return l&&!u?-1:!l&&u?1:pe(s,o,r,n)})}async sortVoicesByLanguages(e,n){const r=n||this.voices;if(!r?.length)return[];if(!e?.length){const c=[...r];return await Tn(c),c}const i=Gt(e),{voicesByLang:s,otherLangVoices:o}=Kt(r,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 Tn(o),a.push(...o),a}async sortVoicesByRegions(e,n){return Co(e,n||this.voices)}groupVoices(e,n){const r={},i=n||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}r[o]||(r[o]=[]),r[o].push(s)}return r}}const qo=["webKit","moz","ms","o"],Uo=["boundary","end","error","mark","pause","resume","start"],Vo=t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`,He=(t={},e)=>Object.hasOwnProperty.call(t,e)||e in t||!!t[e],zo=t=>typeof window<"u"&&t in window,Mo=t=>{const e=Vo(t),n=qo.map(i=>`${i}${e}`),r=[t,e].concat(n).find(zo);return r&&typeof window<"u"?window[r]:void 0},jo=()=>{const t={};["speechSynthesis","speechSynthesisUtterance","speechSynthesisVoice","speechSynthesisEvent","speechSynthesisErrorEvent"].forEach(n=>{t[n]=Mo(n)}),t.onvoiceschanged=He(t.speechSynthesis,"onvoiceschanged"),t.speechSynthesisSpeaking=He(t.speechSynthesis,"speaking"),t.speechSynthesisPaused=He(t.speechSynthesis,"paused");const e=t.speechSynthesisUtterance?He(t.speechSynthesisUtterance,"prototype"):!1;return Uo.forEach(n=>{const r=`on${n}`;t[r]=e&&t.speechSynthesisUtterance?He(t.speechSynthesisUtterance.prototype,r):!1}),t},Ho=()=>{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()}};let Jt=class{listeners=new Map;on(e,n){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(n),()=>{const r=this.listeners.get(e);if(r){const i=r.indexOf(n);i>-1&&r.splice(i,1)}}}emit(e,n){const r=this.listeners.get(e);r&&[...r].forEach(i=>{try{i(n)}catch(s){console.error(`Error in "${String(e)}" listener:`,s)}})}clear(){this.listeners.clear()}};const kt=(t,e)=>Math.min(Math.max(t,0),Math.max(e-1,0));function me(t,e,n,r){return Number.isFinite(t)?Math.max(e,Math.min(n,t)):r}function Wo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var an,Vr;function Go(){if(Vr)return an;Vr=1,an=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,u)=>new Map(o(Array.from(l),u))),i.set(Set,(l,u)=>new Set(o(Array.from(l),u))),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,u){const h=Object.keys(l),d=new Array(h.length);for(let g=0;g<h.length;g++){const p=h[g],m=l[p];typeof m!="object"||m===null?d[p]=m:m.constructor!==Object&&(s=i.get(m.constructor))?d[p]=s(m,u):ArrayBuffer.isView(m)?d[p]=t(m):d[p]=u(m)}return d}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 u={};for(const h in l){if(Object.hasOwnProperty.call(l,h)===!1)continue;const d=l[h];typeof d!="object"||d===null?u[h]=d:d.constructor!==Object&&(s=i.get(d.constructor))?u[h]=s(d,a):ArrayBuffer.isView(d)?u[h]=t(d):u[h]=a(d)}return u}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 u={};for(const h in l){const d=l[h];typeof d!="object"||d===null?u[h]=d:d.constructor!==Object&&(s=i.get(d.constructor))?u[h]=s(d,c):ArrayBuffer.isView(d)?u[h]=t(d):u[h]=c(d)}return u}}function n(r){const i=[],s=[],o=new Map;if(o.set(Date,h=>new Date(h)),o.set(Map,(h,d)=>new Map(c(Array.from(h),d))),o.set(Set,(h,d)=>new Set(c(Array.from(h),d))),r.constructorHandlers)for(const h of r.constructorHandlers)o.set(h[0],h[1]);let a=null;return r.proto?u:l;function c(h,d){const g=Object.keys(h),p=new Array(g.length);for(let m=0;m<g.length;m++){const b=g[m],x=h[b];if(typeof x!="object"||x===null)p[b]=x;else if(x.constructor!==Object&&(a=o.get(x.constructor)))p[b]=a(x,d);else if(ArrayBuffer.isView(x))p[b]=t(x);else{const A=i.indexOf(x);A!==-1?p[b]=s[A]:p[b]=d(x)}}return p}function l(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return c(h,l);if(h.constructor!==Object&&(a=o.get(h.constructor)))return a(h,l);const d={};i.push(h),s.push(d);for(const g in h){if(Object.hasOwnProperty.call(h,g)===!1)continue;const p=h[g];if(typeof p!="object"||p===null)d[g]=p;else if(p.constructor!==Object&&(a=o.get(p.constructor)))d[g]=a(p,l);else if(ArrayBuffer.isView(p))d[g]=t(p);else{const m=i.indexOf(p);m!==-1?d[g]=s[m]:d[g]=l(p)}}return i.pop(),s.pop(),d}function u(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return c(h,u);if(h.constructor!==Object&&(a=o.get(h.constructor)))return a(h,u);const d={};i.push(h),s.push(d);for(const g in h){const p=h[g];if(typeof p!="object"||p===null)d[g]=p;else if(p.constructor!==Object&&(a=o.get(p.constructor)))d[g]=a(p,u);else if(ArrayBuffer.isView(p))d[g]=t(p);else{const m=i.indexOf(p);m!==-1?d[g]=s[m]:d[g]=u(p)}}return i.pop(),s.pop(),d}}return an}var Ko=Go();const ss=Wo(Ko);ss();function Fn(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 Oe(t){return typeof t=="string"}function Jo(t){return Number.isFinite(t)}function xe(t){return Number.isSafeInteger(t)&&t>=0}function se(t){return t!=null}function Xo(t,e){return Fn(t)&&Oe(e)&&e in t}var Yo=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,Qo=typeof self=="object"&&self&&self.Object===Object&&self,sr=Yo||Qo||Function("return this")(),$e=sr.Symbol,as=Object.prototype,Zo=as.hasOwnProperty,el=as.toString,We=$e?$e.toStringTag:void 0;function tl(t){var e=Zo.call(t,We),n=t[We];try{t[We]=void 0;var r=!0}catch{}var i=el.call(t);return r&&(e?t[We]=n:delete t[We]),i}var nl=Object.prototype,rl=nl.toString;function il(t){return rl.call(t)}var sl="[object Null]",al="[object Undefined]",zr=$e?$e.toStringTag:void 0;function os(t){return t==null?t===void 0?al:sl:zr&&zr in Object(t)?tl(t):il(t)}function ls(t){return t!=null&&typeof t=="object"}var ol="[object Symbol]";function ll(t){return typeof t=="symbol"||ls(t)&&os(t)==ol}function cl(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 ul=Array.isArray,Mr=$e?$e.prototype:void 0,jr=Mr?Mr.toString:void 0;function ar(t){if(typeof t=="string")return t;if(ul(t))return cl(t,ar)+"";if(ll(t))return jr?jr.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}var hl=/\s/;function dl(t){for(var e=t.length;e--&&hl.test(t.charAt(e)););return e}var fl=/^\s+/;function gl(t){return t&&t.slice(0,dl(t)+1).replace(fl,"")}function cs(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function us(t){return t}var pl="[object AsyncFunction]",ml="[object Function]",yl="[object GeneratorFunction]",bl="[object Proxy]";function hs(t){if(!cs(t))return!1;var e=os(t);return e==ml||e==yl||e==pl||e==bl}var on=sr["__core-js_shared__"],Hr=(function(){var t=/[^.]+$/.exec(on&&on.keys&&on.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function Sl(t){return!!Hr&&Hr in t}var vl=Function.prototype,wl=vl.toString;function xl(t){if(t!=null){try{return wl.call(t)}catch{}try{return t+""}catch{}}return""}var El=/[\\^$.*+?()[\]{}|]/g,Cl=/^\[object .+?Constructor\]$/,kl=Function.prototype,Ol=Object.prototype,Al=kl.toString,Tl=Ol.hasOwnProperty,Rl=RegExp("^"+Al.call(Tl).replace(El,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Nl(t){if(!cs(t)||Sl(t))return!1;var e=hs(t)?Rl:Cl;return e.test(xl(t))}function Dl(t,e){return t?.[e]}function or(t,e){var n=Dl(t,e);return Nl(n)?n:void 0}function Fl(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 Il=800,Pl=16,Ll=Date.now;function $l(t){var e=0,n=0;return function(){var r=Ll(),i=Pl-(r-n);if(n=r,i>0){if(++e>=Il)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function _l(t){return function(){return t}}var Wr=(function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Bl=Wr?function(t,e){return Wr(t,"toString",{configurable:!0,enumerable:!1,value:_l(e),writable:!0})}:us,ql=$l(Bl);function Ul(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 Vl(t){return t!==t}function zl(t,e,n){for(var r=n-1,i=t.length;++r<i;)if(t[r]===e)return r;return-1}function lr(t,e,n){return e===e?zl(t,e,n):Ul(t,Vl,n)}function Ml(t,e){var n=t==null?0:t.length;return!!n&&lr(t,e,0)>-1}function jl(t,e){return t===e||t!==t&&e!==e}var Gr=Math.max;function Hl(t,e,n){return e=Gr(e===void 0?t.length-1:e,0),function(){for(var r=arguments,i=-1,s=Gr(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),Fl(t,this,a)}}function Wl(t,e){return ql(Hl(t,e,us),t+"")}var Gl=9007199254740991;function Kl(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Gl}function Jl(t){return t!=null&&Kl(t.length)&&!hs(t)}var st=or(Object,"create");function Xl(){this.__data__=st?st(null):{},this.size=0}function Yl(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Ql="__lodash_hash_undefined__",Zl=Object.prototype,ec=Zl.hasOwnProperty;function tc(t){var e=this.__data__;if(st){var n=e[t];return n===Ql?void 0:n}return ec.call(e,t)?e[t]:void 0}var nc=Object.prototype,rc=nc.hasOwnProperty;function ic(t){var e=this.__data__;return st?e[t]!==void 0:rc.call(e,t)}var sc="__lodash_hash_undefined__";function ac(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=st&&e===void 0?sc:e,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=Xl;ye.prototype.delete=Yl;ye.prototype.get=tc;ye.prototype.has=ic;ye.prototype.set=ac;function oc(){this.__data__=[],this.size=0}function Xt(t,e){for(var n=t.length;n--;)if(jl(t[n][0],e))return n;return-1}var lc=Array.prototype,cc=lc.splice;function uc(t){var e=this.__data__,n=Xt(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():cc.call(e,n,1),--this.size,!0}function hc(t){var e=this.__data__,n=Xt(e,t);return n<0?void 0:e[n][1]}function dc(t){return Xt(this.__data__,t)>-1}function fc(t,e){var n=this.__data__,r=Xt(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=oc;Me.prototype.delete=uc;Me.prototype.get=hc;Me.prototype.has=dc;Me.prototype.set=fc;var gc=or(sr,"Map");function pc(){this.size=0,this.__data__={hash:new ye,map:new(gc||Me),string:new ye}}function mc(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Yt(t,e){var n=t.__data__;return mc(e)?n[typeof e=="string"?"string":"hash"]:n.map}function yc(t){var e=Yt(this,t).delete(t);return this.size-=e?1:0,e}function bc(t){return Yt(this,t).get(t)}function Sc(t){return Yt(this,t).has(t)}function vc(t,e){var n=Yt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}function je(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])}}je.prototype.clear=pc;je.prototype.delete=yc;je.prototype.get=bc;je.prototype.has=Sc;je.prototype.set=vc;function wc(t){return t==null?"":ar(t)}function xc(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 Ec(t,e,n){var r=t.length;return n=n===void 0?r:n,!e&&n>=r?t:xc(t,e,n)}var Cc="\\ud800-\\udfff",kc="\\u0300-\\u036f",Oc="\\ufe20-\\ufe2f",Ac="\\u20d0-\\u20ff",Tc=kc+Oc+Ac,Rc="\\ufe0e\\ufe0f",Nc="\\u200d",Dc=RegExp("["+Nc+Cc+Tc+Rc+"]");function Fc(t){return Dc.test(t)}function Ic(t){return t.split("")}var ds="\\ud800-\\udfff",Pc="\\u0300-\\u036f",Lc="\\ufe20-\\ufe2f",$c="\\u20d0-\\u20ff",_c=Pc+Lc+$c,Bc="\\ufe0e\\ufe0f",qc="["+ds+"]",In="["+_c+"]",Pn="\\ud83c[\\udffb-\\udfff]",Uc="(?:"+In+"|"+Pn+")",fs="[^"+ds+"]",gs="(?:\\ud83c[\\udde6-\\uddff]){2}",ps="[\\ud800-\\udbff][\\udc00-\\udfff]",Vc="\\u200d",ms=Uc+"?",ys="["+Bc+"]?",zc="(?:"+Vc+"(?:"+[fs,gs,ps].join("|")+")"+ys+ms+")*",Mc=ys+ms+zc,jc="(?:"+[fs+In+"?",In,gs,ps,qc].join("|")+")",Hc=RegExp(Pn+"(?="+Pn+")|"+jc+Mc,"g");function Wc(t){return t.match(Hc)||[]}function Kr(t){return Fc(t)?Wc(t):Ic(t)}var Gc="__lodash_hash_undefined__";function Kc(t){return this.__data__.set(t,Gc),this}function Jc(t){return this.__data__.has(t)}function Dt(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new je;++e<n;)this.add(t[e])}Dt.prototype.add=Dt.prototype.push=Kc;Dt.prototype.has=Jc;function Xc(t,e){return t.has(e)}function Yc(t){return ls(t)&&Jl(t)}var Qc=200;function Zc(t,e,n,r){var i=-1,s=Ml,o=!0,a=t.length,c=[],l=e.length;if(!a)return c;e.length>=Qc&&(s=Xc,o=!1,e=new Dt(e));e:for(;++i<a;){var u=t[i],h=u;if(u=u!==0?u:0,o&&h===h){for(var d=l;d--;)if(e[d]===h)continue e;c.push(u)}else s(e,h,r)||c.push(u)}return c}function eu(t,e){for(var n=t.length;n--&&lr(e,t[n],0)>-1;);return n}function tu(t,e){for(var n=-1,r=t.length;++n<r&&lr(e,t[n],0)>-1;);return n}function Jr(t,e,n){if(t=wc(t),t&&e===void 0)return gl(t);if(!t||!(e=ar(e)))return t;var r=Kr(t),i=Kr(e),s=tu(r,i),o=eu(r,i)+1;return Ec(r,s,o).join("")}var nu=Wl(function(t,e){return Yc(t)?Zc(t,e):[]}),Ne=function(){return Ne=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},Ne.apply(this,arguments)},ru="~",iu="~~";function cr(t,e){for(var n={},r={},i=t.split(iu),s=!1,o=0;i.length>o;o++){for(var a=i[o].split(ru),c=0;c<a.length;c+=2){var l=a[c],u=a[c+1],h="&"+l+";";n[h]=u,s&&(n["&"+l]=u),r[u]=h}s=!0}return e?{entities:Ne(Ne({},n),e.entities),characters:Ne(Ne({},r),e.characters)}:{entities:n,characters:r}}var ln={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},_e={};_e.xml=cr(`lt~<~gt~>~quot~"~apos~'~amp~&`);_e.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~>`);_e.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~®',_e.html4);var su={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},au=String.fromCodePoint||function(t){return String.fromCharCode(Math.floor((t-65536)/1024)+55296,(t-65536)%1024+56320)},Be=function(){return Be=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},Be.apply(this,arguments)},ou=Be(Be({},_e),{all:_e.html5}),lu={scope:"body",level:"all"},cn=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g,un=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g,Xr={xml:{strict:cn,attribute:un,body:ln.xml},html4:{strict:cn,attribute:un,body:ln.html4},html5:{strict:cn,attribute:un,body:ln.html5}},cu=Be(Be({},Xr),{all:Xr.html5}),bs=String.fromCharCode,uu=bs(65533);function hu(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?uu:c>65535?au(c):bs(su[c]||c)}}return i}function Yr(t,e){var n=e===void 0?lu: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=cu[i][o],c=ou[i].entities,l=o==="attribute",u=o==="strict";return t.replace(a,function(h){return hu(h,c,l,u)})}var du={strictlyTwoElementsInRangeArrays:!1,progressFn:null};function Ft(t,e){if(!Array.isArray(t)||!t.length)return t;let n={...du,...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 Qr={mergeType:1,progressFn:null,joinRangesThatTouchEdges:!0};function fu(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={...Qr,...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 r={...
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=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()]}},re={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},係越中文聲。"}},sn=new Map,yo=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 bo(t){try{const e=t.split("-")[0],n=yo[`../../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(wo)}}catch(e){return console.warn(`Failed to load voice data for ${t}:`,e),{language:t,defaultRegion:"",testUtterance:"",voices:[]}}}function Lr(t){return sn.has(t)||sn.set(t,bo(t)),sn.get(t)}const So=["veryLow","low","normal","high","veryHigh"],vo=["android","apple"],wo=t=>({...t,quality:t.quality?.filter(e=>So.includes(e)),localizedName:t.localizedName&&vo.includes(t.localizedName)?t.localizedName:void 0}),Pe={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"},J=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 Pe[e]||e},On=async t=>{if(!t)return[];try{const e=J(t);try{const r=await Lr(e);if(r?.voices?.length)return r.voices}catch(r){console.warn(`Failed to load voices for ${e}:`,r)}const[n]=q(e);if(n!==e)try{const r=await Lr(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),[]}},An=(t,e)=>{try{return new Intl.DisplayNames(e?[e]:[],{type:"language",languageDisplay:"standard"}).of(t)||t.toUpperCase()}catch{return t.toUpperCase()}},$r=t=>{if(!t)return"";try{const e=J(t),n=re[e];if(n?.testUtterance)return n.testUtterance;if(e in Pe){const i=Pe[e];if(i&&re[i]?.testUtterance)return re[i].testUtterance}const[r]=q(e);return r!==e&&re[r]?.testUtterance?re[r].testUtterance:""}catch(e){return console.error(`Error in getTestUtterance for ${t}:`,e),""}},Wt=t=>{if(!t)return"";try{const e=J(t),n=re[e];if(n?.defaultRegion)return`${e}-${n.defaultRegion}`;if(e in Pe){const i=Pe[e];if(i){const s=re[i];if(s?.defaultRegion)return`${i}-${s.defaultRegion}`}}const[r]=q(e);if(r!==e){const i=re[r];if(i?.defaultRegion)return`${r}-${i.defaultRegion}`}return""}catch(e){return console.error(`Failed to get default region for ${t}:`,e),""}},Gt=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=J(s),[a,c]=q(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(re[i]?.availableRegions||[]),a=Array.from(s),c=Array.from(e).filter(u=>o.has(u)&&!a.includes(u)),l=Array.from(new Set([...a,...c])).sort((u,h)=>{const d=r.get(u)??Number.MAX_SAFE_INTEGER,g=r.get(h)??Number.MAX_SAFE_INTEGER;return d-g});if(l.length===0){const u=Wt(i),[,h]=q(u);h&&l.push(h)}return{baseLang:i,regions:l}})},Le=async t=>{const e=new Map;for(const r of t){if(r.source!=="json")continue;const[i]=q(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 On(r),a=new Map;o.forEach((c,l)=>{a.set(c.name.toLowerCase(),l),c.altNames?.forEach(u=>{a.set(u.toLowerCase(),l)})});for(const c of i){const l=c.name.toLowerCase(),u=a.get(l);u!==void 0&&s.set(c.name,u)}s.size>0&&n.set(r,s)}return n},xo={veryLow:1,low:2,normal:3,high:4,veryHigh:5},Nt=t=>t?xo[t]??0:0,pe=(t,e,n,r)=>{const i=Nt(t.quality),s=Nt(e.quality);if(n&&r&&t.source==="json"&&e.source==="json"){const o=n.get(r);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)},Kt=(t,e)=>{const n=new Map(e.map(s=>[s.baseLang,s])),r=new Map,i=[];for(const s of t){const[o]=q(s.language);n.get(o)?(r.has(o)||r.set(o,[]),r.get(o).push(s)):i.push(s)}return{voicesByLang:r,otherLangVoices:i}},rs=(t,e,n,r)=>{const[,i]=q(t.language),[,s]=q(e.language),o=i&&n.regions.includes(i),a=s&&n.regions.includes(s);if(o&&a){const d=n.regions.indexOf(i),g=n.regions.indexOf(s);return d===g?pe(t,e,r,n.baseLang):d-g}if(o)return-1;if(a)return 1;const c=Wt(n.baseLang),[,l]=q(c),u=!!l&&i===l,h=!!l&&s===l;if(u&&!h)return-1;if(!u&&h)return 1;if(i&&s){const d=i.localeCompare(s);return d!==0?d:pe(t,e,r,n.baseLang)}return i?-1:s?1:pe(t,e,r,n.baseLang)},Eo=async(t,e,n)=>{const r=n??await Le(t);t.sort((i,s)=>rs(i,s,e,r))},is=(t,e,n)=>{const[r]=q(t.language),[i]=q(e.language),s=An(r).toLowerCase(),o=An(i).toLowerCase(),a=s.localeCompare(o);if(a!==0)return a;if(r===i){const c=Wt(r),[,l]=q(t.language),[,u]=q(e.language),h=c&&l===c.split("-")[1],d=c&&u===c.split("-")[1];if(h&&!d)return-1;if(!h&&d)return 1;if(l&&u){const g=l.localeCompare(u);if(g!==0)return g}return l&&!u?-1:!l&&u?1:pe(t,e,n,r)}return pe(t,e,n,r)},Tn=async(t,e)=>{const n=e??await Le(t);t.sort((r,i)=>is(r,i,n))},Co=async(t,e)=>{if(!e?.length)return[];const n=Gt(t||[]),{voicesByLang:r,otherLangVoices:i}=Kt(e,n),s=await Le(e),o=[];for(const a of n){const c=r.get(a.baseLang);c&&(await Eo(c,a,s),o.push(...c))}return await Tn(i,s),o.push(...i),o},ko=async(t,e)=>{if(!e.length)return null;const[n]=Gt([t]),{voicesByLang:r,otherLangVoices:i}=Kt(e,[n]),s=r.get(n.baseLang),o=s?.length?s:i,a=await Le(e),c=s?.length?(l,u)=>rs(l,u,n,a):(l,u)=>is(l,u,a);return o.reduce((l,u)=>c(u,l)<0?u:l)},Oo=[{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}],Ao={voices:Oo},To=[{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}],Ro={voices:To},No=Ao,Do=Ro,Rn=(t,e)=>No.voices.some(n=>t.includes(n.name)||e&&n.nativeID?.some(r=>e.includes(r))||n.altNames?.some(r=>t.includes(r))),Nn=(t,e)=>Do.voices.some(n=>t.includes(n.name))||e==="veryLow",_r=t=>t?.length?t.filter(e=>!(e.isNovelty||Rn(e.name,e.voiceURI))):[],Br=t=>t?.length?t.filter(e=>!Nn(e.name,e.quality)):[],Fo={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"}},Io={quality:Fo},Dn={apple:Io.quality},Po=(t,e,n)=>{if(!t)return;const r=Array.isArray(n)?n:n?[n]:[];for(const i of r)if(i&&Dn[i]){const s=Dn[i],o=q(e)[0],a=s[e]||s[o];if(a){const c=t.toLowerCase(),{normal:l,high:u}=a;if(u&&c.includes(u.toLowerCase()))return"high";if(l&&c.includes(l.toLowerCase()))return"normal"}}},Lo=(t,e)=>{const n=Dn[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}},$o={low:{values:["super-compact","compact"],quality:"low"},normal:{values:["enhanced"],quality:"normal"},high:{values:["premium"],quality:"high"}},qr=t=>{if(!t)return;const n=t.toLowerCase().split(/[._-]/);for(const r of Object.values($o))if(r.values.some(i=>n.includes(i)))return r.quality};function _o(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 Bo(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 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 n=P.instance;return e?.languages&&e.languages.length>0&&await n.broadenLanguages(e.languages),n}return P.initializationPromise||(P.initializationPromise=(async()=>{try{const n=new P;P.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=P.toBaseLangSet(e.languages)):n.scopedLanguages=null,n.voices=await n.parseToReadiumSpeechVoices(r),n.isInitialized=!0,n}catch(n){throw P.initializationPromise=null,console.error("Failed to initialize WebSpeechVoiceManager:",n),n}})()),P.initializationPromise}filterBrowserVoicesByLanguages(e,n){if(!n?.length)return e;const r=P.toBaseLangSet(n);return e.filter(i=>{if(!i?.lang)return!1;const s=J(i.lang),[o]=P.extractLangRegionFromBCP47(s);return r.has(o)})}static toBaseLangSet(e){return new Set(e.map(n=>{const r=J(n),[i]=P.extractLangRegionFromBCP47(r);return i}))}async broadenLanguages(e){if(this.scopedLanguages===null)return;const r=[...P.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 q(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 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=Lo(n,"apple");r&&(this.systemLocale=r)}inferVoiceQuality(e,n,r){const i=e.voiceURI?qr(e.voiceURI):void 0;if(i)return i;if(n?.nativeID&&Array.isArray(n.nativeID))for(const s of n.nativeID){const o=qr(s);if(o)return o}if(n?.localizedName&&e.voiceURI&&e.lang){const s=Po(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(Bo(r,s)){const o=_o(r,s);n.set(i,o)}else{const o=Nt(s.quality);Nt(r.quality)>=o&&n.set(i,r)}}return Array.from(n.values())}getTestUtterance(e){if(!e)return"";const n=$r(e);if(n)return n;const[r]=P.extractLangRegionFromBCP47(e);if(r&&r!==e){const i=$r(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 u=J(c.language).split("-")[0];if(!a.has(u)){const h=An(u,e),d=s.filter(g=>J(g.language).split("-")[0]===u).length;o.push({code:u,label:h,count:d}),a.add(u)}}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[,u]=P.extractLangRegionFromBCP47(l.language);u&&c.set(u,(c.get(u)||0)+1)}for(const l of s){const[,u]=P.extractLangRegionFromBCP47(l.language);if(u&&!a.has(u)){let h=l.language;try{const d=e||navigator.language;h=new Intl.DisplayNames([d],{type:"region"}).of(u)||l.language}catch(d){console.warn(`Failed to get display name for region ${u}`,d)}o.push({code:u,label:h,count:c.get(u)||0}),a.add(u)}}return r?o:o.sort((l,u)=>l.label.localeCompare(u.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 u=()=>{if(a<1)return s([]);--a;const h=r();if(Array.isArray(h)&&h.length)return s(h);setTimeout(u,n)};setTimeout(u,n)};window.speechSynthesis.onvoiceschanged!==void 0?window.speechSynthesis.onvoiceschanged=()=>{const u=r();Array.isArray(u)&&u.length?s(u):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=J(i.lang),[o]=P.extractLangRegionFromBCP47(s),a=this.normalizeVoiceName(i.name),c=`${i.lang.toLowerCase()}_${a}`,l=n.get(c)||1;let u=await On(s);(!u||u.length===0)&&(u=await On(o));const h=this.findMatchingJsonVoice(u,a),d=this.inferVoiceQuality(i,h,l);return h?{...h,label:h.label??this.cleanVoiceName(i.name),source:"json",originalName:i.name,language:h.language??s,voiceURI:i.voiceURI,quality:d,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Rn(i.name,i.voiceURI),isLowQuality:Nn(i.name,d)}:{source:"browser",label:this.cleanVoiceName(i.name),name:i.name,originalName:i.name,language:s,voiceURI:i.voiceURI,quality:d,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Rn(i.name,i.voiceURI),isLowQuality:Nn(i.name,d)}}))}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(),u=o.altLanguage?.toLowerCase();if(l===c||u===c)return!0;const[h]=c.split("-");return l&&l.startsWith(h)||u&&u.startsWith(h)}))}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=_r(r)),i.excludeVeryLowQuality&&(r=Br(r)),i.removeDuplicates&&(r=this.removeDuplicates(r)),r}filterOutNoveltyVoices(e){const n=e??this.voices;return _r(n)}filterOutVeryLowQualityVoices(e){const n=e??this.voices;return Br(n)}async sortVoicesByQuality(e){const n=e||this.voices;if(!n?.length)return[];const r=await Le(n);return[...n].sort((i,s)=>pe(i,s,r))}static async sortByDefaultRegion(e,n){const r=await Le(e),i=Wt(n);e.sort((s,o)=>{const[,a]=P.extractLangRegionFromBCP47(s.language),[,c]=P.extractLangRegionFromBCP47(o.language),l=i&&a===i.split("-")[1],u=i&&c===i.split("-")[1];return l&&!u?-1:!l&&u?1:pe(s,o,r,n)})}async sortVoicesByLanguages(e,n){const r=n||this.voices;if(!r?.length)return[];if(!e?.length){const c=[...r];return await Tn(c),c}const i=Gt(e),{voicesByLang:s,otherLangVoices:o}=Kt(r,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 Tn(o),a.push(...o),a}async sortVoicesByRegions(e,n){return Co(e,n||this.voices)}groupVoices(e,n){const r={},i=n||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}r[o]||(r[o]=[]),r[o].push(s)}return r}}const qo=["webKit","moz","ms","o"],Uo=["boundary","end","error","mark","pause","resume","start"],zo=t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`,He=(t={},e)=>Object.hasOwnProperty.call(t,e)||e in t||!!t[e],Vo=t=>typeof window<"u"&&t in window,Mo=t=>{const e=zo(t),n=qo.map(i=>`${i}${e}`),r=[t,e].concat(n).find(Vo);return r&&typeof window<"u"?window[r]:void 0},jo=()=>{const t={};["speechSynthesis","speechSynthesisUtterance","speechSynthesisVoice","speechSynthesisEvent","speechSynthesisErrorEvent"].forEach(n=>{t[n]=Mo(n)}),t.onvoiceschanged=He(t.speechSynthesis,"onvoiceschanged"),t.speechSynthesisSpeaking=He(t.speechSynthesis,"speaking"),t.speechSynthesisPaused=He(t.speechSynthesis,"paused");const e=t.speechSynthesisUtterance?He(t.speechSynthesisUtterance,"prototype"):!1;return Uo.forEach(n=>{const r=`on${n}`;t[r]=e&&t.speechSynthesisUtterance?He(t.speechSynthesisUtterance.prototype,r):!1}),t},Ho=()=>{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()}};let Jt=class{listeners=new Map;on(e,n){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(n),()=>{const r=this.listeners.get(e);if(r){const i=r.indexOf(n);i>-1&&r.splice(i,1)}}}emit(e,n){const r=this.listeners.get(e);r&&[...r].forEach(i=>{try{i(n)}catch(s){console.error(`Error in "${String(e)}" listener:`,s)}})}clear(){this.listeners.clear()}};const Ot=(t,e)=>Math.min(Math.max(t,0),Math.max(e-1,0));function me(t,e,n,r){return Number.isFinite(t)?Math.max(e,Math.min(n,t)):r}function Wo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var an,Ur;function Go(){if(Ur)return an;Ur=1,an=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,u)=>new Map(o(Array.from(l),u))),i.set(Set,(l,u)=>new Set(o(Array.from(l),u))),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,u){const h=Object.keys(l),d=new Array(h.length);for(let g=0;g<h.length;g++){const p=h[g],m=l[p];typeof m!="object"||m===null?d[p]=m:m.constructor!==Object&&(s=i.get(m.constructor))?d[p]=s(m,u):ArrayBuffer.isView(m)?d[p]=t(m):d[p]=u(m)}return d}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 u={};for(const h in l){if(Object.hasOwnProperty.call(l,h)===!1)continue;const d=l[h];typeof d!="object"||d===null?u[h]=d:d.constructor!==Object&&(s=i.get(d.constructor))?u[h]=s(d,a):ArrayBuffer.isView(d)?u[h]=t(d):u[h]=a(d)}return u}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 u={};for(const h in l){const d=l[h];typeof d!="object"||d===null?u[h]=d:d.constructor!==Object&&(s=i.get(d.constructor))?u[h]=s(d,c):ArrayBuffer.isView(d)?u[h]=t(d):u[h]=c(d)}return u}}function n(r){const i=[],s=[],o=new Map;if(o.set(Date,h=>new Date(h)),o.set(Map,(h,d)=>new Map(c(Array.from(h),d))),o.set(Set,(h,d)=>new Set(c(Array.from(h),d))),r.constructorHandlers)for(const h of r.constructorHandlers)o.set(h[0],h[1]);let a=null;return r.proto?u:l;function c(h,d){const g=Object.keys(h),p=new Array(g.length);for(let m=0;m<g.length;m++){const b=g[m],w=h[b];if(typeof w!="object"||w===null)p[b]=w;else if(w.constructor!==Object&&(a=o.get(w.constructor)))p[b]=a(w,d);else if(ArrayBuffer.isView(w))p[b]=t(w);else{const O=i.indexOf(w);O!==-1?p[b]=s[O]:p[b]=d(w)}}return p}function l(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return c(h,l);if(h.constructor!==Object&&(a=o.get(h.constructor)))return a(h,l);const d={};i.push(h),s.push(d);for(const g in h){if(Object.hasOwnProperty.call(h,g)===!1)continue;const p=h[g];if(typeof p!="object"||p===null)d[g]=p;else if(p.constructor!==Object&&(a=o.get(p.constructor)))d[g]=a(p,l);else if(ArrayBuffer.isView(p))d[g]=t(p);else{const m=i.indexOf(p);m!==-1?d[g]=s[m]:d[g]=l(p)}}return i.pop(),s.pop(),d}function u(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return c(h,u);if(h.constructor!==Object&&(a=o.get(h.constructor)))return a(h,u);const d={};i.push(h),s.push(d);for(const g in h){const p=h[g];if(typeof p!="object"||p===null)d[g]=p;else if(p.constructor!==Object&&(a=o.get(p.constructor)))d[g]=a(p,u);else if(ArrayBuffer.isView(p))d[g]=t(p);else{const m=i.indexOf(p);m!==-1?d[g]=s[m]:d[g]=u(p)}}return i.pop(),s.pop(),d}}return an}var Ko=Go();const ss=Wo(Ko);ss();function Fn(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 Oe(t){return typeof t=="string"}function Jo(t){return Number.isFinite(t)}function xe(t){return Number.isSafeInteger(t)&&t>=0}function ae(t){return t!=null}function Xo(t,e){return Fn(t)&&Oe(e)&&e in t}var Yo=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,Qo=typeof self=="object"&&self&&self.Object===Object&&self,sr=Yo||Qo||Function("return this")(),$e=sr.Symbol,as=Object.prototype,Zo=as.hasOwnProperty,el=as.toString,We=$e?$e.toStringTag:void 0;function tl(t){var e=Zo.call(t,We),n=t[We];try{t[We]=void 0;var r=!0}catch{}var i=el.call(t);return r&&(e?t[We]=n:delete t[We]),i}var nl=Object.prototype,rl=nl.toString;function il(t){return rl.call(t)}var sl="[object Null]",al="[object Undefined]",zr=$e?$e.toStringTag:void 0;function os(t){return t==null?t===void 0?al:sl:zr&&zr in Object(t)?tl(t):il(t)}function ls(t){return t!=null&&typeof t=="object"}var ol="[object Symbol]";function ll(t){return typeof t=="symbol"||ls(t)&&os(t)==ol}function cl(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 ul=Array.isArray,Vr=$e?$e.prototype:void 0,Mr=Vr?Vr.toString:void 0;function ar(t){if(typeof t=="string")return t;if(ul(t))return cl(t,ar)+"";if(ll(t))return Mr?Mr.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}var hl=/\s/;function dl(t){for(var e=t.length;e--&&hl.test(t.charAt(e)););return e}var fl=/^\s+/;function gl(t){return t&&t.slice(0,dl(t)+1).replace(fl,"")}function cs(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function us(t){return t}var pl="[object AsyncFunction]",ml="[object Function]",yl="[object GeneratorFunction]",bl="[object Proxy]";function hs(t){if(!cs(t))return!1;var e=os(t);return e==ml||e==yl||e==pl||e==bl}var on=sr["__core-js_shared__"],jr=(function(){var t=/[^.]+$/.exec(on&&on.keys&&on.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function Sl(t){return!!jr&&jr in t}var vl=Function.prototype,wl=vl.toString;function xl(t){if(t!=null){try{return wl.call(t)}catch{}try{return t+""}catch{}}return""}var El=/[\\^$.*+?()[\]{}|]/g,Cl=/^\[object .+?Constructor\]$/,kl=Function.prototype,Ol=Object.prototype,Al=kl.toString,Tl=Ol.hasOwnProperty,Rl=RegExp("^"+Al.call(Tl).replace(El,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Nl(t){if(!cs(t)||Sl(t))return!1;var e=hs(t)?Rl:Cl;return e.test(xl(t))}function Dl(t,e){return t?.[e]}function or(t,e){var n=Dl(t,e);return Nl(n)?n:void 0}function Fl(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 Il=800,Pl=16,Ll=Date.now;function $l(t){var e=0,n=0;return function(){var r=Ll(),i=Pl-(r-n);if(n=r,i>0){if(++e>=Il)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function _l(t){return function(){return t}}var Hr=(function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Bl=Hr?function(t,e){return Hr(t,"toString",{configurable:!0,enumerable:!1,value:_l(e),writable:!0})}:us,ql=$l(Bl);function Ul(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 zl(t){return t!==t}function Vl(t,e,n){for(var r=n-1,i=t.length;++r<i;)if(t[r]===e)return r;return-1}function lr(t,e,n){return e===e?Vl(t,e,n):Ul(t,zl,n)}function Ml(t,e){var n=t==null?0:t.length;return!!n&&lr(t,e,0)>-1}function jl(t,e){return t===e||t!==t&&e!==e}var Wr=Math.max;function Hl(t,e,n){return e=Wr(e===void 0?t.length-1:e,0),function(){for(var r=arguments,i=-1,s=Wr(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),Fl(t,this,a)}}function Wl(t,e){return ql(Hl(t,e,us),t+"")}var Gl=9007199254740991;function Kl(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Gl}function Jl(t){return t!=null&&Kl(t.length)&&!hs(t)}var at=or(Object,"create");function Xl(){this.__data__=at?at(null):{},this.size=0}function Yl(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Ql="__lodash_hash_undefined__",Zl=Object.prototype,ec=Zl.hasOwnProperty;function tc(t){var e=this.__data__;if(at){var n=e[t];return n===Ql?void 0:n}return ec.call(e,t)?e[t]:void 0}var nc=Object.prototype,rc=nc.hasOwnProperty;function ic(t){var e=this.__data__;return at?e[t]!==void 0:rc.call(e,t)}var sc="__lodash_hash_undefined__";function ac(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=at&&e===void 0?sc:e,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=Xl;ye.prototype.delete=Yl;ye.prototype.get=tc;ye.prototype.has=ic;ye.prototype.set=ac;function oc(){this.__data__=[],this.size=0}function Xt(t,e){for(var n=t.length;n--;)if(jl(t[n][0],e))return n;return-1}var lc=Array.prototype,cc=lc.splice;function uc(t){var e=this.__data__,n=Xt(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():cc.call(e,n,1),--this.size,!0}function hc(t){var e=this.__data__,n=Xt(e,t);return n<0?void 0:e[n][1]}function dc(t){return Xt(this.__data__,t)>-1}function fc(t,e){var n=this.__data__,r=Xt(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=oc;Me.prototype.delete=uc;Me.prototype.get=hc;Me.prototype.has=dc;Me.prototype.set=fc;var gc=or(sr,"Map");function pc(){this.size=0,this.__data__={hash:new ye,map:new(gc||Me),string:new ye}}function mc(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Yt(t,e){var n=t.__data__;return mc(e)?n[typeof e=="string"?"string":"hash"]:n.map}function yc(t){var e=Yt(this,t).delete(t);return this.size-=e?1:0,e}function bc(t){return Yt(this,t).get(t)}function Sc(t){return Yt(this,t).has(t)}function vc(t,e){var n=Yt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}function je(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])}}je.prototype.clear=pc;je.prototype.delete=yc;je.prototype.get=bc;je.prototype.has=Sc;je.prototype.set=vc;function wc(t){return t==null?"":ar(t)}function xc(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 Ec(t,e,n){var r=t.length;return n=n===void 0?r:n,!e&&n>=r?t:xc(t,e,n)}var Cc="\\ud800-\\udfff",kc="\\u0300-\\u036f",Oc="\\ufe20-\\ufe2f",Ac="\\u20d0-\\u20ff",Tc=kc+Oc+Ac,Rc="\\ufe0e\\ufe0f",Nc="\\u200d",Dc=RegExp("["+Nc+Cc+Tc+Rc+"]");function Fc(t){return Dc.test(t)}function Ic(t){return t.split("")}var ds="\\ud800-\\udfff",Pc="\\u0300-\\u036f",Lc="\\ufe20-\\ufe2f",$c="\\u20d0-\\u20ff",_c=Pc+Lc+$c,Bc="\\ufe0e\\ufe0f",qc="["+ds+"]",In="["+_c+"]",Pn="\\ud83c[\\udffb-\\udfff]",Uc="(?:"+In+"|"+Pn+")",fs="[^"+ds+"]",gs="(?:\\ud83c[\\udde6-\\uddff]){2}",ps="[\\ud800-\\udbff][\\udc00-\\udfff]",zc="\\u200d",ms=Uc+"?",ys="["+Bc+"]?",Vc="(?:"+zc+"(?:"+[fs,gs,ps].join("|")+")"+ys+ms+")*",Mc=ys+ms+Vc,jc="(?:"+[fs+In+"?",In,gs,ps,qc].join("|")+")",Hc=RegExp(Pn+"(?="+Pn+")|"+jc+Mc,"g");function Wc(t){return t.match(Hc)||[]}function Gr(t){return Fc(t)?Wc(t):Ic(t)}var Gc="__lodash_hash_undefined__";function Kc(t){return this.__data__.set(t,Gc),this}function Jc(t){return this.__data__.has(t)}function Dt(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new je;++e<n;)this.add(t[e])}Dt.prototype.add=Dt.prototype.push=Kc;Dt.prototype.has=Jc;function Xc(t,e){return t.has(e)}function Yc(t){return ls(t)&&Jl(t)}var Qc=200;function Zc(t,e,n,r){var i=-1,s=Ml,o=!0,a=t.length,c=[],l=e.length;if(!a)return c;e.length>=Qc&&(s=Xc,o=!1,e=new Dt(e));e:for(;++i<a;){var u=t[i],h=u;if(u=u!==0?u:0,o&&h===h){for(var d=l;d--;)if(e[d]===h)continue e;c.push(u)}else s(e,h,r)||c.push(u)}return c}function eu(t,e){for(var n=t.length;n--&&lr(e,t[n],0)>-1;);return n}function tu(t,e){for(var n=-1,r=t.length;++n<r&&lr(e,t[n],0)>-1;);return n}function Kr(t,e,n){if(t=wc(t),t&&e===void 0)return gl(t);if(!t||!(e=ar(e)))return t;var r=Gr(t),i=Gr(e),s=tu(r,i),o=eu(r,i)+1;return Ec(r,s,o).join("")}var nu=Wl(function(t,e){return Yc(t)?Zc(t,e):[]}),Ne=function(){return Ne=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},Ne.apply(this,arguments)},ru="~",iu="~~";function cr(t,e){for(var n={},r={},i=t.split(iu),s=!1,o=0;i.length>o;o++){for(var a=i[o].split(ru),c=0;c<a.length;c+=2){var l=a[c],u=a[c+1],h="&"+l+";";n[h]=u,s&&(n["&"+l]=u),r[u]=h}s=!0}return e?{entities:Ne(Ne({},n),e.entities),characters:Ne(Ne({},r),e.characters)}:{entities:n,characters:r}}var ln={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},_e={};_e.xml=cr(`lt~<~gt~>~quot~"~apos~'~amp~&`);_e.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~>`);_e.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~®',_e.html4);var su={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},au=String.fromCodePoint||function(t){return String.fromCharCode(Math.floor((t-65536)/1024)+55296,(t-65536)%1024+56320)},Be=function(){return Be=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},Be.apply(this,arguments)},ou=Be(Be({},_e),{all:_e.html5}),lu={scope:"body",level:"all"},cn=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g,un=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g,Jr={xml:{strict:cn,attribute:un,body:ln.xml},html4:{strict:cn,attribute:un,body:ln.html4},html5:{strict:cn,attribute:un,body:ln.html5}},cu=Be(Be({},Jr),{all:Jr.html5}),bs=String.fromCharCode,uu=bs(65533);function hu(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?uu:c>65535?au(c):bs(su[c]||c)}}return i}function Xr(t,e){var n=e===void 0?lu: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=cu[i][o],c=ou[i].entities,l=o==="attribute",u=o==="strict";return t.replace(a,function(h){return hu(h,c,l,u)})}var du={strictlyTwoElementsInRangeArrays:!1,progressFn:null};function Ft(t,e){if(!Array.isArray(t)||!t.length)return t;let n={...du,...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 Yr={mergeType:1,progressFn:null,joinRangesThatTouchEdges:!0};function fu(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={...Yr,...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 r={...Yr};let i=t.filter(l=>Array.isArray(l)).map(l=>[...l]).filter(l=>l[2]!==void 0||l[0]!==l[1]),s,o,a;r.progressFn?s=Ft(i,{progressFn:l=>{a=Math.floor(l/5),a!==o&&(o=a,r.progressFn(a))}}):s=Ft(i);let c=s.length-1;for(let l=c;l>0;l--)r.progressFn&&(a=Math.floor((1-l/c)*78)+21,a!==o&&a>o&&(o=a,r.progressFn(a))),(s[l][0]<=s[l-1][0]||!r.joinRangesThatTouchEdges&&s[l][0]<s[l-1][1]||r.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?+r.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 gu={},pu=gu.NODE_ENV==="production",Qr="Invariant failed";function mu(t,e){if(!t){if(pu)throw new Error(Qr);var n=Qr;throw new Error(n)}}function yu(t,e,n){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 r;Array.isArray(e)&&Number.isInteger(e[0])&&Number.isInteger(e[1])?r=[Array.from(e)]:r=Array.from(e),r.length,r.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)}.`);r[a][0]=+r[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)}.`);r[a][1]=+r[a][1]}});let i=fu(r,{progressFn:o=>{}});mu(i);let s=i.length;if(s>0){let o=t.slice(i[s-1][1]);t=i.reduce((a,c,l,u)=>{let h=l===0?0:u[l-1][1],d=u[l][0];return`${a}${t.slice(h,d)}${u[l][2]||""}`},""),t+=o}return t}function hn(t,e=1){let n=" ";function r(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 u=0,h="";for(let d=0,g=s.length;d<g;d++)(s[d]===c||s[d]===l&&s[d-1]!==c)&&u++,`\r
|
|
5
|
-
`.includes(s[d])||s[d]===n?s[d]===n?h+=s[d]:s[d]===c?u<=o&&(h+=s[d],s[d+1]===l&&(h+=s[d+1],d++)):s[d]===l&&s?.[d-1]!==c&&u<=o&&(h+=s[d]):!s[d+1]&&!u&&(h+=" ");return h}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)===n)){for(let c=t.length;c--;)if(t[c].trim()){a=t.slice(c+1);break}}return`${i(o,s,!1)}${t.trim()}${r(i(r(a),s,!0))}`}return t}var
|
|
6
|
-
${JSON.stringify(e,null,4)} (type ${typeof e})`);else r={...
|
|
7
|
-
${JSON.stringify(r,null,4)}`);if(
|
|
5
|
+
`.includes(s[d])||s[d]===n?s[d]===n?h+=s[d]:s[d]===c?u<=o&&(h+=s[d],s[d+1]===l&&(h+=s[d+1],d++)):s[d]===l&&s?.[d-1]!==c&&u<=o&&(h+=s[d]):!s[d+1]&&!u&&(h+=" ");return h}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)===n)){for(let c=t.length;c--;)if(t[c].trim()){a=t.slice(c+1);break}}return`${i(o,s,!1)}${t.trim()}${r(i(r(a),s,!0))}`}return t}var Zr={mergeType:1,progressFn:null,joinRangesThatTouchEdges:!0};function bu(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={...Zr,...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] resolvedOpts.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] resolvedOpts.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] resolvedOpts.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(`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 r={...Zr};let i=t.filter(l=>Array.isArray(l)).map(l=>[...l]).filter(l=>l[2]!==void 0||l[0]!==l[1]),s,o,a;r.progressFn?s=Ft(i,{progressFn:l=>{a=Math.floor(l/5),a!==o&&(o=a,r.progressFn!=null&&r.progressFn(a))}}):s=Ft(i);let c=s.length-1;for(let l=c;l>0;l--)r.progressFn&&(a=Math.floor((1-l/c)*78)+21,a!==o&&a>o&&(o=a,r.progressFn(a))),(s[l][0]<=s[l-1][0]||!r.joinRangesThatTouchEdges&&s[l][0]<s[l-1][1]||r.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?+(r||{})?.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 Su={limitToBeAddedWhitespace:!1,limitLinebreaksCount:1,mergeType:1},vu=class{constructor(e){let n={...Su,...e};if(n.mergeType&&n.mergeType!==1&&n.mergeType!==2)if(Oe(n.mergeType)&&n.mergeType.trim()==="1")n.mergeType=1;else if(Oe(n.mergeType)&&n.mergeType.trim()==="2")n.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 n.mergeType}", equal to ${JSON.stringify(n.mergeType,null,4)}`);this.opts=n,this.ranges=[]}ranges;opts;add(e,n,r){if(e==null&&n==null)return;if(ae(e)&&!ae(n)){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&&xe(+e[0])&&xe(+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(n,null,0)})`)}else if(!ae(e)&&ae(n))throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_13] the second input argument, "to" is set (${JSON.stringify(n,null,0)}) but first-one, "from" is not (${JSON.stringify(e,null,0)})`);let i=+e,s=+n;if(xe(i)&&xe(s)){if(ae(r)&&!Oe(r)&&!Jo(r))throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_08] The third argument, the value to add, was given not as string but ${typeof r}, equal to:
|
|
7
|
+
${JSON.stringify(r,null,4)}`);if(ae(this.ranges)&&Array.isArray(this.last())&&i===this.last()[1]){if(this.last()[1]=s,this.last()[2],this.last()[2]!==null&&ae(r)){let o=this.last()[2]&&this.last()[2].length&&(!this.opts?.mergeType||this.opts.mergeType===1)?`${this.last()[2]}${r}`:r;this.opts.limitToBeAddedWhitespace&&(o=hn(o,this.opts.limitLinebreaksCount)),Oe(o)&&!o.length||(this.last()[2]=o)}}else{this.ranges||(this.ranges=[]);let o=r!==void 0&&!(Oe(r)&&!r.length)?[i,s,r&&this.opts.limitToBeAddedWhitespace?hn(r,this.opts.limitLinebreaksCount):r]:[i,s];this.ranges.push(o)}}else throw xe(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,n,r){this.add(e,n,r)}current(){return Array.isArray(this.ranges)&&this.ranges.length?(this.ranges=bu(this.ranges,{mergeType:this.opts.mergeType}),this.ranges&&this.opts.limitToBeAddedWhitespace?this.ranges.map(e=>ae(e[2])?[e[0],e[1],hn(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])&&xe(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}};ss();var dn=" ";function wu({str:t,idx:e=0,stopAtNewlines:n=!1,stopAtRawNbsp:r=!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()||n&&`
|
|
8
8
|
\r`.includes(t[e+1])||r&&t[e+1]===dn))return e+1;if(t[e+2]&&(t[e+2].trim()||n&&`
|
|
9
9
|
\r`.includes(t[e+2])||r&&t[e+2]===dn))return e+2;for(let i=e+1,s=t.length;i<s;i++)if(t[i].trim()||n&&`
|
|
10
|
-
\r`.includes(t[i])||r&&t[i]===dn)return i;return null}function Y(t,e=0){return wu({str:t,idx:e,stopAtNewlines:!1,stopAtRawNbsp:!1})}function xu(t){return/[-_A-Za-z0-9]/.test(t)}function
|
|
11
|
-
`)&&
|
|
10
|
+
\r`.includes(t[i])||r&&t[i]===dn)return i;return null}function Y(t,e=0){return wu({str:t,idx:e,stopAtNewlines:!1,stopAtRawNbsp:!1})}function xu(t){return/[-_A-Za-z0-9]/.test(t)}function ei(t,e){if(!t)return[];if(Array.isArray(t))return t.filter(n=>typeof n=="string"&&n.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 mt(t,e,n,r){for(let i=e,s=t.length;i<s;i++){if(t.startsWith(n,i))return!0;if(t.startsWith(r,i))return!1}return!1}function ti(t,e,n){return t?.quotes,t?.quotes?.value&&mt(e,n+1,t.quotes.value,">"),t?.quotes?.next,mt(e,t?.quotes?.next-1,t?.quotes?.value,">"),!t?.quotes||!mt(e,n+1,t.quotes.value,">")&&t?.quotes?.next!==-1&&mt(e,t?.quotes?.next-1,t?.quotes?.value,">")}function Eu(t,e){return(e.match(new RegExp(t,"g"))||[]).length}var Ge=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"]),fn=new Set(["a","b","i","p","q","s","u"]),gn=new Set([".",",",";","!","?"]),ni=new Set([".",",","?",";",")","…",'"',"»"]),Cu=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"]),ri={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 Ss(t,e){let n=Date.now(),r=[],i=[],s=[],o=[],a={};function c(){a={attributes:[]}}c();let l=null,u=null,h=null,d=!1,g={},p={tagName:"",hrefValue:"",openingTagEnds:void 0},m="",b=!1,w=null,O=!0;function S(f,v,C){if(Array.isArray(v.stripTogetherWithTheirContents)&&(v.stripTogetherWithTheirContents.includes(a.name)||v.stripTogetherWithTheirContents.includes("*")))if(a.slashPresent&&Array.isArray(r)&&r.some(E=>E.name===a.name)){for(let E=r.length;E--;)if(r[E].name===a.name){o=o.filter(([N,B])=>(N<r[E].lastOpeningBracketAt||N>=f+1)&&(B<=r[E].lastOpeningBracketAt||B>f+1));let F=f+1;a.lastClosingBracketAt&&(F=a.lastClosingBracketAt+1),o.push([r[E].lastOpeningBracketAt,F]),ni.has(t[f])&&v.cb?v.cb({tag:a,deleteFrom:r[E].lastOpeningBracketAt,deleteTo:f+1,insert:null,rangesArr:C,proposedReturn:[r[E].lastOpeningBracketAt,f,null]}):v.cb&&v.cb({tag:a,deleteFrom:r[E].lastOpeningBracketAt,deleteTo:f,insert:"",rangesArr:C,proposedReturn:[r[E].lastOpeningBracketAt,f,""]}),r.splice(E,1);break}}else a.slashPresent||r.push(a);else Array.isArray(v.ignoreTagsWithTheirContents)&&X(f,v,a)&&(O=!1)}function x(f,v,C,E,F,N){if(Array.isArray(k.current())&&typeof C=="number"&&k.current()[0][0]===0&&k.current()[0][1]>=C)return"";if(t.length===E&&N&&!y?.dumpLinkHrefsNearby?.enabled)return null;let B="";if(Number.isInteger(C)&&C<F&&(B+=f.slice(C,F)),Number.isInteger(E)&&E>N+1){let Z=f.slice(N+1,E);E&&!Y(t,E-1)&&(Z=Z.trimEnd()),Z.includes(`
|
|
11
|
+
`)&&I(E,f)?B+=" ":B+=Z}let we=!ni.has(f[v]),Ir=f[E-1]!==">"||!f[C].trim(),Pr=!['"',"("].includes(f[F-1]),mo=![";",".",":","!"].includes(f[v]);if((we||Ir&&Pr&&mo)&&(Ir||Pr)&&f[v]!=="!"&&(!Cu.has(a.name)||typeof C=="number"&&C<F||typeof E=="number"&&E>N+1)){let Z=B.match(/\n/g);return Array.isArray(Z)&&Z.length?Z.length===1?`
|
|
12
12
|
`:Z.length===2?`
|
|
13
13
|
|
|
14
14
|
`:`
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
`:" "}return""}function
|
|
17
|
+
`:" "}return""}function R(f,v){if(f.dumpLinkHrefsNearby?.enabled&&p.tagName&&p.tagName===a.name&&a.lastOpeningBracketAt&&(p.openingTagEnds&&a.lastOpeningBracketAt>p.openingTagEnds||!p.openingTagEnds)&&(b=!0),b){let C=f.dumpLinkHrefsNearby?.putOnNewLine?`
|
|
18
18
|
|
|
19
|
-
`:"";m=`${C}${p.hrefValue}`,(typeof v!="number"||Y(t,v-1))&&(m+=C)}}function
|
|
19
|
+
`:"";m=`${C}${p.hrefValue}`,(typeof v!="number"||Y(t,v-1))&&(m+=C)}}function I(f,v){return v?v[f]==="<"&&v[f+1]!=="%":t[f]==="<"&&t[f+1]!=="%"}function L(f){return t[f]===">"&&t[f-1]!=="%"}function X(f,v,C){if(v.ignoreTagsWithTheirContents.includes("*"))return!0;let E=t.indexOf(`<${C.name}`,f),F=t.indexOf(`</${C.name}`,f);return!C.slashPresent&&F===-1||C.slashPresent&&!i.some(N=>N.name===C.name)||F>-1&&E>-1&&E<F?!1:v.ignoreTagsWithTheirContents.includes(C.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
20
|
${JSON.stringify(t,null,4)}`);if(e)if(Fn(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 M(){b&&(p={tagName:"",hrefValue:"",openingTagEnds:void 0},b=!1)}let y={...
|
|
22
|
-
`.includes(t[f])){let v=a.lastClosingBracketAt===f?f+1:f;y.trimOnlySpaces&&v===U-1&&
|
|
21
|
+
${JSON.stringify(e,null,4)}`);function M(){b&&(p={tagName:"",hrefValue:"",openingTagEnds:void 0},b=!1)}let y={...ri,...e,dumpLinkHrefsNearby:Object.assign({},ri.dumpLinkHrefsNearby,e?.dumpLinkHrefsNearby)};if(Xo(y,"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(y.reportProgressFunc){if(typeof y.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 y.reportProgressFuncFrom}, equal to ${JSON.stringify(y.reportProgressFuncFrom,null,4)}`);if(typeof y.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 y.reportProgressFuncTo}, equal to ${JSON.stringify(y.reportProgressFuncTo,null,4)}`)}y.ignoreTags=ei(y.ignoreTags,"resolvedOpts.ignoreTags"),y.onlyStripTags=ei(y.onlyStripTags,"resolvedOpts.onlyStripTags");let pt=!!y.onlyStripTags.length;y.onlyStripTags.length&&y.ignoreTags.length&&(y.onlyStripTags=nu(y.onlyStripTags,...y.ignoreTags)),y.stripTogetherWithTheirContents?typeof y.stripTogetherWithTheirContents=="string"&&y.stripTogetherWithTheirContents.length&&(y.stripTogetherWithTheirContents=[y.stripTogetherWithTheirContents]):y.stripTogetherWithTheirContents=[];let ue={};if(y.stripTogetherWithTheirContents&&Array.isArray(y.stripTogetherWithTheirContents)&&y.stripTogetherWithTheirContents.length&&!y.stripTogetherWithTheirContents.every((f,v)=>typeof f!="string"?(ue.el=f,ue.i=v,!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 ${ue.i} has a value ${ue.el} which is not string but ${(typeof ue.el).toLowerCase()}.`);y.cb||(y.cb=({rangesArr:f,proposedReturn:v})=>{v&&f.push(...v)});let k=new vu({limitToBeAddedWhitespace:!0,limitLinebreaksCount:2});if(!y.skipHtmlDecoding)for(;t!==Xr(t,{scope:"strict"});)t=Xr(t,{scope:"strict"});let _=!1,G=!1,z=0,H=0,U=t.length,ve=Math.floor(U/2);for(let f=0;f<U;f++){if(y.reportProgressFunc&&(U>1e3&&U<2e3?f===ve&&y.reportProgressFunc(Math.floor((y.reportProgressFuncTo-y.reportProgressFuncFrom)/2)):U>=2e3&&(z=y.reportProgressFuncFrom+Math.floor(f/U*(y.reportProgressFuncTo-y.reportProgressFuncFrom)),z!==H&&(H=z,y.reportProgressFunc(z)))),Object.keys(a).length>1&&a.lastClosingBracketAt&&a.lastClosingBracketAt<f&&t[f]!==" "&&w===null&&(w=f),!_&&t[f]==="%"&&t[f-1]==="{"&&t.includes("%}",f+1)){h=null;let v=t.indexOf("%}",f)-1;if(v>f){f=v;continue}}if(!_&&L(f)&&(!a||Object.keys(a).length<2)&&f>1){for(let v=f;v--;)if(t[v-1]===void 0||L(v)){let C=t[v-1]===void 0?v:v+1,E=t.slice(C,f+1)||"";if((E.includes("/>")||E.includes("/ >")||E.includes('="')||E.includes("='"))&&t!==`<${Kr(E.trim(),"/>")}>`&&[...Ge].some(F=>Kr(E.trim().split(/\s+/).filter(N=>N.trim()).filter((N,B)=>B===0),"/>").toLowerCase()===F)&&Ss(`<${E.trim()}>`,y).result===""){(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([C,f+1]),(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([C,f+1]);let F=x(t,f,C,f+1,C,f+1),N=f+1;if(t[N]&&!t[N].trim()){for(let B=N;B<U;B++)if(t[B].trim()){N=B;break}}y.cb({tag:a,deleteFrom:C,deleteTo:N,insert:F,rangesArr:k,proposedReturn:[C,N,F]})}break}}if(!G&&t[f]==="/"&&!a.quotes?.value&&Number.isInteger(a.lastOpeningBracketAt)&&!Number.isInteger(a.lastClosingBracketAt)&&(a.slashPresent=f),t[f]==='"'||t[f]==="'")if(!G&&a.nameStarts&&a?.quotes?.value===t[f])if(g.valueStarts===void 0)g={},delete a.quotes;else{g.valueEnds=f,g.value=t.slice(g.valueStarts,f),a.attributes.push(g),g={},delete a.quotes;let v;y.dumpLinkHrefsNearby?.enabled&&!r.length&&a.attributes.some(C=>{if(typeof C.name=="string"&&C.name.toLowerCase()==="href")return v=`${y.dumpLinkHrefsNearby?.wrapHeads||""}${C.value}${y.dumpLinkHrefsNearby?.wrapTails||""}`,!0})&&(p={tagName:a.name,hrefValue:v,openingTagEnds:void 0})}else!G&&!a.quotes&&a.nameStarts&&(a.quotes={},a.quotes.value=t[f],a.quotes.start=f,a.quotes.next=t.indexOf(t[f],f+1),g.nameStarts&&g.nameEnds&&g.nameEnds<f&&g.nameStarts<f&&!g.valueStarts&&(g.name=t.slice(g.nameStarts,g.nameEnds)));if(a.nameStarts!==void 0&&a.nameEnds===void 0&&(!t[f].trim()||!xu(t[f]))){if(a.nameEnds=f,a.name=t.slice(a.nameStarts,a.nameEnds+(!L(f)&&t[f]!=="/"&&t[f+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"&&(G=!0),I(f)){R(y);let v=x(t,f,a.leftOuterWhitespace,f,a.lastOpeningBracketAt,f);(y.stripTogetherWithTheirContents.includes(a.name)||y.stripTogetherWithTheirContents.includes("*"))&&(o=o.filter(([C,E])=>!(C===a.leftOuterWhitespace&&E===f))),y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:f,insert:`${v}${m}${v}`,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,f,`${v}${m}${v}`]}),M(),S(f,y,k)}}if(a.quotes?.start&&a.quotes.start<f&&!a.quotes.end&&g.nameEnds&&g.equalsAt&&!g.valueStarts&&(g.valueStarts=f),!a.quotes&&g.nameEnds&&t[f]==="="&&!g.valueStarts&&!g.equalsAt&&(g.equalsAt=f),!a.quotes&&g.nameStarts&&g.nameEnds&&!g.valueStarts&&t[f].trim()&&t[f]!=="="&&(a.attributes.push(g),g={}),!a.quotes&&g.nameStarts&&!g.nameEnds&&(G&&`'"`.includes(t[g.nameStarts])?g.nameStarts<f&&t[f]===t[g.nameStarts]&&(g.nameEnds=f+1,g.name=t.slice(g.nameStarts,g.nameEnds)):t[f].trim()?t[f]==="="?g.equalsAt||(g.nameEnds=f,g.equalsAt=f,g.name=t.slice(g.nameStarts,g.nameEnds)):t[f]==="/"||L(f)?(g.nameEnds=f,g.name=t.slice(g.nameStarts,g.nameEnds),a.attributes.push(g),g={}):I(f)&&(g.nameEnds=f,g.name=t.slice(g.nameStarts,g.nameEnds),a.attributes.push(g),g={}):(g.nameEnds=f,g.name=t.slice(g.nameStarts,g.nameEnds))),!a.quotes&&a.nameEnds<f&&!t[f-1].trim()&&t[f].trim()&&!"<>/!".includes(t[f])&&!g.nameStarts&&!a.lastClosingBracketAt&&(g.nameStarts=f),a.lastOpeningBracketAt!==null&&a.lastOpeningBracketAt<f&&t[f]==="/"&&a.onlyPlausible&&(a.onlyPlausible=!1),a.lastOpeningBracketAt!==null&&a.lastOpeningBracketAt<f&&t[f]!=="/"&&(a.onlyPlausible===void 0&&((!t[f].trim()||I(f))&&!a.slashPresent?a.onlyPlausible=!0:a.onlyPlausible=!1),t[f].trim()&&a.nameStarts===void 0&&!I(f)&&t[f]!=="/"&&!L(f)&&t[f]!=="!"&&(a.nameStarts=f,a.nameContainsLetters=!1)),a.nameStarts&&!a.quotes&&typeof t[f]=="string"&&t[f].toLowerCase()!==t[f].toUpperCase()&&(a.nameContainsLetters=!0),L(f)&&(ti(a,t,f)||a.quotes.value&&typeof a.lastOpeningBracketAt=="number"&&Eu(a.quotes.value,t.slice(a.lastOpeningBracketAt,f))%2===1&&!t.slice(a.lastOpeningBracketAt+1,f).includes("<")&&!t.slice(a.lastOpeningBracketAt+1,f).includes(">"))&&a.lastOpeningBracketAt!==void 0&&(a.lastClosingBracketAt=f,w=null,Object.keys(g).length&&(a.attributes.push(g),g={}),y.dumpLinkHrefsNearby?.enabled&&p.tagName&&!p.openingTagEnds&&(p.openingTagEnds=f)),(!G||t[f]===">")&&a.lastOpeningBracketAt!==void 0){if(a.lastClosingBracketAt===void 0){if(a.lastOpeningBracketAt<f&&!I(f)&&(t[f+1]===void 0||I(f+1)&&!a?.quotes?.value)&&a.nameContainsLetters&&typeof a.nameStarts=="number"){if(a.name=t.slice(a.nameStarts,a.nameEnds||f+1).toLowerCase(),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,f+1]),y.ignoreTags.includes(a.name)||X(f,y,a)||!Ge.has(a.name)&&(a.onlyPlausible||y.stripRecognisedHTMLOnly)){a={},g={};continue}if((Ge.has(a.name)||fn.has(a.name))&&(a.onlyPlausible===!1||a.onlyPlausible===!0&&a.attributes.length)||t[f+1]===void 0){R(y);let v=x(t,f,a.leftOuterWhitespace,f+1,a.lastOpeningBracketAt,a.lastClosingBracketAt);_&&a.name==="script"&&a.slashPresent&&(_=!1);let C;v===null||m===null?C=null:C=`${v}${m}${v}`,y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:f+1,insert:C,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,f+1,C]}),M(),S(f,y,k)}if(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt&&o[o.length-1][1]!==f+1)if(y.stripTogetherWithTheirContents.includes(a.name)||y.stripTogetherWithTheirContents.includes("*")){let v;for(let C=r.length;C--;)r[C].name===a.name&&(v=r[C]);v?(o=o.filter(([C])=>C!==v.lastOpeningBracketAt),o.push([v.lastOpeningBracketAt,f+1])):o.push([a.lastOpeningBracketAt,f+1])}else o.push([a.lastOpeningBracketAt,f+1])}}else if(f>a.lastClosingBracketAt&&t[f].trim()||t[f+1]===void 0||y.ignoreIndentations&&`\r
|
|
22
|
+
`.includes(t[f])){let v=a.lastClosingBracketAt===f?f+1:f;y.trimOnlySpaces&&v===U-1&&w!==null&&w<f&&(v=w),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,a.lastClosingBracketAt+1]);let C=y.ignoreTags.includes(a.name),E=X(f,y,a);if(!O||y.stripRecognisedHTMLOnly&&typeof a.name=="string"&&!Ge.has(a.name.toLowerCase())&&!fn.has(a.name.toLowerCase())||!pt&&(C||E)||pt&&!y.onlyStripTags.includes(a.name)||y.ignoreTagsWithTheirContents.includes(a.name)){if(E)if(a.slashPresent){for(let F=i.length;F--;)if(i[F].name===a.name){i.splice(F,1);break}i.length||(O=!0)}else O&&(O=!1),i.push(a);y.cb({tag:a,deleteFrom:null,deleteTo:null,insert:null,rangesArr:k,proposedReturn:null}),a={},g={}}else if(!a.onlyPlausible||a.attributes.length===0&&a.name&&(Ge.has(a.name.toLowerCase())||fn.has(a.name.toLowerCase()))||a.attributes?.some(F=>F.equalsAt)){(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([a.lastOpeningBracketAt,a.lastClosingBracketAt+1]);let F=x(t,f,a.leftOuterWhitespace,v,a.lastOpeningBracketAt,a.lastClosingBracketAt);m="",b=!1,R(y,v);let N;typeof m=="string"&&m.length?(N=`${F}${m}${F===`
|
|
23
23
|
|
|
24
24
|
`?`
|
|
25
|
-
`:
|
|
26
|
-
`)?B+=we-f:(!we||we>f)&&B++}y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:v+B,insert:N,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,v+B,N]}),M(),S(f,y,k)}else a={};L(f)||(a={})}G&&(G=!1)}if((!_||t[f]==="<"&&Y(t,Y(t,f))&&t[Y(t,f)]==="/"&&t.startsWith("script",Y(t,Y(t,f))))&&
|
|
27
|
-
`||t[f]==="\r")&&(h=f,d&&(d=!1))):(l!==null&&(!a.quotes&&g.equalsAt>l-1&&g.nameEnds&&g.equalsAt>g.nameEnds&&t[f]!=='"'&&t[f]!=="'"&&(Fn(g)&&a.attributes.push(g),g={},a.equalsSpottedAt=void 0),l=null),d||(d=!0,A&&!_&&typeof h=="number"&&f&&h<f-1&&(t.slice(h+1,f).trim()?h=null:y.ignoreIndentations||k.push([h+1,f])))),t[f]===" "?u===null&&(u=f):u!==null&&(u=null),a.name==="script"&&(_=!a.slashPresent)}if(t&&!y.ignoreIndentations&&(y.trimOnlySpaces&&t[0]===" "||!y.trimOnlySpaces&&!t[0].trim()))for(let f=0;f<U;f++)if(y.trimOnlySpaces&&t[f]!==" "||!y.trimOnlySpaces&&t[f].trim()){k.push([0,f]);break}else t[f+1]||k.push([0,f+1]);if(t&&(y.trimOnlySpaces&&t[~-t.length]===" "||!y.trimOnlySpaces&&!t[~-t.length].trim())){for(let f=t.length;f--;)if(y.trimOnlySpaces&&t[f]!==" "||!y.trimOnlySpaces&&t[f].trim()){k.push([f+1,U]);break}}let K=k.current();if(!e?.cb&&K&&(K[0]&&!K[0][0]&&(K[0][1],k.ranges[0]=[k.ranges[0][0],k.ranges[0][1]]),K[K.length-1]?.[1]===t.length&&(K[K.length-1][0],k.ranges))){let f=k.ranges[k.ranges.length-1][0];t[f-1]&&(y.trimOnlySpaces&&t[f-1]===" "||!y.trimOnlySpaces&&!t[f-1].trim())&&(f-=1);let v=k.ranges[k.ranges.length-1][2];k.ranges[k.ranges.length-1]=[f,k.ranges[k.ranges.length-1][1]],v?.trim()&&k.ranges[k.ranges.length-1].push(v.trimEnd())}return{log:{timeTakenInMilliseconds:Date.now()-n},result:yu(t,k.current()),ranges:k.current(),allTagLocations:s,filteredTagLocations:o}}class Ln{speechSynthesis;speechSynthesisUtterance;currentVoice=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Jt;voiceManager=null;voices=[];defaultVoice=null;speakInContentLanguage=!1;languageVoiceCache=new Map;warmingLanguages=new Map;speakGeneration=0;resumeInfinityTimer;isSpeakingInternal=!1;restartPending=!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=jo(),this.patches=Ho(),!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 P.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]=q(n),[s,o]=q(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=J(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=>J(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 P.initialize({languages:[o]}),this.voices=this.voiceManager.getVoices();const c=this.voices.filter(h=>this.voiceMatchesLanguage(h,o)),u=(await this.voiceManager.sortVoicesByQuality(c))[0]??null;this.languageVoiceCache.set(o,u),u||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?Ss(n.ssml).result:"")}))}loadUtterances(e,n){this.currentUtterances=this.toPlainText(e),this.currentUtteranceIndex=kt(n??0,e.length),this.warmLanguageVoiceCache(this.currentUtterances),this.playbackState="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.restartPending=!1,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>=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.cancelCurrentSpeech(),this.speakGeneration++,this.currentUtteranceIndex=0,this.patches.isAndroid&&(this.isAndroidPaused=!1),this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){const n=me(e,.1,10,this.rate);n!==this.rate&&(this.rate=n,this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const n=me(e,0,2,this.pitch);n!==this.pitch&&(this.pitch=n,this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const n=me(e,0,1,this.volume);n!==this.volume&&(this.volume=n,this.scheduleRestartIfSpeaking())}getVolume(){return this.volume}scheduleRestartIfSpeaking(){!this.isSpeakingInternal||this.restartPending||(this.restartPending=!0,queueMicrotask(()=>{this.restartPending&&(this.restartPending=!1,this.isSpeakingInternal&&this.speak(this.currentUtteranceIndex))}))}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.events.on(e,n)}emitEvent(e){this.events.emit(e.type,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.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[],this.defaultVoice=null,this.languageVoiceCache.clear(),this.warmingLanguages.clear(),this.initialized=!1}}class ku{id="webspeech";name="Web Speech API";voiceEngine=null;async getVoices(){return this.voiceEngine||(this.voiceEngine=new Ln,await this.voiceEngine.initialize()),this.voiceEngine.getAvailableVoices()}async createEngine(e){const n=new Ln;return await n.initialize(),e&&await n.setVoice(e),n}async destroy(){this.voiceEngine&&(await this.voiceEngine.destroy(),this.voiceEngine=null)}}const De="\\p{Pe}\\p{Pf}.,;:!?,。、;:!?،؛؟",$n="\\p{Ps}\\p{Pi}¿¡",Ou=new RegExp(`^[${De}]`,"u"),Au=new RegExp(`^[${$n}]`,"u");function Qt(t){return Ou.test(t)}function Tu(t){return Au.test(t)}function vs(t,e){const n=[];let r=-1,i=-1;const s=()=>{r!==-1&&(n.push({text:Ru(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 Ru(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 ws=new RegExp(`[^${De}]*[${De}]+\\s*|[^${De}]+$`,"gu"),Nu=/\S+\s*|\s+/g;function ur(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 hr(t,e){if(t.text.length<=e||t.atomic)return[t];const n=ur(t.text,t.offset,Nu);if(n.length>1)return n.flatMap(o=>hr(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 xs(t,e){if(t.length<=e)return[{text:t,offset:0}];const r=ur(t,0,ws).flatMap(i=>hr(i,e));return vs(r,e)}const Du=/<([a-zA-Z][\w-]*)\b[^>]*>[\s\S]*?<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function Es(t,e){if(t.length<=e)return[{text:t,offset:0}];const n=[];for(const i of t.matchAll(Du))i[0][0]==="<"?n.push({text:i[0],offset:i.index,atomic:!0}):n.push(...ur(i[0],i.index,ws));const r=n.flatMap(i=>hr(i,e));return vs(r,e)}const Fu={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 Cs(t){return Fu[t]??`audio/${t}`}const Iu=["flac","wav","opus","aac","ogg","webm","mp3"],Pu=["opus","aac","webm","ogg","mp3","wav","flac"];function ks(t,e,n){const r=a=>n(Cs(a))!=="",i=t.formats.filter(r);if(e.preferredFormat&&i.includes(e.preferredFormat))return e.preferredFormat;const s=e.strategy==="bandwidth"?Pu:Iu,o=[...s,...i.filter(a=>!s.includes(a))];for(const a of o)if(i.includes(a))return a;return t.default}const Lu=new Set(["wav","flac"]),$u={mp3:48e3,opus:24e3,aac:48e3,ogg:48e3,webm:32e3};function Os(t,e,n){return Lu.has(t)||!e||!n?void 0:n.saveData===!0||/2g/.test(n.effectiveType??"")?$u[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 qe 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}}class fr extends qe{constructor(e){super(e,{status:408,type:"https://readium.org/speech-server/error#stall",title:"Synthesis Stalled"}),this.name="SpeechServerStallError"}}class gr extends Error{constructor(e){super(e),this.name="SpeechServerAudioDecodeError"}}class pr extends Error{constructor(e){super(e),this.name="SpeechServerNetworkError"}}async function Fe(t){if((t.headers.get("content-type")??"").includes("application/problem+json"))try{const n=await t.json();return new qe(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 qe(`Request failed with status ${t.status}`,{status:t.status})}const _u=3,Bu=400;function qu(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 Uu(t){return me(t,.25,4,1)}function mt(t){return t?.plain??t?.ssml??void 0}function si(t){return t instanceof fr?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance,recoverable:!0}:t instanceof qe?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance,recoverable:!1}:t instanceof gr?{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 As{endpoints;fetchImpl;currentVoice=null;voices=[];serviceInfo=null;serviceInfoPromise=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Jt;speakInContentLanguage=!1;speakGeneration=0;loadGeneration=0;prefetchWindow;readyBufferChars;overLengthText;timeoutMs;formatOptions;canPlayType;prefetchCache=new Map;prefetchChainTail=Promise.resolve();activeControllers=new Set;liveControllers=new Set;isSpeakingInternal=!1;restartPending=!1;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??_u,this.readyBufferChars=e.readyBufferChars??Bu,this.overLengthText=e.overLengthText??"split",this.timeoutMs=e.timeoutMs,this.formatOptions=e.format??{},this.canPlayType=typeof Audio<"u"?n=>new Audio().canPlayType(n):()=>""}setAvailableVoices(e){this.voices=e}async fetchNetwork(e,n){try{return await this.fetchImpl(e,n)}catch(r){throw r instanceof TypeError?new pr(r.message):r}}loadUtterances(e,n){this.abortLiveControllers(),this.clearPrefetchCache(),this.currentUtterances=e,this.currentUtteranceIndex=kt(n??0,e.length),this.setState("loading"),this.bufferUntilReady(++this.loadGeneration)}async bufferUntilReady(e){const n=kt(this.currentUtteranceIndex,this.currentUtterances.length),r=Math.min(this.indexCoveringChars(this.readyBufferChars,n),n+this.prefetchWindow),i=[];for(let s=n;s<=r;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,n){if(this.currentUtterances.length===0)return-1;const r=kt(n,this.currentUtterances.length);let i=0;for(let s=r;s<this.currentUtterances.length;s++)if(i+=(mt(this.currentUtterances[s])??"").length,i>=e)return s;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.abortLiveControllers(),this.clearPrefetchCache()}getCurrentVoice(){return this.currentVoice}async getAvailableVoices(){if(this.voices.length>0)return this.voices;const[e,n]=await Promise.all([this.fetchNetwork(this.endpoints.voices),this.getServiceInfo()]);if(!e.ok)throw await Fe(e);const r=await e.json(),i=new Map(n.providers.map(s=>[s.id,s.controls]));return this.voices=r.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 Fe(e);return e.json()}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,this.abortLiveControllers(),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.restartPending=!1,this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.stopAudio(),this.abortLiveControllers();const n=++this.speakGeneration;this.isSpeakingInternal=!0,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.isSpeakingInternal=!1,this.setState("idle"),this.emitEvent({type:"error",detail:si(r)})}}async resolveSynthesisStream(e){const n=this.prefetchCache.get(e);if(n){this.prefetchCache.delete(e);try{const r=await n;for(const{controller:i}of r)this.activeControllers.delete(i),this.liveControllers.add(i);return r}catch{}}return this.synthesizeStream(e,!1)}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,!0));this.prefetchCache.set(e,n),this.prefetchChainTail=n.then(r=>Promise.all(r.map(i=>i.promise))).then(()=>{},()=>{}),n.catch(()=>{}),n.then(r=>r.forEach(i=>i.promise.catch(()=>{}))).catch(()=>{})}clearPrefetchCache(){this.prefetchCache.clear(),this.activeControllers.forEach(e=>e.abort()),this.activeControllers.clear()}abortLiveControllers(){this.liveControllers.forEach(e=>e.abort()),this.liveControllers.clear()}async synthesizeStream(e,n){const r=this.currentUtterances[e],i=!r.plain&&!!r.ssml,s=this.speakInContentLanguage?r.language:void 0,o=mt(r)??"",a=mt(this.currentUtterances[e-1]),c=mt(this.currentUtterances[e+1]),l=await this.getServiceInfo(),u=ks(l.output,this.formatOptions,this.canPlayType),h=navigator.connection,d=Os(u,this.formatOptions.adaptBitrateToNetwork??!1,h);if(o.length<=l.limits.maxTextLength){const x=new AbortController;return(n?this.activeControllers:this.liveControllers).add(x),[{promise:this.synthesizeChunk(r,o,0,i,s,a,c,u,d,x),controller:x}]}if(this.overLengthText==="error")throw new qe(`Text exceeds this server's maximum length of ${l.limits.maxTextLength} characters`,{status:413,type:"https://readium.org/speech-server/error#payload_too_large",title:"Payload Too Large"});const g=Math.min(l.limits.maxTextLength,this.readyBufferChars),p=i?Es(o,g):xs(o,g),m=[];let b=Promise.resolve();for(let x=0;x<p.length;x++){const A=x===0?a:p[x-1].text,S=x===p.length-1?c:p[x+1].text,w=p[x],T=new AbortController;(n?this.activeControllers:this.liveControllers).add(T);const F=b.then(()=>this.synthesizeChunk(r,w.text,w.offset,i,s,A,S,u,d,T));m.push({promise:F,controller:T}),b=F}return m}async synthesizeChunk(e,n,r,i,s,o,a,c,l,u){try{const h=await this.fetchNetwork(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}}),signal:u.signal});if(!h.ok)throw await Fe(h);const d=await h.json(),g=qu(d.audio);let p;try{p=await this.ensureAudioContext().decodeAudioData(g)}catch{throw new gr("Audio playback failed")}return{audioBuffer:p,format:d.format,boundaries:d.boundaries,textOffset:r}}finally{this.activeControllers.delete(u),this.liveControllers.delete(u)}}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,n,r){if(this.timeoutMs===void 0)return e;const i=r+this.timeoutMs;return new Promise((s,o)=>{const a=setTimeout(()=>{n.abort(),o(new fr(`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,n){const r=await this.awaitWithStallDeadline(e[0].promise,e[0].controller,0);if(n!==this.speakGeneration)return;const i=this.ensureAudioContext(),s=this.masterGain,a=this.currentVoice?.controls?.speed===!0?1:Uu(this.rate);this.scheduledChunks=[],this.setState("playing"),this.emitEvent({type:"start"});let c=i.currentTime,l=null;const u=h=>{const d=i.createBufferSource();d.buffer=h.audioBuffer,d.playbackRate.value=a,d.connect(s),d.start(c),l&&(l.onended=null),d.onended=()=>this.handleUtteranceEnded(n),l=d,this.scheduledChunks.push({chunk:h,startTime:c,node:d,nextBoundaryIndex:0,rate:a}),c+=h.audioBuffer.duration/a};u(r),this.startBoundaryPolling(n);for(let h=1;h<e.length;h++){let d;try{const g=Math.max(0,(c-i.currentTime)*1e3);d=await this.awaitWithStallDeadline(e[h].promise,e[h].controller,g)}catch(g){n===this.speakGeneration&&this.emitEvent({type:"error",detail:si(g)});return}if(n!==this.speakGeneration)return;u(d)}}handleUtteranceEnded(e){e===this.speakGeneration&&(this.checkBoundaries(),this.stopBoundaryPolling(),this.isSpeakingInternal=!1,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.isSpeakingInternal=!1,this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.audioContext&&(this.audioContext.resume().catch(()=>{}),this.startBoundaryPolling(this.speakGeneration),this.isSpeakingInternal=!0,this.setState("playing"),this.emitEvent({type:"resume"}))}stop(){this.speakGeneration++,this.loadGeneration++,this.stopAudio(),this.abortLiveControllers(),this.clearPrefetchCache(),this.isSpeakingInternal=!1,this.currentUtteranceIndex=0,this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){const n=me(e,.1,10,this.rate);n!==this.rate&&(this.rate=n,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const n=me(e,0,2,this.pitch);n!==this.pitch&&(this.pitch=n,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const n=me(e,0,1,this.volume);n!==this.volume&&(this.volume=n,this.masterGain&&(this.masterGain.gain.value=this.volume))}getVolume(){return this.volume}scheduleRestartIfSpeaking(){!this.isSpeakingInternal||this.restartPending||(this.restartPending=!0,queueMicrotask(()=>{this.restartPending&&(this.restartPending=!1,this.isSpeakingInternal&&this.speak(this.currentUtteranceIndex))}))}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.events.on(e,n)}emitEvent(e){this.events.emit(e.type,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.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[]}}class Vu{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[n,r]=await Promise.all([this.fetchImpl(this.options.endpoints.voices),this.fetchImpl(this.options.endpoints.service)]);if(!n.ok)throw await Fe(n);if(!r.ok)throw await Fe(r);const i=await n.json(),s=await r.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 n=new As(this.options);return this.voices.length>0&&n.setAvailableVoices(this.voices),e&&n.setVoice(e),n}async destroy(){this.voices=[]}}function Ts(t){return t.detail?.recoverable===!0}const zu=3e4,Mu=["start","pause","resume","end","stop","skip","boundary","mark","idle","loading","ready","voiceschanged","languagefallback"];class Rs{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 Jt;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??zu,this.lastVoiceRequest=e.primaryEngine.getCurrentVoice()??void 0,this.bindActiveEngine()}async initialize(){return this.activeEngine.initialize?.()}loadUtterances(e,n){this.loadToken++,this.currentUtterances=e,this.desiredIndex=n??0,this.desiredPlaying=!1,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.loadUtterances(e,n))}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,n){if(this.desiredIndex=e,!this.isEngineTrusted()){n?.(!0);return}this.activeEngine.setCurrentUtteranceIndex(e,n)}getUtteranceCount(){return this.activeEngine.getUtteranceCount()}on(e,n){return this.events.on(e,n)}emitEvent(e){this.events.emit(e.type,e)}bindActiveEngine(){const e=this.activeEngine,n=Mu.map(r=>e.on(r,i=>{this.emitEvent(i),this.maybeRecoverNow()}));n.push(e.on("error",r=>this.handleError(r))),this.unbindActiveEngine=()=>n.forEach(r=>r())}handleError(e){if(this.hasFallenBack||this.swapInFlight||this.onFailure==="error"||!Ts(e)){this.emitEvent(e);return}this.swapToFallback(e)}copyPlaybackParameters(e,n){n.setRate(e.getRate()),n.setPitch(e.getPitch()),n.setVolume(e.getVolume()),n.setSpeakInContentLanguage(e.getSpeakInContentLanguage())}startEngineWhenReady(e){const n=this.loadToken,r=e.on("ready",()=>{r(),n===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 n=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");if(n=await this.pickBestFallbackVoice(s,i?.gender),!n)throw new Error("no offline-available fallback voice found");return this.fallbackProvider.createEngine(n)},()=>(this.hasFallenBack=!0,this.onFailure==="fallbackAndRecover"&&this.startHealthCheck(),{type:"enginefallback",detail:{reason:e.detail,voice:n}}),()=>{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,n,r){this.swapInFlight=!0;const i=this.teardownEpoch,s=this.activeEngine;let o;try{o=await e()}catch{this.swapInFlight=!1,r();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(n(o)),this.startEngineWhenReady(o),o.loadUtterances(this.currentUtterances,this.desiredIndex),await s.destroy()}async pickBestFallbackVoice(e,n){const r=await this.fallbackProvider.getVoices(),s=typeof navigator<"u"&&navigator.onLine===!0?r:r.filter(d=>d.offlineAvailability===!0);if(s.length===0)return null;const[o]=Gt([e]),{voicesByLang:a}=Kt(s,[o]),c=a.get(o.baseLang)??[],l=c.length>0?c:s,u=n?l.filter(d=>d.gender===n):[],h=u.length>0?u:l;return ko(e,h)}async destroy(){this.teardownEpoch++,this.healthCheckTimer!==null&&(clearTimeout(this.healthCheckTimer),this.healthCheckTimer=null),this.unbindActiveEngine?.(),this.events.clear(),await this.activeEngine.destroy()}}class ju{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(n){if(this.onFailure==="error")throw n;return this.fallback.getVoices(e)}}async createEngine(e){let n;try{n=await this.primary.createEngine(e)}catch(r){if(this.onFailure==="error")throw r;return this.fallback.createEngine(e)}return new Rs({primaryEngine:n,primaryProvider:this.primary,fallbackProvider:this.fallback,onFailure:this.onFailure,healthCheckIntervalMs:this.healthCheckIntervalMs})}async destroy(){await Promise.all([this.primary.destroy(),this.fallback.destroy()])}}let Hu=class{};function Wu(t){return(t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode)==="vertical-lr"}function Gu(t){const e=t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode;return e==="vertical-rl"||e==="vertical-lr"}function Ee(t){const e=Gu(t),n=e&&Wu(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,u=a;return{isVertical:e,isVertLR:n,viewportInlineSize:e?i:r,viewportBlockSize:e?r:i,pageInlineSize:e?i:r/(c||1),xDocOffset:l,yDocOffset:u,inlineScrollOffset:e?u:l,blockScrollOffset:e?l:u,inlineStart:h=>e?h.top:h.left,blockStart:h=>e?h.left:h.top,inlineSize:h=>e?h.height:h.width,blockSize:h=>e?h.width:h.height,applyPosition(h,d,g,p,m,b){h.style.position="absolute",e?(h.style.top=`${d*b}px`,h.style.left=`${g*b}px`,h.style.height=`${p*b}px`,h.style.width=`${m*b}px`):(h.style.left=`${d*b}px`,h.style.top=`${g*b}px`,h.style.width=`${p*b}px`,h.style.height=`${m*b}px`)},toRect(h,d,g,p){return e?new DOMRect(d,h,p,g):new DOMRect(h,d,g,p)}}}function ai(t,e){return t.document.documentElement.style.getPropertyValue(e)}function Ku(t){return t&&Array.isArray(t)?t:void 0}function Ju(t){return t&&typeof t=="string"?[t]:Ku(t)}function Ot(t){return isNaN(t)?void 0:t}function pn(t){return Ot(t)!==void 0&&Math.sign(t)>=0?t:void 0}let It=class Ns{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let n=pn(e.textNodeIndex);if(n===void 0)return;let r=pn(e.charOffset);return r===void 0&&(r=pn(e.offset)),new Ns({cssSelector:e.cssSelector,textNodeIndex:n,charOffset:r})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}},Ds=class Fs{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let n=It.deserialize(e.start);if(n)return new Fs({start:n,end:It.deserialize(e.end)})}serialize(){const e={start:this.start.serialize()};return this.end&&(e.end=this.end.serialize()),e}},yt=null,mn=null,Ke=0;const Ae={r:255,g:255,b:255,a:1},Ce=new Map,Xu=()=>{if(!yt)if(typeof OffscreenCanvas<"u")yt=new OffscreenCanvas(5,5),mn=yt.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const t=document.createElement("canvas");t.width=5,t.height=5,yt=t,mn=t.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return mn},Yu=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))},bt=(t,e)=>{console.warn(`[Decorator] Could not parse color: "${t}". ${e} Falling back to ${JSON.stringify(Ae)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},be=(t,e=null)=>{const n=e?`${t}|${e}`:t,r=Ce.get(n);if(r!==void 0)return r??Ae;if(Yu(t))return bt(t,"Unsupported color format or special value."),Ce.set(n,null),Ae;const i=Xu();if(!i)return bt(t,"Could not get canvas context."),Ce.set(n,null),Ae;try{Ke===0&&i.clearRect(0,0,5,5);const s=Ke%5,o=Math.floor(Ke/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);Ke=(Ke+1)%25;const[c,l,u,h]=a.data;if(h===0)return bt(t,"Fully transparent color."),Ce.set(n,null),Ae;const d={r:c,g:l,b:u,a:h/255};return Ce.set(n,d),d}catch(s){return bt(t,`Error: ${s instanceof Error?s.message:String(s)}`),Ce.set(n,null),Ae}},yn=t=>{const e=t/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},_n=t=>{const e=yn(t.r),n=yn(t.g),r=yn(t.b);return .2126*e+.7152*n+.0722*r},Pt=(t,e)=>{const n=typeof t=="string"?be(t):t,r=typeof e=="string"?be(e):e,i=_n(n),s=_n(r),o=Math.max(i,s),a=Math.min(i,s);return(o+.05)/(a+.05)},Is=(t,e=null)=>{const n=be(t,e),r=Pt(n,{r:255,g:255,b:255,a:1}),i=Pt(n,{r:0,g:0,b:0,a:1});return r>i},oi=(t,e=null)=>Is(t,e)?"white":"black",Qu=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})`},Zu=(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}),eh=(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}),ke=(t,e=null,n=3)=>{const r=be(t),i=e?be(e):{r:255,g:255,b:255,a:1};let s=Pt(r,i);if(s>=n)return t;const o=_n(i)<.5;let a={...r,a:r.a??1};const c=20,l=.1;for(let u=0;u<c&&(o?a=Zu(a,l):a=eh(a,l),s=Pt(a,i),!(s>=n));u++);return Qu(a)},Ps=()=>typeof navigator>"u"?"":navigator.userAgent||"",Ls=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;let $s=class{constructor(){const e=Ls(),n=Ps(),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},[])}}},th=class extends $s{get iOSRequest(){const e=Ls(),n=Ps();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 nh=new $s;new th;const li=":~:text=";function rh(t){if(!t)return;const e=t.indexOf(li);if(e===-1)return;const n=t.slice(e+li.length).split("&")[0];if(n)try{let r=n.split(",");const i={textStart:""};return r.length>1&&r[0].endsWith("-")&&(i.prefix=decodeURIComponent(r[0].slice(0,-1)),r=r.slice(1)),r.length>1&&r[r.length-1].startsWith("-")&&(i.suffix=decodeURIComponent(r[r.length-1].slice(1)),r=r.slice(0,-1)),r.length===0||r[0]===""?void 0:(i.textStart=decodeURIComponent(r[0]),r.length>1&&(i.textEnd=decodeURIComponent(r[1])),i)}catch{return}}const _s=["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","BR","DETAILS","DIALOG","DD","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","LI","MAIN","NAV","OL","P","PRE","SECTION","TABLE","UL","TR","TH","TD","COLGROUP","COL","CAPTION","THEAD","TBODY","TFOOT"],Qe=/[\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u,ih=/[^\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u,Bs=(t,e,n)=>{const r=[],i=e.createRange();for(i.selectNodeContents(n??e);!i.collapsed&&r.length<2;){let s;if(t.prefix){const o=Ze(t.prefix,i);if(o==null)break;St(i,o.startContainer,o.startOffset);const a=e.createRange();if(a.setStart(o.endContainer,o.endOffset),a.setEnd(i.endContainer,i.endOffset),qs(a),a.collapsed||(s=Ze(t.textStart,a),s==null))break;if(s.compareBoundaryPoints(Range.START_TO_START,a)!==0)continue}else{if(s=Ze(t.textStart,i),s==null)break;St(i,s.startContainer,s.startOffset)}if(t.textEnd){const o=e.createRange();o.setStart(s.endContainer,s.endOffset),o.setEnd(i.endContainer,i.endOffset);let a=!1;for(;!o.collapsed&&r.length<2;){const c=Ze(t.textEnd,o);if(c==null)break;if(St(o,c.startContainer,c.startOffset),s.setEnd(c.endContainer,c.endOffset),t.suffix){const l=ci(t.suffix,s,i,e);if(l===te.NO_SUFFIX_MATCH)break;if(l===te.SUFFIX_MATCH){a=!0,r.push(s.cloneRange());continue}else if(l===te.MISPLACED_SUFFIX)continue}else a=!0,r.push(s.cloneRange())}if(!a)break}else if(t.suffix){const o=ci(t.suffix,s,i,e);if(o===te.NO_SUFFIX_MATCH)break;if(o===te.SUFFIX_MATCH){r.push(s.cloneRange()),St(i,i.startContainer,i.startOffset);continue}else if(o===te.MISPLACED_SUFFIX)continue}else r.push(s.cloneRange())}return r},te={NO_SUFFIX_MATCH:0,SUFFIX_MATCH:1,MISPLACED_SUFFIX:2},ci=(t,e,n,r)=>{const i=r.createRange();i.setStart(e.endContainer,e.endOffset),i.setEnd(n.endContainer,n.endOffset),qs(i);const s=Ze(t,i);return s==null?te.NO_SUFFIX_MATCH:s.compareBoundaryPoints(Range.START_TO_START,i)!==0?te.MISPLACED_SUFFIX:te.SUFFIX_MATCH},St=(t,e,n)=>{try{t.setStart(e,n+1)}catch{t.setStartAfter(e)}},qs=t=>{const e=Us(t);let n=e.nextNode();for(;!t.collapsed&&n!=null;){if(n!==t.startContainer&&t.setStart(n,0),n.textContent.length>t.startOffset&&!n.textContent[t.startOffset].match(/\s/))return;try{t.setStart(n,t.startOffset+1)}catch{n=e.nextNode(),n==null?t.collapse():t.setStart(n,0)}}},Us=t=>(t.commonAncestorContainer.ownerDocument??t.commonAncestorContainer).createTreeWalker(t.commonAncestorContainer,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode:e=>ah(e,t)}),sh=t=>{if(t.hidden==="until-found")return!0;const e=t.attributes;return!!(e&&e.hidden&&e.hidden.value==="until-found")},mr=t=>{let e=t;for(;e!=null&&!(e instanceof HTMLElement);)e=e.parentNode;const n=e?.ownerDocument?.defaultView;if(e!=null&&n!=null){if(sh(e))return!0;const r=n.getComputedStyle(e);if(r.visibility==="hidden"||r.display==="none"||parseInt(r.height,10)===0&&r.overflowY!="visible"||parseInt(r.width,10)===0&&r.overflowX!="visible"||parseInt(r.opacity,10)===0)return!1}return!0},Vs=(t,e)=>e!=null&&!e.intersectsNode(t)?NodeFilter.FILTER_REJECT:mr(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT,ah=(t,e)=>e!=null&&!e.intersectsNode(t)||!mr(t)?NodeFilter.FILTER_REJECT:t.nodeType===Node.TEXT_NODE?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,oh=(t,e)=>{const n=[];let r=[];const i=Array.from(ch(t,s=>Vs(s,e)));for(const s of i)s.nodeType===Node.TEXT_NODE?r.push(s):s instanceof HTMLElement&&_s.includes(s.tagName.toUpperCase())&&r.length>0&&(n.push(r),r=[]);return r.length>0&&n.push(r),n},lh=(t,e,n)=>{let r="";return t.length===1?r=t[0].textContent.substring(e,n):r=t[0].textContent.substring(e)+t.slice(1,-1).reduce((i,s)=>i+s.textContent,"")+t.slice(-1)[0].textContent.substring(0,n),r.replace(/[\t\n\r ]+/g," ")};function*ch(t,e){const n=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:e}),r=new Set;for(;Ms(n,r)!==null;)yield n.currentNode}const Ze=(t,e)=>{const n=oh(e.commonAncestorContainer,e),r=zs(e.commonAncestorContainer.ownerDocument??void 0);for(const i of n){const s=uh(t,e,i,r);if(s!==void 0)return s}},uh=(t,e,n,r)=>{if(!t||!e||!(n||[]).length)return;const i=n[0]===e.startContainer?e.startOffset:0,s=ae(lh(n,i,void 0)),o=ae(t);let a=0,c,l;for(;a<s.length;){const u=s.indexOf(o,a);if(u===-1)return;if(hh(s,u,o.length,r)){const h=ae(n[0].data.slice(0,i)).length;c=ui(h+u,n,!1),l=ui(h+u+o.length,n,!0)}if(c!=null&&l!=null){const h=new Range;if(h.setStart(c.node,c.offset),h.setEnd(l.node,l.offset),e.compareBoundaryPoints(Range.START_TO_START,h)<=0&&e.compareBoundaryPoints(Range.END_TO_END,h)>=0)return h}a=u+1}},ui=(t,e,n)=>{let r=0,i;for(let s=0;s<e.length;s++){const o=e[s];i||(i=ae(o.data));let a=r+i.length;if(n&&(a+=1),a>t){const c=t-r;let l=Math.min(t-r,o.data.length);const u=n?i.substring(0,c):i.substring(c);let h=ae(n?o.data.substring(0,l):o.data.substring(l));const d=(n?-1:1)*(u.length>h.length?-1:1);for(;l>=0&&l<=o.data.length;){if(h.length===u.length)return{node:o,offset:l};l+=d,h=ae(n?o.data.substring(0,l):o.data.substring(l))}}if(r+=i.length,s+1<e.length){const c=ae(e[s+1].data);i.slice(-1)===" "&&c.slice(0,1)===" "&&(r-=1),i=c}}},hh=(t,e,n,r)=>{if(e<0||e>=t.length||n<=0||e+n>t.length)return!1;if(r){const i=r.segment(t),s=i.containing(e);if(!s||s.isWordLike&&s.index!=e)return!1;const o=e+n,a=i.containing(o);if(a&&a.isWordLike&&a.index!=o)return!1}else if(t[e].match(Qe)&&(++e,--n,!n)||t[e+n-1].match(Qe)&&(--n,!n)||e!==0&&!t[e-1].match(Qe)||e+n!==t.length&&!t[e+n].match(Qe))return!1;return!0},ae=t=>(t||"").normalize("NFKD").replace(/\s+/g," ").replace(/[\u0300-\u036f]/g,"").toLowerCase(),zs=t=>{if(Intl.Segmenter){const e=t?.documentElement?.lang||t?.defaultView?.navigator?.language||void 0;return new Intl.Segmenter(e,{granularity:"word"})}},Ms=(t,e)=>{if(!e.has(t.currentNode)){const i=t.firstChild();if(i!==null)return i}const n=t.nextSibling();if(n!==null)return n;const r=t.parentNode();return r!==null&&e.add(r),r},dh=(t,e)=>{if(!e.has(t.currentNode)){const i=t.lastChild();if(i!==null)return i}const n=t.previousSibling();if(n!==null)return n;const r=t.parentNode();return r!==null&&e.add(r),r},D={BLOCK_ELEMENTS:_s,BOUNDARY_CHARS:Qe,NON_BOUNDARY_CHARS:ih,acceptNodeIfVisibleInRange:Vs,normalizeString:ae,makeNewSegmenter:zs,forwardTraverse:Ms,backwardTraverse:dh,makeTextNodeWalker:Us,isNodeVisible:mr},fh=300,js=20,gh=1,hi=3,di=1;let ph=500,Hs;class Ws extends Error{constructor(){super(...arguments),this.isTimeout=!0}}const de={SUCCESS:0,INVALID_SELECTION:1,AMBIGUOUS:2,TIMEOUT:3,EXECUTION_FAILED:4},mh=(t,e=Date.now())=>{try{return yh(t,e)}catch(n){return n instanceof Ws?{status:de.TIMEOUT}:{status:de.EXECUTION_FAILED}}},yh=(t,e)=>{Sh(e);const n=t.startContainer.ownerDocument,r=bh(n);Oh(t),Rh(t);const i=t.cloneRange();if(Ah(t),t.collapsed)return{status:de.INVALID_SELECTION};let s;if(wh(t)){const h=D.normalizeString(t.toString()),d={textStart:h};if(h.length>=js&&Ks(d,n,r))return{status:de.SUCCESS,fragment:d};s=new bn(n,r).setExactTextMatch(h)}else{const h=fi(t),d=gi(t);h&&d?s=new bn(n,r).setStartAndEndSearchSpace(h,d):s=new bn(n,r).setSharedSearchSpace(t.toString().trim())}const o=n.createRange();o.selectNodeContents(r);const a=o.cloneRange();o.setEnd(i.startContainer,i.startOffset),a.setStart(i.endContainer,i.endOffset);const c=gi(o),l=fi(a);(c||l)&&s.setPrefixAndSuffixSearchSpace(c,l),s.useSegmenter(D.makeNewSegmenter(n));let u=!1;do{j(),u=s.embiggen();const h=s.tryToMakeUniqueFragment();if(h!=null)return{status:de.SUCCESS,fragment:h}}while(u);return{status:de.AMBIGUOUS}},bh=t=>t.querySelector("body")??t.documentElement,j=()=>{const t=Date.now()-Hs;if(t>ph)throw new Ws(`Fragment generation timed out after ${t} ms.`)},Sh=t=>{Hs=t},fi=t=>{let e=ut(t);const n=Se(e,t.endContainer);if(!n)return;const r=new Set;t.startContainer.nodeType===Node.ELEMENT_NODE&&t.startOffset===t.startContainer.childNodes.length&&r.add(t.startContainer);const i=e,s=new Gs(t,!0),o=t.cloneRange();for(;!o.collapsed&&e!=null;){if(j(),e.contains?.(i)?o.setStartAfter(e):o.setStartBefore(e),s.appendNode(e),s.textInBlock!==null)return s.textInBlock;e=D.forwardTraverse(n,r)}},gi=t=>{let e=Zt(t);const n=Se(e,t.startContainer);if(!n)return;const r=new Set;t.endContainer.nodeType===Node.ELEMENT_NODE&&t.endOffset===0&&r.add(t.endContainer);const i=e,s=new Gs(t,!1),o=t.cloneRange();for(;!o.collapsed&&e!=null;){if(j(),e.contains?.(i)?o.setEnd(e,0):o.setEndAfter(e),s.appendNode(e),s.textInBlock!==null)return s.textInBlock;e=D.backwardTraverse(n,r)}},vh={ALL_PARTS:1,SHARED_START_AND_END:2,CONTEXT_ONLY:3};let bn=class{constructor(e,n){this.Mode=vh,this.startOffset=null,this.endOffset=null,this.prefixOffset=null,this.suffixOffset=null,this.prefixSearchSpace="",this.backwardsPrefixSearchSpace="",this.suffixSearchSpace="",this.numIterations=0,this.doc=e,this.root=n}tryToMakeUniqueFragment(){let e;if(this.mode===this.Mode.CONTEXT_ONLY?e={textStart:this.exactTextMatch}:e={textStart:this.getStartSearchSpace().substring(0,this.startOffset).trim(),textEnd:this.getEndSearchSpace().substring(this.endOffset).trim()},this.prefixOffset!=null){const n=this.getPrefixSearchSpace().substring(this.prefixOffset).trim();n&&(e.prefix=n)}if(this.suffixOffset!=null){const n=this.getSuffixSearchSpace().substring(0,this.suffixOffset).trim();n&&(e.suffix=n)}return Ks(e,this.doc,this.root)?e:void 0}embiggen(){let e=!0;if(this.mode===this.Mode.SHARED_START_AND_END?this.startOffset>=this.endOffset&&(e=!1):this.mode===this.Mode.ALL_PARTS?this.startOffset===this.getStartSearchSpace().length&&this.backwardsEndOffset()===this.getEndSearchSpace().length&&(e=!1):this.mode===this.Mode.CONTEXT_ONLY&&(e=!1),e){const r=this.getNumberOfRangeWordsToAdd();if(this.startOffset<this.getStartSearchSpace().length){let i=0;if(this.getStartSegments()!=null)for(;i<r&&this.startOffset<this.getStartSearchSpace().length;)this.startOffset=this.getNextOffsetForwards(this.getStartSegments(),this.startOffset,this.getStartSearchSpace()),i++;else{let s=this.startOffset;do{j();const o=this.getStartSearchSpace().substring(this.startOffset+1).search(D.BOUNDARY_CHARS);o===-1?this.startOffset=this.getStartSearchSpace().length:this.startOffset=this.startOffset+1+o,this.getStartSearchSpace().substring(s,this.startOffset).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.startOffset,i++)}while(this.startOffset<this.getStartSearchSpace().length&&i<r)}this.mode===this.Mode.SHARED_START_AND_END&&(this.startOffset=Math.min(this.startOffset,this.endOffset))}if(this.backwardsEndOffset()<this.getEndSearchSpace().length){let i=0;if(this.getEndSegments()!=null)for(;i<r&&this.endOffset>0;)this.endOffset=this.getNextOffsetBackwards(this.getEndSegments(),this.endOffset),i++;else{let s=this.backwardsEndOffset();do{j();const o=this.getBackwardsEndSearchSpace().substring(this.backwardsEndOffset()+1).search(D.BOUNDARY_CHARS);o===-1?this.setBackwardsEndOffset(this.getEndSearchSpace().length):this.setBackwardsEndOffset(this.backwardsEndOffset()+1+o),this.getBackwardsEndSearchSpace().substring(s,this.backwardsEndOffset()).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.backwardsEndOffset(),i++)}while(this.backwardsEndOffset()<this.getEndSearchSpace().length&&i<r)}this.mode===this.Mode.SHARED_START_AND_END&&(this.endOffset=Math.max(this.startOffset,this.endOffset))}}let n=!1;if((!e||this.startOffset+this.backwardsEndOffset()<js||this.numIterations>=gh)&&(this.backwardsPrefixOffset()!=null&&this.backwardsPrefixOffset()!==this.getPrefixSearchSpace().length||this.suffixOffset!=null&&this.suffixOffset!==this.getSuffixSearchSpace().length)&&(n=!0),n){const r=this.getNumberOfContextWordsToAdd();if(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length){let i=0;if(this.getPrefixSegments()!=null)for(;i<r&&this.prefixOffset>0;)this.prefixOffset=this.getNextOffsetBackwards(this.getPrefixSegments(),this.prefixOffset),i++;else{let s=this.backwardsPrefixOffset();do{j();const o=this.getBackwardsPrefixSearchSpace().substring(this.backwardsPrefixOffset()+1).search(D.BOUNDARY_CHARS);o===-1?this.setBackwardsPrefixOffset(this.getBackwardsPrefixSearchSpace().length):this.setBackwardsPrefixOffset(this.backwardsPrefixOffset()+1+o),this.getBackwardsPrefixSearchSpace().substring(s,this.backwardsPrefixOffset()).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.backwardsPrefixOffset(),i++)}while(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length&&i<r)}}if(this.suffixOffset<this.getSuffixSearchSpace().length){let i=0;if(this.getSuffixSegments()!=null)for(;i<r&&this.suffixOffset<this.getSuffixSearchSpace().length;)this.suffixOffset=this.getNextOffsetForwards(this.getSuffixSegments(),this.suffixOffset,this.getSuffixSearchSpace()),i++;else{let s=this.suffixOffset;do{j();const o=this.getSuffixSearchSpace().substring(this.suffixOffset+1).search(D.BOUNDARY_CHARS);o===-1?this.suffixOffset=this.getSuffixSearchSpace().length:this.suffixOffset=this.suffixOffset+1+o,this.getSuffixSearchSpace().substring(s,this.suffixOffset).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.suffixOffset,i++)}while(this.suffixOffset<this.getSuffixSearchSpace().length&&i<r)}}}return this.numIterations++,e||n}setStartAndEndSearchSpace(e,n){return this.startSearchSpace=e,this.endSearchSpace=n,this.backwardsEndSearchSpace=At(n),this.startOffset=0,this.endOffset=n.length,this.mode=this.Mode.ALL_PARTS,this}setSharedSearchSpace(e){return this.sharedSearchSpace=e,this.backwardsSharedSearchSpace=At(e),this.startOffset=0,this.endOffset=e.length,this.mode=this.Mode.SHARED_START_AND_END,this}setExactTextMatch(e){return this.exactTextMatch=e,this.mode=this.Mode.CONTEXT_ONLY,this}setPrefixAndSuffixSearchSpace(e,n){return e&&(this.prefixSearchSpace=e,this.backwardsPrefixSearchSpace=At(e),this.prefixOffset=e.length),n&&(this.suffixSearchSpace=n,this.suffixOffset=0),this}useSegmenter(e){return e==null?this:(this.mode===this.Mode.ALL_PARTS?(this.startSegments=e.segment(this.startSearchSpace),this.endSegments=e.segment(this.endSearchSpace)):this.mode===this.Mode.SHARED_START_AND_END&&(this.sharedSegments=e.segment(this.sharedSearchSpace)),this.prefixSearchSpace&&(this.prefixSegments=e.segment(this.prefixSearchSpace)),this.suffixSearchSpace&&(this.suffixSegments=e.segment(this.suffixSearchSpace)),this)}getNumberOfContextWordsToAdd(){return this.backwardsPrefixOffset()===0&&this.suffixOffset===0?hi:di}getNumberOfRangeWordsToAdd(){return this.startOffset===0&&this.backwardsEndOffset()===0?hi:di}getNextOffsetForwards(e,n,r){let i=e.containing(n);for(;i!=null;){j();const s=i.index+i.segment.length;if(i.isWordLike)return s;i=e.containing(s)}return r.length}getNextOffsetBackwards(e,n){let r=e.containing(n);for((!r||n==r.index)&&(r=e.containing(n-1));r!=null;){if(j(),r.isWordLike)return r.index;r=e.containing(r.index-1)}return 0}getStartSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSearchSpace:this.startSearchSpace}getStartSegments(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSegments:this.startSegments}getEndSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSearchSpace:this.endSearchSpace}getEndSegments(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSegments:this.endSegments}getBackwardsEndSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.backwardsSharedSearchSpace:this.backwardsEndSearchSpace}getPrefixSearchSpace(){return this.prefixSearchSpace}getPrefixSegments(){return this.prefixSegments}getBackwardsPrefixSearchSpace(){return this.backwardsPrefixSearchSpace}getSuffixSearchSpace(){return this.suffixSearchSpace}getSuffixSegments(){return this.suffixSegments}backwardsEndOffset(){return this.getEndSearchSpace().length-this.endOffset}setBackwardsEndOffset(e){this.endOffset=this.getEndSearchSpace().length-e}backwardsPrefixOffset(){return this.prefixOffset==null?null:this.getPrefixSearchSpace().length-this.prefixOffset}setBackwardsPrefixOffset(e){this.prefixOffset!=null&&(this.prefixOffset=this.getPrefixSearchSpace().length-e)}};class Gs{constructor(e,n){this.textFound=!1,this.textNodes=[],this.textInBlock=null,this.searchRange=e,this.isForwardTraversal=n}appendNode(e){if(this.textInBlock!==null)return;if(le(e)){this.textFound?(this.isForwardTraversal||this.textNodes.reverse(),this.textInBlock=this.textNodes.map(r=>r.textContent).join("").trim()):this.textNodes=[];return}if(!yr(e))return;const n=this.getNodeIntersectionWithRange(e);this.textFound=this.textFound||(n.textContent??"").trim()!=="",this.textNodes.push(n)}getNodeIntersectionWithRange(e){let n=null,r=null;const i=(e.textContent??"").length;return e===this.searchRange.startContainer&&this.searchRange.startOffset!==0&&(n=this.searchRange.startOffset),e===this.searchRange.endContainer&&this.searchRange.endOffset!==i&&(r=this.searchRange.endOffset),n!==null||r!==null?{textContent:(e.textContent??"").substring(n??0,r??i)}:e}}const Ks=(t,e,n)=>Bs(t,e,n).length===1,At=t=>[...t||""].reverse().join(""),wh=t=>t.toString().length>fh?!1:!Ch(t),ut=t=>{let e=t.startContainer;return e.nodeType==Node.ELEMENT_NODE&&t.startOffset<e.childNodes.length&&(e=e.childNodes[t.startOffset]),e},Zt=t=>{let e=t.endContainer;return e.nodeType==Node.ELEMENT_NODE&&t.endOffset>0&&(e=e.childNodes[t.endOffset-1]),e},xh=t=>{const e=ut(t);if(yr(e)&&D.isNodeVisible(e))return e;const n=D.makeTextNodeWalker(t);return n.currentNode=e,n.nextNode()},Eh=t=>{const e=Zt(t);if(yr(e)&&D.isNodeVisible(e))return e;const n=D.makeTextNodeWalker(t);return n.currentNode=e,D.backwardTraverse(n,new Set)},Ch=t=>{const e=t.cloneRange();let n=ut(e);const r=Se(n);if(!r)return!1;const i=new Set;for(;!e.collapsed&&n!=null;){if(le(n))return!0;n!=null&&e.setStartAfter(n),n=D.forwardTraverse(r,i),j()}return!1},pi=(t,e)=>{if(t.nodeType!==Node.TEXT_NODE)return-1;const n=t,r=e??n.data.length;if(r<n.data.length&&D.BOUNDARY_CHARS.test(n.data[r]))return r;const i=n.data.substring(0,r),s=At(i).search(D.BOUNDARY_CHARS);return s!==-1?r-s:-1},kh=(t,e)=>{if(t.nodeType!==Node.TEXT_NODE)return-1;const n=t,r=e??0;if(r<n.data.length&&r>0&&D.BOUNDARY_CHARS.test(n.data[r-1]))return r;const i=n.data.substring(r).search(D.BOUNDARY_CHARS);return i!==-1?r+i:-1},Se=(t,e)=>{if(!t)return;let n=t;const r=e??t;for(;!n.contains?.(r)||!le(n);)n.parentNode&&(n=n.parentNode);const i=(n.ownerDocument??n).createTreeWalker(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:s=>D.acceptNodeIfVisibleInRange(s)});return i.currentNode=t,i},Oh=t=>{const e=D.makeNewSegmenter(t.startContainer.ownerDocument??void 0);if(e){const n=ut(t);n!==t.startContainer&&t.setStartBefore(n),Js(e,!1,t)}else{const n=pi(t.startContainer,t.startOffset);if(n!==-1){t.setStart(t.startContainer,n);return}if(le(t.startContainer)&&t.startOffset===0)return;const r=Se(t.startContainer);if(!r)return;const i=new Set;let s=D.backwardTraverse(r,i);for(;s!=null;){const o=pi(s);if(o!==-1){t.setStart(s,o);return}if(le(s)){s.contains?.(t.startContainer)?t.setStart(s,0):t.setStartAfter(s);return}s=D.backwardTraverse(r,i),t.collapse()}}},Ah=t=>{const e=xh(t);if(e==null){t.collapse();return}ut(t)!==e&&t.setStart(e,0);const n=Zt(t),r=Eh(t);n!==r&&t.setEnd(r,(r.textContent??"").length)},Js=(t,e,n)=>{const r=e?{node:n.endContainer,offset:n.endOffset}:{node:n.startContainer,offset:n.startOffset},i=Th(r.node);if(!i)return;const s=i.preNodes.reduce((p,m)=>p.concat(m.textContent??""),""),o=i.innerNodes.reduce((p,m)=>p.concat(m.textContent??""),"");let a=s.length;r.node.nodeType===Node.TEXT_NODE?a+=r.offset:e&&(a+=o.length);const c=i.postNodes.reduce((p,m)=>p.concat(m.textContent??""),""),l=[...i.preNodes,...i.innerNodes,...i.postNodes];if(l.length==0)return;const u=s.concat(o,c),h=t.segment(u).containing(a);if(!h){e?n.setEndAfter(l[l.length-1]):n.setEndBefore(l[0]);return}if(!h.isWordLike||a===h.index||a===h.index+h.segment.length)return;const d=e?h.index+h.segment.length:h.index;let g=0;for(const p of l){const m=(p.textContent??"").length;if(g<=d&&d<g+m){const b=d-g;e?b>=m?n.setEndAfter(p):n.setEnd(p,b):b>=m?n.setStartAfter(p):n.setStart(p,b);return}g+=m}e?n.setEndAfter(l[l.length-1]):n.setStartBefore(l[0])},Th=t=>{const e=[],n=Se(t);if(!n)return;const r=new Set;let i=D.backwardTraverse(n,r);for(;i!=null&&!le(i);)j(),i.nodeType===Node.TEXT_NODE&&e.push(i),i=D.backwardTraverse(n,r);e.reverse();const s=[];if(t.nodeType===Node.TEXT_NODE)s.push(t);else{const u=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:d=>D.acceptNodeIfVisibleInRange(d)});u.currentNode=t;let h=u.nextNode();for(;h!=null;)j(),h.nodeType===Node.TEXT_NODE&&s.push(h),h=u.nextNode()}const o=[],a=Se(t);if(!a)return;const c=new Set([t]);let l=D.forwardTraverse(a,c);for(;l!=null&&!le(l);)j(),l.nodeType===Node.TEXT_NODE&&o.push(l),l=D.forwardTraverse(a,c);return{preNodes:e,innerNodes:s,postNodes:o}},Rh=t=>{const e=D.makeNewSegmenter(t.endContainer.ownerDocument??void 0);if(e){const n=Zt(t);n!==t.endContainer&&t.setEndAfter(n),Js(e,!0,t)}else{let n=t.endOffset,r=t.endContainer;r.nodeType===Node.ELEMENT_NODE&&t.endOffset<r.childNodes.length&&(r=r.childNodes[t.endOffset]);const i=Se(r);if(!i)return;const s=new Set([r]);for(;r!=null;){j();const o=kh(r,n);if(n=null,o!==-1){t.setEnd(r,o);return}if(le(r)){r.contains?.(t.endContainer)?t.setEnd(r,r.childNodes.length):t.setEndBefore(r);return}r=D.forwardTraverse(i,s)}t.collapse()}},le=t=>t.nodeType===Node.ELEMENT_NODE&&(D.BLOCK_ELEMENTS.includes(t.tagName.toUpperCase())||t.tagName.toUpperCase()==="HTML"||t.tagName.toUpperCase()==="BODY"),yr=t=>t.nodeType===Node.TEXT_NODE;function Bn(t){return t.otherLocations?.get("cssSelector")}function Nh(t){return Ds.deserialize(t.otherLocations?.get("domRange"))}function Dh(t){for(const e of t.fragments){const n=rh(e);if(n)return n}}let ue=class Xs{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=Ot(e.progression),r=Ot(e.totalProgression),i=Ot(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 Xs({fragments:Ju(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}},br=class Ys{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new Ys({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}},Sr=class qn{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 ue({...e.locations,fragments:[r]}):e.locations:r?new ue({fragments:[r]}):new ue({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new qn({href:e.href,type:e.type,title:e.title,locations:ue.deserialize(e.locations),text:br.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 qn({href:this.href,type:this.type,title:this.title,text:this.text,locations:new ue({...this.locations,...e})})}};function mi(t){return t.split("").reverse().join("")}function Fh(t,e,n){const r=mi(e);return n.map(i=>{const s=Math.max(0,i.end-e.length-i.errors),o=mi(t.slice(s,i.end));return{start:Qs(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 Sn(t){return(t|-t)>>31&1}function yi(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 u=s|~(l|i),h=i&l;const d=Sn(u&t.lastRowMask[n])-Sn(h&t.lastRowMask[n]);return u<<=1,h<<=1,h|=o,u|=Sn(r)-o,i=h|~(c|u),s=u&c,t.P[n]=i,t.M[n]=s,d}function Qs(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 d=0;d<256;d++)l.push(a);for(let d=0;d<e.length;d+=1){const g=e.charCodeAt(d);if(c.has(g))continue;const p=new Uint32Array(s+1);c.set(g,p),g<l.length&&(l[g]=p);for(let m=0;m<=s;m+=1){p[m]=0;for(let b=0;b<i;b+=1){const x=m*i+b;x>=e.length||e.charCodeAt(x)===g&&(p[m]|=1<<b)}}}let u=Math.max(0,Math.ceil(n/i)-1);const h=new Uint32Array(s+1);for(let d=0;d<=u;d+=1)h[d]=(d+1)*i;h[s]=e.length;for(let d=0;d<=u;d+=1)o.P[d]=-1,o.M[d]=0;for(let d=0;d<t.length;d+=1){const g=t.charCodeAt(d);let p;g<l.length?p=l[g]:(p=c.get(g),typeof p>"u"&&(p=a));let m=0;for(let b=0;b<=u;b+=1)m=yi(o,p,b,m),h[b]+=m;if(h[u]-m<=n&&u<s&&(p[u+1]&1||m<0)){u+=1,o.P[u]=-1,o.M[u]=0;let b;if(u===s){const x=e.length%i;b=x===0?i:x}else b=i;h[u]=h[u-1]+b-m+yi(o,p,u,m)}else for(;u>0&&h[u]>=n+i;)u-=1;u===s&&h[u]<=n&&(h[u]<n&&r.splice(0,r.length),r.push({start:-1,end:d+1,errors:h[u]}),n=h[u])}return r}function Ih(t,e,n){const r=Qs(t,e,n);return Fh(t,e,r)}function Zs(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:Ih(t,e,n)}function bi(t,e){return e.length===0||t.length===0?0:1-Zs(t,e,e.length)[0].errors/e.length}function Ph(t,e,n={}){if(e.length===0)return null;const r=Math.min(256,e.length/2),i=Zs(t,e,r);if(i.length===0)return null;const s=a=>{const c=1-a.errors/e.length,l=n.prefix?bi(t.slice(Math.max(0,a.start-n.prefix.length),a.start),n.prefix):1,u=n.suffix?bi(t.slice(a.end,a.end+n.suffix.length),n.suffix):1;let h=1;return typeof n.hint=="number"&&(h=1-Math.abs(a.start-n.hint)/t.length),(50*c+20*l+20*u+2*h)/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 Un(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 Si(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=Un(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 Lh(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:Un(t.startContainer.textContent,t.startOffset,1),end:Un(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}=Si(e,1);s&&o>=0&&e.setStart(s,o)}if(!r){const{node:s,offset:o}=Si(e,2);s&&o>0&&e.setEnd(s,o)}return e}function ea(t){switch(t.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return t.textContent?.length??0;default:return 0}}function vi(t){let e=t.previousSibling,n=0;for(;e;)n+=ea(e),e=e.previousSibling;return n}function ta(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 vt=class Te{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+=vi(n),n=n.parentElement;return new Te(n,r)}resolve(e={}){try{return ta(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 Te.fromPoint(e,n);case Node.ELEMENT_NODE:return new Te(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=vi(e)+n;return new Te(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+=ea(e.childNodes[i]);return new Te(e,r)}default:throw new Error("Point is not in an element or text node")}}},Vn=class et{constructor(e,n){this.start=e,this.end=n}relativeTo(e){return new et(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]=ta(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=vt.fromPoint(e.startContainer,e.startOffset),r=vt.fromPoint(e.endContainer,e.endOffset);return new et(n,r)}static fromOffsets(e,n,r){return new et(new vt(e,n),new vt(e,r))}static trimmedRange(e){return Lh(et.fromRange(e).toRange())}},$h=class zn{constructor(e,n,r){this.root=e,this.start=n,this.end=r}static fromRange(e,n){const r=Vn.fromRange(n).relativeTo(e);return new zn(e,r.start.offset,r.end.offset)}static fromSelector(e,n){return new zn(e,n.start,n.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return Vn.fromOffsets(this.root,this.start,this.end).toRange()}},_h=class Mn{constructor(e,n,r={}){this.root=e,this.exact=n,this.context=r}static fromRange(e,n){const r=e.textContent,i=Vn.fromRange(n).relativeTo(e),s=i.start.offset,o=i.end.offset,a=32;return new Mn(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 Mn(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=Ph(n,this.exact,{...this.context,hint:e.hint});if(!r)throw new Error("Quote not found");return new $h(this.root,r.start,r.end)}};function Bh(t){const e=t.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function wi(t,e){const n=e&&Bn(e);let r=null;if(n)try{r=t.querySelector(n)}catch(i){console.warn(`Invalid cssSelector: ${n}`,i)}return r??t.body??t.documentElement}function xi(t,e){let n;try{n=t.querySelector(e.cssSelector)}catch(i){return console.error(`Invalid domRange cssSelector: ${e.cssSelector}`,i),null}if(!n)return console.error(`Can't resolve domRange cssSelector: ${e.cssSelector}`),null;let r=0;for(const i of n.childNodes)if(i.nodeType===Node.TEXT_NODE){if(r===e.textNodeIndex)return{node:i,offset:e.charOffset};r++}return console.error(`Can't resolve domRange textNodeIndex ${e.textNodeIndex} for selector: ${e.cssSelector}`),null}function qh(t,e){try{const n=e.locations,r=e.text;if(n){const i=Nh(n);if(i){const s=xi(t,i.start),o=i.end?xi(t,i.end):s;if(s&&o)try{const a=t.createRange();return s.offset!==void 0?a.setStart(s.node,s.offset):a.setStartBefore(s.node),o.offset!==void 0?a.setEnd(o.node,o.offset):a.setEndBefore(o.node),a}catch(a){console.warn("Invalid domRange, falling back:",a)}}}if(n){const i=Dh(n);if(i){const s=wi(t,n),o=Bs(i,t,s);if(o.length>0)return o[0]}}if(r&&r.highlight){const i=wi(t,n),s=new _h(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&&Bn(n)&&(i=t.querySelector(Bn(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||Bh(i)?(s.selectNode(i),s):(s.setStartBefore(i),s.setEndAfter(i),s)}}}catch(n){console.error(n)}return null}function Uh(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 u=t.cloneRange();u.selectNode(a),u.compareBoundaryPoints(Range.START_TO_START,t)<0&&u.setStart(t.startContainer,t.startOffset),u.compareBoundaryPoints(Range.END_TO_END,t)>0&&u.setEnd(t.endContainer,t.endOffset);for(const h of u.getClientRects())r.push({left:h.left,right:h.right,top:h.top,bottom:h.bottom,width:h.width,height:h.height})}}a=o.nextNode()}return r}function Je(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 u of l)i.push({bottom:u.bottom,height:u.height,left:u.left,right:u.right,top:u.top,width:u.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=na(i,1,e,n),o=zh(s,1),a=ra(o),c=4;for(let l=a.length-1;l>=0;l--){const u=a[l];if(!(u.width*u.height>c))if(a.length>1)a.splice(l,1);else break}return a}function na(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=W(o.top,a.top,e)&&W(o.bottom,a.bottom,e),l=W(o.left,a.left,e)&&W(o.right,a.right,e);if((l&&!n&&!r||c&&!l)&&ia(o,a,e)){const u=t.filter(d=>d!==o&&d!==a),h=Vh(o,a);return u.push(h),na(u,e,n,r)}}return t}function Vh(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 zh(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)&&Mh(i,r,e)){n.delete(r);break}}return Array.from(n)}function Mh(t,e,n){return oe(t,e.left,e.top,n)&&oe(t,e.right,e.top,n)&&oe(t,e.left,e.bottom,n)&&oe(t,e.right,e.bottom,n)}function oe(t,e,n,r){return(t.left<e||W(t.left,e,r))&&(t.right>e||W(t.right,e,r))&&(t.top<n||W(t.top,n,r))&&(t.bottom>n||W(t.bottom,n,r))}function ra(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&&ia(r,i,-1)){let s=[],o;const a=Ei(r,i);if(a.length===1)s=a,o=r;else{const l=Ei(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),ra(c)}}return t}function Ei(t,e){const n=jh(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 jh(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 ia(t,e,n){return(t.left<e.right||n>=0&&W(t.left,e.right,n))&&(e.left<t.right||n>=0&&W(e.left,t.right,n))&&(t.top<e.bottom||n>=0&&W(t.top,e.bottom,n))&&(e.top<t.bottom||n>=0&&W(e.top,t.bottom,n))}function W(t,e,n){return Math.abs(t-e)<=n}const Ci=["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"],Hh=/^on/i,Wh=new Set(["href","src","action","formaction","xlink:href"]),Gh=/^\s*(javascript|data):/i;function Kh(t,e){const n=t.document.createElement("div");if("Sanitizer"in t&&typeof n.setHTML=="function")try{const i=new t.Sanitizer({allowElements:Ci});return n.setHTML(e,{sanitizer:i}),n.firstElementChild}catch{}const r=t.document.implementation.createHTMLDocument("");for(r.body.innerHTML=e,Jh(r.body,new Set(Ci));r.body.firstChild;)n.appendChild(t.document.adoptNode(r.body.firstChild));return n.firstElementChild}function Jh(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))(Hh.test(i)||Wh.has(i)&&Gh.test(s))&&r.removeAttribute(i)}}function vn(t){switch(t){case R.Mask:return"rgba(255, 255, 255, 0.5)";case R.Highlight:case R.HighlightUnderline:return"#FFFF00";default:return"#FF0000"}}const R={Highlight:"highlight",HighlightUnderline:"highlightUnderline",Underline:"underline",Strikethrough:"strikethrough",Outline:"outline",TextColor:"textColor",Mask:"mask",Template:"template"};var sa=(t=>(t.Wrap="wrap",t.Viewport="viewport",t.Bounds="bounds",t.Page="page",t))(sa||{}),aa=(t=>(t.Boxes="boxes",t.Bounds="bounds",t))(aa||{});const Xh=()=>"Highlight"in window,ki=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Yh{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,Xh()&&(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}get hasOverlayItems(){return!this.experimentalHighlights||(this.notTextFlag?.size??0)>0}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=qh(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&&(ki.includes(i.nodeName.toUpperCase())&&this.notTextFlag?.set(n,!0),r.cloneContents().querySelector(ki.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!==R.TextColor&&(o===R.Outline||o===R.Template||o===R.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(Je(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===R.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,n=Ee(this.wnd)){const 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=Ee(this.wnd);return{docX:e.clientX+n.xDocOffset,docY:e.clientY+n.yDocOffset}}effectiveZoom(){if(!nh.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===R.Template)for(const a of s.clickableElements??[]){const c=a.getBoundingClientRect();if(oe(c,e.clientX,e.clientY,0)){o=c;break}}else for(const a of s.hitRects)if(oe(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===R.Template)for(const c of a.clickableElements??[]){const l=c.getBoundingClientRect();if(oe(l,e.clientX,e.clientY,0)){s=a,o=l;break}}else for(const c of a.hitRects)if(oe(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(Je(e.range,!1,!1,(e.decoration.style.expand??0)+this.hitGap()))}),this.renderLayout(this.items),this.updateSharedMask()})})}repositionOverlays(){let e=!1;const n=[],r=Ee(this.wnd);this.items.forEach(i=>{if(!(this.experimentalHighlights&&!this.notTextFlag?.has(i.id))){if(i.decoration.style?.type===R.Mask){e=!0;return}this.repositionItem(i,r)||(i.container?.remove(),this.layout(i),n.push(i)),i.hitRects=this.clientRectsToDocCoords(Je(i.range,!1,!1,(i.decoration.style.expand??0)+this.hitGap()),r)}}),n.length&&this.renderLayout(n),e&&this.updateSharedMask()}experimentalLayout(e){const n=this.requireContainer(!0),r=this.wnd.CSS.highlights,i=e.decoration.style,s=i.type??R.Highlight,o=i.tint??vn(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(m=>m!==e&&m.highlightSubKey===e.highlightSubKey)&&r.delete(e.highlightSubKey)),e.highlightSubKey=l;let u;r.has(l)?u=r.get(l):(u=new this.wnd.Highlight,r.set(l,u));const h=(m,b)=>this.wnd.document.caretPositionFromPoint?.(m,b)??null;if(s===R.TextColor&&(c==="bounds"||a==="bounds"||a==="page")){const m=Ee(this.wnd);if(m.isVertical)console.warn("Vertical writing detected: caretPositionFromPoint has known bugs, falling back to original range"),u.add(e.range);else{const b=e.range.getBoundingClientRect();let x,A;a==="page"?(x=Math.floor(m.inlineStart(b)/m.pageInlineSize)*m.pageInlineSize,A=m.pageInlineSize):(x=m.inlineStart(b),A=m.inlineSize(b));const S=h(x,m.blockStart(b)+1),w=h(x+A,m.blockStart(b)+m.blockSize(b)-1);if(S&&w){const T=this.wnd.document.createRange();T.setStart(S.offsetNode,S.offset),T.setEnd(w.offsetNode,w.offset),u.add(T),e.range=T}else u.add(e.range)}}else u.add(e.range);const d=this.getBackgroundColor(),g=i.enforceContrast!==!1?ke(o,d):o;let p;switch(s){case R.Underline:p=`::highlight(${l}) {
|
|
25
|
+
`:F}`,v===a.lastClosingBracketAt+1&&(!t[v]||!gn.has(t[v]))&&(N+=" "),a.leftOuterWhitespace===a.lastOpeningBracketAt&&k.last()&&k.last()[1]<a.lastOpeningBracketAt&&(!y?.dumpLinkHrefsNearby?.putOnNewLine||!gn.has(t[v]))&&(N=" "+N)):N=F,N!==null&&(a.leftOuterWhitespace===0||!Y(t,v-1))&&(!y.dumpLinkHrefsNearby?.enabled||a.name!=="a")&&(N=void 0);let B=0;if(b&&gn.has(t[v])){y.dumpLinkHrefsNearby?.putOnNewLine&&(N=`${t[v]}${N||""}`);let we=Y(t,v);we&&N?.endsWith(`
|
|
26
|
+
`)?B+=we-f:(!we||we>f)&&B++}y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:v+B,insert:N,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,v+B,N]}),M(),S(f,y,k)}else a={};L(f)||(a={})}G&&(G=!1)}if((!_||t[f]==="<"&&Y(t,Y(t,f))&&t[Y(t,f)]==="/"&&t.startsWith("script",Y(t,Y(t,f))))&&I(f)&&!I(f-1)&&!`'"`.includes(t[f+1])&&(!`'"`.includes(t[f+2])||/\w/.test(t[f+1]))&&!(t[f+1]==="c"&&t[f+2]===":")&&!(t[f+1]==="f"&&t[f+2]==="m"&&t[f+3]==="t"&&t[f+4]===":")&&!(t[f+1]==="s"&&t[f+2]==="q"&&t[f+3]==="l"&&t[f+4]===":")&&!(t[f+1]==="x"&&t[f+2]===":")&&!(t[f+1]==="f"&&t[f+2]==="n"&&t[f+3]===":")&&ti(a,t,f)){if(L(Y(t,f)))continue;if(a.nameEnds&&a.nameEnds<f&&!a.lastClosingBracketAt&&(a.onlyPlausible===!0&&a.attributes?.length||a.onlyPlausible===!1)){let v=x(t,f,a.leftOuterWhitespace,f,a.lastOpeningBracketAt,f);y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:f,insert:v,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,f,v]}),S(f,y,k),a={},g={}}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=f,a.slashPresent=!1,a.attributes=[],l===null?a.leftOuterWhitespace=f:y.trimOnlySpaces&&l===0?a.leftOuterWhitespace=u||f:a.leftOuterWhitespace=l,`${t[f+1]}${t[f+2]}${t[f+3]}`=="!--"||`${t[f+1]}${t[f+2]}${t[f+3]}${t[f+4]}${t[f+5]}${t[f+6]}${t[f+7]}${t[f+8]}`=="![CDATA[")){let v=!0;t[f+2]==="-"&&(v=!1);let C;for(let E=f;E<U;E++)if((!C&&v&&`${t[E-2]}${t[E-1]}${t[E]}`=="]]>"||!v&&`${t[E-2]}${t[E-1]}${t[E]}`=="-->")&&(C=E),C&&(C<E&&t[E].trim()||t[E+1]===void 0)){let F=E;(t[E+1]===void 0&&!t[E].trim()||t[E]===">")&&(F+=1),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,C+1]),(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([a.lastOpeningBracketAt,C+1]);let N=x(t,E,a.leftOuterWhitespace,F,a.lastOpeningBracketAt,C);y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:F,insert:N,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,F,N]}),f=E-1,t[E]===">"&&(f=E),a={},g={};break}}}!t[f].trim()||t[f].charCodeAt(0)===847?(l===null&&(l=f,a.lastOpeningBracketAt!==void 0&&a.lastOpeningBracketAt<f&&a.nameStarts&&a.nameStarts<a.lastOpeningBracketAt&&f===a.lastOpeningBracketAt+1&&!r.some(v=>v.name===a.name)&&(a.onlyPlausible=!0,a.name=void 0,a.nameStarts=void 0)),(t[f]===`
|
|
27
|
+
`||t[f]==="\r")&&(h=f,d&&(d=!1))):(l!==null&&(!a.quotes&&g.equalsAt>l-1&&g.nameEnds&&g.equalsAt>g.nameEnds&&t[f]!=='"'&&t[f]!=="'"&&(Fn(g)&&a.attributes.push(g),g={},a.equalsSpottedAt=void 0),l=null),d||(d=!0,O&&!_&&typeof h=="number"&&f&&h<f-1&&(t.slice(h+1,f).trim()?h=null:y.ignoreIndentations||k.push([h+1,f])))),t[f]===" "?u===null&&(u=f):u!==null&&(u=null),a.name==="script"&&(_=!a.slashPresent)}if(t&&!y.ignoreIndentations&&(y.trimOnlySpaces&&t[0]===" "||!y.trimOnlySpaces&&!t[0].trim()))for(let f=0;f<U;f++)if(y.trimOnlySpaces&&t[f]!==" "||!y.trimOnlySpaces&&t[f].trim()){k.push([0,f]);break}else t[f+1]||k.push([0,f+1]);if(t&&(y.trimOnlySpaces&&t[~-t.length]===" "||!y.trimOnlySpaces&&!t[~-t.length].trim())){for(let f=t.length;f--;)if(y.trimOnlySpaces&&t[f]!==" "||!y.trimOnlySpaces&&t[f].trim()){k.push([f+1,U]);break}}let K=k.current();if(!e?.cb&&K&&(K[0]&&!K[0][0]&&(K[0][1],k.ranges[0]=[k.ranges[0][0],k.ranges[0][1]]),K[K.length-1]?.[1]===t.length&&(K[K.length-1][0],k.ranges))){let f=k.ranges[k.ranges.length-1][0];t[f-1]&&(y.trimOnlySpaces&&t[f-1]===" "||!y.trimOnlySpaces&&!t[f-1].trim())&&(f-=1);let v=k.ranges[k.ranges.length-1][2];k.ranges[k.ranges.length-1]=[f,k.ranges[k.ranges.length-1][1]],v?.trim()&&k.ranges[k.ranges.length-1].push(v.trimEnd())}return{log:{timeTakenInMilliseconds:Date.now()-n},result:yu(t,k.current()),ranges:k.current(),allTagLocations:s,filteredTagLocations:o}}class Ln{speechSynthesis;speechSynthesisUtterance;currentVoice=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Jt;voiceManager=null;voices=[];defaultVoice=null;speakInContentLanguage=!1;languageVoiceCache=new Map;warmingLanguages=new Map;speakGeneration=0;resumeInfinityTimer;isSpeakingInternal=!1;restartPending=!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=jo(),this.patches=Ho(),!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 P.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]=q(n),[s,o]=q(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=J(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=>J(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 P.initialize({languages:[o]}),this.voices=this.voiceManager.getVoices();const c=this.voices.filter(h=>this.voiceMatchesLanguage(h,o)),u=(await this.voiceManager.sortVoicesByQuality(c))[0]??null;this.languageVoiceCache.set(o,u),u||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?Ss(n.ssml).result:"")}))}loadUtterances(e,n){this.currentUtterances=this.toPlainText(e),this.currentUtteranceIndex=Ot(n??0,e.length),this.warmLanguageVoiceCache(this.currentUtterances),this.playbackState="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.restartPending=!1,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>=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.cancelCurrentSpeech(),this.speakGeneration++,this.currentUtteranceIndex=0,this.patches.isAndroid&&(this.isAndroidPaused=!1),this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){const n=me(e,.1,10,this.rate);n!==this.rate&&(this.rate=n,this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const n=me(e,0,2,this.pitch);n!==this.pitch&&(this.pitch=n,this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const n=me(e,0,1,this.volume);n!==this.volume&&(this.volume=n,this.scheduleRestartIfSpeaking())}getVolume(){return this.volume}scheduleRestartIfSpeaking(){!this.isSpeakingInternal||this.restartPending||(this.restartPending=!0,queueMicrotask(()=>{this.restartPending&&(this.restartPending=!1,this.isSpeakingInternal&&this.speak(this.currentUtteranceIndex))}))}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.events.on(e,n)}emitEvent(e){this.events.emit(e.type,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.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[],this.defaultVoice=null,this.languageVoiceCache.clear(),this.warmingLanguages.clear(),this.initialized=!1}}class ku{id="webspeech";name="Web Speech API";voiceEngine=null;async getVoices(){return this.voiceEngine||(this.voiceEngine=new Ln,await this.voiceEngine.initialize()),this.voiceEngine.getAvailableVoices()}async createEngine(e){const n=new Ln;return await n.initialize(),e&&await n.setVoice(e),n}async destroy(){this.voiceEngine&&(await this.voiceEngine.destroy(),this.voiceEngine=null)}}const De="\\p{Pe}\\p{Pf}.,;:!?,。、;:!?،؛؟",$n="\\p{Ps}\\p{Pi}¿¡",Ou=new RegExp(`^[${De}]`,"u"),Au=new RegExp(`^[${$n}]`,"u");function Qt(t){return Ou.test(t)}function Tu(t){return Au.test(t)}function vs(t,e){const n=[];let r=-1,i=-1;const s=()=>{r!==-1&&(n.push({text:Ru(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 Ru(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 ws=new RegExp(`[^${De}]*[${De}]+\\s*|[^${De}]+$`,"gu"),Nu=/\S+\s*|\s+/g;function ur(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 hr(t,e){if(t.text.length<=e||t.atomic)return[t];const n=ur(t.text,t.offset,Nu);if(n.length>1)return n.flatMap(o=>hr(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 xs(t,e){if(t.length<=e)return[{text:t,offset:0}];const r=ur(t,0,ws).flatMap(i=>hr(i,e));return vs(r,e)}const Du=/<([a-zA-Z][\w-]*)\b[^>]*>[\s\S]*?<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function Es(t,e){if(t.length<=e)return[{text:t,offset:0}];const n=[];for(const i of t.matchAll(Du))i[0][0]==="<"?n.push({text:i[0],offset:i.index,atomic:!0}):n.push(...ur(i[0],i.index,ws));const r=n.flatMap(i=>hr(i,e));return vs(r,e)}const Fu={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 Cs(t){return Fu[t]??`audio/${t}`}const Iu=["flac","wav","opus","aac","ogg","webm","mp3"],Pu=["opus","aac","webm","ogg","mp3","wav","flac"];function ks(t,e,n){const r=a=>n(Cs(a))!=="",i=t.formats.filter(r);if(e.preferredFormat&&i.includes(e.preferredFormat))return e.preferredFormat;const s=e.strategy==="bandwidth"?Pu:Iu,o=[...s,...i.filter(a=>!s.includes(a))];for(const a of o)if(i.includes(a))return a;return t.default}const Lu=new Set(["wav","flac"]),$u={mp3:48e3,opus:24e3,aac:48e3,ogg:48e3,webm:32e3};function Os(t,e,n){return Lu.has(t)||!e||!n?void 0:n.saveData===!0||/2g/.test(n.effectiveType??"")?$u[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 qe 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}}class fr extends qe{constructor(e){super(e,{status:408,type:"https://readium.org/speech-server/error#stall",title:"Synthesis Stalled"}),this.name="SpeechServerStallError"}}class gr extends Error{constructor(e){super(e),this.name="SpeechServerAudioDecodeError"}}class pr extends Error{constructor(e){super(e),this.name="SpeechServerNetworkError"}}async function Fe(t){if((t.headers.get("content-type")??"").includes("application/problem+json"))try{const n=await t.json();return new qe(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 qe(`Request failed with status ${t.status}`,{status:t.status})}const _u=3,Bu=400;function qu(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 Uu(t){return me(t,.25,4,1)}function yt(t){return t?.plain??t?.ssml??void 0}function ii(t){return t instanceof fr?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance,recoverable:!0}:t instanceof qe?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance,recoverable:!1}:t instanceof gr?{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 As{endpoints;fetchImpl;currentVoice=null;voices=[];serviceInfo=null;serviceInfoPromise=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Jt;speakInContentLanguage=!1;speakGeneration=0;loadGeneration=0;prefetchWindow;readyBufferChars;overLengthText;timeoutMs;formatOptions;canPlayType;prefetchCache=new Map;prefetchChainTail=Promise.resolve();activeControllers=new Set;liveControllers=new Set;isSpeakingInternal=!1;restartPending=!1;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??_u,this.readyBufferChars=e.readyBufferChars??Bu,this.overLengthText=e.overLengthText??"split",this.timeoutMs=e.timeoutMs,this.formatOptions=e.format??{},this.canPlayType=typeof Audio<"u"?n=>new Audio().canPlayType(n):()=>""}setAvailableVoices(e){this.voices=e}async fetchNetwork(e,n){try{return await this.fetchImpl(e,n)}catch(r){throw r instanceof TypeError?new pr(r.message):r}}loadUtterances(e,n){this.abortLiveControllers(),this.clearPrefetchCache(),this.currentUtterances=e,this.currentUtteranceIndex=Ot(n??0,e.length),this.setState("loading"),this.bufferUntilReady(++this.loadGeneration)}async bufferUntilReady(e){const n=Ot(this.currentUtteranceIndex,this.currentUtterances.length),r=Math.min(this.indexCoveringChars(this.readyBufferChars,n),n+this.prefetchWindow),i=[];for(let s=n;s<=r;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,n){if(this.currentUtterances.length===0)return-1;const r=Ot(n,this.currentUtterances.length);let i=0;for(let s=r;s<this.currentUtterances.length;s++)if(i+=(yt(this.currentUtterances[s])??"").length,i>=e)return s;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.abortLiveControllers(),this.clearPrefetchCache()}getCurrentVoice(){return this.currentVoice}async getAvailableVoices(){if(this.voices.length>0)return this.voices;const[e,n]=await Promise.all([this.fetchNetwork(this.endpoints.voices),this.getServiceInfo()]);if(!e.ok)throw await Fe(e);const r=await e.json(),i=new Map(n.providers.map(s=>[s.id,s.controls]));return this.voices=r.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 Fe(e);return e.json()}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,this.abortLiveControllers(),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.restartPending=!1,this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.stopAudio(),this.abortLiveControllers();const n=++this.speakGeneration;this.isSpeakingInternal=!0,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.isSpeakingInternal=!1,this.setState("idle"),this.emitEvent({type:"error",detail:ii(r)})}}async resolveSynthesisStream(e){const n=this.prefetchCache.get(e);if(n){this.prefetchCache.delete(e);try{const r=await n;for(const{controller:i}of r)this.activeControllers.delete(i),this.liveControllers.add(i);return r}catch{}}return this.synthesizeStream(e,!1)}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,!0));this.prefetchCache.set(e,n),this.prefetchChainTail=n.then(r=>Promise.all(r.map(i=>i.promise))).then(()=>{},()=>{}),n.catch(()=>{}),n.then(r=>r.forEach(i=>i.promise.catch(()=>{}))).catch(()=>{})}clearPrefetchCache(){this.prefetchCache.clear(),this.activeControllers.forEach(e=>e.abort()),this.activeControllers.clear()}abortLiveControllers(){this.liveControllers.forEach(e=>e.abort()),this.liveControllers.clear()}async synthesizeStream(e,n){const r=this.currentUtterances[e],i=!r.plain&&!!r.ssml,s=this.speakInContentLanguage?r.language:void 0,o=yt(r)??"",a=yt(this.currentUtterances[e-1]),c=yt(this.currentUtterances[e+1]),l=await this.getServiceInfo(),u=ks(l.output,this.formatOptions,this.canPlayType),h=navigator.connection,d=Os(u,this.formatOptions.adaptBitrateToNetwork??!1,h);if(o.length<=l.limits.maxTextLength){const w=new AbortController;return(n?this.activeControllers:this.liveControllers).add(w),[{promise:this.synthesizeChunk(r,o,0,i,s,a,c,u,d,w),controller:w}]}if(this.overLengthText==="error")throw new qe(`Text exceeds this server's maximum length of ${l.limits.maxTextLength} characters`,{status:413,type:"https://readium.org/speech-server/error#payload_too_large",title:"Payload Too Large"});const g=Math.min(l.limits.maxTextLength,this.readyBufferChars),p=i?Es(o,g):xs(o,g),m=[];let b=Promise.resolve();for(let w=0;w<p.length;w++){const O=w===0?a:p[w-1].text,S=w===p.length-1?c:p[w+1].text,x=p[w],R=new AbortController;(n?this.activeControllers:this.liveControllers).add(R);const I=b.then(()=>this.synthesizeChunk(r,x.text,x.offset,i,s,O,S,u,d,R));m.push({promise:I,controller:R}),b=I}return m}async synthesizeChunk(e,n,r,i,s,o,a,c,l,u){try{const h=await this.fetchNetwork(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}}),signal:u.signal});if(!h.ok)throw await Fe(h);const d=await h.json(),g=qu(d.audio);let p;try{p=await this.ensureAudioContext().decodeAudioData(g)}catch{throw new gr("Audio playback failed")}return{audioBuffer:p,format:d.format,boundaries:d.boundaries,textOffset:r}}finally{this.activeControllers.delete(u),this.liveControllers.delete(u)}}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,n,r){if(this.timeoutMs===void 0)return e;const i=r+this.timeoutMs;return new Promise((s,o)=>{const a=setTimeout(()=>{n.abort(),o(new fr(`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,n){const r=await this.awaitWithStallDeadline(e[0].promise,e[0].controller,0);if(n!==this.speakGeneration)return;const i=this.ensureAudioContext(),s=this.masterGain,a=this.currentVoice?.controls?.speed===!0?1:Uu(this.rate);this.scheduledChunks=[],this.setState("playing"),this.emitEvent({type:"start"});let c=i.currentTime,l=null;const u=h=>{const d=i.createBufferSource();d.buffer=h.audioBuffer,d.playbackRate.value=a,d.connect(s),d.start(c),l&&(l.onended=null),d.onended=()=>this.handleUtteranceEnded(n),l=d,this.scheduledChunks.push({chunk:h,startTime:c,node:d,nextBoundaryIndex:0,rate:a}),c+=h.audioBuffer.duration/a};u(r),this.startBoundaryPolling(n);for(let h=1;h<e.length;h++){let d;try{const g=Math.max(0,(c-i.currentTime)*1e3);d=await this.awaitWithStallDeadline(e[h].promise,e[h].controller,g)}catch(g){n===this.speakGeneration&&this.emitEvent({type:"error",detail:ii(g)});return}if(n!==this.speakGeneration)return;u(d)}}handleUtteranceEnded(e){e===this.speakGeneration&&(this.checkBoundaries(),this.stopBoundaryPolling(),this.isSpeakingInternal=!1,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.isSpeakingInternal=!1,this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.audioContext&&(this.audioContext.resume().catch(()=>{}),this.startBoundaryPolling(this.speakGeneration),this.isSpeakingInternal=!0,this.setState("playing"),this.emitEvent({type:"resume"}))}stop(){this.speakGeneration++,this.loadGeneration++,this.stopAudio(),this.abortLiveControllers(),this.clearPrefetchCache(),this.isSpeakingInternal=!1,this.currentUtteranceIndex=0,this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){const n=me(e,.1,10,this.rate);n!==this.rate&&(this.rate=n,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const n=me(e,0,2,this.pitch);n!==this.pitch&&(this.pitch=n,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const n=me(e,0,1,this.volume);n!==this.volume&&(this.volume=n,this.masterGain&&(this.masterGain.gain.value=this.volume))}getVolume(){return this.volume}scheduleRestartIfSpeaking(){!this.isSpeakingInternal||this.restartPending||(this.restartPending=!0,queueMicrotask(()=>{this.restartPending&&(this.restartPending=!1,this.isSpeakingInternal&&this.speak(this.currentUtteranceIndex))}))}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.events.on(e,n)}emitEvent(e){this.events.emit(e.type,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.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[]}}class zu{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[n,r]=await Promise.all([this.fetchImpl(this.options.endpoints.voices),this.fetchImpl(this.options.endpoints.service)]);if(!n.ok)throw await Fe(n);if(!r.ok)throw await Fe(r);const i=await n.json(),s=await r.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 n=new As(this.options);return this.voices.length>0&&n.setAvailableVoices(this.voices),e&&n.setVoice(e),n}async destroy(){this.voices=[]}}function Ts(t){return t.detail?.recoverable===!0}const Vu=3e4,Mu=["start","pause","resume","end","stop","skip","boundary","mark","idle","loading","ready","voiceschanged","languagefallback"];class Rs{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 Jt;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??Vu,this.lastVoiceRequest=e.primaryEngine.getCurrentVoice()??void 0,this.bindActiveEngine()}async initialize(){return this.activeEngine.initialize?.()}loadUtterances(e,n){this.loadToken++,this.currentUtterances=e,this.desiredIndex=n??0,this.desiredPlaying=!1,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.loadUtterances(e,n))}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,n){if(this.desiredIndex=e,!this.isEngineTrusted()){n?.(!0);return}this.activeEngine.setCurrentUtteranceIndex(e,n)}getUtteranceCount(){return this.activeEngine.getUtteranceCount()}on(e,n){return this.events.on(e,n)}emitEvent(e){this.events.emit(e.type,e)}bindActiveEngine(){const e=this.activeEngine,n=Mu.map(r=>e.on(r,i=>{this.emitEvent(i),this.maybeRecoverNow()}));n.push(e.on("error",r=>this.handleError(r))),this.unbindActiveEngine=()=>n.forEach(r=>r())}handleError(e){if(this.hasFallenBack||this.swapInFlight||this.onFailure==="error"||!Ts(e)){this.emitEvent(e);return}this.swapToFallback(e)}copyPlaybackParameters(e,n){n.setRate(e.getRate()),n.setPitch(e.getPitch()),n.setVolume(e.getVolume()),n.setSpeakInContentLanguage(e.getSpeakInContentLanguage())}startEngineWhenReady(e){const n=this.loadToken,r=e.on("ready",()=>{r(),n===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 n=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");if(n=await this.pickBestFallbackVoice(s,i?.gender),!n)throw new Error("no offline-available fallback voice found");return this.fallbackProvider.createEngine(n)},()=>(this.hasFallenBack=!0,this.onFailure==="fallbackAndRecover"&&this.startHealthCheck(),{type:"enginefallback",detail:{reason:e.detail,voice:n}}),()=>{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,n,r){this.swapInFlight=!0;const i=this.teardownEpoch,s=this.activeEngine;let o;try{o=await e()}catch{this.swapInFlight=!1,r();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(n(o)),this.startEngineWhenReady(o),o.loadUtterances(this.currentUtterances,this.desiredIndex),await s.destroy()}async pickBestFallbackVoice(e,n){const r=await this.fallbackProvider.getVoices(),s=typeof navigator<"u"&&navigator.onLine===!0?r:r.filter(d=>d.offlineAvailability===!0);if(s.length===0)return null;const[o]=Gt([e]),{voicesByLang:a}=Kt(s,[o]),c=a.get(o.baseLang)??[],l=c.length>0?c:s,u=n?l.filter(d=>d.gender===n):[],h=u.length>0?u:l;return ko(e,h)}async destroy(){this.teardownEpoch++,this.healthCheckTimer!==null&&(clearTimeout(this.healthCheckTimer),this.healthCheckTimer=null),this.unbindActiveEngine?.(),this.events.clear(),await this.activeEngine.destroy()}}class ju{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(n){if(this.onFailure==="error")throw n;return this.fallback.getVoices(e)}}async createEngine(e){let n;try{n=await this.primary.createEngine(e)}catch(r){if(this.onFailure==="error")throw r;return this.fallback.createEngine(e)}return new Rs({primaryEngine:n,primaryProvider:this.primary,fallbackProvider:this.fallback,onFailure:this.onFailure,healthCheckIntervalMs:this.healthCheckIntervalMs})}async destroy(){await Promise.all([this.primary.destroy(),this.fallback.destroy()])}}let Hu=class{};function Wu(t){return(t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode)==="vertical-lr"}function Gu(t){const e=t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode;return e==="vertical-rl"||e==="vertical-lr"}function Ee(t){const e=Gu(t),n=e&&Wu(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,u=a;return{isVertical:e,isVertLR:n,viewportInlineSize:e?i:r,viewportBlockSize:e?r:i,pageInlineSize:e?i:r/(c||1),xDocOffset:l,yDocOffset:u,inlineScrollOffset:e?u:l,blockScrollOffset:e?l:u,inlineStart:h=>e?h.top:h.left,blockStart:h=>e?h.left:h.top,inlineSize:h=>e?h.height:h.width,blockSize:h=>e?h.width:h.height,applyPosition(h,d,g,p,m,b){h.style.position="absolute",e?(h.style.top=`${d*b}px`,h.style.left=`${g*b}px`,h.style.height=`${p*b}px`,h.style.width=`${m*b}px`):(h.style.left=`${d*b}px`,h.style.top=`${g*b}px`,h.style.width=`${p*b}px`,h.style.height=`${m*b}px`)},toRect(h,d,g,p){return e?new DOMRect(d,h,p,g):new DOMRect(h,d,g,p)}}}function si(t,e){return t.document.documentElement.style.getPropertyValue(e)}function Ku(t){return t&&Array.isArray(t)?t:void 0}function Ju(t){return t&&typeof t=="string"?[t]:Ku(t)}function At(t){return isNaN(t)?void 0:t}function pn(t){return At(t)!==void 0&&Math.sign(t)>=0?t:void 0}let It=class Ns{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let n=pn(e.textNodeIndex);if(n===void 0)return;let r=pn(e.charOffset);return r===void 0&&(r=pn(e.offset)),new Ns({cssSelector:e.cssSelector,textNodeIndex:n,charOffset:r})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}},Ds=class Fs{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let n=It.deserialize(e.start);if(n)return new Fs({start:n,end:It.deserialize(e.end)})}serialize(){const e={start:this.start.serialize()};return this.end&&(e.end=this.end.serialize()),e}},bt=null,mn=null,Ke=0;const Ae={r:255,g:255,b:255,a:1},Ce=new Map,Xu=()=>{if(!bt)if(typeof OffscreenCanvas<"u")bt=new OffscreenCanvas(5,5),mn=bt.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const t=document.createElement("canvas");t.width=5,t.height=5,bt=t,mn=t.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return mn},Yu=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))},St=(t,e)=>{console.warn(`[Decorator] Could not parse color: "${t}". ${e} Falling back to ${JSON.stringify(Ae)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},be=(t,e=null)=>{const n=e?`${t}|${e}`:t,r=Ce.get(n);if(r!==void 0)return r??Ae;if(Yu(t))return St(t,"Unsupported color format or special value."),Ce.set(n,null),Ae;const i=Xu();if(!i)return St(t,"Could not get canvas context."),Ce.set(n,null),Ae;try{Ke===0&&i.clearRect(0,0,5,5);const s=Ke%5,o=Math.floor(Ke/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);Ke=(Ke+1)%25;const[c,l,u,h]=a.data;if(h===0)return St(t,"Fully transparent color."),Ce.set(n,null),Ae;const d={r:c,g:l,b:u,a:h/255};return Ce.set(n,d),d}catch(s){return St(t,`Error: ${s instanceof Error?s.message:String(s)}`),Ce.set(n,null),Ae}},yn=t=>{const e=t/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},_n=t=>{const e=yn(t.r),n=yn(t.g),r=yn(t.b);return .2126*e+.7152*n+.0722*r},Pt=(t,e)=>{const n=typeof t=="string"?be(t):t,r=typeof e=="string"?be(e):e,i=_n(n),s=_n(r),o=Math.max(i,s),a=Math.min(i,s);return(o+.05)/(a+.05)},Is=(t,e=null)=>{const n=be(t,e),r=Pt(n,{r:255,g:255,b:255,a:1}),i=Pt(n,{r:0,g:0,b:0,a:1});return r>i},ai=(t,e=null)=>Is(t,e)?"white":"black",Qu=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})`},Zu=(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}),eh=(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}),ke=(t,e=null,n=3)=>{const r=be(t),i=e?be(e):{r:255,g:255,b:255,a:1};let s=Pt(r,i);if(s>=n)return t;const o=_n(i)<.5;let a={...r,a:r.a??1};const c=20,l=.1;for(let u=0;u<c&&(o?a=Zu(a,l):a=eh(a,l),s=Pt(a,i),!(s>=n));u++);return Qu(a)},Ps=()=>typeof navigator>"u"?"":navigator.userAgent||"",Ls=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;let $s=class{constructor(){const e=Ls(),n=Ps(),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},[])}}},th=class extends $s{get iOSRequest(){const e=Ls(),n=Ps();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 nh=new $s;new th;const oi=":~:text=";function rh(t){if(!t)return;const e=t.indexOf(oi);if(e===-1)return;const n=t.slice(e+oi.length).split("&")[0];if(n)try{let r=n.split(",");const i={textStart:""};return r.length>1&&r[0].endsWith("-")&&(i.prefix=decodeURIComponent(r[0].slice(0,-1)),r=r.slice(1)),r.length>1&&r[r.length-1].startsWith("-")&&(i.suffix=decodeURIComponent(r[r.length-1].slice(1)),r=r.slice(0,-1)),r.length===0||r[0]===""?void 0:(i.textStart=decodeURIComponent(r[0]),r.length>1&&(i.textEnd=decodeURIComponent(r[1])),i)}catch{return}}const _s=["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","BR","DETAILS","DIALOG","DD","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","LI","MAIN","NAV","OL","P","PRE","SECTION","TABLE","UL","TR","TH","TD","COLGROUP","COL","CAPTION","THEAD","TBODY","TFOOT"],Qe=/[\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u,ih=/[^\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u,Bs=(t,e,n)=>{const r=[],i=e.createRange();for(i.selectNodeContents(n??e);!i.collapsed&&r.length<2;){let s;if(t.prefix){const o=Ze(t.prefix,i);if(o==null)break;vt(i,o.startContainer,o.startOffset);const a=e.createRange();if(a.setStart(o.endContainer,o.endOffset),a.setEnd(i.endContainer,i.endOffset),qs(a),a.collapsed||(s=Ze(t.textStart,a),s==null))break;if(s.compareBoundaryPoints(Range.START_TO_START,a)!==0)continue}else{if(s=Ze(t.textStart,i),s==null)break;vt(i,s.startContainer,s.startOffset)}if(t.textEnd){const o=e.createRange();o.setStart(s.endContainer,s.endOffset),o.setEnd(i.endContainer,i.endOffset);let a=!1;for(;!o.collapsed&&r.length<2;){const c=Ze(t.textEnd,o);if(c==null)break;if(vt(o,c.startContainer,c.startOffset),s.setEnd(c.endContainer,c.endOffset),t.suffix){const l=li(t.suffix,s,i,e);if(l===te.NO_SUFFIX_MATCH)break;if(l===te.SUFFIX_MATCH){a=!0,r.push(s.cloneRange());continue}else if(l===te.MISPLACED_SUFFIX)continue}else a=!0,r.push(s.cloneRange())}if(!a)break}else if(t.suffix){const o=li(t.suffix,s,i,e);if(o===te.NO_SUFFIX_MATCH)break;if(o===te.SUFFIX_MATCH){r.push(s.cloneRange()),vt(i,i.startContainer,i.startOffset);continue}else if(o===te.MISPLACED_SUFFIX)continue}else r.push(s.cloneRange())}return r},te={NO_SUFFIX_MATCH:0,SUFFIX_MATCH:1,MISPLACED_SUFFIX:2},li=(t,e,n,r)=>{const i=r.createRange();i.setStart(e.endContainer,e.endOffset),i.setEnd(n.endContainer,n.endOffset),qs(i);const s=Ze(t,i);return s==null?te.NO_SUFFIX_MATCH:s.compareBoundaryPoints(Range.START_TO_START,i)!==0?te.MISPLACED_SUFFIX:te.SUFFIX_MATCH},vt=(t,e,n)=>{try{t.setStart(e,n+1)}catch{t.setStartAfter(e)}},qs=t=>{const e=Us(t);let n=e.nextNode();for(;!t.collapsed&&n!=null;){if(n!==t.startContainer&&t.setStart(n,0),n.textContent.length>t.startOffset&&!n.textContent[t.startOffset].match(/\s/))return;try{t.setStart(n,t.startOffset+1)}catch{n=e.nextNode(),n==null?t.collapse():t.setStart(n,0)}}},Us=t=>(t.commonAncestorContainer.ownerDocument??t.commonAncestorContainer).createTreeWalker(t.commonAncestorContainer,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode:e=>ah(e,t)}),sh=t=>{if(t.hidden==="until-found")return!0;const e=t.attributes;return!!(e&&e.hidden&&e.hidden.value==="until-found")},mr=t=>{let e=t;for(;e!=null&&!(e instanceof HTMLElement);)e=e.parentNode;const n=e?.ownerDocument?.defaultView;if(e!=null&&n!=null){if(sh(e))return!0;const r=n.getComputedStyle(e);if(r.visibility==="hidden"||r.display==="none"||parseInt(r.height,10)===0&&r.overflowY!="visible"||parseInt(r.width,10)===0&&r.overflowX!="visible"||parseInt(r.opacity,10)===0)return!1}return!0},zs=(t,e)=>e!=null&&!e.intersectsNode(t)?NodeFilter.FILTER_REJECT:mr(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT,ah=(t,e)=>e!=null&&!e.intersectsNode(t)||!mr(t)?NodeFilter.FILTER_REJECT:t.nodeType===Node.TEXT_NODE?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,oh=(t,e)=>{const n=[];let r=[];const i=Array.from(ch(t,s=>zs(s,e)));for(const s of i)s.nodeType===Node.TEXT_NODE?r.push(s):s instanceof HTMLElement&&_s.includes(s.tagName.toUpperCase())&&r.length>0&&(n.push(r),r=[]);return r.length>0&&n.push(r),n},lh=(t,e,n)=>{let r="";return t.length===1?r=t[0].textContent.substring(e,n):r=t[0].textContent.substring(e)+t.slice(1,-1).reduce((i,s)=>i+s.textContent,"")+t.slice(-1)[0].textContent.substring(0,n),r.replace(/[\t\n\r ]+/g," ")};function*ch(t,e){const n=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:e}),r=new Set;for(;Ms(n,r)!==null;)yield n.currentNode}const Ze=(t,e)=>{const n=oh(e.commonAncestorContainer,e),r=Vs(e.commonAncestorContainer.ownerDocument??void 0);for(const i of n){const s=uh(t,e,i,r);if(s!==void 0)return s}},uh=(t,e,n,r)=>{if(!t||!e||!(n||[]).length)return;const i=n[0]===e.startContainer?e.startOffset:0,s=oe(lh(n,i,void 0)),o=oe(t);let a=0,c,l;for(;a<s.length;){const u=s.indexOf(o,a);if(u===-1)return;if(hh(s,u,o.length,r)){const h=oe(n[0].data.slice(0,i)).length;c=ci(h+u,n,!1),l=ci(h+u+o.length,n,!0)}if(c!=null&&l!=null){const h=new Range;if(h.setStart(c.node,c.offset),h.setEnd(l.node,l.offset),e.compareBoundaryPoints(Range.START_TO_START,h)<=0&&e.compareBoundaryPoints(Range.END_TO_END,h)>=0)return h}a=u+1}},ci=(t,e,n)=>{let r=0,i;for(let s=0;s<e.length;s++){const o=e[s];i||(i=oe(o.data));let a=r+i.length;if(n&&(a+=1),a>t){const c=t-r;let l=Math.min(t-r,o.data.length);const u=n?i.substring(0,c):i.substring(c);let h=oe(n?o.data.substring(0,l):o.data.substring(l));const d=(n?-1:1)*(u.length>h.length?-1:1);for(;l>=0&&l<=o.data.length;){if(h.length===u.length)return{node:o,offset:l};l+=d,h=oe(n?o.data.substring(0,l):o.data.substring(l))}}if(r+=i.length,s+1<e.length){const c=oe(e[s+1].data);i.slice(-1)===" "&&c.slice(0,1)===" "&&(r-=1),i=c}}},hh=(t,e,n,r)=>{if(e<0||e>=t.length||n<=0||e+n>t.length)return!1;if(r){const i=r.segment(t),s=i.containing(e);if(!s||s.isWordLike&&s.index!=e)return!1;const o=e+n,a=i.containing(o);if(a&&a.isWordLike&&a.index!=o)return!1}else if(t[e].match(Qe)&&(++e,--n,!n)||t[e+n-1].match(Qe)&&(--n,!n)||e!==0&&!t[e-1].match(Qe)||e+n!==t.length&&!t[e+n].match(Qe))return!1;return!0},oe=t=>(t||"").normalize("NFKD").replace(/\s+/g," ").replace(/[\u0300-\u036f]/g,"").toLowerCase(),Vs=t=>{if(Intl.Segmenter){const e=t?.documentElement?.lang||t?.defaultView?.navigator?.language||void 0;return new Intl.Segmenter(e,{granularity:"word"})}},Ms=(t,e)=>{if(!e.has(t.currentNode)){const i=t.firstChild();if(i!==null)return i}const n=t.nextSibling();if(n!==null)return n;const r=t.parentNode();return r!==null&&e.add(r),r},dh=(t,e)=>{if(!e.has(t.currentNode)){const i=t.lastChild();if(i!==null)return i}const n=t.previousSibling();if(n!==null)return n;const r=t.parentNode();return r!==null&&e.add(r),r},D={BLOCK_ELEMENTS:_s,BOUNDARY_CHARS:Qe,NON_BOUNDARY_CHARS:ih,acceptNodeIfVisibleInRange:zs,normalizeString:oe,makeNewSegmenter:Vs,forwardTraverse:Ms,backwardTraverse:dh,makeTextNodeWalker:Us,isNodeVisible:mr},fh=300,js=20,gh=1,ui=3,hi=1;let ph=500,Hs;class Ws extends Error{constructor(){super(...arguments),this.isTimeout=!0}}const fe={SUCCESS:0,INVALID_SELECTION:1,AMBIGUOUS:2,TIMEOUT:3,EXECUTION_FAILED:4},mh=(t,e=Date.now())=>{try{return yh(t,e)}catch(n){return n instanceof Ws?{status:fe.TIMEOUT}:{status:fe.EXECUTION_FAILED}}},yh=(t,e)=>{Sh(e);const n=t.startContainer.ownerDocument,r=bh(n);Oh(t),Rh(t);const i=t.cloneRange();if(Ah(t),t.collapsed)return{status:fe.INVALID_SELECTION};let s;if(wh(t)){const h=D.normalizeString(t.toString()),d={textStart:h};if(h.length>=js&&Ks(d,n,r))return{status:fe.SUCCESS,fragment:d};s=new bn(n,r).setExactTextMatch(h)}else{const h=di(t),d=fi(t);h&&d?s=new bn(n,r).setStartAndEndSearchSpace(h,d):s=new bn(n,r).setSharedSearchSpace(t.toString().trim())}const o=n.createRange();o.selectNodeContents(r);const a=o.cloneRange();o.setEnd(i.startContainer,i.startOffset),a.setStart(i.endContainer,i.endOffset);const c=fi(o),l=di(a);(c||l)&&s.setPrefixAndSuffixSearchSpace(c,l),s.useSegmenter(D.makeNewSegmenter(n));let u=!1;do{j(),u=s.embiggen();const h=s.tryToMakeUniqueFragment();if(h!=null)return{status:fe.SUCCESS,fragment:h}}while(u);return{status:fe.AMBIGUOUS}},bh=t=>t.querySelector("body")??t.documentElement,j=()=>{const t=Date.now()-Hs;if(t>ph)throw new Ws(`Fragment generation timed out after ${t} ms.`)},Sh=t=>{Hs=t},di=t=>{let e=ht(t);const n=Se(e,t.endContainer);if(!n)return;const r=new Set;t.startContainer.nodeType===Node.ELEMENT_NODE&&t.startOffset===t.startContainer.childNodes.length&&r.add(t.startContainer);const i=e,s=new Gs(t,!0),o=t.cloneRange();for(;!o.collapsed&&e!=null;){if(j(),e.contains?.(i)?o.setStartAfter(e):o.setStartBefore(e),s.appendNode(e),s.textInBlock!==null)return s.textInBlock;e=D.forwardTraverse(n,r)}},fi=t=>{let e=Zt(t);const n=Se(e,t.startContainer);if(!n)return;const r=new Set;t.endContainer.nodeType===Node.ELEMENT_NODE&&t.endOffset===0&&r.add(t.endContainer);const i=e,s=new Gs(t,!1),o=t.cloneRange();for(;!o.collapsed&&e!=null;){if(j(),e.contains?.(i)?o.setEnd(e,0):o.setEndAfter(e),s.appendNode(e),s.textInBlock!==null)return s.textInBlock;e=D.backwardTraverse(n,r)}},vh={ALL_PARTS:1,SHARED_START_AND_END:2,CONTEXT_ONLY:3};let bn=class{constructor(e,n){this.Mode=vh,this.startOffset=null,this.endOffset=null,this.prefixOffset=null,this.suffixOffset=null,this.prefixSearchSpace="",this.backwardsPrefixSearchSpace="",this.suffixSearchSpace="",this.numIterations=0,this.doc=e,this.root=n}tryToMakeUniqueFragment(){let e;if(this.mode===this.Mode.CONTEXT_ONLY?e={textStart:this.exactTextMatch}:e={textStart:this.getStartSearchSpace().substring(0,this.startOffset).trim(),textEnd:this.getEndSearchSpace().substring(this.endOffset).trim()},this.prefixOffset!=null){const n=this.getPrefixSearchSpace().substring(this.prefixOffset).trim();n&&(e.prefix=n)}if(this.suffixOffset!=null){const n=this.getSuffixSearchSpace().substring(0,this.suffixOffset).trim();n&&(e.suffix=n)}return Ks(e,this.doc,this.root)?e:void 0}embiggen(){let e=!0;if(this.mode===this.Mode.SHARED_START_AND_END?this.startOffset>=this.endOffset&&(e=!1):this.mode===this.Mode.ALL_PARTS?this.startOffset===this.getStartSearchSpace().length&&this.backwardsEndOffset()===this.getEndSearchSpace().length&&(e=!1):this.mode===this.Mode.CONTEXT_ONLY&&(e=!1),e){const r=this.getNumberOfRangeWordsToAdd();if(this.startOffset<this.getStartSearchSpace().length){let i=0;if(this.getStartSegments()!=null)for(;i<r&&this.startOffset<this.getStartSearchSpace().length;)this.startOffset=this.getNextOffsetForwards(this.getStartSegments(),this.startOffset,this.getStartSearchSpace()),i++;else{let s=this.startOffset;do{j();const o=this.getStartSearchSpace().substring(this.startOffset+1).search(D.BOUNDARY_CHARS);o===-1?this.startOffset=this.getStartSearchSpace().length:this.startOffset=this.startOffset+1+o,this.getStartSearchSpace().substring(s,this.startOffset).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.startOffset,i++)}while(this.startOffset<this.getStartSearchSpace().length&&i<r)}this.mode===this.Mode.SHARED_START_AND_END&&(this.startOffset=Math.min(this.startOffset,this.endOffset))}if(this.backwardsEndOffset()<this.getEndSearchSpace().length){let i=0;if(this.getEndSegments()!=null)for(;i<r&&this.endOffset>0;)this.endOffset=this.getNextOffsetBackwards(this.getEndSegments(),this.endOffset),i++;else{let s=this.backwardsEndOffset();do{j();const o=this.getBackwardsEndSearchSpace().substring(this.backwardsEndOffset()+1).search(D.BOUNDARY_CHARS);o===-1?this.setBackwardsEndOffset(this.getEndSearchSpace().length):this.setBackwardsEndOffset(this.backwardsEndOffset()+1+o),this.getBackwardsEndSearchSpace().substring(s,this.backwardsEndOffset()).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.backwardsEndOffset(),i++)}while(this.backwardsEndOffset()<this.getEndSearchSpace().length&&i<r)}this.mode===this.Mode.SHARED_START_AND_END&&(this.endOffset=Math.max(this.startOffset,this.endOffset))}}let n=!1;if((!e||this.startOffset+this.backwardsEndOffset()<js||this.numIterations>=gh)&&(this.backwardsPrefixOffset()!=null&&this.backwardsPrefixOffset()!==this.getPrefixSearchSpace().length||this.suffixOffset!=null&&this.suffixOffset!==this.getSuffixSearchSpace().length)&&(n=!0),n){const r=this.getNumberOfContextWordsToAdd();if(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length){let i=0;if(this.getPrefixSegments()!=null)for(;i<r&&this.prefixOffset>0;)this.prefixOffset=this.getNextOffsetBackwards(this.getPrefixSegments(),this.prefixOffset),i++;else{let s=this.backwardsPrefixOffset();do{j();const o=this.getBackwardsPrefixSearchSpace().substring(this.backwardsPrefixOffset()+1).search(D.BOUNDARY_CHARS);o===-1?this.setBackwardsPrefixOffset(this.getBackwardsPrefixSearchSpace().length):this.setBackwardsPrefixOffset(this.backwardsPrefixOffset()+1+o),this.getBackwardsPrefixSearchSpace().substring(s,this.backwardsPrefixOffset()).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.backwardsPrefixOffset(),i++)}while(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length&&i<r)}}if(this.suffixOffset<this.getSuffixSearchSpace().length){let i=0;if(this.getSuffixSegments()!=null)for(;i<r&&this.suffixOffset<this.getSuffixSearchSpace().length;)this.suffixOffset=this.getNextOffsetForwards(this.getSuffixSegments(),this.suffixOffset,this.getSuffixSearchSpace()),i++;else{let s=this.suffixOffset;do{j();const o=this.getSuffixSearchSpace().substring(this.suffixOffset+1).search(D.BOUNDARY_CHARS);o===-1?this.suffixOffset=this.getSuffixSearchSpace().length:this.suffixOffset=this.suffixOffset+1+o,this.getSuffixSearchSpace().substring(s,this.suffixOffset).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.suffixOffset,i++)}while(this.suffixOffset<this.getSuffixSearchSpace().length&&i<r)}}}return this.numIterations++,e||n}setStartAndEndSearchSpace(e,n){return this.startSearchSpace=e,this.endSearchSpace=n,this.backwardsEndSearchSpace=Tt(n),this.startOffset=0,this.endOffset=n.length,this.mode=this.Mode.ALL_PARTS,this}setSharedSearchSpace(e){return this.sharedSearchSpace=e,this.backwardsSharedSearchSpace=Tt(e),this.startOffset=0,this.endOffset=e.length,this.mode=this.Mode.SHARED_START_AND_END,this}setExactTextMatch(e){return this.exactTextMatch=e,this.mode=this.Mode.CONTEXT_ONLY,this}setPrefixAndSuffixSearchSpace(e,n){return e&&(this.prefixSearchSpace=e,this.backwardsPrefixSearchSpace=Tt(e),this.prefixOffset=e.length),n&&(this.suffixSearchSpace=n,this.suffixOffset=0),this}useSegmenter(e){return e==null?this:(this.mode===this.Mode.ALL_PARTS?(this.startSegments=e.segment(this.startSearchSpace),this.endSegments=e.segment(this.endSearchSpace)):this.mode===this.Mode.SHARED_START_AND_END&&(this.sharedSegments=e.segment(this.sharedSearchSpace)),this.prefixSearchSpace&&(this.prefixSegments=e.segment(this.prefixSearchSpace)),this.suffixSearchSpace&&(this.suffixSegments=e.segment(this.suffixSearchSpace)),this)}getNumberOfContextWordsToAdd(){return this.backwardsPrefixOffset()===0&&this.suffixOffset===0?ui:hi}getNumberOfRangeWordsToAdd(){return this.startOffset===0&&this.backwardsEndOffset()===0?ui:hi}getNextOffsetForwards(e,n,r){let i=e.containing(n);for(;i!=null;){j();const s=i.index+i.segment.length;if(i.isWordLike)return s;i=e.containing(s)}return r.length}getNextOffsetBackwards(e,n){let r=e.containing(n);for((!r||n==r.index)&&(r=e.containing(n-1));r!=null;){if(j(),r.isWordLike)return r.index;r=e.containing(r.index-1)}return 0}getStartSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSearchSpace:this.startSearchSpace}getStartSegments(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSegments:this.startSegments}getEndSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSearchSpace:this.endSearchSpace}getEndSegments(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSegments:this.endSegments}getBackwardsEndSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.backwardsSharedSearchSpace:this.backwardsEndSearchSpace}getPrefixSearchSpace(){return this.prefixSearchSpace}getPrefixSegments(){return this.prefixSegments}getBackwardsPrefixSearchSpace(){return this.backwardsPrefixSearchSpace}getSuffixSearchSpace(){return this.suffixSearchSpace}getSuffixSegments(){return this.suffixSegments}backwardsEndOffset(){return this.getEndSearchSpace().length-this.endOffset}setBackwardsEndOffset(e){this.endOffset=this.getEndSearchSpace().length-e}backwardsPrefixOffset(){return this.prefixOffset==null?null:this.getPrefixSearchSpace().length-this.prefixOffset}setBackwardsPrefixOffset(e){this.prefixOffset!=null&&(this.prefixOffset=this.getPrefixSearchSpace().length-e)}};class Gs{constructor(e,n){this.textFound=!1,this.textNodes=[],this.textInBlock=null,this.searchRange=e,this.isForwardTraversal=n}appendNode(e){if(this.textInBlock!==null)return;if(ce(e)){this.textFound?(this.isForwardTraversal||this.textNodes.reverse(),this.textInBlock=this.textNodes.map(r=>r.textContent).join("").trim()):this.textNodes=[];return}if(!yr(e))return;const n=this.getNodeIntersectionWithRange(e);this.textFound=this.textFound||(n.textContent??"").trim()!=="",this.textNodes.push(n)}getNodeIntersectionWithRange(e){let n=null,r=null;const i=(e.textContent??"").length;return e===this.searchRange.startContainer&&this.searchRange.startOffset!==0&&(n=this.searchRange.startOffset),e===this.searchRange.endContainer&&this.searchRange.endOffset!==i&&(r=this.searchRange.endOffset),n!==null||r!==null?{textContent:(e.textContent??"").substring(n??0,r??i)}:e}}const Ks=(t,e,n)=>Bs(t,e,n).length===1,Tt=t=>[...t||""].reverse().join(""),wh=t=>t.toString().length>fh?!1:!Ch(t),ht=t=>{let e=t.startContainer;return e.nodeType==Node.ELEMENT_NODE&&t.startOffset<e.childNodes.length&&(e=e.childNodes[t.startOffset]),e},Zt=t=>{let e=t.endContainer;return e.nodeType==Node.ELEMENT_NODE&&t.endOffset>0&&(e=e.childNodes[t.endOffset-1]),e},xh=t=>{const e=ht(t);if(yr(e)&&D.isNodeVisible(e))return e;const n=D.makeTextNodeWalker(t);return n.currentNode=e,n.nextNode()},Eh=t=>{const e=Zt(t);if(yr(e)&&D.isNodeVisible(e))return e;const n=D.makeTextNodeWalker(t);return n.currentNode=e,D.backwardTraverse(n,new Set)},Ch=t=>{const e=t.cloneRange();let n=ht(e);const r=Se(n);if(!r)return!1;const i=new Set;for(;!e.collapsed&&n!=null;){if(ce(n))return!0;n!=null&&e.setStartAfter(n),n=D.forwardTraverse(r,i),j()}return!1},gi=(t,e)=>{if(t.nodeType!==Node.TEXT_NODE)return-1;const n=t,r=e??n.data.length;if(r<n.data.length&&D.BOUNDARY_CHARS.test(n.data[r]))return r;const i=n.data.substring(0,r),s=Tt(i).search(D.BOUNDARY_CHARS);return s!==-1?r-s:-1},kh=(t,e)=>{if(t.nodeType!==Node.TEXT_NODE)return-1;const n=t,r=e??0;if(r<n.data.length&&r>0&&D.BOUNDARY_CHARS.test(n.data[r-1]))return r;const i=n.data.substring(r).search(D.BOUNDARY_CHARS);return i!==-1?r+i:-1},Se=(t,e)=>{if(!t)return;let n=t;const r=e??t;for(;!n.contains?.(r)||!ce(n);)n.parentNode&&(n=n.parentNode);const i=(n.ownerDocument??n).createTreeWalker(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:s=>D.acceptNodeIfVisibleInRange(s)});return i.currentNode=t,i},Oh=t=>{const e=D.makeNewSegmenter(t.startContainer.ownerDocument??void 0);if(e){const n=ht(t);n!==t.startContainer&&t.setStartBefore(n),Js(e,!1,t)}else{const n=gi(t.startContainer,t.startOffset);if(n!==-1){t.setStart(t.startContainer,n);return}if(ce(t.startContainer)&&t.startOffset===0)return;const r=Se(t.startContainer);if(!r)return;const i=new Set;let s=D.backwardTraverse(r,i);for(;s!=null;){const o=gi(s);if(o!==-1){t.setStart(s,o);return}if(ce(s)){s.contains?.(t.startContainer)?t.setStart(s,0):t.setStartAfter(s);return}s=D.backwardTraverse(r,i),t.collapse()}}},Ah=t=>{const e=xh(t);if(e==null){t.collapse();return}ht(t)!==e&&t.setStart(e,0);const n=Zt(t),r=Eh(t);n!==r&&t.setEnd(r,(r.textContent??"").length)},Js=(t,e,n)=>{const r=e?{node:n.endContainer,offset:n.endOffset}:{node:n.startContainer,offset:n.startOffset},i=Th(r.node);if(!i)return;const s=i.preNodes.reduce((p,m)=>p.concat(m.textContent??""),""),o=i.innerNodes.reduce((p,m)=>p.concat(m.textContent??""),"");let a=s.length;r.node.nodeType===Node.TEXT_NODE?a+=r.offset:e&&(a+=o.length);const c=i.postNodes.reduce((p,m)=>p.concat(m.textContent??""),""),l=[...i.preNodes,...i.innerNodes,...i.postNodes];if(l.length==0)return;const u=s.concat(o,c),h=t.segment(u).containing(a);if(!h){e?n.setEndAfter(l[l.length-1]):n.setEndBefore(l[0]);return}if(!h.isWordLike||a===h.index||a===h.index+h.segment.length)return;const d=e?h.index+h.segment.length:h.index;let g=0;for(const p of l){const m=(p.textContent??"").length;if(g<=d&&d<g+m){const b=d-g;e?b>=m?n.setEndAfter(p):n.setEnd(p,b):b>=m?n.setStartAfter(p):n.setStart(p,b);return}g+=m}e?n.setEndAfter(l[l.length-1]):n.setStartBefore(l[0])},Th=t=>{const e=[],n=Se(t);if(!n)return;const r=new Set;let i=D.backwardTraverse(n,r);for(;i!=null&&!ce(i);)j(),i.nodeType===Node.TEXT_NODE&&e.push(i),i=D.backwardTraverse(n,r);e.reverse();const s=[];if(t.nodeType===Node.TEXT_NODE)s.push(t);else{const u=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:d=>D.acceptNodeIfVisibleInRange(d)});u.currentNode=t;let h=u.nextNode();for(;h!=null;)j(),h.nodeType===Node.TEXT_NODE&&s.push(h),h=u.nextNode()}const o=[],a=Se(t);if(!a)return;const c=new Set([t]);let l=D.forwardTraverse(a,c);for(;l!=null&&!ce(l);)j(),l.nodeType===Node.TEXT_NODE&&o.push(l),l=D.forwardTraverse(a,c);return{preNodes:e,innerNodes:s,postNodes:o}},Rh=t=>{const e=D.makeNewSegmenter(t.endContainer.ownerDocument??void 0);if(e){const n=Zt(t);n!==t.endContainer&&t.setEndAfter(n),Js(e,!0,t)}else{let n=t.endOffset,r=t.endContainer;r.nodeType===Node.ELEMENT_NODE&&t.endOffset<r.childNodes.length&&(r=r.childNodes[t.endOffset]);const i=Se(r);if(!i)return;const s=new Set([r]);for(;r!=null;){j();const o=kh(r,n);if(n=null,o!==-1){t.setEnd(r,o);return}if(ce(r)){r.contains?.(t.endContainer)?t.setEnd(r,r.childNodes.length):t.setEndBefore(r);return}r=D.forwardTraverse(i,s)}t.collapse()}},ce=t=>t.nodeType===Node.ELEMENT_NODE&&(D.BLOCK_ELEMENTS.includes(t.tagName.toUpperCase())||t.tagName.toUpperCase()==="HTML"||t.tagName.toUpperCase()==="BODY"),yr=t=>t.nodeType===Node.TEXT_NODE;function Bn(t){return t.otherLocations?.get("cssSelector")}function Nh(t){return Ds.deserialize(t.otherLocations?.get("domRange"))}function Dh(t){for(const e of t.fragments){const n=rh(e);if(n)return n}}let he=class Xs{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=At(e.progression),r=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 Xs({fragments:Ju(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}},br=class Ys{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new Ys({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}},Sr=class qn{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 he({...e.locations,fragments:[r]}):e.locations:r?new he({fragments:[r]}):new he({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new qn({href:e.href,type:e.type,title:e.title,locations:he.deserialize(e.locations),text:br.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 qn({href:this.href,type:this.type,title:this.title,text:this.text,locations:new he({...this.locations,...e})})}};function pi(t){return t.split("").reverse().join("")}function Fh(t,e,n){const r=pi(e);return n.map(i=>{const s=Math.max(0,i.end-e.length-i.errors),o=pi(t.slice(s,i.end));return{start:Qs(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 Sn(t){return(t|-t)>>31&1}function mi(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 u=s|~(l|i),h=i&l;const d=Sn(u&t.lastRowMask[n])-Sn(h&t.lastRowMask[n]);return u<<=1,h<<=1,h|=o,u|=Sn(r)-o,i=h|~(c|u),s=u&c,t.P[n]=i,t.M[n]=s,d}function Qs(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 d=0;d<256;d++)l.push(a);for(let d=0;d<e.length;d+=1){const g=e.charCodeAt(d);if(c.has(g))continue;const p=new Uint32Array(s+1);c.set(g,p),g<l.length&&(l[g]=p);for(let m=0;m<=s;m+=1){p[m]=0;for(let b=0;b<i;b+=1){const w=m*i+b;w>=e.length||e.charCodeAt(w)===g&&(p[m]|=1<<b)}}}let u=Math.max(0,Math.ceil(n/i)-1);const h=new Uint32Array(s+1);for(let d=0;d<=u;d+=1)h[d]=(d+1)*i;h[s]=e.length;for(let d=0;d<=u;d+=1)o.P[d]=-1,o.M[d]=0;for(let d=0;d<t.length;d+=1){const g=t.charCodeAt(d);let p;g<l.length?p=l[g]:(p=c.get(g),typeof p>"u"&&(p=a));let m=0;for(let b=0;b<=u;b+=1)m=mi(o,p,b,m),h[b]+=m;if(h[u]-m<=n&&u<s&&(p[u+1]&1||m<0)){u+=1,o.P[u]=-1,o.M[u]=0;let b;if(u===s){const w=e.length%i;b=w===0?i:w}else b=i;h[u]=h[u-1]+b-m+mi(o,p,u,m)}else for(;u>0&&h[u]>=n+i;)u-=1;u===s&&h[u]<=n&&(h[u]<n&&r.splice(0,r.length),r.push({start:-1,end:d+1,errors:h[u]}),n=h[u])}return r}function Ih(t,e,n){const r=Qs(t,e,n);return Fh(t,e,r)}function Zs(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:Ih(t,e,n)}function yi(t,e){return e.length===0||t.length===0?0:1-Zs(t,e,e.length)[0].errors/e.length}function Ph(t,e,n={}){if(e.length===0)return null;const r=Math.min(256,e.length/2),i=Zs(t,e,r);if(i.length===0)return null;const s=a=>{const c=1-a.errors/e.length,l=n.prefix?yi(t.slice(Math.max(0,a.start-n.prefix.length),a.start),n.prefix):1,u=n.suffix?yi(t.slice(a.end,a.end+n.suffix.length),n.suffix):1;let h=1;return typeof n.hint=="number"&&(h=1-Math.abs(a.start-n.hint)/t.length),(50*c+20*l+20*u+2*h)/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 Un(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 bi(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=Un(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 Lh(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:Un(t.startContainer.textContent,t.startOffset,1),end:Un(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}=bi(e,1);s&&o>=0&&e.setStart(s,o)}if(!r){const{node:s,offset:o}=bi(e,2);s&&o>0&&e.setEnd(s,o)}return e}function ea(t){switch(t.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return t.textContent?.length??0;default:return 0}}function Si(t){let e=t.previousSibling,n=0;for(;e;)n+=ea(e),e=e.previousSibling;return n}function ta(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 wt=class Te{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+=Si(n),n=n.parentElement;return new Te(n,r)}resolve(e={}){try{return ta(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 Te.fromPoint(e,n);case Node.ELEMENT_NODE:return new Te(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=Si(e)+n;return new Te(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+=ea(e.childNodes[i]);return new Te(e,r)}default:throw new Error("Point is not in an element or text node")}}},zn=class et{constructor(e,n){this.start=e,this.end=n}relativeTo(e){return new et(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]=ta(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=wt.fromPoint(e.startContainer,e.startOffset),r=wt.fromPoint(e.endContainer,e.endOffset);return new et(n,r)}static fromOffsets(e,n,r){return new et(new wt(e,n),new wt(e,r))}static trimmedRange(e){return Lh(et.fromRange(e).toRange())}},$h=class Vn{constructor(e,n,r){this.root=e,this.start=n,this.end=r}static fromRange(e,n){const r=zn.fromRange(n).relativeTo(e);return new Vn(e,r.start.offset,r.end.offset)}static fromSelector(e,n){return new Vn(e,n.start,n.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return zn.fromOffsets(this.root,this.start,this.end).toRange()}},_h=class Mn{constructor(e,n,r={}){this.root=e,this.exact=n,this.context=r}static fromRange(e,n){const r=e.textContent,i=zn.fromRange(n).relativeTo(e),s=i.start.offset,o=i.end.offset,a=32;return new Mn(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 Mn(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=Ph(n,this.exact,{...this.context,hint:e.hint});if(!r)throw new Error("Quote not found");return new $h(this.root,r.start,r.end)}};function Bh(t){const e=t.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function vi(t,e){const n=e&&Bn(e);let r=null;if(n)try{r=t.querySelector(n)}catch(i){console.warn(`Invalid cssSelector: ${n}`,i)}return r??t.body??t.documentElement}function wi(t,e){let n;try{n=t.querySelector(e.cssSelector)}catch(i){return console.error(`Invalid domRange cssSelector: ${e.cssSelector}`,i),null}if(!n)return console.error(`Can't resolve domRange cssSelector: ${e.cssSelector}`),null;let r=0;for(const i of n.childNodes)if(i.nodeType===Node.TEXT_NODE){if(r===e.textNodeIndex)return{node:i,offset:e.charOffset};r++}return console.error(`Can't resolve domRange textNodeIndex ${e.textNodeIndex} for selector: ${e.cssSelector}`),null}function qh(t,e){try{const n=e.locations,r=e.text;if(n){const i=Nh(n);if(i){const s=wi(t,i.start),o=i.end?wi(t,i.end):s;if(s&&o)try{const a=t.createRange();return s.offset!==void 0?a.setStart(s.node,s.offset):a.setStartBefore(s.node),o.offset!==void 0?a.setEnd(o.node,o.offset):a.setEndBefore(o.node),a}catch(a){console.warn("Invalid domRange, falling back:",a)}}}if(n){const i=Dh(n);if(i){const s=vi(t,n),o=Bs(i,t,s);if(o.length>0)return o[0]}}if(r&&r.highlight){const i=vi(t,n),s=new _h(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&&Bn(n)&&(i=t.querySelector(Bn(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||Bh(i)?(s.selectNode(i),s):(s.setStartBefore(i),s.setEndAfter(i),s)}}}catch(n){console.error(n)}return null}function Uh(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 u=t.cloneRange();u.selectNode(a),u.compareBoundaryPoints(Range.START_TO_START,t)<0&&u.setStart(t.startContainer,t.startOffset),u.compareBoundaryPoints(Range.END_TO_END,t)>0&&u.setEnd(t.endContainer,t.endOffset);for(const h of u.getClientRects())r.push({left:h.left,right:h.right,top:h.top,bottom:h.bottom,width:h.width,height:h.height})}}a=o.nextNode()}return r}function Je(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 u of l)i.push({bottom:u.bottom,height:u.height,left:u.left,right:u.right,top:u.top,width:u.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=na(i,1,e,n),o=Vh(s,1),a=ra(o),c=4;for(let l=a.length-1;l>=0;l--){const u=a[l];if(!(u.width*u.height>c))if(a.length>1)a.splice(l,1);else break}return a}function na(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=W(o.top,a.top,e)&&W(o.bottom,a.bottom,e),l=W(o.left,a.left,e)&&W(o.right,a.right,e);if((l&&!n&&!r||c&&!l)&&ia(o,a,e)){const u=t.filter(d=>d!==o&&d!==a),h=zh(o,a);return u.push(h),na(u,e,n,r)}}return t}function zh(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 Vh(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)&&Mh(i,r,e)){n.delete(r);break}}return Array.from(n)}function Mh(t,e,n){return le(t,e.left,e.top,n)&&le(t,e.right,e.top,n)&&le(t,e.left,e.bottom,n)&&le(t,e.right,e.bottom,n)}function le(t,e,n,r){return(t.left<e||W(t.left,e,r))&&(t.right>e||W(t.right,e,r))&&(t.top<n||W(t.top,n,r))&&(t.bottom>n||W(t.bottom,n,r))}function ra(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&&ia(r,i,-1)){let s=[],o;const a=xi(r,i);if(a.length===1)s=a,o=r;else{const l=xi(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),ra(c)}}return t}function xi(t,e){const n=jh(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 jh(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 ia(t,e,n){return(t.left<e.right||n>=0&&W(t.left,e.right,n))&&(e.left<t.right||n>=0&&W(e.left,t.right,n))&&(t.top<e.bottom||n>=0&&W(t.top,e.bottom,n))&&(e.top<t.bottom||n>=0&&W(e.top,t.bottom,n))}function W(t,e,n){return Math.abs(t-e)<=n}const Ei=["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"],Hh=/^on/i,Wh=new Set(["href","src","action","formaction","xlink:href"]),Gh=/^\s*(javascript|data):/i;function Kh(t,e){const n=t.document.createElement("div");if("Sanitizer"in t&&typeof n.setHTML=="function")try{const i=new t.Sanitizer({allowElements:Ei});return n.setHTML(e,{sanitizer:i}),n.firstElementChild}catch{}const r=t.document.implementation.createHTMLDocument("");for(r.body.innerHTML=e,Jh(r.body,new Set(Ei));r.body.firstChild;)n.appendChild(t.document.adoptNode(r.body.firstChild));return n.firstElementChild}function Jh(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))(Hh.test(i)||Wh.has(i)&&Gh.test(s))&&r.removeAttribute(i)}}function vn(t){switch(t){case T.Mask:return"rgba(255, 255, 255, 0.5)";case T.Highlight:case T.HighlightUnderline:return"#FFFF00";default:return"#FF0000"}}const T={Highlight:"highlight",HighlightUnderline:"highlightUnderline",Underline:"underline",Strikethrough:"strikethrough",Outline:"outline",TextColor:"textColor",Mask:"mask",Template:"template"};var sa=(t=>(t.Wrap="wrap",t.Viewport="viewport",t.Bounds="bounds",t.Page="page",t))(sa||{}),aa=(t=>(t.Boxes="boxes",t.Bounds="bounds",t))(aa||{});const Xh=()=>"Highlight"in window,Ci=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Yh{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,Xh()&&(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}get hasOverlayItems(){return!this.experimentalHighlights||(this.notTextFlag?.size??0)>0}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=qh(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&&(Ci.includes(i.nodeName.toUpperCase())&&this.notTextFlag?.set(n,!0),r.cloneContents().querySelector(Ci.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!==T.TextColor&&(o===T.Outline||o===T.Template||o===T.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(Je(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===T.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,n=Ee(this.wnd)){const 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=Ee(this.wnd);return{docX:e.clientX+n.xDocOffset,docY:e.clientY+n.yDocOffset}}effectiveZoom(){if(!nh.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===T.Template)for(const a of s.clickableElements??[]){const c=a.getBoundingClientRect();if(le(c,e.clientX,e.clientY,0)){o=c;break}}else for(const a of s.hitRects)if(le(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===T.Template)for(const c of a.clickableElements??[]){const l=c.getBoundingClientRect();if(le(l,e.clientX,e.clientY,0)){s=a,o=l;break}}else for(const c of a.hitRects)if(le(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(Je(e.range,!1,!1,(e.decoration.style.expand??0)+this.hitGap()))}),this.renderLayout(this.items),this.updateSharedMask()})})}repositionOverlays(){let e=!1;const n=[],r=Ee(this.wnd);this.items.forEach(i=>{if(!(this.experimentalHighlights&&!this.notTextFlag?.has(i.id))){if(i.decoration.style?.type===T.Mask){e=!0;return}this.repositionItem(i,r)||(i.container?.remove(),this.layout(i),n.push(i)),i.hitRects=this.clientRectsToDocCoords(Je(i.range,!1,!1,(i.decoration.style.expand??0)+this.hitGap()),r)}}),n.length&&this.renderLayout(n),e&&this.updateSharedMask()}experimentalLayout(e){const n=this.requireContainer(!0),r=this.wnd.CSS.highlights,i=e.decoration.style,s=i.type??T.Highlight,o=i.tint??vn(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(m=>m!==e&&m.highlightSubKey===e.highlightSubKey)&&r.delete(e.highlightSubKey)),e.highlightSubKey=l;let u;r.has(l)?u=r.get(l):(u=new this.wnd.Highlight,r.set(l,u));const h=(m,b)=>this.wnd.document.caretPositionFromPoint?.(m,b)??null;if(s===T.TextColor&&(c==="bounds"||a==="bounds"||a==="page")){const m=Ee(this.wnd);if(m.isVertical)console.warn("Vertical writing detected: caretPositionFromPoint has known bugs, falling back to original range"),u.add(e.range);else{const b=e.range.getBoundingClientRect();let w,O;a==="page"?(w=Math.floor(m.inlineStart(b)/m.pageInlineSize)*m.pageInlineSize,O=m.pageInlineSize):(w=m.inlineStart(b),O=m.inlineSize(b));const S=h(w,m.blockStart(b)+1),x=h(w+O,m.blockStart(b)+m.blockSize(b)-1);if(S&&x){const R=this.wnd.document.createRange();R.setStart(S.offsetNode,S.offset),R.setEnd(x.offsetNode,x.offset),u.add(R),e.range=R}else u.add(e.range)}}else u.add(e.range);const d=this.getBackgroundColor(),g=i.enforceContrast!==!1?ke(o,d):o;let p;switch(s){case T.Underline:p=`::highlight(${l}) {
|
|
28
28
|
text-decoration: underline;
|
|
29
29
|
text-decoration-color: ${g};
|
|
30
30
|
text-decoration-thickness: 0.1em;
|
|
31
|
-
}`;break;case
|
|
31
|
+
}`;break;case T.Strikethrough:p=`::highlight(${l}) {
|
|
32
32
|
text-decoration: line-through;
|
|
33
33
|
text-decoration-color: ${g};
|
|
34
34
|
text-decoration-thickness: 0.1em;
|
|
35
|
-
}`;break;case
|
|
35
|
+
}`;break;case T.Outline:p=`::highlight(${l}) {
|
|
36
36
|
outline: 2px solid ${g};
|
|
37
37
|
outline-offset: 1px;
|
|
38
|
-
}`;break;case
|
|
38
|
+
}`;break;case T.TextColor:p=`::highlight(${l}) {
|
|
39
39
|
color: ${g};
|
|
40
|
-
}`;break;case
|
|
41
|
-
color: ${
|
|
42
|
-
background-color: ${
|
|
40
|
+
}`;break;case T.HighlightUnderline:{const{r:m,g:b,b:w}=be(g),O=`rgba(${m}, ${b}, ${w}, 0.3)`;p=`::highlight(${l}) {
|
|
41
|
+
color: ${ai(g,d)};
|
|
42
|
+
background-color: ${O};
|
|
43
43
|
text-decoration: underline;
|
|
44
44
|
text-decoration-color: ${g};
|
|
45
45
|
text-decoration-thickness: 0.1em;
|
|
46
|
-
}`;break}case
|
|
47
|
-
color: ${
|
|
46
|
+
}`;break}case T.Highlight:default:p=`::highlight(${l}) {
|
|
47
|
+
color: ${ai(g,d)};
|
|
48
48
|
background-color: ${g};
|
|
49
49
|
}`}e.highlightCSS=p,this._rebuildHighlightStylesheet(n)}_getSubKey(e,n){const r=`${e}::${n}`;let i=this._tintSubKeys.get(r);return i||(i=`${this.id}--${this._subKeyCounter++}`,this._tintSubKeys.set(r,i)),i}_rebuildHighlightStylesheet(e){const n=new Set,r=[];for(const i of this.items)i.highlightSubKey&&i.highlightCSS&&!n.has(i.highlightSubKey)&&(n.add(i.highlightSubKey),r.push(i.highlightCSS));e.innerHTML=r.join(`
|
|
50
|
-
`)}positionElement(e,n,r,i,s,o,a=0){const c=e.decoration?.style?.width,l=s;switch(c){case"viewport":{const u=Math.floor(n.inlineStart(l)/n.viewportInlineSize)*n.viewportInlineSize;n.applyPosition(i,u+n.inlineScrollOffset+a,n.blockStart(l)+n.blockScrollOffset,n.viewportInlineSize-2*a,n.blockSize(l),r);break}case"page":{const u=Math.floor(n.inlineStart(l)/n.pageInlineSize)*n.pageInlineSize;n.applyPosition(i,u+n.inlineScrollOffset+a,n.blockStart(l)+n.blockScrollOffset,n.pageInlineSize-2*a,n.blockSize(l),r);break}case"bounds":{n.applyPosition(i,n.inlineStart(o)+n.inlineScrollOffset,n.blockStart(l)+n.blockScrollOffset,n.inlineSize(o),n.blockSize(l),r);break}default:n.applyPosition(i,n.inlineStart(l)+n.inlineScrollOffset,n.blockStart(l)+n.blockScrollOffset,n.inlineSize(l),n.blockSize(l),r)}}computeOverlayRects(e,n,r,i){if(e.decoration?.style?.layout==="bounds")return[i?{left:r.left-i,right:r.right+i,top:r.top-i,bottom:r.bottom+i,width:r.width+i*2,height:r.height+i*2}:r];const s=e.decoration.style.type,o=s===R.Underline||s===R.Strikethrough,a=s===R.Strikethrough,c=o?Uh(e.range,["rt","rp"]):e.range;let l=Je(c,!0,n.isVertical,o?0:i);return l=l.sort((u,h)=>n.isVertical?(n.isVertLR?1:-1)*(u.left-h.left):u.top-h.top),l.map(u=>{let h=u;if(a){const d=n.blockSize(u)*.1,g=n.blockStart(u)+n.blockSize(u)/2-d/2;h=n.isVertical?{left:g,right:g+d,top:u.top,bottom:u.bottom,width:d,height:u.height}:{top:g,bottom:g+d,left:u.left,right:u.right,height:d,width:u.width}}return i&&o&&(h=n.isVertical?{...h,top:h.top-i,bottom:h.bottom+i,height:h.height+i*2}:{...h,left:h.left-i,right:h.right+i,width:h.width+i*2}),h})}repositionItem(e,n){if(!e.container)return!0;const r=e.decoration.style;if(r.type!==R.Template){const u=r.type??R.Highlight;if(u===R.TextColor||u===R.Mask)return!0}const i=1/this.effectiveZoom(),s=r.expand??0,o=e.range.getBoundingClientRect(),a=(()=>{if(r.type!==R.Outline)return 0;const u=r.width;return u==="page"||u==="viewport"?3:0})(),c=this.computeOverlayRects(e,n,o,s),l=Array.from(e.container.children);return l.length!==c.length?!1:(l.forEach((u,h)=>this.positionElement(e,n,i,u,c[h],o,a)),!0)}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=Ee(this.wnd),i=1/this.effectiveZoom(),s=e.decoration.style.expand??0,o=e.range.getBoundingClientRect(),a=e.decoration.style,c=(()=>{if(a.type!==R.Outline)return 0;const h=a.width;return h==="page"||h==="viewport"?3:0})();let l;if(a.type===R.Template){a.stylesheet&&this.injectCustomStylesheet(a.stylesheet);const h=Kh(this.wnd,a.element);if(!h){e.container=n,e.clickableElements=[];return}h.style.setProperty("pointer-events","none"),l=h}else{const h=a,d=h.type??R.Highlight,g=h.tint??vn(d);if(d===R.TextColor){e.container=n,e.clickableElements=[];return}if(d===R.Mask){e.container=n,e.clickableElements=[],this.updateSharedMask();return}const p=this.getCurrentDarkMode(),m=this.getBackgroundColor(),b=h.enforceContrast!==!1,x=(()=>{switch(d){case R.Underline:{const S=b?ke(g,m):g,w=h.layout==="bounds",[T,F]=r.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[w?`${F}: 0.1em solid ${S} !important`:null,`${T}: 0.1em solid ${S} !important`,"background-color: transparent !important","box-sizing: border-box !important"].filter(Boolean).join("; ")}case R.Strikethrough:{const S=b?ke(g,m):g;return h.layout==="bounds"?[`background: repeating-linear-gradient(-45deg, transparent, transparent 19px, ${S} 19px, ${S} 20px) !important`,"background-color: transparent !important","box-sizing: border-box !important"].join("; "):[`background-color: ${S} !important`,"box-sizing: border-box !important"].join("; ")}case R.Outline:return[`outline: 2px solid ${b?ke(g,m):g} !important`,"outline-offset: 1px !important","background-color: transparent !important","box-sizing: border-box !important"].join("; ");case R.HighlightUnderline:{const S=b?ke(g,m):g,{r:w,g:T,b:F}=be(S),L=`rgba(${w}, ${T}, ${F}, 0.3)`,X=h.layout==="bounds",[M,y]=r.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[`background-color: ${L} !important`,X?`${y}: 0.1em solid ${S} !important`:null,`${M}: 0.1em solid ${S} !important`,"box-sizing: border-box !important"].filter(Boolean).join("; ")}case R.Highlight:default:return[`background-color: ${b?ke(g,m):g} !important`,`mix-blend-mode: ${p?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important","transform: translateZ(0) !important"].join("; ")}})(),A=this.wnd.document.createElement("template");A.innerHTML=`<div data-readium="true" class="readium-${d}" style="${x}"></div>`.trim(),l=A.content.firstElementChild}const u=this.computeOverlayRects(e,r,o,s);for(const h of u){const d=l.cloneNode(!0);d.style.setProperty("pointer-events","none"),this.positionElement(e,r,i,d,h,o,c),n.append(d)}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 ai(this.wnd,"--USER__appearance")==="readium-night-on"||Is(this.getBackgroundColor())}getBackgroundColor(){return ai(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color")}updateSharedMask(){const e=this.items.filter(d=>d.decoration.style?.type===R.Mask);if(e.length===0){this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowHost&&!this.container&&(this.shadowHost.remove(),this.shadowRoot=void 0,this.shadowHost=void 0);return}const n=Ee(this.wnd),r=1/this.effectiveZoom(),i=this.wnd.document.documentElement,s=i.scrollWidth,o=i.scrollHeight,a=[];for(const d of e){const g=d.decoration.style,p=g.layout??"boxes",m=g.width??"wrap",b=g.expand??0,x=d.range.getBoundingClientRect(),A=p==="bounds"?[b?{left:x.left-b,top:x.top-b,right:x.right+b,bottom:x.bottom+b,width:x.width+b*2,height:x.height+b*2}:x]:Je(d.range,!1,!1,b);for(const S of A){let w;switch(m){case"viewport":{const T=Math.floor(n.inlineStart(S)/n.viewportInlineSize)*n.viewportInlineSize;w=n.toRect(T,n.blockStart(S),n.viewportInlineSize,n.blockSize(S));break}case"page":{const T=Math.floor(n.inlineStart(S)/n.pageInlineSize)*n.pageInlineSize;w=n.toRect(T,n.blockStart(S),n.pageInlineSize,n.blockSize(S));break}case"bounds":{w=n.toRect(n.inlineStart(x),n.blockStart(S),n.inlineSize(x),n.blockSize(S));break}default:w=n.toRect(n.inlineStart(S),n.blockStart(S),n.inlineSize(S),n.blockSize(S))}a.push(w)}}const c=[`M0 0 H${s} V${o} H0 Z`,...a.map(d=>{const g=(d.left+n.xDocOffset)*r,p=(d.top+n.yDocOffset)*r,m=(d.right+n.xDocOffset)*r,b=(d.bottom+n.yDocOffset)*r;return`M${g} ${p} H${m} V${b} H${g} 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 d=this.wnd.document.createElementNS(l,"defs"),g=this.wnd.document.createElementNS(l,"clipPath"),p=`${this.id}-mask-clip`;g.setAttribute("id",p),g.setAttribute("clipPathUnits","userSpaceOnUse");const m=this.wnd.document.createElementNS(l,"path");m.setAttribute("clip-rule","evenodd"),g.appendChild(m),d.appendChild(g),this.maskSvg.appendChild(d);const b=this.wnd.document.createElementNS(l,"rect");b.setAttribute("id",`${this.id}-mask-rect`),b.setAttribute("clip-path",`url(#${p})`),b.style.pointerEvents="none",this.maskSvg.appendChild(b),this.shadowRoot.appendChild(this.maskSvg)}this.maskSvg.style.width=`${s}px`,this.maskSvg.style.height=`${o}px`;const u=this.maskSvg.querySelector("path");u&&u.setAttribute("d",c);const h=this.maskSvg.querySelector("rect");if(h){const d=e[0].decoration.style.tint,g=d??this.getBackgroundColor()??vn(R.Mask),p=d?"1":"0.5";h.setAttribute("x","0"),h.setAttribute("y","0"),h.setAttribute("width",String(s)),h.setAttribute("height",String(o)),h.setAttribute("fill",g),h.setAttribute("fill-opacity",p)}}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 oa=class Re extends Hu{constructor(){super(...arguments),this.observedResizeTargets=new Map,this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this),this.scrollScheduled=!1,this.handleScroller=this.handleScroll.bind(this)}cleanup(){this.groups.forEach(e=>e.destroy()),this.groups.clear(),this.observedResizeTargets.clear()}updateHighlightStyles(){this.groups.forEach(e=>{e.requestLayout()})}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(e=>e.requestLayout())},50)}handleScroll(){this.scrollScheduled||(this.scrollScheduled=!0,this.wnd.requestAnimationFrame(()=>{this.scrollScheduled=!1,this.groups.forEach(e=>{e.hasOverlayItems&&e.repositionOverlays()})}))}mount(e,n){return this.wnd=e,n.register("decorate",Re.moduleName,(r,i)=>{const s=r;(s.action==="add"||s.action==="update")&&s.decoration.locator&&(s.decoration.locator=Sr.deserialize(s.decoration.locator)),this.groups.has(s.group)||this.groups.set(s.group,new Yh(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_resize",Re.moduleName,(r,i)=>{const s=r;s.action==="watch"?this.addDecorationResizeTarget(s.selector):this.removeDecorationResizeTarget(s.selector),i(!0)}),n.register("decoration_activatable",Re.moduleName,(r,i)=>{const s=r,o=this.groups.get(s.group);o&&(o.activatable=s.activatable),i(!0)}),n.register("decoration_hoverable",Re.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),e.addEventListener("scroll",this.handleScroller,{passive:!0,capture:!0}),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),e.removeEventListener("scroll",this.handleScroller,{capture:!0}),n.unregisterAll(Re.moduleName),this.resizeObserver.disconnect(),this.styleObserver.disconnect(),this.cleanup(),n.log("Decorator Unmounted"),!0}addDecorationResizeTarget(e){const n=this.observedResizeTargets.get(e);n&&this.resizeObserver.unobserve(n);const r=this.wnd.document.querySelector(e);r?(this.resizeObserver.observe(r),this.observedResizeTargets.set(e,r)):this.observedResizeTargets.delete(e)}removeDecorationResizeTarget(e){const n=this.observedResizeTargets.get(e);n&&(this.resizeObserver.unobserve(n),this.observedResizeTargets.delete(e))}};oa.moduleName="decorator";let la=oa;const ca=new Set(Object.values(R));function ua(t,e){return t===R.TextColor?typeof window<"u"&&"Highlight"in window:ca.has(t)?!0:!!e?.[t]}function jn(t,e){const{style:n}=t;if(n.type===R.Template){const r=n;return{...t,style:{...r,element:Oi(r,t)}}}if(n.type&&e?.[n.type]){const r=e[n.type];return{...t,style:{type:R.Template,layout:r.layout,width:r.width,stylesheet:r.stylesheet,element:Oi(r,t)}}}return t}function Oi(t,e){return typeof t.element=="function"?t.element(e):t.element}function Qh(t,e){if(t.type!==e.type)return!1;if(t.type===R.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 ha(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)&&Qh(t.style,e.style)&&JSON.stringify(t.extras??null)===JSON.stringify(e.extras??null)}class da{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 fa{constructor(){this.frame=new ga(this),this.host=new pa(this)}}class ga{constructor(e){this.channel=e,this.registrar=new Map,this.outbox=new da,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 pa{constructor(e){this.channel=e,this.listeners=new Map,this.outbox=new da,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 ma{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,n.resizeWatchSelectors?.forEach(r=>this.addDecorationResizeTarget(r)),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}))})}addDecorationResizeTarget(e){this.host.send("decoration_resize",{action:"watch",selector:e})}removeDecorationResizeTarget(e){this.host.send("decoration_resize",{action:"unwatch",selector:e})}supportsDecorationStyle(e){return ua(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 u=s.get(c);u?ha(l,u)||this.host.send("decorate",{group:n,action:"update",decoration:jn(u,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:jn(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 Zh(t){return new Ds({start:new It(t.start),end:t.end?new It(t.end):void 0})}function ya(t,e=window){const{text:n,cssSelector:r,domRange:i,fragment:s}=t,o=n?new br(n):void 0,a=r||i?new Map:void 0;a&&(r&&a.set("cssSelector",r),i&&a.set("domRange",Zh(i).serialize()));const l=a!==void 0||s!==void 0?new ue({fragments:s?[s]:void 0,otherLocations:a}):void 0;return new Sr({href:e.location.href,type:"text/html",text:o,locations:l})}class ba extends ma{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:ya(s,this.wnd)})),n)}destroy(){super.destroy(),this.decorator.unmount(this.wnd,this.channel.frame),this.channel.frame.destroy()}}function ed(t=window,e={}){const n=new fa,r=new la;return r.mount(t,n.frame),new ba(n,t,r,e)}class td{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 Lt={range:[0,5e3],step:100},$t={range:[.1,10],step:.1},_t={range:[0,2],step:.1},Bt={range:[0,1],step:.05},vr=["none","few","some","most","custom"],wr=["none","block-level","always"],xr=["plain","ssml"],Er=["none","utterance","block"],Ai=["format","inlineContextualization","verbosity","skip","contextualize","language"];function Cr(t){return t==null||typeof t=="boolean"?t:void 0}function re(t,e){return t==null||e.includes(t)?t:void 0}function ie(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 at(t){return t==null||Array.isArray(t)&&t.every(e=>typeof e=="string")?t:void 0}class Sa{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=re(e.format,xr)??"plain",this.inlineContextualization=Cr(e.inlineContextualization)??!1,this.verbosity=re(e.verbosity,vr)??"few",this.skip=at(e.skip)??[],this.contextualize=at(e.contextualize)??[],this.language=re(e.language,wr)??"block-level",this.pauseDuration=ie(e.pauseDuration,Lt.range)??300,this.autoPause=re(e.autoPause,Er)??"none",this.rate=ie(e.rate,$t.range)??1,this.pitch=ie(e.pitch,_t.range)??1,this.volume=ie(e.volume,Bt.range)??1}}class Ue{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=re(e.format,xr),this.inlineContextualization=Cr(e.inlineContextualization),this.verbosity=re(e.verbosity,vr),this.skip=at(e.skip),this.contextualize=at(e.contextualize),this.language=re(e.language,wr),this.pauseDuration=ie(e.pauseDuration,Lt.range),this.autoPause=re(e.autoPause,Er),this.rate=ie(e.rate,$t.range),this.pitch=ie(e.pitch,_t.range),this.volume=ie(e.volume,Bt.range)}merging(e){const n={...this};for(const r of Object.keys(e))e[r]!==void 0&&(n[r]=e[r]);return new Ue(n)}}class ht{_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 tt extends ht{_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&&re(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 va extends ht{set value(e){if(e!=null&&Cr(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 Hn extends ht{set value(e){if(e!=null&&at(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 nt extends ht{_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&&ie(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 Wn{preferences;settings;constructor(e,n){this.preferences=new Ue({...e}),this.settings=n}clear(){this.preferences=new Ue({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 tt({initialValue:this.preferences.format,effectiveValue:this.settings.format,isEffective:this.preferences.format!=null,onChange:e=>this.updatePreference("format",e??null),supportedValues:xr})}get inlineContextualization(){return new va({initialValue:this.preferences.inlineContextualization,effectiveValue:this.settings.inlineContextualization,isEffective:this.preferences.inlineContextualization!=null,onChange:e=>this.updatePreference("inlineContextualization",e??null)})}get verbosity(){return new tt({initialValue:this.preferences.verbosity,effectiveValue:this.settings.verbosity,isEffective:this.preferences.verbosity!=null,onChange:e=>this.updatePreference("verbosity",e??null),supportedValues:vr})}get skip(){return new Hn({initialValue:this.preferences.skip,effectiveValue:this.settings.skip,isEffective:this.preferences.skip!=null,onChange:e=>this.updatePreference("skip",e??null)})}get contextualize(){return new Hn({initialValue:this.preferences.contextualize,effectiveValue:this.settings.contextualize,isEffective:this.preferences.contextualize!=null,onChange:e=>this.updatePreference("contextualize",e??null)})}get language(){return new tt({initialValue:this.preferences.language,effectiveValue:this.settings.language,isEffective:this.preferences.language!=null,onChange:e=>this.updatePreference("language",e??null),supportedValues:wr})}get pauseDuration(){return new nt({initialValue:this.preferences.pauseDuration,effectiveValue:this.settings.pauseDuration,isEffective:this.preferences.pauseDuration!=null,onChange:e=>this.updatePreference("pauseDuration",e??null),supportedRange:Lt.range,step:Lt.step})}get autoPause(){return new tt({initialValue:this.preferences.autoPause,effectiveValue:this.settings.autoPause,isEffective:this.preferences.autoPause!=null,onChange:e=>this.updatePreference("autoPause",e??null),supportedValues:Er})}get rate(){return new nt({initialValue:this.preferences.rate,effectiveValue:this.settings.rate,isEffective:this.preferences.rate!=null,onChange:e=>this.updatePreference("rate",e??null),supportedRange:$t.range,step:$t.step})}get pitch(){return new nt({initialValue:this.preferences.pitch,effectiveValue:this.settings.pitch,isEffective:this.preferences.pitch!=null,onChange:e=>this.updatePreference("pitch",e??null),supportedRange:_t.range,step:_t.step})}get volume(){return new nt({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!=null,onChange:e=>this.updatePreference("volume",e??null),supportedRange:Bt.range,step:Bt.step})}}const wa=["audio","figure","image","math","table","video"],xa=[...wa,"blockquote","chapter","cover","details","notice","part","preformatted","qna","row","rowheader","subtitle","tip"],nd=[...xa,"abstract","acknowledgments","afterword","appendix","aside","backlink","bibliography","biblioref","colophon","complementary","conclusion","credit","credits","dedication","definition","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","glossref","heading1","heading2","heading3","heading4","heading5","heading6","index","introduction","list","listItem","noteref","pagebreak","pagelist","preface","prologue","pullquote","separator","summary","term"],Ea={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"])},Ca={none:new Set,few:new Set(wa),some:new Set(xa),most:new Set(nd)},Gn={table:{few:"inline",some:"block",most:"block"}};function wt(t){const e={};for(const n of Object.keys(Gn))e[n]=Gn[n]?.[t]??"inline";return e}const ka={none:wt("none"),few:wt("few"),some:wt("some"),most:wt("most")},rd=Object.keys(Gn);function id(t,e){const n=t==="custom"?{}:ka[t];if(!e)return n;const r={...n};for(const i of Object.keys(e)){const s=e[i]?.[t];s&&(r[i]=s)}return r}class Kn{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=[...Ea[this.verbosity]],this.contextualize=[...Ca[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}}const O=t=>typeof t=="string",Xe=()=>{let t,e;const n=new Promise((r,i)=>{t=r,e=i});return n.resolve=t,n.reject=e,n},Ti=t=>t==null?"":String(t),sd=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},ad=/###/g,Ri=t=>t&&t.includes("###")?t.replace(ad,"."):t,Ni=t=>!t||O(t),rt=(t,e,n)=>{const r=O(e)?e.split("."):e;let i=0;for(;i<r.length-1;){if(Ni(t))return{};const s=Ri(r[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return Ni(t)?{}:{obj:t,k:Ri(r[i])}},Di=(t,e,n)=>{const{obj:r,k:i}=rt(t,e,Object);if(r!==void 0||e.length===1){r[i]=n;return}let s=e[e.length-1],o=e.slice(0,e.length-1),a=rt(t,o,Object);for(;a.obj===void 0&&o.length;)s=`${o[o.length-1]}.${s}`,o=o.slice(0,o.length-1),a=rt(t,o,Object),a?.obj&&typeof a.obj[`${a.k}.${s}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${s}`]=n},od=(t,e,n,r)=>{const{obj:i,k:s}=rt(t,e,Object);i[s]=i[s]||[],i[s].push(n)},qt=(t,e)=>{const{obj:n,k:r}=rt(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},ld=(t,e,n)=>{const r=qt(t,n);return r!==void 0?r:qt(e,n)},Oa=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,r)?O(t[r])||t[r]instanceof String||O(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):Oa(t[r],e[r],n):t[r]=e[r]);return t},ee=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),cd={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},ud=t=>O(t)?t.replace(/[&<>"'\/]/g,e=>cd[e]):t;class hd{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const dd=[" ",",","?","!",";"],fd=new hd(20),gd=(t,e,n)=>{e=e||"",n=n||"";const r=dd.filter(o=>!e.includes(o)&&!n.includes(o));if(r.length===0)return!0;const i=fd.getRegExp(`(${r.map(o=>o==="?"?"\\?":o).join("|")})`);let s=!i.test(t);if(!s){const o=t.indexOf(n);o>0&&!i.test(t.substring(0,o))&&(s=!0)}return s},Jn=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(n);let i=t;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let o,a="";for(let c=s;c<r.length;++c)if(c!==s&&(a+=n),a+=r[c],o=i[a],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<r.length-1)continue;s+=c-s+1;break}i=o}return i},ot=t=>t?.replace(/_/g,"-"),pd={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Ut{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||pd,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,r,i){return i&&!this.debug?null:(e=e.map(s=>O(s)?s.replace(/[\r\n\x00-\x1F\x7F]/g," "):s),O(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Ut(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ut(this.logger,e)}}var Q=new Ut;class en{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}once(e,n){const r=(...i)=>{n(...i),this.off(e,r)};return this.on(e,r),this}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i(e,...n)})}}class Fi extends en{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,n,r,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.includes(".")?a=e.split("."):(a=[e,n],r&&(Array.isArray(r)?a.push(...r):O(r)&&s?a.push(...r.split(s)):a.push(r)));const c=qt(this.data,a);return!c&&!n&&!r&&e.includes(".")&&(e=a[0],n=a[1],r=a.slice(2).join(".")),c||!o||!O(r)?c:Jn(this.data?.[e]?.[n],r,s)}addResource(e,n,r,i,s={silent:!1}){const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let a=[e,n];r&&(a=a.concat(o?r.split(o):r)),e.includes(".")&&(a=e.split("."),i=n,n=a[1]),this.addNamespaces(n),Di(this.data,a,i),s.silent||this.emit("added",e,n,r,i)}addResources(e,n,r,i={silent:!1}){for(const s in r)(O(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});i.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,i,s,o={silent:!1,skipCopy:!1}){let a=[e,n];e.includes(".")&&(a=e.split("."),i=r,r=n,n=a[1]),this.addNamespaces(n);let c=qt(this.data,a)||{};o.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?Oa(c,r,s):c={...c,...r},Di(this.data,a,c),o.silent||this.emit("added",e,n,r)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var Aa={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,i){return t.forEach(s=>{e=this.processors[s]?.process(e,n,r,i)??e}),e}};const Ta=Symbol("i18next/PATH_KEY");function md(){const t=[],e=Object.create(null);let n;return e.get=(r,i)=>(n?.revoke?.(),i===Ta?t:(t.push(i),n=Proxy.revocable(r,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Ie(t,e){const{[Ta]:n}=t(md()),r=e?.keySeparator??".",i=e?.nsSeparator??":",s=e?.enableSelector==="strict";if(n.length>1&&i){const o=e?.ns,a=s?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(a&&(s?a:a.length>1?a.slice(1):[]).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}const wn=t=>!O(t)&&typeof t!="boolean"&&typeof t!="number";class Vt extends en{constructor(e,n={}){super(),sd(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Q.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const i=this.resolve(e,r);if(i?.res===void 0)return!1;const s=wn(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(e,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const o=r&&e.includes(r),a=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!gd(e,r,i);if(o&&!a){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:O(s)?[s]:s};const l=e.split(r);(r!==i||r===i&&this.options.ns.includes(l[0]))&&(s=l.shift()),e=l.join(i)}return{key:e,namespaces:O(s)?[s]:s}}translate(e,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),e==null)return"";typeof e=="function"&&(e=Ie(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]),e=e.map(k=>typeof k=="function"?Ie(k,{...this.options,...i}):String(k));const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:a,namespaces:c}=this.extractFromKey(e[e.length-1],i),l=c[c.length-1];let u=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const h=i.lng||this.language,d=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(h?.toLowerCase()==="cimode")return d?s?{res:`${l}${u}${a}`,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${u}${a}`:s?{res:a,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:a;const g=this.resolve(e,i);let p=g?.res;const m=g?.usedKey||a,b=g?.exactUsedKey||a,x=["[object Number]","[object Function]","[object RegExp]"],A=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,w=i.count!==void 0&&!O(i.count),T=Vt.hasDefaultValue(i),F=w?this.pluralResolver.getSuffix(h,i.count,i):"",L=i.ordinal&&w?this.pluralResolver.getSuffix(h,i.count,{ordinal:!1}):"",X=w&&!i.ordinal&&i.count===0,M=X&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${F}`]||i[`defaultValue${L}`]||i.defaultValue;let y=p;S&&!p&&T&&(y=M);const gt=wn(y),ce=Object.prototype.toString.apply(y);if(S&&y&>&&!x.includes(ce)&&!(O(A)&&Array.isArray(y))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const k=this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,y,{...i,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(g.res=k,g.usedParams=this.getUsedParamsDetails(i),g):k}if(o){const k=Array.isArray(y),_=k?[]:{},G=k?b:m;for(const V in y)if(Object.prototype.hasOwnProperty.call(y,V)){const H=`${G}${o}${V}`;T&&!p?_[V]=this.translate(H,{...i,defaultValue:wn(M)?M[V]:void 0,joinArrays:!1,ns:c}):_[V]=this.translate(H,{...i,joinArrays:!1,ns:c}),_[V]===H&&(_[V]=y[V])}p=_}}else if(S&&O(A)&&Array.isArray(p))p=p.join(A),p&&(p=this.extendTranslation(p,e,i,r));else{let k=!1,_=!1;!this.isValidLookup(p)&&T&&(k=!0,p=M),this.isValidLookup(p)||(_=!0,p=a);const V=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&_?void 0:p,H=T&&M!==p&&this.options.updateMissing;if(_||k||H){if(this.logger.log(H?"updateKey":"missingKey",h,l,w&&!H?`${a}${this.pluralResolver.getSuffix(h,i.count,i)}`:a,H?M:p),o){const f=this.resolve(a,{...i,keySeparator:!1});f&&f.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let U=[];const ve=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ve&&ve[0])for(let f=0;f<ve.length;f++)U.push(ve[f]);else this.options.saveMissingTo==="all"?U=this.languageUtils.toResolveHierarchy(i.lng||this.language):U.push(i.lng||this.language);const K=(f,v,C)=>{const E=T&&C!==p?C:V;this.options.missingKeyHandler?this.options.missingKeyHandler(f,l,v,E,H,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(f,l,v,E,H,i),this.emit("missingKey",f,l,v,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&w?U.forEach(f=>{const v=this.pluralResolver.getSuffixes(f,i);X&&i[`defaultValue${this.options.pluralSeparator}zero`]&&!v.includes(`${this.options.pluralSeparator}zero`)&&v.push(`${this.options.pluralSeparator}zero`),v.forEach(C=>{K([f],a+C,i[`defaultValue${C}`]||M)})}):K(U,a,M))}p=this.extendTranslation(p,e,i,g,r),_&&p===a&&this.options.appendNamespaceToMissingKey&&(p=`${l}${u}${a}`),(_||k)&&this.options.parseMissingKeyHandler&&(p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${u}${a}`:a,k?p:void 0,i))}return s?(g.res=p,g.usedParams=this.getUsedParamsDetails(i),g):p}extendTranslation(e,n,r,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const c=O(e)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let l;if(c){const h=e.match(this.interpolator.nestingRegexp);l=h&&h.length}let u=r.replace&&!O(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,r.lng||this.language||i.usedLng,r),c){const h=e.match(this.interpolator.nestingRegexp),d=h&&h.length;l<d&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...h)=>s?.[0]===h[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${h[0]} in key: ${n[0]}`),null):this.translate(...h,n),r)),r.interpolation&&this.interpolator.reset()}const o=r.postProcess||this.options.postProcess,a=O(o)?[o]:o;return e!=null&&a?.length&&r.applyPostProcessor!==!1&&(e=Aa.handle(a,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,i,s,o,a;return O(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?Ie(c,{...this.options,...n}):c)),e.forEach(c=>{if(this.isValidLookup(r))return;const l=this.extractFromKey(c,n),u=l.key;i=u;let h=l.namespaces;this.options.fallbackNS&&(h=h.concat(this.options.fallbackNS));const d=n.count!==void 0&&!O(n.count),g=d&&!n.ordinal&&n.count===0,p=n.context!==void 0&&(O(n.context)||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);h.forEach(b=>{this.isValidLookup(r)||(a=b,!this.checkedLoadedFor[`${m[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(this.checkedLoadedFor[`${m[0]}-${b}`]=!0,this.logger.warn(`key "${i}" for languages "${m.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(x=>{if(this.isValidLookup(r))return;o=x;const A=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(A,u,x,b,n);else{let w;d&&(w=this.pluralResolver.getSuffix(x,n.count,n));const T=`${this.options.pluralSeparator}zero`,F=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(n.ordinal&&w.startsWith(F)&&A.push(u+w.replace(F,this.options.pluralSeparator)),A.push(u+w),g&&A.push(u+T)),p){const L=`${u}${this.options.contextSeparator||"_"}${n.context}`;A.push(L),d&&(n.ordinal&&w.startsWith(F)&&A.push(L+w.replace(F,this.options.pluralSeparator)),A.push(L+w),g&&A.push(L+T))}}let S;for(;S=A.pop();)this.isValidLookup(r)||(s=S,r=this.getResource(x,b,S,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:o,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,r,i):this.resourceStore.getResource(e,n,r,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!O(e.replace);let i=r?e.replace:e;if(r&&typeof e.count<"u"&&(i={...i,count:e.count}),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(e){const n="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&r.startsWith(n)&&e[r]!==void 0)return!0;return!1}}class Ii{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Q.create("languageUtils"),this.resolveHierarchyCache={}}clearCache(){this.resolveHierarchyCache={}}getScriptPartFromCode(e){if(e=ot(e),!e||!e.includes("-"))return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=ot(e),!e||!e.includes("-"))return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(O(e)&&e.includes("-")){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>o===s?!0:!o.includes("-")&&!s.includes("-")?!1:!!(o.includes("-")&&!s.includes("-")&&o.slice(0,o.indexOf("-"))===s||o.startsWith(s)&&s.length>1))}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),O(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let r=e[n];return r||(r=e[this.getScriptPartFromCode(n)]),r||(r=e[this.formatLanguageCode(n)]),r||(r=e[this.getLanguagePartFromCode(n)]),r||(r=e.default),r||[]}toResolveHierarchy(e,n){const r=this.options.fallbackLng,i=Array.isArray(r)?r.join("|"):r;i!==this._cachedFallbackLng&&(this.resolveHierarchyCache={},this._cachedFallbackLng=i);const s=n===void 0||n===!1||O(n),o=n===void 0&&typeof this.options.fallbackLng=="function",a=O(e)&&s&&!o;let c=null;if(a){let d;n===void 0?d="undefined":n===!1?d="boolean:false":d=`string:${n}`,c=`${e.length}:${e}|${d}`}if(c!==null){const d=this.resolveHierarchyCache[c];if(d!==void 0)return d.slice()}const l=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),u=[],h=d=>{d&&(this.isSupportedCode(d)?u.push(d):this.logger.warn(`rejecting language code not found in supportedLngs: ${d}`))};return O(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&h(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&h(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&h(this.getLanguagePartFromCode(e))):O(e)&&h(this.formatLanguageCode(e)),l.forEach(d=>{u.includes(d)||h(this.formatLanguageCode(d))}),c!==null?(this.resolveHierarchyCache[c]=u,u.slice()):u}}const Pi={zero:0,one:1,two:2,few:3,many:4,other:5},Li={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class yd{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Q.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=ot(e==="dev"?"en":e),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(r,{type:i})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Li;if(!e.match(/-|_/))return Li;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,n)}return this.pluralRulesCache[s]=o,o}needsPlural(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,r={}){return this.getSuffixes(e,r).map(i=>`${n}${i}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>Pi[i]-Pi[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,r={}){const i=this.getRule(e,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const $i=(t,e,n,r=".",i=!0)=>{let s=ld(t,e,n);return!s&&i&&O(n)&&(s=Jn(t,n,r),s===void 0&&(s=Jn(e,n,r))),s},bd=t=>t.replace(/\$/g,"$$$$");class _i{constructor(e={}){this.logger=Q.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:o,suffix:a,suffixEscaped:c,formatSeparator:l,unescapeSuffix:u,unescapePrefix:h,nestingPrefix:d,nestingPrefixEscaped:g,nestingSuffix:p,nestingSuffixEscaped:m,nestingOptionsSeparator:b,maxReplaces:x,alwaysFormat:A}=e.interpolation;this.escape=n!==void 0?n:ud,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?ee(s):o||"{{",this.suffix=a?ee(a):c||"}}",this.formatSeparator=l||",",this.unescapePrefix=u?"":h?ee(h):"-",this.unescapeSuffix=this.unescapePrefix?"":u?ee(u):"",this.nestingPrefix=d?ee(d):g||ee("$t("),this.nestingSuffix=p?ee(p):m||ee(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=x||1e3,this.alwaysFormat=A!==void 0?A:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,r,i){let s,o,a;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=g=>{if(!g.includes(this.formatSeparator)){const x=$i(n,c,g,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(x,void 0,r,{...i,...n,interpolationkey:g}):x}const p=g.split(this.formatSeparator),m=p.shift().trim(),b=p.join(this.formatSeparator).trim();return this.format($i(n,c,m,this.options.keySeparator,this.options.ignoreJSONStructure),b,r,{...i,...n,interpolationkey:m})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,h=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:g=>g},{regex:this.regexp,safeValue:g=>this.escapeValue?this.escape(g):g}].forEach(g=>{for(a=0;s=g.regex.exec(e);){const p=s[1].trim();if(o=l(p),o===void 0)if(typeof u=="function"){const b=u(e,s,i);o=O(b)?b:""}else if(i&&Object.prototype.hasOwnProperty.call(i,p))o="";else if(h){o=s[0];continue}else this.logger.warn(`missed to pass in variable ${p} for interpolating ${e}`),o="";else!O(o)&&!this.useRawValueToEscape&&(o=Ti(o));const m=g.safeValue(o);if(e=e.replace(s[0],bd(m)),h?(g.regex.lastIndex+=m.length,g.regex.lastIndex-=s[0].length):g.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,n,r={}){let i,s,o;const a=(c,l)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const h=c.split(new RegExp(`${ee(u)}[ ]*{`));let d=`{${h[1]}`;c=h[0],d=this.interpolate(d,o);const g=d.match(/'/g),p=d.match(/"/g);((g?.length??0)%2===0&&!p||(p?.length??0)%2!==0)&&(d=d.replace(/'/g,'"'));try{o=JSON.parse(d),l&&(o={...l,...o})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,m),`${c}${u}${d}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,c};for(;i=this.nestingRegexp.exec(e);){let c=[];o={...r},o=o.replace&&!O(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const l=/{.*}/s.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(l!==-1&&(c=i[1].slice(l).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),i[1]=i[1].slice(0,l)),s=n(a.call(this,i[1].trim(),o),o),s&&i[0]===e&&!O(s))return s;O(s)||(s=Ti(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),c.length&&(s=c.reduce((u,h)=>this.format(u,h,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const Sd=t=>{let e=t.toLowerCase().trim();const n={};if(t.includes("(")){const r=t.split("(");e=r[0].toLowerCase().trim();const i=r[1].slice(0,-1);e==="currency"&&!i.includes(":")?n.currency||(n.currency=i.trim()):e==="relativetime"&&!i.includes(":")?n.range||(n.range=i.trim()):i.split(";").forEach(o=>{if(o){const[a,...c]=o.split(":"),l=c.join(":").trim().replace(/^'+|'+$/g,""),u=a.trim();n[u]||(n[u]=l),l==="false"&&(n[u]=!1),l==="true"&&(n[u]=!0),isNaN(l)||(n[u]=parseInt(l,10))}})}return{formatName:e,formatOptions:n}},Bi=t=>{const e={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const o=r+JSON.stringify(s);let a=e[o];return a||(a=t(ot(r),i),e[o]=a),a(n)}},vd=t=>(e,n,r)=>t(ot(n),r)(e);class wd{constructor(e={}){this.logger=Q.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?Bi:vd;this.formats={number:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s});return a=>o.format(a)}),currency:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s,style:"currency"});return a=>o.format(a)}),datetime:r((i,s)=>{const o=new Intl.DateTimeFormat(i,{...s});return a=>o.format(a)}),relativetime:r((i,s)=>{const o=new Intl.RelativeTimeFormat(i,{...s});return a=>o.format(a,s.range||"day")}),list:r((i,s)=>{const o=new Intl.ListFormat(i,{...s});return a=>o.format(a)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=Bi(n)}format(e,n,r,i={}){if(!n||e==null)return e;const s=n.split(this.formatSeparator),o=[];for(let c=0;c<s.length;c++){let l=s[c];for(;l.indexOf("(")>-1&&!l.includes(")")&&c+1<s.length;)l=`${l}${this.formatSeparator}${s[++c]}`;o.push(l)}return o.reduce((c,l)=>{const{formatName:u,formatOptions:h}=Sd(l);if(this.formats[u]){let d=c;try{const g=i?.formatParams?.[i.interpolationkey]||{},p=g.locale||g.lng||i.locale||i.lng||r;d=this.formats[u](c,p,{...h,...i,...g})}catch(g){this.logger.warn(g)}return d}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const xd=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Ed extends en{constructor(e,n,r,i={}){super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=Q.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(e,n,r,i){const s={},o={},a={},c={};return e.forEach(l=>{let u=!0;n.forEach(h=>{const d=`${l}|${h}`;!r.reload&&this.store.hasResourceBundle(l,h)?this.state[d]=2:this.state[d]<0||(this.state[d]===1?o[d]===void 0&&(o[d]=!0):(this.state[d]=1,u=!1,o[d]===void 0&&(o[d]=!0),s[d]===void 0&&(s[d]=!0),c[h]===void 0&&(c[h]=!0)))}),u||(a[l]=!0)}),(Object.keys(s).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(o),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(c)}}loaded(e,n,r){const i=e.split("|"),s=i[0],o=i[1];n&&this.emit("failedLoading",s,o,n),!n&&r&&this.store.addResourceBundle(s,o,r,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&r&&(this.state[e]=0);const a={};this.queue.forEach(c=>{od(c.loaded,[s],o),xd(c,e),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(l=>{a[l]||(a[l]={});const u=c.loaded[l];u.length&&u.forEach(h=>{a[l][h]===void 0&&(a[l][h]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(c=>!c.done)}read(e,n,r,i=0,s=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:i,wait:s,callback:o});return}this.readingCalls++;const a=(l,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const h=this.waitingReads.shift();this.read(h.lng,h.ns,h.fcName,h.tried,h.wait,h.callback)}if(l&&u&&i<this.maxRetries){setTimeout(()=>{this.read(e,n,r,i+1,s*2,o)},s);return}o(l,u)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const l=c(e,n);l&&typeof l.then=="function"?l.then(u=>a(null,u)).catch(a):a(null,l)}catch(l){a(l)}return}return c(e,n,a)}prepareLoading(e,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();O(e)&&(e=this.languageUtils.toResolveHierarchy(e)),O(n)&&(n=[n]);const s=this.queueLoad(e,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(o=>{this.loadOne(o)})}load(e,n,r){this.prepareLoading(e,n,{},r)}reload(e,n,r){this.prepareLoading(e,n,{reload:!0},r)}loadOne(e,n=""){const r=e.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(o,a)=>{o&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,o),!o&&a&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,a),this.loaded(e,o,a)})}saveMissing(e,n,r,i,s,o={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend?.create){const c={...o,isUpdate:s},l=this.backend.create.bind(this.backend);if(l.length<6)try{let u;l.length===5?u=l(e,n,r,i,c):u=l(e,n,r,i),u&&typeof u.then=="function"?u.then(h=>a(null,h)).catch(a):a(null,u)}catch(u){a(u)}else l(e,n,r,i,a,c)}!e||!e[0]||this.store.addResource(e[0],n,r,i)}}}const xn=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),O(t[1])&&(e.defaultValue=t[1]),O(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(r=>{e[r]=n[r]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),qi=t=>(O(t.ns)&&(t.ns=[t.ns]),O(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),O(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&!t.supportedLngs.includes("cimode")&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t),xt=()=>{},Cd=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class it extends en{constructor(e={},n){if(super(),this.options=qi(e),this.services={},this.logger=Q,this.modules={external:[]},Cd(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(O(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const r=xn();this.options={...r,...this.options,...qi(e)},this.options.interpolation={...r.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler);const i=l=>l?typeof l=="function"?new l:l:null;if(!this.options.isClone){this.modules.logger?Q.init(i(this.modules.logger),this.options):Q.init(null,this.options);let l;this.modules.formatter?l=this.modules.formatter:l=wd;const u=new Ii(this.options);this.store=new Fi(this.options.resources,this.options);const h=this.services;h.logger=Q,h.resourceStore=this.store,h.languageUtils=u,h.pluralResolver=new yd(u,{prepend:this.options.pluralSeparator}),l&&(h.formatter=i(l),h.formatter.init&&h.formatter.init(h,this.options),this.options.interpolation.format=h.formatter.format.bind(h.formatter)),h.interpolator=new _i(this.options),h.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},h.backendConnector=new Ed(i(this.modules.backend),h.resourceStore,h,this.options),h.backendConnector.on("*",(d,...g)=>{this.emit(d,...g)}),this.modules.languageDetector&&(h.languageDetector=i(this.modules.languageDetector),h.languageDetector.init&&h.languageDetector.init(h,this.options.detection,this.options)),this.modules.i18nFormat&&(h.i18nFormat=i(this.modules.i18nFormat),h.i18nFormat.init&&h.i18nFormat.init(this)),this.translator=new Vt(this.services,this.options),this.translator.on("*",(d,...g)=>{this.emit(d,...g)}),this.modules.external.forEach(d=>{d.init&&d.init(this)})}if(this.format=this.options.interpolation.format,n||(n=xt),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const l=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);l.length>0&&l[0]!=="dev"&&(this.options.lng=l[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(l=>{this[l]=(...u)=>this.store[l](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(l=>{this[l]=(...u)=>(this.store[l](...u),this)});const a=Xe(),c=()=>{const l=(u,h)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(h),n(u,h)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return l(null,this.t.bind(this));this.changeLanguage(this.options.lng,l)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),a}loadResources(e,n=xt){let r=n;const i=O(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],o=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(l=>{l!=="cimode"&&(s.includes(l)||s.push(l))})};i?o(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>o(c)),this.options.preload?.forEach?.(a=>o(a)),this.services.backendConnector.load(s,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(a)})}else r(null)}reloadResources(e,n,r){const i=Xe();return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),r||(r=xt),this.services.backendConnector.reload(e,n,s=>{i.resolve(),r(s)}),i}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&Aa.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!["cimode","dev"].includes(r)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const r=Xe();this.emit("languageChanging",e);const i=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},s=(a,c)=>{c?this.isLanguageChangingTo===e&&(i(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,r.resolve((...l)=>this.t(...l)),n&&n(a,(...l)=>this.t(...l))},o=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const c=O(a)?a:a&&a[0],l=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(O(a)?[a]:a);l&&(this.language||i(l),this.translator.language||this.translator.changeLanguage(l),this.services.languageDetector?.cacheUserLanguage?.(l)),this.loadResources(l,u=>{s(u,l)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),r}getFixedT(e,n,r,i){const s=i?.scopeNs,o=(a,c,...l)=>{let u;typeof c!="object"?u=this.options.overloadTranslationOptionHandler([a,c].concat(l)):u={...c},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs;const h=u.ns!==void 0&&u.ns!==null;u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||r||o.keyPrefix);const d={...this.options,...u};Array.isArray(s)&&!h&&(d.ns=s),typeof u.keyPrefix=="function"&&(u.keyPrefix=Ie(u.keyPrefix,d));const g=this.options.keySeparator||".";let p;return u.keyPrefix&&Array.isArray(a)?p=a.map(m=>(typeof m=="function"&&(m=Ie(m,d)),`${u.keyPrefix}${g}${m}`)):(typeof a=="function"&&(a=Ie(a,d)),p=u.keyPrefix?`${u.keyPrefix}${g}${a}`:a),this.t(p,u)};return O(e)?o.lng=e:o.lngs=e,o.ns=n,o.keyPrefix=r,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const o=(a,c)=>{const l=this.services.backendConnector.state[`${a}|${c}`];return l===-1||l===0||l===2};if(n.precheck){const a=n.precheck(this,o);if(a!==void 0)return a}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(r,e)&&(!i||o(s,e)))}loadNamespaces(e,n){const r=Xe();return this.options.ns?(O(e)&&(e=[e]),e.forEach(i=>{this.options.ns.includes(i)||this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(e,n){const r=Xe();O(e)&&(e=[e]);const i=this.options.preload||[],s=e.filter(o=>!i.includes(o)&&this.services.languageUtils.isSupportedCode(o));return s.length?(this.options.preload=i.concat(s),this.loadResources(o=>{r.resolve(),n&&n(o)}),r):(n&&n(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const i=new Intl.Locale(e);if(i&&i.getTextInfo){const s=i.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services?.languageUtils||new Ii(xn());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.includes(r.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const r=new it(e,n);return r.createInstance=it.createInstance,r}cloneInstance(e={},n=xt){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new it(i);if((e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["store","services","language"].forEach(a=>{s[a]=this[a]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const a=Object.keys(this.store.data).reduce((c,l)=>(c[l]={...this.store.data[l]},c[l]=Object.keys(c[l]).reduce((u,h)=>(u[h]={...c[l][h]},u),c[l]),c),{});s.store=new Fi(a,i),s.services.resourceStore=s.store}if(e.interpolation){const c={...xn().interpolation,...this.options.interpolation,...e.interpolation},l={...i,interpolation:c};s.services.interpolator=new _i(l)}return s.translator=new Vt(s.services,i),s.translator.on("*",(a,...c)=>{s.emit(a,...c)}),s.init(i,n),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const z=it.createInstance();z.createInstance;z.dir;z.init;z.loadResources;z.reloadResources;z.use;z.changeLanguage;z.getFixedT;z.t;z.exists;z.setDefaultNamespace;z.hasLoadedNamespace;z.loadNamespaces;z.loadLanguages;function dt(t){return t.plain===""&&t.ssml===""&&t.language===""}function kd(t){if(!t||dt(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 Od(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 zt=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),En=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Ad=/[\u00A0\u2007\u202F]/;function Td(t){return Ad.test(t)}function Ve(t,e){let n="",r=!1,i=!1;for(const s of t)if(Td(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 Xn="#css(",Yn=")";function Ra(t){return`${Xn}${encodeURIComponent(t)}${Yn}`}function Na(t){if(!(!t||!t.startsWith(Xn)||!t.endsWith(Yn)))return decodeURIComponent(t.slice(Xn.length,-Yn.length))}const Qn="#domrange(",Zn=")";function Da(t){return`${Qn}${encodeURIComponent(JSON.stringify(t))}${Zn}`}function Fa(t){if(!(!t||!t.startsWith(Qn)||!t.endsWith(Zn)))try{const e=JSON.parse(decodeURIComponent(t.slice(Qn.length,-Zn.length)));return!e?.start?.cssSelector||typeof e.start.textNodeIndex!="number"?void 0:e}catch{return}}const er=":~:text=";function Et(t){return encodeURIComponent(t).replace(/-/g,"%2D")}function Ia(t){let e="";return t.prefix&&(e+=`${Et(t.prefix)}-,`),e+=Et(t.textStart),t.textEnd&&(e+=`,${Et(t.textEnd)}`),t.suffix&&(e+=`,-${Et(t.suffix)}`),`${er}${e}`}function Rd(t){if(!t)return;const e=t.indexOf(er);if(e===-1)return;const n=t.slice(e+er.length).split("&")[0];if(n)try{let r=n.split(",");const i={textStart:""};return r[0].endsWith("-")&&(i.prefix=decodeURIComponent(r[0].slice(0,-1)),r=r.slice(1)),r.length>0&&r[r.length-1].startsWith("-")&&(i.suffix=decodeURIComponent(r[r.length-1].slice(1)),r=r.slice(0,-1)),r.length===0||r[0]===""?void 0:(i.textStart=decodeURIComponent(r[0]),r.length>1&&(i.textEnd=decodeURIComponent(r[1])),i)}catch{return}}function tr(t){const e=t?.textref;if(!e)return;const n=e.indexOf(":~:"),r=n===-1?e:e.slice(0,n);let i,s;const o=Fa(r);if(o)s=o,i=o.start.cssSelector;else{const l=Na(r);l!==void 0?i=l:t?.id&&r===`#${CSS.escape(t.id)}`&&(i=r)}const a=Rd(e);if(i===void 0&&s===void 0&&a===void 0)return;const c={};return i!==void 0&&(c.cssSelector=i),s!==void 0&&(c.domRange=s),a?.textEnd!==void 0?c.fragment=Ia(a):a&&(c.text={highlight:a.textStart},a.prefix!==void 0&&(c.text.before=a.prefix),a.suffix!==void 0&&(c.text.after=a.suffix)),c}const Nd={contextualizations:{abstract:{block:{start:"Start of the abstract.",end:"End of the abstract."}},acknowledgments:{block:{start:"Start of the acknowledgments.",end:"End of the acknowledgments."}},afterword:{block:{start:"Start of the afterword.",end:"End of the afterword."}},appendix:{block:{start:"Start of the appendix.",end:"End of the appendix."}},aside:{block:{start:"Start of the aside.",end:"End of the aside."}},audio:{inline:{labelled:"Audio with a label: {{ description }}",unlabelled:"Audio with no label."}},bibliography:{block:{start:"Start of the bibliography.",end:"End of the bibliography."}},blockquote:{inline:"Blockquote."},cell:{inline:{withHeader:"{{ header }}: {{ value }}",withoutHeader:"{{ value }}"}},chapter:{block:{start:"Start of the chapter.",end:"End of the chapter."}},colophon:{inline:"Colophon."},complementary:{block:{start:"Start of the complementary content.",end:"End of the complementary content."}},conclusion:{block:{start:"Start of the conclusion.",end:"End of the conclusion."}},cover:{inline:{labelled:"Cover with a label: {{ description }}",unlabelled:"Cover with no label."}},credit:{inline:"Credit."},credits:{block:{start:"Start of the credits.",end:"End of the credits."}},dedication:{inline:"Dedication."},definition:{inline:"Definition."},details:{block:{start:"Start of the disclosure.",end:"End of the disclosure."}},endnotes:{block:{start:"Start of the endnotes.",end:"End of the endnotes."}},epigraph:{inline:"Epigraph."},epilogue:{block:{start:"Start of the epilogue.",end:"End of the epilogue."}},errata:{block:{start:"Start of the errata.",end:"End of the errata."}},example:{block:{start:"Start of the example.",end:"End of the example."}},figure:{inline:"Figure: {{ description }}"},footnote:{block:{start:"Start of the footnote.",end:"End of the footnote."}},foreword:{block:{start:"Start of the foreword.",end:"End of the foreword."}},glossary:{block:{start:"Start of the glossary.",end:"End of the glossary."}},heading1:{inline:"Heading level 1."},heading2:{inline:"Heading level 2."},heading3:{inline:"Heading level 3."},heading4:{inline:"Heading level 4."},heading5:{inline:"Heading level 5."},heading6:{inline:"Heading level 6."},image:{inline:{labelled:"Image with a label: {{ description }}",unlabelled:"Image with no label."}},index:{block:{start:"Start of the index.",end:"End of the index."}},introduction:{block:{start:"Start of the introduction.",end:"End of the introduction."}},list:{block:{start:"Start of the list.",end:"End of the list."}},listItem:{inline:"List item."},math:{inline:{labelled:"{{ description }}",unlabelled:"Math formula with no label."}},notice:{inline:"Notice."},pagebreak:{inline:"Pagebreak."},pagelist:{block:{start:"Start of the page list.",end:"End of the page list."}},part:{inline:"Part."},preface:{block:{start:"Start of the preface.",end:"End of the preface."}},prologue:{block:{start:"Start of the prologue.",end:"End of the prologue."}},pullquote:{inline:"Pullquote."},qna:{block:{start:"Start of the questions and answers.",end:"End of the questions and answers."}},row:{inline:"Row: {{ count }}"},rowheader:{inline:{withHeader:"{{ header }}: {{ value }}",withoutHeader:"{{ value }}"}},separator:{inline:"Separator."},subtitle:{inline:"Subtitle."},summary:{inline:"Summary."},table:{block:{end:"End of the table.",start:{labelled:"Table: {{ description }}. {{ lines }}. {{ columns }}.",unlabelled:"Table. {{ lines }}. {{ columns }}."}},inline:{labelled:"Table: {{ description }}. {{ lines }}. {{ columns }}.",unlabelled:"Table. {{ lines }}. {{ columns }}."},parts:{columns_one:"1 column",columns_other:"{{ count }} columns",lines_one:"1 line",lines_other:"{{ count }} lines"}},term:{inline:"Term."},tip:{inline:"Tip."},video:{inline:{labelled:"Video with a label: {{ description }}",unlabelled:"Video with no label."}}}},Dd={speech:Nd},kr=Dd.speech.contextualizations,Ui={en:kr},Fd={};async function Id(t){const e=Ui[t];if(e)return e;const n=Fd[t];if(!n)return kr;const r=(await n()).speech.contextualizations;return Ui[t]=r,r}const Pd=/<lang xml:lang="[^"]*">([\s\S]*?)<\/lang>/g;function Pa(t){return t.replace(Pd,"$1")}const Ld=/\s*<readium:[a-zA-Z][\w-]*\s+id="[^"]*"\s*\/>\s*/g;function $d(t){return t.replace(Ld,(n,r,i)=>{const s=i.slice(r+n.length);return s.length===0||Qt(s)?"":" "}).replace(/ {2,}/g," ").trim()}function _d(t){return t.includes("<")}function Or(t){if(t===void 0)return;if(typeof t=="string")return{plain:t};const e={language:t.language};if(t.ssml){const n=$d(t.ssml);_d(n)&&(e.ssml=n)}return t.plain&&(e.plain=t.plain),e.plain||e.ssml?e:void 0}function tn(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ").trim()}const La=/<lang xml:lang="([^"]*)">([\s\S]*?)<\/lang>/g;function $a(t){return new RegExp(La).test(t)}function Vi(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ")}const Bd=new RegExp(`\\s+|[${$n}]+|[${De}]+|[^\\s${$n}${De}]+`,"gu");function Cn(t){const e=[];for(const[n]of t.matchAll(Bd))/^\s/.test(n)?e.push({kind:"space"}):Tu(n)?e.push({kind:"open",text:n}):Qt(n)?e.push({kind:"close",text:n}):e.push({kind:"word",text:n});return e}function qd(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 Ud(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 Vd(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 _a(t,e){const n=[];let r=0;for(const s of t.matchAll(La))n.push({tokens:Cn(Vi(t.slice(r,s.index))),language:e,tagged:!1}),n.push({tokens:Cn(tn(s[2])),language:s[1],tagged:!0}),r=s.index+s[0].length;n.push({tokens:Cn(Vi(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(...Ud(n[s].tokens)):n[s].tagged&&!n[s+1].tagged&&n[s].tokens.push(...Vd(n[s+1].tokens));const i=[];for(const s of n){const o=qd(s.tokens);o&&i.push({plain:o,language:s.language})}return i}const Ba=/<readium:[a-zA-Z][\w-]*\s+id="([^"]*)"\s*\/>/g;function zd(t){return new RegExp(Ba).test(t)}function Md(t){const e=[];let n=0;for(const i of t.matchAll(Ba)){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}const jd=["aside","audio","bibliography","cell","columnheader","details","endnotes","figure","footnote","image","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","table","toc","video"],qa=["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"],Hd={footnote:{drops:["aside"],unconditional:!0},cover:{drops:["image"]},pullquote:{drops:["blockquote","aside"]},epigraph:{drops:["blockquote"]}},Wd=["noteref","pagebreak"],Gd=["audio","video","image","figure","math","table","cover"],Kd=["cell","rowheader"],Jd=["separator"];function Ua(t){const e=Or(t.text);return e?e.plain??(e.ssml?tn(e.ssml):""):""}function Xd(t){const e=new Map,n=new Map;let r=0,i;return t.forEach((s,o)=>{e.set(s,o+1);const a=s.children??[];if(r=Math.max(r,a.length),a.some(c=>c.role?.includes("columnheader"))){i=a.map(Ua);return}i&&a.forEach((c,l)=>{const u=c.role??[];if(!u.includes("cell")&&!u.includes("rowheader"))return;const h=i[l];h&&n.set(c,h)})}),{lines:t.length,columns:r,rowNumbers:e,cellHeaders:n}}const Yd=new Set(qa),Qd=new Set(Wd),Zd=new Set(Gd),Ar=new Set(Kd),ef=new Set(Jd);function lt(t,e,n,r){const i=n?`${e}.${n}`:void 0;if(i&&t.i18n.exists(i))return t.i18n.t(i,r);if(t.i18n.exists(e))return t.i18n.t(e,r)}function fe(t,e){return e==="ssml"?{ssml:zt(t),synthetic:!0}:{plain:t,synthetic:!0}}function ge(t,e,n,r){t.push(...r);for(let i=0;i<r.length;i++)e.push(n)}function Va(t,e,n,r,i,s,o){o?(i.some(a=>n.blockStarts.has(a))&&n.blockStarts.add(o),ge(t,e,s[0]??r,[o])):(t.push(...i),e.push(...s))}function Tr(t,e){return Ar.has(t)?!0:e.contextualize.has(t)}function tf(t,e,n){return e.some(r=>{const i=Hd[r];return i?.drops.includes(t)?i.unconditional||Tr(r,n):!1})}function zi(t,e,n,r,i,s,o,a){if(!Tr(i,r))return;if((r.i18n.exists(`${i}.block.start`)||r.i18n.exists(`${i}.block.end`))&&r.contextualizationShapes[i]!=="inline"){const l=s==="before"?`${i}.block.start`:`${i}.block.end`,u=lt(r,l,o,a);u&&ge(t,e,n,[fe(u,r.format)]);return}if(s==="before"){const l=lt(r,`${i}.inline`,o,a);if(l){const u=fe(l,r.format);if(Ar.has(i)&&(delete u.synthetic,r.language!=="none")){const h=typeof n.text=="object"?n.text.language:void 0;h&&(u.language=h)}ge(t,e,n,[u])}}}function Mi(t,e){return e.size>0&&t.some(n=>e.has(n))}function Rr(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&&!Qt(a)&&(s+=" "),s+=a);const o=e==="ssml"?{ssml:s}:{plain:s};return n&&(o.language=n),t.some(a=>a.synthetic)&&(o.synthetic=!0),o}function nf(t,e){const n=Or(t.text),r=n?za(n,e.format,e.language):[];if(!e.contextualize.has("pagebreak"))return r;const i=e.i18n.exists("pagebreak.block.start")?"pagebreak.block.start":"pagebreak.inline",s=lt(e,i);if(s===void 0)return r;const o=fe(s,e.format);if(r.length===0)return[o];const a=Rr([o,...r],e.format);return a?(a.plain!==void 0&&(a.plain+="."),a.ssml!==void 0&&(a.ssml+="."),[a]):[o,...r]}function za(t,e,n){if(e==="plain"&&n!=="block-level"&&n!=="none"&&t.ssml&&$a(t.ssml))return _a(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??zt(t.plain??""):r.plain=t.plain??tn(t.ssml??""),(n==="block-level"||n==="none")&&(r.ssml&&(r.ssml=Pa(r.ssml)),n==="none"&&delete r.language),[r]}function rf(t){return(t.role??[]).some(e=>Qd.has(e))}function sf(t,e,n,r,i,s){const o=typeof t.text=="object"?t.text.language:void 0,a=new Map((t.children??[]).map(d=>[d.id,d])),c=[],l=[],u=[];for(const d of Md(e)){if(d.placeholderId!==void 0){const p=a.get(d.placeholderId);if(!p)continue;i.inlineContextualization||!rf(p)?Ma(p,c,l,i,s):u.push(p);continue}if(!d.ssml)continue;if(i.format==="plain"&&i.language!=="block-level"&&i.language!=="none"&&$a(d.ssml)){for(const p of _a(d.ssml,o)){const m={plain:p.plain};p.language&&(m.language=p.language),c.push(m),l.push(t)}continue}const g={};o&&(g.language=o),i.format==="ssml"?g.ssml=d.ssml:g.plain=tn(d.ssml),(i.language==="block-level"||i.language==="none")&&(g.ssml&&(g.ssml=Pa(g.ssml)),i.language==="none"&&delete g.language),c.push(g),l.push(t)}const h=c.length>1?Rr(c,i.format):void 0;return Va(n,r,i,t,c,l,h),u}function ji(t,e,n,r){const i=`${e}.parts.${n}`;return t.i18n.exists(i,{count:r})?t.i18n.t(i,{count:r}):String(r)}function af(t){return t.description===void 0?{variantKey:"unlabelled"}:{variantKey:"labelled",params:{description:t.description}}}function Hi(t,e){const n=e.tableCellHeaders.get(t);return{variantKey:n!==void 0?"withHeader":"withoutHeader",params:{header:n??"",value:Ua(t)}}}const of={table:(t,e)=>{const n=(t.children??[]).filter(i=>i.role?.includes("row")),r=Xd(n);for(const[i,s]of r.rowNumbers)e.tableRowNumbers.set(i,s);for(const[i,s]of r.cellHeaders)e.tableCellHeaders.set(i,s);return{params:{lines:ji(e,"table","lines",r.lines),columns:ji(e,"table","columns",r.columns)}}},row:(t,e)=>({params:{count:String(e.tableRowNumbers.get(t)??"")}}),cell:Hi,rowheader:Hi};function Wi(t,e,n){const r=af(e);let i=r.variantKey,s=r.params;const o=of[t]?.(e,n);o&&(o.variantKey&&(i=o.variantKey),s={...s,...o.params});const a=n.contextualizationParams?.(t,e);return a&&(s={...s,...a}),{variantKey:i,params:s}}function Ma(t,e,n,r,i){const s=t.role??[];if(Mi(s,r.skip))return;const o=s.some(d=>Yd.has(d)),a=o&&!i,c=e.length,l=s.filter(d=>d!=="footnote"&&d!=="pagebreak"&&!tf(d,s,r)),u=s.some(d=>Zd.has(d)&&r.contextualize.has(d)),h=s.includes("table")&&t.description!==void 0&&!u;h&&ge(e,n,t,[fe(t.description,r.format)]);for(const d of l){if(d==="figure"&&t.description===void 0)continue;const{variantKey:g,params:p}=Wi(d,t,r);zi(e,n,t,r,d,"before",g,p)}if(s.includes("noteref"))for(const d of t.children??[]){const g=d.role??[];if(!Mi(g,r.skip))if(g.includes("footnote")){const p=[],m=[];he([d],p,m,r,i);const b=r.contextualize.has("footnote"),x=r.i18n.exists("footnote.block.start")||r.i18n.exists("footnote.block.end"),A=b?lt(r,x?"footnote.block.start":"footnote.inline"):void 0,S=b&&(A!==void 0||x),w=[],T=[];if(A!==void 0&&(w.push(fe(A,r.format)),T.push(d)),w.push(...p),T.push(...m),S&&x){const L=lt(r,"footnote.block.end");L!==void 0&&(w.push(fe(L,r.format)),T.push(d))}const F=S&&w.length>1?Rr(w,r.format):void 0;Va(e,n,r,d,w,T,F)}else he([d],e,n,r,i)}else if(!s.some(d=>ef.has(d))){const d=typeof t.text=="object"?t.text.ssml:void 0;if(d&&zd(d)){const g=sf(t,d,e,n,r,i);if(g.length>0){const p=i||o&&e.length>c;he(g,e,n,r,p)}}else if(s.includes("pagebreak")){if(ge(e,n,t,nf(t,r)),t.children){const g=i||o&&e.length>c;he(t.children,e,n,r,g)}}else{const p=s.some(m=>Ar.has(m)&&Tr(m,r))?void 0:Or(t.text);if(p&&ge(e,n,t,za(p,r.format,r.language)),t.children){const m=i||o&&e.length>c;he(t.children,e,n,r,m)}}}a&&e.length>c&&r.blockStarts.add(e[c]),t.description!==void 0&&!u&&!h&&ge(e,n,t,[fe(t.description,r.format)]);for(const d of l){if(d==="figure"&&t.description===void 0)continue;const{variantKey:g,params:p}=Wi(d,t,r);zi(e,n,t,r,d,"after",g,p)}}function he(t,e,n,r,i){t.forEach((s,o)=>Ma(s,e,n,r,o===0?i:!1))}function lf(t,e){const n=z.createInstance();return n.init({lng:t,resources:{[t]:{translation:e}},interpolation:{escapeValue:!1}}),n}function ja(t,e){if(typeof e=="string"||typeof t!="object")return e;const n={...t};for(const r of Object.keys(e))n[r]=ja(t[r],e[r]);return n}function cf(t,e){if(!e)return t;const n={...t};for(const r of Object.keys(e))n[r]=ja(t[r],e[r]);return n}async function Ha(t){const e=t.contextualizationLocale??"en",n=cf(await Id(e),t.contextualization?.contextualizations);return{contextualizations:n,i18n:lf(e,n),skip:new Set(t.skip??[]),contextualize:new Set(t.contextualize??[]),contextualizationShapes:t.contextualization?.shapes??{},contextualizationParams:t.contextualization?.params,format:t.format??"plain",inlineContextualization:t.inlineContextualization??!1,language:t.language??"block-level",blockStarts:new Set,tableRowNumbers:new Map,tableCellHeaders:new Map}}async function uf(t,e){const n=[],r=[];return he(t,n,r,await Ha(e),!1),Wa(n,r,Nr(t))}async function hf(t,e){const n=[],r=[],i=await Ha(e);he(t,n,r,i,!1);const s=n.map(o=>i.blockStarts.has(o));return{utterances:Wa(n,r,Nr(t)),sources:r,blockStarts:s}}function Nr(t,e=[],n=new Map){for(const r of t)n.set(r,e),r.children&&Nr(r.children,[r,...e],n);return n}function Wa(t,e,n){return t.map((r,i)=>{const s=e[i];let o=tr(s);if(!o&&s){for(const a of n.get(s)??[])if(o=tr(a),o)break}return o?{...r,locate:o}:r})}class df{engine;contentQueue=[];events=new Jt;navigatorState="idle";pendingAdvanceTimeout=null;_defaults;_preferences;_settings;_preferencesEditor=null;contextualizationOverrides;source;contentSources=[];contentBlockStarts=[];pendingResumeIndex=null;pendingResumeState=null;pendingAutoPauseIndex=null;constructor(e,n={}){this.engine=e,this._defaults=new Sa(n.defaults),this._preferences=new Ue(n.preferences),this._settings=new Kn(this._preferences,this._defaults),this.contextualizationOverrides=n.contextualizationOverrides,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.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,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)}),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)}async loadGndContent(e){this.source=e,await 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,n??void 0),this.emitContentChangeEvent({content:i})}async 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}=await hf(this.source,{format:this._settings.format,inlineContextualization:this._settings.inlineContextualization,skip:this._settings.skip,contextualize:this._settings.contextualize,contextualization:{contextualizations:this.contextualizationOverrides?.contextualizations,shapes:id(this._settings.verbosity,this.contextualizationOverrides?.shapes),params:this.contextualizationOverrides?.params},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.events.on(e,n)}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 Wn(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){!this.source&&Ai.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),await this.applyPreferences()}async applyPreferences(){const e=this._settings;this._settings=new Kn(this._preferences,this._defaults),this.applyEngineParameters(),this._preferencesEditor!==null&&(this._preferencesEditor=new Wn(this._preferences,this._settings)),Ai.some(n=>!this.sameSettingValue(e[n],this._settings[n]))&&await 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.events.clear(),await this.engine.destroy()}}const ff=["heading1","heading2","heading3","heading4","heading5","heading6"],Gi={"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",grid:"table",gridcell:"cell",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"},gf={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"},pf={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"},mf=new Set(["table","tr","td","th"]),yf=new Set(["table","row","cell","columnheader","rowheader"]);function bf(t){const e=t.getAttribute("role");if(!e)return!1;const n=e.split(/\s+/).filter(Boolean);return n.includes("presentation")||n.includes("none")}function Sf(t){for(let e=t.parentElement;e;e=e.parentElement)if(bf(e))return!0;return!1}function vf(t,e,n){return mf.has(e)||n.some(r=>yf.has(r))}function Tt(t,e){const n=t.getAttribute("role");return n?n.split(/\s+/).filter(Boolean).includes(e):!1}function wf(t){return t.tagName.toLowerCase()==="table"||Tt(t,"table")||Tt(t,"grid")||Tt(t,"treegrid")}function xf(t){return t.tagName.toLowerCase()==="tr"||Tt(t,"row")}function Ef(t){let e=null;for(let r=t.parentElement;r;r=r.parentElement)if(wf(r)){e=r;break}return e?e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>xf(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}).nextNode()===t:!1}function Ga(t){const e=[];let n=!1;const r=t.getAttribute("role");if(r)for(const s of r.split(/\s+/).filter(Boolean))if((s==="presentation"||s==="none")&&(n=!0),s==="heading"){let o=2;const a=parseInt(t.getAttribute("aria-level")??"",10);Number.isFinite(a)&&a>=1&&(o=Math.min(a,6)),e.push(ff[o-1])}else Gi[s]&&e.push(Gi[s]);const i=t.getAttribute("epub:type");if(i)for(const s of i.split(/\s+/).filter(Boolean)){const o=gf[s];o&&e.push(o)}return{attrRoles:e,presentational:n}}function Ka(t){const{attrRoles:e,presentational:n}=Ga(t);return e.length>0||n}function Rt(t){const e=[],n=o=>{e.includes(o)||e.push(o)},{attrRoles:r,presentational:i}=Ga(t),s=t.tagName.toLowerCase();if(i)return["presentation"];if(vf(t,s,r)&&Sf(t))return["presentation"];if(s==="body")n("body");else if(s==="th")switch(t.getAttribute("scope")){case"col":n("columnheader");break;case"row":n("rowheader");break;default:{const o=t.parentElement;o&&Ef(o)?n("columnheader"):t.previousElementSibling===null?n("rowheader"):n("cell")}}else{const o=pf[s];o&&n(o)}for(const o of r)n(o);return e}function Ki(t){return!!(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))}function Cf(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 nn(t){return Ve(Cf(t),!0).trim()}function nr(t){let e="";const n=(r,i)=>{if(r.nodeType===3){e+=r.nodeValue??"";return}if(!(r.nodeType===1&&!i&&Ka(r)))for(let s=r.firstChild;s;s=s.nextSibling)n(s,!1)};return n(t,!0),e}function Ji(t){return Ve(nr(t),!0).trim()}function kf(t){if(Ki(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((u,h)=>{if(Ki(u))return;const d=u.getAttribute("aria-label");c+=d||nr(u),h<a.length-1&&(c+=" ")});const l=Ve(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=>nr(l)).join(" "),c=Ve(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=nn(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 Of={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function Af(t){return Of[t]??["",void 0]}const Tf=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]),Rf=["math","separator"];function rr(t){return t.role?.some(e=>Rf.includes(e))?!1:!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||dt(t.text))&&!(t.children&&t.children.length>0)&&!t.description}function Nf(t){return!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||dt(t.text))&&!!(t.children&&t.children.length>0)&&!(t.role&&t.role.length>0)&&!t.id}function Df(t){return!(t.role&&t.role.length>0)&&!t.id&&!t.textref&&!t.imgref&&!t.audioref&&!t.videoref}class Ct{el;object={};children=[];noText=!1;finalize(){const e=this.object,n=[];for(const r of this.children){const i=r.finalize();if(!rr(i)){if(Nf(i)){n.push(...i.children??[]);continue}n.push(i)}}if(n.length>0&&(e.children=n),e.role?.length&&e.children?.length===1&&!e.role.includes("presentation")){const r=e.children[0];r.role?.length&&e.role.every(i=>r.role.includes(i))&&delete e.role}if((!e.text||dt(e.text))&&e.children?.length===1){const r=e.children[0];Df(r)&&(r.text&&(e.text=r.text),e.children=r.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 n=kd(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(ir)),t.description&&(e.description=t.description),e}function Ja(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(Ja)),e}const Ff=1;function Xi(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 If(t){for(let e=t.firstChild;e;e=e.nextSibling)if(e.nodeType===Ff)return!0;return!1}function Xa(t,e){for(let n=e;n;n=n.parentElement)if(n===t)return!0;return!1}const Pf=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"]);function Lf(t){return Pf.has(t)}function $f(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"}function Ya(t){return typeof t=="object"&&t!==null&&t.nodeType===Node.ELEMENT_NODE}const ct={NONE:"",DESCENDANT:" ",CHILD:" > "},$={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"};function _f(t,e){return Object.values(t).includes(e)}const Bf="CssSelectorGenerator";function Mt(t="unknown problem",...e){console.warn(`${Bf}: ${t}`,...e)}const qf={selectors:[$.id,$.class,$.tag,$.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY,useScope:!1,ignoreGeneratedClassNames:!1};function Ye(t){return!!t}function Uf(t){return Array.isArray(t)?t.filter(e=>_f($,e)):[]}function Qa(t){return t instanceof RegExp}function Vf(t){return["string","function"].includes(typeof t)||Qa(t)}function Yi(t){return Array.isArray(t)?t.filter(Vf):[]}function zf(t){return t!=null&&typeof t=="object"&&"nodeType"in t&&typeof t.nodeType=="number"}function Qi(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return zf(t)&&e.includes(t.nodeType)}function Za(t,e){if(Qi(t))return t.contains(e)||Mt("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element's real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will not work as intended."),t;const n=e.getRootNode({composed:!1});return Qi(n)?(n.nodeType!==Node.DOCUMENT_NODE&&Mt("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):Fr(e)}function kn(t){return typeof t=="number"?t:Number.POSITIVE_INFINITY}function Mf(t,e={}){const n=Object.assign(Object.assign({},qf),e);return{selectors:Uf(n.selectors),whitelist:Yi(n.whitelist),blacklist:Yi(n.blacklist),root:Za(n.root,t),combineWithinSelector:Ye(n.combineWithinSelector),combineBetweenSelectors:Ye(n.combineBetweenSelectors),includeTag:Ye(n.includeTag),maxCombinations:kn(n.maxCombinations),maxCandidates:kn(n.maxCandidates),useScope:Ye(n.useScope),maxResults:kn(n.maxResults),ignoreGeneratedClassNames:Ye(n.ignoreGeneratedClassNames)}}function ft(t=[]){const[e=[],...n]=t;return n.length===0?e:n.reduce((r,i)=>{const s=new Set(i);return r.filter(o=>s.has(o))},e)}function jf(t){return[].concat(...t)}function Hf(t){return t.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function jt(t){const e=t.map(n=>{if(Qa(n))return r=>n.test(r);if(typeof n=="function")return r=>{const i=n(r);return typeof i!="boolean"?(Mt("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",n),!1):i};if(typeof n=="string"){const r=new RegExp("^"+Hf(n)+"$");return i=>r.test(i)}return Mt("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",n),()=>!1});return n=>e.some(r=>r(n))}function Dr(t,e,n){const r=Za(n,t[0]).querySelectorAll(e);if(r.length!==t.length)return!1;const i=new Set(r);return t.every(s=>i.has(s))}function eo(t,e){e=e??Fr(t);const n=[];let r=t;for(;r&&r!==e;)Ya(r)&&n.push(r),r=r.parentNode;return n}function Wf(t,e){return ft(t.map(n=>eo(n,e)))}function Gf(t){return typeof t=="object"&&t!==null&&"nodeType"in t&&t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function Fr(t){return t.ownerDocument.querySelector(":root")}const to=", ",Kf=new RegExp(["^$","\\s"].join("|")),Jf=new RegExp(["^$"].join("|")),no=[$.nthoftype,$.tag,$.id,$.class,$.attribute,$.nthchild],Xf=jt(["class","id","ng-*"]);function Yf({name:t}){return`[${t}]`}function Qf({name:t,value:e}){return`[${t}='${e}']`}function Zf({nodeName:t,nodeValue:e},n){const r=n.tagName.toLowerCase();return["input","option"].includes(r)&&t==="value"||t==="src"&&e?.startsWith("data:")?!1:!Xf(t)}function eg({nodeName:t,nodeValue:e}){return{name:ze(t),value:ze(e??void 0)}}function ro(t,e){const n=Array.from(t.attributes).filter(r=>Zf(r,t)).map(eg);return[...n.map(Yf),...n.map(Qf)]}function tg(t,e){const n=t.map(r=>ro(r));return ft(n)}const ng=/^[a-z_-]{3,}$/i,rg=/[bcdfghjklmnpqrstvwxyz]{4,}/i;function ig(t){if(!ng.test(t)||t.includes("_")&&!t.includes("__")||/^(css|sc|jsx|emotion|makeStyles|MuiButton|MuiBox)-/i.test(t))return!1;const e=t.split(new RegExp("--|__|[-]|(?<=[a-z])(?=[A-Z])")).filter(n=>n.length>0);if(e.length===0||e.length===1&&e[0].length<4)return!1;for(const n of e)if(n.length<=2||rg.test(n))return!1;return!0}function io(t,e){var n;const r=((n=t.getAttribute("class"))!==null&&n!==void 0?n:"").trim().split(/\s+/).filter(s=>!Jf.test(s));let i=r;if(e?.ignoreGeneratedClassNames){const s=jt(e.whitelist);i=r.filter(o=>{const a=`.${ze(o)}`;return s(a)?!0:ig(o)})}return i.map(s=>`.${ze(s)}`)}function sg(t,e){const n=t.map(r=>io(r,e));return ft(n)}function so(t,e){var n;const r=(n=t.getAttribute("id"))!==null&&n!==void 0?n:"",i=`#${ze(r)}`,s=t.getRootNode({composed:!1});return!Kf.test(r)&&Dr([t],i,s)?[i]:[]}function ag(t,e){return t.length===0||t.length>1?[]:so(t[0])}function ao(t,e){const n=t.parentNode,r=n&&"children"in n?n.children:null;if(r){for(let i=0;i<r.length;i++)if(r[i]===t)return[`:nth-child(${String(i+1)})`]}return[]}function og(t,e){return ft(t.map(n=>ao(n)))}function oo(t,e){return[ze(t.tagName.toLowerCase())]}function lo(t,e){const n=[...new Set(jf(t.map(r=>oo(r))))];return n.length===0||n.length>1?[]:[n[0]]}function co(t,e){const n=lo([t])[0],r=t.parentNode,i=r&&"children"in r?r:null;if(i){const o=Array.from(i.children).filter(a=>a.tagName.toLowerCase()===n).indexOf(t);if(o>-1)return[`${n}:nth-of-type(${String(o+1)})`]}return[]}function lg(t,e){return ft(t.map(n=>co(n)))}function*uo(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,r=ho(1);for(;r.length<=t.length&&n<e;){n+=1;const i=new Array(r.length);for(let s=0;s<r.length;s++)i[s]=t[r[s]];yield i,r=ug(r,t.length-1)}}function cg(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(uo(t,{maxResults:e}))}function ug(t=[],e=0){const n=t.length;if(n===0)return t;let r=n-1;for(;r>=0&&t[r]===e-(n-1-r);)r-=1;if(r<0)return ho(n+1);t[r]+=1;for(let i=r+1;i<n;i++)t[i]=t[i-1]+1;return t}function ho(t=1){const e=new Array(t);for(let n=0;n<t;n++)e[n]=n;return e}function*hg(t={}){const e=Object.entries(t);if(e.length===0)return;const n=[{index:e.length-1,partial:{}}];for(;n.length>0;){const r=n.pop();if(!r)break;const{index:i,partial:s}=r;if(i<0){yield s;continue}const[o,a]=e[i];for(let c=a.length-1;c>=0;c--)n.push({index:i-1,partial:Object.assign(Object.assign({},s),{[o]:a[c]})})}}const dg="3a".toUpperCase(),fg=/[ !"#$%&'()[\]{|}<>*+,./;=?@^`~\\]/;function ze(t=""){return CSS?CSS.escape(t):gg(t)}function gg(t=""){return t.split("").map(e=>e===":"?`\\${dg} `:fg.test(e)?`\\${e}`:escape(e).replace(/%/g,"\\")).join("")}const pg={tag:lo,id:ag,class:sg,attribute:tg,nthchild:og,nthoftype:lg},mg={tag:oo,id:so,class:io,attribute:ro,nthchild:ao,nthoftype:co};function yg(t,e,n){return mg[e](t,n)}function bg(t,e,n){const r=pg[e];return r(t,n)}function Sg(t=[],e,n){return t.filter(r=>n(r)||!e(r))}function vg(t=[],e){return t.sort((n,r)=>{const i=e(n),s=e(r);return i&&!s?-1:!i&&s?1:0})}function rn(){const t=new Map;let e;return(n,r)=>{if(n.length!==1)return e??(e=Zi(n,r));const[i]=n;let s=t.get(i);return s||(s=Zi(n,r),t.set(i,s)),s}}function*wg(t,e,n=rn()){const r=new Set,i=n(t,e);for(const s of kg(i,e))r.has(s)||(r.add(s),yield s)}function Zi(t,e){const{blacklist:n,whitelist:r,combineWithinSelector:i,maxCombinations:s}=e,o=jt(n),a=jt(r),c=(l,u)=>{const h=bg(t,u,e),d=Sg(h,o,a),g=vg(d,a);return l[u]=i?Array.from(uo(g,{maxResults:s})):g.map(p=>[p]),l};return xg(e).reduce(c,{})}function xg(t){const{selectors:e,includeTag:n}=t,r=[...e];return n&&!r.includes("tag")&&r.push("tag"),r}function Eg(t){return t.includes($.tag)||t.includes($.nthoftype)?[...t]:[...t,$.tag]}function Cg(t){const{selectors:e,combineBetweenSelectors:n,includeTag:r,maxCandidates:i}=t,s=n?cg(e,{maxResults:i}):e.map(o=>[o]);return r?s.map(Eg):s}function*kg(t,e){for(const n of Cg(e))yield*Og(n,t)}function*Og(t,e){const n={};for(const r of t){const i=e[r];i&&i.length>0&&(n[r]=i)}for(const r of hg(n))yield Tg(r)}function Ag(t,e){return e[t]?e[t].join(""):""}function Tg(t={}){const e=[...no];return t[$.tag]&&t[$.nthoftype]&&e.splice(e.indexOf($.tag),1),e.map(n=>Ag(n,t)).join("")}function Rg(t,e){return[...t.map(n=>e+ct.DESCENDANT+n),...t.map(n=>e+ct.CHILD+n)]}function*Ng(t,e){if(e==="")yield*t;else for(const n of t)yield*Rg([n],e)}function*Dg(t,e,n="",r,i=rn()){const s=wg(t,r,i);for(const o of Ng(s,n))Dr(t,o,e)&&(yield o)}function*Fg(t,e,n="",r,i=rn()){if(t.length===0)return null;const s=[t.length>1?t:[],...Wf(t,e).map(o=>[o])];for(const o of s)for(const a of Dg(o,e,n,r,i))yield{foundElements:o,selector:a}}function*Ig({elements:t,root:e,rootSelector:n="",options:r}){let i=e,s=n,o=!0;const a=rn();for(;o;){let c=!1;for(const l of Fg(t,i,s,r,a)){const{foundElements:u,selector:h}=l;if(c=!0,Dr(t,h,e))yield h;else{i=u[0],s=h;break}}c||(o=!1)}}function Pg(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(Ya);return[...new Set(e)]}function Lg(t){return{value:t,include:!1}}function $g(t,e,n=ct.NONE){const r={};return e.forEach(i=>{Reflect.set(r,i,yg(t,i).map(Lg))}),{element:t,operator:n,selectors:r}}function _g({selectors:t,operator:e}){let n=[...no];t[$.tag]&&t[$.nthoftype]&&(n=n.filter(i=>i!==$.tag));let r="";return n.forEach(i=>{var s;((s=t[i])!==null&&s!==void 0?s:[]).forEach(({value:a,include:c})=>{c&&(r+=a)})}),e+r}function Bg(t,e){const n=eo(t,e).reverse(),r=Gf(e),i=n.map((o,a)=>{var c;const l=$g(o,[$.nthchild],r&&a===0?ct.NONE:ct.CHILD);return((c=l.selectors.nthchild)!==null&&c!==void 0?c:[]).forEach(u=>{u.include=!0}),l});return[r?"":e?":scope":":root",...i.map(_g)].join("")}function qg(t,e){return t.map(n=>Bg(n,e)).join(to)}var Ug=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n};function fo(t,e={}){const n=Object.assign(Object.assign({},e),{maxResults:1});return Vg(t,n).next().value}function*Vg(t,e={}){var n;const r=Pg(t),i=Mf(r[0],e),s=(n=i.root)!==null&&n!==void 0?n:Fr(r[0]);let o=0;for(const c of Ig({elements:r,options:i,root:s,rootSelector:""}))if(yield c,o++,o>=i.maxResults)return;if(r.length>1){const{maxResults:c}=e,l=Ug(e,["maxResults"]);if(yield r.map(u=>fo(u,l)).join(to),o++,o>=i.maxResults)return}const a=e.root!==void 0;yield qg(r,i.useScope||a?s:void 0)}function Ir(t,e){const n=t.getAttribute("id");return n?`#${CSS.escape(n)}`:fo(t,{root:e?.documentElement??void 0})??void 0}function go(t){if(t)return t.startsWith("#")?t:Ra(t)}const zg=3;function Mg(t,e){let n=0;for(const r of Array.from(t.childNodes)){if(r===e)return n;r.nodeType===zg&&n++}return n}function es(t,e,n,r){const i=t.parentElement;if(!i)return;const s=r&&i===r.el?r.selector:Ir(i,n);if(s)return{cssSelector:s,textNodeIndex:Mg(i,t),charOffset:e}}function jg(t,e,n){const r=es(...t.first,e,n);if(!r)return;const i=es(...t.last,e,n);return i?{start:r,end:i}:{start:r}}function Hg(t){const e=mh(t);return e.status===de.SUCCESS?e.fragment:void 0}function ts(t){if(t===!0)return e=>e.length>0;if(Array.isArray(t)&&t.length>0){const e=new Set(t);return n=>n.some(r=>e.has(r))}return null}function Wg(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Gg(t){return Wg(t)?{predicate:ts(t.roles),domRange:!!t.domRange,textFragment:!!t.textFragment}:{predicate:ts(t),domRange:!1,textFragment:!1}}class Kg{claimed=new Set;counters=new Map;allocate(e,n){for(;;){const r=(this.counters.get(e)??0)+1;this.counters.set(e,r);const i=`${e}${r}`;if(!(n(i)||this.claimed.has(i)))return this.claimed.add(i),i}}claim(e){return this.claimed.has(e)?!1:(this.claimed.add(e),!0)}}function Jg(t,e,n){const r=[],i=(s,o)=>{const a=s.getAttribute("id");if(a&&!e.has(a)&&e.set(a,s),o=o||s.getAttribute("aria-hidden")==="true"||s.hasAttribute("hidden"),!o&&s.tagName.toLowerCase()==="a"&&Rt(s).includes("noteref")){const l=s.getAttribute("href")??"";l.startsWith("#")&&r.push({id:l.slice(1),ref:s})}for(let c=s.firstElementChild;c;c=c.nextElementSibling)i(c,o)};i(t,!1);for(const s of r){const o=e.get(s.id);o&&(Xa(o,s.ref)||n.add(o))}}function Xg(t,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&&!dt(i.text)),a=!t.xmlParsed&&(If(e)||o&&e.firstChild!==null);if(!o&&!a){const u=nn(e);u&&(i.text={plain:u,ssml:"",language:""})}const c=Ir(e,t.docRoot),l=go(c);return l&&(i.textref=l),t.placeholder(e,"pagebreak",i),a}function Yg(t,e,n){const r={role:n},i=nn(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=t.ids.get(a);if(c&&!Xa(c,e)&&t.noterefDepth<3){const l=t.spawnChild(c);l.convert(c);const u=l.result();u.length>0&&(r.children=u.map(h=>{const d=Ja(h);return delete d.id,d}))}}!r.children&&s&&(r.children=[{textref:s}]),t.placeholder(e,"noteref",r,o||void 0)}function Qg(t,e,n,r){const i={};if(n.length>0&&(i.role=n),r)i.text={plain:r.plain??"",ssml:r.ssml??"",language:r.language};else{const o=nn(e);o&&(i.text={plain:o,ssml:"",language:""})}const s=e.getAttribute("href");s&&(i.textref=s),t.placeholder(e,n[0]??"link",i)}const Zg=3,ep=1,tp=new Set(["summary","dfn","span"]);function ns(t,e){return tp.has(t)&&e.length>0?!0:!Lf(t)}class Ht{xmlParsed;ids=new Map;suppressed=new Set;idAlloc=new Kg;noterefDepth=0;allowNode=null;selectorPredicate=null;domRangeEnabled=!1;textFragmentEnabled=!1;docRoot=null;root=new Ct;current=this.root;foldedCaptions=new Set;segments=[];textAcc="";currentCtx={lang:"",tag:""};flowEndsWithSpace=!0;pendingChildren=[];flowFirstNode=null;flowFirstOffset=0;flowLastNode=null;flowLastOffset=0;lastFlowRange=null;lastFlowText=null;constructor(e){this.xmlParsed=e}spawnChild(e,n=1){const r=new Ht(this.xmlParsed);return r.ids=this.ids,r.suppressed=this.suppressed,r.idAlloc=this.idAlloc,r.noterefDepth=this.noterefDepth+n,r.allowNode=e,r.docRoot=this.docRoot,r.selectorPredicate=this.selectorPredicate,r.domRangeEnabled=this.domRangeEnabled,r.textFragmentEnabled=this.textFragmentEnabled,r}prescan(e){Jg(e,this.ids,this.suppressed)}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?rr(e)?[]:[ir(e)]:e.children.map(ir)}descend(e,n){const r=new Ct;r.el=e,r.noText=this.foldedCaptions.has(e)||(!Ka(e)||n.includes("caption"))&&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===Zg){this.text(e);return}if(e.nodeType!==ep)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(Tf.has(n)||this.suppressed.has(e)&&e!==this.allowNode)return!0;const[r,i]=kf(e);if(!i&&e!==this.allowNode)return!0;const s=Rt(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!Xg(this,e,r,s);if(n==="a"&&s.includes("noteref")&&e.getAttribute("href"))return Yg(this,e,s),!0;if(n==="a"&&e.getAttribute("href"))return Qg(this,e,s,r),!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 u=e.querySelector(":scope > source[src]");u&&(l=u.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(!ns(n,s))return!1;this.flushText(),this.descend(e,s);const o=this.current.object;if(s.length>0&&(o.role=s),r)o.description=r.plain,s.includes("figure")&&(this.current.noText=!0);else if(s.includes("figure")){const c=this.implicitCaptionOf(e);if(c){const l=Ji(c);l&&(o.description=l,this.current.noText=!0)}}else if(s.includes("table")){const c=this.implicitCaptionOf(e);if(c){const l=Ji(c);l&&(o.description=l,this.foldedCaptions.add(c))}}const a=e.getAttribute("id");return a&&(o.id=a),!1}implicitCaptionOf(e){for(let n=e.firstElementChild;n;n=n.nextElementSibling)if(Rt(n).includes("caption")&&!n.getAttribute("aria-labelledby"))return n;return null}tail(e,n,r){if(n)return;const i=e.tagName.toLowerCase(),s=Rt(e);ns(i,s)&&(this.flushText(),this.selectorPredicate?.(s)&&this.applyTextref(e),this.current=r)}applyTextref(e){const n=this.current.object,r=Ir(e,this.docRoot);if(n.textref=go(r),this.domRangeEnabled&&this.lastFlowRange){const i=r?{el:e,selector:r}:void 0,s=jg(this.lastFlowRange,this.docRoot,i);s&&(n.textref=Da(s))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const i=this.docRoot.createRange();i.setStart(...this.lastFlowRange.first),i.setEnd(...this.lastFlowRange.last);const s=Hg(i);s&&(n.textref=`${n.textref??"#"}${Ia(s)}`)}}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+=Ve(n,this.flowEndsWithSpace),this.updateFlowSpace());return}const r=this.textContext(e);if(Od(r,this.currentCtx)||(this.closeSegment(),this.currentCtx=r),this.textAcc+=Ve(n,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const i=e;this.flowFirstNode===null&&(this.flowFirstNode=i,this.flowFirstOffset=n.search(/\S/)),this.flowLastNode=i,this.flowLastOffset=n.length-(n.match(/\s+$/)?.[0].length??0)}}textContext(e){const n={lang:Xi(e.parentElement),tag:""};for(let r=e.parentElement;r&&r!==this.current.el;r=r.parentElement){const[i,s]=Af(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=[],this.flowFirstNode=null,this.flowFirstOffset=0,this.flowLastNode=null,this.flowLastOffset=0}placeholder(e,n,r,i){if(rr(r))return;const s=new Ct;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}flushText(){this.closeSegment();let e=this.segments;const n=this.pendingChildren,r=this.flowFirstNode,i=this.flowFirstOffset,s=this.flowLastNode,o=this.flowLastOffset;if(this.resetFlow(),this.lastFlowRange=null,this.lastFlowText=null,e.length===0)return;for(;e.length>0;){const S=e[0];if(S.kind==="break"){e=e.slice(1);continue}if(S.kind==="text"){const w=S.text.replace(/^\s+/,"");if(w===""){e=e.slice(1);continue}e=[{...S,text:w},...e.slice(1)]}break}for(;e.length>0;){const S=e[e.length-1];if(S.kind==="break"){e=e.slice(0,-1);continue}if(S.kind==="text"){const w=S.text.replace(/\s+$/,"");if(w===""){e=e.slice(0,-1);continue}e=[...e.slice(0,-1),{...S,text:w}]}break}if(!e.some(S=>S.kind==="text"&&S.text.trim()!=="")){for(const S of n)this.appendChild(S);return}const c=[];for(const S of e)if(S.kind==="text"&&S.text.trim()!==""){const w=S.ctx.lang;c.includes(w)||c.push(w)}let l=Xi(this.current.el??null);c.length===1&&c[0]!==""&&(l=c[0]);let u=!1;for(const S of e)if(S.kind!=="text"||S.ctx.tag!==""||S.ctx.lang!==l){u=!0;break}if(u&&l===""&&(l="en"),u)for(const S of e){if(S.kind!=="placeholder")continue;let w=S.candidateID;(!w||!this.idAlloc.claim(w))&&(w=this.idAlloc.allocate(S.tag,T=>this.ids.has(T))),S.child.object.id=w}let h="",d=!1,g=!1,p=!1,m=!1;for(const S of e)if(S.kind==="text"){const w=S.text.startsWith(" "),T=S.text.replace(/^ +| +$/g,"");if(T===""){m=!0;continue}let F=!1;if(h.length>0){const L=d||m||w;g?F=!0:p?F=L&&!Qt(T):F=L}F&&(h+=" "),h+=T,d=S.text.endsWith(" "),g=!1,p=!1,m=!1}else S.kind==="break"?g=!0:S.kind==="placeholder"&&(p=!0);const b=e.some(S=>S.kind==="placeholder");this.lastFlowText=h.trim();const x={plain:u&&!b?"":h.trim(),ssml:"",language:l};if(u){let S="";for(const w of e)if(w.kind==="text"){let T=w.ctx.tag,F=w.ctx.attrs;if(w.ctx.lang!==l&&w.ctx.lang!==""&&(T="lang",F=void 0),T){S+=`<${T}`;for(const[L,X]of Object.entries(F??{}))S+=` ${L}="${En(X)}"`;w.ctx.lang!==l&&w.ctx.lang!==""&&(S+=` xml:lang="${En(w.ctx.lang)}"`),S+=`>${zt(w.text)}</${T}>`}else S+=zt(w.text)}else w.kind==="break"?S+="<break/>":w.kind==="placeholder"&&(S+=`<readium:${w.tag} id="${En(w.child.object.id)}" />`);x.ssml=S}const A=new Ct;A.object={text:x};for(const S of n)A.children.push(S);this.appendChild(A),r&&s&&(this.lastFlowRange={first:[r,i],last:[s,o]})}}const np=/<body[\s>]/i;function po(t,e,n){const{predicate:r,domRange:i,textFragment:s}=Gg(n?.textrefs);if(typeof t!="string"){const u=e??(t.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),h=new Ht(u==="application/xhtml+xml");return h.selectorPredicate=r,h.domRangeEnabled=i,h.textFragmentEnabled=s,h.docRoot=t.ownerDocument,h.convert(t),h.result()}const o=e??$f(t),a=new DOMParser().parseFromString(t,o),c=new Ht(o==="application/xhtml+xml");c.selectorPredicate=r,c.textFragmentEnabled=s,c.docRoot=a;const l=a.querySelector("body");return l&&!np.test(t)?c.convertChildren(l):c.convert(l??a.documentElement),c.result()}function rp(t,e,n){return{guided:po(t,e,n)}}exports.BUILTIN_DECORATION_TYPES=ca;exports.BooleanPreference=va;exports.DecorationController=ma;exports.DecorationLayout=aa;exports.DecorationStyleType=R;exports.DecorationWidth=sa;exports.Decorator=la;exports.DirectCommsChannel=fa;exports.DirectCommsFrame=ga;exports.DirectCommsHost=pa;exports.EnumPreference=tt;exports.FallbackEngineProvider=ju;exports.FallbackSpeechEngine=Rs;exports.Locator=Sr;exports.LocatorLocations=ue;exports.LocatorText=br;exports.Preference=ht;exports.RangePreference=nt;exports.ReadiumSpeechDecorationController=ba;exports.ReadiumSpeechNavigator=df;exports.ReadiumSpeechProviderRegistry=td;exports.SpeechDefaults=Sa;exports.SpeechPreferences=Ue;exports.SpeechPreferencesEditor=Wn;exports.SpeechServerAudioDecodeError=gr;exports.SpeechServerEngine=As;exports.SpeechServerEngineProvider=Vu;exports.SpeechServerError=qe;exports.SpeechServerNetworkError=pr;exports.SpeechServerStallError=fr;exports.SpeechSettings=Kn;exports.StringArrayPreference=Hn;exports.WebSpeechEngine=Ln;exports.WebSpeechEngineProvider=ku;exports.WebSpeechVoiceManager=P;exports.blockLevelRoles=qa;exports.chineseVariantMap=Pe;exports.chunkPlainText=xs;exports.chunkSsmlText=Es;exports.contextualizationShapesAtVerbosity=ka;exports.contextualizedAtVerbosity=Ca;exports.createLocator=ya;exports.decodeCssSelectorFragment=Na;exports.decodeDomRangeFragment=Fa;exports.decodeTextref=tr;exports.decorationsEqual=ha;exports.defaultContextualizations=kr;exports.encodeCssSelectorFragment=Ra;exports.encodeDomRangeFragment=Da;exports.extractUtterances=uf;exports.isRecoverableFailure=Ts;exports.makeGnd=rp;exports.mapServerVoice=dr;exports.mimeTypeForFormat=Cs;exports.parseMarkup=po;exports.resolveDecorationForWire=jn;exports.selectBitrate=Os;exports.selectFormat=ks;exports.setupDecorations=ed;exports.shapeableRoles=rd;exports.skippableRoles=jd;exports.skippedAtVerbosity=Ea;exports.supportsDecorationStyle=ua;exports.toSpeechServerError=Fe;
|
|
50
|
+
`)}positionElement(e,n,r,i,s,o,a=0){const c=e.decoration?.style?.width,l=s;switch(c){case"viewport":{const u=Math.floor(n.inlineStart(l)/n.viewportInlineSize)*n.viewportInlineSize;n.applyPosition(i,u+n.inlineScrollOffset+a,n.blockStart(l)+n.blockScrollOffset,n.viewportInlineSize-2*a,n.blockSize(l),r);break}case"page":{const u=Math.floor(n.inlineStart(l)/n.pageInlineSize)*n.pageInlineSize;n.applyPosition(i,u+n.inlineScrollOffset+a,n.blockStart(l)+n.blockScrollOffset,n.pageInlineSize-2*a,n.blockSize(l),r);break}case"bounds":{n.applyPosition(i,n.inlineStart(o)+n.inlineScrollOffset,n.blockStart(l)+n.blockScrollOffset,n.inlineSize(o),n.blockSize(l),r);break}default:n.applyPosition(i,n.inlineStart(l)+n.inlineScrollOffset,n.blockStart(l)+n.blockScrollOffset,n.inlineSize(l),n.blockSize(l),r)}}computeOverlayRects(e,n,r,i){if(e.decoration?.style?.layout==="bounds")return[i?{left:r.left-i,right:r.right+i,top:r.top-i,bottom:r.bottom+i,width:r.width+i*2,height:r.height+i*2}:r];const s=e.decoration.style.type,o=s===T.Underline||s===T.Strikethrough,a=s===T.Strikethrough,c=o?Uh(e.range,["rt","rp"]):e.range;let l=Je(c,!0,n.isVertical,o?0:i);return l=l.sort((u,h)=>n.isVertical?(n.isVertLR?1:-1)*(u.left-h.left):u.top-h.top),l.map(u=>{let h=u;if(a){const d=n.blockSize(u)*.1,g=n.blockStart(u)+n.blockSize(u)/2-d/2;h=n.isVertical?{left:g,right:g+d,top:u.top,bottom:u.bottom,width:d,height:u.height}:{top:g,bottom:g+d,left:u.left,right:u.right,height:d,width:u.width}}return i&&o&&(h=n.isVertical?{...h,top:h.top-i,bottom:h.bottom+i,height:h.height+i*2}:{...h,left:h.left-i,right:h.right+i,width:h.width+i*2}),h})}repositionItem(e,n){if(!e.container)return!0;const r=e.decoration.style;if(r.type!==T.Template){const u=r.type??T.Highlight;if(u===T.TextColor||u===T.Mask)return!0}const i=1/this.effectiveZoom(),s=r.expand??0,o=e.range.getBoundingClientRect(),a=(()=>{if(r.type!==T.Outline)return 0;const u=r.width;return u==="page"||u==="viewport"?3:0})(),c=this.computeOverlayRects(e,n,o,s),l=Array.from(e.container.children);return l.length!==c.length?!1:(l.forEach((u,h)=>this.positionElement(e,n,i,u,c[h],o,a)),!0)}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=Ee(this.wnd),i=1/this.effectiveZoom(),s=e.decoration.style.expand??0,o=e.range.getBoundingClientRect(),a=e.decoration.style,c=(()=>{if(a.type!==T.Outline)return 0;const h=a.width;return h==="page"||h==="viewport"?3:0})();let l;if(a.type===T.Template){a.stylesheet&&this.injectCustomStylesheet(a.stylesheet);const h=Kh(this.wnd,a.element);if(!h){e.container=n,e.clickableElements=[];return}h.style.setProperty("pointer-events","none"),l=h}else{const h=a,d=h.type??T.Highlight,g=h.tint??vn(d);if(d===T.TextColor){e.container=n,e.clickableElements=[];return}if(d===T.Mask){e.container=n,e.clickableElements=[],this.updateSharedMask();return}const p=this.getCurrentDarkMode(),m=this.getBackgroundColor(),b=h.enforceContrast!==!1,w=(()=>{switch(d){case T.Underline:{const S=b?ke(g,m):g,x=h.layout==="bounds",[R,I]=r.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[x?`${I}: 0.1em solid ${S} !important`:null,`${R}: 0.1em solid ${S} !important`,"background-color: transparent !important","box-sizing: border-box !important"].filter(Boolean).join("; ")}case T.Strikethrough:{const S=b?ke(g,m):g;return h.layout==="bounds"?[`background: repeating-linear-gradient(-45deg, transparent, transparent 19px, ${S} 19px, ${S} 20px) !important`,"background-color: transparent !important","box-sizing: border-box !important"].join("; "):[`background-color: ${S} !important`,"box-sizing: border-box !important"].join("; ")}case T.Outline:return[`outline: 2px solid ${b?ke(g,m):g} !important`,"outline-offset: 1px !important","background-color: transparent !important","box-sizing: border-box !important"].join("; ");case T.HighlightUnderline:{const S=b?ke(g,m):g,{r:x,g:R,b:I}=be(S),L=`rgba(${x}, ${R}, ${I}, 0.3)`,X=h.layout==="bounds",[M,y]=r.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[`background-color: ${L} !important`,X?`${y}: 0.1em solid ${S} !important`:null,`${M}: 0.1em solid ${S} !important`,"box-sizing: border-box !important"].filter(Boolean).join("; ")}case T.Highlight:default:return[`background-color: ${b?ke(g,m):g} !important`,`mix-blend-mode: ${p?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important","transform: translateZ(0) !important"].join("; ")}})(),O=this.wnd.document.createElement("template");O.innerHTML=`<div data-readium="true" class="readium-${d}" style="${w}"></div>`.trim(),l=O.content.firstElementChild}const u=this.computeOverlayRects(e,r,o,s);for(const h of u){const d=l.cloneNode(!0);d.style.setProperty("pointer-events","none"),this.positionElement(e,r,i,d,h,o,c),n.append(d)}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 si(this.wnd,"--USER__appearance")==="readium-night-on"||Is(this.getBackgroundColor())}getBackgroundColor(){return si(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color")}updateSharedMask(){const e=this.items.filter(d=>d.decoration.style?.type===T.Mask);if(e.length===0){this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowHost&&!this.container&&(this.shadowHost.remove(),this.shadowRoot=void 0,this.shadowHost=void 0);return}const n=Ee(this.wnd),r=1/this.effectiveZoom(),i=this.wnd.document.documentElement,s=i.scrollWidth,o=i.scrollHeight,a=[];for(const d of e){const g=d.decoration.style,p=g.layout??"boxes",m=g.width??"wrap",b=g.expand??0,w=d.range.getBoundingClientRect(),O=p==="bounds"?[b?{left:w.left-b,top:w.top-b,right:w.right+b,bottom:w.bottom+b,width:w.width+b*2,height:w.height+b*2}:w]:Je(d.range,!1,!1,b);for(const S of O){let x;switch(m){case"viewport":{const R=Math.floor(n.inlineStart(S)/n.viewportInlineSize)*n.viewportInlineSize;x=n.toRect(R,n.blockStart(S),n.viewportInlineSize,n.blockSize(S));break}case"page":{const R=Math.floor(n.inlineStart(S)/n.pageInlineSize)*n.pageInlineSize;x=n.toRect(R,n.blockStart(S),n.pageInlineSize,n.blockSize(S));break}case"bounds":{x=n.toRect(n.inlineStart(w),n.blockStart(S),n.inlineSize(w),n.blockSize(S));break}default:x=n.toRect(n.inlineStart(S),n.blockStart(S),n.inlineSize(S),n.blockSize(S))}a.push(x)}}const c=[`M0 0 H${s} V${o} H0 Z`,...a.map(d=>{const g=(d.left+n.xDocOffset)*r,p=(d.top+n.yDocOffset)*r,m=(d.right+n.xDocOffset)*r,b=(d.bottom+n.yDocOffset)*r;return`M${g} ${p} H${m} V${b} H${g} 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 d=this.wnd.document.createElementNS(l,"defs"),g=this.wnd.document.createElementNS(l,"clipPath"),p=`${this.id}-mask-clip`;g.setAttribute("id",p),g.setAttribute("clipPathUnits","userSpaceOnUse");const m=this.wnd.document.createElementNS(l,"path");m.setAttribute("clip-rule","evenodd"),g.appendChild(m),d.appendChild(g),this.maskSvg.appendChild(d);const b=this.wnd.document.createElementNS(l,"rect");b.setAttribute("id",`${this.id}-mask-rect`),b.setAttribute("clip-path",`url(#${p})`),b.style.pointerEvents="none",this.maskSvg.appendChild(b),this.shadowRoot.appendChild(this.maskSvg)}this.maskSvg.style.width=`${s}px`,this.maskSvg.style.height=`${o}px`;const u=this.maskSvg.querySelector("path");u&&u.setAttribute("d",c);const h=this.maskSvg.querySelector("rect");if(h){const d=e[0].decoration.style.tint,g=d??this.getBackgroundColor()??vn(T.Mask),p=d?"1":"0.5";h.setAttribute("x","0"),h.setAttribute("y","0"),h.setAttribute("width",String(s)),h.setAttribute("height",String(o)),h.setAttribute("fill",g),h.setAttribute("fill-opacity",p)}}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 oa=class Re extends Hu{constructor(){super(...arguments),this.observedResizeTargets=new Map,this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this),this.scrollScheduled=!1,this.handleScroller=this.handleScroll.bind(this)}cleanup(){this.groups.forEach(e=>e.destroy()),this.groups.clear(),this.observedResizeTargets.clear()}updateHighlightStyles(){this.groups.forEach(e=>{e.requestLayout()})}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(e=>e.requestLayout())},50)}handleScroll(){this.scrollScheduled||(this.scrollScheduled=!0,this.wnd.requestAnimationFrame(()=>{this.scrollScheduled=!1,this.groups.forEach(e=>{e.hasOverlayItems&&e.repositionOverlays()})}))}mount(e,n){return this.wnd=e,n.register("decorate",Re.moduleName,(r,i)=>{const s=r;(s.action==="add"||s.action==="update")&&s.decoration.locator&&(s.decoration.locator=Sr.deserialize(s.decoration.locator)),this.groups.has(s.group)||this.groups.set(s.group,new Yh(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_resize",Re.moduleName,(r,i)=>{const s=r;s.action==="watch"?this.addDecorationResizeTarget(s.selector):this.removeDecorationResizeTarget(s.selector),i(!0)}),n.register("decoration_activatable",Re.moduleName,(r,i)=>{const s=r,o=this.groups.get(s.group);o&&(o.activatable=s.activatable),i(!0)}),n.register("decoration_hoverable",Re.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),e.addEventListener("scroll",this.handleScroller,{passive:!0,capture:!0}),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),e.removeEventListener("scroll",this.handleScroller,{capture:!0}),n.unregisterAll(Re.moduleName),this.resizeObserver.disconnect(),this.styleObserver.disconnect(),this.cleanup(),n.log("Decorator Unmounted"),!0}addDecorationResizeTarget(e){const n=this.observedResizeTargets.get(e);n&&this.resizeObserver.unobserve(n);const r=this.wnd.document.querySelector(e);r?(this.resizeObserver.observe(r),this.observedResizeTargets.set(e,r)):this.observedResizeTargets.delete(e)}removeDecorationResizeTarget(e){const n=this.observedResizeTargets.get(e);n&&(this.resizeObserver.unobserve(n),this.observedResizeTargets.delete(e))}};oa.moduleName="decorator";let la=oa;const ca=new Set(Object.values(T));function ua(t,e){return t===T.TextColor?typeof window<"u"&&"Highlight"in window:ca.has(t)?!0:!!e?.[t]}function jn(t,e){const{style:n}=t;if(n.type===T.Template){const r=n;return{...t,style:{...r,element:ki(r,t)}}}if(n.type&&e?.[n.type]){const r=e[n.type];return{...t,style:{type:T.Template,layout:r.layout,width:r.width,stylesheet:r.stylesheet,element:ki(r,t)}}}return t}function ki(t,e){return typeof t.element=="function"?t.element(e):t.element}function Qh(t,e){if(t.type!==e.type)return!1;if(t.type===T.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 ha(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)&&Qh(t.style,e.style)&&JSON.stringify(t.extras??null)===JSON.stringify(e.extras??null)}class da{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 fa{constructor(){this.frame=new ga(this),this.host=new pa(this)}}class ga{constructor(e){this.channel=e,this.registrar=new Map,this.outbox=new da,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 pa{constructor(e){this.channel=e,this.listeners=new Map,this.outbox=new da,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 ma{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,n.resizeWatchSelectors?.forEach(r=>this.addDecorationResizeTarget(r)),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}))})}addDecorationResizeTarget(e){this.host.send("decoration_resize",{action:"watch",selector:e})}removeDecorationResizeTarget(e){this.host.send("decoration_resize",{action:"unwatch",selector:e})}supportsDecorationStyle(e){return ua(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 u=s.get(c);u?ha(l,u)||this.host.send("decorate",{group:n,action:"update",decoration:jn(u,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:jn(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 Zh(t){return new Ds({start:new It(t.start),end:t.end?new It(t.end):void 0})}function ya(t,e=window){const{text:n,cssSelector:r,domRange:i,fragment:s}=t,o=n?new br(n):void 0,a=r||i?new Map:void 0;a&&(r&&a.set("cssSelector",r),i&&a.set("domRange",Zh(i).serialize()));const l=a!==void 0||s!==void 0?new he({fragments:s?[s]:void 0,otherLocations:a}):void 0;return new Sr({href:e.location.href,type:"text/html",text:o,locations:l})}class ba extends ma{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:ya(s,this.wnd)})),n)}destroy(){super.destroy(),this.decorator.unmount(this.wnd,this.channel.frame),this.channel.frame.destroy()}}function ed(t=window,e={}){const n=new fa,r=new la;return r.mount(t,n.frame),new ba(n,t,r,e)}class td{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 Lt={range:[0,5e3],step:100},$t={range:[.1,10],step:.1},_t={range:[0,2],step:.1},Bt={range:[0,1],step:.05},vr=["none","few","some","most","custom"],wr=["none","block-level","always"],xr=["plain","ssml"],Er=["none","utterance","block"],Oi=["format","inlineContextualization","verbosity","skip","contextualize","language"];function Cr(t){return t==null||typeof t=="boolean"?t:void 0}function ie(t,e){return t==null||e.includes(t)?t:void 0}function se(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 ot(t){return t==null||Array.isArray(t)&&t.every(e=>typeof e=="string")?t:void 0}class Sa{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=ie(e.format,xr)??"plain",this.inlineContextualization=Cr(e.inlineContextualization)??!1,this.verbosity=ie(e.verbosity,vr)??"few",this.skip=ot(e.skip)??[],this.contextualize=ot(e.contextualize)??[],this.language=ie(e.language,wr)??"block-level",this.pauseDuration=se(e.pauseDuration,Lt.range)??300,this.autoPause=ie(e.autoPause,Er)??"none",this.rate=se(e.rate,$t.range)??1,this.pitch=se(e.pitch,_t.range)??1,this.volume=se(e.volume,Bt.range)??1}}class Ue{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=ie(e.format,xr),this.inlineContextualization=Cr(e.inlineContextualization),this.verbosity=ie(e.verbosity,vr),this.skip=ot(e.skip),this.contextualize=ot(e.contextualize),this.language=ie(e.language,wr),this.pauseDuration=se(e.pauseDuration,Lt.range),this.autoPause=ie(e.autoPause,Er),this.rate=se(e.rate,$t.range),this.pitch=se(e.pitch,_t.range),this.volume=se(e.volume,Bt.range)}merging(e){const n={...this};for(const r of Object.keys(e))e[r]!==void 0&&(n[r]=e[r]);return new Ue(n)}}class dt{_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 tt extends dt{_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&&ie(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 va extends dt{set value(e){if(e!=null&&Cr(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 Hn extends dt{set value(e){if(e!=null&&ot(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 nt extends dt{_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&&se(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 Wn{preferences;settings;constructor(e,n){this.preferences=new Ue({...e}),this.settings=n}clear(){this.preferences=new Ue({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 tt({initialValue:this.preferences.format,effectiveValue:this.settings.format,isEffective:this.preferences.format!=null,onChange:e=>this.updatePreference("format",e??null),supportedValues:xr})}get inlineContextualization(){return new va({initialValue:this.preferences.inlineContextualization,effectiveValue:this.settings.inlineContextualization,isEffective:this.preferences.inlineContextualization!=null,onChange:e=>this.updatePreference("inlineContextualization",e??null)})}get verbosity(){return new tt({initialValue:this.preferences.verbosity,effectiveValue:this.settings.verbosity,isEffective:this.preferences.verbosity!=null,onChange:e=>this.updatePreference("verbosity",e??null),supportedValues:vr})}get skip(){return new Hn({initialValue:this.preferences.skip,effectiveValue:this.settings.skip,isEffective:this.preferences.skip!=null,onChange:e=>this.updatePreference("skip",e??null)})}get contextualize(){return new Hn({initialValue:this.preferences.contextualize,effectiveValue:this.settings.contextualize,isEffective:this.preferences.contextualize!=null,onChange:e=>this.updatePreference("contextualize",e??null)})}get language(){return new tt({initialValue:this.preferences.language,effectiveValue:this.settings.language,isEffective:this.preferences.language!=null,onChange:e=>this.updatePreference("language",e??null),supportedValues:wr})}get pauseDuration(){return new nt({initialValue:this.preferences.pauseDuration,effectiveValue:this.settings.pauseDuration,isEffective:this.preferences.pauseDuration!=null,onChange:e=>this.updatePreference("pauseDuration",e??null),supportedRange:Lt.range,step:Lt.step})}get autoPause(){return new tt({initialValue:this.preferences.autoPause,effectiveValue:this.settings.autoPause,isEffective:this.preferences.autoPause!=null,onChange:e=>this.updatePreference("autoPause",e??null),supportedValues:Er})}get rate(){return new nt({initialValue:this.preferences.rate,effectiveValue:this.settings.rate,isEffective:this.preferences.rate!=null,onChange:e=>this.updatePreference("rate",e??null),supportedRange:$t.range,step:$t.step})}get pitch(){return new nt({initialValue:this.preferences.pitch,effectiveValue:this.settings.pitch,isEffective:this.preferences.pitch!=null,onChange:e=>this.updatePreference("pitch",e??null),supportedRange:_t.range,step:_t.step})}get volume(){return new nt({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!=null,onChange:e=>this.updatePreference("volume",e??null),supportedRange:Bt.range,step:Bt.step})}}const wa=["audio","figure","image","math","table","video"],xa=[...wa,"blockquote","chapter","cover","details","notice","part","preformatted","qna","row","rowheader","subtitle","tip"],nd=[...xa,"abstract","acknowledgments","afterword","appendix","aside","backlink","bibliography","biblioref","colophon","complementary","conclusion","credit","credits","dedication","definition","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","glossref","heading1","heading2","heading3","heading4","heading5","heading6","index","introduction","list","listItem","noteref","pagebreak","pagelist","preface","prologue","pullquote","separator","summary","term"],Ea={none:new Set(["aside","audio","bibliography","biblioref","cell","columnheader","details","endnotes","figure","footnote","glossary","image","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","table","toc","video"]),few:new Set(["aside","bibliography","biblioref","cell","columnheader","details","endnotes","footnote","glossary","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","toc"]),some:new Set(["aside","bibliography","biblioref","endnotes","footnote","glossary","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","toc"]),most:new Set(["landmarks","loa","loi","lot","lov","toc"])},Ca={none:new Set,few:new Set(wa),some:new Set(xa),most:new Set(nd)},Gn={table:{few:"inline",some:"block",most:"block"}};function xt(t){const e={};for(const n of Object.keys(Gn))e[n]=Gn[n]?.[t]??"inline";return e}const ka={none:xt("none"),few:xt("few"),some:xt("some"),most:xt("most")},rd=Object.keys(Gn);function id(t,e){const n=t==="custom"?{}:ka[t];if(!e)return n;const r={...n};for(const i of Object.keys(e)){const s=e[i]?.[t];s&&(r[i]=s)}return r}class Kn{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=[...Ea[this.verbosity]],this.contextualize=[...Ca[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}}const A=t=>typeof t=="string",Xe=()=>{let t,e;const n=new Promise((r,i)=>{t=r,e=i});return n.resolve=t,n.reject=e,n},Ai=t=>t==null?"":String(t),sd=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},ad=/###/g,Ti=t=>t&&t.includes("###")?t.replace(ad,"."):t,Ri=t=>!t||A(t),rt=(t,e,n)=>{const r=A(e)?e.split("."):e;let i=0;for(;i<r.length-1;){if(Ri(t))return{};const s=Ti(r[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return Ri(t)?{}:{obj:t,k:Ti(r[i])}},Ni=(t,e,n)=>{const{obj:r,k:i}=rt(t,e,Object);if(r!==void 0||e.length===1){r[i]=n;return}let s=e[e.length-1],o=e.slice(0,e.length-1),a=rt(t,o,Object);for(;a.obj===void 0&&o.length;)s=`${o[o.length-1]}.${s}`,o=o.slice(0,o.length-1),a=rt(t,o,Object),a?.obj&&typeof a.obj[`${a.k}.${s}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${s}`]=n},od=(t,e,n,r)=>{const{obj:i,k:s}=rt(t,e,Object);i[s]=i[s]||[],i[s].push(n)},qt=(t,e)=>{const{obj:n,k:r}=rt(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},ld=(t,e,n)=>{const r=qt(t,n);return r!==void 0?r:qt(e,n)},Oa=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,r)?A(t[r])||t[r]instanceof String||A(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):Oa(t[r],e[r],n):t[r]=e[r]);return t},ee=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),cd={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},ud=t=>A(t)?t.replace(/[&<>"'\/]/g,e=>cd[e]):t;class hd{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const dd=[" ",",","?","!",";"],fd=new hd(20),gd=(t,e,n)=>{e=e||"",n=n||"";const r=dd.filter(o=>!e.includes(o)&&!n.includes(o));if(r.length===0)return!0;const i=fd.getRegExp(`(${r.map(o=>o==="?"?"\\?":o).join("|")})`);let s=!i.test(t);if(!s){const o=t.indexOf(n);o>0&&!i.test(t.substring(0,o))&&(s=!0)}return s},Jn=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(n);let i=t;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let o,a="";for(let c=s;c<r.length;++c)if(c!==s&&(a+=n),a+=r[c],o=i[a],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<r.length-1)continue;s+=c-s+1;break}i=o}return i},lt=t=>t?.replace(/_/g,"-"),pd={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Ut{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||pd,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,r,i){return i&&!this.debug?null:(e=e.map(s=>A(s)?s.replace(/[\r\n\x00-\x1F\x7F]/g," "):s),A(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Ut(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ut(this.logger,e)}}var Q=new Ut;class en{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}once(e,n){const r=(...i)=>{n(...i),this.off(e,r)};return this.on(e,r),this}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i(e,...n)})}}class Di extends en{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,n,r,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.includes(".")?a=e.split("."):(a=[e,n],r&&(Array.isArray(r)?a.push(...r):A(r)&&s?a.push(...r.split(s)):a.push(r)));const c=qt(this.data,a);return!c&&!n&&!r&&e.includes(".")&&(e=a[0],n=a[1],r=a.slice(2).join(".")),c||!o||!A(r)?c:Jn(this.data?.[e]?.[n],r,s)}addResource(e,n,r,i,s={silent:!1}){const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let a=[e,n];r&&(a=a.concat(o?r.split(o):r)),e.includes(".")&&(a=e.split("."),i=n,n=a[1]),this.addNamespaces(n),Ni(this.data,a,i),s.silent||this.emit("added",e,n,r,i)}addResources(e,n,r,i={silent:!1}){for(const s in r)(A(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});i.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,i,s,o={silent:!1,skipCopy:!1}){let a=[e,n];e.includes(".")&&(a=e.split("."),i=r,r=n,n=a[1]),this.addNamespaces(n);let c=qt(this.data,a)||{};o.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?Oa(c,r,s):c={...c,...r},Ni(this.data,a,c),o.silent||this.emit("added",e,n,r)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var Aa={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,i){return t.forEach(s=>{e=this.processors[s]?.process(e,n,r,i)??e}),e}};const Ta=Symbol("i18next/PATH_KEY");function md(){const t=[],e=Object.create(null);let n;return e.get=(r,i)=>(n?.revoke?.(),i===Ta?t:(t.push(i),n=Proxy.revocable(r,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Ie(t,e){const{[Ta]:n}=t(md()),r=e?.keySeparator??".",i=e?.nsSeparator??":",s=e?.enableSelector==="strict";if(n.length>1&&i){const o=e?.ns,a=s?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(a&&(s?a:a.length>1?a.slice(1):[]).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}const wn=t=>!A(t)&&typeof t!="boolean"&&typeof t!="number";class zt extends en{constructor(e,n={}){super(),sd(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Q.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const i=this.resolve(e,r);if(i?.res===void 0)return!1;const s=wn(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(e,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const o=r&&e.includes(r),a=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!gd(e,r,i);if(o&&!a){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:A(s)?[s]:s};const l=e.split(r);(r!==i||r===i&&this.options.ns.includes(l[0]))&&(s=l.shift()),e=l.join(i)}return{key:e,namespaces:A(s)?[s]:s}}translate(e,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),e==null)return"";typeof e=="function"&&(e=Ie(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]),e=e.map(k=>typeof k=="function"?Ie(k,{...this.options,...i}):String(k));const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:a,namespaces:c}=this.extractFromKey(e[e.length-1],i),l=c[c.length-1];let u=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const h=i.lng||this.language,d=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(h?.toLowerCase()==="cimode")return d?s?{res:`${l}${u}${a}`,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${u}${a}`:s?{res:a,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:a;const g=this.resolve(e,i);let p=g?.res;const m=g?.usedKey||a,b=g?.exactUsedKey||a,w=["[object Number]","[object Function]","[object RegExp]"],O=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,x=i.count!==void 0&&!A(i.count),R=zt.hasDefaultValue(i),I=x?this.pluralResolver.getSuffix(h,i.count,i):"",L=i.ordinal&&x?this.pluralResolver.getSuffix(h,i.count,{ordinal:!1}):"",X=x&&!i.ordinal&&i.count===0,M=X&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${I}`]||i[`defaultValue${L}`]||i.defaultValue;let y=p;S&&!p&&R&&(y=M);const pt=wn(y),ue=Object.prototype.toString.apply(y);if(S&&y&&pt&&!w.includes(ue)&&!(A(O)&&Array.isArray(y))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const k=this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,y,{...i,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(g.res=k,g.usedParams=this.getUsedParamsDetails(i),g):k}if(o){const k=Array.isArray(y),_=k?[]:{},G=k?b:m;for(const z in y)if(Object.prototype.hasOwnProperty.call(y,z)){const H=`${G}${o}${z}`;R&&!p?_[z]=this.translate(H,{...i,defaultValue:wn(M)?M[z]:void 0,joinArrays:!1,ns:c}):_[z]=this.translate(H,{...i,joinArrays:!1,ns:c}),_[z]===H&&(_[z]=y[z])}p=_}}else if(S&&A(O)&&Array.isArray(p))p=p.join(O),p&&(p=this.extendTranslation(p,e,i,r));else{let k=!1,_=!1;!this.isValidLookup(p)&&R&&(k=!0,p=M),this.isValidLookup(p)||(_=!0,p=a);const z=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&_?void 0:p,H=R&&M!==p&&this.options.updateMissing;if(_||k||H){if(this.logger.log(H?"updateKey":"missingKey",h,l,x&&!H?`${a}${this.pluralResolver.getSuffix(h,i.count,i)}`:a,H?M:p),o){const f=this.resolve(a,{...i,keySeparator:!1});f&&f.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let U=[];const ve=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ve&&ve[0])for(let f=0;f<ve.length;f++)U.push(ve[f]);else this.options.saveMissingTo==="all"?U=this.languageUtils.toResolveHierarchy(i.lng||this.language):U.push(i.lng||this.language);const K=(f,v,C)=>{const E=R&&C!==p?C:z;this.options.missingKeyHandler?this.options.missingKeyHandler(f,l,v,E,H,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(f,l,v,E,H,i),this.emit("missingKey",f,l,v,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&x?U.forEach(f=>{const v=this.pluralResolver.getSuffixes(f,i);X&&i[`defaultValue${this.options.pluralSeparator}zero`]&&!v.includes(`${this.options.pluralSeparator}zero`)&&v.push(`${this.options.pluralSeparator}zero`),v.forEach(C=>{K([f],a+C,i[`defaultValue${C}`]||M)})}):K(U,a,M))}p=this.extendTranslation(p,e,i,g,r),_&&p===a&&this.options.appendNamespaceToMissingKey&&(p=`${l}${u}${a}`),(_||k)&&this.options.parseMissingKeyHandler&&(p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${u}${a}`:a,k?p:void 0,i))}return s?(g.res=p,g.usedParams=this.getUsedParamsDetails(i),g):p}extendTranslation(e,n,r,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const c=A(e)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let l;if(c){const h=e.match(this.interpolator.nestingRegexp);l=h&&h.length}let u=r.replace&&!A(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,r.lng||this.language||i.usedLng,r),c){const h=e.match(this.interpolator.nestingRegexp),d=h&&h.length;l<d&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...h)=>s?.[0]===h[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${h[0]} in key: ${n[0]}`),null):this.translate(...h,n),r)),r.interpolation&&this.interpolator.reset()}const o=r.postProcess||this.options.postProcess,a=A(o)?[o]:o;return e!=null&&a?.length&&r.applyPostProcessor!==!1&&(e=Aa.handle(a,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,i,s,o,a;return A(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?Ie(c,{...this.options,...n}):c)),e.forEach(c=>{if(this.isValidLookup(r))return;const l=this.extractFromKey(c,n),u=l.key;i=u;let h=l.namespaces;this.options.fallbackNS&&(h=h.concat(this.options.fallbackNS));const d=n.count!==void 0&&!A(n.count),g=d&&!n.ordinal&&n.count===0,p=n.context!==void 0&&(A(n.context)||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);h.forEach(b=>{this.isValidLookup(r)||(a=b,!this.checkedLoadedFor[`${m[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(this.checkedLoadedFor[`${m[0]}-${b}`]=!0,this.logger.warn(`key "${i}" for languages "${m.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(w=>{if(this.isValidLookup(r))return;o=w;const O=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(O,u,w,b,n);else{let x;d&&(x=this.pluralResolver.getSuffix(w,n.count,n));const R=`${this.options.pluralSeparator}zero`,I=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(n.ordinal&&x.startsWith(I)&&O.push(u+x.replace(I,this.options.pluralSeparator)),O.push(u+x),g&&O.push(u+R)),p){const L=`${u}${this.options.contextSeparator||"_"}${n.context}`;O.push(L),d&&(n.ordinal&&x.startsWith(I)&&O.push(L+x.replace(I,this.options.pluralSeparator)),O.push(L+x),g&&O.push(L+R))}}let S;for(;S=O.pop();)this.isValidLookup(r)||(s=S,r=this.getResource(w,b,S,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:o,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,r,i):this.resourceStore.getResource(e,n,r,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!A(e.replace);let i=r?e.replace:e;if(r&&typeof e.count<"u"&&(i={...i,count:e.count}),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(e){const n="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&r.startsWith(n)&&e[r]!==void 0)return!0;return!1}}class Fi{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Q.create("languageUtils"),this.resolveHierarchyCache={}}clearCache(){this.resolveHierarchyCache={}}getScriptPartFromCode(e){if(e=lt(e),!e||!e.includes("-"))return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=lt(e),!e||!e.includes("-"))return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(A(e)&&e.includes("-")){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>o===s?!0:!o.includes("-")&&!s.includes("-")?!1:!!(o.includes("-")&&!s.includes("-")&&o.slice(0,o.indexOf("-"))===s||o.startsWith(s)&&s.length>1))}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),A(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let r=e[n];return r||(r=e[this.getScriptPartFromCode(n)]),r||(r=e[this.formatLanguageCode(n)]),r||(r=e[this.getLanguagePartFromCode(n)]),r||(r=e.default),r||[]}toResolveHierarchy(e,n){const r=this.options.fallbackLng,i=Array.isArray(r)?r.join("|"):r;i!==this._cachedFallbackLng&&(this.resolveHierarchyCache={},this._cachedFallbackLng=i);const s=n===void 0||n===!1||A(n),o=n===void 0&&typeof this.options.fallbackLng=="function",a=A(e)&&s&&!o;let c=null;if(a){let d;n===void 0?d="undefined":n===!1?d="boolean:false":d=`string:${n}`,c=`${e.length}:${e}|${d}`}if(c!==null){const d=this.resolveHierarchyCache[c];if(d!==void 0)return d.slice()}const l=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),u=[],h=d=>{d&&(this.isSupportedCode(d)?u.push(d):this.logger.warn(`rejecting language code not found in supportedLngs: ${d}`))};return A(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&h(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&h(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&h(this.getLanguagePartFromCode(e))):A(e)&&h(this.formatLanguageCode(e)),l.forEach(d=>{u.includes(d)||h(this.formatLanguageCode(d))}),c!==null?(this.resolveHierarchyCache[c]=u,u.slice()):u}}const Ii={zero:0,one:1,two:2,few:3,many:4,other:5},Pi={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class yd{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Q.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=lt(e==="dev"?"en":e),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(r,{type:i})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Pi;if(!e.match(/-|_/))return Pi;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,n)}return this.pluralRulesCache[s]=o,o}needsPlural(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,r={}){return this.getSuffixes(e,r).map(i=>`${n}${i}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>Ii[i]-Ii[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,r={}){const i=this.getRule(e,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const Li=(t,e,n,r=".",i=!0)=>{let s=ld(t,e,n);return!s&&i&&A(n)&&(s=Jn(t,n,r),s===void 0&&(s=Jn(e,n,r))),s},bd=t=>t.replace(/\$/g,"$$$$");class $i{constructor(e={}){this.logger=Q.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:o,suffix:a,suffixEscaped:c,formatSeparator:l,unescapeSuffix:u,unescapePrefix:h,nestingPrefix:d,nestingPrefixEscaped:g,nestingSuffix:p,nestingSuffixEscaped:m,nestingOptionsSeparator:b,maxReplaces:w,alwaysFormat:O}=e.interpolation;this.escape=n!==void 0?n:ud,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?ee(s):o||"{{",this.suffix=a?ee(a):c||"}}",this.formatSeparator=l||",",this.unescapePrefix=u?"":h?ee(h):"-",this.unescapeSuffix=this.unescapePrefix?"":u?ee(u):"",this.nestingPrefix=d?ee(d):g||ee("$t("),this.nestingSuffix=p?ee(p):m||ee(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=w||1e3,this.alwaysFormat=O!==void 0?O:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,r,i){let s,o,a;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=g=>{if(!g.includes(this.formatSeparator)){const w=Li(n,c,g,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(w,void 0,r,{...i,...n,interpolationkey:g}):w}const p=g.split(this.formatSeparator),m=p.shift().trim(),b=p.join(this.formatSeparator).trim();return this.format(Li(n,c,m,this.options.keySeparator,this.options.ignoreJSONStructure),b,r,{...i,...n,interpolationkey:m})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,h=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:g=>g},{regex:this.regexp,safeValue:g=>this.escapeValue?this.escape(g):g}].forEach(g=>{for(a=0;s=g.regex.exec(e);){const p=s[1].trim();if(o=l(p),o===void 0)if(typeof u=="function"){const b=u(e,s,i);o=A(b)?b:""}else if(i&&Object.prototype.hasOwnProperty.call(i,p))o="";else if(h){o=s[0];continue}else this.logger.warn(`missed to pass in variable ${p} for interpolating ${e}`),o="";else!A(o)&&!this.useRawValueToEscape&&(o=Ai(o));const m=g.safeValue(o);if(e=e.replace(s[0],bd(m)),h?(g.regex.lastIndex+=m.length,g.regex.lastIndex-=s[0].length):g.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,n,r={}){let i,s,o;const a=(c,l)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const h=c.split(new RegExp(`${ee(u)}[ ]*{`));let d=`{${h[1]}`;c=h[0],d=this.interpolate(d,o);const g=d.match(/'/g),p=d.match(/"/g);((g?.length??0)%2===0&&!p||(p?.length??0)%2!==0)&&(d=d.replace(/'/g,'"'));try{o=JSON.parse(d),l&&(o={...l,...o})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,m),`${c}${u}${d}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,c};for(;i=this.nestingRegexp.exec(e);){let c=[];o={...r},o=o.replace&&!A(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const l=/{.*}/s.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(l!==-1&&(c=i[1].slice(l).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),i[1]=i[1].slice(0,l)),s=n(a.call(this,i[1].trim(),o),o),s&&i[0]===e&&!A(s))return s;A(s)||(s=Ai(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),c.length&&(s=c.reduce((u,h)=>this.format(u,h,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const Sd=t=>{let e=t.toLowerCase().trim();const n={};if(t.includes("(")){const r=t.split("(");e=r[0].toLowerCase().trim();const i=r[1].slice(0,-1);e==="currency"&&!i.includes(":")?n.currency||(n.currency=i.trim()):e==="relativetime"&&!i.includes(":")?n.range||(n.range=i.trim()):i.split(";").forEach(o=>{if(o){const[a,...c]=o.split(":"),l=c.join(":").trim().replace(/^'+|'+$/g,""),u=a.trim();n[u]||(n[u]=l),l==="false"&&(n[u]=!1),l==="true"&&(n[u]=!0),isNaN(l)||(n[u]=parseInt(l,10))}})}return{formatName:e,formatOptions:n}},_i=t=>{const e={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const o=r+JSON.stringify(s);let a=e[o];return a||(a=t(lt(r),i),e[o]=a),a(n)}},vd=t=>(e,n,r)=>t(lt(n),r)(e);class wd{constructor(e={}){this.logger=Q.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?_i:vd;this.formats={number:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s});return a=>o.format(a)}),currency:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s,style:"currency"});return a=>o.format(a)}),datetime:r((i,s)=>{const o=new Intl.DateTimeFormat(i,{...s});return a=>o.format(a)}),relativetime:r((i,s)=>{const o=new Intl.RelativeTimeFormat(i,{...s});return a=>o.format(a,s.range||"day")}),list:r((i,s)=>{const o=new Intl.ListFormat(i,{...s});return a=>o.format(a)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=_i(n)}format(e,n,r,i={}){if(!n||e==null)return e;const s=n.split(this.formatSeparator),o=[];for(let c=0;c<s.length;c++){let l=s[c];for(;l.indexOf("(")>-1&&!l.includes(")")&&c+1<s.length;)l=`${l}${this.formatSeparator}${s[++c]}`;o.push(l)}return o.reduce((c,l)=>{const{formatName:u,formatOptions:h}=Sd(l);if(this.formats[u]){let d=c;try{const g=i?.formatParams?.[i.interpolationkey]||{},p=g.locale||g.lng||i.locale||i.lng||r;d=this.formats[u](c,p,{...h,...i,...g})}catch(g){this.logger.warn(g)}return d}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const xd=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Ed extends en{constructor(e,n,r,i={}){super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=Q.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(e,n,r,i){const s={},o={},a={},c={};return e.forEach(l=>{let u=!0;n.forEach(h=>{const d=`${l}|${h}`;!r.reload&&this.store.hasResourceBundle(l,h)?this.state[d]=2:this.state[d]<0||(this.state[d]===1?o[d]===void 0&&(o[d]=!0):(this.state[d]=1,u=!1,o[d]===void 0&&(o[d]=!0),s[d]===void 0&&(s[d]=!0),c[h]===void 0&&(c[h]=!0)))}),u||(a[l]=!0)}),(Object.keys(s).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(o),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(c)}}loaded(e,n,r){const i=e.split("|"),s=i[0],o=i[1];n&&this.emit("failedLoading",s,o,n),!n&&r&&this.store.addResourceBundle(s,o,r,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&r&&(this.state[e]=0);const a={};this.queue.forEach(c=>{od(c.loaded,[s],o),xd(c,e),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(l=>{a[l]||(a[l]={});const u=c.loaded[l];u.length&&u.forEach(h=>{a[l][h]===void 0&&(a[l][h]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(c=>!c.done)}read(e,n,r,i=0,s=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:i,wait:s,callback:o});return}this.readingCalls++;const a=(l,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const h=this.waitingReads.shift();this.read(h.lng,h.ns,h.fcName,h.tried,h.wait,h.callback)}if(l&&u&&i<this.maxRetries){setTimeout(()=>{this.read(e,n,r,i+1,s*2,o)},s);return}o(l,u)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const l=c(e,n);l&&typeof l.then=="function"?l.then(u=>a(null,u)).catch(a):a(null,l)}catch(l){a(l)}return}return c(e,n,a)}prepareLoading(e,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();A(e)&&(e=this.languageUtils.toResolveHierarchy(e)),A(n)&&(n=[n]);const s=this.queueLoad(e,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(o=>{this.loadOne(o)})}load(e,n,r){this.prepareLoading(e,n,{},r)}reload(e,n,r){this.prepareLoading(e,n,{reload:!0},r)}loadOne(e,n=""){const r=e.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(o,a)=>{o&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,o),!o&&a&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,a),this.loaded(e,o,a)})}saveMissing(e,n,r,i,s,o={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend?.create){const c={...o,isUpdate:s},l=this.backend.create.bind(this.backend);if(l.length<6)try{let u;l.length===5?u=l(e,n,r,i,c):u=l(e,n,r,i),u&&typeof u.then=="function"?u.then(h=>a(null,h)).catch(a):a(null,u)}catch(u){a(u)}else l(e,n,r,i,a,c)}!e||!e[0]||this.store.addResource(e[0],n,r,i)}}}const xn=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),A(t[1])&&(e.defaultValue=t[1]),A(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(r=>{e[r]=n[r]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Bi=t=>(A(t.ns)&&(t.ns=[t.ns]),A(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),A(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&!t.supportedLngs.includes("cimode")&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t),Et=()=>{},Cd=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class it extends en{constructor(e={},n){if(super(),this.options=Bi(e),this.services={},this.logger=Q,this.modules={external:[]},Cd(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(A(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const r=xn();this.options={...r,...this.options,...Bi(e)},this.options.interpolation={...r.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler);const i=l=>l?typeof l=="function"?new l:l:null;if(!this.options.isClone){this.modules.logger?Q.init(i(this.modules.logger),this.options):Q.init(null,this.options);let l;this.modules.formatter?l=this.modules.formatter:l=wd;const u=new Fi(this.options);this.store=new Di(this.options.resources,this.options);const h=this.services;h.logger=Q,h.resourceStore=this.store,h.languageUtils=u,h.pluralResolver=new yd(u,{prepend:this.options.pluralSeparator}),l&&(h.formatter=i(l),h.formatter.init&&h.formatter.init(h,this.options),this.options.interpolation.format=h.formatter.format.bind(h.formatter)),h.interpolator=new $i(this.options),h.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},h.backendConnector=new Ed(i(this.modules.backend),h.resourceStore,h,this.options),h.backendConnector.on("*",(d,...g)=>{this.emit(d,...g)}),this.modules.languageDetector&&(h.languageDetector=i(this.modules.languageDetector),h.languageDetector.init&&h.languageDetector.init(h,this.options.detection,this.options)),this.modules.i18nFormat&&(h.i18nFormat=i(this.modules.i18nFormat),h.i18nFormat.init&&h.i18nFormat.init(this)),this.translator=new zt(this.services,this.options),this.translator.on("*",(d,...g)=>{this.emit(d,...g)}),this.modules.external.forEach(d=>{d.init&&d.init(this)})}if(this.format=this.options.interpolation.format,n||(n=Et),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const l=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);l.length>0&&l[0]!=="dev"&&(this.options.lng=l[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(l=>{this[l]=(...u)=>this.store[l](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(l=>{this[l]=(...u)=>(this.store[l](...u),this)});const a=Xe(),c=()=>{const l=(u,h)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(h),n(u,h)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return l(null,this.t.bind(this));this.changeLanguage(this.options.lng,l)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),a}loadResources(e,n=Et){let r=n;const i=A(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],o=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(l=>{l!=="cimode"&&(s.includes(l)||s.push(l))})};i?o(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>o(c)),this.options.preload?.forEach?.(a=>o(a)),this.services.backendConnector.load(s,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(a)})}else r(null)}reloadResources(e,n,r){const i=Xe();return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),r||(r=Et),this.services.backendConnector.reload(e,n,s=>{i.resolve(),r(s)}),i}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&Aa.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!["cimode","dev"].includes(r)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const r=Xe();this.emit("languageChanging",e);const i=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},s=(a,c)=>{c?this.isLanguageChangingTo===e&&(i(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,r.resolve((...l)=>this.t(...l)),n&&n(a,(...l)=>this.t(...l))},o=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const c=A(a)?a:a&&a[0],l=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(A(a)?[a]:a);l&&(this.language||i(l),this.translator.language||this.translator.changeLanguage(l),this.services.languageDetector?.cacheUserLanguage?.(l)),this.loadResources(l,u=>{s(u,l)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),r}getFixedT(e,n,r,i){const s=i?.scopeNs,o=(a,c,...l)=>{let u;typeof c!="object"?u=this.options.overloadTranslationOptionHandler([a,c].concat(l)):u={...c},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs;const h=u.ns!==void 0&&u.ns!==null;u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||r||o.keyPrefix);const d={...this.options,...u};Array.isArray(s)&&!h&&(d.ns=s),typeof u.keyPrefix=="function"&&(u.keyPrefix=Ie(u.keyPrefix,d));const g=this.options.keySeparator||".";let p;return u.keyPrefix&&Array.isArray(a)?p=a.map(m=>(typeof m=="function"&&(m=Ie(m,d)),`${u.keyPrefix}${g}${m}`)):(typeof a=="function"&&(a=Ie(a,d)),p=u.keyPrefix?`${u.keyPrefix}${g}${a}`:a),this.t(p,u)};return A(e)?o.lng=e:o.lngs=e,o.ns=n,o.keyPrefix=r,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const o=(a,c)=>{const l=this.services.backendConnector.state[`${a}|${c}`];return l===-1||l===0||l===2};if(n.precheck){const a=n.precheck(this,o);if(a!==void 0)return a}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(r,e)&&(!i||o(s,e)))}loadNamespaces(e,n){const r=Xe();return this.options.ns?(A(e)&&(e=[e]),e.forEach(i=>{this.options.ns.includes(i)||this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(e,n){const r=Xe();A(e)&&(e=[e]);const i=this.options.preload||[],s=e.filter(o=>!i.includes(o)&&this.services.languageUtils.isSupportedCode(o));return s.length?(this.options.preload=i.concat(s),this.loadResources(o=>{r.resolve(),n&&n(o)}),r):(n&&n(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const i=new Intl.Locale(e);if(i&&i.getTextInfo){const s=i.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services?.languageUtils||new Fi(xn());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.includes(r.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const r=new it(e,n);return r.createInstance=it.createInstance,r}cloneInstance(e={},n=Et){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new it(i);if((e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["store","services","language"].forEach(a=>{s[a]=this[a]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const a=Object.keys(this.store.data).reduce((c,l)=>(c[l]={...this.store.data[l]},c[l]=Object.keys(c[l]).reduce((u,h)=>(u[h]={...c[l][h]},u),c[l]),c),{});s.store=new Di(a,i),s.services.resourceStore=s.store}if(e.interpolation){const c={...xn().interpolation,...this.options.interpolation,...e.interpolation},l={...i,interpolation:c};s.services.interpolator=new $i(l)}return s.translator=new zt(s.services,i),s.translator.on("*",(a,...c)=>{s.emit(a,...c)}),s.init(i,n),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const V=it.createInstance();V.createInstance;V.dir;V.init;V.loadResources;V.reloadResources;V.use;V.changeLanguage;V.getFixedT;V.t;V.exists;V.setDefaultNamespace;V.hasLoadedNamespace;V.loadNamespaces;V.loadLanguages;function ft(t){return t.plain===""&&t.ssml===""&&t.language===""}function kd(t){if(!t||ft(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 Od(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 Vt=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),En=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Ad=/[\u00A0\u2007\u202F]/;function Td(t){return Ad.test(t)}function ze(t,e){let n="",r=!1,i=!1;for(const s of t)if(Td(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 Xn="#css(",Yn=")";function Ra(t){return`${Xn}${encodeURIComponent(t)}${Yn}`}function Na(t){if(!(!t||!t.startsWith(Xn)||!t.endsWith(Yn)))return decodeURIComponent(t.slice(Xn.length,-Yn.length))}const Qn="#domrange(",Zn=")";function Da(t){return`${Qn}${encodeURIComponent(JSON.stringify(t))}${Zn}`}function Fa(t){if(!(!t||!t.startsWith(Qn)||!t.endsWith(Zn)))try{const e=JSON.parse(decodeURIComponent(t.slice(Qn.length,-Zn.length)));return!e?.start?.cssSelector||typeof e.start.textNodeIndex!="number"?void 0:e}catch{return}}const er=":~:text=";function Ct(t){return encodeURIComponent(t).replace(/-/g,"%2D")}function Ia(t){let e="";return t.prefix&&(e+=`${Ct(t.prefix)}-,`),e+=Ct(t.textStart),t.textEnd&&(e+=`,${Ct(t.textEnd)}`),t.suffix&&(e+=`,-${Ct(t.suffix)}`),`${er}${e}`}function Rd(t){if(!t)return;const e=t.indexOf(er);if(e===-1)return;const n=t.slice(e+er.length).split("&")[0];if(n)try{let r=n.split(",");const i={textStart:""};return r[0].endsWith("-")&&(i.prefix=decodeURIComponent(r[0].slice(0,-1)),r=r.slice(1)),r.length>0&&r[r.length-1].startsWith("-")&&(i.suffix=decodeURIComponent(r[r.length-1].slice(1)),r=r.slice(0,-1)),r.length===0||r[0]===""?void 0:(i.textStart=decodeURIComponent(r[0]),r.length>1&&(i.textEnd=decodeURIComponent(r[1])),i)}catch{return}}function tr(t){const e=t?.textref;if(!e)return;const n=e.indexOf(":~:"),r=n===-1?e:e.slice(0,n);let i,s;const o=Fa(r);if(o)s=o,i=o.start.cssSelector;else{const l=Na(r);l!==void 0?i=l:t?.id&&r===`#${CSS.escape(t.id)}`&&(i=r)}const a=Rd(e);if(i===void 0&&s===void 0&&a===void 0)return;const c={};return i!==void 0&&(c.cssSelector=i),s!==void 0&&(c.domRange=s),a?.textEnd!==void 0?c.fragment=Ia(a):a&&(c.text={highlight:a.textStart},a.prefix!==void 0&&(c.text.before=a.prefix),a.suffix!==void 0&&(c.text.after=a.suffix)),c}const Nd={contextualizations:{abstract:{block:{start:"Start of the abstract.",end:"End of the abstract."}},acknowledgments:{block:{start:"Start of the acknowledgments.",end:"End of the acknowledgments."}},afterword:{block:{start:"Start of the afterword.",end:"End of the afterword."}},appendix:{block:{start:"Start of the appendix.",end:"End of the appendix."}},aside:{block:{start:"Start of the aside.",end:"End of the aside."}},audio:{inline:{labelled:"Audio with a label: {{ description }}",unlabelled:"Audio with no label."}},bibliography:{block:{start:"Start of the bibliography.",end:"End of the bibliography."}},blockquote:{inline:"Blockquote."},cell:{inline:{withHeader:"{{ header }}: {{ value }}",withoutHeader:"{{ value }}"}},chapter:{block:{start:"Start of the chapter.",end:"End of the chapter."}},colophon:{inline:"Colophon."},complementary:{block:{start:"Start of the complementary content.",end:"End of the complementary content."}},conclusion:{block:{start:"Start of the conclusion.",end:"End of the conclusion."}},cover:{inline:{labelled:"Cover with a label: {{ description }}",unlabelled:"Cover with no label."}},credit:{inline:"Credit."},credits:{block:{start:"Start of the credits.",end:"End of the credits."}},dedication:{inline:"Dedication."},definition:{inline:"Definition."},details:{block:{start:"Start of the disclosure.",end:"End of the disclosure."}},endnotes:{block:{start:"Start of the endnotes.",end:"End of the endnotes."}},epigraph:{inline:"Epigraph."},epilogue:{block:{start:"Start of the epilogue.",end:"End of the epilogue."}},errata:{block:{start:"Start of the errata.",end:"End of the errata."}},example:{block:{start:"Start of the example.",end:"End of the example."}},figure:{inline:"Figure: {{ description }}"},footnote:{block:{start:"Start of the footnote.",end:"End of the footnote."}},foreword:{block:{start:"Start of the foreword.",end:"End of the foreword."}},glossary:{block:{start:"Start of the glossary.",end:"End of the glossary."}},heading1:{inline:"Heading level 1."},heading2:{inline:"Heading level 2."},heading3:{inline:"Heading level 3."},heading4:{inline:"Heading level 4."},heading5:{inline:"Heading level 5."},heading6:{inline:"Heading level 6."},image:{inline:{labelled:"Image with a label: {{ description }}",unlabelled:"Image with no label."}},index:{block:{start:"Start of the index.",end:"End of the index."}},introduction:{block:{start:"Start of the introduction.",end:"End of the introduction."}},list:{block:{start:"Start of the list.",end:"End of the list."}},listItem:{inline:"List item."},math:{inline:{labelled:"{{ description }}",unlabelled:"Math formula with no label."}},notice:{inline:"Notice."},pagebreak:{inline:"Pagebreak."},pagelist:{block:{start:"Start of the page list.",end:"End of the page list."}},part:{inline:"Part."},preface:{block:{start:"Start of the preface.",end:"End of the preface."}},prologue:{block:{start:"Start of the prologue.",end:"End of the prologue."}},pullquote:{inline:"Pullquote."},qna:{block:{start:"Start of the questions and answers.",end:"End of the questions and answers."}},row:{inline:"Row: {{ count }}"},rowheader:{inline:{withHeader:"{{ header }}: {{ value }}",withoutHeader:"{{ value }}"}},separator:{inline:"Separator."},subtitle:{inline:"Subtitle."},summary:{inline:"Summary."},table:{block:{end:"End of the table.",start:{labelled:"Table: {{ description }}. {{ lines }}. {{ columns }}.",unlabelled:"Table. {{ lines }}. {{ columns }}."}},inline:{labelled:"Table: {{ description }}. {{ lines }}. {{ columns }}.",unlabelled:"Table. {{ lines }}. {{ columns }}."},parts:{columns_one:"1 column",columns_other:"{{ count }} columns",lines_one:"1 line",lines_other:"{{ count }} lines"}},term:{inline:"Term."},tip:{inline:"Tip."},video:{inline:{labelled:"Video with a label: {{ description }}",unlabelled:"Video with no label."}}}},Dd={speech:Nd},kr=Dd.speech.contextualizations,qi={en:kr},Fd={};async function Id(t){const e=qi[t];if(e)return e;const n=Fd[t];if(!n)return kr;const r=(await n()).speech.contextualizations;return qi[t]=r,r}const Pd=/<lang xml:lang="[^"]*">([\s\S]*?)<\/lang>/g;function Pa(t){return t.replace(Pd,"$1")}const Ld=/\s*<readium:[a-zA-Z][\w-]*\s+id="[^"]*"\s*\/>\s*/g;function $d(t){return t.replace(Ld,(n,r,i)=>{const s=i.slice(r+n.length);return s.length===0||Qt(s)?"":" "}).replace(/ {2,}/g," ").trim()}function _d(t){return t.includes("<")}function Or(t){if(t===void 0)return;if(typeof t=="string")return{plain:t};const e={language:t.language};if(t.ssml){const n=$d(t.ssml);_d(n)&&(e.ssml=n)}return t.plain&&(e.plain=t.plain),e.plain||e.ssml?e:void 0}function tn(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ").trim()}const La=/<lang xml:lang="([^"]*)">([\s\S]*?)<\/lang>/g;function $a(t){return new RegExp(La).test(t)}function Ui(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ")}const Bd=new RegExp(`\\s+|[${$n}]+|[${De}]+|[^\\s${$n}${De}]+`,"gu");function Cn(t){const e=[];for(const[n]of t.matchAll(Bd))/^\s/.test(n)?e.push({kind:"space"}):Tu(n)?e.push({kind:"open",text:n}):Qt(n)?e.push({kind:"close",text:n}):e.push({kind:"word",text:n});return e}function qd(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 Ud(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 zd(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 _a(t,e){const n=[];let r=0;for(const s of t.matchAll(La))n.push({tokens:Cn(Ui(t.slice(r,s.index))),language:e,tagged:!1}),n.push({tokens:Cn(tn(s[2])),language:s[1],tagged:!0}),r=s.index+s[0].length;n.push({tokens:Cn(Ui(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(...Ud(n[s].tokens)):n[s].tagged&&!n[s+1].tagged&&n[s].tokens.push(...zd(n[s+1].tokens));const i=[];for(const s of n){const o=qd(s.tokens);o&&i.push({plain:o,language:s.language})}return i}const Ba=/<readium:[a-zA-Z][\w-]*\s+id="([^"]*)"\s*\/>/g;function Vd(t){return new RegExp(Ba).test(t)}function Md(t){const e=[];let n=0;for(const i of t.matchAll(Ba)){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}const jd=["aside","audio","bibliography","biblioref","cell","columnheader","details","endnotes","figure","footnote","glossary","image","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","table","toc","video"],qa=["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"],Hd={footnote:{drops:["aside"],unconditional:!0},cover:{drops:["image"]},pullquote:{drops:["blockquote","aside"]},epigraph:{drops:["blockquote"]}},Wd=["noteref","pagebreak"],Gd=["audio","video","image","figure","math","table","cover"],Kd=["cell","rowheader"],Jd=["separator"];function Ua(t){const e=Or(t.text);return e?e.plain??(e.ssml?tn(e.ssml):""):""}function Xd(t){const e=new Map,n=new Map;let r=0,i;return t.forEach((s,o)=>{e.set(s,o+1);const a=s.children??[];if(r=Math.max(r,a.length),a.some(c=>c.role?.includes("columnheader"))){i=a.map(Ua);return}i&&a.forEach((c,l)=>{const u=c.role??[];if(!u.includes("cell")&&!u.includes("rowheader"))return;const h=i[l];h&&n.set(c,h)})}),{lines:t.length,columns:r,rowNumbers:e,cellHeaders:n}}const zi=new Set(qa),Yd=new Set(Wd),Qd=new Set(Gd),Ar=new Set(Kd),Zd=new Set(Jd);function ct(t,e,n,r){const i=n?`${e}.${n}`:void 0;if(i&&t.i18n.exists(i))return t.i18n.t(i,r);if(t.i18n.exists(e))return t.i18n.t(e,r)}function ge(t,e){return e==="ssml"?{ssml:Vt(t),synthetic:!0}:{plain:t,synthetic:!0}}function ne(t,e,n,r){t.push(...r);for(let i=0;i<r.length;i++)e.push(n)}function ef(t,e,n,r,i,s,o){o?(i.some(a=>n.blockStarts.has(a))&&n.blockStarts.add(o),ne(t,e,s[0]??r,[o])):(t.push(...i),e.push(...s))}function Tr(t,e){return Ar.has(t)?!0:e.contextualize.has(t)}function tf(t,e,n){return e.some(r=>{const i=Hd[r];return i?.drops.includes(t)?i.unconditional||Tr(r,n):!1})}function Vi(t,e,n,r,i,s,o,a){if(!Tr(i,r))return;if((r.i18n.exists(`${i}.block.start`)||r.i18n.exists(`${i}.block.end`))&&r.contextualizationShapes[i]!=="inline"){const l=s==="before"?`${i}.block.start`:`${i}.block.end`,u=ct(r,l,o,a);u&&ne(t,e,n,[ge(u,r.format)]);return}if(s==="before"){const l=ct(r,`${i}.inline`,o,a);if(l){const u=ge(l,r.format);if(Ar.has(i)&&(delete u.synthetic,r.language!=="none")){const h=typeof n.text=="object"?n.text.language:void 0;h&&(u.language=h)}ne(t,e,n,[u])}}}function Mi(t,e){return e.size>0&&t.some(n=>e.has(n))}function za(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&&!Qt(a)&&(s+=" "),s+=a);const o=e==="ssml"?{ssml:s}:{plain:s};return n&&(o.language=n),t.some(a=>a.synthetic)&&(o.synthetic=!0),o}function nf(t,e){const n=Or(t.text),r=n?Va(n,e.format,e.language):[];if(!e.contextualize.has("pagebreak"))return r;const i=e.i18n.exists("pagebreak.block.start")?"pagebreak.block.start":"pagebreak.inline",s=ct(e,i);if(s===void 0)return r;const o=ge(s,e.format);if(r.length===0)return[o];const a=za([o,...r],e.format);return a?(a.plain!==void 0&&(a.plain+="."),a.ssml!==void 0&&(a.ssml+="."),[a]):[o,...r]}function Va(t,e,n){if(e==="plain"&&n!=="block-level"&&n!=="none"&&t.ssml&&$a(t.ssml))return _a(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??Vt(t.plain??""):r.plain=t.plain??tn(t.ssml??""),(n==="block-level"||n==="none")&&(r.ssml&&(r.ssml=Pa(r.ssml)),n==="none"&&delete r.language),[r]}function rf(t){return(t.role??[]).some(e=>Yd.has(e))}function sf(t,e,n,r,i,s){const o=typeof t.text=="object"?t.text.language:void 0,a=new Map((t.children??[]).map(d=>[d.id,d])),c=[],l=[],u=[];for(const d of Md(e)){if(d.placeholderId!==void 0){const p=a.get(d.placeholderId);if(!p)continue;i.inlineContextualization||!rf(p)?Ma(p,c,l,i,s):u.push(p);continue}if(!d.ssml)continue;if(i.format==="plain"&&i.language!=="block-level"&&i.language!=="none"&&$a(d.ssml)){for(const p of _a(d.ssml,o)){const m={plain:p.plain};p.language&&(m.language=p.language),c.push(m),l.push(t)}continue}const g={};o&&(g.language=o),i.format==="ssml"?g.ssml=d.ssml:g.plain=tn(d.ssml),(i.language==="block-level"||i.language==="none")&&(g.ssml&&(g.ssml=Pa(g.ssml)),i.language==="none"&&delete g.language),c.push(g),l.push(t)}const h=c.length>1?za(c,i.format):void 0;return ef(n,r,i,t,c,l,h),u}function ji(t,e,n,r){const i=`${e}.parts.${n}`;return t.i18n.exists(i,{count:r})?t.i18n.t(i,{count:r}):String(r)}function af(t){return t.description===void 0?{variantKey:"unlabelled"}:{variantKey:"labelled",params:{description:t.description}}}function Hi(t,e){const n=e.tableCellHeaders.get(t);return{variantKey:n!==void 0?"withHeader":"withoutHeader",params:{header:n??"",value:Ua(t)}}}const of={table:(t,e)=>{const n=(t.children??[]).filter(i=>i.role?.includes("row")),r=Xd(n);for(const[i,s]of r.rowNumbers)e.tableRowNumbers.set(i,s);for(const[i,s]of r.cellHeaders)e.tableCellHeaders.set(i,s);return{params:{lines:ji(e,"table","lines",r.lines),columns:ji(e,"table","columns",r.columns)}}},row:(t,e)=>({params:{count:String(e.tableRowNumbers.get(t)??"")}}),cell:Hi,rowheader:Hi};function Wi(t,e,n){const r=af(e);let i=r.variantKey,s=r.params;const o=of[t]?.(e,n);o&&(o.variantKey&&(i=o.variantKey),s={...s,...o.params});const a=n.contextualizationParams?.(t,e);return a&&(s={...s,...a}),{variantKey:i,params:s}}function Ma(t,e,n,r,i){const s=t.role??[];if(Mi(s,r.skip))return;const o=s.some(d=>zi.has(d)),a=o&&!i,c=e.length,l=s.filter(d=>d!=="footnote"&&d!=="pagebreak"&&!tf(d,s,r)),u=s.some(d=>Qd.has(d)&&r.contextualize.has(d)),h=s.includes("table")&&t.description!==void 0&&!u;h&&ne(e,n,t,[ge(t.description,r.format)]);for(const d of l){if(d==="figure"&&t.description===void 0)continue;const{variantKey:g,params:p}=Wi(d,t,r);Vi(e,n,t,r,d,"before",g,p)}if(s.includes("noteref"))for(const d of t.children??[]){const g=d.role??[];if(!Mi(g,r.skip))if(g.includes("footnote")){const p=r.contextualize.has("footnote"),m=r.i18n.exists("footnote.block.start")||r.i18n.exists("footnote.block.end"),b=g.some(O=>zi.has(O))&&!i&&!r.inlineContextualization,w=e.length;if(p){const O=ct(r,m?"footnote.block.start":"footnote.inline");O!==void 0&&ne(e,n,d,[ge(O,r.format)])}if(de([d],e,n,r,i||b),b&&e.length>w&&r.blockStarts.add(e[w]),p&&m){const O=ct(r,"footnote.block.end");O!==void 0&&ne(e,n,d,[ge(O,r.format)])}}else de([d],e,n,r,i)}else if(!s.some(d=>Zd.has(d))){const d=typeof t.text=="object"?t.text.ssml:void 0;if(d&&Vd(d)){const g=sf(t,d,e,n,r,i);if(g.length>0){const p=i||o&&e.length>c;de(g,e,n,r,p)}}else if(s.includes("pagebreak")){if(ne(e,n,t,nf(t,r)),t.children){const g=i||o&&e.length>c;de(t.children,e,n,r,g)}}else{const p=s.some(m=>Ar.has(m)&&Tr(m,r))?void 0:Or(t.text);if(p&&ne(e,n,t,Va(p,r.format,r.language)),t.children){const m=i||o&&e.length>c;de(t.children,e,n,r,m)}}}a&&e.length>c&&r.blockStarts.add(e[c]),t.description!==void 0&&!u&&!h&&ne(e,n,t,[ge(t.description,r.format)]);for(const d of l){if(d==="figure"&&t.description===void 0)continue;const{variantKey:g,params:p}=Wi(d,t,r);Vi(e,n,t,r,d,"after",g,p)}}function de(t,e,n,r,i){t.forEach((s,o)=>Ma(s,e,n,r,o===0?i:!1))}function lf(t,e){const n=V.createInstance();return n.init({lng:t,resources:{[t]:{translation:e}},interpolation:{escapeValue:!1}}),n}function ja(t,e){if(typeof e=="string"||typeof t!="object")return e;const n={...t};for(const r of Object.keys(e))n[r]=ja(t[r],e[r]);return n}function cf(t,e){if(!e)return t;const n={...t};for(const r of Object.keys(e))n[r]=ja(t[r],e[r]);return n}async function Ha(t){const e=t.contextualizationLocale??"en",n=cf(await Id(e),t.contextualization?.contextualizations);return{contextualizations:n,i18n:lf(e,n),skip:new Set(t.skip??[]),contextualize:new Set(t.contextualize??[]),contextualizationShapes:t.contextualization?.shapes??{},contextualizationParams:t.contextualization?.params,format:t.format??"plain",inlineContextualization:t.inlineContextualization??!1,language:t.language??"block-level",blockStarts:new Set,tableRowNumbers:new Map,tableCellHeaders:new Map}}async function uf(t,e){const n=[],r=[];return de(t,n,r,await Ha(e),!1),Wa(n,r,Rr(t))}async function hf(t,e){const n=[],r=[],i=await Ha(e);de(t,n,r,i,!1);const s=n.map(o=>i.blockStarts.has(o));return{utterances:Wa(n,r,Rr(t)),sources:r,blockStarts:s}}function Rr(t,e=[],n=new Map){for(const r of t)n.set(r,e),r.children&&Rr(r.children,[r,...e],n);return n}function Wa(t,e,n){return t.map((r,i)=>{const s=e[i];let o=tr(s);if(!o&&s){for(const a of n.get(s)??[])if(o=tr(a),o)break}return o?{...r,locate:o}:r})}class df{engine;contentQueue=[];events=new Jt;navigatorState="idle";pendingAdvanceTimeout=null;_defaults;_preferences;_settings;_preferencesEditor=null;contextualizationOverrides;source;contentSources=[];contentBlockStarts=[];pendingResumeIndex=null;pendingResumeState=null;pendingAutoPauseIndex=null;constructor(e,n={}){this.engine=e,this._defaults=new Sa(n.defaults),this._preferences=new Ue(n.preferences),this._settings=new Kn(this._preferences,this._defaults),this.contextualizationOverrides=n.contextualizationOverrides,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.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,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)}),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)}async loadGndContent(e){this.source=e,await 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,n??void 0),this.emitContentChangeEvent({content:i})}async 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}=await hf(this.source,{format:this._settings.format,inlineContextualization:this._settings.inlineContextualization,skip:this._settings.skip,contextualize:this._settings.contextualize,contextualization:{contextualizations:this.contextualizationOverrides?.contextualizations,shapes:id(this._settings.verbosity,this.contextualizationOverrides?.shapes),params:this.contextualizationOverrides?.params},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.events.on(e,n)}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 Wn(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){!this.source&&Oi.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),await this.applyPreferences()}async applyPreferences(){const e=this._settings;this._settings=new Kn(this._preferences,this._defaults),this.applyEngineParameters(),this._preferencesEditor!==null&&(this._preferencesEditor=new Wn(this._preferences,this._settings)),Oi.some(n=>!this.sameSettingValue(e[n],this._settings[n]))&&await 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.events.clear(),await this.engine.destroy()}}const ff=["heading1","heading2","heading3","heading4","heading5","heading6"],Gi={"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",grid:"table",gridcell:"cell",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"},gf={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"},pf={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"},mf=new Set(["table","tr","td","th"]),yf=new Set(["table","row","cell","columnheader","rowheader"]);function bf(t){const e=t.getAttribute("role");if(!e)return!1;const n=e.split(/\s+/).filter(Boolean);return n.includes("presentation")||n.includes("none")}function Sf(t){for(let e=t.parentElement;e;e=e.parentElement)if(bf(e))return!0;return!1}function vf(t,e,n){return mf.has(e)||n.some(r=>yf.has(r))}function Rt(t,e){const n=t.getAttribute("role");return n?n.split(/\s+/).filter(Boolean).includes(e):!1}function wf(t){return t.tagName.toLowerCase()==="table"||Rt(t,"table")||Rt(t,"grid")||Rt(t,"treegrid")}function xf(t){return t.tagName.toLowerCase()==="tr"||Rt(t,"row")}function Ef(t){let e=null;for(let r=t.parentElement;r;r=r.parentElement)if(wf(r)){e=r;break}return e?e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>xf(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}).nextNode()===t:!1}function Ga(t){const e=[];let n=!1;const r=t.getAttribute("role");if(r)for(const s of r.split(/\s+/).filter(Boolean))if((s==="presentation"||s==="none")&&(n=!0),s==="heading"){let o=2;const a=parseInt(t.getAttribute("aria-level")??"",10);Number.isFinite(a)&&a>=1&&(o=Math.min(a,6)),e.push(ff[o-1])}else Gi[s]&&e.push(Gi[s]);const i=t.getAttribute("epub:type");if(i)for(const s of i.split(/\s+/).filter(Boolean)){const o=gf[s];o&&e.push(o)}return{attrRoles:e,presentational:n}}function Ka(t){const{attrRoles:e,presentational:n}=Ga(t);return e.length>0||n}function st(t){const e=[],n=o=>{e.includes(o)||e.push(o)},{attrRoles:r,presentational:i}=Ga(t),s=t.tagName.toLowerCase();if(i)return["presentation"];if(vf(t,s,r)&&Sf(t))return["presentation"];if(s==="body")n("body");else if(s==="th")switch(t.getAttribute("scope")){case"col":n("columnheader");break;case"row":n("rowheader");break;default:{const o=t.parentElement;o&&Ef(o)?n("columnheader"):t.previousElementSibling===null?n("rowheader"):n("cell")}}else{const o=pf[s];o&&n(o)}for(const o of r)n(o);return e}function Ki(t){return!!(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))}function Cf(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 nn(t){return ze(Cf(t),!0).trim()}function nr(t){let e="";const n=(r,i)=>{if(r.nodeType===3){e+=r.nodeValue??"";return}if(!(r.nodeType===1&&!i&&Ka(r)))for(let s=r.firstChild;s;s=s.nextSibling)n(s,!1)};return n(t,!0),e}function Ji(t){return ze(nr(t),!0).trim()}function kf(t){if(Ki(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((u,h)=>{if(Ki(u))return;const d=u.getAttribute("aria-label");c+=d||nr(u),h<a.length-1&&(c+=" ")});const l=ze(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=>nr(l)).join(" "),c=ze(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=nn(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 Of={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function Af(t){return Of[t]??["",void 0]}const Tf=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]),Rf=["math","separator"];function rr(t){return t.role?.some(e=>Rf.includes(e))?!1:!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||ft(t.text))&&!(t.children&&t.children.length>0)&&!t.description}function Nf(t){return!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||ft(t.text))&&!!(t.children&&t.children.length>0)&&!(t.role&&t.role.length>0)&&!t.id}function Df(t){return!(t.role&&t.role.length>0)&&!t.id&&!t.textref&&!t.imgref&&!t.audioref&&!t.videoref}class kt{el;object={};children=[];noText=!1;finalize(){const e=this.object,n=[];for(const r of this.children){const i=r.finalize();if(!rr(i)){if(Nf(i)){n.push(...i.children??[]);continue}n.push(i)}}if(n.length>0&&(e.children=n),e.role?.length&&e.children?.length===1&&!e.role.includes("presentation")){const r=e.children[0];r.role?.length&&e.role.every(i=>r.role.includes(i))&&delete e.role}if((!e.text||ft(e.text))&&e.children?.length===1){const r=e.children[0];Df(r)&&(r.text&&(e.text=r.text),e.children=r.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 n=kd(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(ir)),t.description&&(e.description=t.description),e}function Ja(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(Ja)),e}const Ff=1;function Xi(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 If(t){for(let e=t.firstChild;e;e=e.nextSibling)if(e.nodeType===Ff)return!0;return!1}function Xa(t,e){for(let n=e;n;n=n.parentElement)if(n===t)return!0;return!1}const Pf=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"]);function Lf(t){return Pf.has(t)}function $f(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"}function Ya(t){return typeof t=="object"&&t!==null&&t.nodeType===Node.ELEMENT_NODE}const ut={NONE:"",DESCENDANT:" ",CHILD:" > "},$={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"};function _f(t,e){return Object.values(t).includes(e)}const Bf="CssSelectorGenerator";function Mt(t="unknown problem",...e){console.warn(`${Bf}: ${t}`,...e)}const qf={selectors:[$.id,$.class,$.tag,$.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY,useScope:!1,ignoreGeneratedClassNames:!1};function Ye(t){return!!t}function Uf(t){return Array.isArray(t)?t.filter(e=>_f($,e)):[]}function Qa(t){return t instanceof RegExp}function zf(t){return["string","function"].includes(typeof t)||Qa(t)}function Yi(t){return Array.isArray(t)?t.filter(zf):[]}function Vf(t){return t!=null&&typeof t=="object"&&"nodeType"in t&&typeof t.nodeType=="number"}function Qi(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return Vf(t)&&e.includes(t.nodeType)}function Za(t,e){if(Qi(t))return t.contains(e)||Mt("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element's real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will not work as intended."),t;const n=e.getRootNode({composed:!1});return Qi(n)?(n.nodeType!==Node.DOCUMENT_NODE&&Mt("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):Dr(e)}function kn(t){return typeof t=="number"?t:Number.POSITIVE_INFINITY}function Mf(t,e={}){const n=Object.assign(Object.assign({},qf),e);return{selectors:Uf(n.selectors),whitelist:Yi(n.whitelist),blacklist:Yi(n.blacklist),root:Za(n.root,t),combineWithinSelector:Ye(n.combineWithinSelector),combineBetweenSelectors:Ye(n.combineBetweenSelectors),includeTag:Ye(n.includeTag),maxCombinations:kn(n.maxCombinations),maxCandidates:kn(n.maxCandidates),useScope:Ye(n.useScope),maxResults:kn(n.maxResults),ignoreGeneratedClassNames:Ye(n.ignoreGeneratedClassNames)}}function gt(t=[]){const[e=[],...n]=t;return n.length===0?e:n.reduce((r,i)=>{const s=new Set(i);return r.filter(o=>s.has(o))},e)}function jf(t){return[].concat(...t)}function Hf(t){return t.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function jt(t){const e=t.map(n=>{if(Qa(n))return r=>n.test(r);if(typeof n=="function")return r=>{const i=n(r);return typeof i!="boolean"?(Mt("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",n),!1):i};if(typeof n=="string"){const r=new RegExp("^"+Hf(n)+"$");return i=>r.test(i)}return Mt("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",n),()=>!1});return n=>e.some(r=>r(n))}function Nr(t,e,n){const r=Za(n,t[0]).querySelectorAll(e);if(r.length!==t.length)return!1;const i=new Set(r);return t.every(s=>i.has(s))}function eo(t,e){e=e??Dr(t);const n=[];let r=t;for(;r&&r!==e;)Ya(r)&&n.push(r),r=r.parentNode;return n}function Wf(t,e){return gt(t.map(n=>eo(n,e)))}function Gf(t){return typeof t=="object"&&t!==null&&"nodeType"in t&&t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function Dr(t){return t.ownerDocument.querySelector(":root")}const to=", ",Kf=new RegExp(["^$","\\s"].join("|")),Jf=new RegExp(["^$"].join("|")),no=[$.nthoftype,$.tag,$.id,$.class,$.attribute,$.nthchild],Xf=jt(["class","id","ng-*"]);function Yf({name:t}){return`[${t}]`}function Qf({name:t,value:e}){return`[${t}='${e}']`}function Zf({nodeName:t,nodeValue:e},n){const r=n.tagName.toLowerCase();return["input","option"].includes(r)&&t==="value"||t==="src"&&e?.startsWith("data:")?!1:!Xf(t)}function eg({nodeName:t,nodeValue:e}){return{name:Ve(t),value:Ve(e??void 0)}}function ro(t,e){const n=Array.from(t.attributes).filter(r=>Zf(r,t)).map(eg);return[...n.map(Yf),...n.map(Qf)]}function tg(t,e){const n=t.map(r=>ro(r));return gt(n)}const ng=/^[a-z_-]{3,}$/i,rg=/[bcdfghjklmnpqrstvwxyz]{4,}/i;function ig(t){if(!ng.test(t)||t.includes("_")&&!t.includes("__")||/^(css|sc|jsx|emotion|makeStyles|MuiButton|MuiBox)-/i.test(t))return!1;const e=t.split(new RegExp("--|__|[-]|(?<=[a-z])(?=[A-Z])")).filter(n=>n.length>0);if(e.length===0||e.length===1&&e[0].length<4)return!1;for(const n of e)if(n.length<=2||rg.test(n))return!1;return!0}function io(t,e){var n;const r=((n=t.getAttribute("class"))!==null&&n!==void 0?n:"").trim().split(/\s+/).filter(s=>!Jf.test(s));let i=r;if(e?.ignoreGeneratedClassNames){const s=jt(e.whitelist);i=r.filter(o=>{const a=`.${Ve(o)}`;return s(a)?!0:ig(o)})}return i.map(s=>`.${Ve(s)}`)}function sg(t,e){const n=t.map(r=>io(r,e));return gt(n)}function so(t,e){var n;const r=(n=t.getAttribute("id"))!==null&&n!==void 0?n:"",i=`#${Ve(r)}`,s=t.getRootNode({composed:!1});return!Kf.test(r)&&Nr([t],i,s)?[i]:[]}function ag(t,e){return t.length===0||t.length>1?[]:so(t[0])}function ao(t,e){const n=t.parentNode,r=n&&"children"in n?n.children:null;if(r){for(let i=0;i<r.length;i++)if(r[i]===t)return[`:nth-child(${String(i+1)})`]}return[]}function og(t,e){return gt(t.map(n=>ao(n)))}function oo(t,e){return[Ve(t.tagName.toLowerCase())]}function lo(t,e){const n=[...new Set(jf(t.map(r=>oo(r))))];return n.length===0||n.length>1?[]:[n[0]]}function co(t,e){const n=lo([t])[0],r=t.parentNode,i=r&&"children"in r?r:null;if(i){const o=Array.from(i.children).filter(a=>a.tagName.toLowerCase()===n).indexOf(t);if(o>-1)return[`${n}:nth-of-type(${String(o+1)})`]}return[]}function lg(t,e){return gt(t.map(n=>co(n)))}function*uo(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,r=ho(1);for(;r.length<=t.length&&n<e;){n+=1;const i=new Array(r.length);for(let s=0;s<r.length;s++)i[s]=t[r[s]];yield i,r=ug(r,t.length-1)}}function cg(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(uo(t,{maxResults:e}))}function ug(t=[],e=0){const n=t.length;if(n===0)return t;let r=n-1;for(;r>=0&&t[r]===e-(n-1-r);)r-=1;if(r<0)return ho(n+1);t[r]+=1;for(let i=r+1;i<n;i++)t[i]=t[i-1]+1;return t}function ho(t=1){const e=new Array(t);for(let n=0;n<t;n++)e[n]=n;return e}function*hg(t={}){const e=Object.entries(t);if(e.length===0)return;const n=[{index:e.length-1,partial:{}}];for(;n.length>0;){const r=n.pop();if(!r)break;const{index:i,partial:s}=r;if(i<0){yield s;continue}const[o,a]=e[i];for(let c=a.length-1;c>=0;c--)n.push({index:i-1,partial:Object.assign(Object.assign({},s),{[o]:a[c]})})}}const dg="3a".toUpperCase(),fg=/[ !"#$%&'()[\]{|}<>*+,./;=?@^`~\\]/;function Ve(t=""){return CSS?CSS.escape(t):gg(t)}function gg(t=""){return t.split("").map(e=>e===":"?`\\${dg} `:fg.test(e)?`\\${e}`:escape(e).replace(/%/g,"\\")).join("")}const pg={tag:lo,id:ag,class:sg,attribute:tg,nthchild:og,nthoftype:lg},mg={tag:oo,id:so,class:io,attribute:ro,nthchild:ao,nthoftype:co};function yg(t,e,n){return mg[e](t,n)}function bg(t,e,n){const r=pg[e];return r(t,n)}function Sg(t=[],e,n){return t.filter(r=>n(r)||!e(r))}function vg(t=[],e){return t.sort((n,r)=>{const i=e(n),s=e(r);return i&&!s?-1:!i&&s?1:0})}function rn(){const t=new Map;let e;return(n,r)=>{if(n.length!==1)return e??(e=Zi(n,r));const[i]=n;let s=t.get(i);return s||(s=Zi(n,r),t.set(i,s)),s}}function*wg(t,e,n=rn()){const r=new Set,i=n(t,e);for(const s of kg(i,e))r.has(s)||(r.add(s),yield s)}function Zi(t,e){const{blacklist:n,whitelist:r,combineWithinSelector:i,maxCombinations:s}=e,o=jt(n),a=jt(r),c=(l,u)=>{const h=bg(t,u,e),d=Sg(h,o,a),g=vg(d,a);return l[u]=i?Array.from(uo(g,{maxResults:s})):g.map(p=>[p]),l};return xg(e).reduce(c,{})}function xg(t){const{selectors:e,includeTag:n}=t,r=[...e];return n&&!r.includes("tag")&&r.push("tag"),r}function Eg(t){return t.includes($.tag)||t.includes($.nthoftype)?[...t]:[...t,$.tag]}function Cg(t){const{selectors:e,combineBetweenSelectors:n,includeTag:r,maxCandidates:i}=t,s=n?cg(e,{maxResults:i}):e.map(o=>[o]);return r?s.map(Eg):s}function*kg(t,e){for(const n of Cg(e))yield*Og(n,t)}function*Og(t,e){const n={};for(const r of t){const i=e[r];i&&i.length>0&&(n[r]=i)}for(const r of hg(n))yield Tg(r)}function Ag(t,e){return e[t]?e[t].join(""):""}function Tg(t={}){const e=[...no];return t[$.tag]&&t[$.nthoftype]&&e.splice(e.indexOf($.tag),1),e.map(n=>Ag(n,t)).join("")}function Rg(t,e){return[...t.map(n=>e+ut.DESCENDANT+n),...t.map(n=>e+ut.CHILD+n)]}function*Ng(t,e){if(e==="")yield*t;else for(const n of t)yield*Rg([n],e)}function*Dg(t,e,n="",r,i=rn()){const s=wg(t,r,i);for(const o of Ng(s,n))Nr(t,o,e)&&(yield o)}function*Fg(t,e,n="",r,i=rn()){if(t.length===0)return null;const s=[t.length>1?t:[],...Wf(t,e).map(o=>[o])];for(const o of s)for(const a of Dg(o,e,n,r,i))yield{foundElements:o,selector:a}}function*Ig({elements:t,root:e,rootSelector:n="",options:r}){let i=e,s=n,o=!0;const a=rn();for(;o;){let c=!1;for(const l of Fg(t,i,s,r,a)){const{foundElements:u,selector:h}=l;if(c=!0,Nr(t,h,e))yield h;else{i=u[0],s=h;break}}c||(o=!1)}}function Pg(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(Ya);return[...new Set(e)]}function Lg(t){return{value:t,include:!1}}function $g(t,e,n=ut.NONE){const r={};return e.forEach(i=>{Reflect.set(r,i,yg(t,i).map(Lg))}),{element:t,operator:n,selectors:r}}function _g({selectors:t,operator:e}){let n=[...no];t[$.tag]&&t[$.nthoftype]&&(n=n.filter(i=>i!==$.tag));let r="";return n.forEach(i=>{var s;((s=t[i])!==null&&s!==void 0?s:[]).forEach(({value:a,include:c})=>{c&&(r+=a)})}),e+r}function Bg(t,e){const n=eo(t,e).reverse(),r=Gf(e),i=n.map((o,a)=>{var c;const l=$g(o,[$.nthchild],r&&a===0?ut.NONE:ut.CHILD);return((c=l.selectors.nthchild)!==null&&c!==void 0?c:[]).forEach(u=>{u.include=!0}),l});return[r?"":e?":scope":":root",...i.map(_g)].join("")}function qg(t,e){return t.map(n=>Bg(n,e)).join(to)}var Ug=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n};function fo(t,e={}){const n=Object.assign(Object.assign({},e),{maxResults:1});return zg(t,n).next().value}function*zg(t,e={}){var n;const r=Pg(t),i=Mf(r[0],e),s=(n=i.root)!==null&&n!==void 0?n:Dr(r[0]);let o=0;for(const c of Ig({elements:r,options:i,root:s,rootSelector:""}))if(yield c,o++,o>=i.maxResults)return;if(r.length>1){const{maxResults:c}=e,l=Ug(e,["maxResults"]);if(yield r.map(u=>fo(u,l)).join(to),o++,o>=i.maxResults)return}const a=e.root!==void 0;yield qg(r,i.useScope||a?s:void 0)}function Fr(t,e){const n=t.getAttribute("id");return n?`#${CSS.escape(n)}`:fo(t,{root:e?.documentElement??void 0})??void 0}function go(t){if(t)return t.startsWith("#")?t:Ra(t)}const Vg=3;function Mg(t,e){let n=0;for(const r of Array.from(t.childNodes)){if(r===e)return n;r.nodeType===Vg&&n++}return n}function es(t,e,n,r){const i=t.parentElement;if(!i)return;const s=r&&i===r.el?r.selector:Fr(i,n);if(s)return{cssSelector:s,textNodeIndex:Mg(i,t),charOffset:e}}function jg(t,e,n){const r=es(...t.first,e,n);if(!r)return;const i=es(...t.last,e,n);return i?{start:r,end:i}:{start:r}}function Hg(t){const e=mh(t);return e.status===fe.SUCCESS?e.fragment:void 0}function ts(t){if(t===!0)return e=>e.length>0;if(Array.isArray(t)&&t.length>0){const e=new Set(t);return n=>n.some(r=>e.has(r))}return null}function Wg(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Gg(t){return Wg(t)?{predicate:ts(t.roles),domRange:!!t.domRange,textFragment:!!t.textFragment}:{predicate:ts(t),domRange:!1,textFragment:!1}}class Kg{claimed=new Set;counters=new Map;allocate(e,n){for(;;){const r=(this.counters.get(e)??0)+1;this.counters.set(e,r);const i=`${e}${r}`;if(!(n(i)||this.claimed.has(i)))return this.claimed.add(i),i}}claim(e){return this.claimed.has(e)?!1:(this.claimed.add(e),!0)}}function Jg(t){for(let e=t.parentElement;e;e=e.parentElement)if(st(e).includes("endnotes"))return!0;return!1}function Xg(t,e,n){const r=[],i=(s,o)=>{const a=s.getAttribute("id");if(a&&!e.has(a)&&e.set(a,s),o=o||s.getAttribute("aria-hidden")==="true"||s.hasAttribute("hidden"),!o&&s.tagName.toLowerCase()==="a"&&st(s).includes("noteref")){const l=s.getAttribute("href")??"";l.startsWith("#")&&r.push({id:l.slice(1),ref:s})}for(let c=s.firstElementChild;c;c=c.nextElementSibling)i(c,o)};i(t,!1);for(const s of r){const o=e.get(s.id);o&&(Xa(o,s.ref)||Jg(o)||n.add(o))}}function Yg(t,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&&!ft(i.text)),a=!t.xmlParsed&&(If(e)||o&&e.firstChild!==null);if(!o&&!a){const u=nn(e);u&&(i.text={plain:u,ssml:"",language:""})}const c=Fr(e,t.docRoot),l=go(c);return l&&(i.textref=l),t.placeholder(e,"pagebreak",i),a}function Qg(t,e,n){const r={role:n},i=nn(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=t.ids.get(a);if(c&&!Xa(c,e)&&t.noterefDepth<3){const l=t.spawnChild(c);l.convert(c);const u=l.result();u.length>0&&(r.children=u.map(h=>{const d=Ja(h);return delete d.id,d}))}}!r.children&&s&&(r.children=[{textref:s}]),t.placeholder(e,"noteref",r,o||void 0)}function Zg(t,e,n,r){const i={};if(n.length>0&&(i.role=n),r)i.text={plain:r.plain??"",ssml:r.ssml??"",language:r.language};else{const o=nn(e);o&&(i.text={plain:o,ssml:"",language:""})}const s=e.getAttribute("href");s&&(i.textref=s),t.placeholder(e,n[0]??"link",i)}const ep=3,tp=1,np=new Set(["summary","dfn","span"]);function ns(t,e){return np.has(t)&&e.length>0?!0:!Lf(t)}class Ht{xmlParsed;ids=new Map;suppressed=new Set;idAlloc=new Kg;noterefDepth=0;allowNode=null;selectorPredicate=null;domRangeEnabled=!1;textFragmentEnabled=!1;docRoot=null;root=new kt;current=this.root;foldedCaptions=new Set;segments=[];textAcc="";currentCtx={lang:"",tag:""};flowEndsWithSpace=!0;pendingChildren=[];flowFirstNode=null;flowFirstOffset=0;flowLastNode=null;flowLastOffset=0;lastFlowRange=null;lastFlowText=null;constructor(e){this.xmlParsed=e}spawnChild(e,n=1){const r=new Ht(this.xmlParsed);return r.ids=this.ids,r.suppressed=this.suppressed,r.idAlloc=this.idAlloc,r.noterefDepth=this.noterefDepth+n,r.allowNode=e,r.docRoot=this.docRoot,r.selectorPredicate=this.selectorPredicate,r.domRangeEnabled=this.domRangeEnabled,r.textFragmentEnabled=this.textFragmentEnabled,r}prescan(e){Xg(e,this.ids,this.suppressed)}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?rr(e)?[]:[ir(e)]:e.children.map(ir)}descend(e,n){const r=new kt;r.el=e,r.noText=this.foldedCaptions.has(e)||(!Ka(e)||n.includes("caption"))&&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===ep){this.text(e);return}if(e.nodeType!==tp)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(Tf.has(n)||this.suppressed.has(e)&&e!==this.allowNode)return!0;const[r,i]=kf(e);if(!i&&e!==this.allowNode)return!0;const s=st(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!Yg(this,e,r,s);if(n==="a"&&s.includes("noteref")&&e.getAttribute("href"))return Qg(this,e,s),!0;if(n==="a"&&e.getAttribute("href"))return Zg(this,e,s,r),!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 u=e.querySelector(":scope > source[src]");u&&(l=u.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(!ns(n,s))return!1;this.flushText(),this.descend(e,s);const o=this.current.object;if(s.length>0&&(o.role=s),r)o.description=r.plain,s.includes("figure")&&(this.current.noText=!0);else if(s.includes("figure")){const c=this.implicitCaptionOf(e);if(c){const l=Ji(c);l&&(o.description=l,this.current.noText=!0)}}else if(s.includes("table")){const c=this.implicitCaptionOf(e);if(c){const l=Ji(c);l&&(o.description=l,this.foldedCaptions.add(c))}}const a=e.getAttribute("id");return a&&(o.id=a),!1}implicitCaptionOf(e){for(let n=e.firstElementChild;n;n=n.nextElementSibling)if(st(n).includes("caption")&&!n.getAttribute("aria-labelledby"))return n;return null}tail(e,n,r){if(n)return;const i=e.tagName.toLowerCase(),s=st(e);ns(i,s)&&(this.flushText(),this.selectorPredicate?.(s)&&this.applyTextref(e),this.current=r)}applyTextref(e){const n=this.current.object,r=Fr(e,this.docRoot);if(n.textref=go(r),this.domRangeEnabled&&this.lastFlowRange){const i=r?{el:e,selector:r}:void 0,s=jg(this.lastFlowRange,this.docRoot,i);s&&(n.textref=Da(s))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const i=this.docRoot.createRange();i.setStart(...this.lastFlowRange.first),i.setEnd(...this.lastFlowRange.last);const s=Hg(i);s&&(n.textref=`${n.textref??"#"}${Ia(s)}`)}}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+=ze(n,this.flowEndsWithSpace),this.updateFlowSpace());return}const r=this.textContext(e);if(Od(r,this.currentCtx)||(this.closeSegment(),this.currentCtx=r),this.textAcc+=ze(n,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const i=e;this.flowFirstNode===null&&(this.flowFirstNode=i,this.flowFirstOffset=n.search(/\S/)),this.flowLastNode=i,this.flowLastOffset=n.length-(n.match(/\s+$/)?.[0].length??0)}}textContext(e){const n={lang:Xi(e.parentElement),tag:""};for(let r=e.parentElement;r&&r!==this.current.el;r=r.parentElement){const[i,s]=Af(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=[],this.flowFirstNode=null,this.flowFirstOffset=0,this.flowLastNode=null,this.flowLastOffset=0}placeholder(e,n,r,i){if(rr(r))return;const s=new kt;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}flushText(){this.closeSegment();let e=this.segments;const n=this.pendingChildren,r=this.flowFirstNode,i=this.flowFirstOffset,s=this.flowLastNode,o=this.flowLastOffset;if(this.resetFlow(),this.lastFlowRange=null,this.lastFlowText=null,e.length===0)return;for(;e.length>0;){const S=e[0];if(S.kind==="break"){e=e.slice(1);continue}if(S.kind==="text"){const x=S.text.replace(/^\s+/,"");if(x===""){e=e.slice(1);continue}e=[{...S,text:x},...e.slice(1)]}break}for(;e.length>0;){const S=e[e.length-1];if(S.kind==="break"){e=e.slice(0,-1);continue}if(S.kind==="text"){const x=S.text.replace(/\s+$/,"");if(x===""){e=e.slice(0,-1);continue}e=[...e.slice(0,-1),{...S,text:x}]}break}if(!e.some(S=>S.kind==="text"&&S.text.trim()!=="")){for(const S of n)this.appendChild(S);return}const c=[];for(const S of e)if(S.kind==="text"&&S.text.trim()!==""){const x=S.ctx.lang;c.includes(x)||c.push(x)}let l=Xi(this.current.el??null);c.length===1&&c[0]!==""&&(l=c[0]);let u=!1;for(const S of e)if(S.kind!=="text"||S.ctx.tag!==""||S.ctx.lang!==l){u=!0;break}if(u&&l===""&&(l="en"),u)for(const S of e){if(S.kind!=="placeholder")continue;let x=S.candidateID;(!x||!this.idAlloc.claim(x))&&(x=this.idAlloc.allocate(S.tag,R=>this.ids.has(R))),S.child.object.id=x}let h="",d=!1,g=!1,p=!1,m=!1;for(const S of e)if(S.kind==="text"){const x=S.text.startsWith(" "),R=S.text.replace(/^ +| +$/g,"");if(R===""){m=!0;continue}let I=!1;if(h.length>0){const L=d||m||x;g?I=!0:p?I=L&&!Qt(R):I=L}I&&(h+=" "),h+=R,d=S.text.endsWith(" "),g=!1,p=!1,m=!1}else S.kind==="break"?g=!0:S.kind==="placeholder"&&(p=!0);const b=e.some(S=>S.kind==="placeholder");this.lastFlowText=h.trim();const w={plain:u&&!b?"":h.trim(),ssml:"",language:l};if(u){let S="";for(const x of e)if(x.kind==="text"){let R=x.ctx.tag,I=x.ctx.attrs;if(x.ctx.lang!==l&&x.ctx.lang!==""&&(R="lang",I=void 0),R){S+=`<${R}`;for(const[L,X]of Object.entries(I??{}))S+=` ${L}="${En(X)}"`;x.ctx.lang!==l&&x.ctx.lang!==""&&(S+=` xml:lang="${En(x.ctx.lang)}"`),S+=`>${Vt(x.text)}</${R}>`}else S+=Vt(x.text)}else x.kind==="break"?S+="<break/>":x.kind==="placeholder"&&(S+=`<readium:${x.tag} id="${En(x.child.object.id)}" />`);w.ssml=S}const O=new kt;O.object={text:w};for(const S of n)O.children.push(S);this.appendChild(O),r&&s&&(this.lastFlowRange={first:[r,i],last:[s,o]})}}const rp=/<body[\s>]/i;function po(t,e,n){const{predicate:r,domRange:i,textFragment:s}=Gg(n?.textrefs);if(typeof t!="string"){const u=e??(t.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),h=new Ht(u==="application/xhtml+xml");return h.selectorPredicate=r,h.domRangeEnabled=i,h.textFragmentEnabled=s,h.docRoot=t.ownerDocument,h.convert(t),h.result()}const o=e??$f(t),a=new DOMParser().parseFromString(t,o),c=new Ht(o==="application/xhtml+xml");c.selectorPredicate=r,c.textFragmentEnabled=s,c.docRoot=a;const l=a.querySelector("body");return l&&!rp.test(t)?c.convertChildren(l):c.convert(l??a.documentElement),c.result()}function ip(t,e,n){return{guided:po(t,e,n)}}exports.BUILTIN_DECORATION_TYPES=ca;exports.BooleanPreference=va;exports.DecorationController=ma;exports.DecorationLayout=aa;exports.DecorationStyleType=T;exports.DecorationWidth=sa;exports.Decorator=la;exports.DirectCommsChannel=fa;exports.DirectCommsFrame=ga;exports.DirectCommsHost=pa;exports.EnumPreference=tt;exports.FallbackEngineProvider=ju;exports.FallbackSpeechEngine=Rs;exports.Locator=Sr;exports.LocatorLocations=he;exports.LocatorText=br;exports.Preference=dt;exports.RangePreference=nt;exports.ReadiumSpeechDecorationController=ba;exports.ReadiumSpeechNavigator=df;exports.ReadiumSpeechProviderRegistry=td;exports.SpeechDefaults=Sa;exports.SpeechPreferences=Ue;exports.SpeechPreferencesEditor=Wn;exports.SpeechServerAudioDecodeError=gr;exports.SpeechServerEngine=As;exports.SpeechServerEngineProvider=zu;exports.SpeechServerError=qe;exports.SpeechServerNetworkError=pr;exports.SpeechServerStallError=fr;exports.SpeechSettings=Kn;exports.StringArrayPreference=Hn;exports.WebSpeechEngine=Ln;exports.WebSpeechEngineProvider=ku;exports.WebSpeechVoiceManager=P;exports.blockLevelRoles=qa;exports.chineseVariantMap=Pe;exports.chunkPlainText=xs;exports.chunkSsmlText=Es;exports.contextualizationShapesAtVerbosity=ka;exports.contextualizedAtVerbosity=Ca;exports.createLocator=ya;exports.decodeCssSelectorFragment=Na;exports.decodeDomRangeFragment=Fa;exports.decodeTextref=tr;exports.decorationsEqual=ha;exports.defaultContextualizations=kr;exports.encodeCssSelectorFragment=Ra;exports.encodeDomRangeFragment=Da;exports.extractUtterances=uf;exports.isRecoverableFailure=Ts;exports.makeGnd=ip;exports.mapServerVoice=dr;exports.mimeTypeForFormat=Cs;exports.parseMarkup=po;exports.resolveDecorationForWire=jn;exports.selectBitrate=Os;exports.selectFormat=ks;exports.setupDecorations=ed;exports.shapeableRoles=rd;exports.skippableRoles=jd;exports.skippedAtVerbosity=Ea;exports.supportsDecorationStyle=ua;exports.toSpeechServerError=Fe;
|