1 |
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SRE=t():e.SRE=t()}(this,(()=>(()=>{"use strict";var __webpack_modules__={212:(__unused_webpack___webpack_module__,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{f:()=>SystemExternal});var _variables_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(904);class SystemExternal{static nodeRequire(){return eval("require")}static extRequire(e){return"undefined"!=typeof process&&"undefined"!=typeof require?SystemExternal.nodeRequire()(e):null}}SystemExternal.windowSupported=!("undefined"==typeof window),SystemExternal.documentSupported=SystemExternal.windowSupported&&!(void 0===window.document),SystemExternal.xmldom=SystemExternal.documentSupported?window:SystemExternal.extRequire("@xmldom/xmldom"),SystemExternal.document=SystemExternal.documentSupported?window.document:(new SystemExternal.xmldom.DOMImplementation).createDocument("","",0),SystemExternal.xpath=SystemExternal.documentSupported?document:function(){const e={document:{},XPathResult:{}};return SystemExternal.extRequire("wicked-good-xpath").install(e),e.document.XPathResult=e.XPathResult,e.document}(),SystemExternal.mathmapsIePath="https://cdn.jsdelivr.net/npm/sre-mathmaps-ie@"+_variables_js__WEBPACK_IMPORTED_MODULE_0__.u.VERSION+"mathmaps_ie.js",SystemExternal.fs=SystemExternal.documentSupported?null:SystemExternal.extRequire("fs"),SystemExternal.url=_variables_js__WEBPACK_IMPORTED_MODULE_0__.u.url,SystemExternal.jsonPath=function(){if(SystemExternal.documentSupported)return SystemExternal.url;if(process.env.SRE_JSON_PATH||global.SRE_JSON_PATH)return process.env.SRE_JSON_PATH||global.SRE_JSON_PATH;try{return SystemExternal.nodeRequire().resolve("speech-rule-engine").replace(/sre\.js$/,"")+"mathmaps"}catch(e){}try{return SystemExternal.nodeRequire().resolve(".").replace(/sre\.js$/,"")+"mathmaps"}catch(e){}return"undefined"!=typeof __dirname?__dirname+(__dirname.match(/lib?$/)?"/mathmaps":"/lib/mathmaps"):process.cwd()+"/lib/mathmaps"}(),SystemExternal.WGXpath=_variables_js__WEBPACK_IMPORTED_MODULE_0__.u.WGXpath,SystemExternal.wgxpath=null;var __WEBPACK_DEFAULT_EXPORT__=SystemExternal},904:(e,t,n)=>{n.d(t,{u:()=>r});class r{static ensureLocale(e,t){return r.LOCALES.get(e)?e:(console.error(`Locale ${e} does not exist! Using ${r.LOCALES.get(t)} instead.`),t)}}r.VERSION="4.1.2",r.LOCALES=new Map([["af","Africaans"],["ca","Catalan"],["da","Danish"],["de","German"],["en","English"],["es","Spanish"],["euro","Euro"],["fr","French"],["hi","Hindi"],["it","Italian"],["ko","Korean"],["nb","Bokm\xe5l"],["nn","Nynorsk"],["sv","Swedish"],["nemeth","Nemeth"]]),r.mathjaxVersion="4.0.0-beta.5",r.url="https://cdn.jsdelivr.net/npm/speech-rule-engine@"+r.VERSION+"/lib/mathmaps",r.WGXpath="https://cdn.jsdelivr.net/npm/wicked-good-xpath@1.3.0/dist/wgxpath.install.js"}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{cli:()=>cli,engineReady:()=>engineReady,engineSetup:()=>engineSetup,exit:()=>exit,file:()=>file,localeLoader:()=>localeLoader,localePath:()=>system_localePath,move:()=>move,number:()=>number,numericOrdinal:()=>system_numericOrdinal,ordinal:()=>ordinal,processFile:()=>processFile,setupEngine:()=>setupEngine,toDescription:()=>toDescription,toEnriched:()=>toEnriched,toJson:()=>toJson,toSemantic:()=>toSemantic,toSpeech:()=>toSpeech,variables:()=>mjs_variables,version:()=>version,vulgar:()=>vulgar,walk:()=>walk});var system_namespaceObject={},Axis,Mode,personalityProps;__webpack_require__.r(system_namespaceObject),__webpack_require__.d(system_namespaceObject,{engineReady:()=>engineReady,engineSetup:()=>engineSetup,exit:()=>exit,file:()=>file,localeLoader:()=>localeLoader,localePath:()=>system_localePath,move:()=>move,number:()=>number,numericOrdinal:()=>system_numericOrdinal,ordinal:()=>ordinal,processFile:()=>processFile,setupEngine:()=>setupEngine,toDescription:()=>toDescription,toEnriched:()=>toEnriched,toJson:()=>toJson,toSemantic:()=>toSemantic,toSpeech:()=>toSpeech,version:()=>version,vulgar:()=>vulgar,walk:()=>walk}),function(e){e.DOMAIN="domain",e.STYLE="style",e.LOCALE="locale",e.TOPIC="topic",e.MODALITY="modality"}(Axis||(Axis={}));class DynamicProperties{static createProp(...e){const t=DynamicCstr.DEFAULT_ORDER,n={};for(let r=0,i=e.length,s=t.length;r<i&&r<s;r++)n[t[r]]=e[r];return new DynamicProperties(n)}constructor(e,t=Object.keys(e)){this.properties=e,this.order=t}getProperties(){return this.properties}getOrder(){return this.order}getAxes(){return this.order}getProperty(e){return this.properties[e]}updateProperties(e){this.properties=e}allProperties(){const e=[];return this.order.forEach((t=>e.push(this.getProperty(t).slice()))),e}toString(){const e=[];return this.order.forEach((t=>e.push(t+": "+this.getProperty(t).toString()))),e.join("\n")}}class DynamicCstr extends DynamicProperties{static createCstr(...e){const t=DynamicCstr.DEFAULT_ORDER,n={};for(let r=0,i=e.length,s=t.length;r<i&&r<s;r++)n[t[r]]=e[r];return new DynamicCstr(n)}static defaultCstr(){return DynamicCstr.createCstr.apply(null,DynamicCstr.DEFAULT_ORDER.map((function(e){return DynamicCstr.DEFAULT_VALUES[e]})))}static validOrder(e){const t=DynamicCstr.DEFAULT_ORDER.slice();return e.every((e=>{const n=t.indexOf(e);return-1!==n&&t.splice(n,1)}))}constructor(e,t){const n={};for(const[t,r]of Object.entries(e))n[t]=[r];super(n,t),this.components=e}getComponents(){return this.components}getValue(e){return this.components[e]}getValues(){return this.order.map((e=>this.getValue(e)))}allProperties(){const e=super.allProperties();for(let t,n,r=0;t=e[r],n=this.order[r];r++){const e=this.getValue(n);-1===t.indexOf(e)&&t.unshift(e)}return e}toString(){return this.getValues().join(".")}equal(e){const t=e.getAxes();if(this.order.length!==t.length)return!1;for(let n,r=0;n=t[r];r++){const t=this.getValue(n);if(!t||e.getValue(n)!==t)return!1}return!0}}DynamicCstr.DEFAULT_ORDER=[Axis.LOCALE,Axis.MODALITY,Axis.DOMAIN,Axis.STYLE,Axis.TOPIC],DynamicCstr.BASE_LOCALE="base",DynamicCstr.DEFAULT_VALUE="default",DynamicCstr.DEFAULT_VALUES={[Axis.LOCALE]:"en",[Axis.DOMAIN]:DynamicCstr.DEFAULT_VALUE,[Axis.STYLE]:DynamicCstr.DEFAULT_VALUE,[Axis.TOPIC]:DynamicCstr.DEFAULT_VALUE,[Axis.MODALITY]:"speech"};class DynamicCstrParser{constructor(e){this.order=e}parse(e){const t=e.split("."),n={};if(t.length>this.order.length)throw new Error("Invalid dynamic constraint: "+n);let r=0;for(let e,i=0;e=this.order[i],t.length;i++,r++){const r=t.shift();n[e]=r}return new DynamicCstr(n,this.order.slice(0,r))}}class DefaultComparator{constructor(e,t=new DynamicProperties(e.getProperties(),e.getOrder())){this.reference=e,this.fallback=t,this.order=this.reference.getOrder()}getReference(){return this.reference}setReference(e,t){this.reference=e,this.fallback=t||new DynamicProperties(e.getProperties(),e.getOrder()),this.order=this.reference.getOrder()}match(e){const t=e.getAxes();return t.length===this.reference.getAxes().length&&t.every((t=>{const n=e.getValue(t);return n===this.reference.getValue(t)||-1!==this.fallback.getProperty(t).indexOf(n)}))}compare(e,t){let n=!1;for(let r,i=0;r=this.order[i];i++){const i=e.getValue(r),s=t.getValue(r);if(!n){const e=this.reference.getValue(r);if(e===i&&e!==s)return-1;if(e===s&&e!==i)return 1;if(e===i&&e===s)continue;e!==i&&e!==s&&(n=!0)}const o=this.fallback.getProperty(r),a=o.indexOf(i),c=o.indexOf(s);if(a<c)return-1;if(c<a)return 1}return 0}toString(){return this.reference.toString()+"\n"+this.fallback.toString()}}!function(e){e.SYNC="sync",e.ASYNC="async",e.HTTP="http"}(Mode||(Mode={})),function(e){e.PITCH="pitch",e.RATE="rate",e.VOLUME="volume",e.PAUSE="pause",e.JOIN="join",e.LAYOUT="layout"}(personalityProps||(personalityProps={}));const personalityPropList=[personalityProps.PITCH,personalityProps.RATE,personalityProps.VOLUME,personalityProps.PAUSE,personalityProps.JOIN];var Speech,Markup;!function(e){e.NONE="none",e.SHALLOW="shallow",e.DEEP="deep"}(Speech||(Speech={})),function(e){e.NONE="none",e.LAYOUT="layout",e.COUNTING="counting",e.PUNCTUATION="punctuation",e.SSML="ssml",e.ACSS="acss",e.SABLE="sable",e.VOICEXML="voicexml"}(Markup||(Markup={}));const DOMAIN_TO_STYLES={mathspeak:"default",clearspeak:"default"};var system_external=__webpack_require__(212);class debugger_Debugger{static getInstance(){return debugger_Debugger.instance=debugger_Debugger.instance||new debugger_Debugger,debugger_Debugger.instance}init(e){return e&&this.startDebugFile_(e),this.isActive_=!0,this.fileHandle}output(...e){this.isActive_&&this.output_(e)}generateOutput(e){this.isActive_&&this.output_(e.apply(e,[]))}exit(e=()=>{}){this.fileHandle.then((()=>{this.isActive_&&this.stream_&&this.stream_.end("","",e)}))}constructor(){this.isActive_=!1,this.outputFunction_=console.info,this.fileHandle=Promise.resolve(),this.stream_=null}startDebugFile_(e){this.fileHandle=system_external.f.fs.promises.open(e,"w"),this.fileHandle=this.fileHandle.then((t=>{this.stream_=t.createWriteStream(e),this.outputFunction_=function(...e){this.stream_.write(e.join(" ")),this.stream_.write("\n")}.bind(this),this.stream_.on("error",function(e){console.info("Invalid log file. Debug information sent to console."),this.outputFunction_=console.info}.bind(this)),this.stream_.on("finish",(function(){console.info("Finalizing debug file.")}))}))}output_(e){console.info!==this.outputFunction_?this.fileHandle.then((()=>this.outputFunction_.apply(this.outputFunction_,["Speech Rule Engine Debugger:"].concat(e)))):this.outputFunction_.apply(console,["Speech Rule Engine Debugger:"].concat(e))}}var variables=__webpack_require__(904);class SREError extends Error{constructor(e=""){super(),this.message=e,this.name="SRE Error"}}class engine_Engine{set defaultLocale(e){this._defaultLocale=variables.u.ensureLocale(e,this._defaultLocale)}get defaultLocale(){return this._defaultLocale}static getInstance(){return engine_Engine.instance=engine_Engine.instance||new engine_Engine,engine_Engine.instance}static defaultEvaluator(e,t){return e}static evaluateNode(e){return engine_Engine.nodeEvaluator(e)}getRate(){const e=parseInt(this.rate,10);return isNaN(e)?100:e}setDynamicCstr(e){if(this.defaultLocale&&(DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]=this.defaultLocale),e){const t=Object.keys(e);for(let n=0;n<t.length;n++){const r=t[n];if(-1!==DynamicCstr.DEFAULT_ORDER.indexOf(r)){const t=e[r];this[r]=t}}}DOMAIN_TO_STYLES[this.domain]=this.style;const t=[this.locale,this.modality,this.domain,this.style].join("."),n=DynamicProperties.createProp([DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]],[DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]],[DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN]],[DynamicCstr.DEFAULT_VALUES[Axis.STYLE]]),r=this.comparators[this.domain],i=this.parsers[this.domain];this.parser=i||this.defaultParser,this.dynamicCstr=this.parser.parse(t),this.dynamicCstr.updateProperties(n.getProperties()),this.comparator=r?r():new DefaultComparator(this.dynamicCstr)}constructor(){this.customLoader=null,this.parsers={},this.comparator=null,this.mode=Mode.SYNC,this.init=!0,this.delay=!1,this.comparators={},this.domain="mathspeak",this.style=DynamicCstr.DEFAULT_VALUES[Axis.STYLE],this._defaultLocale=DynamicCstr.DEFAULT_VALUES[Axis.LOCALE],this.locale=DynamicCstr.DEFAULT_VALUES[Axis.LOCALE],this.subiso="",this.modality=DynamicCstr.DEFAULT_VALUES[Axis.MODALITY],this.speech=Speech.NONE,this.markup=Markup.NONE,this.mark=!0,this.automark=!1,this.character=!0,this.cleanpause=!0,this.cayleyshort=!0,this.linebreaks=!1,this.rate="100",this.walker="Table",this.structure=!1,this.aria=!1,this.ruleSets=[],this.strict=!1,this.isIE=!1,this.isEdge=!1,this.pprint=!1,this.config=!1,this.rules="",this.prune="",this.locale=this.defaultLocale,this.evaluator=engine_Engine.defaultEvaluator,this.defaultParser=new DynamicCstrParser(DynamicCstr.DEFAULT_ORDER),this.parser=this.defaultParser,this.dynamicCstr=DynamicCstr.defaultCstr()}configurate(e){this.mode!==Mode.HTTP||this.config||(configBlocks(e),this.config=!0),configFeature(e)}setCustomLoader(e){e&&(this.customLoader=e)}}engine_Engine.BINARY_FEATURES=["automark","mark","character","cleanpause","strict","structure","aria","pprint","cayleyshort","linebreaks"],engine_Engine.STRING_FEATURES=["markup","style","domain","speech","walker","defaultLocale","locale","delay","modality","rate","rules","subiso","prune"],engine_Engine.nodeEvaluator=function(e){return[]};const engine=null;function configFeature(e){if("undefined"!=typeof SREfeature)for(const[t,n]of Object.entries(SREfeature))e[t]=n}function configBlocks(e){const t=document.documentElement.querySelectorAll('script[type="text/x-sre-config"]');for(let n=0,r=t.length;n<r;n++){let r;try{r=t[n].innerHTML;const i=JSON.parse(r);for(const[t,n]of Object.entries(i))e[t]=n}catch(e){debugger_Debugger.getInstance().output("Illegal configuration ",r)}}}class engine_EnginePromise{static get(e=engine_Engine.getInstance().locale){return engine_EnginePromise.promises[e]||Promise.resolve("")}static getall(){return Promise.all(Object.values(engine_EnginePromise.promises))}}function xpathSupported(){return"undefined"!=typeof XPathResult}engine_EnginePromise.loaded={},engine_EnginePromise.promises={};const xpath={currentDocument:null,evaluate:xpathSupported()?document.evaluate:system_external.f.xpath.evaluate,result:xpathSupported()?XPathResult:system_external.f.xpath.XPathResult,createNSResolver:xpathSupported()?document.createNSResolver:system_external.f.xpath.createNSResolver},nameSpaces={xhtml:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",mml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};function resolveNameSpace(e){return nameSpaces[e]||null}class Resolver{constructor(){this.lookupNamespaceURI=resolveNameSpace}}function evaluateXpath(e,t,n){return engine_Engine.getInstance().mode!==Mode.HTTP||engine_Engine.getInstance().isIE||engine_Engine.getInstance().isEdge?xpath.evaluate(e,t,new Resolver,n,null):xpath.currentDocument.evaluate(e,t,resolveNameSpace,n,null)}function evalXPath(e,t){let n;try{n=evaluateXpath(e,t,xpath.result.ORDERED_NODE_ITERATOR_TYPE)}catch(e){return[]}const r=[];for(let e=n.iterateNext();e;e=n.iterateNext())r.push(e);return r}function evaluateBoolean(e,t){let n;try{n=evaluateXpath(e,t,xpath.result.BOOLEAN_TYPE)}catch(e){return!1}return n.booleanValue}function evaluateString(e,t){let n;try{n=evaluateXpath(e,t,xpath.result.STRING_TYPE)}catch(e){return""}return n.stringValue}function updateEvaluator(e){if(engine_Engine.getInstance().mode!==Mode.HTTP)return;let t=e;for(;t&&!t.evaluate;)t=t.parentNode;t&&t.evaluate?xpath.currentDocument=t:e.ownerDocument&&(xpath.currentDocument=e.ownerDocument)}function toArray(e){const t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}function trimInput(e){return(e=e.replace(/ /g,"\xa0")).replace(/>[ \f\n\r\t\v\u200b]+</g,"><").trim()}function parseInput(e){const t=new system_external.f.xmldom.DOMParser,n=trimInput(e),r=!!n.match(/&(?!lt|gt|amp|quot|apos)\w+;/g);if(!n)throw new Error("Empty input!");try{const e=t.parseFromString(n,r?"text/html":"text/xml");return engine_Engine.getInstance().mode===Mode.HTTP?(xpath.currentDocument=e,r?e.body.childNodes[0]:e.documentElement):e.documentElement}catch(e){throw new SREError("Illegal input: "+e.message)}}var NodeType,Font,Embellish,Base;function replaceNode(e,t){e.parentNode&&(e.parentNode.insertBefore(t,e),e.parentNode.removeChild(e))}function createElement(e){return system_external.f.document.createElement(e)}function createElementNS(e,t){return system_external.f.document.createElementNS(e,t)}function createTextNode(e){return system_external.f.document.createTextNode(e)}function formatXml(e){let t="",n=/(>)(<)(\/*)/g,r=0,i=(e=e.replace(n,"$1\r\n$2$3")).split("\r\n");for(n=/(\.)*(<)(\/*)/g,i=i.map((e=>e.replace(n,"$1\r\n$2$3").split("\r\n"))).reduce(((e,t)=>e.concat(t)),[]);i.length;){let e=i.shift();if(!e)continue;let n=0;if(e.match(/^<\w[^>/]*>[^>]+$/)){const t=matchingStartEnd(e,i[0]);t[0]?t[1]?(e+=i.shift().slice(0,-t[1].length),t[1].trim()&&i.unshift(t[1])):e+=i.shift():n=1}else if(e.match(/^<\/\w/))0!==r&&(r-=1);else if(e.match(/^<\w[^>]*[^/]>.*$/))n=1;else if(e.match(/^<\w[^>]*\/>.+$/)){const t=e.indexOf(">")+1,n=e.slice(t);n.trim()&&i.unshift(),e=e.slice(0,t)+n}else n=0;t+=new Array(r+1).join(" ")+e+"\r\n",r+=n}return t}function matchingStartEnd(e,t){if(!t)return[!1,""];const n=e.match(/^<([^> ]+).*>/),r=t.match(/^<\/([^>]+)>(.*)/);return n&&r&&n[1]===r[1]?[!0,r[2]]:[!1,""]}function querySelectorAllByAttr(e,t){return e.querySelectorAll?toArray(e.querySelectorAll(`[${t}]`)):evalXPath(`.//*[@${t}]`,e)}function querySelectorAllByAttrValue(e,t,n){return e.querySelectorAll?toArray(e.querySelectorAll(`[${t}="${n}"]`)):evalXPath(`.//*[@${t}="${n}"]`,e)}function querySelectorAll(e,t){return e.querySelectorAll?toArray(e.querySelectorAll(t)):evalXPath(`.//${t}`,e)}function dom_util_tagName(e){return e.tagName.toUpperCase()}function cloneNode(e){return e.cloneNode(!0)}function serializeXml(e){return(new system_external.f.xmldom.XMLSerializer).serializeToString(e)}function num2str(e){const t=e.toString(16).toUpperCase();return t.length>3?t:("000"+t).slice(-4)}function makeInterval([e,t],n){const r=parseInt(e,16),i=parseInt(t,16),s=[];for(let e=r;e<=i;e++){let t=num2str(e);!1!==n[t]&&(t=n[t]||t,s.push(t))}return s}function makeCharInterval(e,t={}){return makeInterval(e,t).map((e=>String.fromCodePoint(parseInt(e,16))))}function makeMultiInterval(e){let t=[];for(const n of e)Array.isArray(n)?t=t.concat(makeCharInterval(n)):t.push(String.fromCodePoint(parseInt(n,16)));return t}function makeCodeInterval(e){let t=[];for(const n of e)Array.isArray(n)?t=t.concat(makeInterval(n,{}).map((e=>parseInt(e,16)))):t.push(parseInt(n,16));return t}!function(e){e[e.ELEMENT_NODE=1]="ELEMENT_NODE",e[e.ATTRIBUTE_NODE=2]="ATTRIBUTE_NODE",e[e.TEXT_NODE=3]="TEXT_NODE",e[e.CDATA_SECTION_NODE=4]="CDATA_SECTION_NODE",e[e.ENTITY_REFERENCE_NODE=5]="ENTITY_REFERENCE_NODE",e[e.ENTITY_NODE=6]="ENTITY_NODE",e[e.PROCESSING_INSTRUCTION_NODE=7]="PROCESSING_INSTRUCTION_NODE",e[e.COMMENT_NODE=8]="COMMENT_NODE",e[e.DOCUMENT_NODE=9]="DOCUMENT_NODE",e[e.DOCUMENT_TYPE_NODE=10]="DOCUMENT_TYPE_NODE",e[e.DOCUMENT_FRAGMENT_NODE=11]="DOCUMENT_FRAGMENT_NODE",e[e.NOTATION_NODE=12]="NOTATION_NODE"}(NodeType||(NodeType={})),function(e){e.BOLD="bold",e.BOLDFRAKTUR="bold-fraktur",e.BOLDITALIC="bold-italic",e.BOLDSCRIPT="bold-script",e.DOUBLESTRUCK="double-struck",e.DOUBLESTRUCKITALIC="double-struck-italic",e.FULLWIDTH="fullwidth",e.FRAKTUR="fraktur",e.ITALIC="italic",e.MONOSPACE="monospace",e.NORMAL="normal",e.SCRIPT="script",e.SANSSERIF="sans-serif",e.SANSSERIFITALIC="sans-serif-italic",e.SANSSERIFBOLD="sans-serif-bold",e.SANSSERIFBOLDITALIC="sans-serif-bold-italic"}(Font||(Font={})),function(e){e.SUPER="super",e.SUB="sub",e.CIRCLED="circled",e.PARENTHESIZED="parenthesized",e.PERIOD="period",e.NEGATIVECIRCLED="negative-circled",e.DOUBLECIRCLED="double-circled",e.CIRCLEDSANSSERIF="circled-sans-serif",e.NEGATIVECIRCLEDSANSSERIF="negative-circled-sans-serif",e.COMMA="comma",e.SQUARED="squared",e.NEGATIVESQUARED="negative-squared"}(Embellish||(Embellish={})),function(e){e.LATINCAP="latinCap",e.LATINSMALL="latinSmall",e.GREEKCAP="greekCap",e.GREEKSMALL="greekSmall",e.DIGIT="digit"}(Base||(Base={}));const PROTO_INTERVALS=[{interval:["1D400","1D419"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.BOLD},{interval:["1D41A","1D433"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.BOLD},{interval:["1D56C","1D585"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.BOLDFRAKTUR},{interval:["1D586","1D59F"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.BOLDFRAKTUR},{interval:["1D468","1D481"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.BOLDITALIC},{interval:["1D482","1D49B"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.BOLDITALIC},{interval:["1D4D0","1D4E9"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.BOLDSCRIPT},{interval:["1D4EA","1D503"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.BOLDSCRIPT},{interval:["1D538","1D551"],base:Base.LATINCAP,subst:{"1D53A":"2102","1D53F":"210D","1D545":"2115","1D547":"2119","1D548":"211A","1D549":"211D","1D551":"2124"},capital:!0,category:"Lu",font:Font.DOUBLESTRUCK},{interval:["1D552","1D56B"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.DOUBLESTRUCK},{interval:["1D504","1D51D"],base:Base.LATINCAP,subst:{"1D506":"212D","1D50B":"210C","1D50C":"2111","1D515":"211C","1D51D":"2128"},capital:!0,category:"Lu",font:Font.FRAKTUR},{interval:["1D51E","1D537"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.FRAKTUR},{interval:["FF21","FF3A"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.FULLWIDTH},{interval:["FF41","FF5A"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.FULLWIDTH},{interval:["1D434","1D44D"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.ITALIC},{interval:["1D44E","1D467"],base:Base.LATINSMALL,subst:{"1D455":"210E"},capital:!1,category:"Ll",font:Font.ITALIC},{interval:["1D670","1D689"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.MONOSPACE},{interval:["1D68A","1D6A3"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.MONOSPACE},{interval:["0041","005A"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.NORMAL},{interval:["0061","007A"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.NORMAL},{interval:["1D49C","1D4B5"],base:Base.LATINCAP,subst:{"1D49D":"212C","1D4A0":"2130","1D4A1":"2131","1D4A3":"210B","1D4A4":"2110","1D4A7":"2112","1D4A8":"2133","1D4AD":"211B"},capital:!0,category:"Lu",font:Font.SCRIPT},{interval:["1D4B6","1D4CF"],base:Base.LATINSMALL,subst:{"1D4BA":"212F","1D4BC":"210A","1D4C4":"2134"},capital:!1,category:"Ll",font:Font.SCRIPT},{interval:["1D5A0","1D5B9"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.SANSSERIF},{interval:["1D5BA","1D5D3"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.SANSSERIF},{interval:["1D608","1D621"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.SANSSERIFITALIC},{interval:["1D622","1D63B"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.SANSSERIFITALIC},{interval:["1D5D4","1D5ED"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.SANSSERIFBOLD},{interval:["1D5EE","1D607"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.SANSSERIFBOLD},{interval:["1D63C","1D655"],base:Base.LATINCAP,subst:{},capital:!0,category:"Lu",font:Font.SANSSERIFBOLDITALIC},{interval:["1D656","1D66F"],base:Base.LATINSMALL,subst:{},capital:!1,category:"Ll",font:Font.SANSSERIFBOLDITALIC},{interval:["0391","03A9"],base:Base.GREEKCAP,subst:{"03A2":"03F4"},capital:!0,category:"Lu",font:Font.NORMAL},{interval:["03B0","03D0"],base:Base.GREEKSMALL,subst:{"03B0":"2207","03CA":"2202","03CB":"03F5","03CC":"03D1","03CD":"03F0","03CE":"03D5","03CF":"03F1","03D0":"03D6"},capital:!1,category:"Ll",font:Font.NORMAL},{interval:["1D6A8","1D6C0"],base:Base.GREEKCAP,subst:{},capital:!0,category:"Lu",font:Font.BOLD},{interval:["1D6C1","1D6E1"],base:Base.GREEKSMALL,subst:{},capital:!1,category:"Ll",font:Font.BOLD},{interval:["1D6E2","1D6FA"],base:Base.GREEKCAP,subst:{},capital:!0,category:"Lu",font:Font.ITALIC},{interval:["1D6FB","1D71B"],base:Base.GREEKSMALL,subst:{},capital:!1,category:"Ll",font:Font.ITALIC},{interval:["1D71C","1D734"],base:Base.GREEKCAP,subst:{},capital:!0,category:"Lu",font:Font.BOLDITALIC},{interval:["1D735","1D755"],base:Base.GREEKSMALL,subst:{},capital:!1,category:"Ll",font:Font.BOLDITALIC},{interval:["1D756","1D76E"],base:Base.GREEKCAP,subst:{},capital:!0,category:"Lu",font:Font.SANSSERIFBOLD},{interval:["1D76F","1D78F"],base:Base.GREEKSMALL,subst:{},capital:!1,category:"Ll",font:Font.SANSSERIFBOLD},{interval:["1D790","1D7A8"],base:Base.GREEKCAP,subst:{},capital:!0,category:"Lu",font:Font.SANSSERIFBOLDITALIC},{interval:["1D7A9","1D7C9"],base:Base.GREEKSMALL,subst:{},capital:!1,category:"Ll",font:Font.SANSSERIFBOLDITALIC},{interval:["0030","0039"],base:Base.DIGIT,subst:{},offset:0,category:"Nd",font:Font.NORMAL},{interval:["2070","2079"],base:Base.DIGIT,subst:{2071:"00B9",2072:"00B2",2073:"00B3"},offset:0,category:"No",font:Embellish.SUPER},{interval:["2080","2089"],base:Base.DIGIT,subst:{},offset:0,category:"No",font:Embellish.SUB},{interval:["245F","2473"],base:Base.DIGIT,subst:{"245F":"24EA"},offset:0,category:"No",font:Embellish.CIRCLED},{interval:["3251","325F"],base:Base.DIGIT,subst:{},offset:21,category:"No",font:Embellish.CIRCLED},{interval:["32B1","32BF"],base:Base.DIGIT,subst:{},offset:36,category:"No",font:Embellish.CIRCLED},{interval:["2474","2487"],base:Base.DIGIT,subst:{},offset:1,category:"No",font:Embellish.PARENTHESIZED},{interval:["2487","249B"],base:Base.DIGIT,subst:{2487:"1F100"},offset:0,category:"No",font:Embellish.PERIOD},{interval:["2775","277F"],base:Base.DIGIT,subst:{2775:"24FF"},offset:0,category:"No",font:Embellish.NEGATIVECIRCLED},{interval:["24EB","24F4"],base:Base.DIGIT,subst:{},offset:11,category:"No",font:Embellish.NEGATIVECIRCLED},{interval:["24F5","24FE"],base:Base.DIGIT,subst:{},offset:1,category:"No",font:Embellish.DOUBLECIRCLED},{interval:["277F","2789"],base:Base.DIGIT,subst:{"277F":"1F10B"},offset:0,category:"No",font:Embellish.CIRCLEDSANSSERIF},{interval:["2789","2793"],base:Base.DIGIT,subst:{2789:"1F10C"},offset:0,category:"No",font:Embellish.NEGATIVECIRCLEDSANSSERIF},{interval:["FF10","FF19"],base:Base.DIGIT,subst:{},offset:0,category:"Nd",font:Font.FULLWIDTH},{interval:["1D7CE","1D7D7"],base:Base.DIGIT,subst:{},offset:0,category:"Nd",font:Font.BOLD},{interval:["1D7D8","1D7E1"],base:Base.DIGIT,subst:{},offset:0,category:"Nd",font:Font.DOUBLESTRUCK},{interval:["1D7E2","1D7EB"],base:Base.DIGIT,subst:{},offset:0,category:"Nd",font:Font.SANSSERIF},{interval:["1D7EC","1D7F5"],base:Base.DIGIT,subst:{},offset:0,category:"Nd",font:Font.SANSSERIFBOLD},{interval:["1D7F6","1D7FF"],base:Base.DIGIT,subst:{},offset:0,category:"Nd",font:Font.MONOSPACE},{interval:["1F101","1F10A"],base:Base.DIGIT,subst:{},offset:0,category:"No",font:Embellish.COMMA},{interval:["24B6","24CF"],base:Base.LATINCAP,subst:{},capital:!0,category:"So",font:Embellish.CIRCLED},{interval:["24D0","24E9"],base:Base.LATINSMALL,subst:{},capital:!1,category:"So",font:Embellish.CIRCLED},{interval:["1F110","1F129"],base:Base.LATINCAP,subst:{},capital:!0,category:"So",font:Embellish.PARENTHESIZED},{interval:["249C","24B5"],base:Base.LATINSMALL,subst:{},capital:!1,category:"So",font:Embellish.PARENTHESIZED},{interval:["1F130","1F149"],base:Base.LATINCAP,subst:{},capital:!0,category:"So",font:Embellish.SQUARED},{interval:["1F170","1F189"],base:Base.LATINCAP,subst:{},capital:!0,category:"So",font:Embellish.NEGATIVESQUARED},{interval:["1F150","1F169"],base:Base.LATINCAP,subst:{},capital:!0,category:"So",font:Embellish.NEGATIVECIRCLED}],INTERVALS=new Map;function alphabetName(e,t){return e+t.split("-").map((e=>e[0].toUpperCase()+e.slice(1))).join("")}for(const e of PROTO_INTERVALS){const t=alphabetName(e.base,e.font),n=makeCharInterval(e.interval,e.subst);let r=INTERVALS.get(t);r?r.unicode=r.unicode.concat(n):(r=e,r.unicode=n,INTERVALS.set(t,r))}var Types;!function(e){e.PUNCTUATION="punctuation",e.FENCE="fence",e.NUMBER="number",e.IDENTIFIER="identifier",e.TEXT="text",e.OPERATOR="operator",e.RELATION="relation",e.LARGEOP="largeop",e.FUNCTION="function",e.ACCENT="accent",e.FENCED="fenced",e.FRACTION="fraction",e.PUNCTUATED="punctuated",e.RELSEQ="relseq",e.MULTIREL="multirel",e.INFIXOP="infixop",e.PREFIXOP="prefixop",e.POSTFIXOP="postfixop",e.APPL="appl",e.INTEGRAL="integral",e.BIGOP="bigop",e.SQRT="sqrt",e.ROOT="root",e.LIMUPPER="limupper",e.LIMLOWER="limlower",e.LIMBOTH="limboth",e.SUBSCRIPT="subscript",e.SUPERSCRIPT="superscript",e.UNDERSCORE="underscore",e.OVERSCORE="overscore",e.TENSOR="tensor",e.TABLE="table",e.MULTILINE="multiline",e.MATRIX="matrix",e.VECTOR="vector",e.CASES="cases",e.ROW="row",e.LINE="line",e.CELL="cell",e.ENCLOSE="enclose",e.INFERENCE="inference",e.RULELABEL="rulelabel",e.CONCLUSION="conclusion",e.PREMISES="premises",e.UNKNOWN="unknown",e.EMPTY="empty"}(Types||(Types={}));const SemanticType=Object.assign({},Types);var Roles;!function(e){e.COMMA="comma",e.SEMICOLON="semicolon",e.ELLIPSIS="ellipsis",e.FULLSTOP="fullstop",e.QUESTION="question",e.EXCLAMATION="exclamation",e.QUOTES="quotes",e.DASH="dash",e.TILDE="tilde",e.PRIME="prime",e.DEGREE="degree",e.VBAR="vbar",e.COLON="colon",e.OPENFENCE="openfence",e.CLOSEFENCE="closefence",e.APPLICATION="application",e.DUMMY="dummy",e.UNIT="unit",e.LABEL="label",e.OPEN="open",e.CLOSE="close",e.TOP="top",e.BOTTOM="bottom",e.NEUTRAL="neutral",e.METRIC="metric",e.LATINLETTER="latinletter",e.GREEKLETTER="greekletter",e.OTHERLETTER="otherletter",e.NUMBERSET="numbersetletter",e.INTEGER="integer",e.FLOAT="float",e.OTHERNUMBER="othernumber",e.INFTY="infty",e.MIXED="mixed",e.MULTIACCENT="multiaccent",e.OVERACCENT="overaccent",e.UNDERACCENT="underaccent",e.UNDEROVER="underover",e.SUBSUP="subsup",e.LEFTSUB="leftsub",e.LEFTSUPER="leftsuper",e.RIGHTSUB="rightsub",e.RIGHTSUPER="rightsuper",e.LEFTRIGHT="leftright",e.ABOVEBELOW="abovebelow",e.SETEMPTY="set empty",e.SETEXT="set extended",e.SETSINGLE="set singleton",e.SETCOLLECT="set collection",e.STRING="string",e.SPACE="space",e.ANNOTATION="annotation",e.TEXT="text",e.SEQUENCE="sequence",e.ENDPUNCT="endpunct",e.STARTPUNCT="startpunct",e.NEGATIVE="negative",e.POSITIVE="positive",e.NEGATION="negation",e.MULTIOP="multiop",e.PREFIXOP="prefix operator",e.POSTFIXOP="postfix operator",e.LIMFUNC="limit function",e.INFIXFUNC="infix function",e.PREFIXFUNC="prefix function",e.POSTFIXFUNC="postfix function",e.SIMPLEFUNC="simple function",e.COMPFUNC="composed function",e.SUM="sum",e.INTEGRAL="integral",e.GEOMETRY="geometry",e.BOX="box",e.BLOCK="block",e.ADDITION="addition",e.MULTIPLICATION="multiplication",e.SUBTRACTION="subtraction",e.IMPLICIT="implicit",e.DIVISION="division",e.VULGAR="vulgar",e.EQUALITY="equality",e.INEQUALITY="inequality",e.ARROW="arrow",e.ELEMENT="element",e.NONELEMENT="nonelement",e.REELEMENT="reelement",e.RENONELEMENT="renonelement",e.SET="set",e.DETERMINANT="determinant",e.ROWVECTOR="rowvector",e.BINOMIAL="binomial",e.SQUAREMATRIX="squarematrix",e.CYCLE="cycle",e.MULTILINE="multiline",e.MATRIX="matrix",e.VECTOR="vector",e.CASES="cases",e.TABLE="table",e.CAYLEY="cayley",e.PROOF="proof",e.LEFT="left",e.RIGHT="right",e.UP="up",e.DOWN="down",e.FINAL="final",e.SINGLE="single",e.HYP="hyp",e.AXIOM="axiom",e.LOGIC="logic",e.UNKNOWN="unknown",e.MGLYPH="mglyph"}(Roles||(Roles={}));const SemanticRole=Object.assign({},Roles);var ExtraFont;!function(e){e.CALIGRAPHIC="caligraphic",e.CALIGRAPHICBOLD="caligraphic-bold",e.OLDSTYLE="oldstyle",e.OLDSTYLEBOLD="oldstyle-bold",e.UNKNOWN="unknown"}(ExtraFont||(ExtraFont={}));const SemanticFont=Object.assign(Object.assign(Object.assign({},Font),ExtraFont),Embellish);var SecondaryEnum;!function(e){e.ALLLETTERS="allLetters",e.D="d",e.BAR="bar",e.TILDE="tilde"}(SecondaryEnum||(SecondaryEnum={}));const SemanticSecondary=Object.assign(Object.assign({},Base),SecondaryEnum);function pluralCase(e,t){return e.toString()}function identityTransformer(e){return e.toString()}function siCombiner(e,t){return e+t.toLowerCase()}const Combiners={};function convertVulgarFraction(e,t=""){if(!e.childNodes||!e.childNodes[0]||!e.childNodes[0].childNodes||e.childNodes[0].childNodes.length<2||e.childNodes[0].childNodes[0].tagName!==SemanticType.NUMBER||e.childNodes[0].childNodes[0].getAttribute("role")!==SemanticRole.INTEGER||e.childNodes[0].childNodes[1].tagName!==SemanticType.NUMBER||e.childNodes[0].childNodes[1].getAttribute("role")!==SemanticRole.INTEGER)return{convertible:!1,content:e.textContent};const n=e.childNodes[0].childNodes[1].textContent,r=e.childNodes[0].childNodes[0].textContent,i=Number(n),s=Number(r);return isNaN(i)||isNaN(s)?{convertible:!1,content:`${r} ${t} ${n}`}:{convertible:!0,enumerator:s,denominator:i}}function vulgarFractionSmall(e,t,n){const r=convertVulgarFraction(e);if(r.convertible){const e=r.enumerator,i=r.denominator;return e>0&&e<t&&i>0&&i<n}return!1}function MESSAGES(){return{MS:{},MSroots:{},font:{},embellish:{},role:{},enclose:{},navigate:{},regexp:{},unitTimes:""}}function NUMBERS(e={}){return Object.assign({zero:"zero",ones:[],tens:[],large:[],special:{},wordOrdinal:identityTransformer,numericOrdinal:identityTransformer,numberToWords:identityTransformer,numberToOrdinal:pluralCase,vulgarSep:" ",numSep:" "},e)}function ALPHABETS(){return{latinSmall:[],latinCap:[],greekSmall:[],greekCap:[],capPrefix:{default:""},smallPrefix:{default:""},digitPrefix:{default:""},languagePrefix:{},digitTrans:{default:identityTransformer,mathspeak:identityTransformer,clearspeak:identityTransformer},letterTrans:{default:identityTransformer},combiner:(e,t,n)=>e}}function FUNCTIONS(){return{fracNestDepth:e=>vulgarFractionSmall(e,10,100),radicalNestDepth:e=>"",combineRootIndex:function(e,t){return e},combineNestedFraction:Combiners.identityCombiner,combineNestedRadical:Combiners.identityCombiner,fontRegexp:function(e){return new RegExp("^"+e.split(/ |-/).join("( |-)")+"( |-)")},si:siCombiner,plural:identityTransformer}}function SUBISO(){return{default:"",current:"",all:[]}}Combiners.identityCombiner=function(e,t,n){return e+t+n},Combiners.prefixCombiner=function(e,t,n){return e=n?n+" "+e:e,t?t+" "+e:e},Combiners.postfixCombiner=function(e,t,n){return e=n?n+" "+e:e,t?e+" "+t:e},Combiners.romanceCombiner=function(e,t,n){return e=n?e+" "+n:e,t?e+" "+t:e};const LOCALE=createLocale();function createLocale(){return{FUNCTIONS:FUNCTIONS(),MESSAGES:MESSAGES(),ALPHABETS:ALPHABETS(),NUMBERS:NUMBERS(),COMBINERS:{},CORRECTIONS:{},SUBISO:SUBISO()}}function nestingToString(e){switch(e){case 1:return LOCALE.MESSAGES.MS.ONCE||"";case 2:return LOCALE.MESSAGES.MS.TWICE;default:return e.toString()}}function combinePostfixIndex(e,t){return e===LOCALE.MESSAGES.MS.ROOTINDEX||e===LOCALE.MESSAGES.MS.INDEX?e:e+" "+t}function localFont(e){return extractString(LOCALE.MESSAGES.font[e],e)}function localRole(e){return extractString(LOCALE.MESSAGES.role[e],e)}function localEnclose(e){return extractString(LOCALE.MESSAGES.enclose[e],e)}function extractString(e,t){return void 0===e?t:"string"==typeof e?e:e[0]}function localeFontCombiner(e){return"string"==typeof e?{font:e,combiner:LOCALE.ALPHABETS.combiner}:{font:e[0],combiner:LOCALE.COMBINERS[e[1]]||Combiners[e[1]]||LOCALE.ALPHABETS.combiner}}const ATTRIBUTE="grammar";class Grammar{static getInstance(){return Grammar.instance=Grammar.instance||new Grammar,Grammar.instance}static parseInput(e){const t={},n=e.split(":");for(const e of n){const n=e.split("="),r=n[0].trim();n[1]?t[r]=n[1].trim():r.match(/^!/)?t[r.slice(1)]=!1:t[r]=!0}return t}static parseState(e){const t={},n=e.split(" ");for(const e of n){const n=e.split(":"),r=n[0],i=n[1];t[r]=i||!0}return t}static translateString(e){if(e.match(/:unit$/))return Grammar.translateUnit(e);const t=engine_Engine.getInstance();let n=t.evaluator(e,t.dynamicCstr);return n=null===n?e:n,Grammar.getInstance().getParameter("plural")&&(n=LOCALE.FUNCTIONS.plural(n)),n}static translateUnit(e){e=Grammar.prepareUnit(e);const t=engine_Engine.getInstance(),n=Grammar.getInstance().getParameter("plural"),r=t.strict,i=`${t.locale}.${t.modality}.default`;let s,o;return t.strict=!0,n&&(s=t.defaultParser.parse(i+".plural"),o=t.evaluator(e,s)),o?(t.strict=r,o):(s=t.defaultParser.parse(i+".default"),o=t.evaluator(e,s),t.strict=r,o?(n&&(o=LOCALE.FUNCTIONS.plural(o)),o):Grammar.cleanUnit(e))}static prepareUnit(e){const t=e.match(/:unit$/);return t?e.slice(0,t.index).replace(/\s+/g," ")+e.slice(t.index):e}static cleanUnit(e){return e.match(/:unit$/)?e.replace(/:unit$/,""):e}clear(){this.parameters_={},this.stateStack_=[]}setParameter(e,t){const n=this.parameters_[e];return t?this.parameters_[e]=t:delete this.parameters_[e],n}getParameter(e){return this.parameters_[e]}setCorrection(e,t){this.corrections_[e]=t}setPreprocessor(e,t){this.preprocessors_[e]=t}getCorrection(e){return this.corrections_[e]}getState(){const e=[];for(const[t,n]of Object.entries(this.parameters_))e.push("string"==typeof n?t+":"+n:t);return e.join(" ")}processSingles(){const e={};for(const t of this.singles)e[t]=!1;this.singles=[],this.pushState(e)}pushState(e){for(let[t,n]of Object.entries(e))t.match(/^\?/)&&(delete e[t],t=t.slice(1),this.singles.push(t)),e[t]=this.setParameter(t,n);this.stateStack_.push(e)}popState(){const e=this.stateStack_.pop();for(const[t,n]of Object.entries(e))this.setParameter(t,n)}setAttribute(e){if(e&&e.nodeType===NodeType.ELEMENT_NODE){const t=this.getState();t&&e.setAttribute(ATTRIBUTE,t)}}preprocess(e){return this.runProcessors(e,this.preprocessors_)}correct(e){return this.runProcessors(e,this.corrections_)}apply(e,t){return this.currentFlags=t||{},e=this.currentFlags.adjust||this.currentFlags.preprocess?Grammar.getInstance().preprocess(e):e,(this.parameters_.translate||this.currentFlags.translate)&&(e=Grammar.translateString(e)),e=this.currentFlags.adjust||this.currentFlags.correct?Grammar.getInstance().correct(e):e,this.currentFlags={},e}runProcessors(e,t){for(const[n,r]of Object.entries(this.parameters_)){const i=t[n];i&&(e=!0===r?i(e):i(e,r))}return e}constructor(){this.currentFlags={},this.parameters_={},this.corrections_={},this.preprocessors_={},this.stateStack_=[],this.singles=[]}}function correctFont(e,t){if(!t||!e)return e;const n=LOCALE.FUNCTIONS.fontRegexp(localFont(t));return e.replace(n,"")}function correctCaps(e){let t=LOCALE.ALPHABETS.capPrefix[engine_Engine.getInstance().domain];return void 0===t&&(t=LOCALE.ALPHABETS.capPrefix.default),correctFont(e,t)}function addAnnotation(e,t){return e+":"+t}function numbersToAlpha(e){return e.match(/\d+/)?LOCALE.NUMBERS.numberToWords(parseInt(e,10)):e}function noTranslateText(e){return e.match(new RegExp("^["+LOCALE.MESSAGES.regexp.TEXT+"]+$"))&&(Grammar.getInstance().currentFlags.translate=!1),e}function hundredsToWords_(e){let t=e%1e3,n="",r=numbers_af_NUMBERS.ones[Math.floor(t/100)];if(n+=r?r+numbers_af_NUMBERS.numSep+"honderd":"",t%=100,t)if(n+=n?numbers_af_NUMBERS.numSep:"",r=numbers_af_NUMBERS.ones[t],r)n+=r;else{const e=numbers_af_NUMBERS.tens[Math.floor(t/10)];r=numbers_af_NUMBERS.ones[t%10],n+=r?r+"-en-"+e:e}return n}function numberToWords(e){if(0===e)return numbers_af_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let t=0,n="";for(;e>0;){if(e%1e3){const r=hundredsToWords_(e%1e3);if(t){const e=numbers_af_NUMBERS.large[t];n=r+numbers_af_NUMBERS.numSep+e+(n?numbers_af_NUMBERS.numSep+n:"")}else n=r+(n?numbers_af_NUMBERS.numSep+n:"")}e=Math.floor(e/1e3),t++}return n}function numberToOrdinal(e,t){return 1===e?"enkel":2===e?t?"helftes":"helfte":4===e?t?"kwarte":"kwart":wordOrdinal(e)+(t?"s":"")}function wordOrdinal(e){if(1===e)return"eerste";if(3===e)return"derde";if(8===e)return"agste";if(9===e)return"negende";return numberToWords(e)+(e<19?"de":"ste")}function numericOrdinal(e){return e.toString()+"."}Grammar.getInstance().setCorrection("localFont",localFont),Grammar.getInstance().setCorrection("localRole",localRole),Grammar.getInstance().setCorrection("localEnclose",localEnclose),Grammar.getInstance().setCorrection("ignoreFont",correctFont),Grammar.getInstance().setPreprocessor("annotation",addAnnotation),Grammar.getInstance().setPreprocessor("noTranslateText",noTranslateText),Grammar.getInstance().setCorrection("ignoreCaps",correctCaps),Grammar.getInstance().setPreprocessor("numbers2alpha",numbersToAlpha);const numbers_af_NUMBERS=NUMBERS({wordOrdinal,numericOrdinal,numberToWords,numberToOrdinal}),germanPostfixCombiner=function(e,t,n){return e=n?n+" "+e:e,t?e+" "+t:e};let locale=null;function af(){return locale||(locale=create()),locale}function create(){const e=createLocale();return e.NUMBERS=numbers_af_NUMBERS,e.COMBINERS.germanPostfix=germanPostfixCombiner,e.FUNCTIONS.radicalNestDepth=nestingToString,e.FUNCTIONS.plural=e=>/.*s$/.test(e)?e:e+"s",e.FUNCTIONS.fontRegexp=function(e){return new RegExp("((^"+e+" )|( "+e+"$))")},e.ALPHABETS.combiner=Combiners.prefixCombiner,e.ALPHABETS.digitTrans.default=numbers_af_NUMBERS.numberToWords,e.CORRECTIONS.article=e=>Grammar.getInstance().getParameter("noArticle")?"":e,e}function tensToWords_(e){const t=e%100;if(t<20)return numbers_ca_NUMBERS.ones[t];const n=Math.floor(t/10),r=numbers_ca_NUMBERS.tens[n],i=numbers_ca_NUMBERS.ones[t%10];return r&&i?r+(2===n?"-i-":"-")+i:r||i}function numbers_ca_hundredsToWords_(e){const t=e%1e3,n=Math.floor(t/100),r=n?1===n?"cent":numbers_ca_NUMBERS.ones[n]+"-cents":"",i=tensToWords_(t%100);return r&&i?r+numbers_ca_NUMBERS.numSep+i:r||i}function numbers_ca_numberToWords(e){if(0===e)return numbers_ca_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let t=0,n="";for(;e>0;){const r=e%(t>1?1e6:1e3);if(r){let e=numbers_ca_NUMBERS.large[t];if(t)if(1===t)n=(1===r?"":numbers_ca_hundredsToWords_(r)+numbers_ca_NUMBERS.numSep)+e+(n?numbers_ca_NUMBERS.numSep+n:"");else{const t=numbers_ca_numberToWords(r);e=1===r?e:e.replace(/\u00f3$/,"ons"),n=t+numbers_ca_NUMBERS.numSep+e+(n?numbers_ca_NUMBERS.numSep+n:"")}else n=numbers_ca_hundredsToWords_(r)}e=Math.floor(e/(t>1?1e6:1e3)),t++}return n}function numbers_ca_numberToOrdinal(e,t){if(e>1999)return numbers_ca_numericOrdinal(e);if(e<=10)return numbers_ca_NUMBERS.special.onesOrdinals[e-1];const n=numbers_ca_numberToWords(e);return n.match(/mil$/)?n.replace(/mil$/,"mil\xb7l\xe8sima"):n.match(/u$/)?n.replace(/u$/,"vena"):n.match(/a$/)?n.replace(/a$/,"ena"):n+(n.match(/e$/)?"na":"ena")}function numbers_ca_numericOrdinal(e){const t=Grammar.getInstance().getParameter("gender");return e.toString()+("f"===t?"a":"n")}const numbers_ca_NUMBERS=NUMBERS({numericOrdinal:numbers_ca_numericOrdinal,numberToWords:numbers_ca_numberToWords,numberToOrdinal:numbers_ca_numberToOrdinal}),sansserifCombiner=function(e,t,n){return e="sans serif "+(n?n+" "+e:e),t?e+" "+t:e};let locale_ca_locale=null;function ca(){return locale_ca_locale||(locale_ca_locale=locale_ca_create()),locale_ca_locale}function locale_ca_create(){const e=createLocale();return e.NUMBERS=numbers_ca_NUMBERS,e.COMBINERS.sansserif=sansserifCombiner,e.FUNCTIONS.fracNestDepth=e=>!1,e.FUNCTIONS.combineRootIndex=combinePostfixIndex,e.FUNCTIONS.combineNestedRadical=(e,t,n)=>e+n,e.FUNCTIONS.fontRegexp=e=>RegExp("^"+e+" "),e.FUNCTIONS.plural=e=>/.*os$/.test(e)?e+"sos":/.*s$/.test(e)?e+"os":/.*ga$/.test(e)?e.slice(0,-2)+"gues":/.*\xe7a$/.test(e)?e.slice(0,-2)+"ces":/.*ca$/.test(e)?e.slice(0,-2)+"ques":/.*ja$/.test(e)?e.slice(0,-2)+"ges":/.*qua$/.test(e)?e.slice(0,-3)+"q\xfces":/.*a$/.test(e)?e.slice(0,-1)+"es":/.*(e|i)$/.test(e)?e+"ns":/.*\xed$/.test(e)?e.slice(0,-1)+"ins":e+"s",e.FUNCTIONS.si=(e,t)=>(t.match(/^metre/)&&(e=e.replace(/a$/,"\xe0").replace(/o$/,"\xf2").replace(/i$/,"\xed")),e+t),e.ALPHABETS.combiner=Combiners.prefixCombiner,e}function onePrefix_(e,t=!1){return e===numbers_da_NUMBERS.ones[1]?t?"et":"en":e}function numbers_da_hundredsToWords_(e,t=!1){let n=e%1e3,r="",i=numbers_da_NUMBERS.ones[Math.floor(n/100)];if(r+=i?onePrefix_(i,!0)+" hundrede":"",n%=100,n)if(r+=r?" og ":"",i=t?numbers_da_NUMBERS.special.smallOrdinals[n]:numbers_da_NUMBERS.ones[n],i)r+=i;else{const e=t?numbers_da_NUMBERS.special.tensOrdinals[Math.floor(n/10)]:numbers_da_NUMBERS.tens[Math.floor(n/10)];i=numbers_da_NUMBERS.ones[n%10],r+=i?onePrefix_(i)+"og"+e:e}return r}function numbers_da_numberToWords(e,t=!1){if(0===e)return numbers_da_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let n=0,r="";for(;e>0;){const i=e%1e3;if(i){const e=numbers_da_hundredsToWords_(i,t&&!n);if(n){const t=numbers_da_NUMBERS.large[n],s=i>1?"er":"";r=onePrefix_(e,n<=1)+" "+t+s+(r?" og ":"")+r}else r=onePrefix_(e)+r}e=Math.floor(e/1e3),n++}return r}function numbers_da_numberToOrdinal(e,t){return 1===e?t?"hel":"hele":2===e?t?"halv":"halve":numbers_da_wordOrdinal(e)+(t?"dele":"del")}function numbers_da_wordOrdinal(e){if(e%100)return numbers_da_numberToWords(e,!0);const t=numbers_da_numberToWords(e);return t.match(/e$/)?t:t+"e"}function numbers_da_numericOrdinal(e){return e.toString()+"."}const numbers_da_NUMBERS=NUMBERS({wordOrdinal:numbers_da_wordOrdinal,numericOrdinal:numbers_da_numericOrdinal,numberToWords:numbers_da_numberToWords,numberToOrdinal:numbers_da_numberToOrdinal});let locale_da_locale=null;function da(){return locale_da_locale||(locale_da_locale=locale_da_create()),locale_da_locale}function locale_da_create(){const e=createLocale();return e.NUMBERS=numbers_da_NUMBERS,e.FUNCTIONS.radicalNestDepth=nestingToString,e.FUNCTIONS.fontRegexp=t=>t===e.ALPHABETS.capPrefix.default?RegExp("^"+t+" "):RegExp(" "+t+"$"),e.ALPHABETS.combiner=Combiners.postfixCombiner,e.ALPHABETS.digitTrans.default=numbers_da_NUMBERS.numberToWords,e}function numbers_de_onePrefix_(e,t=!1){return e===numbers_de_NUMBERS.ones[1]?t?"eine":"ein":e}function numbers_de_hundredsToWords_(e){let t=e%1e3,n="",r=numbers_de_NUMBERS.ones[Math.floor(t/100)];if(n+=r?numbers_de_onePrefix_(r)+"hundert":"",t%=100,t)if(n+=n?numbers_de_NUMBERS.numSep:"",r=numbers_de_NUMBERS.ones[t],r)n+=r;else{const e=numbers_de_NUMBERS.tens[Math.floor(t/10)];r=numbers_de_NUMBERS.ones[t%10],n+=r?numbers_de_onePrefix_(r)+"und"+e:e}return n}function numbers_de_numberToWords(e){if(0===e)return numbers_de_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let t=0,n="";for(;e>0;){const r=e%1e3;if(r){const i=numbers_de_hundredsToWords_(e%1e3);if(t){const e=numbers_de_NUMBERS.large[t],s=t>1&&r>1?e.match(/e$/)?"n":"en":"";n=numbers_de_onePrefix_(i,t>1)+e+s+n}else n=numbers_de_onePrefix_(i,t>1)+n}e=Math.floor(e/1e3),t++}return n.replace(/ein$/,"eins")}function numbers_de_numberToOrdinal(e,t){return 1===e?"eintel":2===e?t?"halbe":"halb":numbers_de_wordOrdinal(e)+"l"}function numbers_de_wordOrdinal(e){if(1===e)return"erste";if(3===e)return"dritte";if(7===e)return"siebte";if(8===e)return"achte";return numbers_de_numberToWords(e)+(e<19?"te":"ste")}function numbers_de_numericOrdinal(e){return e.toString()+"."}const numbers_de_NUMBERS=NUMBERS({wordOrdinal:numbers_de_wordOrdinal,numericOrdinal:numbers_de_numericOrdinal,numberToWords:numbers_de_numberToWords,numberToOrdinal:numbers_de_numberToOrdinal}),germanPrefixCombiner=function(e,t,n){return"s"===n&&(t=t.split(" ").map((function(e){return e.replace(/s$/,"")})).join(" "),n=""),e=n?n+" "+e:e,t?t+" "+e:e},locale_de_germanPostfixCombiner=function(e,t,n){return e=n&&"s"!==n?n+" "+e:e,t?e+" "+t:e};let locale_de_locale=null;function de(){return locale_de_locale||(locale_de_locale=locale_de_create()),locale_de_locale}function locale_de_create(){const e=createLocale();return e.NUMBERS=numbers_de_NUMBERS,e.COMBINERS.germanPostfix=locale_de_germanPostfixCombiner,e.ALPHABETS.combiner=germanPrefixCombiner,e.FUNCTIONS.radicalNestDepth=t=>t>1?e.NUMBERS.numberToWords(t)+"fach":"",e.FUNCTIONS.combineRootIndex=(e,t)=>{const n=t?t+"wurzel":"";return e.replace("Wurzel",n)},e.FUNCTIONS.combineNestedRadical=(e,t,n)=>{const r=(t?t+" ":"")+(e=n.match(/exponent$/)?e+"r":e);return n.match(/ /)?n.replace(/ /," "+r+" "):r+" "+n},e.FUNCTIONS.fontRegexp=function(e){return e=e.split(" ").map((function(e){return e.replace(/s$/,"(|s)")})).join(" "),new RegExp("((^"+e+" )|( "+e+"$))")},e.CORRECTIONS.correctOne=e=>e.replace(/^eins$/,"ein"),e.CORRECTIONS.localFontNumber=e=>localFont(e).split(" ").map((function(e){return e.replace(/s$/,"")})).join(" "),e.CORRECTIONS.lowercase=e=>e.toLowerCase(),e.CORRECTIONS.article=e=>{const t=Grammar.getInstance().getParameter("case"),n=Grammar.getInstance().getParameter("plural");return"dative"===t?{der:"dem",die:n?"den":"der",das:"dem"}[e]:e},e.CORRECTIONS.masculine=e=>"dative"===Grammar.getInstance().getParameter("case")?e+"n":e,e}function numbers_en_hundredsToWords_(e){let t=e%1e3,n="";return n+=numbers_en_NUMBERS.ones[Math.floor(t/100)]?numbers_en_NUMBERS.ones[Math.floor(t/100)]+numbers_en_NUMBERS.numSep+"hundred":"",t%=100,t&&(n+=n?numbers_en_NUMBERS.numSep:"",n+=numbers_en_NUMBERS.ones[t]||numbers_en_NUMBERS.tens[Math.floor(t/10)]+(t%10?numbers_en_NUMBERS.numSep+numbers_en_NUMBERS.ones[t%10]:"")),n}function numbers_en_numberToWords(e){if(0===e)return numbers_en_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let t=0,n="";for(;e>0;){e%1e3&&(n=numbers_en_hundredsToWords_(e%1e3)+(t?"-"+numbers_en_NUMBERS.large[t]+"-":"")+n),e=Math.floor(e/1e3),t++}return n.replace(/-$/,"")}function numbers_en_numberToOrdinal(e,t){if(1===e)return t?"oneths":"oneth";if(2===e)return t?"halves":"half";const n=numbers_en_wordOrdinal(e);return t?n+"s":n}function numbers_en_wordOrdinal(e){let t=numbers_en_numberToWords(e);return t.match(/one$/)?t=t.slice(0,-3)+"first":t.match(/two$/)?t=t.slice(0,-3)+"second":t.match(/three$/)?t=t.slice(0,-5)+"third":t.match(/five$/)?t=t.slice(0,-4)+"fifth":t.match(/eight$/)?t=t.slice(0,-5)+"eighth":t.match(/nine$/)?t=t.slice(0,-4)+"ninth":t.match(/twelve$/)?t=t.slice(0,-6)+"twelfth":t.match(/ty$/)?t=t.slice(0,-2)+"tieth":t+="th",t}function numbers_en_numericOrdinal(e){const t=e%100,n=e.toString();if(t>10&&t<20)return n+"th";switch(e%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd";default:return n+"th"}}const numbers_en_NUMBERS=NUMBERS({wordOrdinal:numbers_en_wordOrdinal,numericOrdinal:numbers_en_numericOrdinal,numberToWords:numbers_en_numberToWords,numberToOrdinal:numbers_en_numberToOrdinal});let locale_en_locale=null;function en(){return locale_en_locale||(locale_en_locale=locale_en_create()),locale_en_locale}function locale_en_create(){const e=createLocale();return e.NUMBERS=numbers_en_NUMBERS,e.FUNCTIONS.radicalNestDepth=nestingToString,e.FUNCTIONS.plural=e=>/.*s$/.test(e)?e:e+"s",e.ALPHABETS.combiner=Combiners.prefixCombiner,e.ALPHABETS.digitTrans.default=numbers_en_NUMBERS.numberToWords,e.CORRECTIONS.article=e=>Grammar.getInstance().getParameter("noArticle")?"":e,e}function numbers_es_tensToWords_(e){const t=e%100;if(t<30)return numbers_es_NUMBERS.ones[t];const n=numbers_es_NUMBERS.tens[Math.floor(t/10)],r=numbers_es_NUMBERS.ones[t%10];return n&&r?n+" y "+r:n||r}function numbers_es_hundredsToWords_(e){const t=e%1e3,n=Math.floor(t/100),r=numbers_es_NUMBERS.special.hundreds[n],i=numbers_es_tensToWords_(t%100);return 1===n?i?r+"to "+i:r:r&&i?r+" "+i:r||i}function numbers_es_numberToWords(e){if(0===e)return numbers_es_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let t=0,n="";for(;e>0;){const r=e%1e3;if(r){let e=numbers_es_NUMBERS.large[t];const i=numbers_es_hundredsToWords_(r);t?1===r?(e=e.match("/^mil( |$)/")?e:"un "+e,n=e+(n?" "+n:"")):(e=e.replace(/\u00f3n$/,"ones"),n=numbers_es_hundredsToWords_(r)+" "+e+(n?" "+n:"")):n=i}e=Math.floor(e/1e3),t++}return n}function numbers_es_numberToOrdinal(e,t){if(e>1999)return e.toString()+"a";if(e<=12)return numbers_es_NUMBERS.special.onesOrdinals[e-1];const n=[];if(e>=1e3&&(e-=1e3,n.push("mil\xe9sima")),!e)return n.join(" ");let r=0;return r=Math.floor(e/100),r>0&&(n.push(numbers_es_NUMBERS.special.hundredsOrdinals[r-1]),e%=100),e<=12?n.push(numbers_es_NUMBERS.special.onesOrdinals[e-1]):(r=Math.floor(e/10),r>0&&(n.push(numbers_es_NUMBERS.special.tensOrdinals[r-1]),e%=10),e>0&&n.push(numbers_es_NUMBERS.special.onesOrdinals[e-1])),n.join(" ")}function numbers_es_numericOrdinal(e){const t=Grammar.getInstance().getParameter("gender");return e.toString()+("f"===t?"a":"o")}const numbers_es_NUMBERS=NUMBERS({numericOrdinal:numbers_es_numericOrdinal,numberToWords:numbers_es_numberToWords,numberToOrdinal:numbers_es_numberToOrdinal}),locale_es_sansserifCombiner=function(e,t,n){return e="sans serif "+(n?n+" "+e:e),t?e+" "+t:e};let locale_es_locale=null;function es(){return locale_es_locale||(locale_es_locale=locale_es_create()),locale_es_locale}function locale_es_create(){const e=createLocale();return e.NUMBERS=numbers_es_NUMBERS,e.COMBINERS.sansserif=locale_es_sansserifCombiner,e.FUNCTIONS.fracNestDepth=e=>!1,e.FUNCTIONS.combineRootIndex=combinePostfixIndex,e.FUNCTIONS.combineNestedRadical=(e,t,n)=>e+n,e.FUNCTIONS.fontRegexp=e=>RegExp("^"+e+" "),e.FUNCTIONS.plural=e=>/.*(a|e|i|o|u)$/.test(e)?e+"s":/.*z$/.test(e)?e.slice(0,-1)+"ces":/.*c$/.test(e)?e.slice(0,-1)+"ques":/.*g$/.test(e)?e+"ues":/.*\u00f3n$/.test(e)?e.slice(0,-2)+"ones":e+"es",e.FUNCTIONS.si=(e,t)=>(t.match(/^metro/)&&(e=e.replace(/a$/,"\xe1").replace(/o$/,"\xf3").replace(/i$/,"\xed")),e+t),e.ALPHABETS.combiner=Combiners.prefixCombiner,e}let locale_euro_locale=null;function euro(){return locale_euro_locale||(locale_euro_locale=createLocale()),locale_euro_locale}function numbers_fr_hundredsToWords_(e){let t=e%1e3,n="";if(n+=numbers_fr_NUMBERS.ones[Math.floor(t/100)]?numbers_fr_NUMBERS.ones[Math.floor(t/100)]+"-cent":"",t%=100,t){n+=n?"-":"";let e=numbers_fr_NUMBERS.ones[t];if(e)n+=e;else{const r=numbers_fr_NUMBERS.tens[Math.floor(t/10)];r.match(/-dix$/)?(e=numbers_fr_NUMBERS.ones[t%10+10],n+=r.replace(/-dix$/,"")+"-"+e):n+=r+(t%10?"-"+numbers_fr_NUMBERS.ones[t%10]:"")}}const r=n.match(/s-\w+$/);return r?n.replace(/s-\w+$/,r[0].slice(1)):n.replace(/-un$/,"-et-un")}function numbers_fr_numberToWords(e){if(0===e)return numbers_fr_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();numbers_fr_NUMBERS.special["tens-"+engine_Engine.getInstance().subiso]&&(numbers_fr_NUMBERS.tens=numbers_fr_NUMBERS.special["tens-"+engine_Engine.getInstance().subiso]);let t=0,n="";for(;e>0;){const r=e%1e3;if(r){let e=numbers_fr_NUMBERS.large[t];const i=numbers_fr_hundredsToWords_(r);if(e&&e.match(/^mille /)){const r=e.replace(/^mille /,"");n=n.match(RegExp(r))?i+(t?"-mille-":"")+n:n.match(RegExp(r.replace(/s$/,"")))?i+(t?"-mille-":"")+n.replace(r.replace(/s$/,""),r):i+(t?"-"+e+"-":"")+n}else e=1===r&&e?e.replace(/s$/,""):e,n=i+(t?"-"+e+"-":"")+n}e=Math.floor(e/1e3),t++}return n.replace(/-$/,"")}const SMALL_ORDINAL={1:"uni\xe8me",2:"demi",3:"tiers",4:"quart"};function numbers_fr_numberToOrdinal(e,t){const n=SMALL_ORDINAL[e]||numbers_fr_wordOrdinal(e);return 3===e?n:t?n+"s":n}function numbers_fr_wordOrdinal(e){if(1===e)return"premi\xe8re";let t=numbers_fr_numberToWords(e);return t.match(/^neuf$/)?t=t.slice(0,-1)+"v":t.match(/cinq$/)?t+="u":t.match(/trois$/)?t+="":(t.match(/e$/)||t.match(/s$/))&&(t=t.slice(0,-1)),t+="i\xe8me",t}function numbers_fr_numericOrdinal(e){const t=Grammar.getInstance().getParameter("gender");return 1===e?e.toString()+("m"===t?"er":"re"):e.toString()+"e"}const numbers_fr_NUMBERS=NUMBERS({wordOrdinal:numbers_fr_wordOrdinal,numericOrdinal:numbers_fr_numericOrdinal,numberToWords:numbers_fr_numberToWords,numberToOrdinal:numbers_fr_numberToOrdinal});let locale_fr_locale=null;function fr(){return locale_fr_locale||(locale_fr_locale=locale_fr_create()),locale_fr_locale}function locale_fr_create(){const e=createLocale();return e.NUMBERS=numbers_fr_NUMBERS,e.FUNCTIONS.radicalNestDepth=nestingToString,e.FUNCTIONS.combineRootIndex=combinePostfixIndex,e.FUNCTIONS.combineNestedFraction=(e,t,n)=>n.replace(/ $/g,"")+t+e,e.FUNCTIONS.combineNestedRadical=(e,t,n)=>n+" "+e,e.FUNCTIONS.fontRegexp=e=>RegExp(" (en |)"+e+"$"),e.FUNCTIONS.plural=e=>/.*s$/.test(e)?e:e+"s",e.CORRECTIONS.article=e=>Grammar.getInstance().getParameter("noArticle")?"":e,e.ALPHABETS.combiner=Combiners.romanceCombiner,e.SUBISO={default:"fr",current:"fr",all:["fr","be","ch"]},e}function numbers_hi_hundredsToWords_(e){let t=e%1e3,n="";return n+=numbers_hi_NUMBERS.ones[Math.floor(t/100)]?numbers_hi_NUMBERS.ones[Math.floor(t/100)]+numbers_hi_NUMBERS.numSep+numbers_hi_NUMBERS.special.hundred:"",t%=100,t&&(n+=n?numbers_hi_NUMBERS.numSep:"",n+=numbers_hi_NUMBERS.ones[t]),n}function numbers_hi_numberToWords(e){if(0===e)return numbers_hi_NUMBERS.zero;if(e>=Math.pow(10,32))return e.toString();let t=0,n="";const r=numbers_hi_hundredsToWords_(e%1e3);if(!(e=Math.floor(e/1e3)))return r;for(;e>0;){const r=e%100;r&&(n=numbers_hi_NUMBERS.ones[r]+numbers_hi_NUMBERS.numSep+numbers_hi_NUMBERS.large[t]+(n?numbers_hi_NUMBERS.numSep+n:"")),e=Math.floor(e/100),t++}return r?n+numbers_hi_NUMBERS.numSep+r:n}function numbers_hi_numberToOrdinal(e,t){return e<=10?numbers_hi_NUMBERS.special.smallDenominators[e]:numbers_hi_wordOrdinal(e)+" \u0905\u0902\u0936"}function numbers_hi_wordOrdinal(e){const t=Grammar.getInstance().getParameter("gender");if(e<=0)return e.toString();if(e<10)return"f"===t?numbers_hi_NUMBERS.special.ordinalsFeminine[e]:numbers_hi_NUMBERS.special.ordinalsMasculine[e];return numbers_hi_numberToWords(e)+("f"===t?"\u0935\u0940\u0902":"\u0935\u093e\u0901")}function numbers_hi_numericOrdinal(e){const t=Grammar.getInstance().getParameter("gender");if(e>0&&e<10)return"f"===t?numbers_hi_NUMBERS.special.simpleSmallOrdinalsFeminine[e]:numbers_hi_NUMBERS.special.simpleSmallOrdinalsMasculine[e];return e.toString().split("").map((function(e){const t=parseInt(e,10);return isNaN(t)?"":numbers_hi_NUMBERS.special.simpleNumbers[t]})).join("")+("f"===t?"\u0935\u0940\u0902":"\u0935\u093e\u0901")}const numbers_hi_NUMBERS=NUMBERS({wordOrdinal:numbers_hi_wordOrdinal,numericOrdinal:numbers_hi_numericOrdinal,numberToWords:numbers_hi_numberToWords,numberToOrdinal:numbers_hi_numberToOrdinal});let locale_hi_locale=null;function hi(){return locale_hi_locale||(locale_hi_locale=locale_hi_create()),locale_hi_locale}function locale_hi_create(){const e=createLocale();return e.NUMBERS=numbers_hi_NUMBERS,e.ALPHABETS.combiner=Combiners.prefixCombiner,e.FUNCTIONS.radicalNestDepth=nestingToString,e}function thousandsToWords_(e){let t=e%1e4,n="";return n+=numbers_ko_NUMBERS.ones[Math.floor(t/1e3)]?1===Math.floor(t/1e3)?"\ucc9c":numbers_ko_NUMBERS.ones[Math.floor(t/1e3)]+"\ucc9c":"",t%=1e3,t&&(n+=numbers_ko_NUMBERS.ones[Math.floor(t/100)]?1===Math.floor(t/100)?"\ubc31":numbers_ko_NUMBERS.ones[Math.floor(t/100)]+"\ubc31":"",t%=100,n+=numbers_ko_NUMBERS.tens[Math.floor(t/10)]+(t%10?numbers_ko_NUMBERS.ones[t%10]:"")),n}function numbers_ko_numberToWords(e){if(0===e)return numbers_ko_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let t=0,n="";for(;e>0;){e%1e4&&(n=thousandsToWords_(e%1e4)+(t?numbers_ko_NUMBERS.large[t]+numbers_ko_NUMBERS.numSep:"")+n),e=Math.floor(e/1e4),t++}return n.replace(/ $/,"")}function numbers_ko_numberToOrdinal(e,t){return 1===e?"\uccab\ubc88\uc9f8":numbers_ko_wordOrdinal(e)+"\ubc88\uc9f8"}function numbers_ko_wordOrdinal(e){const t=numbers_ko_numberToWords(e),n=numbers_ko_numberToWords(e%=100);if(!n||!e)return t;const r=20===e?"\uc2a4\ubb34":numbers_ko_NUMBERS.tens[10+Math.floor(e/10)],i=numbers_ko_NUMBERS.ones[10+Math.floor(e%10)];return t.slice(0,-n.length)+r+i}function numbers_ko_numericOrdinal(e){return numbers_ko_numberToOrdinal(e,!1)}const numbers_ko_NUMBERS=NUMBERS({wordOrdinal:numbers_ko_wordOrdinal,numericOrdinal:numbers_ko_numericOrdinal,numberToWords:numbers_ko_numberToWords,numberToOrdinal:numbers_ko_numberToOrdinal});let locale_ko_locale=null;function ko(){return locale_ko_locale||(locale_ko_locale=locale_ko_create()),locale_ko_locale}function locale_ko_create(){const e=createLocale();return e.NUMBERS=numbers_ko_NUMBERS,e.FUNCTIONS.radicalNestDepth=nestingToString,e.FUNCTIONS.plural=function(e){return e},e.FUNCTIONS.si=(e,t)=>e+t,e.FUNCTIONS.combineRootIndex=function(e,t){return e+t},e.ALPHABETS.combiner=Combiners.prefixCombiner,e.ALPHABETS.digitTrans.default=numbers_ko_NUMBERS.numberToWords,e.CORRECTIONS.postposition=e=>{if(["\uac19\ub2e4","\ub294","\uc640","\ub97c","\ub85c"].includes(e))return e;const t=e.slice(-1);let n=(t.charCodeAt(0)-44032)%28>0;return t.match(/[r,l,n,m,1,3,6,7,8,0]/i)&&(n=!0),Grammar.getInstance().setParameter("final",n),e},e.CORRECTIONS.article=e=>{const t=Grammar.getInstance().getParameter("final");t&&Grammar.getInstance().setParameter("final",!1),"\uac19\ub2e4"===e&&(e="\ub294");const n={\ub294:"\uc740",\uc640:"\uacfc",\ub97c:"\uc744",\ub85c:"\uc73c\ub85c"}[e];return void 0!==n&&t?n:e},e}function numbers_it_hundredsToWords_(e){let t=e%1e3,n="";if(n+=numbers_it_NUMBERS.ones[Math.floor(t/100)]?numbers_it_NUMBERS.ones[Math.floor(t/100)]+numbers_it_NUMBERS.numSep+"cento":"",t%=100,t){n+=n?numbers_it_NUMBERS.numSep:"";const e=numbers_it_NUMBERS.ones[t];if(e)n+=e;else{let e=numbers_it_NUMBERS.tens[Math.floor(t/10)];const r=t%10;1!==r&&8!==r||(e=e.slice(0,-1)),n+=e,n+=r?numbers_it_NUMBERS.numSep+numbers_it_NUMBERS.ones[t%10]:""}}return n}function numbers_it_numberToWords(e){if(0===e)return numbers_it_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();if(1===e&&Grammar.getInstance().getParameter("fraction"))return"un";let t=0,n="";for(;e>0;){e%1e3&&(n=numbers_it_hundredsToWords_(e%1e3)+(t?"-"+numbers_it_NUMBERS.large[t]+"-":"")+n),e=Math.floor(e/1e3),t++}return n.replace(/-$/,"")}function numbers_it_numberToOrdinal(e,t){if(2===e)return t?"mezzi":"mezzo";const n=numbers_it_wordOrdinal(e);if(!t)return n;const r=n.match(/o$/)?"i":"e";return n.slice(0,-1)+r}function numbers_it_wordOrdinal(e){const t="m"===Grammar.getInstance().getParameter("gender")?"o":"a";let n=numbers_it_NUMBERS.special.onesOrdinals[e];return n?n.slice(0,-1)+t:(n=numbers_it_numberToWords(e),n.slice(0,-1)+"esim"+t)}function numbers_it_numericOrdinal(e){const t=Grammar.getInstance().getParameter("gender");return e.toString()+("m"===t?"o":"a")}const numbers_it_NUMBERS=NUMBERS({wordOrdinal:numbers_it_wordOrdinal,numericOrdinal:numbers_it_numericOrdinal,numberToWords:numbers_it_numberToWords,numberToOrdinal:numbers_it_numberToOrdinal}),italianPostfixCombiner=function(e,t,n){return e.match(/^[a-zA-Z]$/)&&(t=t.replace("cerchiato","cerchiata")),e=n?e+" "+n:e,t?e+" "+t:e};let locale_it_locale=null;function it(){return locale_it_locale||(locale_it_locale=locale_it_create()),locale_it_locale}function locale_it_create(){const e=createLocale();return e.NUMBERS=numbers_it_NUMBERS,e.COMBINERS.italianPostfix=italianPostfixCombiner,e.FUNCTIONS.radicalNestDepth=nestingToString,e.FUNCTIONS.combineRootIndex=combinePostfixIndex,e.FUNCTIONS.combineNestedFraction=(e,t,n)=>n.replace(/ $/g,"")+t+e,e.FUNCTIONS.combineNestedRadical=(e,t,n)=>n+" "+e,e.FUNCTIONS.fontRegexp=e=>RegExp(" (en |)"+e+"$"),e.ALPHABETS.combiner=Combiners.romanceCombiner,e}function hundredsToWordsRo_(e,t=!1){let n=e%1e3,r="";const i=Math.floor(n/100),s=numbers_nn_NUMBERS.ones[i];if(r+=s?(1===i?"":s)+"hundre":"",n%=100,n){if(r+=r?"og":"",t){const e=numbers_nn_NUMBERS.special.smallOrdinals[n];if(e)return r+e;if(n%10)return r+numbers_nn_NUMBERS.tens[Math.floor(n/10)]+numbers_nn_NUMBERS.special.smallOrdinals[n%10]}r+=numbers_nn_NUMBERS.ones[n]||numbers_nn_NUMBERS.tens[Math.floor(n/10)]+(n%10?numbers_nn_NUMBERS.ones[n%10]:"")}return t?replaceOrdinal(r):r}function numberToWordsRo(e,t=!1){if(0===e)return t?numbers_nn_NUMBERS.special.smallOrdinals[0]:numbers_nn_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let n=0,r="";for(;e>0;){const i=e%1e3;if(i){const s=hundredsToWordsRo_(e%1e3,!n&&t);!n&&t&&(t=!t),r=s+(n?" "+numbers_nn_NUMBERS.large[n]+(n>1&&i>1?"er":"")+(r?" ":""):"")+r}e=Math.floor(e/1e3),n++}return t?r+(r.match(/tusen$/)?"de":"te"):r}function numbers_nn_numberToOrdinal(e,t){return numbers_nn_wordOrdinal(e)}function replaceOrdinal(e){const t=numbers_nn_NUMBERS.special.endOrdinal[0];return"a"===t&&e.match(/en$/)?e.slice(0,-2)+numbers_nn_NUMBERS.special.endOrdinal:e.match(/(d|n)$/)||e.match(/hundre$/)?e+"de":e.match(/i$/)?e+numbers_nn_NUMBERS.special.endOrdinal:"a"===t&&e.match(/e$/)?e.slice(0,-1)+numbers_nn_NUMBERS.special.endOrdinal:(e.match(/e$/),e+"nde")}function numbers_nn_wordOrdinal(e){return numbers_nn_numberToWords(e,!0)}function numbers_nn_numericOrdinal(e){return e.toString()+"."}const numbers_nn_NUMBERS=NUMBERS({wordOrdinal:numbers_nn_wordOrdinal,numericOrdinal:numbers_nn_numericOrdinal,numberToWords:numbers_nn_numberToWords,numberToOrdinal:numbers_nn_numberToOrdinal});function numbers_nn_onePrefix_(e,t=!1){return e===numbers_nn_NUMBERS.ones[1]?"ein"===e?"eitt ":t?"et":"ett":e}function hundredsToWordsGe_(e,t=!1){let n=e%1e3,r="",i=numbers_nn_NUMBERS.ones[Math.floor(n/100)];if(r+=i?numbers_nn_onePrefix_(i)+"hundre":"",n%=100,n){if(r+=r?"og":"",t){const e=numbers_nn_NUMBERS.special.smallOrdinals[n];if(e)return r+e}if(i=numbers_nn_NUMBERS.ones[n],i)r+=i;else{const e=numbers_nn_NUMBERS.tens[Math.floor(n/10)];i=numbers_nn_NUMBERS.ones[n%10],r+=i?i+"og"+e:e}}return t?replaceOrdinal(r):r}function numberToWordsGe(e,t=!1){if(0===e)return t?numbers_nn_NUMBERS.special.smallOrdinals[0]:numbers_nn_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let n=0,r="";for(;e>0;){const i=e%1e3;if(i){const s=hundredsToWordsGe_(e%1e3,!n&&t);!n&&t&&(t=!t),r=(1===n?numbers_nn_onePrefix_(s,!0):s)+(n>1?numbers_nn_NUMBERS.numSep:"")+(n?numbers_nn_NUMBERS.large[n]+(n>1&&i>1?"er":""):"")+(n>1&&r?numbers_nn_NUMBERS.numSep:"")+r}e=Math.floor(e/1e3),n++}return t?r+(r.match(/tusen$/)?"de":"te"):r}function numbers_nn_numberToWords(e,t=!1){return"alt"===engine_Engine.getInstance().subiso?numberToWordsGe(e,t):numberToWordsRo(e,t)}let locale_nb_locale=null;function nb(){return locale_nb_locale||(locale_nb_locale=locale_nb_create()),locale_nb_locale}function locale_nb_create(){const e=createLocale();return e.NUMBERS=numbers_nn_NUMBERS,e.ALPHABETS.combiner=Combiners.prefixCombiner,e.ALPHABETS.digitTrans.default=numbers_nn_NUMBERS.numberToWords,e.FUNCTIONS.radicalNestDepth=nestingToString,e}function numbers_nemeth_numberToWords(e){return e.toString().split("").map((function(e){return numbers_nemeth_NUMBERS.ones[parseInt(e,10)]})).join("")}const numbers_nemeth_NUMBERS=NUMBERS({numberToWords:numbers_nemeth_numberToWords,numberToOrdinal:numbers_nemeth_numberToWords}),simpleEnglish=function(e){return e.match(RegExp("^"+locale_nemeth_locale.ALPHABETS.languagePrefix.english))?e.slice(1):e},postfixCombiner=function(e,t,n){return e=simpleEnglish(e),t?e+t:e},germanCombiner=function(e,t,n){return t+simpleEnglish(e)},embellishCombiner=function(e,t,n){return t+(n||"")+(e=simpleEnglish(e))+"\u283b"},doubleEmbellishCombiner=function(e,t,n){return t+(n||"")+(e=simpleEnglish(e))+"\u283b\u283b"},parensCombiner=function(e,t,n){return t+(e=simpleEnglish(e))+"\u283e"};let locale_nemeth_locale=null;function nemeth(){return locale_nemeth_locale||(locale_nemeth_locale=locale_nemeth_create()),locale_nemeth_locale}function locale_nemeth_create(){const e=createLocale();return e.NUMBERS=numbers_nemeth_NUMBERS,e.COMBINERS={postfixCombiner,germanCombiner,embellishCombiner,doubleEmbellishCombiner,parensCombiner},e.FUNCTIONS.fracNestDepth=e=>!1,e.FUNCTIONS.fontRegexp=e=>RegExp("^"+e),e.FUNCTIONS.si=identityTransformer,e.ALPHABETS.combiner=(e,t,n)=>t?t+n+e:simpleEnglish(e),e.ALPHABETS.digitTrans={default:numbers_nemeth_NUMBERS.numberToWords},e}let locale_nn_locale=null;function nn(){return locale_nn_locale||(locale_nn_locale=locale_nn_create()),locale_nn_locale}function locale_nn_create(){const e=createLocale();return e.NUMBERS=numbers_nn_NUMBERS,e.ALPHABETS.combiner=Combiners.prefixCombiner,e.ALPHABETS.digitTrans.default=numbers_nn_NUMBERS.numberToWords,e.FUNCTIONS.radicalNestDepth=nestingToString,e.SUBISO={default:"",current:"",all:["","alt"]},e}function numbers_sv_hundredsToWords_(e){let t=e%1e3,n="";const r=Math.floor(t/100);return n+=numbers_sv_NUMBERS.ones[r]?(1===r?"":numbers_sv_NUMBERS.ones[r]+numbers_sv_NUMBERS.numSep)+"hundra":"",t%=100,t&&(n+=n?numbers_sv_NUMBERS.numSep:"",n+=numbers_sv_NUMBERS.ones[t]||numbers_sv_NUMBERS.tens[Math.floor(t/10)]+(t%10?numbers_sv_NUMBERS.numSep+numbers_sv_NUMBERS.ones[t%10]:"")),n}function numbers_sv_numberToWords(e,t=!1){if(0===e)return numbers_sv_NUMBERS.zero;if(e>=Math.pow(10,36))return e.toString();let n=0,r="";for(;e>0;){const i=e%1e3;if(i){const s=numbers_sv_NUMBERS.large[n],o=i>1&&n>1&&!t?"er":"";r=(1===n&&1===i?"":(n>1&&1===i?"en":numbers_sv_hundredsToWords_(e%1e3))+(n>1?" ":""))+(n?s+o+(n>1?" ":""):"")+r}e=Math.floor(e/1e3),n++}return r.replace(/ $/,"")}function numbers_sv_numberToOrdinal(e,t){if(1===e)return"hel";if(2===e)return t?"halva":"halv";let n=numbers_sv_wordOrdinal(e);return n=n.match(/de$/)?n.replace(/de$/,""):n,n+(t?"delar":"del")}function numbers_sv_wordOrdinal(e){let t=numbers_sv_numberToWords(e,!0);return t.match(/^noll$/)?t="nollte":t.match(/ett$/)?t=t.replace(/ett$/,"f\xf6rsta"):t.match(/tv\xe5$/)?t=t.replace(/tv\xe5$/,"andra"):t.match(/tre$/)?t=t.replace(/tre$/,"tredje"):t.match(/fyra$/)?t=t.replace(/fyra$/,"fj\xe4rde"):t.match(/fem$/)?t=t.replace(/fem$/,"femte"):t.match(/sex$/)?t=t.replace(/sex$/,"sj\xe4tte"):t.match(/sju$/)?t=t.replace(/sju$/,"sjunde"):t.match(/\xe5tta$/)?t=t.replace(/\xe5tta$/,"\xe5ttonde"):t.match(/nio$/)?t=t.replace(/nio$/,"nionde"):t.match(/tio$/)?t=t.replace(/tio$/,"tionde"):t.match(/elva$/)?t=t.replace(/elva$/,"elfte"):t.match(/tolv$/)?t=t.replace(/tolv$/,"tolfte"):t.match(/tusen$/)?t=t.replace(/tusen$/,"tusonde"):t.match(/jard$/)||t.match(/jon$/)?t+="te":t+="de",t}function numbers_sv_numericOrdinal(e){const t=e.toString();return t.match(/11$|12$/)?t+":e":t+(t.match(/1$|2$/)?":a":":e")}const numbers_sv_NUMBERS=NUMBERS({wordOrdinal:numbers_sv_wordOrdinal,numericOrdinal:numbers_sv_numericOrdinal,numberToWords:numbers_sv_numberToWords,numberToOrdinal:numbers_sv_numberToOrdinal});let locale_sv_locale=null;function sv(){return locale_sv_locale||(locale_sv_locale=locale_sv_create()),locale_sv_locale}function locale_sv_create(){const e=createLocale();return e.NUMBERS=numbers_sv_NUMBERS,e.FUNCTIONS.radicalNestDepth=nestingToString,e.FUNCTIONS.fontRegexp=function(e){return new RegExp("((^"+e+" )|( "+e+"$))")},e.ALPHABETS.combiner=Combiners.prefixCombiner,e.ALPHABETS.digitTrans.default=numbers_sv_NUMBERS.numberToWords,e.CORRECTIONS.correctOne=e=>e.replace(/^ett$/,"en"),e}const locales={af,ca,da,de,en,es,euro,fr,hi,it,ko,nb,nn,sv,nemeth};function setLocale(){const e=getLocale();if(setSubiso(e),e){for(const t of Object.getOwnPropertyNames(e))LOCALE[t]=e[t];for(const[t,n]of Object.entries(e.CORRECTIONS))Grammar.getInstance().setCorrection(t,n)}}function setSubiso(e){const t=engine_Engine.getInstance().subiso;-1===e.SUBISO.all.indexOf(t)&&(engine_Engine.getInstance().subiso=e.SUBISO.default),e.SUBISO.current=engine_Engine.getInstance().subiso}function getLocale(){const e=variables.u.ensureLocale(engine_Engine.getInstance().locale,engine_Engine.getInstance().defaultLocale);return engine_Engine.getInstance().locale=e,locales[e]()}function completeLocale(e){const t=locales[e.locale];if(!t)return void console.error("Locale "+e.locale+" does not exist!");const n=e.kind.toUpperCase(),r=e.messages;if(!r)return;const i=t();for(const[e,t]of Object.entries(r))i[n][e]=t}function detectIE(){return"undefined"!=typeof window&&"ActiveXObject"in window&&"clipboardData"in window&&(loadMapsForIE(),loadWGXpath(),!0)}function detectEdge(){var e;return"undefined"!=typeof window&&"MSGestureEvent"in window&&null===(null===(e=window.chrome)||void 0===e?void 0:e.loadTimes)&&(document.evaluate=null,loadWGXpath(!0),!0)}const mapsForIE=null;function loadWGXpath(e){loadScript(system_external.f.WGXpath),installWGXpath(e)}function installWGXpath(e,t){let n=t||1;"undefined"==typeof wgxpath&&n<10?setTimeout((function(){installWGXpath(e,n++)}),200):n>=10||(system_external.f.wgxpath=wgxpath,e?system_external.f.wgxpath.install({document}):system_external.f.wgxpath.install(),xpath.evaluate=document.evaluate,xpath.result=XPathResult,xpath.createNSResolver=document.createNSResolver)}function loadMapsForIE(){loadScript(system_external.f.mathmapsIePath)}function loadScript(e){const t=system_external.f.document.createElement("script");t.type="text/javascript",t.src=e,system_external.f.document.head?system_external.f.document.head.appendChild(t):system_external.f.document.body.appendChild(t)}function makePath(e){return e.match("/$")?e:e+"/"}function localePath(e,t="json"){return makePath(system_external.f.jsonPath)+e+(t.match(/^\./)?t:"."+t)}var __rest=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n};const NamedSymbol={functionApplication:String.fromCodePoint(8289),invisibleTimes:String.fromCodePoint(8290),invisibleComma:String.fromCodePoint(8291),invisiblePlus:String.fromCodePoint(8292)};class meaningMap extends Map{get(e){return super.get(e)||{role:SemanticRole.UNKNOWN,type:SemanticType.UNKNOWN,font:SemanticFont.UNKNOWN}}}class secondaryMap extends Map{set(e,t,n=""){return super.set(this.secKey(t,e),n||t),this}has(e,t){return super.has(this.secKey(t,e))}get(e,t){return super.get(this.secKey(t,e))}secKey(e,t){return t?`${e} ${t}`:`${e}`}}const SemanticMap={Meaning:new meaningMap,Secondary:new secondaryMap,FencesHoriz:new Map,FencesVert:new Map,LatexCommands:new Map};function addMeaning(e,t){for(const n of e)SemanticMap.Meaning.set(n,{role:t.role||SemanticRole.UNKNOWN,type:t.type||SemanticType.UNKNOWN,font:t.font||SemanticFont.UNKNOWN}),t.secondary&&SemanticMap.Secondary.set(n,t.secondary)}function initMeaning(){[{set:["23","26","40","5c","a1","a7","b6","bf","2017",["2022","2025"],"2027","203b","203c",["2041","2043"],["2047","2049"],["204b","204d"],"2050","2055","2056",["2058","205e"],"2234","2235","fe45","fe46","fe5f","fe60","fe68","fe6b","ff03","ff06","ff0f","ff20","ff3c"],type:SemanticType.PUNCTUATION,role:SemanticRole.UNKNOWN},{set:["22","ab","bb","2dd",["2018","201f"],"2039","203a",["301d","301f"],"fe10","ff02","ff07"],type:SemanticType.PUNCTUATION,role:SemanticRole.QUOTES},{set:["3b","204f","2a1f","2a3e","fe14","fe54","ff1b"],type:SemanticType.PUNCTUATION,role:SemanticRole.SEMICOLON},{set:["3f","203d","fe16","fe56","ff1f"],type:SemanticType.PUNCTUATION,role:SemanticRole.QUESTION},{set:["21","fe15","fe57","ff01"],type:SemanticType.PUNCTUATION,role:SemanticRole.EXCLAMATION},{set:["5e","60","a8","aa","b4","ba","2c7",["2d8","2da"],"2040","207a","207d","207e","ff3e","ff40"],type:SemanticType.PUNCTUATION,role:SemanticRole.OVERACCENT},{set:["b8","2db","2038","203f","2054","208a","208d","208e"],type:SemanticType.PUNCTUATION,role:SemanticRole.UNDERACCENT},{set:["3a","2982","fe13","fe30","fe55","ff1a"],type:SemanticType.PUNCTUATION,role:SemanticRole.COLON},{set:["2c","2063","fe50","ff0c"],type:SemanticType.PUNCTUATION,role:SemanticRole.COMMA},{set:["2026",["22ee","22f1"],"fe19"],type:SemanticType.PUNCTUATION,role:SemanticRole.ELLIPSIS},{set:["2e","fe52","ff0e"],type:SemanticType.PUNCTUATION,role:SemanticRole.FULLSTOP},{set:["2d","207b","208b","2212","2796","fe63","ff0d"],type:SemanticType.OPERATOR,role:SemanticRole.DASH,secondary:SemanticSecondary.BAR},{set:["5f","af",["2010","2015"],"203e","208b",["fe49","fe4f"],"fe58","ff3f","ffe3"],type:SemanticType.PUNCTUATION,role:SemanticRole.DASH,secondary:SemanticSecondary.BAR},{set:["7e","2dc","2f7","303","330","334","2053","223c","223d","301c","ff5e"],type:SemanticType.OPERATOR,role:SemanticRole.TILDE,secondary:SemanticSecondary.TILDE},{set:["27","2b9","2ba",["2032","2037"],"2057"],type:SemanticType.PUNCTUATION,role:SemanticRole.PRIME},{set:["b0"],type:SemanticType.PUNCTUATION,role:SemanticRole.DEGREE},{set:["2b","b1","2064","2213","2214","2228","222a",["228c","228e"],"2294","2295","229d","229e","22bb","22bd","22c4","22ce","22d3","2304","271b","271c","2795","27cf","29fa","29fb","29fe",["2a22","2a28"],"2a2d","2a2e","2a39","2a42","2a45","2a46","2a48","2a4a","2a4c","2a4f","2a50","2a52","2a54","2a56","2a57","2a59","2a5b","2a5d",["2a61","2a63"],"2adc","2add","fe62","ff0b"],type:SemanticType.OPERATOR,role:SemanticRole.ADDITION},{set:["2a","b7","d7","2020","2021","204e","2051","2062",["2217","2219"],"2227","2229","2240","2293","2297",["2299","229b"],"22a0","22a1","22b9","22bc",["22c5","22cc"],"22cf","22d2","22d4","2303","2305","2306","25cb","2715","2716","27ce","27d1",["29d1","29d7"],"29e2","2a1d",["2a2f","2a37"],["2a3b","2a3d"],"2a40","2a43","2a44","2a47","2a49","2a4b","2a4d","2a4e","2a51","2a53","2a55","2a58","2a5a","2a5c",["2a5e","2a60"],"2ada","2adb","fe61","ff0a"],type:SemanticType.OPERATOR,role:SemanticRole.MULTIPLICATION},{set:["2d","af","2010","2011","2052","207b","208b","2212","2216","2238","2242","2296","229f","2796","29ff",["2a29","2a2c"],"2a3a","2a41","fe63","ff0d"],type:SemanticType.OPERATOR,role:SemanticRole.SUBTRACTION},{set:["2f","f7","2044","2215","2298","2797","27cc","29bc",["29f5","29f9"],"2a38"],type:SemanticType.OPERATOR,role:SemanticRole.DIVISION},{set:["25","2030","2031","ff05","fe6a"],type:SemanticType.OPERATOR,role:SemanticRole.POSTFIXOP},{set:["ac","2200","2201","2203","2204","2206",["221a","221c"],"2310","ffe2"],type:SemanticType.OPERATOR,role:SemanticRole.PREFIXOP},{set:["2320","2321","23aa","23ae","23af","23b2","23b3","23b6","23b7"],type:SemanticType.OPERATOR,role:SemanticRole.PREFIXOP},{set:["1d7ca","1d7cb"],type:SemanticType.OPERATOR,role:SemanticRole.PREFIXOP,font:SemanticFont.BOLD},{set:["3d","7e","207c","208c","221d","2237",["223a","223f"],"2243","2245","2248",["224a","224e"],["2251","225f"],"2261","2263","229c","22cd","22d5","29e4","29e6","2a66","2a67",["2a6a","2a6c"],["2a6c","2a78"],"fe66","ff1d"],type:SemanticType.RELATION,role:SemanticRole.EQUALITY},{set:["3c","3e","2241","2242","2244","2246","2247","2249","224f","2250","2260","2262",["2264","2281"],"22b0","22b1",["22d6","22e1"],["22e6","22e9"],["2976","2978"],"29c0","29c1","29e1","29e3","29e5",["2a79","2abc"],["2af7","2afa"],"fe64","fe65","ff1c","ff1e"],type:SemanticType.RELATION,role:SemanticRole.INEQUALITY},{set:[["2282","228b"],["228f","2292"],["22b2","22b8"],"22d0","22d1",["22e2","22e5"],["22ea","22ed"],"27c3","27c4",["27c7","27c9"],["27d5","27d7"],"27dc",["2979","297b"],"29df",["2abd","2ad8"]],type:SemanticType.RELATION,role:SemanticRole.SET},{set:["2236",["27e0","27e5"],"292b","292c",["29b5","29bb"],"29be","29bf",["29c2","29d0"]],type:SemanticType.RELATION,role:SemanticRole.UNKNOWN},{set:["2205",["29b0","29b4"]],type:SemanticType.IDENTIFIER,role:SemanticRole.SETEMPTY},{set:["1ab2","221e",["29dc","29de"]],type:SemanticType.IDENTIFIER,role:SemanticRole.INFTY},{set:["22a2","22a3",["22a6","22af"],"27da","27db","27dd","27de","2ade",["2ae2","2ae6"],"2aec","2aed"],type:SemanticType.RELATION,role:SemanticRole.LOGIC},{set:["22a4","22a5","22ba","27d8","27d9","27df","2adf","2ae0",["2ae7","2aeb"],"2af1"],type:SemanticType.IDENTIFIER,role:SemanticRole.LOGIC},{set:[["2190","21ff"],"2301","2324","238b","2794",["2798","27af"],["27b1","27be"],["27f0","27ff"],["2900","292a"],["292d","2975"],["297c","297f"],["2b00","2b11"],["2b30","2b4c"],["ffe9","ffec"]],type:SemanticType.RELATION,role:SemanticRole.ARROW},{set:["2208","220a",["22f2","22f9"],"22ff","27d2","2ad9"],type:SemanticType.OPERATOR,role:SemanticRole.ELEMENT},{set:["2209"],type:SemanticType.OPERATOR,role:SemanticRole.NONELEMENT},{set:["220b","220d",["22fa","22fe"]],type:SemanticType.OPERATOR,role:SemanticRole.REELEMENT},{set:["220c"],type:SemanticType.OPERATOR,role:SemanticRole.RENONELEMENT},{set:[["220f","2211"],["22c0","22c3"],["2a00","2a0b"],"2a3f","2afc","2aff"],type:SemanticType.LARGEOP,role:SemanticRole.SUM},{set:["2140"],type:SemanticType.LARGEOP,role:SemanticRole.SUM,font:SemanticFont.DOUBLESTRUCK},{set:[["222b","2233"],["2a0c","2a17"],["2a17","2a1c"]],type:SemanticType.LARGEOP,role:SemanticRole.INTEGRAL},{set:[["2500","257F"]],type:SemanticType.RELATION,role:SemanticRole.BOX},{set:[["2580","259F"]],type:SemanticType.IDENTIFIER,role:SemanticRole.BLOCK},{set:[["25A0","25FF"],["2B12","2B2F"],["2B50","2B59"]],type:SemanticType.RELATION,role:SemanticRole.GEOMETRY},{set:["220e","2300","2302","2311","29bd","29e0",["29e8","29f3"],"2a1e","2afe","ffed","ffee"],type:SemanticType.OPERATOR,role:SemanticRole.GEOMETRY},{set:[["221f","2222"],"22be","22bf",["2312","2314"],"237c","27c0",["299b","29af"]],type:SemanticType.OPERATOR,role:SemanticRole.GEOMETRY},{set:["24",["a2","a5"],"b5","2123",["2125","2127"],"212a","212b","fe69","ff04","ffe0","ffe1","ffe5","ffe6"],type:SemanticType.IDENTIFIER,role:SemanticRole.UNKNOWN},{set:["a9","ae","210f","2114","2116","2117",["211e","2122"],"212e","2132",["2139","213b"],["2141","2144"],"214d","214e",["1f12a","1f12c"],"1f18a"],type:SemanticType.IDENTIFIER,role:SemanticRole.OTHERLETTER},{set:["2224","2226","2239","2307","27b0","27bf","27c1","27c2","27ca","27cb","27cd","27d0","27d3","27d4","2981","2999","299a","29e7","29f4","2a20","2a21","2a64","2a65","2a68","2a69","2ae1",["2aee","2af0"],"2af2","2af3","2af5","2af6","2afb","2afd"],type:SemanticType.OPERATOR,role:SemanticRole.UNKNOWN},{set:["2605","2606","26aa","26ab",["2720","274d"]],type:SemanticType.OPERATOR,role:SemanticRole.UNKNOWN},{set:[["2145","2149"]],type:SemanticType.IDENTIFIER,role:SemanticRole.LATINLETTER,font:SemanticFont.DOUBLESTRUCKITALIC,secondary:SemanticSecondary.ALLLETTERS},{set:[["213c","213f"]],type:SemanticType.IDENTIFIER,role:SemanticRole.GREEKLETTER,font:SemanticFont.DOUBLESTRUCK,secondary:SemanticSecondary.ALLLETTERS},{set:["3d0","3d7","3f6",["1d26","1d2a"],"1d5e","1d60",["1d66","1d6a"]],type:SemanticType.IDENTIFIER,role:SemanticRole.GREEKLETTER,font:SemanticFont.NORMAL,secondary:SemanticSecondary.ALLLETTERS},{set:[["2135","2138"]],type:SemanticType.IDENTIFIER,role:SemanticRole.OTHERLETTER,font:SemanticFont.NORMAL,secondary:SemanticSecondary.ALLLETTERS},{set:["131","237"],type:SemanticType.IDENTIFIER,role:SemanticRole.LATINLETTER,font:SemanticFont.NORMAL},{set:["1d6a4","1d6a5"],type:SemanticType.IDENTIFIER,role:SemanticRole.LATINLETTER,font:SemanticFont.ITALIC},{set:["2113","2118"],type:SemanticType.IDENTIFIER,role:SemanticRole.LATINLETTER,font:SemanticFont.SCRIPT},{set:[["c0","d6"],["d8","f6"],["f8","1bf"],["1c4","2af"],["1d00","1d25"],["1d6b","1d9a"],["1e00","1ef9"],["363","36f"],["1dd3","1de6"],["1d62","1d65"],"1dca","2071","207f",["2090","209c"],"2c7c"],type:SemanticType.IDENTIFIER,role:SemanticRole.LATINLETTER,font:SemanticFont.NORMAL},{set:[["00bc","00be"],["2150","215f"],"2189"],type:SemanticType.NUMBER,role:SemanticRole.FLOAT},{set:["23E8",["3248","324f"]],type:SemanticType.NUMBER,role:SemanticRole.INTEGER},{set:[["214A","214C"],"2705","2713","2714","2717","2718"],type:SemanticType.IDENTIFIER,role:SemanticRole.UNKNOWN},{set:["20","a0","ad",["2000","200f"],["2028","202f"],["205f","2060"],"206a","206b","206e","206f","feff",["fff9","fffb"]],type:SemanticType.TEXT,role:SemanticRole.SPACE},{set:["7c","a6","2223","23b8","23b9","23d0","2758",["fe31","fe34"],"ff5c","ffe4","ffe8"],type:SemanticType.FENCE,role:SemanticRole.NEUTRAL},{set:["2016","2225","2980","2af4"],type:SemanticType.FENCE,role:SemanticRole.METRIC}].forEach((e=>{var{set:t}=e,n=__rest(e,["set"]);return addMeaning(makeMultiInterval(t),n)}))}function addFences(e,t,n=1){const r={},i=makeCodeInterval(t);for(const t of i)r[t]||(e.set(String.fromCodePoint(t),String.fromCodePoint(t+n)),r[t]=!0,r[t+n]=!0)}function initFences(){addFences(SemanticMap.FencesVert,["23b4",["23dc","23e1"],["fe35","fe44"],"fe47"]),addFences(SemanticMap.FencesHoriz,["28","2045",["2308","230f"],["231c","231f"],"2329","23b0",["2768","2775"],"27c5",["27e6","27ef"],["2983","2998"],["29d8","29db"],"29fc",["2e22","2e29"],["3008","3011"],["3014","301b"],"fd3e","fe17",["fe59","fe5e"],"ff08","ff5f","ff62"]),addFences(SemanticMap.FencesHoriz,["5b","7b","ff3b","ff5b"],2),addFences(SemanticMap.FencesHoriz,[["239b","23a6"]],3),addFences(SemanticMap.FencesHoriz,[["23a7","23a9"]],4),addMeaning([...SemanticMap.FencesHoriz.keys()],{type:SemanticType.FENCE,role:SemanticRole.OPEN}),addMeaning([...SemanticMap.FencesHoriz.values()],{type:SemanticType.FENCE,role:SemanticRole.CLOSE}),addMeaning([...SemanticMap.FencesVert.keys()],{type:SemanticType.FENCE,role:SemanticRole.TOP}),addMeaning([...SemanticMap.FencesVert.values()],{type:SemanticType.FENCE,role:SemanticRole.BOTTOM})}const trigonometricFunctions=["cos","cot","csc","sec","sin","tan","arccos","arccot","arccsc","arcsec","arcsin","arctan"],hyperbolicFunctions=["cosh","coth","csch","sech","sinh","tanh","arcosh","arcoth","arcsch","arsech","arsinh","artanh"],algebraicFunctions=["deg","det","dim","hom","ker","Tr"],elementaryFunctions=["log","ln","lg","exp","gcd","lcm","arg","im","re","Pr"],prefixFunctions=trigonometricFunctions.concat(hyperbolicFunctions,algebraicFunctions,elementaryFunctions);function initFunctions(){addMeaning(["inf","lim","liminf","limsup","max","min","sup","injlim","projlim"],{type:SemanticType.FUNCTION,role:SemanticRole.LIMFUNC}),addMeaning(prefixFunctions,{type:SemanticType.FUNCTION,role:SemanticRole.PREFIXFUNC}),addMeaning(["mod","rem"],{type:SemanticType.OPERATOR,role:SemanticRole.PREFIXFUNC})}function addFunctionSemantic(e,t){addMeaning(t,SemanticMap.Meaning.get(e)||{type:SemanticType.FUNCTION,role:SemanticRole.PREFIXFUNC})}function equal(e,t){return e.type===t.type&&e.role===t.role&&e.font===t.font}function isMatchingFence(e,t){const n=SemanticMap.Meaning.get(e);return n.type===SemanticType.FENCE&&(n.role===SemanticRole.NEUTRAL||n.role===SemanticRole.METRIC?e===t:SemanticMap.FencesHoriz.get(e)===t||SemanticMap.FencesVert.get(e)===t)}function changeSemantics(e,t){for(const[n,r]of Object.entries(t)){const t=e[n];void 0!==t&&SemanticMap.Meaning.set(t,r)}}function addSecondaries(e,t){for(const[n,r]of Object.entries(t)){const t=e[n];void 0!==t&&SemanticMap.Secondary.set(t,r)}}function singleAlphabet(e,t,n,r,i,s=[],o={},a={}){const c=INTERVALS.get(alphabetName(e,r));c&&(c.unicode.forEach((e=>{SemanticMap.Meaning.set(e,{type:t,role:n,font:i}),s.forEach((t=>SemanticMap.Secondary.set(e,t)))})),changeSemantics(c.unicode,o),addSecondaries(c.unicode,a))}function initAlphabets(){for(const[e,t]of Object.entries(SemanticFont)){const n=!!Embellish[e]?SemanticFont.UNKNOWN:t===SemanticFont.FULLWIDTH?SemanticFont.NORMAL:t;singleAlphabet(Base.LATINCAP,SemanticType.IDENTIFIER,SemanticRole.LATINLETTER,t,n,[SemanticSecondary.ALLLETTERS]),singleAlphabet(Base.LATINSMALL,SemanticType.IDENTIFIER,SemanticRole.LATINLETTER,t,n,[SemanticSecondary.ALLLETTERS],{},{3:SemanticSecondary.D}),singleAlphabet(Base.GREEKCAP,SemanticType.IDENTIFIER,SemanticRole.GREEKLETTER,t,n,[SemanticSecondary.ALLLETTERS]),singleAlphabet(Base.GREEKSMALL,SemanticType.IDENTIFIER,SemanticRole.GREEKLETTER,t,n,[SemanticSecondary.ALLLETTERS],{0:{type:SemanticType.OPERATOR,role:SemanticRole.PREFIXOP,font:n},26:{type:SemanticType.OPERATOR,role:SemanticRole.PREFIXOP,font:n}}),singleAlphabet(Base.DIGIT,SemanticType.NUMBER,SemanticRole.INTEGER,t,n)}}initMeaning(),initFences(),initAlphabets(),initFunctions();class MathSimpleStore{constructor(){this.rules=new Map}static parseUnicode(e){const t=parseInt(e,16);return String.fromCodePoint(t)}static testDynamicConstraints_(e,t){return engine_Engine.getInstance().strict?t.cstr.equal(e):engine_Engine.getInstance().comparator.match(t.cstr)}defineRulesFromMappings(e,t,n){for(const[r,i]of Object.entries(n))for(const[n,s]of Object.entries(i))this.defineRuleFromStrings(e,t,r,n,s)}getRules(e){let t=this.rules.get(e);return t||(t=[],this.rules.set(e,t)),t}defineRuleFromStrings(e,t,n,r,i){let s=this.getRules(e);const o=engine_Engine.getInstance().parsers[n]||engine_Engine.getInstance().defaultParser,a=engine_Engine.getInstance().comparators[n],c=`${e}.${t}.${n}.${r}`,l=o.parse(c),u=a?a():engine_Engine.getInstance().comparator,m=u.getReference();u.setReference(l);const d={cstr:l,action:i};s=s.filter((e=>!l.equal(e.cstr))),s.push(d),this.rules.set(e,s),u.setReference(m)}lookupRule(e,t){let n=this.getRules(t.getValue(Axis.LOCALE));return n=n.filter((function(e){return MathSimpleStore.testDynamicConstraints_(t,e)})),1===n.length?n[0]:n.length?n.sort(((e,t)=>engine_Engine.getInstance().comparator.compare(e.cstr,t.cstr)))[0]:null}}let math_compound_store_locale=DynamicCstr.DEFAULT_VALUES[Axis.LOCALE],modality=DynamicCstr.DEFAULT_VALUES[Axis.MODALITY];function changeLocale(e){return!(!e.locale&&!e.modality)&&(math_compound_store_locale=e.locale||math_compound_store_locale,modality=e.modality||modality,!0)}let siPrefixes={};function setSiPrefixes(e){siPrefixes=e}const subStores=new Map,baseStores=new Map;function getSubStore(e,t){let n=subStores.get(t);return n||(n=new MathSimpleStore,n.base=baseStores.get(e),subStores.set(t,n),n)}function completeWithBase(e){const t=baseStores.get(e.key);if(!t)return;const n=e.names;Object.assign(e,t),n&&t.names&&(e.names=e.names.concat(n))}function defineRules(e,t,n){getSubStore(e,t).defineRulesFromMappings(math_compound_store_locale,modality,n)}function defineRule(e,t,n,r){getSubStore(n,n).defineRuleFromStrings(math_compound_store_locale,modality,e,t,r)}function addSymbolRules(e){for(const t of e){if(changeLocale(t))continue;const e=MathSimpleStore.parseUnicode(t.key);"base"!==math_compound_store_locale?defineRules(e,e,t.mappings):baseStores.set(e,t)}}function addCharacterRule(e){if(!changeLocale(e))for(const[t,n]of Object.entries(e))defineRule("default","default",t,n)}const addCharacterRules=e=>e.forEach(addCharacterRule);function addFunctionRule(e){for(let t,n=0;t=e.names[n];n++)defineRules(e.key,t,e.mappings)}function addFunctionRules(e){for(const t of e)changeLocale(t)||(addFunctionSemantic(t.key,t.names||[]),"base"!==math_compound_store_locale?(completeWithBase(t),addFunctionRule(t)):baseStores.set(t.key,t))}function addUnitRules(e){for(const t of e)changeLocale(t)||(t.key+=":unit","base"!==math_compound_store_locale?(completeWithBase(t),t.names&&(t.names=t.names.map((function(e){return e+":unit"}))),t.si&&addSiUnitRule(t),addFunctionRule(t)):baseStores.set(t.key,t))}function addSiUnitRule(e){for(const t of Object.keys(siPrefixes)){const n=Object.assign({},e);n.mappings={};const r=siPrefixes[t];n.names=n.names.map((function(e){return t+e}));for(const t of Object.keys(e.mappings)){n.mappings[t]={};for(const i of Object.keys(e.mappings[t]))n.mappings[t][i]=locales[math_compound_store_locale]().FUNCTIONS.si(r,e.mappings[t][i])}addFunctionRule(n)}}function lookupRule(e,t){const n=subStores.get(e);return n?n.lookupRule(null,t):null}function lookupCategory(e){const t=subStores.get(e);return(null==t?void 0:t.base)?t.base.category:""}function lookupString(e,t){const n=lookupRule(e,t);return n?n.action:null}function enumerate(e={}){for(const t of subStores.values())for(const[,n]of t.rules.entries())for(const{cstr:t}of n)e=enumerate_(t.getValues(),e);return e}function enumerate_(e,t){return t=t||{},e.length?(t[e[0]]=enumerate_(e.slice(1),t[e[0]]),t):t}function math_compound_store_reset(){math_compound_store_locale=DynamicCstr.DEFAULT_VALUES[Axis.LOCALE],modality=DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]}engine_Engine.getInstance().evaluator=lookupString;class Span{constructor(e,t){this.speech=e,this.attributes=t}static empty(){return new Span("",{})}static stringEmpty(e){return new Span(e,{})}static stringAttr(e,t){return new Span(e,t)}static singleton(e,t={}){return[Span.stringAttr(e,t)]}static node(e,t,n={}){const r=Span.getAttributes(t);return Object.assign(r,n),new Span(e,r)}static getAttributes(e){const t={};for(const n of Span.attributeList)e.hasAttribute(n)&&(t[n]=e.getAttribute(n));return t}}Span.attributeList=["id","extid"];class AuditoryItem{constructor(e=null){this.data=e,this.prev=null,this.next=null}}class AuditoryList extends Set{constructor(e){super(),this.annotations=[],this.anchor=new AuditoryItem,this.anchor.next=this.anchor,this.anchor.prev=this.anchor,e.forEach((e=>{const t=new AuditoryItem(e);e.annotation&&this.annotations.push(t),this.push(t)}))}first(){return this.empty?null:this.anchor.next}last(){return this.empty?null:this.anchor.prev}push(e){e.next=this.anchor,e.prev=this.anchor.prev,e.prev.next=e,this.anchor.prev=e,super.add(e)}pop(){const e=this.last();return e?(this.delete(e),e):null}delete(e){return!!this.has(e)&&(super.delete(e),e.prev.next=e.next,e.next=e.prev,!0)}insertAfter(e,t){this.insertBefore(e,t.next)}insertBefore(e,t){const n=new AuditoryItem(e);t&&this.has(t)?(t.prev.next=n,n.prev=t.prev,n.next=t,t.prev=n):this.push(n)}prevText(e){do{e=e.prev}while(e!==this.anchor&&!e.data.text);return e===this.anchor?null:e}*[Symbol.iterator](){let e=this.anchor.next;for(;e!==this.anchor;)yield e,e=e.next}nextText(e){for(;e!==this.anchor&&!e.data.text;)e=e.next;return e}clear(){this.anchor.next=this.anchor,this.anchor.prev=this.anchor,super.clear()}empty(){return this.anchor.prev===this.anchor&&this.anchor===this.anchor.next}toList(){const e=[];let t=this.anchor.next;for(;t!==this.anchor;)e.push(t.data),t=t.next;return e}}class AuditoryDescription{static create(e,t={}){return e.text=Grammar.getInstance().apply(e.text,t),new AuditoryDescription(e)}constructor({context:e,text:t,userValue:n,annotation:r,attributes:i,personality:s,layout:o}){this.context=e||"",this.text=t||"",this.userValue=n||"",this.annotation=r||"",this.attributes=i||{},this.personality=s||{},this.layout=o||""}isEmpty(){return 0===this.context.length&&0===this.text.length&&0===this.userValue.length&&0===this.annotation.length}clone(){let e,t;if(this.personality){e={};for(const[t,n]of Object.entries(this.personality))e[t]=n}if(this.attributes){t={};for(const[e,n]of Object.entries(this.attributes))t[e]=n}return new AuditoryDescription({context:this.context,text:this.text,userValue:this.userValue,annotation:this.annotation,personality:e,attributes:t,layout:this.layout})}toString(){return'AuditoryDescription(context="'+this.context+'" text="'+this.text+'" userValue="'+this.userValue+'" annotation="'+this.annotation+'")'}descriptionString(){return this.context&&this.text?this.context+" "+this.text:this.context||this.text}descriptionSpan(){return Span.stringAttr(this.descriptionString(),this.attributes)}equals(e){return this.context===e.context&&this.text===e.text&&this.userValue===e.userValue&&this.annotation===e.annotation}}const funcStore=new Map;function addStore(e,t,n){const r={};if(t){const e=funcStore.get(t)||{};Object.assign(r,e)}funcStore.set(e,Object.assign(r,n))}function getStore(e,t,n){return funcStore.get([e,t,n].join("."))||funcStore.get([DynamicCstr.DEFAULT_VALUES[Axis.LOCALE],t,n].join("."))||funcStore.get([DynamicCstr.BASE_LOCALE,t,n].join("."))||{}}function nodeCounter(e,t){const n=e.length;let r=0,i=t;return t||(i=""),function(){return r<n&&(r+=1),i+" "+r}}function pauseSeparator(e,t){const n=parseFloat(t),r=isNaN(n)?t:n;return function(){return[AuditoryDescription.create({text:"",personality:{pause:r}})]}}function contentIterator(e,t){let n;return n=e.length>0?evalXPath("../../content/*",e[0]):[],function(){const e=n.shift(),r=t?[AuditoryDescription.create({text:t},{translate:!0})]:[];if(!e)return r;const i=engine_Engine.evaluateNode(e);return r.concat(i)}}class SemanticAnnotator{constructor(e,t,n){this.domain=e,this.name=t,this.func=n,this.active=!1}annotate(e){e.childNodes.forEach(this.annotate.bind(this)),e.contentNodes.forEach(this.annotate.bind(this)),e.addAnnotation(this.domain,this.func(e))}}class SemanticVisitor{constructor(e,t,n,r={}){this.domain=e,this.name=t,this.func=n,this.def=r,this.active=!1}visit(e,t){let n=this.func(e,t);e.addAnnotation(this.domain,n[0]);for(let t,r=0;t=e.childNodes[r];r++)n=this.visit(t,n[1]);for(let t,r=0;t=e.contentNodes[r];r++)n=this.visit(t,n[1]);return n}}const annotators=new Map,visitors=new Map;function register(e){const t=e.domain+":"+e.name;e instanceof SemanticAnnotator?annotators.set(t,e):visitors.set(t,e)}function activate(e,t){const n=e+":"+t,r=annotators.get(n)||visitors.get(n);r&&(r.active=!0)}function deactivate(e,t){const n=e+":"+t,r=annotators.get(n)||visitors.get(n);r&&(r.active=!1)}function annotate(e){for(const t of annotators.values())t.active&&t.annotate(e);for(const t of visitors.values())t.active&&t.visit(e,Object.assign({},t.def))}function clearspeak_util_nodeCounter(e,t){const n=t.split("-"),r=nodeCounter(e,n[0]||""),i=n[1]||"",s=n[2]||"";let o=!0;return function(){const e=r();return o?(o=!1,s+e+i):e+i}}function isSimpleExpression(e){return isSimpleNumber_(e)||isSimpleLetters_(e)||isSimpleDegree_(e)||isSimpleNegative_(e)||isSimpleFunction_(e)}function isSimpleFunction_(e){return e.type===SemanticType.APPL&&(e.childNodes[0].role===SemanticRole.PREFIXFUNC||e.childNodes[0].role===SemanticRole.SIMPLEFUNC)&&(isSimple_(e.childNodes[1])||e.childNodes[1].type===SemanticType.FENCED&&isSimple_(e.childNodes[1].childNodes[0]))}function isSimpleNegative_(e){return e.type===SemanticType.PREFIXOP&&e.role===SemanticRole.NEGATIVE&&isSimple_(e.childNodes[0])&&e.childNodes[0].type!==SemanticType.PREFIXOP&&e.childNodes[0].type!==SemanticType.APPL&&e.childNodes[0].type!==SemanticType.PUNCTUATED}function isSimpleDegree_(e){return e.type===SemanticType.PUNCTUATED&&e.role===SemanticRole.ENDPUNCT&&2===e.childNodes.length&&e.childNodes[1].role===SemanticRole.DEGREE&&(isLetter_(e.childNodes[0])||isNumber_(e.childNodes[0])||e.childNodes[0].type===SemanticType.PREFIXOP&&e.childNodes[0].role===SemanticRole.NEGATIVE&&(isLetter_(e.childNodes[0].childNodes[0])||isNumber_(e.childNodes[0].childNodes[0])))}function isSimpleLetters_(e){return isLetter_(e)||e.type===SemanticType.INFIXOP&&e.role===SemanticRole.IMPLICIT&&(2===e.childNodes.length&&(isLetter_(e.childNodes[0])||isSimpleNumber_(e.childNodes[0]))&&isLetter_(e.childNodes[1])||3===e.childNodes.length&&isSimpleNumber_(e.childNodes[0])&&isLetter_(e.childNodes[1])&&isLetter_(e.childNodes[2]))}function isSimple_(e){return e.hasAnnotation("clearspeak","simple")}function isLetter_(e){return e.type===SemanticType.IDENTIFIER&&(e.role===SemanticRole.LATINLETTER||e.role===SemanticRole.GREEKLETTER||e.role===SemanticRole.OTHERLETTER||e.role===SemanticRole.SIMPLEFUNC)}function isNumber_(e){return e.type===SemanticType.NUMBER&&(e.role===SemanticRole.INTEGER||e.role===SemanticRole.FLOAT)}function isSimpleNumber_(e){return isNumber_(e)||isSimpleFraction_(e)}function isSimpleFraction_(e){if(hasPreference("Fraction_Over")||hasPreference("Fraction_FracOver"))return!1;if(e.type!==SemanticType.FRACTION||e.role!==SemanticRole.VULGAR)return!1;if(hasPreference("Fraction_Ordinal"))return!0;const t=parseInt(e.childNodes[0].textContent,10),n=parseInt(e.childNodes[1].textContent,10);return t>0&&t<20&&n>0&&n<11}function hasPreference(e){return engine_Engine.getInstance().style===e}function simpleNode(e){if(!e.hasAttribute("annotation"))return!1;const t=e.getAttribute("annotation");return!!/clearspeak:simple$|clearspeak:simple;/.exec(t)}function simpleCell_(e){if(simpleNode(e))return!0;if(e.tagName!==SemanticType.SUBSCRIPT)return!1;const t=e.childNodes[0].childNodes,n=t[1];return t[0].tagName===SemanticType.IDENTIFIER&&(isInteger_(n)||n.tagName===SemanticType.INFIXOP&&n.hasAttribute("role")&&n.getAttribute("role")===SemanticRole.IMPLICIT&&allIndices_(n))}function isInteger_(e){return e.tagName===SemanticType.NUMBER&&e.hasAttribute("role")&&e.getAttribute("role")===SemanticRole.INTEGER}function allIndices_(e){return evalXPath("children/*",e).every((e=>isInteger_(e)||e.tagName===SemanticType.IDENTIFIER))}function allCellsSimple(e){return evalXPath(e.tagName===SemanticType.MATRIX?"children/row/children/cell/children/*":"children/line/children/*",e).every(simpleCell_)?[e]:[]}function isSmallVulgarFraction(e){return vulgarFractionSmall(e,20,11)?[e]:[]}function isUnitExpression(e){return e.type===SemanticType.TEXT&&e.role!==SemanticRole.LABEL||e.type===SemanticType.PUNCTUATED&&e.role===SemanticRole.TEXT&&isNumber_(e.childNodes[0])&&allTextLastContent_(e.childNodes.slice(1))||e.type===SemanticType.IDENTIFIER&&e.role===SemanticRole.UNIT||e.type===SemanticType.INFIXOP&&(e.role===SemanticRole.IMPLICIT||e.role===SemanticRole.UNIT)}function allTextLastContent_(e){for(let t=0;t<e.length-1;t++)if(e[t].type!==SemanticType.TEXT||""!==e[t].textContent)return!1;return e[e.length-1].type===SemanticType.TEXT}function ordinalExponent(e){const t=parseInt(e.textContent,10);return[Span.stringEmpty(isNaN(t)?e.textContent:t>10?LOCALE.NUMBERS.numericOrdinal(t):LOCALE.NUMBERS.wordOrdinal(t))]}register(new SemanticAnnotator("clearspeak","simple",(function(e){return isSimpleExpression(e)?"simple":""}))),register(new SemanticAnnotator("clearspeak","unit",(function(e){return isUnitExpression(e)?"unit":""})));let NESTING_DEPTH=null;function nestingDepth(e){let t=0;const n=e.textContent,r="open"===e.getAttribute("role")?0:1;let i=e.parentNode;for(;i;)i.tagName===SemanticType.FENCED&&i.childNodes[0].childNodes[r].textContent===n&&t++,i=i.parentNode;return NESTING_DEPTH=t>1?LOCALE.NUMBERS.wordOrdinal(t):"",[Span.stringEmpty(NESTING_DEPTH)]}function matchingFences(e){const t=e.previousSibling;let n,r;return t?(n=t,r=e):(n=e,r=e.nextSibling),r&&isMatchingFence(n.textContent,r.textContent)?[e]:[]}function insertNesting(e,t){if(!t||!e)return e;const n=e.match(/^(open|close) /);return n?n[0]+t+" "+e.substring(n[0].length):t+" "+e}function fencedArguments(e){const t=toArray(e.parentNode.childNodes),n=evalXPath("../../children/*",e),r=t.indexOf(e);return fencedFactor_(n[r])||fencedFactor_(n[r+1])?[e]:[]}function simpleArguments(e){const t=toArray(e.parentNode.childNodes),n=evalXPath("../../children/*",e),r=t.indexOf(e);return simpleFactor_(n[r])&&n[r+1]&&(simpleFactor_(n[r+1])||n[r+1].tagName===SemanticType.ROOT||n[r+1].tagName===SemanticType.SQRT||n[r+1].tagName===SemanticType.SUPERSCRIPT&&n[r+1].childNodes[0].childNodes[0]&&(n[r+1].childNodes[0].childNodes[0].tagName===SemanticType.NUMBER||n[r+1].childNodes[0].childNodes[0].tagName===SemanticType.IDENTIFIER)&&("2"===n[r+1].childNodes[0].childNodes[1].textContent||"3"===n[r+1].childNodes[0].childNodes[1].textContent))?[e]:[]}function simpleFactor_(e){return!!e&&(e.tagName===SemanticType.NUMBER||e.tagName===SemanticType.IDENTIFIER||e.tagName===SemanticType.FUNCTION||e.tagName===SemanticType.APPL||e.tagName===SemanticType.FRACTION)}function fencedFactor_(e){return e&&(e.tagName===SemanticType.FENCED||e.hasAttribute("role")&&e.getAttribute("role")===SemanticRole.LEFTRIGHT||layoutFactor_(e))}function layoutFactor_(e){return!!e&&(e.tagName===SemanticType.MATRIX||e.tagName===SemanticType.VECTOR)}function clearspeak_util_wordOrdinal(e){return[Span.stringEmpty(LOCALE.NUMBERS.wordOrdinal(parseInt(e.textContent,10)))]}function removeEmpty(e){return e.filter((e=>e))}function interleaveLists(e,t){const n=[];for(;e.length||t.length;)e.length&&n.push(e.shift()),t.length&&n.push(t.shift());return n}function setdifference(e,t){return e?t?e.filter((e=>t.indexOf(e)<0)):e:[]}Grammar.getInstance().setCorrection("insertNesting",insertNesting);const SemanticHeuristics={factory:null,updateFactory:function(e){SemanticHeuristics.factory=e},heuristics:new Map,flags:{combine_juxtaposition:!0,convert_juxtaposition:!0,multioperator:!0},blacklist:{},add:function(e){const t=e.name;SemanticHeuristics.heuristics.set(t,e),SemanticHeuristics.flags[t]||(SemanticHeuristics.flags[t]=!1)},run:function(e,t,n){const r=SemanticHeuristics.heuristics.get(e);return r&&!SemanticHeuristics.blacklist[e]&&(SemanticHeuristics.flags[e]||r.applicable(t))?r.apply(t):n?n(t):t}},comparators=[];function add(e){comparators.push(e)}function apply(e,t){for(let n,r=0;n=comparators[r];r++){const r=n.compare(e,t);if(0!==r)return r}return 0}function sort(e){e.sort(apply)}function reduce(e){if(e.length<=1)return e;const t=e.slice();sort(t);const n=[];let r;do{r=t.pop(),n.push(r)}while(r&&t.length&&0===apply(t[t.length-1],r));return n}class SemanticComparator{constructor(e,t=null){this.comparator=e,this.type=t,add(this)}compare(e,t){return this.type&&this.type===e.type&&this.type===t.type?this.comparator(e,t):0}}function simpleFunction(e,t){return e.role===SemanticRole.SIMPLEFUNC?1:t.role===SemanticRole.SIMPLEFUNC?-1:0}function key(e,t){return e.match(/^.+:.+$/)||!t?e:e+":"+t}new SemanticComparator(simpleFunction,SemanticType.IDENTIFIER);class SemanticDefault extends Map{set(e,t){return super.set(key(e,t.font),t),this}setNode(e){this.set(e.textContent,e.meaning())}get(e,t=null){return super.get(key(e,t))}getNode(e){return this.get(e.textContent,e.font)}}class SemanticCollator extends Map{add(e,t){const n=this.get(e);n?n.push(t):super.set(e,[t])}get(e,t=null){return super.get(key(e,t))}getNode(e){return this.get(e.textContent,e.font)}minimize(){for(const[e,t]of this)1===t.length&&this.delete(e)}isMultiValued(){for(const e of this.values())if(e.length>1)return!0;return!1}}class SemanticNodeCollator extends SemanticCollator{add(e,t){super.add(key(e,t.font),t)}addNode(e){this.add(e.textContent,e)}toString(){const e=[];for(const[t,n]of this){const r=Array(t.length+3).join(" "),i=n.map((e=>e.toString())).join("\n"+r);e.push(t+": "+i)}return e.join("\n")}collateMeaning(){const e=new SemanticMeaningCollator;for(const[t,n]of this)e.set(t,n.map((e=>e.meaning())));return e}}class SemanticMeaningCollator extends SemanticCollator{add(e,t){const n=this.get(e,t.font);n&&n.find((function(e){return equal(e,t)}))||super.add(key(e,t.font),t)}addNode(e){this.add(e.textContent,e.meaning())}toString(){const e=[];for(const[t,n]of this){const r=Array(t.length+3).join(" "),i=n.map((e=>`{type: ${e.type}, role: ${e.role}, font: ${e.font}}`)).join("\n"+r);e.push(t+": "+i)}return e.join("\n")}reduce(){for(const[e,t]of this)1!==t.length&&this.set(e,reduce(t))}default(){const e=new SemanticDefault;for(const[t,n]of this)1===n.length&&e.set(t,n[0]);return e}newDefault(){const e=this.default();this.reduce();const t=this.default();return e.size!==t.size?t:null}}var MMLTAGS;!function(e){e.ANNOTATION="ANNOTATION",e.ANNOTATIONXML="ANNOTATION-XML",e.MACTION="MACTION",e.MALIGNGROUP="MALIGNGROUP",e.MALIGNMARK="MALIGNMARK",e.MATH="MATH",e.MENCLOSE="MENCLOSE",e.MERROR="MERROR",e.MFENCED="MFENCED",e.MFRAC="MFRAC",e.MGLYPH="MGLYPH",e.MI="MI",e.MLABELEDTR="MLABELEDTR",e.MMULTISCRIPTS="MMULTISCRIPTS",e.MN="MN",e.MO="MO",e.MOVER="MOVER",e.MPADDED="MPADDED",e.MPHANTOM="MPHANTOM",e.MPRESCRIPTS="MPRESCRIPTS",e.MROOT="MROOT",e.MROW="MROW",e.MS="MS",e.MSPACE="MSPACE",e.MSQRT="MSQRT",e.MSTYLE="MSTYLE",e.MSUB="MSUB",e.MSUBSUP="MSUBSUP",e.MSUP="MSUP",e.MTABLE="MTABLE",e.MTD="MTD",e.MTEXT="MTEXT",e.MTR="MTR",e.MUNDER="MUNDER",e.MUNDEROVER="MUNDEROVER",e.NONE="NONE",e.SEMANTICS="SEMANTICS"}(MMLTAGS||(MMLTAGS={}));const ALLTAGS=Object.values(MMLTAGS),LEAFTAGS=[MMLTAGS.MO,MMLTAGS.MI,MMLTAGS.MN,MMLTAGS.MTEXT,MMLTAGS.MS,MMLTAGS.MSPACE],IGNORETAGS=[MMLTAGS.MERROR,MMLTAGS.MPHANTOM,MMLTAGS.MALIGNGROUP,MMLTAGS.MALIGNMARK,MMLTAGS.MPRESCRIPTS,MMLTAGS.ANNOTATION,MMLTAGS.ANNOTATIONXML],EMPTYTAGS=[MMLTAGS.MATH,MMLTAGS.MROW,MMLTAGS.MPADDED,MMLTAGS.MACTION,MMLTAGS.NONE,MMLTAGS.MSTYLE,MMLTAGS.SEMANTICS],DISPLAYTAGS=[MMLTAGS.MROOT,MMLTAGS.MSQRT],directSpeechKeys=["aria-label","exact-speech","alt"];function hasMathTag(e){return!!e&&dom_util_tagName(e)===MMLTAGS.MATH}function hasLeafTag(e){return!!e&&LEAFTAGS.includes(dom_util_tagName(e))}function hasIgnoreTag(e){return!!e&&(IGNORETAGS.includes(dom_util_tagName(e))||!ALLTAGS.includes(dom_util_tagName(e)))}function hasEmptyTag(e){return!!e&&EMPTYTAGS.includes(dom_util_tagName(e))}function hasDisplayTag(e){return!!e&&DISPLAYTAGS.includes(dom_util_tagName(e))}function isOrphanedGlyph(e){return!!e&&dom_util_tagName(e)===MMLTAGS.MGLYPH&&!hasLeafTag(e.parentNode)}function purgeNodes(e){const t=[];for(let n,r=0;n=e[r];r++){if(n.nodeType!==NodeType.ELEMENT_NODE)continue;const e=dom_util_tagName(n);IGNORETAGS.includes(e)||(EMPTYTAGS.includes(e)&&0===n.childNodes.length||t.push(n))}return t}function isZeroLength(e){if(!e)return!1;if(["negativeveryverythinmathspace","negativeverythinmathspace","negativethinmathspace","negativemediummathspace","negativethickmathspace","negativeverythickmathspace","negativeveryverythickmathspace"].includes(e))return!0;const t=e.match(/[0-9.]+/);return!!t&&0===parseFloat(t[0])}function addAttributes(e,t){if(t.hasAttributes()){const n=t.attributes;for(let t=n.length-1;t>=0;t--){const r=n[t].name;r.match(/^ext/)&&(e.attributes[r]=n[t].value,e.nobreaking=!0),directSpeechKeys.includes(r)&&(e.attributes["ext-speech"]=n[t].value,e.nobreaking=!0),r.match(/texclass$/)&&(e.attributes.texclass=n[t].value),"data-latex"===r.toLowerCase()&&(e.attributes.latex=n[t].value),"href"===r&&(e.attributes.href=n[t].value,e.nobreaking=!0)}}}function getEmbellishedInner(e){return e&&e.embellished&&e.childNodes.length>0?getEmbellishedInner(e.childNodes[0]):e}function sliceNodes(e,t,n){n&&e.reverse();const r=[];for(let i,s=0;i=e[s];s++){if(t(i))return n?{head:e.slice(s+1).reverse(),div:i,tail:r.reverse()}:{head:r,div:i,tail:e.slice(s+1)};r.push(i)}return n?{head:[],div:null,tail:r.reverse()}:{head:r,div:null,tail:[]}}function partitionNodes(e,t){let n=e;const r=[],i=[];let s=null;do{s=sliceNodes(n,t),i.push(s.head),r.push(s.div),n=s.tail}while(s.div);return r.pop(),{rel:r,comp:i}}class SemanticNode{static fromXml(e){const t=parseInt(e.getAttribute("id"),10),n=new SemanticNode(t);return n.type=e.tagName,SemanticNode.setAttribute(n,e,"role"),SemanticNode.setAttribute(n,e,"font"),SemanticNode.setAttribute(n,e,"embellished"),SemanticNode.setAttribute(n,e,"fencepointer","fencePointer"),e.getAttribute("annotation")&&n.parseAnnotation(e.getAttribute("annotation")),addAttributes(n,e),SemanticNode.processChildren(n,e),n}static setAttribute(e,t,n,r){r=r||n;const i=t.getAttribute(n);i&&(e[r]=i)}static processChildren(e,t){for(const n of toArray(t.childNodes)){if(n.nodeType===NodeType.TEXT_NODE){e.textContent=n.textContent;continue}const t=toArray(n.childNodes).map(SemanticNode.fromXml);t.forEach((t=>t.parent=e)),"CONTENT"===dom_util_tagName(n)?e.contentNodes=t:e.childNodes=t}}constructor(e){this.id=e,this.mathml=[],this.parent=null,this.type=SemanticType.UNKNOWN,this.role=SemanticRole.UNKNOWN,this.font=SemanticFont.UNKNOWN,this.embellished=null,this.fencePointer="",this.childNodes=[],this.textContent="",this.mathmlTree=null,this.contentNodes=[],this.annotation={},this.attributes={},this.nobreaking=!1}querySelectorAll(e){let t=[];for(let n,r=0;n=this.childNodes[r];r++)t=t.concat(n.querySelectorAll(e));for(let n,r=0;n=this.contentNodes[r];r++)t=t.concat(n.querySelectorAll(e));return e(this)&&t.unshift(this),t}xml(e,t){const n=function(n,r){const i=r.map((function(n){return n.xml(e,t)})),s=e.createElementNS("",n);for(let e,t=0;e=i[t];t++)s.appendChild(e);return s},r=e.createElementNS("",this.type);return t||this.xmlAttributes(r),r.textContent=this.textContent,this.contentNodes.length>0&&r.appendChild(n("content",this.contentNodes)),this.childNodes.length>0&&r.appendChild(n("children",this.childNodes)),r}toString(e=!1){const t=parseInput("<snode/>");return serializeXml(this.xml(t.ownerDocument,e))}allAttributes(){const e=[];return e.push(["role",this.role]),this.font!==SemanticFont.UNKNOWN&&e.push(["font",this.font]),Object.keys(this.annotation).length&&e.push(["annotation",this.annotationXml()]),this.embellished&&e.push(["embellished",this.embellished]),this.fencePointer&&e.push(["fencepointer",this.fencePointer]),e.push(["id",this.id.toString()]),e}annotationXml(){const e=[];for(const[t,n]of Object.entries(this.annotation))n.forEach((n=>e.push(t+":"+n)));return e.join(";")}attributesXml(){const e=[];for(const[t,n]of Object.entries(this.attributes))e.push(t+":"+SemanticNode.escapeValue(n));return e.join(";")}toJson(){const e={};e.type=this.type;const t=this.allAttributes();for(let n,r=0;n=t[r];r++)e[n[0]]=n[1].toString();return this.textContent&&(e.$t=this.textContent),this.childNodes.length&&(e.children=this.childNodes.map((function(e){return e.toJson()}))),this.contentNodes.length&&(e.content=this.contentNodes.map((function(e){return e.toJson()}))),e}updateContent(e,t){const n=t?e.replace(/^[ \f\n\r\t\v\u200b]*/,"").replace(/[ \f\n\r\t\v\u200b]*$/,""):e.trim();if(e=e&&!n?e:n,this.textContent===e)return;const r=SemanticMap.Meaning.get(e.replace(/\s/g," "));this.textContent=e,this.role=r.role,this.type=r.type,this.font=r.font}addMathmlNodes(e){for(let t,n=0;t=e[n];n++)-1===this.mathml.indexOf(t)&&this.mathml.push(t)}appendChild(e){this.childNodes.push(e),this.addMathmlNodes(e.mathml),e.parent=this}replaceChild(e,t){const n=this.childNodes.indexOf(e);if(-1===n)return;e.parent=null,t.parent=this,this.childNodes[n]=t;const r=e.mathml.filter((function(e){return-1===t.mathml.indexOf(e)})),i=t.mathml.filter((function(t){return-1===e.mathml.indexOf(t)}));this.removeMathmlNodes(r),this.addMathmlNodes(i)}appendContentNode(e){e&&(this.contentNodes.push(e),this.addMathmlNodes(e.mathml),e.parent=this)}removeContentNode(e){if(e){const t=this.contentNodes.indexOf(e);-1!==t&&this.contentNodes.slice(t,1)}}equals(e){if(!e)return!1;if(this.type!==e.type||this.role!==e.role||this.textContent!==e.textContent||this.childNodes.length!==e.childNodes.length||this.contentNodes.length!==e.contentNodes.length)return!1;for(let t,n,r=0;t=this.childNodes[r],n=e.childNodes[r];r++)if(!t.equals(n))return!1;for(let t,n,r=0;t=this.contentNodes[r],n=e.contentNodes[r];r++)if(!t.equals(n))return!1;return!0}displayTree(){console.info(this.displayTree_(0))}addAnnotation(e,t){t&&this.addAnnotation_(e,t)}getAnnotation(e){const t=this.annotation[e];return t||[]}hasAnnotation(e,t){const n=this.annotation[e];return!!n&&-1!==n.indexOf(t)}parseAnnotation(e){const t=e.split(";");for(let e=0,n=t.length;e<n;e++){const n=t[e].split(":");this.addAnnotation(n[0],n[1])}}meaning(){return{type:this.type,role:this.role,font:this.font}}xmlAttributes(e){const t=this.allAttributes();for(let n,r=0;n=t[r];r++)e.setAttribute(n[0],n[1]);this.addExternalAttributes(e)}addExternalAttributes(e){for(const[t,n]of Object.entries(this.attributes))e.setAttribute(t,n)}static escapeValue(e){return e.replace(/;/g,"\\0003B")}parseAttributes(e){if(!e)return;const t=e.split(";");for(let e=0,n=t.length;e<n;e++){const[n,...r]=t[e].split(":");n&&(this.attributes[n]=r.join("").replace(/\\0003B/g,";"))}}removeMathmlNodes(e){const t=this.mathml;for(let n,r=0;n=e[r];r++){const e=t.indexOf(n);-1!==e&&t.splice(e,1)}this.mathml=t}displayTree_(e){e++;const t=Array(e).join(" ");let n="";n+="\n"+t+this.toString(),n+="\n"+t+"MathmlTree:",n+="\n"+t+this.mathmlTreeString(),n+="\n"+t+"MathML:";for(let e,r=0;e=this.mathml[r];r++)n+="\n"+t+e.toString();return n+="\n"+t+"Begin Content",this.contentNodes.forEach((function(t){n+=t.displayTree_(e)})),n+="\n"+t+"End Content",n+="\n"+t+"Begin Children",this.childNodes.forEach((function(t){n+=t.displayTree_(e)})),n+="\n"+t+"End Children",n}mathmlTreeString(){return this.mathmlTree?this.mathmlTree.toString():"EMPTY"}addAnnotation_(e,t){const n=this.annotation[e];n&&!n.includes(t)?n.push(t):this.annotation[e]=[t]}}class SemanticNodeFactory{constructor(){this.leafMap=new SemanticNodeCollator,this.defaultMap=new SemanticDefault,this.idCounter_=-1}makeNode(e){return this.createNode_(e)}makeUnprocessed(e){const t=this.createNode_();return t.mathml=[e],t.mathmlTree=e,t}makeEmptyNode(){const e=this.createNode_();return e.type=SemanticType.EMPTY,e}makeContentNode(e){const t=this.createNode_();return t.updateContent(e),t}makeMultipleContentNodes(e,t){const n=[];for(let r=0;r<e;r++)n.push(this.makeContentNode(t));return n}makeLeafNode(e,t){if(!e)return this.makeEmptyNode();const n=this.makeContentNode(e);n.font=t||n.font;const r=this.defaultMap.getNode(n);return r&&(n.type=r.type,n.role=r.role,n.font=r.font),this.leafMap.addNode(n),n}makeBranchNode(e,t,n,r){const i=this.createNode_();return r&&i.updateContent(r),i.type=e,i.childNodes=t,i.contentNodes=n,t.concat(n).forEach((function(e){e.parent=i,i.addMathmlNodes(e.mathml)})),i}createNode_(e){return void 0!==e?this.idCounter_=Math.max(this.idCounter_,e):e=++this.idCounter_,new SemanticNode(e)}}function isType(e,t){return e.type===t}function embellishedType(e,t){return e.embellished===t}function isRole(e,t){return e.role===t}function isAccent(e){return isType(e,SemanticType.FENCE)||isType(e,SemanticType.PUNCTUATION)||isType(e,SemanticType.OPERATOR)||isType(e,SemanticType.RELATION)}function isSimpleFunctionScope(e){const t=e.childNodes;if(0===t.length)return!0;if(t.length>1)return!1;const n=t[0];if(n.type===SemanticType.INFIXOP){if(n.role!==SemanticRole.IMPLICIT)return!1;if(n.childNodes.some((e=>isType(e,SemanticType.INFIXOP))))return!1}return!0}function isPrefixFunctionBoundary(e){return isOperator(e)&&!isRole(e,SemanticRole.DIVISION)||isType(e,SemanticType.APPL)||isGeneralFunctionBoundary(e)}function isBigOpBoundary(e){return isOperator(e)||isGeneralFunctionBoundary(e)}function isIntegralDxBoundary(e,t){return!!t&&isType(t,SemanticType.IDENTIFIER)&&SemanticMap.Secondary.has(e.textContent,SemanticSecondary.D)}function isIntegralDxBoundarySingle(e){if(isType(e,SemanticType.IDENTIFIER)){const t=e.textContent[0];return t&&e.textContent[1]&&SemanticMap.Secondary.has(t,SemanticSecondary.D)}return!1}function isGeneralFunctionBoundary(e){return isRelation(e)||isPunctuation(e)}function isEmbellished(e){return e.embellished?e.embellished:isEmbellishedType(e.type)?e.type:null}function isEmbellishedType(e){return e===SemanticType.OPERATOR||e===SemanticType.RELATION||e===SemanticType.FENCE||e===SemanticType.PUNCTUATION}function isOperator(e){return isType(e,SemanticType.OPERATOR)||embellishedType(e,SemanticType.OPERATOR)}function isRelation(e){return isType(e,SemanticType.RELATION)||embellishedType(e,SemanticType.RELATION)}function isPunctuation(e){return isType(e,SemanticType.PUNCTUATION)||embellishedType(e,SemanticType.PUNCTUATION)}function isFence(e){return isType(e,SemanticType.FENCE)||embellishedType(e,SemanticType.FENCE)}function isElligibleEmbellishedFence(e){return!(!e||!isFence(e))&&(!e.embellished||recurseBaseNode(e))}function bothSide(e){return isType(e,SemanticType.TENSOR)&&(!isType(e.childNodes[1],SemanticType.EMPTY)||!isType(e.childNodes[2],SemanticType.EMPTY))&&(!isType(e.childNodes[3],SemanticType.EMPTY)||!isType(e.childNodes[4],SemanticType.EMPTY))}function recurseBaseNode(e){return!e.embellished||!bothSide(e)&&((!isRole(e,SemanticRole.CLOSE)||!isType(e,SemanticType.TENSOR))&&((!isRole(e,SemanticRole.OPEN)||!isType(e,SemanticType.SUBSCRIPT)&&!isType(e,SemanticType.SUPERSCRIPT))&&recurseBaseNode(e.childNodes[0])))}function isTableOrMultiline(e){return!!e&&(isType(e,SemanticType.TABLE)||isType(e,SemanticType.MULTILINE))}function tableIsMatrixOrVector(e){return!!e&&isFencedElement(e)&&isTableOrMultiline(e.childNodes[0])}function isFencedElement(e){return!!e&&isType(e,SemanticType.FENCED)&&(isRole(e,SemanticRole.LEFTRIGHT)||isNeutralFence(e))&&1===e.childNodes.length}function tableIsCases(e,t){return t.length>0&&isRole(t[t.length-1],SemanticRole.OPENFENCE)}function tableIsMultiline(e){return e.childNodes.every((function(e){return e.childNodes.length<=1}))}function lineIsLabelled(e){return isType(e,SemanticType.LINE)&&e.contentNodes.length&&isRole(e.contentNodes[0],SemanticRole.LABEL)}function isBinomial(e){return 2===e.childNodes.length}function isLimitBase(e){return isType(e,SemanticType.LARGEOP)||isType(e,SemanticType.LIMBOTH)||isType(e,SemanticType.LIMLOWER)||isType(e,SemanticType.LIMUPPER)||isType(e,SemanticType.FUNCTION)&&isRole(e,SemanticRole.LIMFUNC)||(isType(e,SemanticType.OVERSCORE)||isType(e,SemanticType.UNDERSCORE))&&isLimitBase(e.childNodes[0])}function isSimpleFunctionHead(e){return e.type===SemanticType.IDENTIFIER||e.role===SemanticRole.LATINLETTER||e.role===SemanticRole.GREEKLETTER||e.role===SemanticRole.OTHERLETTER}function singlePunctAtPosition(e,t,n){return 1===t.length&&(e[n].type===SemanticType.PUNCTUATION||e[n].embellished===SemanticType.PUNCTUATION)&&e[n]===t[0]}function isSimpleFunction(e){return isType(e,SemanticType.IDENTIFIER)&&isRole(e,SemanticRole.SIMPLEFUNC)}function isLeftBrace(e){return!!e&&-1!==["{","\ufe5b","\uff5b"].indexOf(e.textContent)}function isRightBrace(e){return!!e&&-1!==["}","\ufe5c","\uff5d"].indexOf(e.textContent)}function isSetNode(e){return isLeftBrace(e.contentNodes[0])&&isRightBrace(e.contentNodes[1])}const illegalSingleton=[SemanticType.PUNCTUATION,SemanticType.PUNCTUATED,SemanticType.RELSEQ,SemanticType.MULTIREL,SemanticType.TABLE,SemanticType.MULTILINE,SemanticType.CASES,SemanticType.INFERENCE],scriptedElement=[SemanticType.LIMUPPER,SemanticType.LIMLOWER,SemanticType.LIMBOTH,SemanticType.SUBSCRIPT,SemanticType.SUPERSCRIPT,SemanticType.UNDERSCORE,SemanticType.OVERSCORE,SemanticType.TENSOR];function isSingletonSetContent(e){const t=e.type;return-1===illegalSingleton.indexOf(t)&&(t!==SemanticType.INFIXOP||e.role===SemanticRole.IMPLICIT)&&(t===SemanticType.FENCED?e.role!==SemanticRole.LEFTRIGHT||isSingletonSetContent(e.childNodes[0]):-1===scriptedElement.indexOf(t)||isSingletonSetContent(e.childNodes[0]))}function isNumber(e){return e.type===SemanticType.NUMBER&&(e.role===SemanticRole.INTEGER||e.role===SemanticRole.FLOAT)}function isUnitCounter(e){return isNumber(e)||e.role===SemanticRole.VULGAR||e.role===SemanticRole.MIXED}function isPureUnit(e){const t=e.childNodes;return e.role===SemanticRole.UNIT&&(!t.length||t[0].role===SemanticRole.UNIT)}function isUnitProduct(e){const t=e.childNodes;return e.type===SemanticType.INFIXOP&&(e.role===SemanticRole.MULTIPLICATION||e.role===SemanticRole.IMPLICIT)&&t.length&&(isPureUnit(t[0])||isUnitCounter(t[0]))&&e.childNodes.slice(1).every(isPureUnit)}function isImplicit(e){return e.type===SemanticType.INFIXOP&&(e.role===SemanticRole.IMPLICIT||e.role===SemanticRole.UNIT&&!!e.contentNodes.length&&e.contentNodes[0].textContent===NamedSymbol.invisibleTimes)}function isImplicitOp(e){return e.type===SemanticType.INFIXOP&&e.role===SemanticRole.IMPLICIT}function isNeutralFence(e){return e.role===SemanticRole.NEUTRAL||e.role===SemanticRole.METRIC}function compareNeutralFences(e,t){return isNeutralFence(e)&&isNeutralFence(t)&&getEmbellishedInner(e).textContent===getEmbellishedInner(t).textContent}function elligibleLeftNeutral(e){return!!isNeutralFence(e)&&(!e.embellished||e.type!==SemanticType.SUPERSCRIPT&&e.type!==SemanticType.SUBSCRIPT&&(e.type!==SemanticType.TENSOR||e.childNodes[3].type===SemanticType.EMPTY&&e.childNodes[4].type===SemanticType.EMPTY))}function elligibleRightNeutral(e){return!!isNeutralFence(e)&&(!e.embellished||(e.type!==SemanticType.TENSOR||e.childNodes[1].type===SemanticType.EMPTY&&e.childNodes[2].type===SemanticType.EMPTY))}function isMembership(e){return[SemanticRole.ELEMENT,SemanticRole.NONELEMENT,SemanticRole.REELEMENT,SemanticRole.RENONELEMENT].includes(e.role)}class SemanticProcessor{static getInstance(){return SemanticProcessor.instance=SemanticProcessor.instance||new SemanticProcessor,SemanticProcessor.instance}static tableToMultiline(e){if(!tableIsMultiline(e))return SemanticHeuristics.run("rewrite_subcases",e,SemanticProcessor.classifyTable);e.type=SemanticType.MULTILINE;for(let t,n=0;t=e.childNodes[n];n++)SemanticProcessor.rowToLine_(t,SemanticRole.MULTILINE);return 1===e.childNodes.length&&!lineIsLabelled(e.childNodes[0])&&isFencedElement(e.childNodes[0].childNodes[0])&&SemanticProcessor.tableToMatrixOrVector_(SemanticProcessor.rewriteFencedLine_(e)),SemanticProcessor.binomialForm_(e),SemanticProcessor.classifyMultiline(e),e}static number(e){e.type!==SemanticType.UNKNOWN&&e.type!==SemanticType.IDENTIFIER||(e.type=SemanticType.NUMBER),SemanticProcessor.meaningFromContent(e,SemanticProcessor.numberRole_),SemanticProcessor.exprFont_(e)}static classifyMultiline(e){let t=0;const n=e.childNodes.length;let r;for(;t<n&&(!(r=e.childNodes[t])||!r.childNodes.length);)t++;if(t>=n)return;const i=r.childNodes[0].role;i!==SemanticRole.UNKNOWN&&e.childNodes.every((function(e){const t=e.childNodes[0];return!t||t.role===i&&(isType(t,SemanticType.RELATION)||isType(t,SemanticType.RELSEQ))}))&&(e.role=i)}static classifyTable(e){const t=SemanticProcessor.computeColumns_(e);return SemanticProcessor.classifyByColumns_(e,t,SemanticRole.EQUALITY)||SemanticProcessor.classifyByColumns_(e,t,SemanticRole.INEQUALITY,[SemanticRole.EQUALITY])||SemanticProcessor.classifyByColumns_(e,t,SemanticRole.ARROW)||SemanticProcessor.detectCaleyTable(e),e}static detectCaleyTable(e){if(!e.mathmlTree)return!1;const t=e.mathmlTree,n=t.getAttribute("columnlines"),r=t.getAttribute("rowlines");return!(!n||!r)&&(!(!SemanticProcessor.cayleySpacing(n)||!SemanticProcessor.cayleySpacing(r))&&(e.role=SemanticRole.CAYLEY,!0))}static cayleySpacing(e){const t=e.split(" ");return("solid"===t[0]||"dashed"===t[0])&&t.slice(1).every((e=>"none"===e))}static proof(e,t,n){const r=SemanticProcessor.separateSemantics(t);return SemanticProcessor.getInstance().proof(e,r,n)}static findSemantics(e,t,n){const r=null==n?null:n,i=SemanticProcessor.getSemantics(e);return!!i&&(!!i[t]&&(null==r||i[t]===r))}static getSemantics(e){const t=e.getAttribute("semantics");return t?SemanticProcessor.separateSemantics(t):null}static removePrefix(e){const[,...t]=e.split("_");return t.join("_")}static separateSemantics(e){const t={};return e.split(";").forEach((function(e){const[n,r]=e.split(":");t[SemanticProcessor.removePrefix(n)]=r})),t}static matchSpaces_(e,t){for(let n,r=0;n=t[r];r++){const t=e[r].mathmlTree,i=e[r+1].mathmlTree;if(!t||!i)continue;const s=t.nextSibling;if(!s||s===i)continue;const o=SemanticProcessor.getSpacer_(s);o&&(n.mathml.push(o),n.mathmlTree=o,n.role=SemanticRole.SPACE)}}static getSpacer_(e){if(dom_util_tagName(e)===MMLTAGS.MSPACE)return e;for(;hasEmptyTag(e)&&1===e.childNodes.length;)if(dom_util_tagName(e=e.childNodes[0])===MMLTAGS.MSPACE)return e;return null}static fenceToPunct_(e){const t=SemanticProcessor.FENCE_TO_PUNCT_[e.role];if(t){for(;e.embellished;)e.embellished=SemanticType.PUNCTUATION,isRole(e,SemanticRole.SUBSUP)||isRole(e,SemanticRole.UNDEROVER)||(e.role=t),e=e.childNodes[0];e.type=SemanticType.PUNCTUATION,e.role=t}}static classifyFunction_(e,t){if(e.type===SemanticType.APPL||e.type===SemanticType.BIGOP||e.type===SemanticType.INTEGRAL)return"";if(t[0]&&t[0].textContent===NamedSymbol.functionApplication){SemanticProcessor.getInstance().funcAppls[e.id]=t.shift();let n=SemanticRole.SIMPLEFUNC;return SemanticHeuristics.run("simple2prefix",e),e.role!==SemanticRole.PREFIXFUNC&&e.role!==SemanticRole.LIMFUNC||(n=e.role),SemanticProcessor.propagateFunctionRole_(e,n),"prefix"}const n=SemanticProcessor.CLASSIFY_FUNCTION_[e.role];return n||(isSimpleFunctionHead(e)?"simple":"")}static propagateFunctionRole_(e,t){if(e){if(e.type===SemanticType.INFIXOP)return;isRole(e,SemanticRole.SUBSUP)||isRole(e,SemanticRole.UNDEROVER)||(e.role=t),SemanticProcessor.propagateFunctionRole_(e.childNodes[0],t)}}static getFunctionOp_(e,t){if(t(e))return e;for(let n,r=0;n=e.childNodes[r];r++){const e=SemanticProcessor.getFunctionOp_(n,t);if(e)return e}return null}static tableToMatrixOrVector_(e){const t=e.childNodes[0];isType(t,SemanticType.MULTILINE)?SemanticProcessor.tableToVector_(e):SemanticProcessor.tableToMatrix_(e),e.contentNodes.forEach(t.appendContentNode.bind(t));for(let e,n=0;e=t.childNodes[n];n++)SemanticProcessor.assignRoleToRow_(e,SemanticProcessor.getComponentRoles_(t));return t.parent=null,t}static tableToVector_(e){const t=e.childNodes[0];t.type=SemanticType.VECTOR,1!==t.childNodes.length?SemanticProcessor.binomialForm_(t):SemanticProcessor.tableToSquare_(e)}static binomialForm_(e){isRole(e,SemanticRole.UNKNOWN)&&isBinomial(e)&&(e.role=SemanticRole.BINOMIAL,e.childNodes[0].role=SemanticRole.BINOMIAL,e.childNodes[1].role=SemanticRole.BINOMIAL)}static tableToMatrix_(e){const t=e.childNodes[0];t.type=SemanticType.MATRIX,t.childNodes&&t.childNodes.length>0&&t.childNodes[0].childNodes&&t.childNodes.length===t.childNodes[0].childNodes.length?SemanticProcessor.tableToSquare_(e):t.childNodes&&1===t.childNodes.length&&(t.role=SemanticRole.ROWVECTOR)}static tableToSquare_(e){const t=e.childNodes[0];isRole(t,SemanticRole.UNKNOWN)&&(isNeutralFence(e)?t.role=SemanticRole.DETERMINANT:t.role=SemanticRole.SQUAREMATRIX)}static getComponentRoles_(e){const t=e.role;return t&&t!==SemanticRole.UNKNOWN?t:e.type.toLowerCase()||SemanticRole.UNKNOWN}static tableToCases_(e,t){for(let t,n=0;t=e.childNodes[n];n++)SemanticProcessor.assignRoleToRow_(t,SemanticRole.CASES);return e.type=SemanticType.CASES,e.appendContentNode(t),tableIsMultiline(e)&&SemanticProcessor.binomialForm_(e),e}static rewriteFencedLine_(e){const t=e.childNodes[0],n=e.childNodes[0].childNodes[0],r=e.childNodes[0].childNodes[0].childNodes[0];return n.parent=e.parent,e.parent=n,r.parent=t,n.childNodes=[e],t.childNodes=[r],n}static rowToLine_(e,t){const n=t||SemanticRole.UNKNOWN;isType(e,SemanticType.ROW)&&(e.type=SemanticType.LINE,e.role=n,1===e.childNodes.length&&isType(e.childNodes[0],SemanticType.CELL)&&(e.childNodes=e.childNodes[0].childNodes,e.childNodes.forEach((function(t){t.parent=e}))))}static assignRoleToRow_(e,t){isType(e,SemanticType.LINE)?e.role=t:isType(e,SemanticType.ROW)&&(e.role=t,e.childNodes.forEach((function(e){isType(e,SemanticType.CELL)&&(e.role=t)})))}static nextSeparatorFunction_(e){let t;if(e){if(e.match(/^\s+$/))return null;t=e.replace(/\s/g,"").split("").filter((function(e){return e}))}else t=[","];return function(){return t.length>1?t.shift():t[0]}}static meaningFromContent(e,t){const n=[...e.textContent].filter((e=>e.match(/[^\s]/))),r=n.map((e=>SemanticMap.Meaning.get(e)));t(e,n,r)}static numberRole_(e,t,n){if(e.role===SemanticRole.UNKNOWN)return n.every((function(e){return e.type===SemanticType.NUMBER&&e.role===SemanticRole.INTEGER||e.type===SemanticType.PUNCTUATION&&e.role===SemanticRole.COMMA}))?(e.role=SemanticRole.INTEGER,void("0"===t[0]&&e.addAnnotation("general","basenumber"))):void(n.every((function(e){return e.type===SemanticType.NUMBER&&e.role===SemanticRole.INTEGER||e.type===SemanticType.PUNCTUATION}))?e.role=SemanticRole.FLOAT:e.role=SemanticRole.OTHERNUMBER)}static exprFont_(e){e.font===SemanticFont.UNKNOWN&&SemanticProcessor.compSemantics(e,"font",SemanticFont)}static compSemantics(e,t,n){const r=[...e.textContent].map((e=>SemanticMap.Meaning.get(e))).reduce((function(e,r){return e&&r[t]&&r[t]!==n.UNKNOWN&&r[t]!==e?e===n.UNKNOWN?r[t]:null:e}),n.UNKNOWN);r&&(e[t]=r)}static purgeFences_(e){const t=e.rel,n=e.comp,r=[],i=[];for(;t.length>0;){const e=t.shift();let s=n.shift();isElligibleEmbellishedFence(e)?(r.push(e),i.push(s)):(SemanticProcessor.fenceToPunct_(e),s.push(e),s=s.concat(n.shift()),n.unshift(s))}return i.push(n.shift()),{rel:r,comp:i}}static rewriteFencedNode_(e){const t=e.contentNodes[0],n=e.contentNodes[1];let r=SemanticProcessor.rewriteFence_(e,t);return e.contentNodes[0]=r.fence,r=SemanticProcessor.rewriteFence_(r.node,n),e.contentNodes[1]=r.fence,e.contentNodes[0].parent=e,e.contentNodes[1].parent=e,r.node.parent=null,r.node}static rewriteFence_(e,t){if(!t.embellished)return{node:e,fence:t};const n=t.childNodes[0],r=SemanticProcessor.rewriteFence_(e,n);return isType(t,SemanticType.SUPERSCRIPT)||isType(t,SemanticType.SUBSCRIPT)||isType(t,SemanticType.TENSOR)?(isRole(t,SemanticRole.SUBSUP)||(t.role=e.role),n!==r.node&&(t.replaceChild(n,r.node),n.parent=e),SemanticProcessor.propagateFencePointer_(t,n),{node:t,fence:r.fence}):(t.replaceChild(n,r.fence),t.mathmlTree&&-1===t.mathml.indexOf(t.mathmlTree)&&t.mathml.push(t.mathmlTree),{node:r.node,fence:t})}static propagateFencePointer_(e,t){e.fencePointer=t.fencePointer||t.id.toString(),e.embellished=null}static classifyByColumns_(e,t,n,r=[]){const i=[n].concat(r);return!!(3===t.length&&SemanticProcessor.testColumns_(t,1,(e=>SemanticProcessor.isPureRelation_(e,i)))||2===t.length&&(SemanticProcessor.testColumns_(t,1,(e=>SemanticProcessor.isEndRelation_(e,i)||SemanticProcessor.isPureRelation_(e,i)))||SemanticProcessor.testColumns_(t,0,(e=>SemanticProcessor.isEndRelation_(e,i,!0)||SemanticProcessor.isPureRelation_(e,i)))))&&(e.role=n,!0)}static isEndRelation_(e,t,n){const r=n?e.childNodes.length-1:0;return isType(e,SemanticType.RELSEQ)&&t.some((t=>isRole(e,t)))&&isType(e.childNodes[r],SemanticType.EMPTY)}static isPureRelation_(e,t){return isType(e,SemanticType.RELATION)&&t.some((t=>isRole(e,t)))}static computeColumns_(e){const t=[];for(let n,r=0;n=e.childNodes[r];r++)for(let e,r=0;e=n.childNodes[r];r++){t[r]?t[r].push(e):t[r]=[e]}return t}static testColumns_(e,t,n){const r=e[t];return!!r&&(r.some((function(e){return e.childNodes.length&&n(e.childNodes[0])}))&&r.every((function(e){return!e.childNodes.length||n(e.childNodes[0])})))}setNodeFactory(e){SemanticProcessor.getInstance().factory_=e,SemanticHeuristics.updateFactory(SemanticProcessor.getInstance().factory_)}getNodeFactory(){return SemanticProcessor.getInstance().factory_}identifierNode(e,t,n){if("MathML-Unit"===n)e.type=SemanticType.IDENTIFIER,e.role=SemanticRole.UNIT;else if(!t&&1===e.textContent.length&&(e.role===SemanticRole.INTEGER||e.role===SemanticRole.LATINLETTER||e.role===SemanticRole.GREEKLETTER)&&e.font===SemanticFont.NORMAL)return e.font=SemanticFont.ITALIC,SemanticHeuristics.run("simpleNamedFunction",e);return e.type===SemanticType.UNKNOWN&&(e.type=SemanticType.IDENTIFIER),SemanticProcessor.exprFont_(e),SemanticHeuristics.run("simpleNamedFunction",e)}implicitNode(e){if(e=SemanticProcessor.getInstance().getMixedNumbers_(e),1===(e=SemanticProcessor.getInstance().combineUnits_(e)).length)return e[0];const t=SemanticProcessor.getInstance().implicitNode_(e);return SemanticHeuristics.run("combine_juxtaposition",t)}text(e,t){return SemanticProcessor.exprFont_(e),e.type=SemanticType.TEXT,t===MMLTAGS.ANNOTATIONXML?(e.role=SemanticRole.ANNOTATION,e):t===MMLTAGS.MS?(e.role=SemanticRole.STRING,e):t===MMLTAGS.MSPACE||e.textContent.match(/^\s*$/)?(e.role=SemanticRole.SPACE,e):/\s/.exec(e.textContent)?(e.role=SemanticRole.TEXT,e):(e.role=SemanticRole.UNKNOWN,e)}row(e){return 0===(e=e.filter((function(e){return!isType(e,SemanticType.EMPTY)}))).length?SemanticProcessor.getInstance().factory_.makeEmptyNode():(e=SemanticProcessor.getInstance().getFencesInRow_(e),e=SemanticProcessor.getInstance().tablesInRow(e),e=SemanticProcessor.getInstance().getPunctuationInRow_(e),e=SemanticProcessor.getInstance().getTextInRow_(e),e=SemanticProcessor.getInstance().getFunctionsInRow_(e),SemanticProcessor.getInstance().relationsInRow_(e))}limitNode(e,t){if(!t.length)return SemanticProcessor.getInstance().factory_.makeEmptyNode();let n,r=t[0],i=SemanticType.UNKNOWN;if(!t[1])return r;if(SemanticHeuristics.run("op_with_limits",t),isLimitBase(r)){n=SemanticProcessor.MML_TO_LIMIT_[e];const s=n.length;if(i=n.type,t=t.slice(0,n.length+1),1===s&&isAccent(t[1])||2===s&&isAccent(t[1])&&isAccent(t[2]))return n=SemanticProcessor.MML_TO_BOUNDS_[e],SemanticProcessor.getInstance().accentNode_(r,t,n.type,n.length,n.accent);if(2===s){if(isAccent(t[1]))return r=SemanticProcessor.getInstance().accentNode_(r,[r,t[1]],{MSUBSUP:SemanticType.SUBSCRIPT,MUNDEROVER:SemanticType.UNDERSCORE}[e],1,!0),t[2]?SemanticProcessor.getInstance().makeLimitNode_(r,[r,t[2]],null,SemanticType.LIMUPPER):r;if(t[2]&&isAccent(t[2]))return r=SemanticProcessor.getInstance().accentNode_(r,[r,t[2]],{MSUBSUP:SemanticType.SUPERSCRIPT,MUNDEROVER:SemanticType.OVERSCORE}[e],1,!0),SemanticProcessor.getInstance().makeLimitNode_(r,[r,t[1]],null,SemanticType.LIMLOWER);t[s]||(i=SemanticType.LIMLOWER)}return SemanticProcessor.getInstance().makeLimitNode_(r,t,null,i)}return n=SemanticProcessor.MML_TO_BOUNDS_[e],SemanticProcessor.getInstance().accentNode_(r,t,n.type,n.length,n.accent)}tablesInRow(e){let t=partitionNodes(e,tableIsMatrixOrVector),n=[];for(let e,r=0;e=t.rel[r];r++)n=n.concat(t.comp.shift()),n.push(SemanticProcessor.tableToMatrixOrVector_(e));n=n.concat(t.comp.shift()),t=partitionNodes(n,isTableOrMultiline),n=[];for(let e,r=0;e=t.rel[r];r++){const r=t.comp.shift();tableIsCases(e,r)&&SemanticProcessor.tableToCases_(e,r.pop()),n=n.concat(r),n.push(e)}return n.concat(t.comp.shift())}mfenced(e,t,n,r){if(n&&r.length>0){const e=SemanticProcessor.nextSeparatorFunction_(n),t=[r.shift()];r.forEach((n=>{t.push(SemanticProcessor.getInstance().factory_.makeContentNode(e())),t.push(n)})),r=t}return e&&t?SemanticProcessor.getInstance().horizontalFencedNode_(SemanticProcessor.getInstance().factory_.makeContentNode(e),SemanticProcessor.getInstance().factory_.makeContentNode(t),r):(e&&r.unshift(SemanticProcessor.getInstance().factory_.makeContentNode(e)),t&&r.push(SemanticProcessor.getInstance().factory_.makeContentNode(t)),SemanticProcessor.getInstance().row(r))}fractionLikeNode(e,t,n,r){let i;if(!r&&isZeroLength(n)){const n=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.LINE,[e],[]),r=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.LINE,[t],[]);return i=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.MULTILINE,[n,r],[]),SemanticProcessor.binomialForm_(i),SemanticProcessor.classifyMultiline(i),i}return i=SemanticProcessor.getInstance().fractionNode_(e,t),r&&i.addAnnotation("general","bevelled"),i}tensor(e,t,n,r,i){const s=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.TENSOR,[e,SemanticProcessor.getInstance().scriptNode_(t,SemanticRole.LEFTSUB),SemanticProcessor.getInstance().scriptNode_(n,SemanticRole.LEFTSUPER),SemanticProcessor.getInstance().scriptNode_(r,SemanticRole.RIGHTSUB),SemanticProcessor.getInstance().scriptNode_(i,SemanticRole.RIGHTSUPER)],[]);return s.role=e.role,s.embellished=isEmbellished(e),s}pseudoTensor(e,t,n){const r=e=>!isType(e,SemanticType.EMPTY),i=t.filter(r).length,s=n.filter(r).length;if(!i&&!s)return e;const o=i?s?MMLTAGS.MSUBSUP:MMLTAGS.MSUB:MMLTAGS.MSUP,a=[e];return i&&a.push(SemanticProcessor.getInstance().scriptNode_(t,SemanticRole.RIGHTSUB,!0)),s&&a.push(SemanticProcessor.getInstance().scriptNode_(n,SemanticRole.RIGHTSUPER,!0)),SemanticProcessor.getInstance().limitNode(o,a)}font(e){const t=SemanticProcessor.MATHJAX_FONTS[e];return t||e}proof(e,t,n){if(t.inference||t.axiom||console.log("Noise"),t.axiom){const t=SemanticProcessor.getInstance().cleanInference(e.childNodes),r=t.length?SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.INFERENCE,n(t),[]):SemanticProcessor.getInstance().factory_.makeEmptyNode();return r.role=SemanticRole.AXIOM,r.mathmlTree=e,r}const r=SemanticProcessor.getInstance().inference(e,t,n);return t.proof&&(r.role=SemanticRole.PROOF,r.childNodes[0].role=SemanticRole.FINAL),r}inference(e,t,n){if(t.inferenceRule){const t=SemanticProcessor.getInstance().getFormulas(e,[],n);return SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.INFERENCE,[t.conclusion,t.premises],[])}const r=t.labelledRule,i=toArray(e.childNodes),s=[];"left"!==r&&"both"!==r||s.push(SemanticProcessor.getInstance().getLabel(e,i,n,SemanticRole.LEFT)),"right"!==r&&"both"!==r||s.push(SemanticProcessor.getInstance().getLabel(e,i,n,SemanticRole.RIGHT));const o=SemanticProcessor.getInstance().getFormulas(e,i,n),a=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.INFERENCE,[o.conclusion,o.premises],s);return a.mathmlTree=e,a}getLabel(e,t,n,r){const i=SemanticProcessor.getInstance().findNestedRow(t,"prooflabel",r),s=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.RULELABEL,n(toArray(i.childNodes)),[]);return s.role=r,s.mathmlTree=i,s}getFormulas(e,t,n){const r=t.length?SemanticProcessor.getInstance().findNestedRow(t,"inferenceRule"):e,i="up"===SemanticProcessor.getSemantics(r).inferenceRule,s=i?r.childNodes[1]:r.childNodes[0],o=i?r.childNodes[0]:r.childNodes[1],a=s.childNodes[0].childNodes[0],c=toArray(a.childNodes[0].childNodes),l=[];let u=1;for(const e of c)u%2&&l.push(e.childNodes[0]),u++;const m=n(l),d=n(toArray(o.childNodes[0].childNodes))[0],h=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.PREMISES,m,[]);h.mathmlTree=a;const p=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.CONCLUSION,[d],[]);return p.mathmlTree=o.childNodes[0].childNodes[0],{conclusion:p,premises:h}}findNestedRow(e,t,n){return SemanticProcessor.getInstance().findNestedRow_(e,t,0,n)}cleanInference(e){return toArray(e).filter((function(e){return"MSPACE"!==dom_util_tagName(e)}))}operatorNode(e){return e.type===SemanticType.UNKNOWN&&(e.type=SemanticType.OPERATOR),SemanticHeuristics.run("multioperator",e)}constructor(){this.funcAppls={},this.splitRoles=new Map([[SemanticRole.SUBTRACTION,SemanticRole.NEGATIVE],[SemanticRole.ADDITION,SemanticRole.POSITIVE]]),this.splitOps=["\u2212","-","\u2010","\u2011","+"],this.factory_=new SemanticNodeFactory,SemanticHeuristics.updateFactory(this.factory_)}implicitNode_(e){const t=SemanticProcessor.getInstance().factory_.makeMultipleContentNodes(e.length-1,NamedSymbol.invisibleTimes);SemanticProcessor.matchSpaces_(e,t);const n=SemanticProcessor.getInstance().infixNode_(e,t[0]);return n.role=SemanticRole.IMPLICIT,t.forEach((function(e){e.parent=n})),n.contentNodes=t,n}infixNode_(e,t){const n=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.INFIXOP,e,[t],getEmbellishedInner(t).textContent);return n.role=t.role,SemanticHeuristics.run("propagateSimpleFunction",n)}explicitMixed_(e){const t=partitionNodes(e,(function(e){return e.textContent===NamedSymbol.invisiblePlus}));if(!t.rel.length)return e;let n=[];for(let e,r=0;e=t.rel[r];r++){const i=t.comp[r],s=t.comp[r+1],o=i.length-1;if(i[o]&&s[0]&&isType(i[o],SemanticType.NUMBER)&&!isRole(i[o],SemanticRole.MIXED)&&isType(s[0],SemanticType.FRACTION)){const e=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.NUMBER,[i[o],s[0]],[]);e.role=SemanticRole.MIXED,n=n.concat(i.slice(0,o)),n.push(e),s.shift()}else n=n.concat(i),n.push(e)}return n.concat(t.comp[t.comp.length-1])}concatNode_(e,t,n){if(0===t.length)return e;const r=t.map((function(e){return getEmbellishedInner(e).textContent})).join(" "),i=SemanticProcessor.getInstance().factory_.makeBranchNode(n,[e],t,r);return t.length>1&&(i.role=SemanticRole.MULTIOP),i}prefixNode_(e,t){const n=this.splitSingles(t);let r=e;for(;n.length>0;){const e=n.pop();r=SemanticProcessor.getInstance().concatNode_(r,e,SemanticType.PREFIXOP),1===e.length&&-1!==this.splitOps.indexOf(e[0].textContent)&&(r.role=this.splitRoles.get(e[0].role))}return r}splitSingles(e){let t=0;const n=[];let r=0;for(;r<e.length;){const i=e[r];!this.splitRoles.has(i.role)||e[r-1]&&e[r-1].role===i.role||e[r+1]&&e[r+1].role===i.role||-1===this.splitOps.indexOf(i.textContent)||(n.push(e.slice(t,r)),n.push(e.slice(r,r+1)),t=r+1),r++}return t<r&&n.push(e.slice(t,r)),n}postfixNode_(e,t){return t.length?SemanticProcessor.getInstance().concatNode_(e,t,SemanticType.POSTFIXOP):e}combineUnits_(e){const t=partitionNodes(e,(function(e){return!isRole(e,SemanticRole.UNIT)}));if(e.length===t.rel.length)return t.rel;const n=[];let r,i;do{const e=t.comp.shift();r=t.rel.shift();let s=null;i=n.pop(),i&&(e.length&&isUnitCounter(i)?e.unshift(i):n.push(i)),1===e.length&&(s=e.pop()),e.length>1&&(s=SemanticProcessor.getInstance().implicitNode_(e),s.role=SemanticRole.UNIT),s&&n.push(s),r&&n.push(r)}while(r);return n}getMixedNumbers_(e){const t=partitionNodes(e,(function(e){return isType(e,SemanticType.FRACTION)&&isRole(e,SemanticRole.VULGAR)}));if(!t.rel.length)return e;let n=[];for(let e,r=0;e=t.rel[r];r++){const i=t.comp[r],s=i.length-1;if(i[s]&&isType(i[s],SemanticType.NUMBER)&&(isRole(i[s],SemanticRole.INTEGER)||isRole(i[s],SemanticRole.FLOAT))){const t=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.NUMBER,[i[s],e],[]);t.role=SemanticRole.MIXED,n=n.concat(i.slice(0,s)),n.push(t)}else n=n.concat(i),n.push(e)}return n.concat(t.comp[t.comp.length-1])}getTextInRow_(e){if(0===e.length)return e;if(1===e.length)return e[0].type===SemanticType.TEXT&&e[0].role===SemanticRole.UNKNOWN&&(e[0].role=SemanticRole.ANNOTATION),e;const{rel:t,comp:n}=partitionNodes(e,(e=>isType(e,SemanticType.TEXT)));if(0===t.length)return e;const r=[];let i=n.shift();for(;t.length>0;){let e=t.shift(),s=n.shift();const o=[];for(;!s.length&&t.length&&e.role!==SemanticRole.SPACE&&t[0].role!==SemanticRole.SPACE;)o.push(e),e=t.shift(),s=n.shift();if(o.length){i.length&&r.push(SemanticProcessor.getInstance().row(i)),o.push(e);const t=SemanticProcessor.getInstance().dummyNode_(o);r.push(t),i=s;continue}if(e.role!==SemanticRole.UNKNOWN){i.length&&r.push(SemanticProcessor.getInstance().row(i)),r.push(e),i=s;continue}const a=SemanticMap.Meaning.get(e.textContent);a.type!==SemanticType.PUNCTUATION?a.type===SemanticType.UNKNOWN?(SemanticProcessor.meaningFromContent(e,((e,t,n)=>{if(e.role===SemanticRole.UNKNOWN){if(SemanticProcessor.numberRole_(e,t,n),e.role===SemanticRole.OTHERNUMBER)return n.some((e=>e.type!==SemanticType.NUMBER&&e.type!==SemanticType.IDENTIFIER))?(e.type=SemanticType.TEXT,void(e.role=SemanticRole.ANNOTATION)):void(e.role=SemanticRole.UNKNOWN);e.type=SemanticType.NUMBER}})),e.type!==SemanticType.TEXT||e.role===SemanticRole.UNKNOWN?(e.role===SemanticRole.UNKNOWN&&(t.length||s.length?s.length&&s[0].type===SemanticType.FENCED?(e.type=SemanticType.FUNCTION,e.role=SemanticRole.PREFIXFUNC):e.role=SemanticRole.TEXT:(e.type=SemanticType.IDENTIFIER,e.role=SemanticRole.UNIT)),i.push(e),i=i.concat(s)):(i.length&&r.push(SemanticProcessor.getInstance().row(i)),r.push(e),i=s)):(e.type=a.type,e.role=a.role,e.font=a.font,e.addAnnotation("general","text"),i.push(e),i=i.concat(s)):(e.role=a.role,e.font=a.font,i.length&&r.push(SemanticProcessor.getInstance().row(i)),r.push(e),i=s)}return i.length>0&&r.push(SemanticProcessor.getInstance().row(i)),r.length>1?[SemanticProcessor.getInstance().dummyNode_(r)]:r}relationsInRow_(e){const t=partitionNodes(e,isRelation),n=t.rel[0];if(!n)return SemanticProcessor.getInstance().operationsInRow_(e);if(1===e.length)return e[0];const r=t.comp.map(SemanticProcessor.getInstance().operationsInRow_);let i;return t.rel.some((function(e){return!e.equals(n)}))?(i=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.MULTIREL,r,t.rel),t.rel.every((function(e){return e.role===n.role}))&&(i.role=n.role),i):(i=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.RELSEQ,r,t.rel,getEmbellishedInner(n).textContent),i.role=n.role,i)}operationsInRow_(e){if(0===e.length)return SemanticProcessor.getInstance().factory_.makeEmptyNode();if(1===(e=SemanticProcessor.getInstance().explicitMixed_(e)).length)return e[0];const t=[];for(;e.length>0&&isOperator(e[0]);)t.push(e.shift());if(0===e.length)return SemanticProcessor.getInstance().prefixNode_(t.pop(),t);if(1===e.length)return SemanticProcessor.getInstance().prefixNode_(e[0],t);const n=sliceNodes(e=SemanticHeuristics.run("convert_juxtaposition",e),isOperator),r=SemanticProcessor.getInstance().wrapFactor(t,n);return SemanticProcessor.getInstance().addFactor(r,n)}wrapPostfix(e){var t;(null===(t=e.div)||void 0===t?void 0:t.role)===SemanticRole.POSTFIXOP&&(e.tail.length&&e.tail[0].type!==SemanticType.OPERATOR?e.div.role=SemanticRole.DIVISION:(e.head=[SemanticProcessor.getInstance().postfixNode_(SemanticProcessor.getInstance().implicitNode(e.head),[e.div])],e.div=e.tail.shift(),SemanticProcessor.getInstance().wrapPostfix(e)))}wrapFactor(e,t){return SemanticProcessor.getInstance().wrapPostfix(t),SemanticProcessor.getInstance().prefixNode_(SemanticProcessor.getInstance().implicitNode(t.head),e)}addFactor(e,t){return t.div?SemanticProcessor.getInstance().operationsTree_(t.tail,e,t.div):(isUnitProduct(e)&&(e.role=SemanticRole.UNIT),e)}operationsTree_(e,t,n,r=[]){if(0===e.length){if(r.unshift(n),t.type===SemanticType.INFIXOP){const e=SemanticProcessor.getInstance().postfixNode_(t.childNodes.pop(),r);return t.appendChild(e),t}return SemanticProcessor.getInstance().postfixNode_(t,r)}const i=sliceNodes(e,isOperator);if(0===i.head.length)return r.push(i.div),SemanticProcessor.getInstance().operationsTree_(i.tail,t,n,r);const s=SemanticProcessor.getInstance().wrapFactor(r,i),o=SemanticProcessor.getInstance().appendOperand_(t,n,s);return SemanticProcessor.getInstance().addFactor(o,i)}appendOperand_(e,t,n){if(e.type!==SemanticType.INFIXOP)return SemanticProcessor.getInstance().infixNode_([e,n],t);const r=SemanticProcessor.getInstance().appendDivisionOp_(e,t,n);return r||(SemanticProcessor.getInstance().appendExistingOperator_(e,t,n)?e:t.role===SemanticRole.MULTIPLICATION?SemanticProcessor.getInstance().appendMultiplicativeOp_(e,t,n):SemanticProcessor.getInstance().appendAdditiveOp_(e,t,n))}appendDivisionOp_(e,t,n){return t.role===SemanticRole.DIVISION?isImplicit(e)?SemanticProcessor.getInstance().infixNode_([e,n],t):SemanticProcessor.getInstance().appendLastOperand_(e,t,n):e.role===SemanticRole.DIVISION?SemanticProcessor.getInstance().infixNode_([e,n],t):null}appendLastOperand_(e,t,n){let r=e,i=e.childNodes[e.childNodes.length-1];for(;i&&i.type===SemanticType.INFIXOP&&!isImplicit(i);)r=i,i=r.childNodes[e.childNodes.length-1];const s=SemanticProcessor.getInstance().infixNode_([r.childNodes.pop(),n],t);return r.appendChild(s),e}appendMultiplicativeOp_(e,t,n){if(isImplicit(e))return SemanticProcessor.getInstance().infixNode_([e,n],t);let r=e,i=e.childNodes[e.childNodes.length-1];for(;i&&i.type===SemanticType.INFIXOP&&!isImplicit(i);)r=i,i=r.childNodes[e.childNodes.length-1];const s=SemanticProcessor.getInstance().infixNode_([r.childNodes.pop(),n],t);return r.appendChild(s),e}appendAdditiveOp_(e,t,n){return SemanticProcessor.getInstance().infixNode_([e,n],t)}appendExistingOperator_(e,t,n){return!(!e||e.type!==SemanticType.INFIXOP||isImplicit(e))&&(e.contentNodes[0].equals(t)?(e.appendContentNode(t),e.appendChild(n),!0):SemanticProcessor.getInstance().appendExistingOperator_(e.childNodes[e.childNodes.length-1],t,n))}getFencesInRow_(e){let t=partitionNodes(e,isFence);t=SemanticProcessor.purgeFences_(t);const n=t.comp.shift();return SemanticProcessor.getInstance().fences_(t.rel,t.comp,[],[n])}fences_(e,t,n,r){if(0===e.length&&0===n.length)return r[0];const i=SemanticHeuristics.run("bracketed_interval",[e[0],e[1],...t[0]||[]],(()=>null));if(i){e.shift(),e.shift(),t.shift();const s=r.pop()||[];return r.push([...s,i,...t.shift()]),SemanticProcessor.getInstance().fences_(e,t,n,r)}const s=e=>isRole(e,SemanticRole.OPEN);if(0===e.length){const e=r.shift();for(;n.length>0;){if(s(n[0])){const t=n.shift();SemanticProcessor.fenceToPunct_(t),e.push(t)}else{const t=sliceNodes(n,s),i=t.head.length-1,o=SemanticProcessor.getInstance().neutralFences_(t.head,r.slice(0,i));r=r.slice(i),e.push(...o),t.div&&t.tail.unshift(t.div),n=t.tail}e.push(...r.shift())}return e}const o=n[n.length-1],a=e[0].role;if(a===SemanticRole.OPEN||isNeutralFence(e[0])&&(!o||!compareNeutralFences(e[0],o))){n.push(e.shift());const i=t.shift();return i&&r.push(i),SemanticProcessor.getInstance().fences_(e,t,n,r)}if(o&&a===SemanticRole.CLOSE&&o.role===SemanticRole.OPEN){const i=SemanticProcessor.getInstance().horizontalFencedNode_(n.pop(),e.shift(),r.pop());return r.push(r.pop().concat([i],t.shift())),SemanticProcessor.getInstance().fences_(e,t,n,r)}if(o&&compareNeutralFences(e[0],o)){if(!elligibleLeftNeutral(o)||!elligibleRightNeutral(e[0])){n.push(e.shift());const i=t.shift();return i&&r.push(i),SemanticProcessor.getInstance().fences_(e,t,n,r)}const i=SemanticProcessor.getInstance().horizontalFencedNode_(n.pop(),e.shift(),r.pop());return r.push(r.pop().concat([i],t.shift())),SemanticProcessor.getInstance().fences_(e,t,n,r)}if(o&&a===SemanticRole.CLOSE&&isNeutralFence(o)&&n.some(s)){const i=sliceNodes(n,s,!0),o=r.pop(),a=r.length-i.tail.length+1,c=SemanticProcessor.getInstance().neutralFences_(i.tail,r.slice(a));r=r.slice(0,a);const l=SemanticProcessor.getInstance().horizontalFencedNode_(i.div,e.shift(),r.pop().concat(c,o));return r.push(r.pop().concat([l],t.shift())),SemanticProcessor.getInstance().fences_(e,t,i.head,r)}const c=e.shift();return SemanticProcessor.fenceToPunct_(c),r.push(r.pop().concat([c],t.shift())),SemanticProcessor.getInstance().fences_(e,t,n,r)}neutralFences_(e,t){if(0===e.length)return e;if(1===e.length)return SemanticProcessor.fenceToPunct_(e[0]),e;const n=e.shift();if(!elligibleLeftNeutral(n)){SemanticProcessor.fenceToPunct_(n);const r=t.shift();return r.unshift(n),r.concat(SemanticProcessor.getInstance().neutralFences_(e,t))}const r=sliceNodes(e,(function(e){return compareNeutralFences(e,n)}));if(!r.div){SemanticProcessor.fenceToPunct_(n);const r=t.shift();return r.unshift(n),r.concat(SemanticProcessor.getInstance().neutralFences_(e,t))}if(!elligibleRightNeutral(r.div))return SemanticProcessor.fenceToPunct_(r.div),e.unshift(n),SemanticProcessor.getInstance().neutralFences_(e,t);const i=SemanticProcessor.getInstance().combineFencedContent_(n,r.div,r.head,t);if(r.tail.length>0){const e=i.shift(),t=SemanticProcessor.getInstance().neutralFences_(r.tail,i);return e.concat(t)}return i[0]}combineFencedContent_(e,t,n,r){if(0===n.length){const n=SemanticProcessor.getInstance().horizontalFencedNode_(e,t,r.shift());return r.length>0?r[0].unshift(n):r=[[n]],r}const i=r.shift(),s=n.length-1,o=r.slice(0,s),a=(r=r.slice(s)).shift(),c=SemanticProcessor.getInstance().neutralFences_(n,o);i.push(...c),i.push(...a);const l=SemanticProcessor.getInstance().horizontalFencedNode_(e,t,i);return r.length>0?r[0].unshift(l):r=[[l]],r}horizontalFencedNode_(e,t,n){const r=SemanticProcessor.getInstance().row(n);let i=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.FENCED,[r],[e,t]);return e.role===SemanticRole.OPEN?(SemanticProcessor.getInstance().classifyHorizontalFence_(i),i=SemanticHeuristics.run("propagateComposedFunction",i)):i.role=e.role,i=SemanticHeuristics.run("detect_cycle",i),SemanticProcessor.rewriteFencedNode_(i)}classifyHorizontalFence_(e){e.role=SemanticRole.LEFTRIGHT;const t=e.childNodes;if(!isSetNode(e)||t.length>1)return;if(0===t.length||t[0].type===SemanticType.EMPTY)return void(e.role=SemanticRole.SETEMPTY);const n=t[0].type;if(1===t.length&&isSingletonSetContent(t[0]))return void(e.role=SemanticRole.SETSINGLE);const r=t[0].role;if(n===SemanticType.PUNCTUATED&&r===SemanticRole.SEQUENCE){if(t[0].contentNodes[0].role!==SemanticRole.COMMA)return 1!==t[0].contentNodes.length||t[0].contentNodes[0].role!==SemanticRole.VBAR&&t[0].contentNodes[0].role!==SemanticRole.COLON?void 0:(e.role=SemanticRole.SETEXT,void SemanticProcessor.getInstance().setExtension_(e));e.role=SemanticRole.SETCOLLECT}}setExtension_(e){const t=e.childNodes[0].childNodes[0];t&&t.type===SemanticType.INFIXOP&&1===t.contentNodes.length&&isMembership(t.contentNodes[0])&&(t.addAnnotation("set","intensional"),t.contentNodes[0].addAnnotation("set","intensional"))}getPunctuationInRow_(e){if(e.length<=1)return e;const t=e=>{const t=e.type;return"punctuation"===t||"text"===t||"operator"===t||"relation"===t},n=partitionNodes(e,(function(n){if(!isPunctuation(n))return!1;if(isPunctuation(n)&&!isRole(n,SemanticRole.ELLIPSIS))return!0;const r=e.indexOf(n);if(0===r)return!e[1]||!t(e[1]);const i=e[r-1];if(r===e.length-1)return!t(i);const s=e[r+1];return!t(i)||!t(s)}));if(0===n.rel.length)return e;let r=[],i=n.comp.shift();i.length>0&&r.push(SemanticProcessor.getInstance().row(i));let s=0;for(;n.comp.length>0;){let e=[];const t=s;do{e.push(n.rel[s++]),i=n.comp.shift()}while(n.rel[s]&&i&&0===i.length);e=SemanticHeuristics.run("ellipses",e),n.rel.splice(t,s-t,...e),s=t+e.length,r=r.concat(e),i&&i.length>0&&r.push(SemanticProcessor.getInstance().row(i))}return 1===r.length&&1===n.rel.length?r:[SemanticProcessor.getInstance().punctuatedNode_(r,n.rel)]}punctuatedNode_(e,t){const n=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.PUNCTUATED,e,t);if(t.length===e.length){const e=t[0].role;if(e!==SemanticRole.UNKNOWN&&t.every((function(t){return t.role===e})))return n.role=e,n}const r=t[0];return singlePunctAtPosition(e,t,0)?n.role=r.childNodes.length&&!r.embellished?r.role:SemanticRole.STARTPUNCT:singlePunctAtPosition(e,t,e.length-1)?n.role=r.childNodes.length&&!r.embellished?r.role:SemanticRole.ENDPUNCT:t.every((e=>isRole(e,SemanticRole.DUMMY)))?n.role=SemanticRole.TEXT:t.every((e=>isRole(e,SemanticRole.SPACE)))?n.role=SemanticRole.SPACE:n.role=SemanticRole.SEQUENCE,n}dummyNode_(e){const t=SemanticProcessor.getInstance().factory_.makeMultipleContentNodes(e.length-1,NamedSymbol.invisibleComma);return t.forEach((function(e){e.role=SemanticRole.DUMMY})),SemanticProcessor.getInstance().punctuatedNode_(e,t)}accentRole_(e,t){if(!isAccent(e))return!1;const n=e.textContent,r=SemanticMap.Secondary.get(n,SemanticSecondary.BAR)||SemanticMap.Secondary.get(n,SemanticSecondary.TILDE)||e.role;return e.role=t===SemanticType.UNDERSCORE?SemanticRole.UNDERACCENT:SemanticRole.OVERACCENT,e.addAnnotation("accent",r),!0}accentNode_(e,t,n,r,i){const s=(t=t.slice(0,r+1))[1],o=t[2];let a;if(!i&&o&&(a=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.SUBSCRIPT,[e,s],[]),a.role=SemanticRole.SUBSUP,t=[a,o],n=SemanticType.SUPERSCRIPT),i){const r=SemanticProcessor.getInstance().accentRole_(s,n);if(o){SemanticProcessor.getInstance().accentRole_(o,SemanticType.OVERSCORE)&&!r?(a=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.OVERSCORE,[e,o],[]),t=[a,s],n=SemanticType.UNDERSCORE):(a=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.UNDERSCORE,[e,s],[]),t=[a,o],n=SemanticType.OVERSCORE),a.role=SemanticRole.UNDEROVER}}return SemanticProcessor.getInstance().makeLimitNode_(e,t,a,n)}makeLimitNode_(e,t,n,r){if(r===SemanticType.LIMUPPER&&e.type===SemanticType.LIMLOWER)return e.childNodes.push(t[1]),t[1].parent=e,e.type=SemanticType.LIMBOTH,e;if(r===SemanticType.LIMLOWER&&e.type===SemanticType.LIMUPPER)return e.childNodes.splice(1,-1,t[1]),t[1].parent=e,e.type=SemanticType.LIMBOTH,e;const i=SemanticProcessor.getInstance().factory_.makeBranchNode(r,t,[]),s=isEmbellished(e);return n&&(n.embellished=s),i.embellished=s,i.role=e.role,i}getFunctionsInRow_(e,t){const n=t||[];if(0===e.length)return n;const r=e.shift(),i=SemanticProcessor.classifyFunction_(r,e);if(!i)return n.push(r),SemanticProcessor.getInstance().getFunctionsInRow_(e,n);const s=SemanticProcessor.getInstance().getFunctionsInRow_(e,[]),o=SemanticProcessor.getInstance().getFunctionArgs_(r,s,i);return n.concat(o)}getFunctionArgs_(e,t,n){let r,i,s;switch(n){case"integral":{const n=SemanticProcessor.getInstance().getIntegralArgs_(t);if(!n.intvar&&!n.integrand.length)return n.rest.unshift(e),n.rest;const r=SemanticProcessor.getInstance().row(n.integrand);return s=SemanticProcessor.getInstance().integralNode_(e,r,n.intvar),SemanticHeuristics.run("intvar_from_fraction",s),n.rest.unshift(s),n.rest}case"prefix":if(t[0]&&t[0].type===SemanticType.FENCED){const n=t.shift();return isNeutralFence(n)||(n.role=SemanticRole.LEFTRIGHT),s=SemanticProcessor.getInstance().functionNode_(e,n),t.unshift(s),t}if(r=sliceNodes(t,isPrefixFunctionBoundary),r.head.length)i=SemanticProcessor.getInstance().row(r.head),r.div&&r.tail.unshift(r.div);else{if(!r.div||!isType(r.div,SemanticType.APPL))return t.unshift(e),t;i=r.div}return s=SemanticProcessor.getInstance().functionNode_(e,i),r.tail.unshift(s),r.tail;case"bigop":return r=sliceNodes(t,isBigOpBoundary),r.head.length?(i=SemanticProcessor.getInstance().row(r.head),s=SemanticProcessor.getInstance().bigOpNode_(e,i),r.div&&r.tail.unshift(r.div),r.tail.unshift(s),r.tail):(t.unshift(e),t);default:{if(0===t.length)return[e];const n=t[0];return n.type===SemanticType.FENCED&&!isNeutralFence(n)&&isSimpleFunctionScope(n)?(n.role=SemanticRole.LEFTRIGHT,SemanticProcessor.propagateFunctionRole_(e,SemanticRole.SIMPLEFUNC),s=SemanticProcessor.getInstance().functionNode_(e,t.shift()),t.unshift(s),t):(t.unshift(e),t)}}}getIntegralArgs_(e,t=[]){if(0===e.length){const e=sliceNodes(t,isBigOpBoundary);return e.div&&e.tail.unshift(e.div),{integrand:e.head,intvar:null,rest:e.tail}}SemanticHeuristics.run("intvar_from_implicit",e);const n=e[0];if(isGeneralFunctionBoundary(n)){const{integrand:n,rest:r}=SemanticProcessor.getInstance().getIntegralArgs_(t);return{integrand:n,intvar:null,rest:r.concat(e)}}if(isIntegralDxBoundarySingle(n))return n.role=SemanticRole.INTEGRAL,{integrand:t,intvar:n,rest:e.slice(1)};if(e[1]&&isIntegralDxBoundary(n,e[1])){const r=SemanticProcessor.getInstance().prefixNode_(e[1],[n]);return r.role=SemanticRole.INTEGRAL,{integrand:t,intvar:r,rest:e.slice(2)}}return t.push(e.shift()),SemanticProcessor.getInstance().getIntegralArgs_(e,t)}functionNode_(e,t){const n=SemanticProcessor.getInstance().factory_.makeContentNode(NamedSymbol.functionApplication),r=SemanticProcessor.getInstance().funcAppls[e.id];r&&(n.mathmlTree=r.mathmlTree,n.mathml=r.mathml,n.annotation=r.annotation,n.attributes=r.attributes,delete SemanticProcessor.getInstance().funcAppls[e.id]),n.type=SemanticType.PUNCTUATION,n.role=SemanticRole.APPLICATION;const i=SemanticProcessor.getFunctionOp_(e,(function(e){return isType(e,SemanticType.FUNCTION)||isType(e,SemanticType.IDENTIFIER)&&isRole(e,SemanticRole.SIMPLEFUNC)}));return SemanticProcessor.getInstance().functionalNode_(SemanticType.APPL,[e,t],i,[n])}bigOpNode_(e,t){const n=SemanticProcessor.getFunctionOp_(e,(e=>isType(e,SemanticType.LARGEOP)));return SemanticProcessor.getInstance().functionalNode_(SemanticType.BIGOP,[e,t],n,[])}integralNode_(e,t,n){t=t||SemanticProcessor.getInstance().factory_.makeEmptyNode(),n=n||SemanticProcessor.getInstance().factory_.makeEmptyNode();const r=SemanticProcessor.getFunctionOp_(e,(e=>isType(e,SemanticType.LARGEOP)));return SemanticProcessor.getInstance().functionalNode_(SemanticType.INTEGRAL,[e,t,n],r,[])}functionalNode_(e,t,n,r){const i=t[0];let s;n&&(s=n.parent,r.push(n));const o=SemanticProcessor.getInstance().factory_.makeBranchNode(e,t,r);return o.role=i.role,s&&(n.parent=s),o}fractionNode_(e,t){const n=SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.FRACTION,[e,t],[]);return n.role=n.childNodes.every((function(e){return isType(e,SemanticType.NUMBER)&&isRole(e,SemanticRole.INTEGER)}))?SemanticRole.VULGAR:n.childNodes.every(isPureUnit)?SemanticRole.UNIT:SemanticRole.DIVISION,SemanticHeuristics.run("propagateSimpleFunction",n)}scriptNode_(e,t,n){let r;switch(e.length){case 0:r=SemanticProcessor.getInstance().factory_.makeEmptyNode();break;case 1:if(r=e[0],n)return r;break;default:r=SemanticProcessor.getInstance().dummyNode_(e)}return r.role=t,r}findNestedRow_(e,t,n,r){if(n>3)return null;for(let i,s=0;i=e[s];s++){const e=dom_util_tagName(i);if(e!==MMLTAGS.MSPACE){if(e===MMLTAGS.MROW)return SemanticProcessor.getInstance().findNestedRow_(toArray(i.childNodes),t,n+1,r);if(SemanticProcessor.findSemantics(i,t,r))return i}}return null}}SemanticProcessor.FENCE_TO_PUNCT_={[SemanticRole.METRIC]:SemanticRole.METRIC,[SemanticRole.NEUTRAL]:SemanticRole.VBAR,[SemanticRole.OPEN]:SemanticRole.OPENFENCE,[SemanticRole.CLOSE]:SemanticRole.CLOSEFENCE},SemanticProcessor.MML_TO_LIMIT_={[MMLTAGS.MSUB]:{type:SemanticType.LIMLOWER,length:1},[MMLTAGS.MUNDER]:{type:SemanticType.LIMLOWER,length:1},[MMLTAGS.MSUP]:{type:SemanticType.LIMUPPER,length:1},[MMLTAGS.MOVER]:{type:SemanticType.LIMUPPER,length:1},[MMLTAGS.MSUBSUP]:{type:SemanticType.LIMBOTH,length:2},[MMLTAGS.MUNDEROVER]:{type:SemanticType.LIMBOTH,length:2}},SemanticProcessor.MML_TO_BOUNDS_={[MMLTAGS.MSUB]:{type:SemanticType.SUBSCRIPT,length:1,accent:!1},[MMLTAGS.MSUP]:{type:SemanticType.SUPERSCRIPT,length:1,accent:!1},[MMLTAGS.MSUBSUP]:{type:SemanticType.SUBSCRIPT,length:2,accent:!1},[MMLTAGS.MUNDER]:{type:SemanticType.UNDERSCORE,length:1,accent:!0},[MMLTAGS.MOVER]:{type:SemanticType.OVERSCORE,length:1,accent:!0},[MMLTAGS.MUNDEROVER]:{type:SemanticType.UNDERSCORE,length:2,accent:!0}},SemanticProcessor.CLASSIFY_FUNCTION_={[SemanticRole.INTEGRAL]:"integral",[SemanticRole.SUM]:"bigop",[SemanticRole.PREFIXFUNC]:"prefix",[SemanticRole.LIMFUNC]:"prefix",[SemanticRole.SIMPLEFUNC]:"prefix",[SemanticRole.COMPFUNC]:"prefix"},SemanticProcessor.MATHJAX_FONTS={"-tex-caligraphic":SemanticFont.CALIGRAPHIC,"-tex-caligraphic-bold":SemanticFont.CALIGRAPHICBOLD,"-tex-calligraphic":SemanticFont.CALIGRAPHIC,"-tex-calligraphic-bold":SemanticFont.CALIGRAPHICBOLD,"-tex-oldstyle":SemanticFont.OLDSTYLE,"-tex-oldstyle-bold":SemanticFont.OLDSTYLEBOLD,"-tex-mathit":SemanticFont.ITALIC};let mathspeak_util_nestingDepth={};function spaceoutText(e){return Array.from(e.textContent).map(Span.stringEmpty)}function spaceoutNodes(e,t){const n=Array.from(e.textContent),r=[],i=SemanticProcessor.getInstance(),s=e.ownerDocument;for(let e,o=0;e=n[o];o++){const n=i.getNodeFactory().makeLeafNode(e,SemanticFont.UNKNOWN),o=i.identifierNode(n,SemanticFont.UNKNOWN,"");t(o),r.push(o.xml(s))}return r}function spaceoutNumber(e){return spaceoutNodes(e,(function(e){e.textContent.match(/\W/)||(e.type=SemanticType.NUMBER)}))}function spaceoutIdentifier(e){return spaceoutNodes(e,(function(e){e.font=SemanticFont.UNKNOWN,e.type=SemanticType.IDENTIFIER}))}const nestingBarriers=[SemanticType.CASES,SemanticType.CELL,SemanticType.INTEGRAL,SemanticType.LINE,SemanticType.MATRIX,SemanticType.MULTILINE,SemanticType.OVERSCORE,SemanticType.ROOT,SemanticType.ROW,SemanticType.SQRT,SemanticType.SUBSCRIPT,SemanticType.SUPERSCRIPT,SemanticType.TABLE,SemanticType.UNDERSCORE,SemanticType.VECTOR];function resetNestingDepth(e){return mathspeak_util_nestingDepth={},[e]}function getNestingDepth(e,t,n,r,i,s){r=r||nestingBarriers,i=i||{},s=s||function(e){return!1};const o=serializeXml(t);if(mathspeak_util_nestingDepth[e]||(mathspeak_util_nestingDepth[e]={}),mathspeak_util_nestingDepth[e][o])return mathspeak_util_nestingDepth[e][o];if(s(t)||n.indexOf(t.tagName)<0)return 0;const a=computeNestingDepth_(t,n,setdifference(r,n),i,s,0);return mathspeak_util_nestingDepth[e][o]=a,a}function containsAttr(e,t){if(!e.attributes)return!1;const n=toArray(e.attributes);for(let e,r=0;e=n[r];r++)if(t[e.nodeName]===e.nodeValue)return!0;return!1}function computeNestingDepth_(e,t,n,r,i,s){if(i(e)||n.indexOf(e.tagName)>-1||containsAttr(e,r))return s;if(t.indexOf(e.tagName)>-1&&s++,!e.childNodes||0===e.childNodes.length)return s;const o=toArray(e.childNodes);return Math.max.apply(null,o.map((function(e){return computeNestingDepth_(e,t,n,r,i,s)})))}function fractionNestingDepth(e){return getNestingDepth("fraction",e,["fraction"],nestingBarriers,{},LOCALE.FUNCTIONS.fracNestDepth)}function nestedFraction(e,t,n){const r=fractionNestingDepth(e),i=Array(r).fill(t);return n&&i.push(n),i.join(LOCALE.MESSAGES.regexp.JOINER_FRAC)}function openingFractionVerbose(e){return Span.singleton(nestedFraction(e,LOCALE.MESSAGES.MS.START,LOCALE.MESSAGES.MS.FRAC_V))}function closingFractionVerbose(e){return Span.singleton(nestedFraction(e,LOCALE.MESSAGES.MS.END,LOCALE.MESSAGES.MS.FRAC_V),{kind:"LAST"})}function overFractionVerbose(e){return Span.singleton(nestedFraction(e,LOCALE.MESSAGES.MS.FRAC_OVER),{})}function openingFractionBrief(e){return Span.singleton(nestedFraction(e,LOCALE.MESSAGES.MS.START,LOCALE.MESSAGES.MS.FRAC_B))}function closingFractionBrief(e){return Span.singleton(nestedFraction(e,LOCALE.MESSAGES.MS.END,LOCALE.MESSAGES.MS.FRAC_B),{kind:"LAST"})}function openingFractionSbrief(e){const t=fractionNestingDepth(e);return Span.singleton(1===t?LOCALE.MESSAGES.MS.FRAC_S:LOCALE.FUNCTIONS.combineNestedFraction(LOCALE.MESSAGES.MS.NEST_FRAC,LOCALE.FUNCTIONS.radicalNestDepth(t-1),LOCALE.MESSAGES.MS.FRAC_S))}function closingFractionSbrief(e){const t=fractionNestingDepth(e);return Span.singleton(1===t?LOCALE.MESSAGES.MS.ENDFRAC:LOCALE.FUNCTIONS.combineNestedFraction(LOCALE.MESSAGES.MS.NEST_FRAC,LOCALE.FUNCTIONS.radicalNestDepth(t-1),LOCALE.MESSAGES.MS.ENDFRAC),{kind:"LAST"})}function overFractionSbrief(e){const t=fractionNestingDepth(e);return Span.singleton(1===t?LOCALE.MESSAGES.MS.FRAC_OVER:LOCALE.FUNCTIONS.combineNestedFraction(LOCALE.MESSAGES.MS.NEST_FRAC,LOCALE.FUNCTIONS.radicalNestDepth(t-1),LOCALE.MESSAGES.MS.FRAC_OVER))}function mathspeak_util_isSmallVulgarFraction(e){return LOCALE.FUNCTIONS.fracNestDepth(e)?[e]:[]}function nestedSubSuper(e,t,n){for(;e.parentNode;){const r=e.parentNode,i=r.parentNode;if(!i)break;const s=e.getAttribute&&e.getAttribute("role");(i.tagName===SemanticType.SUBSCRIPT&&e===r.childNodes[1]||i.tagName===SemanticType.TENSOR&&s&&(s===SemanticRole.LEFTSUB||s===SemanticRole.RIGHTSUB))&&(t=n.sub+LOCALE.MESSAGES.regexp.JOINER_SUBSUPER+t),(i.tagName===SemanticType.SUPERSCRIPT&&e===r.childNodes[1]||i.tagName===SemanticType.TENSOR&&s&&(s===SemanticRole.LEFTSUPER||s===SemanticRole.RIGHTSUPER))&&(t=n.sup+LOCALE.MESSAGES.regexp.JOINER_SUBSUPER+t),e=i}return t.trim()}function subscriptVerbose(e){return Span.singleton(nestedSubSuper(e,LOCALE.MESSAGES.MS.SUBSCRIPT,{sup:LOCALE.MESSAGES.MS.SUPER,sub:LOCALE.MESSAGES.MS.SUB}))}function subscriptBrief(e){return Span.singleton(nestedSubSuper(e,LOCALE.MESSAGES.MS.SUB,{sup:LOCALE.MESSAGES.MS.SUP,sub:LOCALE.MESSAGES.MS.SUB}))}function superscriptVerbose(e){return Span.singleton(nestedSubSuper(e,LOCALE.MESSAGES.MS.SUPERSCRIPT,{sup:LOCALE.MESSAGES.MS.SUPER,sub:LOCALE.MESSAGES.MS.SUB}))}function superscriptBrief(e){return Span.singleton(nestedSubSuper(e,LOCALE.MESSAGES.MS.SUP,{sup:LOCALE.MESSAGES.MS.SUP,sub:LOCALE.MESSAGES.MS.SUB}))}function baselineVerbose(e){const t=nestedSubSuper(e,"",{sup:LOCALE.MESSAGES.MS.SUPER,sub:LOCALE.MESSAGES.MS.SUB});return Span.singleton(t?t.replace(new RegExp(LOCALE.MESSAGES.MS.SUB+"$"),LOCALE.MESSAGES.MS.SUBSCRIPT).replace(new RegExp(LOCALE.MESSAGES.MS.SUPER+"$"),LOCALE.MESSAGES.MS.SUPERSCRIPT):LOCALE.MESSAGES.MS.BASELINE)}function baselineBrief(e){const t=nestedSubSuper(e,"",{sup:LOCALE.MESSAGES.MS.SUP,sub:LOCALE.MESSAGES.MS.SUB});return Span.singleton(t||LOCALE.MESSAGES.MS.BASE)}function radicalNestingDepth(e){return getNestingDepth("radical",e,["sqrt","root"],nestingBarriers,{})}function nestedRadical(e,t,n){const r=radicalNestingDepth(e),i=getRootIndex(e);return n=i?LOCALE.FUNCTIONS.combineRootIndex(n,i):n,1===r?n:LOCALE.FUNCTIONS.combineNestedRadical(t,LOCALE.FUNCTIONS.radicalNestDepth(r-1),n)}function getRootIndex(e){const t="sqrt"===e.tagName?"2":evalXPath("children/*[1]",e)[0].textContent.trim();return LOCALE.MESSAGES.MSroots[t]||""}function openingRadicalVerbose(e){return Span.singleton(nestedRadical(e,LOCALE.MESSAGES.MS.NESTED,LOCALE.MESSAGES.MS.STARTROOT))}function closingRadicalVerbose(e){return Span.singleton(nestedRadical(e,LOCALE.MESSAGES.MS.NESTED,LOCALE.MESSAGES.MS.ENDROOT))}function indexRadicalVerbose(e){return Span.singleton(nestedRadical(e,LOCALE.MESSAGES.MS.NESTED,LOCALE.MESSAGES.MS.ROOTINDEX))}function openingRadicalBrief(e){return Span.singleton(nestedRadical(e,LOCALE.MESSAGES.MS.NEST_ROOT,LOCALE.MESSAGES.MS.STARTROOT))}function closingRadicalBrief(e){return Span.singleton(nestedRadical(e,LOCALE.MESSAGES.MS.NEST_ROOT,LOCALE.MESSAGES.MS.ENDROOT))}function indexRadicalBrief(e){return Span.singleton(nestedRadical(e,LOCALE.MESSAGES.MS.NEST_ROOT,LOCALE.MESSAGES.MS.ROOTINDEX))}function openingRadicalSbrief(e){return Span.singleton(nestedRadical(e,LOCALE.MESSAGES.MS.NEST_ROOT,LOCALE.MESSAGES.MS.ROOT))}function indexRadicalSbrief(e){return Span.singleton(nestedRadical(e,LOCALE.MESSAGES.MS.NEST_ROOT,LOCALE.MESSAGES.MS.INDEX))}function underscoreNestingDepth(e){return getNestingDepth("underscore",e,["underscore"],nestingBarriers,{},(function(e){return e.tagName&&e.tagName===SemanticType.UNDERSCORE&&e.childNodes[0].childNodes[1].getAttribute("role")===SemanticRole.UNDERACCENT}))}function nestedUnderscript(e){const t=underscoreNestingDepth(e);return Span.singleton(Array(t).join(LOCALE.MESSAGES.MS.UNDER)+LOCALE.MESSAGES.MS.UNDERSCRIPT)}function overscoreNestingDepth(e){return getNestingDepth("overscore",e,["overscore"],nestingBarriers,{},(function(e){return e.tagName&&e.tagName===SemanticType.OVERSCORE&&e.childNodes[0].childNodes[1].getAttribute("role")===SemanticRole.OVERACCENT}))}function endscripts(e){return Span.singleton(LOCALE.MESSAGES.MS.ENDSCRIPTS)}function nestedOverscript(e){const t=overscoreNestingDepth(e);return Span.singleton(Array(t).join(LOCALE.MESSAGES.MS.OVER)+LOCALE.MESSAGES.MS.OVERSCRIPT)}function determinantIsSimple(e){if(e.tagName!==SemanticType.MATRIX||e.getAttribute("role")!==SemanticRole.DETERMINANT)return[];const t=evalXPath("children/row/children/cell/children/*",e);for(let e,n=0;e=t[n];n++)if(e.tagName!==SemanticType.NUMBER){if(e.tagName===SemanticType.IDENTIFIER){const t=e.getAttribute("role");if(t===SemanticRole.LATINLETTER||t===SemanticRole.GREEKLETTER||t===SemanticRole.OTHERLETTER)continue}return[]}return[e]}function generateBaselineConstraint(){const e=e=>e.map((e=>"ancestor::"+e)),t=e=>"not("+e+")",n=t(e(["subscript","superscript","tensor"]).join(" or ")),r=e(["relseq","multrel"]),i=e(["fraction","punctuation","fenced","sqrt","root"]);let s=[];for(let e,t=0;e=i[t];t++)s=s.concat(r.map((function(t){return e+"/"+t})));return[["ancestor::*/following-sibling::*",n,t(s.join(" | "))].join(" and ")]}function removeParens(e){if(!e.childNodes.length||!e.childNodes[0].childNodes.length||!e.childNodes[0].childNodes[0].childNodes.length)return Span.singleton("");const t=e.childNodes[0].childNodes[0].childNodes[0].textContent;return Span.singleton(t.match(/^\(.+\)$/)?t.slice(1,-1):t)}const componentString=new Map([[3,"CSFleftsuperscript"],[4,"CSFleftsubscript"],[2,"CSFbaseline"],[1,"CSFrightsubscript"],[0,"CSFrightsuperscript"]]),childNumber=new Map([[4,2],[3,3],[2,1],[1,4],[0,5]]);function generateTensorRuleStrings_(e){const t=[];let n="",r="",i=parseInt(e,2);for(let e=0;e<5;e++){const s="children/*["+childNumber.get(e)+"]";if(1&i){const t=componentString.get(e%5);n="[t] "+t+"Verbose; [n] "+s+";"+n,r="[t] "+t+"Brief; [n] "+s+";"+r}else t.unshift("name("+s+')="empty"');i>>=1}return[t,n,r]}function generateTensorRules(e,t=!0){const n=["11111","11110","11101","11100","10111","10110","10101","10100","01111","01110","01101","01100"];for(const r of n){let n="tensor"+r,[i,s,o]=generateTensorRuleStrings_(r);if(e.defineRule(n,"default",s,"self::tensor",...i),t&&(e.defineRule(n,"brief",o,"self::tensor",...i),e.defineRule(n,"sbrief",o,"self::tensor",...i)),!(3&parseInt(r,2)))continue;const a=componentString.get(2);s+="; [t]"+a+"Verbose",o+="; [t]"+a+"Brief",n+="-baseline";const c="((.//*[not(*)])[last()]/@id)!=(((.//ancestor::fraction|ancestor::root|ancestor::sqrt|ancestor::cell|ancestor::line|ancestor::stree)[1]//*[not(*)])[last()]/@id)";e.defineRule(n,"default",s,"self::tensor",c,...i),t&&(e.defineRule(n,"brief",o,"self::tensor",c,...i),e.defineRule(n,"sbrief",o,"self::tensor",c,...i))}}function smallRoot(e){let t=Object.keys(LOCALE.MESSAGES.MSroots).length;if(!t)return[];if(t++,!e.childNodes||0===e.childNodes.length||!e.childNodes[0].childNodes)return[];const n=e.childNodes[0].childNodes[0].textContent;if(!/^\d+$/.test(n))return[];const r=parseInt(n,10);return r>1&&r<=t?[e]:[]}function ordinalCounter(e,t){let n=0;return function(){return LOCALE.NUMBERS.numericOrdinal(++n)+" "+t}}function wordCounter(e,t){let n=0;return function(){return LOCALE.NUMBERS.numberToOrdinal(++n,!1)+" "+t}}function vulgarFraction(e){const t=convertVulgarFraction(e,LOCALE.MESSAGES.MS.FRAC_OVER);return t.convertible&&t.enumerator&&t.denominator?[Span.node(LOCALE.NUMBERS.numberToWords(t.enumerator),e.childNodes[0].childNodes[0],{separator:""}),Span.stringAttr(LOCALE.NUMBERS.vulgarSep,{separator:""}),Span.node(LOCALE.NUMBERS.numberToOrdinal(t.denominator,1!==t.enumerator),e.childNodes[0].childNodes[1])]:[Span.node(t.content||"",e)]}function ordinalPosition(e){const t=toArray(e.parentNode.childNodes);return Span.singleton(LOCALE.NUMBERS.numericOrdinal(t.indexOf(e)+1).toString())}function ClearspeakRules(){addStore(DynamicCstr.BASE_LOCALE+".speech.clearspeak","",{CTFpauseSeparator:pauseSeparator,CTFnodeCounter:clearspeak_util_nodeCounter,CTFcontentIterator:contentIterator,CSFvulgarFraction:vulgarFraction,CQFvulgarFractionSmall:isSmallVulgarFraction,CQFcellsSimple:allCellsSimple,CSFordinalExponent:ordinalExponent,CSFwordOrdinal:clearspeak_util_wordOrdinal,CQFmatchingFences:matchingFences,CSFnestingDepth:nestingDepth,CQFfencedArguments:fencedArguments,CQFsimpleArguments:simpleArguments,CQFspaceoutNumber:spaceoutNumber})}function mathspeak_french_util_baselineVerbose(e){const t=baselineVerbose(e);return t[0].speech=t[0].speech.replace(/-$/,""),t}function mathspeak_french_util_baselineBrief(e){const t=baselineBrief(e);return t[0].speech=t[0].speech.replace(/-$/,""),t}function leftSuperscriptVerbose(e){const t=superscriptVerbose(e);return t[0].speech=t[0].speech.replace(/^exposant/,"exposant gauche"),t}function leftSubscriptVerbose(e){const t=subscriptVerbose(e);return t[0].speech=t[0].speech.replace(/^indice/,"indice gauche"),t}function leftSuperscriptBrief(e){const t=superscriptBrief(e);return t[0].speech=t[0].speech.replace(/^sup/,"sup gauche"),t}function leftSubscriptBrief(e){const t=subscriptBrief(e);return t[0].speech=t[0].speech.replace(/^sub/,"sub gauche"),t}function mathspeak_korean_util_nestedFraction(e,t,n){const r=fractionNestingDepth(e),i=[...Array(r)].map((e=>t));return n&&i.unshift(n),i.join(LOCALE.MESSAGES.regexp.JOINER_FRAC)}function mathspeak_korean_util_openingFractionVerbose(e){return Span.singleton(mathspeak_korean_util_nestedFraction(e,LOCALE.MESSAGES.MS.START,LOCALE.MESSAGES.MS.FRAC_V))}function mathspeak_korean_util_closingFractionVerbose(e){return Span.singleton(mathspeak_korean_util_nestedFraction(e,LOCALE.MESSAGES.MS.END,LOCALE.MESSAGES.MS.FRAC_V))}function mathspeak_korean_util_openingFractionBrief(e){return Span.singleton(mathspeak_korean_util_nestedFraction(e,LOCALE.MESSAGES.MS.START,LOCALE.MESSAGES.MS.FRAC_B))}function mathspeak_korean_util_closingFractionBrief(e){return Span.singleton(mathspeak_korean_util_nestedFraction(e,LOCALE.MESSAGES.MS.END,LOCALE.MESSAGES.MS.FRAC_B))}function mathspeak_korean_util_openingFractionSbrief(e){const t=fractionNestingDepth(e);return 1===t?Span.singleton(LOCALE.MESSAGES.MS.FRAC_S):Span.singleton(LOCALE.FUNCTIONS.combineNestedFraction(LOCALE.FUNCTIONS.radicalNestDepth(t-1),LOCALE.MESSAGES.MS.NEST_FRAC,LOCALE.MESSAGES.MS.FRAC_S))}function mathspeak_korean_util_closingFractionSbrief(e){const t=fractionNestingDepth(e);return 1===t?Span.singleton(LOCALE.MESSAGES.MS.ENDFRAC):Span.singleton(LOCALE.FUNCTIONS.combineNestedFraction(LOCALE.FUNCTIONS.radicalNestDepth(t-1),LOCALE.MESSAGES.MS.NEST_FRAC,LOCALE.MESSAGES.MS.ENDFRAC))}function mathspeak_korean_util_overFractionSbrief(e){const t=fractionNestingDepth(e);return 1===t?Span.singleton(LOCALE.MESSAGES.MS.FRAC_OVER):Span.singleton(LOCALE.FUNCTIONS.combineNestedFraction(LOCALE.FUNCTIONS.radicalNestDepth(t-1),LOCALE.MESSAGES.MS.NEST_FRAC,LOCALE.MESSAGES.MS.FRAC_OVER))}function isSimpleIndex(e){return 1===evalXPath("children/*[1]",e)[0].toString().match(/[^>\u2062>]+<\/[^>]*>/g).length?[e]:[]}function mathspeak_korean_util_nestedRadical(e,t,n){const r=radicalNestingDepth(e);return 1===r?n:LOCALE.FUNCTIONS.combineNestedRadical(LOCALE.FUNCTIONS.radicalNestDepth(r-1),t,n)}function mathspeak_korean_util_openingRadicalVerbose(e){return Span.singleton(mathspeak_korean_util_nestedRadical(e,LOCALE.MESSAGES.MS.NESTED,LOCALE.MESSAGES.MS.STARTROOT))}function mathspeak_korean_util_closingRadicalVerbose(e){return Span.singleton(mathspeak_korean_util_nestedRadical(e,LOCALE.MESSAGES.MS.NESTED,LOCALE.MESSAGES.MS.ENDROOT))}function mathspeak_korean_util_openingRadicalBrief(e){return Span.singleton(mathspeak_korean_util_nestedRadical(e,LOCALE.MESSAGES.MS.NEST_ROOT,LOCALE.MESSAGES.MS.STARTROOT))}function mathspeak_korean_util_closingRadicalBrief(e){return Span.singleton(mathspeak_korean_util_nestedRadical(e,LOCALE.MESSAGES.MS.NEST_ROOT,LOCALE.MESSAGES.MS.ENDROOT))}function mathspeak_korean_util_openingRadicalSbrief(e){return Span.singleton(mathspeak_korean_util_nestedRadical(e,LOCALE.MESSAGES.MS.NEST_ROOT,LOCALE.MESSAGES.MS.ROOT))}function mathspeak_korean_util_getRootIndex(e){const t=evalXPath("children/*[1]",e)[0].textContent.trim();return LOCALE.MESSAGES.MSroots[t]||t+"\uc81c\uacf1\uadfc"}function indexRadical(e,t){const n=mathspeak_korean_util_getRootIndex(e);return n||t}function mathspeak_korean_util_indexRadicalVerbose(e){return Span.singleton(indexRadical(e,LOCALE.MESSAGES.MS.ROOTINDEX))}function mathspeak_korean_util_indexRadicalBrief(e){return Span.singleton(indexRadical(e,LOCALE.MESSAGES.MS.ROOTINDEX))}function mathspeak_korean_util_indexRadicalSbrief(e){return Span.singleton(indexRadical(e,LOCALE.MESSAGES.MS.INDEX))}function ordinalConversion(e){const t=evalXPath("children/*",e);return Span.singleton(LOCALE.NUMBERS.wordOrdinal(t.length))}function decreasedOrdinalConversion(e){const t=evalXPath("children/*",e);return Span.singleton(LOCALE.NUMBERS.wordOrdinal(t.length-1))}function listOrdinalConversion(e){const t=evalXPath("children/*",e),n=evalXPath("content/*",e);return Span.singleton(LOCALE.NUMBERS.wordOrdinal(t.length-n.length))}function checkDepth(e){return getDepthValue(e,[])>3?[]:[e]}function getDepthValue(e,t){const n=e.getAttribute("role");t.indexOf(n)>-1||t.push(n);const r=XpathUtil.evalXPath("children/*",e);let i=0,s=0;return r.length?(r.forEach((e=>{s=getDepthValue(e,t),i=s>i?s:i})),i+1):0}function unitMultipliers(e,t){const n=e;let r=0;return function(){const e=AuditoryDescription.create({text:rightMostUnit(n[r])&&leftMostUnit(n[r+1])?LOCALE.MESSAGES.unitTimes:""},{});return r++,[e]}}const SCRIPT_ELEMENTS=[SemanticType.SUPERSCRIPT,SemanticType.SUBSCRIPT,SemanticType.OVERSCORE,SemanticType.UNDERSCORE];function rightMostUnit(e){for(;e;){if("unit"===e.getAttribute("role"))return!0;const t=e.tagName,n=evalXPath("children/*",e);e=-1!==SCRIPT_ELEMENTS.indexOf(t)?n[0]:n[n.length-1]}return!1}function leftMostUnit(e){for(;e;){if("unit"===e.getAttribute("role"))return!0;e=evalXPath("children/*",e)[0]}return!1}function oneLeft(e){for(;e;){if("number"===e.tagName&&"1"===e.textContent)return[e];if("infixop"!==e.tagName||"multiplication"!==e.getAttribute("role")&&"implicit"!==e.getAttribute("role"))return[];e=evalXPath("children/*",e)[0]}return[]}function MathspeakRules(){addStore(DynamicCstr.BASE_LOCALE+".speech.mathspeak","",{CQFspaceoutNumber:spaceoutNumber,CQFspaceoutIdentifier:spaceoutIdentifier,CSFspaceoutText:spaceoutText,CSFopenFracVerbose:openingFractionVerbose,CSFcloseFracVerbose:closingFractionVerbose,CSFoverFracVerbose:overFractionVerbose,CSFopenFracBrief:openingFractionBrief,CSFcloseFracBrief:closingFractionBrief,CSFopenFracSbrief:openingFractionSbrief,CSFcloseFracSbrief:closingFractionSbrief,CSFoverFracSbrief:overFractionSbrief,CSFvulgarFraction:vulgarFraction,CQFvulgarFractionSmall:mathspeak_util_isSmallVulgarFraction,CSFopenRadicalVerbose:openingRadicalVerbose,CSFcloseRadicalVerbose:closingRadicalVerbose,CSFindexRadicalVerbose:indexRadicalVerbose,CSFopenRadicalBrief:openingRadicalBrief,CSFcloseRadicalBrief:closingRadicalBrief,CSFindexRadicalBrief:indexRadicalBrief,CSFopenRadicalSbrief:openingRadicalSbrief,CSFindexRadicalSbrief:indexRadicalSbrief,CQFisSmallRoot:smallRoot,CSFsuperscriptVerbose:superscriptVerbose,CSFsuperscriptBrief:superscriptBrief,CSFsubscriptVerbose:subscriptVerbose,CSFsubscriptBrief:subscriptBrief,CSFbaselineVerbose:baselineVerbose,CSFbaselineBrief:baselineBrief,CSFleftsuperscriptVerbose:superscriptVerbose,CSFleftsubscriptVerbose:subscriptVerbose,CSFrightsuperscriptVerbose:superscriptVerbose,CSFrightsubscriptVerbose:subscriptVerbose,CSFleftsuperscriptBrief:superscriptBrief,CSFleftsubscriptBrief:subscriptBrief,CSFrightsuperscriptBrief:superscriptBrief,CSFrightsubscriptBrief:subscriptBrief,CSFunderscript:nestedUnderscript,CSFoverscript:nestedOverscript,CSFendscripts:endscripts,CTFordinalCounter:ordinalCounter,CTFwordCounter:wordCounter,CTFcontentIterator:contentIterator,CQFdetIsSimple:determinantIsSimple,CSFRemoveParens:removeParens,CQFresetNesting:resetNestingDepth,CGFbaselineConstraint:generateBaselineConstraint,CGFtensorRules:generateTensorRules}),addStore("es.speech.mathspeak",DynamicCstr.BASE_LOCALE+".speech.mathspeak",{CTFunitMultipliers:unitMultipliers,CQFoneLeft:oneLeft}),addStore("fr.speech.mathspeak",DynamicCstr.BASE_LOCALE+".speech.mathspeak",{CSFbaselineVerbose:mathspeak_french_util_baselineVerbose,CSFbaselineBrief:mathspeak_french_util_baselineBrief,CSFleftsuperscriptVerbose:leftSuperscriptVerbose,CSFleftsubscriptVerbose:leftSubscriptVerbose,CSFleftsuperscriptBrief:leftSuperscriptBrief,CSFleftsubscriptBrief:leftSubscriptBrief}),addStore("ko.speech.mathspeak",DynamicCstr.BASE_LOCALE+".speech.mathspeak",{CSFopenFracVerbose:mathspeak_korean_util_openingFractionVerbose,CSFcloseFracVerbose:mathspeak_korean_util_closingFractionVerbose,CSFopenFracBrief:mathspeak_korean_util_openingFractionBrief,CSFcloseFracBrief:mathspeak_korean_util_closingFractionBrief,CSFopenFracSbrief:mathspeak_korean_util_openingFractionSbrief,CSFoverFracSbrief:mathspeak_korean_util_overFractionSbrief,CSFcloseFracSbrief:mathspeak_korean_util_closingFractionSbrief,CQFisSimpleIndex:isSimpleIndex,CSFindexRadicalVerbose:mathspeak_korean_util_indexRadicalVerbose,CSFindexRadicalBrief:mathspeak_korean_util_indexRadicalBrief,CSFindexRadicalSbrief:mathspeak_korean_util_indexRadicalSbrief,CSFopenRadicalVerbose:mathspeak_korean_util_openingRadicalVerbose,CSFcloseRadicalVerbose:mathspeak_korean_util_closingRadicalVerbose,CSFopenRadicalBrief:mathspeak_korean_util_openingRadicalBrief,CSFcloseRadicalBrief:mathspeak_korean_util_closingRadicalBrief,CSFopenRadicalSbrief:mathspeak_korean_util_openingRadicalSbrief})}function openingFraction(e){const t=fractionNestingDepth(e);return Span.singleton(new Array(t).join(LOCALE.MESSAGES.MS.FRACTION_REPEAT)+LOCALE.MESSAGES.MS.FRACTION_START)}function closingFraction(e){const t=fractionNestingDepth(e);return Span.singleton(new Array(t).join(LOCALE.MESSAGES.MS.FRACTION_REPEAT)+LOCALE.MESSAGES.MS.FRACTION_END)}function overFraction(e){const t=fractionNestingDepth(e);return Span.singleton(new Array(t).join(LOCALE.MESSAGES.MS.FRACTION_REPEAT)+LOCALE.MESSAGES.MS.FRACTION_OVER)}function overBevelledFraction(e){const t=fractionNestingDepth(e);return Span.singleton(new Array(t).join(LOCALE.MESSAGES.MS.FRACTION_REPEAT)+"\u2838"+LOCALE.MESSAGES.MS.FRACTION_OVER)}function hyperFractionBoundary(e){return LOCALE.MESSAGES.regexp.HYPER===fractionNestingDepth(e).toString()?[e]:[]}function nemeth_util_nestedRadical(e,t){const n=nemeth_util_radicalNestingDepth(e);return Span.singleton(1===n?t:new Array(n).join(LOCALE.MESSAGES.MS.NESTED)+t)}function nemeth_util_radicalNestingDepth(e,t){const n=t||0;return e.parentNode?nemeth_util_radicalNestingDepth(e.parentNode,"root"===e.tagName||"sqrt"===e.tagName?n+1:n):n}function openingRadical(e){return nemeth_util_nestedRadical(e,LOCALE.MESSAGES.MS.STARTROOT)}function closingRadical(e){return nemeth_util_nestedRadical(e,LOCALE.MESSAGES.MS.ENDROOT)}function nemeth_util_indexRadical(e){return nemeth_util_nestedRadical(e,LOCALE.MESSAGES.MS.ROOTINDEX)}function enlargeFence(e){const t="\u2820";if(1===e.length)return t+e;const n=e.split("");return n.every((function(e){return"\u2833"===e}))?t+n.join(t):e.slice(0,-1)+t+e.slice(-1)}Grammar.getInstance().setCorrection("enlargeFence",enlargeFence);const NUMBER_PROPAGATORS=[SemanticType.MULTIREL,SemanticType.RELSEQ,SemanticType.APPL,SemanticType.ROW,SemanticType.LINE],NUMBER_INHIBITORS=[SemanticType.SUBSCRIPT,SemanticType.SUPERSCRIPT,SemanticType.OVERSCORE,SemanticType.UNDERSCORE];function checkParent(e,t){const n=e.parent;if(!n)return!1;const r=n.type;return-1!==NUMBER_PROPAGATORS.indexOf(r)||r===SemanticType.PREFIXOP&&n.role===SemanticRole.NEGATIVE&&!t.script&&!t.enclosed||r===SemanticType.PREFIXOP&&n.role===SemanticRole.GEOMETRY||!(r!==SemanticType.PUNCTUATED||t.enclosed&&n.role!==SemanticRole.TEXT)}function propagateNumber(e,t){return e.childNodes.length?(-1!==NUMBER_INHIBITORS.indexOf(e.type)&&(t.script=!0),e.type===SemanticType.FENCED?(t.number=!1,t.enclosed=!0,["",t]):e.type===SemanticType.PREFIXOP&&e.role!==SemanticRole.GEOMETRY&&e.role!==SemanticRole.NEGATIVE?(t.number=!1,["",t]):(checkParent(e,t)&&(t.number=!0,t.enclosed=!1),["",t])):(checkParent(e,t)&&(t.number=!0,t.script=!1,t.enclosed=!1),[t.number?"number":"",{number:!1,enclosed:t.enclosed,script:t.script}])}function annotateDepth(e){if(!e.parent)return[1];return[parseInt(e.parent.annotation.depth[0])+1]}function relationIterator(e,t){var n;const r=e.slice(0);let i=!0;const s=e[0].parentNode.parentNode,o=null===(n=s.getAttribute("annotation"))||void 0===n?void 0:n.match(/depth:(\d+)/),a=o?o[1]:"";let c;return c=e.length>0?evalXPath("./content/*",s):[],function(){const e=c.shift(),n=r.shift(),o=r[0],l=t?[AuditoryDescription.create({text:t},{translate:!0})]:[];if(!e)return l;const u=n?nestedSubSuper(n,"",{sup:LOCALE.MESSAGES.MS.SUPER,sub:LOCALE.MESSAGES.MS.SUB}):"",m=n&&"EMPTY"!==dom_util_tagName(n)||i&&s&&s.previousSibling?[AuditoryDescription.create({text:LOCALE.MESSAGES.regexp.SPACE+u},{})]:[],d=o&&"EMPTY"!==dom_util_tagName(o)||!c.length&&s&&s.nextSibling?[AuditoryDescription.create({text:LOCALE.MESSAGES.regexp.SPACE},{})]:[],h=engine_Engine.evaluateNode(e);return h.unshift(new AuditoryDescription({text:"",layout:`beginrel${a}`})),h.push(new AuditoryDescription({text:"",layout:`endrel${a}`})),i=!1,l.concat(m,h,d)}}function implicitIterator(e,t){const n=e.slice(0);let r;return r=e.length>0?evalXPath("../../content/*",e[0]):[],function(){const e=n.shift(),i=n[0],s=r.shift(),o=t?[AuditoryDescription.create({text:t},{translate:!0})]:[];if(!s)return o;const a=e&&"NUMBER"===dom_util_tagName(e),c=i&&"NUMBER"===dom_util_tagName(i);return o.concat(a&&c&&s.getAttribute("role")===SemanticRole.SPACE?[AuditoryDescription.create({text:LOCALE.MESSAGES.regexp.SPACE},{})]:[])}}function ignoreEnglish(e){return correctFont(e,LOCALE.ALPHABETS.languagePrefix.english)}function nemeth_util_contentIterator(e,t){var n;const r=contentIterator(e,t),i=null===(n=e[0].parentNode.parentNode.getAttribute("annotation"))||void 0===n?void 0:n.match(/depth:(\d+)/),s=i?i[1]:"";return function(){const e=r();return e.unshift(new AuditoryDescription({text:"",layout:`beginrel${s}`})),e.push(new AuditoryDescription({text:"",layout:`endrel${s}`})),e}}function literal(e){return Array.from(e).map((e=>engine_Engine.getInstance().evaluator(e,engine_Engine.getInstance().dynamicCstr))).join("")}function PrefixRules(){addStore("en.prefix.default","",{CSFordinalPosition:ordinalPosition})}function OtherRules(){addStore("en.speech.chromevox","",{CTFnodeCounter:nodeCounter,CTFcontentIterator:contentIterator}),addStore("en.speech.emacspeak","en.speech.chromevox",{CQFvulgarFractionSmall:mathspeak_util_isSmallVulgarFraction,CSFvulgarFraction:vulgarFraction}),addStore("ko.summary.","ko.speech.mathspeak",{CSFordinalConversion:ordinalConversion,CSFdecreasedOrdinalConversion:decreasedOrdinalConversion,CSFlistOrdinalConversion:listOrdinalConversion})}function BrailleRules(){addStore("nemeth.braille.default",DynamicCstr.BASE_LOCALE+".speech.mathspeak",{CSFopenFraction:openingFraction,CSFcloseFraction:closingFraction,CSFoverFraction:overFraction,CSFoverBevFraction:overBevelledFraction,CQFhyperFraction:hyperFractionBoundary,CSFopenRadical:openingRadical,CSFcloseRadical:closingRadical,CSFindexRadical:nemeth_util_indexRadical,CSFsubscript:subscriptVerbose,CSFsuperscript:superscriptVerbose,CSFbaseline:baselineVerbose,CGFtensorRules:e=>generateTensorRules(e,!1),CTFcontentIterator:nemeth_util_contentIterator,CTFrelationIterator:relationIterator,CTFimplicitIterator:implicitIterator}),addStore("euro.braille.default","nemeth.braille.default",{})}register(new SemanticVisitor("nemeth","number",propagateNumber,{number:!0})),register(new SemanticVisitor("depth","depth",annotateDepth)),activate("depth","depth"),Grammar.getInstance().setCorrection("ignoreEnglish",ignoreEnglish),Grammar.getInstance().setCorrection("literal",literal);let INIT=!1;function init(){INIT||(MathspeakRules(),ClearspeakRules(),PrefixRules(),OtherRules(),BrailleRules(),INIT=!0)}class SpeechRule{constructor(e,t,n,r){this.name=e,this.dynamicCstr=t,this.precondition=n,this.action=r,this.context=null}toString(){return this.name+" | "+this.dynamicCstr.toString()+" | "+this.precondition.toString()+" ==> "+this.action.toString()}}var ActionType,TrieNodeKind;function actionFromString(e){switch(e){case"[n]":return ActionType.NODE;case"[m]":return ActionType.MULTI;case"[t]":return ActionType.TEXT;case"[p]":return ActionType.PERSONALITY;default:throw"Parse error: "+e}}function actionToString(e){switch(e){case ActionType.NODE:return"[n]";case ActionType.MULTI:return"[m]";case ActionType.TEXT:return"[t]";case ActionType.PERSONALITY:return"[p]";default:throw"Unknown type error: "+e}}!function(e){e.NODE="NODE",e.MULTI="MULTI",e.TEXT="TEXT",e.PERSONALITY="PERSONALITY"}(ActionType||(ActionType={}));class Component{static grammarFromString(e){return Grammar.parseInput(e)}static fromString(e){const t={type:actionFromString(e.substring(0,3))};let n=e.slice(3).trim();if(!n)throw new OutputError("Missing content.");switch(t.type){case ActionType.TEXT:if('"'===n[0]){const e=splitString(n,"\\(")[0].trim();if('"'!==e.slice(-1))throw new OutputError("Invalid string syntax.");t.content=e,n=n.slice(e.length).trim(),-1===n.indexOf("(")&&(n="");break}case ActionType.NODE:case ActionType.MULTI:{const e=n.indexOf(" (");if(-1===e){t.content=n.trim(),n="";break}t.content=n.substring(0,e).trim(),n=n.slice(e).trim()}}if(n){const e=Component.attributesFromString(n);e.grammar&&(t.grammar=e.grammar,delete e.grammar),Object.keys(e).length&&(t.attributes=e)}return new Component(t)}static attributesFromString(e){if("("!==e[0]||")"!==e.slice(-1))throw new OutputError("Invalid attribute expression: "+e);const t={},n=splitString(e.slice(1,-1),",");for(const e of n){const n=e.indexOf(":");if(-1===n)t[e.trim()]="true";else{const r=e.substring(0,n).trim(),i=e.slice(n+1).trim();t[r]=r===ATTRIBUTE?Component.grammarFromString(i):i}}return t}constructor({type:e,content:t,attributes:n,grammar:r}){this.type=e,this.content=t,this.attributes=n,this.grammar=r}toString(){let e="";e+=actionToString(this.type),e+=this.content?" "+this.content:"";const t=this.attributesToString();return e+=t?" "+t:"",e}grammarToString(){return this.getGrammar().join(":")}getGrammar(){if(!this.grammar)return[];const e=[];for(const[t,n]of Object.entries(this.grammar))e.push(!0===n?t:!1===n?`!${t}`:`${t}=${n}`);return e}attributesToString(){const e=this.getAttributes(),t=this.grammarToString();return t&&e.push("grammar:"+t),e.length>0?"("+e.join(", ")+")":""}getAttributes(){if(!this.attributes)return[];const e=[];for(const[t,n]of Object.entries(this.attributes))e.push("true"===n?t:`${t}:${n}`);return e}}class Action{static fromString(e){const t=splitString(e,";").filter((function(e){return e.match(/\S/)})).map((function(e){return e.trim()})),n=[];for(let e=0,r=t.length;e<r;e++){const r=Component.fromString(t[e]);r&&n.push(r)}return Action.naiveSpan(n),new Action(n)}static naiveSpan(e){var t;let n=!1;for(let r,i=0;r=e[i];i++){if(n&&(r.type!==ActionType.TEXT||'"'!==r.content[0]&&!r.content.match(/^CSF/)))continue;if(!n&&r.type===ActionType.PERSONALITY)continue;if(!n){n=!0;continue}if(null===(t=r.attributes)||void 0===t?void 0:t.span)continue;const s=e[i+1];s&&s.type!==ActionType.NODE||Action.addNaiveSpan(r,s?s.content:"LAST")}}static addNaiveSpan(e,t){e.attributes||(e.attributes={}),e.attributes.span=t}constructor(e){this.components=e}toString(){return this.components.map((function(e){return e.toString()})).join("; ")}}class Precondition{static constraintValue(e,t){for(let n,r=0;n=t[r];r++)if(e.match(n))return++r;return 0}toString(){const e=this.constraints.join(", ");return`${this.query}, ${e} (${this.priority}, ${this.rank})`}constructor(e,...t){this.query=e,this.constraints=t;const[n,r]=this.presetPriority();this.priority=n?r:this.calculatePriority()}calculatePriority(){const e=Precondition.constraintValue(this.query,Precondition.queryPriorities);if(!e)return 0;const t=this.query.match(/^self::.+\[(.+)\]/);let n=0;if((null==t?void 0:t.length)&&t[1]){const e=t[1];n=Precondition.constraintValue(e,Precondition.attributePriorities)}return 100*e+10*n}presetPriority(){if(!this.constraints.length)return[!1,0];const e=this.constraints[this.constraints.length-1].match(/^priority=(.*$)/);if(!e)return[!1,0];this.constraints.pop();const t=parseFloat(e[1]);return[!0,isNaN(t)?0:t]}}Precondition.queryPriorities=[/^self::\*$/,/^self::[\w-]+$/,/^self::\*\[.+\]$/,/^self::[\w-]+\[.+\]$/],Precondition.attributePriorities=[/^@[\w-]+$/,/^@[\w-]+!=".+"$/,/^not\(contains\(@[\w-]+,\s*".+"\)\)$/,/^contains\(@[\w-]+,".+"\)$/,/^@[\w-]+=".+"$/];class OutputError extends SREError{constructor(e){super(e),this.name="RuleError"}}function splitString(e,t){const n=[];let r="";for(;""!==e;){const i=e.search(t);if(-1===i){if((e.match(/"/g)||[]).length%2!=0)throw new OutputError("Invalid string in expression: "+e);n.push(r+e),r="",e=""}else if((e.substring(0,i).match(/"/g)||[]).length%2==0)n.push(r+e.substring(0,i)),r="",e=e.substring(i+1);else{const t=e.substring(i).search('"');if(-1===t)throw new OutputError("Invalid string in expression: "+e);r+=e.substring(0,i+t+1),e=e.substring(i+t+1)}}return r&&n.push(r),n}class FunctionsStore{constructor(e,t){this.prefix=e,this.store=t}add(e,t){this.checkCustomFunctionSyntax_(e)&&(this.store[e]=t)}addStore(e){const t=Object.keys(e.store);for(let n,r=0;n=t[r];r++)this.add(n,e.store[n])}lookup(e){return this.store[e]}checkCustomFunctionSyntax_(e){const t=new RegExp("^"+this.prefix);return!!e.match(t)||(console.error("FunctionError: Invalid function name. Expected prefix "+this.prefix),!1)}}class CustomQueries extends FunctionsStore{constructor(){super("CQF",{})}}class CustomStrings extends FunctionsStore{constructor(){super("CSF",{})}}class ContextFunctions extends FunctionsStore{constructor(){super("CTF",{})}}class CustomGenerators extends FunctionsStore{constructor(){super("CGF",{})}}class SpeechRuleContext{constructor(){this.customQueries=new CustomQueries,this.customStrings=new CustomStrings,this.contextFunctions=new ContextFunctions,this.customGenerators=new CustomGenerators}applyCustomQuery(e,t){const n=this.customQueries.lookup(t);return n?n(e):null}applySelector(e,t){return this.applyCustomQuery(e,t)||evalXPath(t,e)}applyQuery(e,t){const n=this.applySelector(e,t);return n.length>0?n[0]:null}applyConstraint(e,t){return!!this.applyQuery(e,t)||evaluateBoolean(t,e)}constructString(e,t){const n=this.constructString_(e,t);return Array.isArray(n)?n.map((e=>e.speech)).join(""):n}constructSpan(e,t,n){const r=this.constructString_(e,t);if(Array.isArray(r)){const e=r[r.length-1];return e.attributes=Object.assign({},n,e.attributes),r}return[Span.node(r,e,n)]}constructString_(e,t){if(!t)return"";if('"'===t.charAt(0))return t.slice(1,-1);const n=this.customStrings.lookup(t);return n?n(e):evaluateString(t,e)}parse(e){const t=Array.isArray(e)?e:Object.entries(e);for(const e of t){switch(e[0].slice(0,3)){case"CQF":this.customQueries.add(e[0],e[1]);break;case"CSF":this.customStrings.add(e[0],e[1]);break;case"CTF":this.contextFunctions.add(e[0],e[1]);break;case"CGF":this.customGenerators.add(e[0],e[1]);break;default:console.error("FunctionError: Invalid function name "+e[0])}}}}class BaseRuleStore{static compareStaticConstraints_(e,t){if(e.length!==t.length)return!1;for(let n,r=0;n=e[r];r++)if(-1===t.indexOf(n))return!1;return!0}static comparePreconditions_(e,t){const n=e.precondition,r=t.precondition;return n.query===r.query&&BaseRuleStore.compareStaticConstraints_(n.constraints,r.constraints)}constructor(){this.context=new SpeechRuleContext,this.parseOrder=DynamicCstr.DEFAULT_ORDER,this.parser=new DynamicCstrParser(this.parseOrder),this.locale=DynamicCstr.DEFAULT_VALUES[Axis.LOCALE],this.modality=DynamicCstr.DEFAULT_VALUES[Axis.MODALITY],this.domain="",this.initialized=!1,this.inherits=null,this.kind="standard",this.customTranscriptions={},this.preconditions=new Map,this.speechRules_=[],this.rank=0,this.parseMethods={Rule:this.defineRule,Generator:this.generateRules,Action:this.defineAction,Precondition:this.definePrecondition,Ignore:this.ignoreRules}}defineRule(e,t,n,r,...i){const s=this.parseAction(n),o=this.parsePrecondition(r,i),a=this.parseCstr(t);if(!(s&&o&&a))return console.error(`Rule Error: ${r}, (${t}): ${n}`),null;const c=new SpeechRule(e,a,o,s);return c.precondition.rank=this.rank++,this.addRule(c),c}addRule(e){e.context=this.context,this.speechRules_.unshift(e)}deleteRule(e){const t=this.speechRules_.indexOf(e);-1!==t&&this.speechRules_.splice(t,1)}findRule(e){for(let t,n=0;t=this.speechRules_[n];n++)if(e(t))return t;return null}findAllRules(e){return this.speechRules_.filter(e)}evaluateDefault(e){const t=e.textContent.slice(0);return t.match(/^\s+$/)?this.evaluateWhitespace(t):this.evaluateString(t)}evaluateWhitespace(e){return[]}evaluateCustom(e){const t=this.customTranscriptions[e];return void 0!==t?AuditoryDescription.create({text:t},{adjust:!0,translate:!1}):null}evaluateCharacter(e){return this.evaluateCustom(e)||AuditoryDescription.create({text:e},{adjust:!0,translate:!0})}removeDuplicates(e){for(let t,n=this.speechRules_.length-1;t=this.speechRules_[n];n--)t!==e&&e.dynamicCstr.equal(t.dynamicCstr)&&BaseRuleStore.comparePreconditions_(t,e)&&this.speechRules_.splice(n,1)}getSpeechRules(){return this.speechRules_}setSpeechRules(e){this.speechRules_=e}getPreconditions(){return this.preconditions}parseCstr(e){try{return this.parser.parse(this.locale+"."+this.modality+(this.domain?"."+this.domain:"")+"."+e)}catch(t){if("RuleError"===t.name)return console.error("Rule Error ",`Illegal Dynamic Constraint: ${e}.`,t.message),null;throw t}}parsePrecondition(e,t){try{const n=this.parsePrecondition_(e);e=n[0];let r=n.slice(1);for(const e of t)r=r.concat(this.parsePrecondition_(e));return new Precondition(e,...r)}catch(n){if("RuleError"===n.name)return console.error("Rule Error ",`Illegal preconditions: ${e}, ${t}.`,n.message),null;throw n}}parseAction(e){try{return Action.fromString(e)}catch(t){if("RuleError"===t.name)return console.error("Rule Error ",`Illegal action: ${e}.`,t.message),null;throw t}}parse(e){this.modality=e.modality||this.modality,this.locale=e.locale||this.locale,this.domain=e.domain||this.domain,this.context.parse(e.functions||[]),"actions"!==e.kind&&(this.kind=e.kind||this.kind,this.inheritRules()),this.parseRules(e.rules||[])}parseRules(e){for(let t,n=0;t=e[n];n++){const e=t[0],n=this.parseMethods[e];e&&n&&n.apply(this,t.slice(1))}}generateRules(e){const t=this.context.customGenerators.lookup(e);t&&t(this)}defineAction(e,t){let n;try{n=Action.fromString(t)}catch(e){if("RuleError"===e.name)return void console.error("Action Error ",t,e.message);throw e}const r=this.getFullPreconditions(e);if(!r)return void console.error(`Action Error: No precondition for action ${e}`);this.ignoreRules(e);const i=new RegExp("^\\w+\\.\\w+\\."+(this.domain?"\\w+\\.":""));r.conditions.forEach((([t,r])=>{const s=this.parseCstr(t.toString().replace(i,""));this.addRule(new SpeechRule(e,s,r,n))}))}getFullPreconditions(e){const t=this.preconditions.get(e);return t||!this.inherits?t:this.inherits.getFullPreconditions(e)}definePrecondition(e,t,n,...r){const i=this.parsePrecondition(n,r),s=this.parseCstr(t);i&&s?(i.rank=this.rank++,this.preconditions.set(e,new Condition(s,i))):console.error(`Precondition Error: ${n}, (${t})`)}inheritRules(){if(!this.inherits||!this.inherits.getSpeechRules().length)return;const e=new RegExp("^\\w+\\.\\w+\\."+(this.domain?"\\w+\\.":""));this.inherits.getSpeechRules().forEach((t=>{const n=this.parseCstr(t.dynamicCstr.toString().replace(e,""));this.addRule(new SpeechRule(t.name,n,t.precondition,t.action))}))}ignoreRules(e,...t){let n=this.findAllRules((t=>t.name===e));if(!t.length)return void n.forEach(this.deleteRule.bind(this));let r=[];for(const e of t){const t=this.parseCstr(e);for(const e of n)t.equal(e.dynamicCstr)?this.deleteRule(e):r.push(e);n=r,r=[]}}parsePrecondition_(e){const t=this.context.customGenerators.lookup(e);return t?t():[e]}}class Condition{constructor(e,t){this.base=e,this._conditions=[],this.constraints=[],this.allCstr={},this.constraints.push(e),this.addCondition(e,t)}get conditions(){return this._conditions}addConstraint(e){if(this.constraints.filter((t=>t.equal(e))).length)return;this.constraints.push(e);const t=[];for(const[n,r]of this.conditions)this.base.equal(n)&&t.push([e,r]);this._conditions=this._conditions.concat(t)}addBaseCondition(e){this.addCondition(this.base,e)}addFullCondition(e){this.constraints.forEach((t=>this.addCondition(t,e)))}addCondition(e,t){const n=e.toString()+" "+t.toString();this.allCstr.condStr||(this.allCstr[n]=!0,this._conditions.push([e,t]))}}class MathStore extends BaseRuleStore{constructor(){super(),this.annotators=[],this.parseMethods.Alias=this.defineAlias,this.parseMethods.SpecializedRule=this.defineSpecializedRule,this.parseMethods.Specialized=this.defineSpecialized}initialize(){this.initialized||(this.annotations(),this.initialized=!0)}annotations(){for(let e,t=0;e=this.annotators[t];t++)activate(this.domain,e)}defineAlias(e,t,...n){const r=this.parsePrecondition(t,n);if(!r)return void console.error(`Precondition Error: ${t} ${n}`);const i=this.preconditions.get(e);i?i.addFullCondition(r):console.error(`Alias Error: No precondition by the name of ${e}`)}defineRulesAlias(e,t,...n){const r=this.findAllRules((function(t){return t.name===e}));if(0===r.length)throw new OutputError("Rule with name "+e+" does not exist.");const i=[];r.forEach((e=>{(e=>{const t=e.dynamicCstr.toString(),n=e.action.toString();for(let e,r=0;e=i[r];r++)if(e.action===n&&e.cstr===t)return!1;return i.push({cstr:t,action:n}),!0})(e)&&this.addAlias_(e,t,n)}))}defineSpecializedRule(e,t,n,r){const i=this.parseCstr(t),s=this.findRule((t=>t.name===e&&i.equal(t.dynamicCstr))),o=this.parseCstr(n);if(!s&&r)throw new OutputError("Rule named "+e+" with style "+t+" does not exist.");const a=r?Action.fromString(r):s.action,c=new SpeechRule(s.name,o,s.precondition,a);this.addRule(c)}defineSpecialized(e,t,n){const r=this.parseCstr(n);if(!r)return void console.error(`Dynamic Constraint Error: ${n}`);const i=this.preconditions.get(e);i?i.addConstraint(r):console.error(`Alias Error: No precondition by the name of ${e}`)}evaluateString(e){const t=[];if(e.match(/^\s+$/))return t;let n=this.matchNumber(e);if(n&&n.length===e.length)return t.push(this.evaluateCharacter(n.number)),t;const r=removeEmpty(e.replace(/\s/g," ").split(" "));for(let e,i=0;e=r[i];i++)if(1===e.length)t.push(this.evaluateCharacter(e));else if(e.match(new RegExp("^["+LOCALE.MESSAGES.regexp.TEXT+"]+$")))t.push(this.evaluateCharacter(e));else{let r=e;for(;r;){n=this.matchNumber(r);const e=r.match(new RegExp("^["+LOCALE.MESSAGES.regexp.TEXT+"]+"));if(n)t.push(this.evaluateCharacter(n.number)),r=r.substring(n.length);else if(e)t.push(this.evaluateCharacter(e[0])),r=r.substring(e[0].length);else{const e=Array.from(r),n=e[0];t.push(this.evaluateCharacter(n)),r=e.slice(1).join("")}}}return t}parse(e){super.parse(e),this.annotators=e.annotators||[]}addAlias_(e,t,n){const r=this.parsePrecondition(t,n),i=new SpeechRule(e.name,e.dynamicCstr,r,e.action);i.name=e.name,this.addRule(i)}matchNumber(e){const t=e.match(new RegExp("^"+LOCALE.MESSAGES.regexp.NUMBER)),n=e.match(new RegExp("^"+MathStore.regexp.NUMBER));if(!t&&!n)return null;const r=n&&n[0]===e;if(t&&t[0]===e||!r)return t?{number:t[0],length:t[0].length}:null;return{number:n[0].replace(new RegExp(MathStore.regexp.DIGIT_GROUP,"g"),"X").replace(new RegExp(MathStore.regexp.DECIMAL_MARK,"g"),LOCALE.MESSAGES.regexp.DECIMAL_MARK).replace(/X/g,LOCALE.MESSAGES.regexp.DIGIT_GROUP.replace(/\\/g,"")),length:n[0].length}}}MathStore.regexp={NUMBER:"((\\d{1,3})(?=(,| ))((,| )\\d{3})*(\\.\\d+)?)|^\\d*\\.\\d+|^\\d+",DECIMAL_MARK:"\\.",DIGIT_GROUP:","};class BrailleStore extends MathStore{constructor(){super(...arguments),this.modality="braille",this.customTranscriptions={"\u22ca":"\u2808\u2821\u2833"}}evaluateString(e){const t=[],n=Array.from(e);for(let e=0;e<n.length;e++)t.push(this.evaluateCharacter(n[e]));return t}annotations(){for(let e,t=0;e=this.annotators[t];t++)activate(this.locale,e)}}class EuroStore extends BrailleStore{constructor(){super(...arguments),this.locale="euro",this.customTranscriptions={},this.customCommands={"\\cdot":"*","\\lt":"<","\\gt":">"},this.lastSpecial=!1,this.specialChars=["^","_","{","}"]}evaluateString(e){const t=e.split(/(\\[a-z]+|\\{|\\}|\\\\)/i),n=this.cleanup(t);return super.evaluateString(n)}cleanup(e){const t=[];let n=!1,r=null;for(let i of e){if(i.match(/^\\/)){"\\text"===i&&(n=!0),this.addSpace(SemanticMap.LatexCommands.get(i))&&t.push(" "),i=this.customCommands[i]||i;const e=i.match(/^\\/);e&&i.match(/^\\[a-zA-Z]+$/)&&r&&t.push(" "),r=e?i:null,t.push(i);continue}const e=i.split("");for(const i of e)n?(t.push(i),n="}"!==i,r=null):i.match(/[a-z]/i)&&r?(r=null,t.push(" "),t.push(i)):i.match(/\s/)||(this.addSpace(i)&&t.push(" "),t.push(i),r=null)}return t.join("")}addSpace(e){if(!e)return!1;if(-1!==this.specialChars.indexOf(e))return this.lastSpecial=!0,!1;if(this.lastSpecial)return this.lastSpecial=!1,!1;const t=SemanticMap.Meaning.get(e);return t.type===SemanticType.OPERATOR||t.type===SemanticType.RELATION||t.type===SemanticType.PUNCTUATION&&t.role===SemanticRole.COLON}}!function(e){e.ROOT="root",e.DYNAMIC="dynamic",e.QUERY="query",e.BOOLEAN="boolean",e.STATIC="static"}(TrieNodeKind||(TrieNodeKind={}));class AbstractTrieNode{constructor(e,t){this.constraint=e,this.test=t,this.children_={},this.kind=TrieNodeKind.ROOT}getConstraint(){return this.constraint}getKind(){return this.kind}applyTest(e){return this.test(e)}addChild(e){const t=e.getConstraint(),n=this.children_[t];return this.children_[t]=e,n}getChild(e){return this.children_[e]}getChildren(){const e=[];for(const t of Object.values(this.children_))e.push(t);return e}findChildren(e){const t=[];for(const n of Object.values(this.children_))n.applyTest(e)&&t.push(n);return t}removeChild(e){delete this.children_[e]}toString(){return this.constraint}}class StaticTrieNode extends AbstractTrieNode{constructor(e,t){super(e,t),this.rule_=null,this.kind=TrieNodeKind.STATIC}getRule(){return this.rule_}setRule(e){this.rule_&&debugger_Debugger.getInstance().output("Replacing rule "+this.rule_+" with "+e),this.rule_=e}toString(){return this.getRule()?this.constraint+"\n==> "+this.getRule().action:this.constraint}}function getNode(e,t,n){switch(e){case TrieNodeKind.ROOT:return new RootTrieNode;case TrieNodeKind.DYNAMIC:return new DynamicTrieNode(t);case TrieNodeKind.QUERY:return new QueryTrieNode(t,n);case TrieNodeKind.BOOLEAN:return new BooleanTrieNode(t,n);default:return null}}class RootTrieNode extends AbstractTrieNode{constructor(){super("",(()=>!0)),this.kind=TrieNodeKind.ROOT}}class DynamicTrieNode extends AbstractTrieNode{constructor(e){super(e,(t=>t===e)),this.kind=TrieNodeKind.DYNAMIC}}const comparator={"=":(e,t)=>e===t,"!=":(e,t)=>e!==t,"<":(e,t)=>e<t,">":(e,t)=>e>t,"<=":(e,t)=>e<=t,">=":(e,t)=>e>=t};function constraintTest(e){if(e.match(/^self::\*$/))return e=>!0;if(e.match(/^self::\w+$/)){const t=e.slice(6).toUpperCase();return e=>e.tagName&&dom_util_tagName(e)===t}if(e.match(/^self::\w+:\w+$/)){const t=e.split(":"),n=resolveNameSpace(t[2]);if(!n)return null;const r=t[3].toUpperCase();return e=>e.localName&&e.localName.toUpperCase()===r&&e.namespaceURI===n}if(e.match(/^@\w+$/)){const t=e.slice(1);return e=>e.hasAttribute&&e.hasAttribute(t)}if(e.match(/^@\w+="[\w\d ]+"$/)){const t=e.split("="),n=t[0].slice(1),r=t[1].slice(1,-1);return e=>e.hasAttribute&&e.hasAttribute(n)&&e.getAttribute(n)===r}if(e.match(/^@\w+!="[\w\d ]+"$/)){const t=e.split("!="),n=t[0].slice(1),r=t[1].slice(1,-1);return e=>!e.hasAttribute||!e.hasAttribute(n)||e.getAttribute(n)!==r}if(e.match(/^contains\(\s*@grammar\s*,\s*"[\w\d ]+"\s*\)$/)){const t=e.split('"')[1];return e=>!!Grammar.getInstance().getParameter(t)}if(e.match(/^not\(\s*contains\(\s*@grammar\s*,\s*"[\w\d ]+"\s*\)\s*\)$/)){const t=e.split('"')[1];return e=>!Grammar.getInstance().getParameter(t)}if(e.match(/^name\(\.\.\/\.\.\)="\w+"$/)){const t=e.split('"')[1].toUpperCase();return e=>{var n,r;return(null===(r=null===(n=e.parentNode)||void 0===n?void 0:n.parentNode)||void 0===r?void 0:r.tagName)&&dom_util_tagName(e.parentNode.parentNode)===t}}if(e.match(/^count\(preceding-sibling::\*\)=\d+$/)){const t=e.split("="),n=parseInt(t[1],10);return e=>{var t;return(null===(t=e.parentNode)||void 0===t?void 0:t.childNodes[n])===e}}if(e.match(/^.+\[@category!?=".+"\]$/)){let[,t,n,r]=e.match(/^(.+)\[@category(!?=)"(.+)"\]$/);const i=r.match(/^unit:(.+)$/);let s="";return i&&(r=i[1],s=":unit"),e=>{const i=evalXPath(t,e)[0];if(i){const e=lookupCategory(i.textContent+s);return"="===n?e===r:e!==r}return!1}}if(e.match(/^string-length\(.+\)\W+\d+/)){const[,t,n,r]=e.match(/^string-length\((.+)\)(\W+)(\d+)/),i=comparator[n]||comparator["="],s=parseInt(r,10);return e=>{const n=evalXPath(t,e)[0];return!!n&&i(Array.from(n.textContent).length,s)}}return null}class QueryTrieNode extends StaticTrieNode{constructor(e,t){super(e,constraintTest(e)),this.context=t,this.kind=TrieNodeKind.QUERY}applyTest(e){return this.test?this.test(e):this.context.applyQuery(e,this.constraint)===e}}class BooleanTrieNode extends StaticTrieNode{constructor(e,t){super(e,constraintTest(e)),this.context=t,this.kind=TrieNodeKind.BOOLEAN}applyTest(e){return this.test?this.test(e):this.context.applyConstraint(e,this.constraint)}}class Trie{static collectRules_(e){const t=[];let n=[e];for(;n.length;){const e=n.shift();if(e.getKind()===TrieNodeKind.QUERY||e.getKind()===TrieNodeKind.BOOLEAN){const n=e.getRule();n&&t.unshift(n)}n=n.concat(e.getChildren())}return t}static printWithDepth_(e,t,n){n+=new Array(t+2).join(t.toString())+": "+e.toString()+"\n";const r=e.getChildren();for(let e,i=0;e=r[i];i++)n=Trie.printWithDepth_(e,t+1,n);return n}static order_(e){const t=e.getChildren();if(!t.length)return 0;const n=Math.max.apply(null,t.map(Trie.order_));return Math.max(t.length,n)}constructor(){this.root=getNode(TrieNodeKind.ROOT,"",null)}addRule(e){let t=this.root;const n=e.context,r=e.dynamicCstr.getValues();for(let e=0,i=r.length;e<i;e++)t=this.addNode_(t,r[e],TrieNodeKind.DYNAMIC,n);t=this.addNode_(t,e.precondition.query,TrieNodeKind.QUERY,n);const i=e.precondition.constraints;for(let e=0,r=i.length;e<r;e++)t=this.addNode_(t,i[e],TrieNodeKind.BOOLEAN,n);t.setRule(e)}lookupRules(e,t){let n=[this.root];const r=[];for(;t.length;){const e=t.shift(),r=[];for(;n.length;){n.shift().getChildren().forEach((t=>{t.getKind()===TrieNodeKind.DYNAMIC&&-1===e.indexOf(t.getConstraint())||r.push(t)}))}n=r.slice()}for(;n.length;){const t=n.shift();if(t.getRule){const e=t.getRule();e&&r.push(e)}const i=t.findChildren(e);n=n.concat(i)}return r}hasSubtrie(e){let t=this.root;for(let n=0,r=e.length;n<r;n++){const r=e[n];if(t=t.getChild(r),!t)return!1}return!0}toString(){return Trie.printWithDepth_(this.root,0,"")}collectRules(e=this.root){return Trie.collectRules_(e)}order(){return Trie.order_(this.root)}enumerate(e){return this.enumerate_(this.root,e)}byConstraint(e){let t=this.root;for(;e.length&&t;){const n=e.shift();t=t.getChild(n)}return t||null}enumerate_(e,t){t=t||{};const n=e.getChildren();for(let e,r=0;e=n[r];r++)e.kind===TrieNodeKind.DYNAMIC&&(t[e.getConstraint()]=this.enumerate_(e,t[e.getConstraint()]));return t}addNode_(e,t,n,r){let i=e.getChild(t);return i||(i=getNode(n,t,r),e.addChild(i)),i}}class SpeechRuleEngine{static getInstance(){return SpeechRuleEngine.instance=SpeechRuleEngine.instance||new SpeechRuleEngine,SpeechRuleEngine.instance}static debugSpeechRule(e,t){const n=e.precondition,r=e.context.applyQuery(t,n.query);debugger_Debugger.getInstance().output(n.query,r?r.toString():r),n.constraints.forEach((n=>debugger_Debugger.getInstance().output(n,e.context.applyConstraint(t,n))))}static debugNamedSpeechRule(e,t){const n=SpeechRuleEngine.getInstance().trie.collectRules().filter((t=>t.name==e));for(let r,i=0;r=n[i];i++)debugger_Debugger.getInstance().output("Rule",e,"DynamicCstr:",r.dynamicCstr.toString(),"number",i),SpeechRuleEngine.debugSpeechRule(r,t)}evaluateNode(e){updateEvaluator(e);const t=(new Date).getTime();let n=[];try{n=this.evaluateNode_(e)}catch(e){console.log(e),console.error("Something went wrong computing speech."),debugger_Debugger.getInstance().output(e)}const r=(new Date).getTime();return debugger_Debugger.getInstance().output("Time:",r-t),n}toString(){return this.trie.collectRules().map((e=>e.toString())).join("\n")}runInSetting(e,t){const n=engine_Engine.getInstance(),r={};for(const[t,i]of Object.entries(e))r[t]=n[t],n[t]=i;n.setDynamicCstr();const i=t();for(const[e,t]of Object.entries(r))n[e]=t;return n.setDynamicCstr(),i}static addStore(e){const t=storeFactory(e);"abstract"!==t.kind&&t.getSpeechRules().forEach((e=>SpeechRuleEngine.getInstance().trie.addRule(e))),SpeechRuleEngine.getInstance().addEvaluator(t)}processGrammar(e,t,n){const r={};for(const[i,s]of Object.entries(n))r[i]="string"==typeof s?e.constructString(t,s):s;Grammar.getInstance().pushState(r)}addEvaluator(e){const t=e.evaluateDefault.bind(e),n=this.evaluators_[e.locale];if(n)return void(n[e.modality]=t);const r={};r[e.modality]=t,this.evaluators_[e.locale]=r}getEvaluator(e,t){const n=this.evaluators_[e]||this.evaluators_[DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]];return n[t]||n[DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]]}enumerate(e){return this.trie.enumerate(e)}constructor(){this.trie=null,this.evaluators_={},this.trie=new Trie}evaluateNode_(e){if(!e)return[];this.updateConstraint_();let t=this.evaluateTree_(e);return t=processAnnotations(t),t}evaluateTree_(e){const t=engine_Engine.getInstance();let n;debugger_Debugger.getInstance().output(t.mode!==Mode.HTTP?e.toString():e),Grammar.getInstance().setAttribute(e);const r=this.lookupRule(e,t.dynamicCstr);if(!r)return t.strict?[]:(n=this.getEvaluator(t.locale,t.modality)(e),e.attributes&&this.addPersonality_(n,{},!1,e),n);debugger_Debugger.getInstance().generateOutput((()=>["Apply Rule:",r.name,r.dynamicCstr.toString(),t.mode===Mode.HTTP?serializeXml(e):e.toString()])),Grammar.getInstance().processSingles();const i=r.context,s=r.action.components;n=[];for(let t,r=0;t=s[r];r++){let r=[];const s=t.content||"",o=t.attributes||{};let a=!1;t.grammar&&this.processGrammar(i,e,t.grammar);let c=null;if(o.engine){c=engine_Engine.getInstance().dynamicCstr.getComponents();const e=Object.assign({},c,Grammar.parseInput(o.engine));engine_Engine.getInstance().setDynamicCstr(e),this.updateConstraint_()}switch(t.type){case ActionType.NODE:{const t=i.applyQuery(e,s);t&&(r=this.evaluateTree_(t))}break;case ActionType.MULTI:{a=!0;const t=i.applySelector(e,s);t.length>0&&(r=this.evaluateNodeList_(i,t,o.sepFunc,i.constructString(e,o.separator),o.ctxtFunc,i.constructString(e,o.context)))}break;case ActionType.TEXT:{const t=o.span;let n={};if(t){const r=evalXPath(t,e);n=r.length?Span.getAttributes(r[0]):{kind:t}}r=i.constructSpan(e,s,n).map((function(e){return AuditoryDescription.create({text:e.speech,attributes:e.attributes},{adjust:!0})}))}break;case ActionType.PERSONALITY:default:r=[AuditoryDescription.create({text:s})]}r[0]&&!a&&(o.context&&(r[0].context=i.constructString(e,o.context)+(r[0].context||"")),o.annotation&&(r[0].annotation=o.annotation)),this.addLayout(r,o,a),t.grammar&&Grammar.getInstance().popState(),n=n.concat(this.addPersonality_(r,o,a,e)),c&&(engine_Engine.getInstance().setDynamicCstr(c),this.updateConstraint_())}return Grammar.getInstance().popState(),n}evaluateNodeList_(e,t,n,r,i,s){if(!t.length)return[];const o=r||"",a=s||"",c=e.contextFunctions.lookup(i),l=c?c(t,a):function(){return a},u=e.contextFunctions.lookup(n),m=u?u(t,o):function(){return[AuditoryDescription.create({text:o},{translate:!0})]};let d=[];for(let e,n=0;e=t[n];n++){const r=this.evaluateTree_(e);if(r.length>0&&(r[0].context=l()+(r[0].context||""),d=d.concat(r),n<t.length-1)){const e=m();d=d.concat(e)}}return d}addLayout(e,t,n){const r=t.layout;r&&(r.match(/^begin/)?e.unshift(new AuditoryDescription({text:"",layout:r})):r.match(/^end/)?e.push(new AuditoryDescription({text:"",layout:r})):(e.unshift(new AuditoryDescription({text:"",layout:`begin${r}`})),e.push(new AuditoryDescription({text:"",layout:`end${r}`}))))}addPersonality_(e,t,n,r){const i={};let s=null;for(const e of personalityPropList){const n=t[e];if(void 0===n)continue;const r=parseFloat(n),o=isNaN(r)?'"'===n.charAt(0)?n.slice(1,-1):n:r;e===personalityProps.PAUSE?s=o:i[e]=o}for(let t,n=0;t=e[n];n++)this.addRelativePersonality_(t,i),this.addExternalAttributes_(t,r);if(n&&e.length&&delete e[e.length-1].personality[personalityProps.JOIN],s&&e.length){const t=e[e.length-1];t.text||Object.keys(t.personality).length?e.push(AuditoryDescription.create({text:"",personality:{pause:s}})):t.personality[personalityProps.PAUSE]=s}return e}addExternalAttributes_(e,t){if(void 0===e.attributes.id&&(e.attributes.id=t.getAttribute("id")),t.hasAttributes()){const n=t.attributes;for(let t=n.length-1;t>=0;t--){const r=n[t].name;!e.attributes[r]&&r.match(/^ext/)&&(e.attributes[r]=n[t].value)}}}addRelativePersonality_(e,t){if(!e.personality)return e.personality=t,e;const n=e.personality;for(const[e,r]of Object.entries(t))n[e]&&"number"==typeof n[e]&&"number"==typeof r?n[e]=(n[e]+r).toString():n[e]||(n[e]=r);return e}updateConstraint_(){const e=engine_Engine.getInstance().dynamicCstr,t=engine_Engine.getInstance().strict,n=this.trie,r={};let i=e.getValue(Axis.LOCALE),s=e.getValue(Axis.MODALITY),o=e.getValue(Axis.DOMAIN);n.hasSubtrie([i,s,o])||(o=DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN],n.hasSubtrie([i,s,o])||(s=DynamicCstr.DEFAULT_VALUES[Axis.MODALITY],n.hasSubtrie([i,s,o])||(i=DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]))),r[Axis.LOCALE]=[i],r[Axis.MODALITY]=["summary"!==s?s:DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]],r[Axis.DOMAIN]=["speech"!==s?DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN]:o];const a=e.getOrder();for(let n,i=0;n=a[i];i++)if(!r[n]){const i=e.getValue(n),s=this.makeSet_(i,e.preference),o=DynamicCstr.DEFAULT_VALUES[n];t||i===o||s.push(o),r[n]=s}e.updateProperties(r)}makeSet_(e,t){return t&&Object.keys(t).length?e.split(":"):[e]}lookupRule(e,t){if(!e||e.nodeType!==NodeType.ELEMENT_NODE&&e.nodeType!==NodeType.TEXT_NODE)return null;const n=this.lookupRules(e,t);return n.length>0?this.pickMostConstraint_(t,n):null}lookupRules(e,t){return this.trie.lookupRules(e,t.allProperties())}pickMostConstraint_(e,t){const n=engine_Engine.getInstance().comparator;return t.sort((function(e,t){return n.compare(e.dynamicCstr,t.dynamicCstr)||t.precondition.priority-e.precondition.priority||t.precondition.constraints.length-e.precondition.constraints.length||t.precondition.rank-e.precondition.rank})),debugger_Debugger.getInstance().generateOutput((()=>t.map((e=>e.name+"("+e.dynamicCstr.toString()+")"))).bind(this)),t[0]}}const stores=new Map;function speech_rule_engine_getStore(e,t){return"braille"===t&&"euro"===e?new EuroStore:"braille"===t?new BrailleStore:new MathStore}function storeFactory(e){const t=`${e.locale}.${e.modality}.${e.domain}`;if("actions"===e.kind){const n=stores.get(t);return n.parse(e),n}init(),e&&!e.functions&&(e.functions=getStore(e.locale,e.modality,e.domain));const n=speech_rule_engine_getStore(e.locale,e.modality);return stores.set(t,n),e.inherits&&(n.inherits=stores.get(`${e.inherits}.${e.modality}.${e.domain}`)),n.parse(e),n.initialize(),n}engine_Engine.nodeEvaluator=SpeechRuleEngine.getInstance().evaluateNode.bind(SpeechRuleEngine.getInstance());const punctuationMarks=["\u2806","\u2812","\u2832","\u2826","\u2834","\u2804"];function processAnnotations(e){const t=new AuditoryList(e);for(const e of t.annotations){const n=e.data;if("punctuation"===n.annotation){const r=t.prevText(e);if(!r)continue;const i=r.data;"punctuation"!==i.annotation&&"\u2800"!==i.text&&1===n.text.length&&-1!==punctuationMarks.indexOf(n.text)&&(n.text="\u2838"+n.text)}}return t.toList()}const Domains={small:["default"],capital:["default"],digit:["default"]};function makeDomains(){const e=LOCALE.ALPHABETS,t=(e,t)=>{const n={};return Object.keys(e).forEach((e=>n[e]=!0)),Object.keys(t).forEach((e=>n[e]=!0)),Object.keys(n)};Domains.small=t(e.smallPrefix,e.letterTrans),Domains.capital=t(e.capPrefix,e.letterTrans),Domains.digit=t(e.digitPrefix,e.digitTrans)}function generateBase(){for(const e of INTERVALS.values()){const t=e.unicode;for(const n of t)baseStores.set(n,{key:n,category:e.category})}}function alphabet_generator_generate(e){const t=engine_Engine.getInstance().locale;engine_Engine.getInstance().locale=e,setLocale(),changeLocale({locale:e}),makeDomains();for(const e of INTERVALS.values()){const t=e.unicode;if("offset"in e)numberRules(t,e.font,e.offset||0);else{alphabetRules(t,LOCALE.ALPHABETS[e.base],e.font,!!e.capital)}}engine_Engine.getInstance().locale=t,setLocale()}function getFont(e){return localeFontCombiner("normal"===e||"fullwidth"===e?"":LOCALE.MESSAGES.font[e]||LOCALE.MESSAGES.embellish[e]||"")}function alphabetRules(e,t,n,r){const i=getFont(n);for(let n,s,o=0;n=e[o],s=t[o];o++){const e=r?LOCALE.ALPHABETS.capPrefix:LOCALE.ALPHABETS.smallPrefix,t=r?Domains.capital:Domains.small;makeLetter(i.combiner,n,s,i.font,e,LOCALE.ALPHABETS.letterTrans,t)}}function numberRules(e,t,n){const r=getFont(t);for(let t,i=0;t=e[i];i++){const e=LOCALE.ALPHABETS.digitPrefix,s=i+n;makeLetter(r.combiner,t,s,r.font,e,LOCALE.ALPHABETS.digitTrans,Domains.digit)}}function makeLetter(e,t,n,r,i,s,o){for(let a,c=0;a=o[c];c++){const o=a in s?s[a]:s.default,c=a in i?i[a]:i.default;defineRule(a,"default",t,e(o(n),r,c))}}var __awaiter=function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const addSymbols={functions:addFunctionRules,symbols:addSymbolRules,units:addUnitRules,si:e=>e.forEach(setSiPrefixes),messages:completeLocale,rules:SpeechRuleEngine.addStore,characters:addCharacterRules};let _init=!1;function loadLocale(){return __awaiter(this,arguments,void 0,(function*(e=engine_Engine.getInstance().locale){return _init||(generateBase(),_loadLocale(DynamicCstr.BASE_LOCALE),_init=!0),engine_EnginePromise.promises[DynamicCstr.BASE_LOCALE].then((()=>__awaiter(this,void 0,void 0,(function*(){const t=engine_Engine.getInstance().defaultLocale;return t?(_loadLocale(t),engine_EnginePromise.promises[t].then((()=>__awaiter(this,void 0,void 0,(function*(){return _loadLocale(e),engine_EnginePromise.promises[e]}))))):(_loadLocale(e),engine_EnginePromise.promises[e])}))))}))}function _loadLocale(e=engine_Engine.getInstance().locale){engine_EnginePromise.loaded[e]||(engine_EnginePromise.loaded[e]=[!1,!1],math_compound_store_reset(),retrieveMaps(e))}function loadMethod(){return engine_Engine.getInstance().customLoader?engine_Engine.getInstance().customLoader:standardLoader()}function standardLoader(){switch(engine_Engine.getInstance().mode){case Mode.ASYNC:return loadFile;case Mode.HTTP:return loadAjax;case Mode.SYNC:default:return loadFileSync}}function retrieveFiles(e){const t=loadMethod(),n=new Promise((n=>{t(e).then((t=>{parseMaps(t),engine_EnginePromise.loaded[e]=[!0,!0],n(e)}),(t=>{engine_EnginePromise.loaded[e]=[!0,!1],console.error(`Unable to load locale: ${e}`),engine_Engine.getInstance().locale=engine_Engine.getInstance().defaultLocale,n(e)}))}));engine_EnginePromise.promises[e]=n}function parseMaps(e){addMaps("string"==typeof e?JSON.parse(e):e)}function addMaps(e,t){let n=!0;for(let r,i=0;r=Object.keys(e)[i];i++){const i=r.split("/");t&&t!==i[0]||(n&&"symbols"===i[1]&&"base"!==i[0]&&(alphabet_generator_generate(i[0]),n=!1),addSymbols[i[1]](e[r]))}}function retrieveMaps(e){engine_Engine.getInstance().isIE&&engine_Engine.getInstance().mode===Mode.HTTP?getJsonIE_(e):retrieveFiles(e)}function getJsonIE_(e,t){let n=t||1;mapsForIE?addMaps(mapsForIE,e):n<=5&&setTimeout((()=>getJsonIE_(e,n++)).bind(this),300)}function loadFile(e){const t=localePath(e);return new Promise(((e,n)=>{system_external.f.fs.readFile(t,"utf8",((t,r)=>{if(t)return n(t);e(r)}))}))}function loadFileSync(e){const t=localePath(e);return new Promise(((e,n)=>{let r="{}";try{r=system_external.f.fs.readFileSync(t,"utf8")}catch(e){return n(e)}e(r)}))}function loadAjax(e){const t=localePath(e),n=new XMLHttpRequest;return new Promise(((e,r)=>{n.onreadystatechange=function(){if(4===n.readyState){const t=n.status;0===t||t>=200&&t<400?e(n.responseText):r(t)}},n.open("GET",t,!0),n.send()}))}var engine_setup_awaiter=function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const MATHSPEAK_ONLY=["ca","da","es"],EN_RULES=["chromevox","clearspeak","mathspeak","emacspeak","html"];function ensureDomain(e){if(e.modality&&"speech"!==e.modality||!e.modality&&"speech"!==engine_Engine.getInstance().modality)return;if(!e.domain)return;if("default"===e.domain)return void(e.domain="mathspeak");const t=e.locale||engine_Engine.getInstance().locale,n=e.domain;-1===MATHSPEAK_ONLY.indexOf(t)?"en"!==t?"mathspeak"!==n&&"clearspeak"!==n&&(e.domain="mathspeak"):-1===EN_RULES.indexOf(n)&&(e.domain="mathspeak"):"mathspeak"!==n&&(e.domain="mathspeak")}function setup(e){return engine_setup_awaiter(this,void 0,void 0,(function*(){ensureDomain(e);const t=engine_Engine.getInstance(),n=n=>{void 0!==e[n]&&(t[n]=e[n])};return n("mode"),t.configurate(e),engine_Engine.BINARY_FEATURES.forEach((n=>{void 0!==e[n]&&(t[n]=!!e[n])})),engine_Engine.STRING_FEATURES.forEach(n),e.debug&&debugger_Debugger.getInstance().init(),e.json&&(system_external.f.jsonPath=makePath(e.json)),e.xpath&&(system_external.f.WGXpath=e.xpath),t.setCustomLoader(e.custom),setupBrowsers(t),setLocale(),t.setDynamicCstr(),t.init?(engine_EnginePromise.promises.init=new Promise(((e,t)=>{setTimeout((()=>{e("init")}),10)})),t.init=!1,engine_EnginePromise.get()):t.delay?(t.delay=!1,engine_EnginePromise.get()):loadLocale()}))}function setupBrowsers(e){e.isIE=detectIE(),e.isEdge=detectEdge()}var KeyCode;!function(e){e[e.ENTER=13]="ENTER",e[e.ESC=27]="ESC",e[e.SPACE=32]="SPACE",e[e.PAGE_UP=33]="PAGE_UP",e[e.PAGE_DOWN=34]="PAGE_DOWN",e[e.END=35]="END",e[e.HOME=36]="HOME",e[e.LEFT=37]="LEFT",e[e.UP=38]="UP",e[e.RIGHT=39]="RIGHT",e[e.DOWN=40]="DOWN",e[e.TAB=9]="TAB",e[e.LESS=188]="LESS",e[e.GREATER=190]="GREATER",e[e.DASH=189]="DASH",e[e.ZERO=48]="ZERO",e[e.ONE=49]="ONE",e[e.TWO=50]="TWO",e[e.THREE=51]="THREE",e[e.FOUR=52]="FOUR",e[e.FIVE=53]="FIVE",e[e.SIX=54]="SIX",e[e.SEVEN=55]="SEVEN",e[e.EIGHT=56]="EIGHT",e[e.NINE=57]="NINE",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z"}(KeyCode||(KeyCode={}));const Move=new Map([[13,"ENTER"],[27,"ESC"],[32,"SPACE"],[33,"PAGE_UP"],[34,"PAGE_DOWN"],[35,"END"],[36,"HOME"],[37,"LEFT"],[38,"UP"],[39,"RIGHT"],[40,"DOWN"],[9,"TAB"],[188,"LESS"],[190,"GREATER"],[189,"DASH"],[48,"ZERO"],[49,"ONE"],[50,"TWO"],[51,"THREE"],[52,"FOUR"],[53,"FIVE"],[54,"SIX"],[55,"SEVEN"],[56,"EIGHT"],[57,"NINE"],[65,"A"],[66,"B"],[67,"C"],[68,"D"],[69,"E"],[70,"F"],[71,"G"],[72,"H"],[73,"I"],[74,"J"],[75,"K"],[76,"L"],[77,"M"],[78,"N"],[79,"O"],[80,"P"],[81,"Q"],[82,"R"],[83,"S"],[84,"T"],[85,"U"],[86,"V"],[87,"W"],[88,"X"],[89,"Y"],[90,"Z"]]);var EventType;!function(e){e.CLICK="click",e.DBLCLICK="dblclick",e.MOUSEDOWN="mousedown",e.MOUSEUP="mouseup",e.MOUSEOVER="mouseover",e.MOUSEOUT="mouseout",e.MOUSEMOVE="mousemove",e.SELECTSTART="selectstart",e.KEYPRESS="keypress",e.KEYDOWN="keydown",e.KEYUP="keyup",e.TOUCHSTART="touchstart",e.TOUCHMOVE="touchmove",e.TOUCHEND="touchend",e.TOUCHCANCEL="touchcancel"}(EventType||(EventType={}));class event_util_Event{constructor(e,t,n){this.src=e,this.type=t,this.callback=n}add(){this.src.addEventListener(this.type,this.callback)}remove(){this.src.removeEventListener(this.type,this.callback)}}function mergePause(e,t,n){return e?{pause:mergePause_(e.pause,t.pause,n)}:t}function mergePause_(e,t,n){return(n||function(n,r){return"number"==typeof n&&"number"==typeof r?n+r:"number"==typeof n?r:"number"==typeof r?n:[e,t].sort()[0]}).call(null,e,t)}function mergeMarkup(e,t){delete e.open,t.close.forEach((t=>delete e[t])),t.open.forEach((n=>e[n]=t[n]));const n=Object.keys(e);e.open=n}function sortClose(e,t){if(e.length<=1)return e;const n=[];for(let r,i=0;r=t[i],e.length;i++)r.close&&r.close.length&&r.close.forEach((function(t){const r=e.indexOf(t);-1!==r&&(n.unshift(t),e.splice(r,1))}));return n}let PersonalityRanges_={},LastOpen_=[];function personalityMarkup(e){PersonalityRanges_={},LastOpen_=[];let t=[];const n={};for(let r,i=0;r=e[i];i++){let e=null;const i=r.descriptionSpan(),s=r.personality,o=s[personalityProps.JOIN];delete s[personalityProps.JOIN],void 0!==s[personalityProps.PAUSE]&&(e={[personalityProps.PAUSE]:s[personalityProps.PAUSE]},delete s[personalityProps.PAUSE]);appendMarkup_(t,i,personalityDiff_(s,n),o,e,!0)}return t=t.concat(finaliseMarkup_()),t=simplifyMarkup_(t),t=engine_Engine.getInstance().cleanpause?cleanPause(t):t,t}function cleanPause(e){for(;isPauseElement(e[0]);)e.shift();for(;isPauseElement(e[e.length-1]);)e.pop();return e}function appendElement_(e,t){const n=e[e.length-1];if(n){if(isSpanElement(t)&&isSpanElement(n)){if(void 0===n.join)return void(n.span=n.span.concat(t.span));const e=n.span.pop(),r=t.span.shift();return n.span.push(e+n.join+r),n.span=n.span.concat(t.span),void(n.join=t.join)}isPauseElement(t)&&isPauseElement(n)?n.pause=mergePause_(n.pause,t.pause):e.push(t)}else e.push(t)}function simplifyMarkup_(e){const t={},n=[];for(let r,i=0;r=e[i];i++){if(!isMarkupElement(r)){appendElement_(n,r);continue}if(!r.close||1!==r.close.length||r.open.length){copyValues_(r,t),n.push(r);continue}let s=e[i+1];if(!s||isSpanElement(s)){copyValues_(r,t),n.push(r);continue}const o=isPauseElement(s)?s:null;o&&(s=e[i+2]),s&&isMarkupElement(s)&&s.open[0]===r.close[0]&&!s.close.length&&s[s.open[0]]===t[s.open[0]]?o?(appendElement_(n,o),i+=2):i+=1:(copyValues_(r,t),n.push(r))}return n}function copyValues_(e,t){e.rate&&(t.rate=e.rate),e.pitch&&(t.pitch=e.pitch),e.volume&&(t.volume=e.volume)}function finaliseMarkup_(){const e=[];for(let t=LastOpen_.length-1;t>=0;t--){const n=LastOpen_[t];if(n.length){const t={open:[],close:[]};for(let e=0;e<n.length;e++){const r=n[e];t.close.push(r),t[r]=0}e.push(t)}}return e}function isMarkupElement(e){return"object"==typeof e&&e.open}function isPauseElement(e){return"object"==typeof e&&1===Object.keys(e).length&&Object.keys(e)[0]===personalityProps.PAUSE}function isSpanElement(e){const t=Object.keys(e);return"object"==typeof e&&(1===t.length&&"span"===t[0]||2===t.length&&("span"===t[0]&&"join"===t[1]||"span"===t[1]&&"join"===t[0]))}function appendMarkup_(e,t,n,r,i,s=!1){if(s){const s=e[e.length-1];let o;if(s&&(o=s[personalityProps.JOIN]),s&&!t.speech&&i&&isPauseElement(s)){const e=personalityProps.PAUSE;s[e]=mergePause_(s[e],i[e]),i=null}if(s&&t.speech&&0===Object.keys(n).length&&isSpanElement(s)){if(void 0!==o){const e=s.span.pop();t=Span.stringAttr(e.speech+o+t.speech,e.attributes)}s.span.push(t),t=Span.empty(),s[personalityProps.JOIN]=r}}0!==Object.keys(n).length&&e.push(n),t.speech&&e.push({span:[t],join:r}),i&&e.push(i)}function personalityDiff_(e,t){if(!t)return e;const n={};for(const r of personalityPropList){const i=e[r],s=t[r];if(!i&&!s||i&&s&&i===s)continue;const o=i||0;isMarkupElement(n)||(n.open=[],n.close=[]),i||n.close.push(r),s||n.open.push(r),s&&i&&(n.close.push(r),n.open.push(r)),t[r]=o,n[r]=o,PersonalityRanges_[r]?PersonalityRanges_[r].push(o):PersonalityRanges_[r]=[o]}if(isMarkupElement(n)){let e=n.close.slice();for(;e.length>0;){let r=LastOpen_.pop();const i=setdifference(r,e);if(e=setdifference(e,r),r=i,0!==e.length){if(0!==r.length){n.close=n.close.concat(r),n.open=n.open.concat(r);for(let e,i=0;e=r[i];i++)n[e]=t[e]}}else 0!==r.length&&LastOpen_.push(r)}LastOpen_.push(n.open)}return n}class AbstractAudioRenderer{constructor(){this.separator_=" "}set separator(e){this.separator_=e}get separator(){return"braille"===engine_Engine.getInstance().modality?"":this.separator_}error(e){return null}merge(e){let t="";const n=e.length-1;for(let r,i=0;r=e[i];i++)if(t+=r.speech,i<n){const e=r.attributes.separator;t+=void 0!==e?e:this.separator}return t}finalize(e){return e}pauseValue(e){let t;switch(e){case"long":t=750;break;case"medium":t=500;break;case"short":t=250;break;default:t=parseInt(e,10)}return Math.floor(t*engine_Engine.getInstance().getRate()/100)}}class MarkupRenderer extends AbstractAudioRenderer{constructor(){super(...arguments),this.ignoreElements=[personalityProps.LAYOUT],this.scaleFunction=null}setScaleFunction(e,t,n,r,i=0){this.scaleFunction=s=>{const o=(s-e)/(t-e),a=n*(1-o)+r*o;return+(Math.round(a+"e+"+i)+"e-"+i)}}applyScaleFunction(e){return this.scaleFunction?this.scaleFunction(e):e}ignoreElement(e){return-1!==this.ignoreElements.indexOf(e)}}class AcssRenderer extends MarkupRenderer{markup(e){this.setScaleFunction(-2,2,0,10,0);const t=personalityMarkup(e),n=[],r={open:[]};let i=null,s=!1;for(let e,o=0;e=t[o];o++){if(isMarkupElement(e)){mergeMarkup(r,e);continue}if(isPauseElement(e)){s&&(i=mergePause(i,e,Math.max));continue}const t='"'+this.merge(e.span)+'"';s=!0,i&&(n.push(this.pause(i)),i=null);const o=this.prosody_(r);n.push(o?"(text ("+o+") "+t+")":t)}return"(exp "+n.join(" ")+")"}error(e){return'(error "'+Move.get(e)+'")'}prosodyElement(e,t){switch(t=this.applyScaleFunction(t),e){case personalityProps.RATE:return"(richness . "+t+")";case personalityProps.PITCH:return"(average-pitch . "+t+")";case personalityProps.VOLUME:return"(stress . "+t+")"}return"(value . "+t+")"}pause(e){return"(pause . "+this.pauseValue(e[personalityProps.PAUSE])+")"}prosody_(e){const t=e.open,n=[];for(let r,i=0;r=t[i];i++)n.push(this.prosodyElement(r,e[r]));return n.join(" ")}}class XmlRenderer extends MarkupRenderer{markup(e){this.setScaleFunction(-2,2,-100,100,2);const t=personalityMarkup(e),n=[],r=[];for(let e,i=0;e=t[i];i++)if(e.span)n.push(this.merge(e.span));else if(isPauseElement(e))n.push(this.pause(e));else{if(e.close.length)for(let t=0;t<e.close.length;t++){const t=r.pop();if(-1===e.close.indexOf(t))throw new SREError("Unknown closing markup element: "+t);n.push(this.closeTag(t))}if(e.open.length){sortClose(e.open.slice(),t.slice(i+1)).forEach((t=>{n.push(this.prosodyElement(t,e[t])),r.push(t)}))}}return n.join(" ")}}class LayoutRenderer extends XmlRenderer{constructor(){super(...arguments),this.values=new Map}finalize(e){return setRelValues(this.values.get("rel")),setTwoDim(e)}pause(e){return""}prosodyElement(e,t){return e===personalityProps.LAYOUT?`<${t}>`:""}closeTag(e){return`</${e}>`}markup(e){this.values.clear();const t=[];let n=[];for(const r of e){if(!r.layout){n.push(r);continue}t.push(this.processContent(n)),n=[];const[e,i,s]=this.layoutValue(r.layout);"begin"!==e?"end"!==e?console.warn("Something went wrong with layout markup: "+i):t.push("</"+i+">"):t.push("<"+i+(s?` value="${s}"`:"")+">")}return t.push(this.processContent(n)),t.join("")}processContent(e){const t=[],n=personalityMarkup(e);for(let e,r=0;e=n[r];r++)e.span?t.push(this.merge(e.span)):isPauseElement(e);return t.join("")}layoutValue(e){const t=e.match(/^(begin|end|)(.*\D)(\d*)$/),n=t[3];return n?(e=t[2],this.values.has(e)||this.values.set(e,{}),this.values.get(e)[n]=!0,[t[1],e,n]):[t[1],t[2],""]}}LayoutRenderer.options={cayleyshort:engine_Engine.getInstance().cayleyshort,linebreaks:engine_Engine.getInstance().linebreaks};let twodExpr="";const handlers={TABLE:handleTable,CASES:handleCases,CAYLEY:handleCayley,MATRIX:handleMatrix,CELL:recurseTree,FENCE:recurseTree,ROW:recurseTree,FRACTION:handleFraction,NUMERATOR:handleFractionPart,DENOMINATOR:handleFractionPart,REL:handleRelation,OP:handleRelation};function applyHandler(e){const t=dom_util_tagName(e),n=handlers[t];return n?n(e):e.textContent}const relValues=new Map;function setRelValues(e){if(relValues.clear(),!e)return;const t=Object.keys(e).map((e=>parseInt(e))).sort();for(let e,n=0;e=t[n];n++)relValues.set(e,n+1)}function setTwoDim(e){twodExpr="";const t=parseInput(`<all>${e}</all>`);return debugger_Debugger.getInstance().output(formatXml(t.toString())),twodExpr=recurseTree(t),twodExpr}function combineContent(e,t){if(!e||!t)return e+t;const n=strHeight(e),r=strHeight(t),i=n-r;e=i<0?padCell(e,r,strWidth(e)):e,t=i>0?padCell(t,n,strWidth(t)):t;const s=e.split(/\r\n|\r|\n/),o=t.split(/\r\n|\r|\n/),a=[];for(let e=0;e<s.length;e++)a.push(s[e]+o[e]);return a.join("\n")}function recurseTree(e){let t="";for(const n of Array.from(e.childNodes))t=n.nodeType!==NodeType.TEXT_NODE?combineContent(t,applyHandler(n)):combineContent(t,n.textContent);return t}function strHeight(e){return e.split(/\r\n|\r|\n/).length}function strWidth(e){return e.split(/\r\n|\r|\n/).reduce(((e,t)=>Math.max(t.length,e)),0)}function padHeight(e,t){const n=t-strHeight(e);return e+(n>0?new Array(n+1).join("\n"):"")}function padWidth(e,t){const n=e.split(/\r\n|\r|\n/),r=[];for(const e of n){const n=t-e.length;r.push(e+(n>0?new Array(n+1).join("\u2800"):""))}return r.join("\n")}function padCell(e,t,n){return padWidth(e=padHeight(e,t),n)}function assembleRows(e){const t=Array.from(e.childNodes),n=[];for(const e of t)e.nodeType===NodeType.ELEMENT_NODE&&n.push(handleRow(e));return n}function getMaxParameters(e){const t=e.reduce(((e,t)=>Math.max(t.height,e)),0),n=[];for(let t=0;t<e[0].width.length;t++)n.push(e.map((e=>e.width[t])).reduce(((e,t)=>Math.max(e,t)),0));return[t,n]}function combineCells(e,t){const n=[];for(const r of e){if(0===r.height)continue;const e=[];for(let n=0;n<r.cells.length;n++)e.push(padCell(r.cells[n],r.height,t[n]));r.cells=e,n.push(r)}return n}function combineRows(e,t){if(1===t)return e.map((e=>e.lfence+e.cells.join(e.sep)+e.rfence)).join("\n");const n=[];for(const t of e){const e=verticalArrange(t.sep,t.height);let r=t.cells.shift();for(;t.cells.length;)r=combineContent(r,e),r=combineContent(r,t.cells.shift());r=combineContent(verticalArrange(t.lfence,t.height),r),r=combineContent(r,verticalArrange(t.rfence,t.height)),n.push(r),n.push(t.lfence+new Array(strWidth(r)-3).join(t.sep)+t.rfence)}return n.slice(0,-1).join("\n")}function verticalArrange(e,t){let n="";for(;t;)n+=e+"\n",t--;return n.slice(0,-1)}function getFence(e){return e.nodeType===NodeType.ELEMENT_NODE&&"FENCE"===dom_util_tagName(e)?applyHandler(e):""}function handleMatrix(e){let t=assembleRows(e);const[n,r]=getMaxParameters(t);return t=combineCells(t,r),combineRows(t,n)}function handleTable(e){let t=assembleRows(e);t.forEach((e=>{e.cells=e.cells.slice(1).slice(0,-1),e.width=e.width.slice(1).slice(0,-1)}));const[n,r]=getMaxParameters(t);return t=combineCells(t,r),combineRows(t,n)}function handleCases(e){let t=assembleRows(e);t.forEach((e=>{e.cells=e.cells.slice(0,-1),e.width=e.width.slice(0,-1)}));const[n,r]=getMaxParameters(t);return t=combineCells(t,r),combineRows(t,n)}function handleCayley(e){let t=assembleRows(e);t.forEach((e=>{e.cells=e.cells.slice(1).slice(0,-1),e.width=e.width.slice(1).slice(0,-1),e.sep=e.sep+e.sep}));const[n,r]=getMaxParameters(t),i={lfence:"",rfence:"",cells:r.map((e=>"\u2810"+new Array(e).join("\u2812"))),width:r,height:1,sep:t[0].sep};return engine_Engine.getInstance().cayleyshort&&"\u2800"===t[0].cells[0]&&(i.cells[0]="\u2800"),t.splice(1,0,i),t=combineCells(t,r),combineRows(t,n)}function handleRow(e){const t=Array.from(e.childNodes),n=getFence(t[0]),r=getFence(t[t.length-1]);n&&t.shift(),r&&t.pop();let i="";const s=[];for(const e of t){if(e.nodeType===NodeType.TEXT_NODE){i=e.textContent;continue}const t=applyHandler(e);s.push(t)}return{lfence:n,rfence:r,sep:i,cells:s,height:s.reduce(((e,t)=>Math.max(strHeight(t),e)),0),width:s.map(strWidth)}}function centerCell(e,t){const n=(t-strWidth(e))/2,[r,i]=Math.floor(n)===n?[n,n]:[Math.floor(n),Math.ceil(n)],s=e.split(/\r\n|\r|\n/),o=[],[a,c]=[new Array(r+1).join("\u2800"),new Array(i+1).join("\u2800")];for(const e of s)o.push(a+e+c);return o.join("\n")}function handleFraction(e){const[t,n,,r,i]=Array.from(e.childNodes),s=applyHandler(n),o=applyHandler(r),a=strWidth(s),c=strWidth(o);let l=Math.max(a,c);const u=t+new Array(l+1).join("\u2812")+i;return l=u.length,`${centerCell(s,l)}\n${u}\n${centerCell(o,l)}`}function handleFractionPart(e){const t=e.firstChild,n=recurseTree(e);if(t&&t.nodeType===NodeType.ELEMENT_NODE){if("ENGLISH"===dom_util_tagName(t))return"\u2830"+n;if("NUMBER"===dom_util_tagName(t))return"\u283c"+n}return n}function handleRelation(e){if(!engine_Engine.getInstance().linebreaks)return recurseTree(e);const t=relValues.get(parseInt(e.getAttribute("value")));return(t?`<br value="${t}"/>`:"")+recurseTree(e)}class PunctuationRenderer extends AbstractAudioRenderer{markup(e){const t=personalityMarkup(e);let n="",r=null,i=!1;for(let e,s=0;e=t[s];s++)isMarkupElement(e)||(isPauseElement(e)?r=e:(r&&(n+=this.pause(r[personalityProps.PAUSE]),r=null),n+=(i?this.separator:"")+this.merge(e.span),i=!0));return n}pause(e){let t;return t="number"==typeof e?e<=250?"short":e<=500?"medium":"long":e,PunctuationRenderer.PAUSE_PUNCTUATION.get(t)||""}}PunctuationRenderer.PAUSE_PUNCTUATION=new Map([["short",","],["medium",";"],["long","."]]);class SableRenderer extends XmlRenderer{finalize(e){return'<?xml version="1.0"?><!DOCTYPE SABLE PUBLIC "-//SABLE//DTD SABLE speech mark up//EN" "Sable.v0_2.dtd" []><SABLE>'+this.separator+e+this.separator+"</SABLE>"}pause(e){return'<BREAK MSEC="'+this.pauseValue(e[personalityProps.PAUSE])+'"/>'}prosodyElement(e,t){switch(t=this.applyScaleFunction(t),e){case personalityProps.PITCH:return'<PITCH RANGE="'+t+'%">';case personalityProps.RATE:return'<RATE SPEED="'+t+'%">';case personalityProps.VOLUME:return'<VOLUME LEVEL="'+t+'%">';default:return"<"+e.toUpperCase()+' VALUE="'+t+'">'}}closeTag(e){return"</"+e.toUpperCase()+">"}}class SsmlRenderer extends XmlRenderer{finalize(e){return`<?xml version="1.0"?><speak version="1.1" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${engine_Engine.getInstance().locale}"><prosody rate="`+engine_Engine.getInstance().getRate()+'%">'+this.separator+e+this.separator+"</prosody></speak>"}pause(e){return'<break time="'+this.pauseValue(e[personalityProps.PAUSE])+'ms"/>'}prosodyElement(e,t){const n=(t=Math.floor(this.applyScaleFunction(t)))<0?t.toString():"+"+t.toString();return"<prosody "+e.toLowerCase()+'="'+n+(e===personalityProps.VOLUME?">":'%">')}closeTag(e){return"</prosody>"}markup(e){return SsmlRenderer.MARKS={},super.markup(e)}merge(e){const t=[];let n="";for(let r=0;r<e.length;r++){const i=e[r];if(this.isEmptySpan(i))continue;const s=SsmlRenderer.MARK_KIND?i.attributes.kind:"",o=engine_Engine.getInstance().automark?i.attributes.id:engine_Engine.getInstance().mark?i.attributes.extid:"";!o||o===n||SsmlRenderer.MARK_ONCE&&SsmlRenderer.MARKS[o]||(t.push(s?`<mark name="${o}" kind="${s}"/>`:`<mark name="${o}"/>`),n=o,SsmlRenderer.MARKS[o]=!0),engine_Engine.getInstance().character&&1===i.speech.length&&i.speech.match(/[a-zA-Z]/)?t.push('<say-as interpret-as="'+SsmlRenderer.CHARACTER_ATTR+'">'+i.speech+"</say-as>"):t.push(i.speech)}return t.join(this.separator)}isEmptySpan(e){const t=e.attributes.separator;return e.speech.match(/^\s*$/)&&(!t||t.match(/^\s*$/))}}SsmlRenderer.MARK_ONCE=!1,SsmlRenderer.MARK_KIND=!0,SsmlRenderer.CHARACTER_ATTR="character",SsmlRenderer.MARKS={};class StringRenderer extends AbstractAudioRenderer{markup(e){let t="";const n=personalityMarkup(e).filter((e=>e.span));if(!n.length)return t;const r=n.length-1;for(let e,i=0;e=n[i];i++){if(e.span&&(t+=this.merge(e.span)),i>=r)continue;const n=e.join;t+=void 0===n?this.separator:n}return t}}class CountingRenderer extends StringRenderer{finalize(e){const t=super.finalize(e),n="braille"===engine_Engine.getInstance().modality?"\u28ff\u2800\u28ff\u2800\u28ff\u2800\u28ff\u2800\u28ff\u2800":"0123456789";let r=new Array(Math.trunc(t.length/10)+1).join(n);return r+=n.slice(0,t.length%10),t+"\n"+r}}const xmlInstance=new SsmlRenderer,renderers=new Map([[Markup.NONE,new StringRenderer],[Markup.COUNTING,new CountingRenderer],[Markup.PUNCTUATION,new PunctuationRenderer],[Markup.LAYOUT,new LayoutRenderer],[Markup.ACSS,new AcssRenderer],[Markup.SABLE,new SableRenderer],[Markup.VOICEXML,xmlInstance],[Markup.SSML,xmlInstance]]);function setSeparator(e){const t=renderers.get(Engine.getInstance().markup);t&&(t.separator=e)}function getSeparator(){const e=renderers.get(Engine.getInstance().markup);return e?e.separator:""}function markup(e){const t=renderers.get(engine_Engine.getInstance().markup);return t?t.markup(e):""}function merge(e){const t=e.map((e=>"string"==typeof e?Span.stringEmpty(e):e)),n=renderers.get(engine_Engine.getInstance().markup);return n?n.merge(t):e.join()}function finalize(e){const t=renderers.get(engine_Engine.getInstance().markup);return t?t.finalize(e):e}function error(e){const t=renderers.get(engine_Engine.getInstance().markup);return t?t.error(e):""}function registerRenderer(e,t){renderers.set(e,t)}function isXml(){return renderers.get(engine_Engine.getInstance().markup)instanceof XmlRenderer}class SemanticAbstractParser{constructor(e){this.type=e,this.factory_=new SemanticNodeFactory}getFactory(){return this.factory_}setFactory(e){this.factory_=e}getType(){return this.type}parseList(e){const t=[];for(let n,r=0;n=e[r];r++)t.push(this.parse(n));return t}}class SemanticMathml extends SemanticAbstractParser{static getAttribute_(e,t,n){if(!e.hasAttribute(t))return n;const r=e.getAttribute(t);return r.match(/^\s*$/)?null:r}constructor(){super("MathML"),this.parseMap_=new Map([[MMLTAGS.SEMANTICS,this.semantics_.bind(this)],[MMLTAGS.MATH,this.rows_.bind(this)],[MMLTAGS.MROW,this.rows_.bind(this)],[MMLTAGS.MPADDED,this.rows_.bind(this)],[MMLTAGS.MSTYLE,this.rows_.bind(this)],[MMLTAGS.MFRAC,this.fraction_.bind(this)],[MMLTAGS.MSUB,this.limits_.bind(this)],[MMLTAGS.MSUP,this.limits_.bind(this)],[MMLTAGS.MSUBSUP,this.limits_.bind(this)],[MMLTAGS.MOVER,this.limits_.bind(this)],[MMLTAGS.MUNDER,this.limits_.bind(this)],[MMLTAGS.MUNDEROVER,this.limits_.bind(this)],[MMLTAGS.MROOT,this.root_.bind(this)],[MMLTAGS.MSQRT,this.sqrt_.bind(this)],[MMLTAGS.MTABLE,this.table_.bind(this)],[MMLTAGS.MLABELEDTR,this.tableLabeledRow_.bind(this)],[MMLTAGS.MTR,this.tableRow_.bind(this)],[MMLTAGS.MTD,this.tableCell_.bind(this)],[MMLTAGS.MS,this.text_.bind(this)],[MMLTAGS.MTEXT,this.text_.bind(this)],[MMLTAGS.MSPACE,this.space_.bind(this)],[MMLTAGS.ANNOTATIONXML,this.text_.bind(this)],[MMLTAGS.MI,this.identifier_.bind(this)],[MMLTAGS.MN,this.number_.bind(this)],[MMLTAGS.MO,this.operator_.bind(this)],[MMLTAGS.MFENCED,this.fenced_.bind(this)],[MMLTAGS.MENCLOSE,this.enclosed_.bind(this)],[MMLTAGS.MMULTISCRIPTS,this.multiscripts_.bind(this)],[MMLTAGS.ANNOTATION,this.empty_.bind(this)],[MMLTAGS.NONE,this.empty_.bind(this)],[MMLTAGS.MACTION,this.action_.bind(this)]]);const e={type:SemanticType.IDENTIFIER,role:SemanticRole.NUMBERSET,font:SemanticFont.DOUBLESTRUCK};["C","H","N","P","Q","R","Z","\u2102","\u210d","\u2115","\u2119","\u211a","\u211d","\u2124"].forEach((t=>this.getFactory().defaultMap.set(t,e)).bind(this))}parse(e){SemanticProcessor.getInstance().setNodeFactory(this.getFactory());const t=toArray(e.childNodes),n=dom_util_tagName(e),r=this.parseMap_.get(n),i=(r||this.dummy_.bind(this))(e,t);return addAttributes(i,e),-1!==[MMLTAGS.MATH,MMLTAGS.MROW,MMLTAGS.MPADDED,MMLTAGS.MSTYLE,MMLTAGS.SEMANTICS,MMLTAGS.MACTION].indexOf(n)||(i.mathml.unshift(e),i.mathmlTree=e),i}semantics_(e,t){return t.length?this.parse(t[0]):this.getFactory().makeEmptyNode()}rows_(e,t){const n=e.getAttribute("semantics");if(n&&n.match("bspr_"))return SemanticProcessor.proof(e,n,this.parseList.bind(this));let r;if(1===(t=purgeNodes(t)).length)r=this.parse(t[0]),r.type!==SemanticType.EMPTY||r.mathmlTree||(r.mathmlTree=e);else{const n=SemanticHeuristics.run("function_from_identifiers",e);r=n&&n!==e?n:SemanticProcessor.getInstance().row(this.parseList(t))}return r.mathml.unshift(e),r}fraction_(e,t){if(!t.length)return this.getFactory().makeEmptyNode();const n=this.parse(t[0]),r=t[1]?this.parse(t[1]):this.getFactory().makeEmptyNode();return SemanticProcessor.getInstance().fractionLikeNode(n,r,e.getAttribute("linethickness"),"true"===e.getAttribute("bevelled"))}limits_(e,t){return SemanticProcessor.getInstance().limitNode(dom_util_tagName(e),this.parseList(t))}root_(e,t){return t[1]?this.getFactory().makeBranchNode(SemanticType.ROOT,[this.parse(t[1]),this.parse(t[0])],[]):this.sqrt_(e,t)}sqrt_(e,t){const n=this.parseList(purgeNodes(t));return this.getFactory().makeBranchNode(SemanticType.SQRT,[SemanticProcessor.getInstance().row(n)],[])}table_(e,t){const n=e.getAttribute("semantics");if(n&&n.match("bspr_"))return SemanticProcessor.proof(e,n,this.parseList.bind(this));const r=this.getFactory().makeBranchNode(SemanticType.TABLE,this.parseList(t),[]);return r.mathmlTree=e,SemanticProcessor.tableToMultiline(r)}tableRow_(e,t){const n=this.getFactory().makeBranchNode(SemanticType.ROW,this.parseList(t),[]);return n.role=SemanticRole.TABLE,n}tableLabeledRow_(e,t){var n;if(!t.length)return this.tableRow_(e,t);const r=this.parse(t[0]);r.role=SemanticRole.LABEL,(null===(n=r.childNodes[0])||void 0===n?void 0:n.type)===SemanticType.TEXT&&(r.childNodes[0].role=SemanticRole.LABEL);const i=this.getFactory().makeBranchNode(SemanticType.ROW,this.parseList(t.slice(1)),[r]);return i.role=SemanticRole.TABLE,i}tableCell_(e,t){const n=this.parseList(purgeNodes(t));let r;r=n.length?1===n.length&&isType(n[0],SemanticType.EMPTY)?n:[SemanticProcessor.getInstance().row(n)]:[];const i=this.getFactory().makeBranchNode(SemanticType.CELL,r,[]);return i.role=SemanticRole.TABLE,i}space_(e,t){const n=e.getAttribute("width"),r=n&&n.match(/[a-z]*$/);if(!r)return this.empty_(e,t);const i=r[0],s=parseFloat(n.slice(0,r.index)),o={cm:.4,pc:.5,em:.5,ex:1,in:.15,pt:5,mm:5}[i];if(!o||isNaN(s)||s<o)return this.empty_(e,t);const a=this.getFactory().makeUnprocessed(e);return SemanticProcessor.getInstance().text(a,dom_util_tagName(e))}text_(e,t){const n=this.leaf_(e,t);return e.textContent?(n.updateContent(e.textContent,!0),SemanticProcessor.getInstance().text(n,dom_util_tagName(e))):n}identifier_(e,t){const n=this.leaf_(e,t);return SemanticProcessor.getInstance().identifierNode(n,SemanticProcessor.getInstance().font(e.getAttribute("mathvariant")),e.getAttribute("class"))}number_(e,t){const n=this.leaf_(e,t);return SemanticProcessor.number(n),n}operator_(e,t){const n=this.leaf_(e,t);return SemanticProcessor.getInstance().operatorNode(n),n}fenced_(e,t){const n=this.parseList(purgeNodes(t)),r=SemanticMathml.getAttribute_(e,"separators",","),i=SemanticMathml.getAttribute_(e,"open","("),s=SemanticMathml.getAttribute_(e,"close",")"),o=SemanticProcessor.getInstance().mfenced(i,s,r,n);return SemanticProcessor.getInstance().tablesInRow([o])[0]}enclosed_(e,t){const n=this.parseList(purgeNodes(t)),r=this.getFactory().makeBranchNode(SemanticType.ENCLOSE,[SemanticProcessor.getInstance().row(n)],[]);return r.role=e.getAttribute("notation")||SemanticRole.UNKNOWN,r}multiscripts_(e,t){if(!t.length)return this.getFactory().makeEmptyNode();const n=this.parse(t.shift());if(!t.length)return n;const r=[],i=[],s=[],o=[];let a=!1,c=0;for(let e,n=0;e=t[n];n++)dom_util_tagName(e)!==MMLTAGS.MPRESCRIPTS?(a?1&c?r.push(e):i.push(e):1&c?s.push(e):o.push(e),c++):(a=!0,c=0);return purgeNodes(r).length||purgeNodes(i).length?SemanticProcessor.getInstance().tensor(n,this.parseList(i),this.parseList(r),this.parseList(o),this.parseList(s)):SemanticProcessor.getInstance().pseudoTensor(n,this.parseList(o),this.parseList(s))}empty_(e,t){return this.getFactory().makeEmptyNode()}action_(e,t){const n=t[e.hasAttribute("selection")?parseInt(e.getAttribute("selection"),10)-1:0],r=this.parse(n);return r.mathmlTree=n,r}dummy_(e,t){const n=this.getFactory().makeUnprocessed(e);return n.role=e.tagName,n.textContent=e.textContent,n}leaf_(e,t){if(1===t.length&&t[0].nodeType!==NodeType.TEXT_NODE){const n=this.getFactory().makeUnprocessed(e);return n.role=t[0].tagName,addAttributes(n,t[0]),n}const n=this.getFactory().makeLeafNode(e.textContent,SemanticProcessor.getInstance().font(e.getAttribute("mathvariant")));return e.hasAttribute("data-latex")&&SemanticMap.LatexCommands.set(e.getAttribute("data-latex"),e.textContent),n}}class SemanticAbstractHeuristic{constructor(e,t,n=e=>!1){this.name=e,this.apply=t,this.applicable=n}}class SemanticTreeHeuristic extends SemanticAbstractHeuristic{}class SemanticMultiHeuristic extends SemanticAbstractHeuristic{}class SemanticMmlHeuristic extends SemanticAbstractHeuristic{}const Prefix="data-semantic-";var enrich_attr_Attribute;!function(e){e.ADDED="data-semantic-added",e.ALTERNATIVE="data-semantic-alternative",e.CHILDREN="data-semantic-children",e.COLLAPSED="data-semantic-collapsed",e.CONTENT="data-semantic-content",e.EMBELLISHED="data-semantic-embellished",e.FENCEPOINTER="data-semantic-fencepointer",e.FONT="data-semantic-font",e.ID="data-semantic-id",e.ANNOTATION="data-semantic-annotation",e.ATTRIBUTES="data-semantic-attributes",e.OPERATOR="data-semantic-operator",e.OWNS="data-semantic-owns",e.PARENT="data-semantic-parent",e.POSTFIX="data-semantic-postfix",e.PREFIX="data-semantic-prefix",e.ROLE="data-semantic-role",e.SPEECH="data-semantic-speech",e.STRUCTURE="data-semantic-structure",e.SUMMARY="data-semantic-summary",e.TYPE="data-semantic-type"}(enrich_attr_Attribute||(enrich_attr_Attribute={}));const EnrichAttributes=[enrich_attr_Attribute.ADDED,enrich_attr_Attribute.ALTERNATIVE,enrich_attr_Attribute.CHILDREN,enrich_attr_Attribute.COLLAPSED,enrich_attr_Attribute.CONTENT,enrich_attr_Attribute.EMBELLISHED,enrich_attr_Attribute.FENCEPOINTER,enrich_attr_Attribute.FONT,enrich_attr_Attribute.ID,enrich_attr_Attribute.ANNOTATION,enrich_attr_Attribute.ATTRIBUTES,enrich_attr_Attribute.OPERATOR,enrich_attr_Attribute.OWNS,enrich_attr_Attribute.PARENT,enrich_attr_Attribute.POSTFIX,enrich_attr_Attribute.PREFIX,enrich_attr_Attribute.ROLE,enrich_attr_Attribute.SPEECH,enrich_attr_Attribute.STRUCTURE,enrich_attr_Attribute.SUMMARY,enrich_attr_Attribute.TYPE];function makeIdList(e){return e.map((function(e){return e.id})).join(",")}function setAttributes(e,t){e.setAttribute(enrich_attr_Attribute.TYPE,t.type);const n=t.allAttributes();for(let t,r=0;t=n[r];r++)e.setAttribute(Prefix+t[0].toLowerCase(),t[1]);t.childNodes.length&&e.setAttribute(enrich_attr_Attribute.CHILDREN,makeIdList(t.childNodes)),t.contentNodes.length&&e.setAttribute(enrich_attr_Attribute.CONTENT,makeIdList(t.contentNodes)),t.parent&&e.setAttribute(enrich_attr_Attribute.PARENT,t.parent.id.toString());const r=t.attributesXml();r&&e.setAttribute(enrich_attr_Attribute.ATTRIBUTES,r),setPostfix(e,t)}function setPostfix(e,t){const n=[];t.role===SemanticRole.MGLYPH&&n.push("image"),t.attributes.href&&n.push("link"),n.length&&e.setAttribute(enrich_attr_Attribute.POSTFIX,n.join(" "))}function removeAttributePrefix(e){return e.toString().replace(new RegExp(Prefix,"g"),"")}function addPrefix(e){return Prefix+e}function addMrow(){const e=createElement("mrow");return e.setAttribute(enrich_attr_Attribute.ADDED,"true"),e}const Options={tree:!1};class SemanticSkeleton{static fromTree(e){return SemanticSkeleton.fromNode(e.root)}static fromNode(e){return new SemanticSkeleton(SemanticSkeleton.fromNode_(e))}static fromString(e){return new SemanticSkeleton(SemanticSkeleton.fromString_(e))}static simpleCollapseStructure(e){return"number"==typeof e}static contentCollapseStructure(e){return!!e&&!SemanticSkeleton.simpleCollapseStructure(e)&&"c"===e[0]}static interleaveIds(e,t){return interleaveLists(SemanticSkeleton.collapsedLeafs(e),SemanticSkeleton.collapsedLeafs(t))}static collapsedLeafs(...e){return e.reduce(((e,t)=>{return e.concat((n=t,SemanticSkeleton.simpleCollapseStructure(n)?[n]:SemanticSkeleton.contentCollapseStructure(n[1])?n.slice(2):n.slice(1)));var n}),[])}static fromStructure(e,t){return new SemanticSkeleton(SemanticSkeleton.tree_(e,t.root))}static combineContentChildren(e,t,n,r){switch(e){case SemanticType.RELSEQ:case SemanticType.INFIXOP:case SemanticType.MULTIREL:return interleaveLists(r,n);case SemanticType.PREFIXOP:return n.concat(r);case SemanticType.POSTFIXOP:return r.concat(n);case SemanticType.MATRIX:case SemanticType.VECTOR:case SemanticType.FENCED:return r.unshift(n[0]),r.push(n[1]),r;case SemanticType.CASES:return r.unshift(n[0]),r;case SemanticType.APPL:return[r[0],n[0],r[1]];case SemanticType.ROOT:return[r[0],r[1]];case SemanticType.ROW:case SemanticType.LINE:return n.length&&r.unshift(n[0]),r;default:return r}}static makeSexp_(e){return SemanticSkeleton.simpleCollapseStructure(e)?e.toString():SemanticSkeleton.contentCollapseStructure(e)?"(c "+e.slice(1).map(SemanticSkeleton.makeSexp_).join(" ")+")":"("+e.map(SemanticSkeleton.makeSexp_).join(" ")+")"}static fromString_(e){let t=e.replace(/\(/g,"[");return t=t.replace(/\)/g,"]"),t=t.replace(/ /g,","),t=t.replace(/c/g,'"c"'),JSON.parse(t)}static fromNode_(e){if(!e)return[];const t=e.contentNodes;let n;t.length&&(n=t.map(SemanticSkeleton.fromNode_),n.unshift("c"));const r=e.childNodes;if(!r.length)return t.length?[e.id,n]:e.id;const i=r.map(SemanticSkeleton.fromNode_);return t.length&&i.unshift(n),i.unshift(e.id),i}static tree_(e,t,n=0,r=1,i=1){if(!t)return[];const s=t.id,o=[s];updateEvaluator(e);const a=evalXPath(`.//self::*[@${enrich_attr_Attribute.ID}=${s}]`,e)[0];if(!t.childNodes.length)return SemanticSkeleton.addAria(a,n,r,i),t.id;const c=SemanticSkeleton.combineContentChildren(t.type,t.role,t.contentNodes.map((function(e){return e})),t.childNodes.map((function(e){return e})));a&&SemanticSkeleton.addOwns_(a,c);for(let t,r=0,i=c.length;t=c[r];r++)o.push(SemanticSkeleton.tree_(e,t,n+1,r+1,i));return SemanticSkeleton.addAria(a,n,r,i,Options.tree?n?"group":"tree":"treeitem"),o}static addAria(e,t,n,r,i=(Options.tree?t?"treeitem":"tree":"treeitem")){engine_Engine.getInstance().aria&&e&&(e.setAttribute("aria-level",t.toString()),e.setAttribute("aria-posinset",n.toString()),e.setAttribute("aria-setsize",r.toString()),e.setAttribute("role",i),e.hasAttribute(enrich_attr_Attribute.OWNS)&&e.setAttribute("aria-owns",e.getAttribute(enrich_attr_Attribute.OWNS)))}static addOwns_(e,t){const n=e.getAttribute(enrich_attr_Attribute.COLLAPSED),r=n?SemanticSkeleton.realLeafs_(SemanticSkeleton.fromString(n).array):t.map((e=>e.id));e.setAttribute(enrich_attr_Attribute.OWNS,r.join(" "))}static realLeafs_(e){if(SemanticSkeleton.simpleCollapseStructure(e))return[e];if(SemanticSkeleton.contentCollapseStructure(e))return[];let t=[];for(let n=1;n<e.length;n++)t=t.concat(SemanticSkeleton.realLeafs_(e[n]));return t}constructor(e){this.parents=null,this.levelsMap=null,e=0===e?e:e||[],this.array=e}populate(){this.parents&&this.levelsMap||(this.parents={},this.levelsMap={},this.populate_(this.array,this.array,[]))}toString(){return SemanticSkeleton.makeSexp_(this.array)}populate_(e,t,n){if(SemanticSkeleton.simpleCollapseStructure(e))return this.levelsMap[e]=t,void(this.parents[e]=e===n[0]?n.slice(1):n);const r=SemanticSkeleton.contentCollapseStructure(e)?e.slice(1):e,i=[r[0]].concat(n);for(let t=0,n=r.length;t<n;t++){const n=r[t];this.populate_(n,e,i)}}isRoot(e){return e===this.levelsMap[e][0]}directChildren(e){if(!this.isRoot(e))return[];return this.levelsMap[e].slice(1).map((e=>SemanticSkeleton.simpleCollapseStructure(e)?e:SemanticSkeleton.contentCollapseStructure(e)?e[1]:e[0]))}subtreeNodes(e){if(!this.isRoot(e))return[];const t=(e,n)=>{SemanticSkeleton.simpleCollapseStructure(e)?n.push(e):(SemanticSkeleton.contentCollapseStructure(e)&&(e=e.slice(1)),e.forEach((e=>t(e,n))))},n=this.levelsMap[e],r=[];return t(n.slice(1),r),r}}function combineJuxtaposition(e){for(let t,n=e.childNodes.length-1;t=e.childNodes[n];n--)isImplicitOp(t)&&!t.nobreaking&&(e.childNodes.splice(n,1,...t.childNodes),e.contentNodes.splice(n,0,...t.contentNodes),t.childNodes.concat(t.contentNodes).forEach((function(t){t.parent=e})),e.addMathmlNodes(t.mathml));return e}function juxtapositionPrePost(e){const t=[],n=[];let r=e.comp.shift(),i=null,s=[];for(;e.comp.length;)if(s=[],r.length)i&&t.push(i),n.push(r),i=e.rel.shift(),r=e.comp.shift();else{for(i&&s.push(i);!r.length&&e.comp.length;)r=e.comp.shift(),s.push(e.rel.shift());i=convertPrePost(s,r,n)}return s.length||r.length?(t.push(i),n.push(r)):(s.push(i),convertPrePost(s,r,n)),{rel:t,comp:n}}function convertPrePost(e,t,n){let r=null;if(!e.length)return r;const i=n[n.length-1],s=i&&i.length,o=t&&t.length,a=SemanticProcessor.getInstance();if(s&&o){if(t[0].type===SemanticType.INFIXOP&&t[0].role===SemanticRole.IMPLICIT)return r=e.pop(),i.push(a.postfixNode_(i.pop(),e)),r;r=e.shift();const n=a.prefixNode_(t.shift(),e);return t.unshift(n),r}return s?(i.push(a.postfixNode_(i.pop(),e)),r):(o&&t.unshift(a.prefixNode_(t.shift(),e)),r)}function recurseJuxtaposition(e,t,n){if(!t.length)return e;const r=e.pop(),i=t.shift(),s=n.shift();if(i.type===SemanticType.INFIXOP&&(i.role===SemanticRole.IMPLICIT||i.role===SemanticRole.UNIT)){debugger_Debugger.getInstance().output("Juxta Heuristic Case 2");const o=(r?[r,i]:[i]).concat(s);return recurseJuxtaposition(e.concat(o),t,n)}if(!r)return debugger_Debugger.getInstance().output("Juxta Heuristic Case 3"),recurseJuxtaposition([i].concat(s),t,n);const o=s.shift();if(!o){debugger_Debugger.getInstance().output("Juxta Heuristic Case 9");const s=SemanticHeuristics.factory.makeBranchNode(SemanticType.INFIXOP,[r,t.shift()],[i],i.textContent);return s.role=SemanticRole.IMPLICIT,SemanticHeuristics.run("combine_juxtaposition",s),t.unshift(s),recurseJuxtaposition(e,t,n)}if(isOperator(r)||isOperator(o))return debugger_Debugger.getInstance().output("Juxta Heuristic Case 4"),recurseJuxtaposition(e.concat([r,i,o]).concat(s),t,n);let a=null;return isImplicitOp(r)&&isImplicitOp(o)?(debugger_Debugger.getInstance().output("Juxta Heuristic Case 5"),r.contentNodes.push(i),r.contentNodes=r.contentNodes.concat(o.contentNodes),r.childNodes.push(o),r.childNodes=r.childNodes.concat(o.childNodes),o.childNodes.forEach((e=>e.parent=r)),i.parent=r,r.addMathmlNodes(i.mathml),r.addMathmlNodes(o.mathml),a=r):isImplicitOp(r)?(debugger_Debugger.getInstance().output("Juxta Heuristic Case 6"),r.contentNodes.push(i),r.childNodes.push(o),o.parent=r,i.parent=r,r.addMathmlNodes(i.mathml),r.addMathmlNodes(o.mathml),a=r):isImplicitOp(o)?(debugger_Debugger.getInstance().output("Juxta Heuristic Case 7"),o.contentNodes.unshift(i),o.childNodes.unshift(r),r.parent=o,i.parent=o,o.addMathmlNodes(i.mathml),o.addMathmlNodes(r.mathml),a=o):(debugger_Debugger.getInstance().output("Juxta Heuristic Case 8"),a=SemanticHeuristics.factory.makeBranchNode(SemanticType.INFIXOP,[r,o],[i],i.textContent),a.role=SemanticRole.IMPLICIT),e.push(a),recurseJuxtaposition(e.concat(s),t,n)}function implicitUnpack(e){const t=e[0].childNodes;e.splice(0,1,...t)}function integralFractionArg(e){const t=e.childNodes[1],n=t.childNodes[0];if(isIntegralDxBoundarySingle(n))return void(n.role=SemanticRole.INTEGRAL);if(!isImplicit(n))return;const r=n.childNodes.length,i=n.childNodes[r-2],s=n.childNodes[r-1];if(isIntegralDxBoundarySingle(s))s.role=SemanticRole.INTEGRAL;else if(isIntegralDxBoundary(i,s)){const e=SemanticProcessor.getInstance().prefixNode_(s,[i]);e.role=SemanticRole.INTEGRAL,2===r?t.childNodes[0]=e:(n.childNodes.pop(),n.contentNodes.pop(),n.childNodes[r-2]=e,e.parent=n)}}function eligibleNode(e){return e.childNodes[0]&&e.childNodes[0].childNodes[0]&&dom_util_tagName(e.childNodes[0])===MMLTAGS.MPADDED&&dom_util_tagName(e.childNodes[0].childNodes[0])===MMLTAGS.MPADDED&&dom_util_tagName(e.childNodes[0].childNodes[e.childNodes[0].childNodes.length-1])===MMLTAGS.MPHANTOM}SemanticHeuristics.add(new SemanticTreeHeuristic("combine_juxtaposition",combineJuxtaposition)),SemanticHeuristics.add(new SemanticTreeHeuristic("propagateSimpleFunction",(e=>(e.type!==SemanticType.INFIXOP&&e.type!==SemanticType.FRACTION||!e.childNodes.every(isSimpleFunction)||(e.role=SemanticRole.COMPFUNC),e)),(e=>"clearspeak"===engine_Engine.getInstance().domain))),SemanticHeuristics.add(new SemanticTreeHeuristic("simpleNamedFunction",(e=>(e.role!==SemanticRole.UNIT&&-1!==["f","g","h","F","G","H"].indexOf(e.textContent)&&(e.role=SemanticRole.SIMPLEFUNC),e)),(e=>"clearspeak"===engine_Engine.getInstance().domain))),SemanticHeuristics.add(new SemanticTreeHeuristic("propagateComposedFunction",(e=>(e.type===SemanticType.FENCED&&e.childNodes[0].role===SemanticRole.COMPFUNC&&(e.role=SemanticRole.COMPFUNC),e)),(e=>"clearspeak"===engine_Engine.getInstance().domain))),SemanticHeuristics.add(new SemanticTreeHeuristic("multioperator",(e=>{e.role!==SemanticRole.UNKNOWN||e.textContent.length<=1||(SemanticProcessor.compSemantics(e,"role",SemanticRole),SemanticProcessor.compSemantics(e,"type",SemanticType))}))),SemanticHeuristics.add(new SemanticMultiHeuristic("convert_juxtaposition",(e=>{let t=partitionNodes(e,(function(e){return e.textContent===NamedSymbol.invisibleTimes&&e.type===SemanticType.OPERATOR}));t=t.rel.length?juxtapositionPrePost(t):t,e=t.comp[0];for(let n,r,i=1;n=t.comp[i],r=t.rel[i-1];i++)e.push(r),e=e.concat(n);return t=partitionNodes(e,(function(e){return e.textContent===NamedSymbol.invisibleTimes&&(e.type===SemanticType.OPERATOR||e.type===SemanticType.INFIXOP)})),t.rel.length?recurseJuxtaposition(t.comp.shift(),t.rel,t.comp):e}))),SemanticHeuristics.add(new SemanticTreeHeuristic("simple2prefix",(e=>(e.textContent.length>1&&!e.textContent[0].match(/[A-Z]/)&&(e.role=SemanticRole.PREFIXFUNC),e)),(e=>"braille"===engine_Engine.getInstance().modality&&e.type===SemanticType.IDENTIFIER))),SemanticHeuristics.add(new SemanticTreeHeuristic("detect_cycle",(e=>{e.type=SemanticType.MATRIX,e.role=SemanticRole.CYCLE;const t=e.childNodes[0];return t.type=SemanticType.ROW,t.role=SemanticRole.CYCLE,t.textContent="",t.contentNodes=[],e}),(e=>e.type===SemanticType.FENCED&&e.childNodes[0].type===SemanticType.INFIXOP&&e.childNodes[0].role===SemanticRole.IMPLICIT&&e.childNodes[0].childNodes.every((function(e){return e.type===SemanticType.NUMBER}))&&e.childNodes[0].contentNodes.every((function(e){return e.role===SemanticRole.SPACE}))))),SemanticHeuristics.add(new SemanticMultiHeuristic("intvar_from_implicit",implicitUnpack,(e=>e[0]&&isImplicit(e[0])))),SemanticHeuristics.add(new SemanticTreeHeuristic("intvar_from_fraction",integralFractionArg,(e=>{if(e.type!==SemanticType.INTEGRAL)return!1;const[,t,n]=e.childNodes;return n.type===SemanticType.EMPTY&&t.type===SemanticType.FRACTION}))),SemanticHeuristics.add(new SemanticTreeHeuristic("rewrite_subcases",rewriteSubcasesTable,(e=>{let t=!0,n=!0;if(eligibleNode(e.childNodes[0].childNodes[0].mathmlTree)){for(let n,r=1;n=e.childNodes[r];r++)if(n.childNodes[0].childNodes.length){t=!1;break}}else t=!1;t&&e.addAnnotation("Emph","left");if(eligibleNode(e.childNodes[0].childNodes[e.childNodes[0].childNodes.length-1].mathmlTree)){const t=e.childNodes[0].childNodes.length;for(let r,i=1;r=e.childNodes[i];i++)if(r.childNodes.length>=t){n=!1;break}}else n=!1;return n&&e.addAnnotation("Emph","right"),t||n})));const rewritable=[SemanticType.PUNCTUATED,SemanticType.RELSEQ,SemanticType.MULTIREL,SemanticType.INFIXOP,SemanticType.PREFIXOP,SemanticType.POSTFIXOP];function rewriteSubcasesTable(e){e.addAnnotation("Emph","top");let t=[];if(e.hasAnnotation("Emph","left")){const n=rewriteCell(e.childNodes[0].childNodes[0].childNodes[0],!0);n.forEach((e=>e.addAnnotation("Emph","left"))),t=t.concat(n);for(let t,n=0;t=e.childNodes[n];n++)t.childNodes.shift()}if(t.push(e),e.hasAnnotation("Emph","right")){const n=rewriteCell(e.childNodes[0].childNodes[e.childNodes[0].childNodes.length-1].childNodes[0]);n.forEach((e=>e.addAnnotation("Emph","left"))),t=t.concat(n),e.childNodes[0].childNodes.pop()}SemanticProcessor.tableToMultiline(e);const n=SemanticProcessor.getInstance().row(t),r=e.annotation.Emph;return e.annotation.Emph=["table"],r.forEach((e=>n.addAnnotation("Emph",e))),n}function rewriteCell(e,t){if(!e.childNodes.length)return rewriteFence(e),[e];let n=null;if(e.type===SemanticType.PUNCTUATED&&(t?e.role===SemanticRole.ENDPUNCT:e.role===SemanticRole.STARTPUNCT)){const r=e.childNodes;rewriteFence(r[t?r.length-1:0])&&(e=r[t?0:r.length-1],n=r[t?r.length-1:0])}if(-1!==rewritable.indexOf(e.type)){const r=e.childNodes;rewriteFence(r[t?r.length-1:0]);const i=SemanticSkeleton.combineContentChildren(e.type,e.role,e.contentNodes,e.childNodes);return n&&(t?i.push(n):i.unshift(n)),i}return n?t?[e,n]:[n,e]:[e]}const PUNCT_TO_FENCE_={[SemanticRole.METRIC]:SemanticRole.METRIC,[SemanticRole.VBAR]:SemanticRole.NEUTRAL,[SemanticRole.OPENFENCE]:SemanticRole.OPEN,[SemanticRole.CLOSEFENCE]:SemanticRole.CLOSE};function rewriteFence(e){if(e.type!==SemanticType.PUNCTUATION)return!1;const t=PUNCT_TO_FENCE_[e.role];return!!t&&(e.role=t,e.type=SemanticType.FENCE,e.addAnnotation("Emph","fence"),!0)}function combineNodes(e,t,n,r=n){const i=[];for(;e&&e.role===n;)i.push(e),e=t.shift();return i.length?(e&&t.unshift(e),[1===i.length?i[0]:combinedNodes(i,r),t]):[e,t]}function combinedNodes(e,t){const n=SemanticHeuristics.factory.makeBranchNode(SemanticType.PUNCTUATION,e,[]);return n.role=t,n}SemanticHeuristics.add(new SemanticMultiHeuristic("ellipses",(e=>{const t=[];let n=e.shift();for(;n;)[n,e]=combineNodes(n,e,SemanticRole.FULLSTOP,SemanticRole.ELLIPSIS),[n,e]=combineNodes(n,e,SemanticRole.DASH),t.push(n),n=e.shift();return t}),(e=>e.length>1))),SemanticHeuristics.add(new SemanticMultiHeuristic("op_with_limits",(e=>{const t=e[0];return t.type=SemanticType.LARGEOP,t.role=SemanticRole.SUM,e}),(e=>e[0].type===SemanticType.OPERATOR&&e.slice(1).some((e=>e.type===SemanticType.RELSEQ||e.type===SemanticType.MULTIREL||e.type===SemanticType.INFIXOP&&e.role===SemanticRole.ELEMENT||e.type===SemanticType.PUNCTUATED&&e.role===SemanticRole.SEQUENCE))))),SemanticHeuristics.add(new SemanticMultiHeuristic("bracketed_interval",(e=>{const t=e[0],n=e[1],r=e.slice(2),i=SemanticProcessor.getInstance().row(r),s=SemanticHeuristics.factory.makeBranchNode(SemanticType.FENCED,[i],[t,n]);return s.role=SemanticRole.LEFTRIGHT,s}),(e=>{const t=e[0],n=e[1],r=e.slice(2);if(!t||"]"!==t.textContent&&"["!==t.textContent||!n||"]"!==n.textContent&&"["!==n.textContent)return!1;const i=partitionNodes(r,isPunctuation);return!(1!==i.rel.length||!i.comp[0].length||!i.comp[1].length)}))),SemanticHeuristics.add(new SemanticMmlHeuristic("function_from_identifiers",(e=>{const t=toArray(e.childNodes).map((e=>e.textContent.trim())).join("");if(SemanticMap.Meaning.get(t).type===SemanticType.UNKNOWN)return e;const n=SemanticHeuristics.factory.makeLeafNode(t,SemanticProcessor.getInstance().font(e.getAttribute("mathvariant")));return n.mathmlTree=e,n}),(e=>{const t=toArray(e.childNodes);return!(t.length<2)&&t.every((e=>dom_util_tagName(e)===MMLTAGS.MI&&SemanticMap.Meaning.get(e.textContent.trim()).role===SemanticRole.LATINLETTER))})));class SemanticTree{static empty(){const e=parseInput("<math/>"),t=new SemanticTree(e);return t.mathml=e,t}static fromNode(e,t){const n=SemanticTree.empty();return n.root=e,t&&(n.mathml=t),n}static fromRoot(e,t){let n=e;for(;n.parent;)n=n.parent;const r=SemanticTree.fromNode(n);return t&&(r.mathml=t),r}static fromXml(e){const t=SemanticTree.empty();return e.childNodes[0]&&(t.root=SemanticNode.fromXml(e.childNodes[0])),t}constructor(e){this.mathml=e,this.parser=new SemanticMathml,this.root=this.parser.parse(e),this.collator=this.parser.getFactory().leafMap.collateMeaning();const t=this.collator.newDefault();t&&(this.parser=new SemanticMathml,this.parser.getFactory().defaultMap=t,this.root=this.parser.parse(e)),unitVisitor.visit(this.root,{}),annotate(this.root)}xml(e){const t=parseInput("<stree></stree>"),n=this.root.xml(t.ownerDocument,e);return t.appendChild(n),t}toString(e){return serializeXml(this.xml(e))}formatXml(e){return formatXml(this.toString(e))}displayTree(){this.root.displayTree()}replaceNode(e,t){const n=e.parent;n?n.replaceChild(e,t):this.root=t}toJson(){const e={};return e.stree=this.root.toJson(),e}}const unitVisitor=new SemanticVisitor("general","unit",((e,t)=>(isUnitProduct(e)&&(e.role=SemanticRole.UNIT),!1)));function xmlTree(e){return getTree(e).xml()}function getTree(e){return new SemanticTree(e)}function getTreeFromString(e){return getTree(DomUtil.parseInput(e))}function getCase(e){for(let t,n=0;t=factory[n];n++)if(t.test(e))return t.constr(e);return null}const factory=[],SETTINGS={collapsed:!0,implicit:!0,wiki:!0},IDS=new Map;function enrich(e,t){IDS.clear();const n=cloneNode(e);return walkTree(t.root),engine_Engine.getInstance().structure&&e.setAttribute(enrich_attr_Attribute.STRUCTURE,SemanticSkeleton.fromStructure(e,t).toString()),debugger_Debugger.getInstance().generateOutput((()=>[formattedOutput(n,"Original MathML",SETTINGS.wiki),formattedOutput(t,"Semantic Tree",SETTINGS.wiki),formattedOutput(e,"Semantically enriched MathML",SETTINGS.wiki)])),e}function walkTree(e){debugger_Debugger.getInstance().output("WALKING START: "+e.toString());const t=getCase(e);let n;if(t)return n=t.getMathml(),debugger_Debugger.getInstance().output("WALKING END: "+e.toString()),ascendNewNode(n);if(1===e.mathml.length){if(debugger_Debugger.getInstance().output("Walktree Case 0"),!e.childNodes.length)return debugger_Debugger.getInstance().output("Walktree Case 0.1"),n=e.mathml[0],setAttributes(n,e),debugger_Debugger.getInstance().output("WALKING END: "+e.toString()),ascendNewNode(n);const t=e.childNodes[0];if(1===e.childNodes.length&&t.type===SemanticType.EMPTY)return debugger_Debugger.getInstance().output("Walktree Case 0.2"),n=e.mathml[0],setAttributes(n,e),n.appendChild(walkTree(t)),debugger_Debugger.getInstance().output("WALKING END: "+e.toString()),ascendNewNode(n);e.childNodes.forEach((e=>{e.mathml.length||(e.mathml=[createInvisibleOperator(e)])}))}const r=e.contentNodes.map(cloneContentNode);setOperatorAttribute(e,r);const i=e.childNodes.map(walkTree),s=SemanticSkeleton.combineContentChildren(e.type,e.role,r,i);if(n=e.mathmlTree,null===n)debugger_Debugger.getInstance().output("Walktree Case 1"),n=introduceNewLayer(s,e);else{const e=attachedElement(s);debugger_Debugger.getInstance().output("Walktree Case 2"),e?(debugger_Debugger.getInstance().output("Walktree Case 2.1"),n=parentNode(e)):(debugger_Debugger.getInstance().output("Walktree Case 2.2"),n=getInnerNode(n))}return n=rewriteMfenced(n),mergeChildren(n,s,e),IDS.has(e.id)||(IDS.set(e.id,!0),setAttributes(n,e)),debugger_Debugger.getInstance().output("WALKING END: "+e.toString()),ascendNewNode(n)}function introduceNewLayer(e,t){const n=mathmlLca(e);let r=n.node;const i=n.type;if(i!==lcaType.VALID||!hasEmptyTag(r)||!r.parentNode&&t.parent)if(debugger_Debugger.getInstance().output("Walktree Case 1.1"),r=addMrow(),i===lcaType.PRUNED)debugger_Debugger.getInstance().output("Walktree Case 1.1.0"),r=introduceLayerAboveLca(r,n.node,e);else if(e[0]){debugger_Debugger.getInstance().output("Walktree Case 1.1.1");const t=attachedElement(e);if(t){const n=childrenSubset(parentNode(t),e);replaceNode(t,r),n.forEach((function(e){r.appendChild(e)}))}else moveSemanticAttributes(r,e[0]),r=e[0]}return t.mathmlTree||(t.mathmlTree=r),r}function introduceLayerAboveLca(e,t,n){let r=descendNode(t);if(hasMathTag(r)){debugger_Debugger.getInstance().output("Walktree Case 1.1.0.0"),moveSemanticAttributes(r,e),toArray(r.childNodes).forEach((function(t){e.appendChild(t)}));const t=e;e=r,r=t}const i=n.indexOf(t);return n[i]=r,replaceNode(r,e),e.appendChild(r),n.forEach((function(t){e.appendChild(t)})),e}function moveSemanticAttributes(e,t){for(const n of EnrichAttributes)e.hasAttribute(n)&&(t.setAttribute(n,e.getAttribute(n)),e.removeAttribute(n))}function childrenSubset(e,t){const n=toArray(e.childNodes);let r=1/0,i=-1/0;return t.forEach((function(e){const t=n.indexOf(e);-1!==t&&(r=Math.min(r,t),i=Math.max(i,t))})),n.slice(r,i+1)}function collateChildNodes(e,t,n){const r=[];let i=toArray(e.childNodes),s=!1;for(;i.length;){const e=i.shift();if(e.hasAttribute(enrich_attr_Attribute.TYPE)){r.push(e);continue}const n=collectChildNodes(e,t);0!==n.length&&(1!==n.length?(s?e.setAttribute("AuxiliaryImplicit",!0):s=!0,i=n.concat(i)):r.push(e))}const o=[],a=n.childNodes.map((function(e){return e.mathmlTree}));for(;a.length;){const e=a.pop();if(e){if(-1!==r.indexOf(e))break;-1!==t.indexOf(e)&&o.unshift(e)}}return r.concat(o)}function collectChildNodes(e,t){const n=[];let r=toArray(e.childNodes);for(;r.length;){const e=r.shift();e.nodeType===NodeType.ELEMENT_NODE&&(e.hasAttribute(enrich_attr_Attribute.TYPE)||-1!==t.indexOf(e)?n.push(e):r=toArray(e.childNodes).concat(r))}return n}function mergeChildren(e,t,n){if(!t.length)return;if(1===t.length&&e===t[0])return;const r=n.role===SemanticRole.IMPLICIT&&SemanticHeuristics.flags.combine_juxtaposition?collateChildNodes(e,t,n):toArray(e.childNodes);if(!r.length)return void t.forEach((function(t){e.appendChild(t)}));let i=0;for(;t.length;){const n=t[0];if(r[i]===n||functionApplication(r[i],n)){t.shift(),i++;continue}if(r[i]&&-1===t.indexOf(r[i])){i++;continue}if(isDescendant(n,e)){t.shift();continue}const s=r[i];if(s)insertNewChild(e,s,n),t.shift();else{if(n.parentNode){e=parentNode(n),t.shift();continue}const r=t[1];if(r&&r.parentNode){(e=parentNode(r)).insertBefore(n,r),t.shift(),t.shift();continue}e.insertBefore(n,null),t.shift()}}}function insertNewChild(e,t,n){let r=t,i=parentNode(r);for(;i&&i.firstChild===r&&!r.hasAttribute("AuxiliaryImplicit")&&i!==e;)r=i,i=parentNode(r);i&&(i.insertBefore(n,r),r.removeAttribute("AuxiliaryImplicit"))}function isDescendant(e,t){if(!e)return!1;do{if((e=parentNode(e))===t)return!0}while(e);return!1}function functionApplication(e,t){const n=NamedSymbol.functionApplication;if(e&&t&&e.textContent&&t.textContent&&e.textContent===n&&t.textContent===n&&"true"===t.getAttribute(enrich_attr_Attribute.ADDED)){for(let n,r=0;n=e.attributes[r];r++)t.hasAttribute(n.nodeName)||t.setAttribute(n.nodeName,n.nodeValue);return replaceNode(e,t),!0}return!1}var lcaType;function mathmlLca(e){const t=attachedElement(e);if(!t)return{type:lcaType.INVALID,node:null};const n=attachedElement(e.slice().reverse());if(t===n)return{type:lcaType.VALID,node:t};const r=pathToRoot(t),i=prunePath(r,e),s=pathToRoot(n,(function(e){return-1!==i.indexOf(e)})),o=s[0],a=i.indexOf(o);return-1===a?{type:lcaType.INVALID,node:null}:{type:i.length!==r.length?lcaType.PRUNED:validLca(i[a+1],s[1])?lcaType.VALID:lcaType.INVALID,node:o}}function prunePath(e,t){let n=0;for(;e[n]&&-1===t.indexOf(e[n]);)n++;return e.slice(0,n+1)}function attachedElement(e){let t=0,n=null;for(;!n&&t<e.length;)e[t].parentNode&&(n=e[t]),t++;return n}function pathToRoot(e,t){const n=t||(e=>!1),r=[e];for(;!n(e)&&!hasMathTag(e)&&e.parentNode;)e=parentNode(e),r.unshift(e);return r}function validLca(e,t){return!(!e||!t||e.previousSibling||t.nextSibling)}function ascendNewNode(e){for(;!hasMathTag(e)&&unitChild(e);)e=parentNode(e);return e}function descendNode(e){const t=toArray(e.childNodes);if(!t)return e;const n=t.filter((function(e){return e.nodeType===NodeType.ELEMENT_NODE&&!hasIgnoreTag(e)}));return 1===n.length&&hasEmptyTag(n[0])&&!n[0].hasAttribute(enrich_attr_Attribute.TYPE)?descendNode(n[0]):e}function unitChild(e){const t=parentNode(e);return!(!t||!hasEmptyTag(t))&&toArray(t.childNodes).every((function(t){return t===e||isIgnorable(t)}))}function isIgnorable(e){if(e.nodeType!==NodeType.ELEMENT_NODE)return!0;if(!e||hasIgnoreTag(e))return!0;const t=toArray(e.childNodes);return!(!hasEmptyTag(e)&&t.length||hasDisplayTag(e)||e.hasAttribute(enrich_attr_Attribute.TYPE)||isOrphanedGlyph(e))&&toArray(e.childNodes).every(isIgnorable)}function parentNode(e){return e.parentNode}function addCollapsedAttribute(e,t){const n=new SemanticSkeleton(t);e.setAttribute(enrich_attr_Attribute.COLLAPSED,n.toString())}function cloneContentNode(e){if(e.mathml.length)return walkTree(e);const t=SETTINGS.implicit?createInvisibleOperator(e):addMrow();return e.mathml=[t],t}function rewriteMfenced(e){if(dom_util_tagName(e)!==MMLTAGS.MFENCED)return e;const t=addMrow();for(let n,r=0;n=e.attributes[r];r++)-1===["open","close","separators"].indexOf(n.name)&&t.setAttribute(n.name,n.value);return toArray(e.childNodes).forEach((function(e){t.appendChild(e)})),replaceNode(e,t),t}function createInvisibleOperator(e){const t=createElement("mo"),n=createTextNode(e.textContent);return t.appendChild(n),setAttributes(t,e),t.setAttribute(enrich_attr_Attribute.ADDED,"true"),t}function setOperatorAttribute(e,t){const n=e.type+(e.textContent?","+e.textContent:"");t.forEach((function(e){getInnerNode(e).setAttribute(enrich_attr_Attribute.OPERATOR,n)}))}function getInnerNode(e){const t=toArray(e.childNodes);if(!t)return e;const n=t.filter((function(e){return!isIgnorable(e)})),r=[];for(let e,t=0;e=n[t];t++)if(hasEmptyTag(e)&&e.getAttribute(enrich_attr_Attribute.TYPE)!==SemanticType.PUNCTUATION){const t=getInnerNode(e);t&&t!==e&&r.push(t)}else r.push(e);return 1===r.length?r[0]:e}function formattedOutput(e,t,n=!1){const r=removeAttributePrefix(formatXml(e.toString()));return n?t+":\n```html\n"+r+"\n```\n":r}function collapsePunctuated(e,t){const n=!!t,r=t||[],i=e.parent,s=e.contentNodes.map((function(e){return e.id}));s.unshift("c");const o=[e.id,s];for(let t,s=0;t=e.childNodes[s];s++){const e=walkTree(t);r.push(e);const s=getInnerNode(e);i&&!n&&s.setAttribute(enrich_attr_Attribute.PARENT,i.id.toString()),o.push(t.id)}return o}!function(e){e.VALID="valid",e.INVALID="invalid",e.PRUNED="pruned"}(lcaType||(lcaType={}));class AbstractEnrichCase{constructor(e){this.semantic=e}}class CaseBinomial extends AbstractEnrichCase{static test(e){return!e.mathmlTree&&e.type===SemanticType.LINE&&e.role===SemanticRole.BINOMIAL}constructor(e){super(e),this.mml=e.mathmlTree}getMathml(){if(!this.semantic.childNodes.length)return this.mml;const e=this.semantic.childNodes[0];if(this.mml=walkTree(e),this.mml.hasAttribute(enrich_attr_Attribute.TYPE)){const e=addMrow();replaceNode(this.mml,e),e.appendChild(this.mml),this.mml=e}return setAttributes(this.mml,this.semantic),this.mml}}class CaseDoubleScript extends AbstractEnrichCase{static test(e){if(!e.mathmlTree||!e.childNodes.length)return!1;const t=dom_util_tagName(e.mathmlTree),n=e.childNodes[0].role;return t===MMLTAGS.MSUBSUP&&n===SemanticRole.SUBSUP||t===MMLTAGS.MUNDEROVER&&n===SemanticRole.UNDEROVER}constructor(e){super(e),this.mml=e.mathmlTree}getMathml(){const e=this.semantic.childNodes[0],t=e.childNodes[0],n=this.semantic.childNodes[1],r=e.childNodes[1],i=walkTree(n),s=walkTree(t),o=walkTree(r);return setAttributes(this.mml,this.semantic),this.mml.setAttribute(enrich_attr_Attribute.CHILDREN,makeIdList([t,r,n])),[s,o,i].forEach((e=>getInnerNode(e).setAttribute(enrich_attr_Attribute.PARENT,this.mml.getAttribute(enrich_attr_Attribute.ID)))),this.mml.setAttribute(enrich_attr_Attribute.TYPE,e.role),addCollapsedAttribute(this.mml,[this.semantic.id,[e.id,t.id,r.id],n.id]),this.mml}}class CaseMultiindex extends AbstractEnrichCase{static multiscriptIndex(e){return e.type===SemanticType.PUNCTUATED&&e.contentNodes[0].role===SemanticRole.DUMMY?collapsePunctuated(e):(walkTree(e),e.id)}static createNone_(e){const t=createElement("none");return e&&setAttributes(t,e),t.setAttribute(enrich_attr_Attribute.ADDED,"true"),t}constructor(e){super(e),this.mml=e.mathmlTree}completeMultiscript(e,t){const n=toArray(this.mml.childNodes).slice(1);let r=0;const i=e=>{for(const t of e){const e=n[r];if(e&&t===parseInt(e.getAttribute(enrich_attr_Attribute.ID)))e.setAttribute(enrich_attr_Attribute.PARENT,this.semantic.id.toString()),r++;else if(e&&t===parseInt(getInnerNode(e).getAttribute(enrich_attr_Attribute.ID)))getInnerNode(e).setAttribute(enrich_attr_Attribute.PARENT,this.semantic.id.toString()),r++;else{const n=this.semantic.querySelectorAll((e=>e.id===t));this.mml.insertBefore(CaseMultiindex.createNone_(n[0]),e||null)}}};i(e),n[r]&&dom_util_tagName(n[r])!==MMLTAGS.MPRESCRIPTS?this.mml.insertBefore(n[r],createElement("mprescripts")):r++,i(t)}}class CaseMultiscripts extends CaseMultiindex{static test(e){if(!e.mathmlTree)return!1;return dom_util_tagName(e.mathmlTree)===MMLTAGS.MMULTISCRIPTS&&(e.type===SemanticType.SUPERSCRIPT||e.type===SemanticType.SUBSCRIPT)}constructor(e){super(e)}getMathml(){let e,t,n;if(setAttributes(this.mml,this.semantic),this.semantic.childNodes[0]&&this.semantic.childNodes[0].role===SemanticRole.SUBSUP){const r=this.semantic.childNodes[0];e=r.childNodes[0],t=CaseMultiindex.multiscriptIndex(this.semantic.childNodes[1]),n=CaseMultiindex.multiscriptIndex(r.childNodes[1]);const i=[this.semantic.id,[r.id,e.id,n],t];addCollapsedAttribute(this.mml,i),this.mml.setAttribute(enrich_attr_Attribute.TYPE,r.role),this.completeMultiscript(SemanticSkeleton.interleaveIds(n,t),[])}else{e=this.semantic.childNodes[0],t=CaseMultiindex.multiscriptIndex(this.semantic.childNodes[1]);const n=[this.semantic.id,e.id,t];addCollapsedAttribute(this.mml,n)}const r=SemanticSkeleton.collapsedLeafs(n||[],t);return getInnerNode(walkTree(e)).setAttribute(enrich_attr_Attribute.PARENT,this.semantic.id.toString()),r.unshift(e.id),this.mml.setAttribute(enrich_attr_Attribute.CHILDREN,r.join(",")),this.mml}}class CaseTensor extends CaseMultiindex{static test(e){return!!e.mathmlTree&&e.type===SemanticType.TENSOR}constructor(e){super(e)}getMathml(){walkTree(this.semantic.childNodes[0]);const e=CaseMultiindex.multiscriptIndex(this.semantic.childNodes[1]),t=CaseMultiindex.multiscriptIndex(this.semantic.childNodes[2]),n=CaseMultiindex.multiscriptIndex(this.semantic.childNodes[3]),r=CaseMultiindex.multiscriptIndex(this.semantic.childNodes[4]);setAttributes(this.mml,this.semantic);const i=[this.semantic.id,this.semantic.childNodes[0].id,e,t,n,r];addCollapsedAttribute(this.mml,i);const s=SemanticSkeleton.collapsedLeafs(e,t,n,r);return s.unshift(this.semantic.childNodes[0].id),this.mml.setAttribute(enrich_attr_Attribute.CHILDREN,s.join(",")),this.completeMultiscript(SemanticSkeleton.interleaveIds(n,r),SemanticSkeleton.interleaveIds(e,t)),this.mml}}class CaseEmbellished extends AbstractEnrichCase{static test(e){return!(!e.mathmlTree||!e.fencePointer||e.mathmlTree.getAttribute("data-semantic-type"))}static makeEmptyNode_(e){const t=addMrow(),n=new SemanticNode(e);return n.type=SemanticType.EMPTY,n.mathmlTree=t,n}static fencedMap_(e,t){t[e.id]=e.mathmlTree,e.embellished&&CaseEmbellished.fencedMap_(e.childNodes[0],t)}constructor(e){super(e),this.fenced=null,this.fencedMml=null,this.fencedMmlNodes=[],this.ofence=null,this.ofenceMml=null,this.ofenceMap={},this.cfence=null,this.cfenceMml=null,this.cfenceMap={},this.parentCleanup=[]}getMathml(){this.getFenced_(),this.fencedMml=walkTree(this.fenced),this.getFencesMml_(),this.fenced.type!==SemanticType.EMPTY||this.fencedMml.parentNode||(this.fencedMml.setAttribute(enrich_attr_Attribute.ADDED,"true"),this.cfenceMml.parentNode.insertBefore(this.fencedMml,this.cfenceMml)),this.getFencedMml_();return this.rewrite_()}fencedElement(e){return e.type===SemanticType.FENCED||e.type===SemanticType.MATRIX||e.type===SemanticType.VECTOR}getFenced_(){let e=this.semantic;for(;!this.fencedElement(e);)e=e.childNodes[0];this.fenced=e.childNodes[0],this.ofence=e.contentNodes[0],this.cfence=e.contentNodes[1],CaseEmbellished.fencedMap_(this.ofence,this.ofenceMap),CaseEmbellished.fencedMap_(this.cfence,this.cfenceMap)}getFencedMml_(){let e=this.ofenceMml.nextSibling;for(e=e===this.fencedMml?e:this.fencedMml;e&&e!==this.cfenceMml;)this.fencedMmlNodes.push(e),e=e.nextSibling}getFencesMml_(){let e=this.semantic;const t=Object.keys(this.ofenceMap),n=Object.keys(this.cfenceMap);for(;!(this.ofenceMml&&this.cfenceMml||e===this.fenced);)-1===t.indexOf(e.fencePointer)||this.ofenceMml||(this.ofenceMml=e.mathmlTree),-1===n.indexOf(e.fencePointer)||this.cfenceMml||(this.cfenceMml=e.mathmlTree),e=e.childNodes[0];this.ofenceMml||(this.ofenceMml=this.ofence.mathmlTree),this.cfenceMml||(this.cfenceMml=this.cfence.mathmlTree),this.ofenceMml&&(this.ofenceMml=ascendNewNode(this.ofenceMml)),this.cfenceMml&&(this.cfenceMml=ascendNewNode(this.cfenceMml))}rewrite_(){let e=this.semantic,t=null;const n=this.introduceNewLayer_();for(setAttributes(n,this.fenced.parent);!this.fencedElement(e);){const r=e.mathmlTree,i=this.specialCase_(e,r);if(i)e=i;else{setAttributes(r,e);const t=[];for(let n,r=1;n=e.childNodes[r];r++)t.push(walkTree(n));e=e.childNodes[0]}const s=createElement("dummy"),o=r.childNodes[0];replaceNode(r,s),replaceNode(n,r),replaceNode(r.childNodes[0],n),replaceNode(s,o),t||(t=r)}return walkTree(this.ofence),walkTree(this.cfence),this.cleanupParents_(),t||n}specialCase_(e,t){const n=dom_util_tagName(t);let r,i=null;if(n===MMLTAGS.MSUBSUP?(i=e.childNodes[0],r=CaseDoubleScript):n===MMLTAGS.MMULTISCRIPTS&&(e.type===SemanticType.SUPERSCRIPT||e.type===SemanticType.SUBSCRIPT?r=CaseMultiscripts:e.type===SemanticType.TENSOR&&(r=CaseTensor),i=r&&e.childNodes[0]&&e.childNodes[0].role===SemanticRole.SUBSUP?e.childNodes[0]:e),!i)return null;const s=i.childNodes[0],o=CaseEmbellished.makeEmptyNode_(s.id);return i.childNodes[0]=o,t=new r(e).getMathml(),i.childNodes[0]=s,this.parentCleanup.push(t),i.childNodes[0]}introduceNewLayer_(){const e=this.fullFence(this.ofenceMml),t=this.fullFence(this.cfenceMml);let n=addMrow();if(replaceNode(this.fencedMml,n),this.fencedMmlNodes.forEach((e=>n.appendChild(e))),n.insertBefore(e,this.fencedMml),n.appendChild(t),!n.parentNode){const e=addMrow();for(;n.childNodes.length>0;)e.appendChild(n.childNodes[0]);n.appendChild(e),n=e}return n}fullFence(e){const t=this.fencedMml.parentNode;let n=e;for(;n.parentNode&&n.parentNode!==t;)n=n.parentNode;return n}cleanupParents_(){this.parentCleanup.forEach((function(e){const t=e.childNodes[1].getAttribute(enrich_attr_Attribute.PARENT);e.childNodes[0].setAttribute(enrich_attr_Attribute.PARENT,t)}))}}class CaseEmpheq extends AbstractEnrichCase{static test(e){return!!e.mathmlTree&&e.hasAnnotation("Emph","top")}constructor(e){super(e),this.mrows=[],this.mml=e.mathmlTree}getMathml(){if(this.recurseToTable(this.semantic),this.mrows.length){const e=addMrow();this.mml.parentNode.insertBefore(e,this.mml);for(const t of this.mrows)e.appendChild(t);e.appendChild(this.mml)}return this.mml}recurseToTable(e){var t,n;if(e.hasAnnotation("Emph","top")||e.hasAnnotation("Emph","fence")||!e.hasAnnotation("Emph","left")&&!e.hasAnnotation("Emph","right")){if(!e.mathmlTree||dom_util_tagName(e.mathmlTree)===MMLTAGS.MTABLE&&(null===(t=e.annotation.Emph)||void 0===t?void 0:t.length)&&"table"!==e.annotation.Emph[0]){const t=addMrow();setAttributes(t,e),this.mrows.unshift(t)}else{if(dom_util_tagName(e.mathmlTree)===MMLTAGS.MTABLE&&(null===(n=e.annotation.Emph)||void 0===n?void 0:n.length)&&"table"===e.annotation.Emph[0])return void this.finalizeTable(e);setAttributes(e.mathmlTree,e)}if(e.childNodes.forEach(this.recurseToTable.bind(this)),e.textContent||"punctuated"===e.type){const t=e.contentNodes.map((e=>{const t=cloneContentNode(e);return t.hasAttribute("data-semantic-added")?this.mrows.unshift(t):this.recurseToTable(e),t}));setOperatorAttribute(e,t)}else e.contentNodes.forEach(this.recurseToTable.bind(this))}else walkTree(e)}finalizeTable(e){setAttributes(e.mathmlTree,e),e.contentNodes.forEach((e=>{walkTree(e)})),e.childNodes.forEach((e=>{walkTree(e)}))}}class CaseLimit extends AbstractEnrichCase{static test(e){if(!e.mathmlTree||!e.childNodes.length)return!1;const t=dom_util_tagName(e.mathmlTree),n=e.type;return(n===SemanticType.LIMUPPER||n===SemanticType.LIMLOWER)&&(t===MMLTAGS.MSUBSUP||t===MMLTAGS.MUNDEROVER)||n===SemanticType.LIMBOTH&&(t===MMLTAGS.MSUB||t===MMLTAGS.MUNDER||t===MMLTAGS.MSUP||t===MMLTAGS.MOVER)}static walkTree_(e){e&&walkTree(e)}constructor(e){super(e),this.mml=e.mathmlTree}getMathml(){const e=this.semantic.childNodes;return this.semantic.type!==SemanticType.LIMBOTH&&this.mml.childNodes.length>=3&&(this.mml=introduceNewLayer([this.mml],this.semantic)),setAttributes(this.mml,this.semantic),e[0].mathmlTree||(e[0].mathmlTree=this.semantic.mathmlTree),e.forEach(CaseLimit.walkTree_),this.mml}}class CaseLine extends AbstractEnrichCase{static test(e){return!!e.mathmlTree&&e.type===SemanticType.LINE}constructor(e){super(e),this.mml=e.mathmlTree}getMathml(){return this.semantic.contentNodes.length&&walkTree(this.semantic.contentNodes[0]),this.semantic.childNodes.length&&walkTree(this.semantic.childNodes[0]),setAttributes(this.mml,this.semantic),this.mml}}class CaseProof extends AbstractEnrichCase{static test(e){return!!e.mathmlTree&&(e.type===SemanticType.INFERENCE||e.type===SemanticType.PREMISES)}constructor(e){super(e),this.mml=e.mathmlTree}getMathml(){return this.semantic.childNodes.length?(this.semantic.contentNodes.forEach((function(e){walkTree(e),setAttributes(e.mathmlTree,e)})),this.semantic.childNodes.forEach((function(e){walkTree(e)})),setAttributes(this.mml,this.semantic),this.mml.getAttribute("data-semantic-id")===this.mml.getAttribute("data-semantic-parent")&&this.mml.removeAttribute("data-semantic-parent"),this.mml):this.mml}}class CaseTable extends AbstractEnrichCase{static test(e){return e.type===SemanticType.MATRIX||e.type===SemanticType.VECTOR||e.type===SemanticType.CASES}constructor(e){super(e),this.inner=[],this.mml=e.mathmlTree}getMathml(){const e=cloneContentNode(this.semantic.contentNodes[0]),t=this.semantic.contentNodes[1]?cloneContentNode(this.semantic.contentNodes[1]):null;if(this.inner=this.semantic.childNodes.map(walkTree),this.mml)if(dom_util_tagName(this.mml)===MMLTAGS.MFENCED){const n=this.mml.childNodes;this.mml.insertBefore(e,n[0]||null),t&&this.mml.appendChild(t),this.mml=rewriteMfenced(this.mml)}else{const n=[e,this.mml];t&&n.push(t),this.mml=introduceNewLayer(n,this.semantic)}else this.mml=introduceNewLayer([e].concat(this.inner,[t]),this.semantic);return setAttributes(this.mml,this.semantic),this.mml}}class CaseText extends AbstractEnrichCase{static test(e){return e.type===SemanticType.PUNCTUATED&&(e.role===SemanticRole.TEXT||e.contentNodes.every((e=>e.role===SemanticRole.DUMMY)))}constructor(e){super(e),this.mml=e.mathmlTree}getMathml(){const e=[],t=collapsePunctuated(this.semantic,e);return this.mml=introduceNewLayer(e,this.semantic),setAttributes(this.mml,this.semantic),this.mml.removeAttribute(enrich_attr_Attribute.CONTENT),addCollapsedAttribute(this.mml,t),this.mml}}function semanticMathmlNode(e){const t=cloneNode(e);return enrich(t,getTree(t))}function semanticMathmlSync(e){return semanticMathmlNode(parseInput(e))}function semanticMathml(e,t){EnginePromise.getall().then((()=>{const n=DomUtil.parseInput(e);t(semanticMathmlNode(n))}))}function testTranslation(e){Debugger.getInstance().init();const t=semanticMathmlSync(prepareMmlString(e));return Debugger.getInstance().exit(),t}function prepareMmlString(e){return e.match(/^<math/)||(e="<math>"+e),e.match(/\/math>$/)||(e+="</math>"),e}factory.push({test:CaseLimit.test,constr:e=>new CaseLimit(e)},{test:CaseEmbellished.test,constr:e=>new CaseEmbellished(e)},{test:CaseDoubleScript.test,constr:e=>new CaseDoubleScript(e)},{test:CaseTensor.test,constr:e=>new CaseTensor(e)},{test:CaseMultiscripts.test,constr:e=>new CaseMultiscripts(e)},{test:CaseLine.test,constr:e=>new CaseLine(e)},{test:CaseBinomial.test,constr:e=>new CaseBinomial(e)},{test:CaseProof.test,constr:e=>new CaseProof(e)},{test:CaseEmpheq.test,constr:e=>new CaseEmpheq(e)},{test:CaseTable.test,constr:e=>new CaseTable(e)},{test:CaseText.test,constr:e=>new CaseText(e)});let counter=0;class AbstractHighlighter{constructor(){this.counter=counter++,this.ATTR="sre-highlight-"+this.counter.toString(),this.color=null,this.mactionName="",this.currentHighlights=[]}highlight(e){this.currentHighlights.push(e.map((e=>{const t=this.highlightNode(e);return this.setHighlighted(e),t})))}highlightAll(e){const t=this.getMactionNodes(e);for(let e,n=0;e=t[n];n++)this.highlight([e])}unhighlight(){const e=this.currentHighlights.pop();e&&e.forEach((e=>{this.isHighlighted(e.node)&&(this.unhighlightNode(e),this.unsetHighlighted(e.node))}))}unhighlightAll(){for(;this.currentHighlights.length>0;)this.unhighlight()}setColor(e){this.color=e}colorString(){return this.color.rgba()}addEvents(e,t){const n=this.getMactionNodes(e);for(let e,r=0;e=n[r];r++)for(const[n,r]of Object.entries(t))e.addEventListener(n,r)}getMactionNodes(e){return Array.from(e.getElementsByClassName(this.mactionName))}isMactionNode(e){const t=e.className||e.getAttribute("class");return!!t&&!!t.match(new RegExp(this.mactionName))}isHighlighted(e){return e.hasAttribute(this.ATTR)}setHighlighted(e){e.setAttribute(this.ATTR,"true")}unsetHighlighted(e){e.removeAttribute(this.ATTR)}colorizeAll(e){updateEvaluator(e);evalXPath(`.//*[@${enrich_attr_Attribute.ID}]`,e).forEach((e=>this.colorize(e)))}uncolorizeAll(e){evalXPath(`.//*[@${enrich_attr_Attribute.ID}]`,e).forEach((e=>this.uncolorize(e)))}colorize(e){const t=addPrefix("foreground");e.hasAttribute(t)&&(e.setAttribute(t+"-old",e.style.color),e.style.color=e.getAttribute(t))}uncolorize(e){const t=addPrefix("foreground")+"-old";e.hasAttribute(t)&&(e.style.color=e.getAttribute(t))}}class CssHighlighter extends AbstractHighlighter{constructor(){super(),this.mactionName="mjx-maction"}highlightNode(e){const t={node:e,background:e.style.backgroundColor,foreground:e.style.color};if(!this.isHighlighted(e)){const t=this.colorString();e.style.backgroundColor=t.background,e.style.color=t.foreground}return t}unhighlightNode(e){e.node.style.backgroundColor=e.background,e.node.style.color=e.foreground}}class ChtmlHighlighter extends CssHighlighter{constructor(){super()}isMactionNode(e){var t;return(null===(t=e.tagName)||void 0===t?void 0:t.toUpperCase())===this.mactionName.toUpperCase()}getMactionNodes(e){return Array.from(e.getElementsByTagName(this.mactionName))}}const namedColors={red:{red:255,green:0,blue:0},green:{red:0,green:255,blue:0},blue:{red:0,green:0,blue:255},yellow:{red:255,green:255,blue:0},cyan:{red:0,green:255,blue:255},magenta:{red:255,green:0,blue:255},white:{red:255,green:255,blue:255},black:{red:0,green:0,blue:0}};function getChannelColor(e,t){const n=e||{color:t};let r=Object.prototype.hasOwnProperty.call(n,"color")?namedColors[n.color]:n;return r||(r=namedColors[t]),r.alpha=Object.prototype.hasOwnProperty.call(n,"alpha")?n.alpha:1,normalizeColor(r)}function normalizeColor(e){const t=e=>(e=Math.max(e,0),e=Math.min(255,e),Math.round(e));return e.red=t(e.red),e.green=t(e.green),e.blue=t(e.blue),e.alpha=Math.max(e.alpha,0),e.alpha=Math.min(1,e.alpha),e}class color_picker_ColorPicker{static toHex(e){const t=e.toString(16);return 1===t.length?"0"+t:t}constructor(e,t){this.foreground=getChannelColor(t,color_picker_ColorPicker.DEFAULT_FOREGROUND_),this.background=getChannelColor(e,color_picker_ColorPicker.DEFAULT_BACKGROUND_)}rgba(){const e=function(e){return"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")"};return{background:e(this.background),foreground:e(this.foreground)}}rgb(){const e=function(e){return"rgb("+e.red+","+e.green+","+e.blue+")"};return{background:e(this.background),alphaback:this.background.alpha.toString(),foreground:e(this.foreground),alphafore:this.foreground.alpha.toString()}}hex(){const e=function(e){return"#"+color_picker_ColorPicker.toHex(e.red)+color_picker_ColorPicker.toHex(e.green)+color_picker_ColorPicker.toHex(e.blue)};return{background:e(this.background),alphaback:this.background.alpha.toString(),foreground:e(this.foreground),alphafore:this.foreground.alpha.toString()}}}function hsl2rgb(e,t,n){t=t>1?t/100:t,n=n>1?n/100:n;const r=(1-Math.abs(2*n-1))*t,i=r*(1-Math.abs(e/60%2-1)),s=n-r/2;let o=0,a=0,c=0;return 0<=e&&e<60?[o,a,c]=[r,i,0]:60<=e&&e<120?[o,a,c]=[i,r,0]:120<=e&&e<180?[o,a,c]=[0,r,i]:180<=e&&e<240?[o,a,c]=[0,i,r]:240<=e&&e<300?[o,a,c]=[i,0,r]:300<=e&&e<360&&([o,a,c]=[r,0,i]),{red:o+s,green:a+s,blue:c+s}}function rgb2RGB(e){return{red:Math.round(255*e.red),green:Math.round(255*e.green),blue:Math.round(255*e.blue)}}function RGB2hex(e){return"rgb("+e.red+","+e.green+","+e.blue+")"}color_picker_ColorPicker.DEFAULT_BACKGROUND_="blue",color_picker_ColorPicker.DEFAULT_FOREGROUND_="black";class ContrastPicker{constructor(){this.hue=10,this.sat=100,this.light=50,this.incr=50}generate(){return RGB2hex(rgb2RGB(hsl2rgb(this.hue,this.sat,this.light)))}increment(){this.hue=(this.hue+this.incr)%360}}class HtmlHighlighter extends AbstractHighlighter{constructor(){super(),this.mactionName="maction"}highlightNode(e){const t={node:e,foreground:e.style.color,position:e.style.position},n=this.color.rgb();e.style.color=n.foreground,e.style.position="relative";const r=e.bbox;if(r&&r.w){const i=.05,s=0,o=createElement("span"),a=parseFloat(e.style.paddingLeft||"0");o.style.backgroundColor=n.background,o.style.opacity=n.alphaback.toString(),o.style.display="inline-block",o.style.height=r.h+r.d+2*i+"em",o.style.verticalAlign=-r.d+"em",o.style.marginTop=o.style.marginBottom=-i+"em",o.style.width=r.w+2*s+"em",o.style.marginLeft=a-s+"em",o.style.marginRight=-r.w-s-a+"em",e.parentNode.insertBefore(o,e),t.box=o}return t}unhighlightNode(e){const t=e.node;t.style.color=e.foreground,t.style.position=e.position,e.box&&e.box.parentNode.removeChild(e.box)}}class MmlCssHighlighter extends CssHighlighter{constructor(){super(),this.mactionName="maction"}getMactionNodes(e){return Array.from(e.getElementsByTagName(this.mactionName))}isMactionNode(e){return e.tagName===this.mactionName}}class MmlHighlighter extends AbstractHighlighter{constructor(){super(),this.mactionName="maction"}highlightNode(e){let t=e.getAttribute("style");return t+=";background-color: "+this.colorString().background,t+=";color: "+this.colorString().foreground,e.setAttribute("style",t),{node:e}}unhighlightNode(e){let t=e.node.getAttribute("style");t=t.replace(";background-color: "+this.colorString().background,""),t=t.replace(";color: "+this.colorString().foreground,""),e.node.setAttribute("style",t)}colorString(){return this.color.rgba()}getMactionNodes(e){return Array.from(e.getElementsByTagName(this.mactionName))}isMactionNode(e){return e.tagName===this.mactionName}}class SvgHighlighter extends AbstractHighlighter{constructor(){super(),this.mactionName="mjx-svg-maction"}highlightNode(e){let t;if(this.isHighlighted(e))return t={node:e.previousSibling||e,background:e.style.backgroundColor,foreground:e.style.color},t;if("svg"===e.tagName){const t={node:e,background:e.style.backgroundColor,foreground:e.style.color};return e.style.backgroundColor=this.colorString().background,e.style.color=this.colorString().foreground,t}const n=createElementNS("http://www.w3.org/2000/svg","rect");let r;if("use"===e.nodeName){const t=createElementNS("http://www.w3.org/2000/svg","g");e.parentNode.insertBefore(t,e),t.appendChild(e),r=t.getBBox(),t.parentNode.replaceChild(e,t)}else r=e.getBBox();n.setAttribute("x",(r.x-40).toString()),n.setAttribute("y",(r.y-40).toString()),n.setAttribute("width",(r.width+80).toString()),n.setAttribute("height",(r.height+80).toString());const i=e.getAttribute("transform");return i&&n.setAttribute("transform",i),n.setAttribute("fill",this.colorString().background),n.setAttribute(this.ATTR,"true"),e.parentNode.insertBefore(n,e),t={node:n,foreground:e.getAttribute("fill")},e.setAttribute("fill",this.colorString().foreground),t}setHighlighted(e){"svg"===e.tagName&&super.setHighlighted(e)}unhighlightNode(e){if("background"in e)return e.node.style.backgroundColor=e.background,void(e.node.style.color=e.foreground);e.foreground?e.node.nextSibling.setAttribute("fill",e.foreground):e.node.nextSibling.removeAttribute("fill"),e.node.parentNode.removeChild(e.node)}isMactionNode(e){let t=e.className||e.getAttribute("class");return!!t&&(t=void 0!==t.baseVal?t.baseVal:t,!!t&&!!t.match(new RegExp(this.mactionName)))}}class SvgV3Highlighter extends SvgHighlighter{constructor(){super(),this.mactionName="maction"}highlightNode(e){let t;if(this.isHighlighted(e))return t={node:e,background:this.colorString().background,foreground:this.colorString().foreground},t;if("svg"===e.tagName||"MJX-CONTAINER"===e.tagName)return t={node:e,background:e.style.backgroundColor,foreground:e.style.color},e.style.backgroundColor=this.colorString().background,e.style.color=this.colorString().foreground,t;const n=createElementNS("http://www.w3.org/2000/svg","rect");n.setAttribute("sre-highlighter-added","true");const r=e.getBBox();n.setAttribute("x",(r.x-40).toString()),n.setAttribute("y",(r.y-40).toString()),n.setAttribute("width",(r.width+80).toString()),n.setAttribute("height",(r.height+80).toString());const i=e.getAttribute("transform");if(i&&n.setAttribute("transform",i),n.setAttribute("fill",this.colorString().background),e.setAttribute(this.ATTR,"true"),e.parentNode.insertBefore(n,e),t={node:e,foreground:e.getAttribute("fill")},"rect"===e.nodeName){const t=new color_picker_ColorPicker({alpha:0,color:"black"});e.setAttribute("fill",t.rgba().foreground)}else e.setAttribute("fill",this.colorString().foreground);return t}unhighlightNode(e){const t=e.node.previousSibling;if(t&&t.hasAttribute("sre-highlighter-added"))return e.foreground?e.node.setAttribute("fill",e.foreground):e.node.removeAttribute("fill"),void e.node.parentNode.removeChild(t);e.node.style.backgroundColor=e.background,e.node.style.color=e.foreground}isMactionNode(e){return e.getAttribute("data-mml-node")===this.mactionName}getMactionNodes(e){return Array.from(evalXPath(`.//*[@data-mml-node="${this.mactionName}"]`,e))}}function highlighter(e,t,n){const r=new color_picker_ColorPicker(e,t),i="NativeMML"===n.renderer&&"Safari"===n.browser?"MML-CSS":"SVG"===n.renderer&&"v3"===n.browser?"SVG-V3":n.renderer,s=new(highlighterMapping[i]||highlighterMapping.NativeMML);return s.setColor(r),s}function update(e,t,n){const r=new ColorPicker(e,t);n.setColor(r)}function addEvents(e,t,n){const r=highlighterMapping[n.renderer];r&&(new r).addEvents(e,t)}const highlighterMapping={SVG:SvgHighlighter,"SVG-V3":SvgV3Highlighter,NativeMML:MmlHighlighter,"HTML-CSS":HtmlHighlighter,"MML-CSS":MmlCssHighlighter,CommonHTML:CssHighlighter,CHTML:ChtmlHighlighter};function splitAttribute(e){return e?e.split(/,/):[]}function getAttribute(e,t){return e.getAttribute(t)}function getSemanticRoot(e){if(e.hasAttribute(enrich_attr_Attribute.TYPE)&&!e.hasAttribute(enrich_attr_Attribute.PARENT))return e;const t=querySelectorAllByAttr(e,enrich_attr_Attribute.TYPE);for(let e,n=0;e=t[n];n++)if(!e.hasAttribute(enrich_attr_Attribute.PARENT))return e;return e}function getBySemanticId(e,t){return e.getAttribute(enrich_attr_Attribute.ID)===t?e:querySelectorAllByAttrValue(e,enrich_attr_Attribute.ID,t)[0]}function getAllBySemanticId(e,t){return e.getAttribute(enrich_attr_Attribute.ID)===t?[e]:querySelectorAllByAttrValue(e,enrich_attr_Attribute.ID,t)}class RebuildStree{static textContent(e,t,n){if(!n&&t.textContent)return void(e.textContent=t.textContent);const r=splitAttribute(getAttribute(t,enrich_attr_Attribute.OPERATOR));r.length>1&&(e.textContent=r[1])}static isPunctuated(e){return!SemanticSkeleton.simpleCollapseStructure(e)&&e[1]&&SemanticSkeleton.contentCollapseStructure(e[1])}constructor(e){this.mathml=e,this.factory=new SemanticNodeFactory,this.nodeDict={},this.mmlRoot=getSemanticRoot(e),this.streeRoot=this.assembleTree(this.mmlRoot),this.stree=SemanticTree.fromNode(this.streeRoot,this.mathml),this.xml=this.stree.xml()}getTree(){return this.stree}assembleTree(e){const t=this.makeNode(e),n=splitAttribute(getAttribute(e,enrich_attr_Attribute.CHILDREN)),r=splitAttribute(getAttribute(e,enrich_attr_Attribute.CONTENT));if(0===r.length&&0===n.length)return RebuildStree.textContent(t,e),t;if(r.length>0){const e=getBySemanticId(this.mathml,r[0]);e&&RebuildStree.textContent(t,e,!0)}t.contentNodes=r.map((e=>this.setParent(e,t))),t.childNodes=n.map((e=>this.setParent(e,t)));const i=getAttribute(e,enrich_attr_Attribute.COLLAPSED);return i?this.postProcess(t,i):t}makeNode(e){const t=getAttribute(e,enrich_attr_Attribute.TYPE),n=getAttribute(e,enrich_attr_Attribute.ROLE),r=getAttribute(e,enrich_attr_Attribute.FONT),i=getAttribute(e,enrich_attr_Attribute.ANNOTATION)||"",s=getAttribute(e,enrich_attr_Attribute.ATTRIBUTES)||"",o=getAttribute(e,enrich_attr_Attribute.ID),a=getAttribute(e,enrich_attr_Attribute.EMBELLISHED),c=getAttribute(e,enrich_attr_Attribute.FENCEPOINTER),l=this.createNode(parseInt(o,10));return l.type=t,l.role=n,l.font=r||SemanticFont.UNKNOWN,l.parseAnnotation(i),l.parseAttributes(s),c&&(l.fencePointer=c),a&&(l.embellished=a),l}makePunctuation(e){const t=this.createNode(e);return t.updateContent(NamedSymbol.invisibleComma),t.role=SemanticRole.DUMMY,t}makePunctuated(e,t,n){const r=this.createNode(t[0]);r.type=SemanticType.PUNCTUATED,r.embellished=e.embellished,r.fencePointer=e.fencePointer,r.role=n;const i=t.splice(1,1)[0].slice(1);r.contentNodes=i.map(this.makePunctuation.bind(this)),this.collapsedChildren_(t)}makeEmpty(e,t,n){const r=this.createNode(t);r.type=SemanticType.EMPTY,r.embellished=e.embellished,r.fencePointer=e.fencePointer,r.role=n}makeIndex(e,t,n){if(RebuildStree.isPunctuated(t))return this.makePunctuated(e,t,n),void(t=t[0]);SemanticSkeleton.simpleCollapseStructure(t)&&!this.nodeDict[t.toString()]&&this.makeEmpty(e,t,n)}postProcess(e,t){const n=SemanticSkeleton.fromString(t).array;if(e.type===SemanticRole.SUBSUP){const t=this.createNode(n[1][0]);return t.type=SemanticType.SUBSCRIPT,t.role=SemanticRole.SUBSUP,e.type=SemanticType.SUPERSCRIPT,t.embellished=e.embellished,t.fencePointer=e.fencePointer,this.makeIndex(e,n[1][2],SemanticRole.RIGHTSUB),this.makeIndex(e,n[2],SemanticRole.RIGHTSUPER),this.collapsedChildren_(n),e}if(e.type===SemanticType.SUBSCRIPT)return this.makeIndex(e,n[2],SemanticRole.RIGHTSUB),this.collapsedChildren_(n),e;if(e.type===SemanticType.SUPERSCRIPT)return this.makeIndex(e,n[2],SemanticRole.RIGHTSUPER),this.collapsedChildren_(n),e;if(e.type===SemanticType.TENSOR)return this.makeIndex(e,n[2],SemanticRole.LEFTSUB),this.makeIndex(e,n[3],SemanticRole.LEFTSUPER),this.makeIndex(e,n[4],SemanticRole.RIGHTSUB),this.makeIndex(e,n[5],SemanticRole.RIGHTSUPER),this.collapsedChildren_(n),e;if(e.type===SemanticType.PUNCTUATED){if(RebuildStree.isPunctuated(n)){const t=n.splice(1,1)[0].slice(1);e.contentNodes=t.map(this.makePunctuation.bind(this))}return e}if(e.type===SemanticRole.UNDEROVER){const t=this.createNode(n[1][0]);return e.childNodes[1].role===SemanticRole.OVERACCENT?(t.type=SemanticType.OVERSCORE,e.type=SemanticType.UNDERSCORE):(t.type=SemanticType.UNDERSCORE,e.type=SemanticType.OVERSCORE),t.role=SemanticRole.UNDEROVER,t.embellished=e.embellished,t.fencePointer=e.fencePointer,this.collapsedChildren_(n),e}return e}createNode(e){const t=this.factory.makeNode(e);return this.nodeDict[e.toString()]=t,t}collapsedChildren_(e){const t=e=>{const n=this.nodeDict[e[0]];n.childNodes=[];for(let r=1,i=e.length;r<i;r++){const i=e[r];n.childNodes.push(SemanticSkeleton.simpleCollapseStructure(i)?this.nodeDict[i]:t(i))}return n};t(e)}setParent(e,t){const n=getBySemanticId(this.mathml,e),r=this.assembleTree(n);return r.parent=t,r}}function computeSpeech(e){return SpeechRuleEngine.getInstance().evaluateNode(e)}function recomputeSpeech(e){return computeSpeech(SemanticTree.fromNode(e).xml())}function computeMarkup(e){return markup(computeSpeech(e))}function recomputeMarkup(e){return markup(recomputeSpeech(e))}function addSpeech(e,t,n){const r=querySelectorAllByAttrValue(n,"id",t.id.toString())[0],i=r?markup(computeSpeech(r)):recomputeMarkup(t);e.setAttribute(enrich_attr_Attribute.SPEECH,i)}function addModality(e,t,n){const r=recomputeMarkup(t);e.setAttribute(n,r)}function speech_generator_util_addPrefix(e,t){const n=retrievePrefix(t);n&&e.setAttribute(enrich_attr_Attribute.PREFIX,n)}function retrievePrefix(e){return markup(computePrefix(e))}function computePrefix(e){const t=SemanticTree.fromRoot(e),n=evalXPath('.//*[@id="'+e.id+'"]',t.xml());let r=n[0];return n.length>1&&(r=nodeAtPosition(e,n)||r),r?SpeechRuleEngine.getInstance().runInSetting({modality:"prefix",domain:"default",style:"default",strict:!0,speech:!0},(function(){return SpeechRuleEngine.getInstance().evaluateNode(r)})):[]}function nodeAtPosition(e,t){const n=t[0];if(!e.parent)return n;const r=[];for(;e;)r.push(e.id),e=e.parent;const i=function(e,t){for(;t.length&&t.shift().toString()===e.getAttribute("id")&&e.parentNode&&e.parentNode.parentNode;)e=e.parentNode.parentNode;return!t.length};for(let e,n=0;e=t[n];n++)if(i(e,r.slice()))return e;return n}function connectMactions(e,t,n){const r=querySelectorAll(t,"maction");for(let t,i=0;t=r[i];i++){const r=querySelectorAllByAttrValue(e,"id",t.getAttribute("id"))[0];if(!r)continue;const i=t.childNodes[1],s=i.getAttribute(enrich_attr_Attribute.ID);let o=getBySemanticId(e,s);if(o&&"dummy"!==o.getAttribute(enrich_attr_Attribute.TYPE))continue;if(o=r.childNodes[0],o.getAttribute("sre-highlighter-added"))continue;const a=i.getAttribute(enrich_attr_Attribute.PARENT);a&&o.setAttribute(enrich_attr_Attribute.PARENT,a),o.setAttribute(enrich_attr_Attribute.TYPE,"dummy"),o.setAttribute(enrich_attr_Attribute.ID,s),o.setAttribute("role","treeitem"),o.setAttribute("aria-level",i.getAttribute("aria-level"));querySelectorAllByAttrValue(n,"id",s)[0].setAttribute("alternative",s)}}function connectAllMactions(e,t){const n=DomUtil.querySelectorAll(e,"maction");for(let e,r=0;e=n[r];r++){const n=e.childNodes[1].getAttribute(Attribute.ID);DomUtil.querySelectorAllByAttrValue(t,"id",n)[0].setAttribute("alternative",n)}}function retrieveSummary(e,t={}){return markup(computeSummary(e,t))}function computeSummary(e,t={}){const n=t.locale?{locale:t.locale}:{};return e?SpeechRuleEngine.getInstance().runInSetting(Object.assign(n,{modality:"summary",strict:!1,speech:!0}),(function(){return SpeechRuleEngine.getInstance().evaluateNode(e)})):[]}class ClearspeakPreferences extends DynamicCstr{static comparator(){return new Comparator(engine_Engine.getInstance().dynamicCstr,DynamicProperties.createProp([DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]],[DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]],[DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN]],[DynamicCstr.DEFAULT_VALUES[Axis.STYLE]]))}static fromPreference(e){const t=e.split(":"),n={},r=PREFERENCES.getProperties(),i=Object.keys(r);for(let e,s=0;e=t[s];s++){const t=e.split("_");if(-1===i.indexOf(t[0]))continue;const s=t[1];s&&s!==ClearspeakPreferences.AUTO&&-1!==r[t[0]].indexOf(s)&&(n[t[0]]=t[1])}return n}static toPreference(e){const t=Object.keys(e),n=[];for(let r=0;r<t.length;r++)n.push(t[r]+"_"+e[t[r]]);return n.length?n.join(":"):DynamicCstr.DEFAULT_VALUE}static getLocalePreferences(e){const t=e||enumerate(SpeechRuleEngine.getInstance().enumerate());return ClearspeakPreferences.getLocalePreferences_(t)}static currentPreference(){return DOMAIN_TO_STYLES.clearspeak}static relevantPreferences(e){const t=SEMANTIC_MAPPING_[e.type];return t&&(t[e.role]||t[""])||"ImpliedTimes"}static findPreference(e,t){if("default"===e)return ClearspeakPreferences.AUTO;return ClearspeakPreferences.fromPreference(e)[t]||ClearspeakPreferences.AUTO}static addPreference(e,t,n){if("default"===e)return t+"_"+n;const r=ClearspeakPreferences.fromPreference(e);return r[t]=n,ClearspeakPreferences.toPreference(r)}static getLocalePreferences_(e){const t={};for(const n of Object.keys(e)){if(!e[n].speech||!e[n].speech.clearspeak)continue;const r=Object.keys(e[n].speech.clearspeak);if(r.length<3)continue;const i=t[n]={};for(const e in PREFERENCES.getProperties()){const t=PREFERENCES.getProperties()[e],n=[e+"_Auto"];if(t)for(const i of t)-1!==r.indexOf(e+"_"+i)&&n.push(e+"_"+i);i[e]=n}}return t}constructor(e,t){super(e),this.preference=t}equal(e){if(!super.equal(e))return!1;const t=Object.keys(this.preference),n=e.preference;if(t.length!==Object.keys(n).length)return!1;for(let e,r=0;e=t[r];r++)if(this.preference[e]!==n[e])return!1;return!0}}ClearspeakPreferences.AUTO="Auto";const PREFERENCES=new DynamicProperties({AbsoluteValue:["Auto","AbsEnd","Cardinality","Determinant"],Bar:["Auto","Conjugate"],Caps:["Auto","SayCaps"],CombinationPermutation:["Auto","ChoosePermute"],Currency:["Auto","Position","Prefix"],Ellipses:["Auto","AndSoOn"],Enclosed:["Auto","EndEnclose"],Exponent:["Auto","AfterPower","Ordinal","OrdinalPower","Exponent"],Fraction:["Auto","EndFrac","FracOver","General","GeneralEndFrac","Ordinal","Over","OverEndFrac","Per"],Functions:["Auto","None","Reciprocal"],ImpliedTimes:["Auto","MoreImpliedTimes","None"],Log:["Auto","LnAsNaturalLog"],Matrix:["Auto","Combinatoric","EndMatrix","EndVector","SilentColNum","SpeakColNum","Vector"],MultiLineLabel:["Auto","Case","Constraint","Equation","Line","None","Row","Step"],MultiLineOverview:["Auto","None"],MultiLinePausesBetweenColumns:["Auto","Long","Short"],MultsymbolDot:["Auto","Dot"],MultsymbolX:["Auto","By","Cross"],Paren:["Auto","CoordPoint","Interval","Silent","Speak","SpeakNestingLevel"],Prime:["Auto","Angle","Length"],Roots:["Auto","PosNegSqRoot","PosNegSqRootEnd","RootEnd"],SetMemberSymbol:["Auto","Belongs","Element","Member","In"],Sets:["Auto","SilentBracket","woAll"],TriangleSymbol:["Auto","Delta"],Trig:["Auto","ArcTrig","TrigInverse","Reciprocal"],VerticalLine:["Auto","Divides","Given","SuchThat"]});class Comparator extends DefaultComparator{constructor(e,t){super(e,t),this.preference=e instanceof ClearspeakPreferences?e.preference:{}}match(e){if(!(e instanceof ClearspeakPreferences))return super.match(e);if("default"===e.getComponents()[Axis.STYLE])return!0;const t=Object.keys(e.preference);for(let n,r=0;n=t[r];r++)if(this.preference[n]!==e.preference[n])return!1;return!0}compare(e,t){const n=super.compare(e,t);if(0!==n)return n;const r=e instanceof ClearspeakPreferences,i=t instanceof ClearspeakPreferences;if(!r&&i)return 1;if(r&&!i)return-1;if(!r&&!i)return 0;const s=Object.keys(e.preference).length,o=Object.keys(t.preference).length;return s>o?-1:s<o?1:0}}class Parser extends DynamicCstrParser{constructor(){super([Axis.LOCALE,Axis.MODALITY,Axis.DOMAIN,Axis.STYLE])}parse(e){const t=super.parse(e);let n=t.getValue(Axis.STYLE);const r=t.getValue(Axis.LOCALE),i=t.getValue(Axis.MODALITY);let s={};return n!==DynamicCstr.DEFAULT_VALUE&&(s=this.fromPreference(n),n=this.toPreference(s)),new ClearspeakPreferences({locale:r,modality:i,domain:"clearspeak",style:n},s)}fromPreference(e){return ClearspeakPreferences.fromPreference(e)}toPreference(e){return ClearspeakPreferences.toPreference(e)}}const REVERSE_MAPPING=[["AbsoluteValue",SemanticType.FENCED,SemanticRole.NEUTRAL,SemanticRole.METRIC],["Bar",SemanticType.OVERSCORE,SemanticRole.OVERACCENT],["Caps",SemanticType.IDENTIFIER,SemanticRole.LATINLETTER],["CombinationPermutation",SemanticType.APPL,SemanticRole.UNKNOWN],["Ellipses",SemanticType.PUNCTUATION,SemanticRole.ELLIPSIS],["Exponent",SemanticType.SUPERSCRIPT,""],["Fraction",SemanticType.FRACTION,""],["Functions",SemanticType.APPL,SemanticRole.SIMPLEFUNC],["ImpliedTimes",SemanticType.OPERATOR,SemanticRole.IMPLICIT],["Log",SemanticType.APPL,SemanticRole.PREFIXFUNC],["Matrix",SemanticType.MATRIX,""],["Matrix",SemanticType.VECTOR,""],["MultiLineLabel",SemanticType.MULTILINE,SemanticRole.LABEL],["MultiLineOverview",SemanticType.MULTILINE,SemanticRole.TABLE],["MultiLinePausesBetweenColumns",SemanticType.MULTILINE,SemanticRole.TABLE],["MultiLineLabel",SemanticType.TABLE,SemanticRole.LABEL],["MultiLineOverview",SemanticType.TABLE,SemanticRole.TABLE],["MultiLinePausesBetweenColumns",SemanticType.TABLE,SemanticRole.TABLE],["MultiLineLabel",SemanticType.CASES,SemanticRole.LABEL],["MultiLineOverview",SemanticType.CASES,SemanticRole.TABLE],["MultiLinePausesBetweenColumns",SemanticType.CASES,SemanticRole.TABLE],["MultsymbolDot",SemanticType.OPERATOR,SemanticRole.MULTIPLICATION],["MultsymbolX",SemanticType.OPERATOR,SemanticRole.MULTIPLICATION],["Paren",SemanticType.FENCED,SemanticRole.LEFTRIGHT],["Prime",SemanticType.SUPERSCRIPT,SemanticRole.PRIME],["Roots",SemanticType.ROOT,""],["Roots",SemanticType.SQRT,""],["SetMemberSymbol",SemanticType.RELATION,SemanticRole.ELEMENT],["Sets",SemanticType.FENCED,SemanticRole.SETEXT],["TriangleSymbol",SemanticType.IDENTIFIER,SemanticRole.GREEKLETTER],["Trig",SemanticType.APPL,SemanticRole.PREFIXFUNC],["VerticalLine",SemanticType.PUNCTUATED,SemanticRole.VBAR]],SEMANTIC_MAPPING_=function(){const e={};for(let t,n=0;t=REVERSE_MAPPING[n];n++){const n=t[0];let r=e[t[1]];r||(r={},e[t[1]]=r),r[t[2]]=n}return e}();engine_Engine.getInstance().comparators.clearspeak=ClearspeakPreferences.comparator,engine_Engine.getInstance().parsers.clearspeak=new Parser;class AbstractSpeechGenerator{constructor(){this.modality=addPrefix("speech"),this.rebuilt_=null,this.options_={}}getRebuilt(){return this.rebuilt_}setRebuilt(e){this.rebuilt_=e}computeRebuilt(e,t=!1){return this.rebuilt_&&!t||(this.rebuilt_=new RebuildStree(e)),this.rebuilt_}setOptions(e){this.options_=e||{},this.modality=addPrefix(this.options_.modality||"speech")}setOption(e,t){const n=this.getOptions();n[e]=t,this.setOptions(n)}getOptions(){return this.options_}generateSpeech(e,t){return this.rebuilt_||(this.rebuilt_=new RebuildStree(t)),setup(this.options_),computeMarkup(this.getRebuilt().xml)}nextRules(){const e=this.getOptions();if("speech"!==e.modality)return;ClearspeakPreferences.getLocalePreferences()[e.locale]&&(DOMAIN_TO_STYLES[e.domain]=e.style,e.domain="mathspeak"===e.domain?"clearspeak":"mathspeak",e.style=DOMAIN_TO_STYLES[e.domain],this.setOptions(e))}nextStyle(e){this.setOption("style",this.nextStyle_(this.getRebuilt().nodeDict[e]))}nextStyle_(e){const{modality:t,domain:n,style:r}=this.getOptions();if("speech"!==t)return r;if("mathspeak"===n){const e=["default","brief","sbrief"],t=e.indexOf(r);return-1===t?r:t>=e.length-1?e[0]:e[t+1]}if("clearspeak"===n){const t=ClearspeakPreferences.getLocalePreferences().en;if(!t)return"default";const n=ClearspeakPreferences.relevantPreferences(e),i=ClearspeakPreferences.findPreference(r,n),s=t[n].map((function(e){return e.split("_")[1]})),o=s.indexOf(i);if(-1===o)return r;const a=o>=s.length-1?s[0]:s[o+1];return ClearspeakPreferences.addPreference(r,n,a)}return r}getLevel(e){return LOCALE.MESSAGES.navigate.LEVEL+" "+e}getActionable(e){return e?e<0?LOCALE.MESSAGES.navigate.EXPANDABLE:LOCALE.MESSAGES.navigate.COLLAPSIBLE:""}}class AdhocSpeechGenerator extends AbstractSpeechGenerator{getSpeech(e,t){const n=this.generateSpeech(e,t);return e.setAttribute(this.modality,n),n}}class ColorGenerator extends AbstractSpeechGenerator{constructor(){super(...arguments),this.modality=addPrefix("foreground"),this.contrast=new ContrastPicker}static visitStree_(e,t,n){if(e.childNodes.length){if(e.contentNodes.length&&("punctuated"===e.type&&e.contentNodes.forEach((e=>n[e.id]=!0)),"implicit"!==e.role&&t.push(e.contentNodes.map((e=>e.id)))),e.childNodes.length){if("implicit"===e.role){const r=[];let i=[];for(const t of e.childNodes){const e=[];ColorGenerator.visitStree_(t,e,n),e.length<=2&&r.push(e.shift()),i=i.concat(e)}return t.push(r),void i.forEach((e=>t.push(e)))}e.childNodes.forEach((e=>ColorGenerator.visitStree_(e,t,n)))}}else n[e.id]||t.push(e.id)}getSpeech(e,t){return getAttribute(e,this.modality)}generateSpeech(e,t){return this.getRebuilt()||this.setRebuilt(new RebuildStree(parseInput(t))),this.colorLeaves_(e),getAttribute(e,this.modality)}colorLeaves_(e){const t=[];ColorGenerator.visitStree_(this.getRebuilt().streeRoot,t,{});for(const n of t){const t=this.contrast.generate();let r=!1;r=Array.isArray(n)?n.map((n=>this.colorLeave_(e,n,t))).reduce(((e,t)=>e||t),!1):this.colorLeave_(e,n.toString(),t),r&&this.contrast.increment()}}colorLeave_(e,t,n){const r=getBySemanticId(e,t);return!!r&&(r.setAttribute(this.modality,n),!0)}}class DirectSpeechGenerator extends AbstractSpeechGenerator{getSpeech(e,t){return getAttribute(e,this.modality)}}class DummySpeechGenerator extends AbstractSpeechGenerator{getSpeech(e,t){return""}}class TreeSpeechGenerator extends AbstractSpeechGenerator{getSpeech(e,t,n=null){this.getRebuilt()&&connectMactions(e,t,this.getRebuilt().xml);const r=this.generateSpeech(e,t),i=this.getRebuilt().nodeDict;for(const[r,s]of Object.entries(i)){const i=getBySemanticId(t,r),o=getBySemanticId(e,r)||n&&getBySemanticId(n,r);i&&o&&(this.modality&&this.modality!==enrich_attr_Attribute.SPEECH?addModality(o,s,this.modality):addSpeech(o,s,this.getRebuilt().xml),this.modality===enrich_attr_Attribute.SPEECH&&speech_generator_util_addPrefix(o,s))}return r}}class NodeSpeechGenerator extends TreeSpeechGenerator{getSpeech(e,t){return super.getSpeech(e,t),getAttribute(e,this.modality)}}class SummarySpeechGenerator extends AbstractSpeechGenerator{getSpeech(e,t){setup(this.getOptions());const n=e.getAttribute(enrich_attr_Attribute.ID);addModality(e,this.getRebuilt().streeRoot.querySelectorAll((e=>e.id.toString()===n))[0],this.modality);return e.getAttribute(enrich_attr_Attribute.SUMMARY)}}function speech_generator_factory_generator(e){return(generatorMapping[e]||generatorMapping.Direct)()}const generatorMapping={Adhoc:()=>new AdhocSpeechGenerator,Color:()=>new ColorGenerator,Direct:()=>new DirectSpeechGenerator,Dummy:()=>new DummySpeechGenerator,Node:()=>new NodeSpeechGenerator,Summary:()=>new SummarySpeechGenerator,Tree:()=>new TreeSpeechGenerator};class Focus{static factory(e,t,n,r){const i=e=>getBySemanticId(r,e),s=n.nodeDict,o=i(e),a=t.map(i),c=t.map((function(e){return s[e]})),l=new Focus(c,s[e]);return l.domNodes=a,l.domPrimary_=o,l.allNodes=Focus.generateAllVisibleNodes_(t,a,s,r),l}static generateAllVisibleNodes_(e,t,n,r){let i=[];for(let s=0,o=e.length;s<o;s++){if(t[s]){const n=Focus.getAllVisibleNodes([e[s]],r);n.length?i=i.concat(n):i.push(t[s]);continue}const o=n[e[s]];if(!o)continue;const a=o.childNodes.map((e=>e.id.toString())),c=Focus.getAllVisibleNodes(a,r);i=i.concat(Focus.generateAllVisibleNodes_(a,c,n,r))}return i}static getAllVisibleNodes(e,t){let n=[];for(const r of e)n=n.concat(getAllBySemanticId(t,r));return n}constructor(e,t){this.nodes=e,this.primary=t,this.domNodes=[],this.domPrimary_=null,this.allNodes=[]}getSemanticPrimary(){return this.primary}getSemanticNodes(){return this.nodes}getNodes(){return this.allNodes}getDomNodes(){return this.domNodes}getDomPrimary(){return this.domPrimary_}toString(){return"Primary:"+this.domPrimary_+" Nodes:"+this.domNodes}clone(){const e=new Focus(this.nodes,this.primary);return e.domNodes=this.domNodes,e.domPrimary_=this.domPrimary_,e.allNodes=this.allNodes,e}}var WalkerMoves;!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right",e.REPEAT="repeat",e.DEPTH="depth",e.ENTER="enter",e.EXPAND="expand",e.HOME="home",e.SUMMARY="summary",e.DETAIL="detail",e.ROW="row",e.CELL="cell"}(WalkerMoves||(WalkerMoves={}));class WalkerState{static resetState(e){delete WalkerState.STATE[e]}static setState(e,t){WalkerState.STATE[e]=t}static getState(e){return WalkerState.STATE[e]}}WalkerState.STATE={};class AbstractWalker{constructor(e,t,n,r){this.node=e,this.generator=t,this.highlighter=n,this.modifier=!1,this.keyMapping=new Map([[KeyCode.UP,this.up.bind(this)],[KeyCode.DOWN,this.down.bind(this)],[KeyCode.RIGHT,this.right.bind(this)],[KeyCode.LEFT,this.left.bind(this)],[KeyCode.TAB,this.repeat.bind(this)],[KeyCode.DASH,this.expand.bind(this)],[KeyCode.SPACE,this.depth.bind(this)],[KeyCode.HOME,this.home.bind(this)],[KeyCode.X,this.summary.bind(this)],[KeyCode.Z,this.detail.bind(this)],[KeyCode.V,this.virtualize.bind(this)],[KeyCode.P,this.previous.bind(this)],[KeyCode.U,this.undo.bind(this)],[KeyCode.LESS,this.previousRules.bind(this)],[KeyCode.GREATER,this.nextRules.bind(this)]]),this.cursors=[],this.xml_=null,this.rebuilt_=null,this.focus_=null,this.active_=!1,this.node.id?this.id=this.node.id:this.node.hasAttribute(AbstractWalker.SRE_ID_ATTR)?this.id=this.node.getAttribute(AbstractWalker.SRE_ID_ATTR):(this.node.setAttribute(AbstractWalker.SRE_ID_ATTR,AbstractWalker.ID_COUNTER.toString()),this.id=AbstractWalker.ID_COUNTER++),this.rootNode=getSemanticRoot(e),this.rootId=this.rootNode.getAttribute(enrich_attr_Attribute.ID),this.xmlString_=r,this.moved=WalkerMoves.ENTER}getXml(){return this.xml_||(this.xml_=parseInput(this.xmlString_)),this.xml_}getRebuilt(){return this.rebuilt_||this.rebuildStree(),this.rebuilt_}isActive(){return this.active_}activate(){this.isActive()||this.toggleActive_()}deactivate(){this.isActive()&&(WalkerState.setState(this.id,this.primaryId()),this.toggleActive_())}getFocus(e=!1){return null===this.rootId&&this.getRebuilt(),this.focus_||(this.focus_=this.singletonFocus(this.rootId)),e&&this.updateFocus(),this.focus_}setFocus(e){this.focus_=e}getDepth(){return this.levels.depth()-1}isSpeech(){return this.generator.modality===enrich_attr_Attribute.SPEECH}focusDomNodes(){return this.getFocus().getDomNodes()}focusSemanticNodes(){return this.getFocus().getSemanticNodes()}speech(){const e=this.focusDomNodes();if(!e.length)return"";const t=this.specialMove();if(null!==t)return t;switch(this.moved){case WalkerMoves.DEPTH:return this.depth_();case WalkerMoves.SUMMARY:return this.summary_();case WalkerMoves.DETAIL:return this.detail_();default:{const t=[],n=this.focusSemanticNodes();for(let r=0,i=e.length;r<i;r++){const i=e[r],s=n[r];t.push(i?this.generator.getSpeech(i,this.getXml(),this.node):recomputeMarkup(s))}return this.mergePrefix_(t)}}}move(e){const t=this.keyMapping.get(e);if(!t)return null;const n=t();return!(!n||n===this.getFocus())&&(this.setFocus(n),this.moved===WalkerMoves.HOME&&(this.levels=this.initLevels()),!0)}up(){return this.moved=WalkerMoves.UP,this.getFocus()}down(){return this.moved=WalkerMoves.DOWN,this.getFocus()}left(){return this.moved=WalkerMoves.LEFT,this.getFocus()}right(){return this.moved=WalkerMoves.RIGHT,this.getFocus()}repeat(){return this.moved=WalkerMoves.REPEAT,this.getFocus().clone()}depth(){return this.moved=this.isSpeech()?WalkerMoves.DEPTH:WalkerMoves.REPEAT,this.getFocus().clone()}home(){this.moved=WalkerMoves.HOME;return this.singletonFocus(this.rootId)}getBySemanticId(e){return getBySemanticId(this.node,e)}primaryId(){return this.getFocus().getSemanticPrimary().id.toString()}expand(){const e=this.getFocus().getDomPrimary(),t=this.actionable_(e);return t?(this.moved=WalkerMoves.EXPAND,t.dispatchEvent(new Event("click")),this.getFocus().clone()):this.getFocus()}expandable(e){return!!this.actionable_(e)&&0===e.childNodes.length}collapsible(e){return!!this.actionable_(e)&&e.childNodes.length>0}restoreState(){if(!this.highlighter)return;const e=WalkerState.getState(this.id);if(!e)return;let t=this.getRebuilt().nodeDict[e];const n=[];for(;t;)n.push(t.id),t=t.parent;for(n.pop();n.length>0;){this.down();const e=n.pop(),t=this.findFocusOnLevel(e);if(!t)break;this.setFocus(t)}this.moved=WalkerMoves.ENTER}updateFocus(){this.setFocus(Focus.factory(this.getFocus().getSemanticPrimary().id.toString(),this.getFocus().getSemanticNodes().map((e=>e.id.toString())),this.getRebuilt(),this.node))}rebuildStree(){this.rebuilt_=new RebuildStree(this.getXml()),this.rootId=this.rebuilt_.stree.root.id.toString(),this.generator.setRebuilt(this.rebuilt_),this.skeleton=SemanticSkeleton.fromTree(this.rebuilt_.stree),this.skeleton.populate(),this.focus_=this.singletonFocus(this.rootId),this.levels=this.initLevels(),connectMactions(this.node,this.getXml(),this.rebuilt_.xml)}previousLevel(){const e=this.getFocus().getDomPrimary();return e?getAttribute(e,enrich_attr_Attribute.PARENT):this.getFocus().getSemanticPrimary().parent.id.toString()}nextLevel(){const e=this.getFocus().getDomPrimary();let t,n;if(e){t=splitAttribute(getAttribute(e,enrich_attr_Attribute.CHILDREN)),n=splitAttribute(getAttribute(e,enrich_attr_Attribute.CONTENT));const r=getAttribute(e,enrich_attr_Attribute.TYPE),i=getAttribute(e,enrich_attr_Attribute.ROLE);return this.combineContentChildren(r,i,n,t)}const r=e=>e.id.toString(),i=this.getRebuilt().nodeDict[this.primaryId()];return t=i.childNodes.map(r),n=i.contentNodes.map(r),0===t.length?[]:this.combineContentChildren(i.type,i.role,n,t)}singletonFocus(e){this.getRebuilt();const t=this.retrieveVisuals(e);return this.focusFromId(e,t)}retrieveVisuals(e){if(!this.skeleton)return[e];const t=parseInt(e,10),n=this.skeleton.subtreeNodes(t);if(!n.length)return[e];n.unshift(t);const r={},i=[];updateEvaluator(this.getXml());for(const e of n)r[e]||(i.push(e.toString()),r[e]=!0,this.subtreeIds(e,r));return i}subtreeIds(e,t){const n=evalXPath(`//*[@data-semantic-id="${e}"]`,this.getXml());evalXPath("*//@data-semantic-id",n[0]).forEach((e=>t[parseInt(e.textContent,10)]=!0))}focusFromId(e,t){return Focus.factory(e,t,this.getRebuilt(),this.node)}summary(){return this.moved=this.isSpeech()?WalkerMoves.SUMMARY:WalkerMoves.REPEAT,this.getFocus().clone()}detail(){return this.moved=this.isSpeech()?WalkerMoves.DETAIL:WalkerMoves.REPEAT,this.getFocus().clone()}specialMove(){return null}virtualize(e){return this.cursors.push({focus:this.getFocus(),levels:this.levels,undo:e||!this.cursors.length}),this.levels=this.levels.clone(),this.getFocus().clone()}previous(){const e=this.cursors.pop();return e?(this.levels=e.levels,e.focus):this.getFocus()}undo(){let e;do{e=this.cursors.pop()}while(e&&!e.undo);return e?(this.levels=e.levels,e.focus):this.getFocus()}update(e){setup(e).then((()=>speech_generator_factory_generator("Tree").getSpeech(this.node,this.getXml())))}nextRules(){this.generator.nextRules();const e=this.generator.getOptions();return"speech"!==e.modality?this.getFocus():(this.update(e),this.moved=WalkerMoves.REPEAT,this.getFocus().clone())}previousRules(){var e;this.generator.nextStyle(null===(e=this.getFocus().getSemanticPrimary())||void 0===e?void 0:e.id.toString());const t=this.generator.getOptions();return"speech"!==t.modality?this.getFocus():(this.update(t),this.moved=WalkerMoves.REPEAT,this.getFocus().clone())}refocus(){let e,t=this.getFocus();for(;!t.getNodes().length;){e=this.levels.peek();const n=this.up();if(!n)break;this.setFocus(n),t=this.getFocus(!0)}this.levels.push(e),this.setFocus(t)}toggleActive_(){this.active_=!this.active_}mergePrefix_(e,t=[]){const n=this.isSpeech()?this.prefix_():"";n&&e.unshift(n);const r=this.isSpeech()?this.postfix_():"";return r&&e.push(r),finalize(merge(t.concat(e)))}prefix_(){const e=this.getFocus().getDomNodes(),t=this.getFocus().getSemanticNodes();return e[0]?getAttribute(e[0],enrich_attr_Attribute.PREFIX):retrievePrefix(t[0])}postfix_(){const e=this.getFocus().getDomNodes();return e[0]?getAttribute(e[0],enrich_attr_Attribute.POSTFIX):""}depth_(){const e=Grammar.getInstance().getParameter("depth");Grammar.getInstance().setParameter("depth",!0);const t=this.getFocus().getDomPrimary(),n=this.expandable(t)?LOCALE.MESSAGES.navigate.EXPANDABLE:this.collapsible(t)?LOCALE.MESSAGES.navigate.COLLAPSIBLE:"",r=LOCALE.MESSAGES.navigate.LEVEL+" "+this.getDepth(),i=retrievePrefix(this.getFocus().getSemanticNodes()[0]),s=[new AuditoryDescription({text:r,personality:{}}),new AuditoryDescription({text:i,personality:{}}),new AuditoryDescription({text:n,personality:{}})];return Grammar.getInstance().setParameter("depth",e),finalize(markup(s))}actionable_(e){const t=null==e?void 0:e.parentNode;return t&&this.highlighter.isMactionNode(t)?t:null}summary_(){const e=this.getFocus().getSemanticPrimary().id.toString(),t=retrieveSummary(this.getRebuilt().xml.getAttribute("id")===e?this.getRebuilt().xml:querySelectorAllByAttrValue(this.getRebuilt().xml,"id",e)[0]);return this.mergePrefix_([t])}detail_(){const e=this.getFocus().getSemanticPrimary().id.toString(),t=this.getRebuilt().xml.getAttribute("id")===e?this.getRebuilt().xml:querySelectorAllByAttrValue(this.getRebuilt().xml,"id",e)[0],n=t.getAttribute("alternative");t.removeAttribute("alternative");const r=computeMarkup(t),i=this.mergePrefix_([r]);return t.setAttribute("alternative",n),i}}AbstractWalker.ID_COUNTER=0,AbstractWalker.SRE_ID_ATTR="sre-explorer-id";class DummyWalker extends AbstractWalker{up(){return null}down(){return null}left(){return null}right(){return null}repeat(){return null}depth(){return null}home(){return null}getDepth(){return 0}initLevels(){return null}combineContentChildren(e,t,n,r){return[]}findFocusOnLevel(e){return null}}class Levels{constructor(){this.level_=[]}push(e){this.level_.push(e)}pop(){return this.level_.pop()}peek(){return this.level_[this.level_.length-1]||null}indexOf(e){const t=this.peek();return t?t.indexOf(e):null}find(e){const t=this.peek();if(!t)return null;for(let n=0,r=t.length;n<r;n++)if(e(t[n]))return t[n];return null}get(e){const t=this.peek();return!t||e<0||e>=t.length?null:t[e]}depth(){return this.level_.length}clone(){const e=new Levels;return e.level_=this.level_.slice(0),e}toString(){let e="";for(let t,n=0;t=this.level_[n];n++)e+="\n"+t.map((function(e){return e.toString()}));return e}}class SemanticWalker extends AbstractWalker{constructor(e,t,n,r){super(e,t,n,r),this.node=e,this.generator=t,this.highlighter=n,this.levels=null,this.restoreState()}initLevels(){const e=new Levels;return e.push([this.getFocus()]),e}up(){super.up();const e=this.previousLevel();if(!e)return null;this.levels.pop();return this.levels.find((function(t){return t.getSemanticNodes().some((function(t){return t.id.toString()===e}))}))}down(){super.down();const e=this.nextLevel();return 0===e.length?null:(this.levels.push(e),e[0])}combineContentChildren(e,t,n,r){switch(e){case SemanticType.RELSEQ:case SemanticType.INFIXOP:case SemanticType.MULTIREL:return this.makePairList(r,n);case SemanticType.PREFIXOP:return[this.focusFromId(r[0],n.concat(r))];case SemanticType.POSTFIXOP:return[this.focusFromId(r[0],r.concat(n))];case SemanticType.MATRIX:case SemanticType.VECTOR:case SemanticType.FENCED:return[this.focusFromId(r[0],[n[0],r[0],n[1]])];case SemanticType.CASES:return[this.focusFromId(r[0],[n[0],r[0]])];case SemanticType.PUNCTUATED:return t===SemanticRole.TEXT?r.map(this.singletonFocus.bind(this)):r.length===n.length?n.map(this.singletonFocus.bind(this)):this.combinePunctuations(r,n,[],[]);case SemanticType.APPL:return[this.focusFromId(r[0],[r[0],n[0]]),this.singletonFocus(r[1])];case SemanticType.ROOT:return[this.singletonFocus(r[0]),this.singletonFocus(r[1])];default:return r.map(this.singletonFocus.bind(this))}}combinePunctuations(e,t,n,r){if(0===e.length)return r;const i=e.shift(),s=t.shift();return i===s?(n.push(s),this.combinePunctuations(e,t,n,r)):(t.unshift(s),n.push(i),e.length===t.length?(r.push(this.focusFromId(i,n.concat(t))),r):(r.push(this.focusFromId(i,n)),this.combinePunctuations(e,t,[],r)))}makePairList(e,t){if(0===e.length)return[];if(1===e.length)return[this.singletonFocus(e[0])];const n=[this.singletonFocus(e.shift())];for(let r=0,i=e.length;r<i;r++)n.push(this.focusFromId(e[r],[t[r],e[r]]));return n}left(){super.left();const e=this.levels.indexOf(this.getFocus());if(null===e)return null;const t=this.levels.get(e-1);return t||null}right(){super.right();const e=this.levels.indexOf(this.getFocus());if(null===e)return null;const t=this.levels.get(e+1);return t||null}findFocusOnLevel(e){return this.levels.find((t=>t.getSemanticPrimary().id===e))}}class SyntaxWalker extends AbstractWalker{constructor(e,t,n,r){super(e,t,n,r),this.node=e,this.generator=t,this.highlighter=n,this.levels=null,this.restoreState()}initLevels(){const e=new Levels;return e.push([this.primaryId()]),e}up(){super.up();const e=this.previousLevel();return e?(this.levels.pop(),this.singletonFocus(e)):null}down(){super.down();const e=this.nextLevel();if(0===e.length)return null;const t=this.singletonFocus(e[0]);return t&&this.levels.push(e),t}combineContentChildren(e,t,n,r){switch(e){case SemanticType.RELSEQ:case SemanticType.INFIXOP:case SemanticType.MULTIREL:return interleaveLists(r,n);case SemanticType.PREFIXOP:return n.concat(r);case SemanticType.POSTFIXOP:return r.concat(n);case SemanticType.MATRIX:case SemanticType.VECTOR:case SemanticType.FENCED:return r.unshift(n[0]),r.push(n[1]),r;case SemanticType.CASES:return r.unshift(n[0]),r;case SemanticType.PUNCTUATED:return t===SemanticRole.TEXT?interleaveLists(r,n):r;case SemanticType.APPL:return[r[0],n[0],r[1]];case SemanticType.ROOT:return[r[0],r[1]];default:return r}}left(){super.left();const e=this.levels.indexOf(this.primaryId());if(null===e)return null;const t=this.levels.get(e-1);return t?this.singletonFocus(t):null}right(){super.right();const e=this.levels.indexOf(this.primaryId());if(null===e)return null;const t=this.levels.get(e+1);return t?this.singletonFocus(t):null}findFocusOnLevel(e){return this.singletonFocus(e.toString())}focusDomNodes(){return[this.getFocus().getDomPrimary()]}focusSemanticNodes(){return[this.getFocus().getSemanticPrimary()]}}class TableWalker extends SyntaxWalker{constructor(e,t,n,r){super(e,t,n,r),this.node=e,this.generator=t,this.highlighter=n,this.firstJump=null,this.key_=null,this.row_=0,this.currentTable_=null,this.keyMapping.set(KeyCode.ZERO,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.ONE,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.TWO,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.THREE,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.FOUR,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.FIVE,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.SIX,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.SEVEN,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.EIGHT,this.jumpCell.bind(this)),this.keyMapping.set(KeyCode.NINE,this.jumpCell.bind(this))}move(e){this.key_=e;const t=super.move(e);return this.modifier=!1,t}up(){return this.moved=WalkerMoves.UP,this.eligibleCell_()?this.verticalMove_(!1):super.up()}down(){return this.moved=WalkerMoves.DOWN,this.eligibleCell_()?this.verticalMove_(!0):super.down()}jumpCell(){if(!this.isInTable_()||null===this.key_)return this.getFocus();if(this.moved===WalkerMoves.ROW){this.moved=WalkerMoves.CELL;const e=this.key_-KeyCode.ZERO;return this.isLegalJump_(this.row_,e)?this.jumpCell_(this.row_,e):this.getFocus()}const e=this.key_-KeyCode.ZERO;return e>this.currentTable_.childNodes.length?this.getFocus():(this.row_=e,this.moved=WalkerMoves.ROW,this.getFocus().clone())}undo(){const e=super.undo();return e===this.firstJump&&(this.firstJump=null),e}eligibleCell_(){const e=this.getFocus().getSemanticPrimary();return this.modifier&&e.type===SemanticType.CELL&&-1!==TableWalker.ELIGIBLE_CELL_ROLES.indexOf(e.role)}verticalMove_(e){const t=this.previousLevel();if(!t)return null;const n=this.getFocus(),r=this.levels.indexOf(this.primaryId()),i=this.levels.pop(),s=this.levels.indexOf(t),o=this.levels.get(e?s+1:s-1);if(!o)return this.levels.push(i),null;this.setFocus(this.singletonFocus(o));const a=this.nextLevel();return a[r]?(this.levels.push(a),this.singletonFocus(a[r])):(this.setFocus(n),this.levels.push(i),null)}jumpCell_(e,t){this.firstJump?this.virtualize(!1):(this.firstJump=this.getFocus(),this.virtualize(!0));const n=this.currentTable_.id.toString();let r;do{r=this.levels.pop()}while(-1===r.indexOf(n));this.levels.push(r),this.setFocus(this.singletonFocus(n)),this.levels.push(this.nextLevel());const i=this.currentTable_.childNodes[e-1];return this.setFocus(this.singletonFocus(i.id.toString())),this.levels.push(this.nextLevel()),this.singletonFocus(i.childNodes[t-1].id.toString())}isLegalJump_(e,t){const n=querySelectorAllByAttrValue(this.getRebuilt().xml,"id",this.currentTable_.id.toString())[0];if(!n||n.hasAttribute("alternative"))return!1;const r=this.currentTable_.childNodes[e-1];if(!r)return!1;const i=querySelectorAllByAttrValue(n,"id",r.id.toString())[0];return!(!i||i.hasAttribute("alternative"))&&!(!r||!r.childNodes[t-1])}isInTable_(){let e=this.getFocus().getSemanticPrimary();for(;e;){if(-1!==TableWalker.ELIGIBLE_TABLE_TYPES.indexOf(e.type))return this.currentTable_=e,!0;e=e.parent}return!1}}function walker(e,t,n,r,i){return(walkerMapping[e.toLowerCase()]||walkerMapping.dummy)(t,n,r,i)}TableWalker.ELIGIBLE_CELL_ROLES=[SemanticRole.DETERMINANT,SemanticRole.ROWVECTOR,SemanticRole.BINOMIAL,SemanticRole.SQUAREMATRIX,SemanticRole.MULTILINE,SemanticRole.MATRIX,SemanticRole.VECTOR,SemanticRole.CASES,SemanticRole.TABLE],TableWalker.ELIGIBLE_TABLE_TYPES=[SemanticType.MULTILINE,SemanticType.MATRIX,SemanticType.VECTOR,SemanticType.CASES,SemanticType.TABLE];const walkerMapping={dummy:(e,t,n,r)=>new DummyWalker(e,t,n,r),semantic:(e,t,n,r)=>new SemanticWalker(e,t,n,r),syntax:(e,t,n,r)=>new SyntaxWalker(e,t,n,r),table:(e,t,n,r)=>new TableWalker(e,t,n,r)};class Processor{static stringify_(e){return e?e.toString():e}constructor(e,t){this.name=e,this.process=t.processor,this.postprocess=t.postprocessor||((e,t)=>e),this.processor=this.postprocess?function(e){return this.postprocess(this.process(e),e)}:this.process,this.print=t.print||Processor.stringify_,this.pprint=t.pprint||this.print}}Processor.LocalState={walker:null,speechGenerator:null,highlighter:null};class KeyProcessor extends Processor{static getKey_(e){return"string"==typeof e?KeyCode[e.toUpperCase()]:e}constructor(e,t){super(e,t),this.key=t.key||KeyProcessor.getKey_}}const PROCESSORS=new Map;function set(e){PROCESSORS.set(e.name,e)}function get(e){const t=PROCESSORS.get(e);if(!t)throw new SREError("Unknown processor "+e);return t}function processor_factory_process(e,t){const n=get(e);try{return n.processor(t)}catch(e){throw new SREError("Processing error for expression "+t)}}function print(e,t){const n=get(e);return engine_Engine.getInstance().pprint?n.pprint(t):n.print(t)}function processor_factory_output(e,t){const n=get(e);try{const e=n.processor(t);return engine_Engine.getInstance().pprint?n.pprint(e):n.print(e)}catch(e){throw console.log(e),new SREError("Processing error for expression "+t)}}function keypress(e,t){const n=get(e),r=n instanceof KeyProcessor?n.key(t):t,i=n.processor(r);return engine_Engine.getInstance().pprint?n.pprint(i):n.print(i)}set(new Processor("semantic",{processor:function(e){return xmlTree(parseInput(e))},postprocessor:function(e,t){const n=engine_Engine.getInstance().speech;if(n===Speech.NONE)return e;const r=cloneNode(e);let i=computeMarkup(r);if(n===Speech.SHALLOW)return e.setAttribute("speech",finalize(i)),e;const s=evalXPath(".//*[@id]",e),o=evalXPath(".//*[@id]",r);for(let e,t,n=0;e=s[n],t=o[n];n++)i=computeMarkup(t),e.setAttribute("speech",finalize(i));return e},pprint:function(e){return formatXml(e.toString())}})),set(new Processor("speech",{processor:function(e){return finalize(markup(computeSpeech(xmlTree(parseInput(e)))))},pprint:function(e){const t=e.toString();return isXml()?formatXml(t):t}})),set(new Processor("json",{processor:function(e){return getTree(parseInput(e)).toJson()},postprocessor:function(e,t){const n=engine_Engine.getInstance().speech;if(n===Speech.NONE)return e;const r=xmlTree(parseInput(t)),i=computeMarkup(r);if(n===Speech.SHALLOW)return e.stree.speech=finalize(i),e;const s=e=>{const t=computeMarkup(evalXPath(`.//*[@id=${e.id}]`,r)[0]);e.speech=finalize(t),e.children&&e.children.forEach(s)};return s(e.stree),e},print:function(e){return JSON.stringify(e)},pprint:function(e){return JSON.stringify(e,null,2)}})),set(new Processor("description",{processor:function(e){return computeSpeech(xmlTree(parseInput(e)))},print:function(e){return JSON.stringify(e)},pprint:function(e){return JSON.stringify(e,null,2)}})),set(new Processor("enriched",{processor:function(e){return semanticMathmlSync(e)},postprocessor:function(e,t){const n=getSemanticRoot(e);let r;switch(engine_Engine.getInstance().speech){case Speech.NONE:break;case Speech.SHALLOW:r=speech_generator_factory_generator("Adhoc"),r.getSpeech(n,e);break;case Speech.DEEP:r=speech_generator_factory_generator("Tree"),r.getSpeech(e,e)}return e},pprint:function(e){return formatXml(e.toString())}})),set(new Processor("rebuild",{processor:function(e){return new RebuildStree(parseInput(e)).stree.xml()},pprint:function(e){return formatXml(e.toString())}})),set(new Processor("walker",{processor:function(e){const t=speech_generator_factory_generator("Node");Processor.LocalState.speechGenerator=t,t.setOptions({modality:engine_Engine.getInstance().modality,locale:engine_Engine.getInstance().locale,domain:engine_Engine.getInstance().domain,style:engine_Engine.getInstance().style}),Processor.LocalState.highlighter=highlighter({color:"black"},{color:"white"},{renderer:"NativeMML"});const n=processor_factory_process("enriched",e),r=print("enriched",n);return Processor.LocalState.walker=walker(engine_Engine.getInstance().walker,n,t,Processor.LocalState.highlighter,r),Processor.LocalState.walker},print:function(e){return Processor.LocalState.walker.speech()}})),set(new KeyProcessor("move",{processor:function(e){if(!Processor.LocalState.walker)return null;return!1===Processor.LocalState.walker.move(e)?error(e):Processor.LocalState.walker.speech()}})),set(new Processor("number",{processor:function(e){const t=parseInt(e,10);return isNaN(t)?"":LOCALE.NUMBERS.numberToWords(t)}})),set(new Processor("ordinal",{processor:function(e){const t=parseInt(e,10);return isNaN(t)?"":LOCALE.NUMBERS.wordOrdinal(t)}})),set(new Processor("numericOrdinal",{processor:function(e){const t=parseInt(e,10);return isNaN(t)?"":LOCALE.NUMBERS.numericOrdinal(t)}})),set(new Processor("vulgar",{processor:function(e){const[t,n]=e.split("/").map((e=>parseInt(e,10)));return isNaN(t)||isNaN(n)?"":processor_factory_process("speech",`<mfrac><mn>${t}</mn><mn>${n}</mn></mfrac>`)}})),set(new Processor("latex",{processor:function(e){return"braille"===engine_Engine.getInstance().modality&&"euro"===engine_Engine.getInstance().locale||console.info("LaTeX input currently only works for Euro Braille output. Please use the latex-to-speech package from npm for general LaTeX input to SRE."),processor_factory_process("speech",`<math data-latex="${e}"></math>`)}}));var system_awaiter=function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const version=variables.u.VERSION;function setupEngine(e){return system_awaiter(this,void 0,void 0,(function*(){return setup(e)}))}function engineSetup(){const e=["mode"].concat(engine_Engine.STRING_FEATURES,engine_Engine.BINARY_FEATURES),t=engine_Engine.getInstance(),n={};return e.forEach((function(e){n[e]=t[e]})),n.json=system_external.f.jsonPath,n.xpath=system_external.f.WGXpath,n.rules=t.ruleSets.slice(),n}function engineReady(){return system_awaiter(this,void 0,void 0,(function*(){return setupEngine({}).then((()=>engine_EnginePromise.getall()))}))}const localeLoader=standardLoader;function toSpeech(e){return processString("speech",e)}function toSemantic(e){return processString("semantic",e)}function toJson(e){return processString("json",e)}function toDescription(e){return processString("description",e)}function toEnriched(e){return processString("enriched",e)}function number(e){return processString("number",e)}function ordinal(e){return processString("ordinal",e)}function system_numericOrdinal(e){return processString("numericOrdinal",e)}function vulgar(e){return processString("vulgar",e)}function processString(e,t){return processor_factory_process(e,t)}const file={};function processFile(e,t,n){switch(engine_Engine.getInstance().mode){case Mode.ASYNC:return processFileAsync(e,t,n);case Mode.SYNC:return processFileSync(e,t,n);default:throw new SREError(`Can process files in ${engine_Engine.getInstance().mode} mode`)}}function processFileSync(e,t,n){const r=processor_factory_output(e,inputFileSync_(t));if(n)try{system_external.f.fs.writeFileSync(n,r)}catch(e){throw new SREError("Can not write to file: "+n)}return r}function inputFileSync_(e){let t;try{t=system_external.f.fs.readFileSync(e,{encoding:"utf8"})}catch(t){throw new SREError("Can not open file: "+e)}return t}function processFileAsync(e,t,n){return system_awaiter(this,void 0,void 0,(function*(){const r=yield system_external.f.fs.promises.readFile(t,{encoding:"utf8"}),i=processor_factory_output(e,r);if(n)try{system_external.f.fs.promises.writeFile(n,i)}catch(e){throw new SREError("Can not write to file: "+n)}return i}))}function walk(e){return processor_factory_output("walker",e)}function move(e){return keypress("move",e)}function exit(e){const t=e||0;engine_EnginePromise.getall().then((()=>process.exit(t)))}file.toSpeech=function(e,t){return processFile("speech",e,t)},file.toSemantic=function(e,t){return processFile("semantic",e,t)},file.toJson=function(e,t){return processFile("json",e,t)},file.toDescription=function(e,t){return processFile("description",e,t)},file.toEnriched=function(e,t){return processFile("enriched",e,t)};const system_localePath=localePath;system_external.f.documentSupported?setupEngine({mode:Mode.HTTP}).then((()=>setupEngine({}))):setupEngine({mode:Mode.SYNC}).then((()=>setupEngine({mode:Mode.ASYNC})));var cli_awaiter=function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class Cli{constructor(){this.setup={mode:Mode.SYNC},this.processors=[],this.output=Cli.process.stdout,this.dp=new system_external.f.xmldom.DOMParser({onError:(e,t)=>{throw new SREError("XML DOM error!")}})}set(e,t,n){this.setup[e]=void 0===t||t}processor(e){this.processors.push(e)}loadLocales(){return cli_awaiter(this,void 0,void 0,(function*(){for(const e of variables.u.LOCALES.keys())yield setupEngine({locale:e})}))}enumerate(){return cli_awaiter(this,arguments,void 0,(function*(e=!1){const t=setupEngine(this.setup),n=DynamicCstr.DEFAULT_ORDER.slice(0,-1);return(e?this.loadLocales():t).then((()=>engine_EnginePromise.getall().then((()=>{const e=n.map((e=>e.length)),t=(t,n)=>{e[n]=Math.max.apply(null,Object.keys(t).map((e=>e.length)).concat(e[n]))},r=(e,t)=>e+new Array(t-e.length+1).join(" ");let i=SpeechRuleEngine.getInstance().enumerate();i=enumerate(i);const s=[];t(i,0);for(const[n,o]of Object.entries(i)){let a=!0;t(o,1);for(const[c,l]of Object.entries(o)){let o=!0;t(l,2);for(const[t,u]of Object.entries(l)){const l=Object.keys(u).sort();if("clearspeak"===t){let l=!0;const u=ClearspeakPreferences.getLocalePreferences(i)[n];if(!u)continue;for(const i of Object.values(u))s.push([r(a?n:"",e[0]),r(o?c:"",e[1]),r(l?t:"",e[2]),i.join(", ")]),a=!1,o=!1,l=!1}else s.push([r(a?n:"",e[0]),r(o?c:"",e[1]),r(t,e[2]),l.join(", ")]);a=!1,o=!1}}}let o=0;const a=n.map((t=>r(t,e[o++]))),c=Cli.commander.opts().pprint,l=e.map((e=>new Array(e+1).join(c?"-":"=")));c||(l[o-1]=l[o-1]+"========================"),s.unshift(l),s.unshift(a);let u=s.map((e=>e.join(" | ")));c&&(u=u.map((e=>`| ${e} |`)),u.unshift(`# Options SRE v${version}\n`)),console.info(u.join("\n"))}))))}))}execute(e){engine_EnginePromise.getall().then((()=>{this.runProcessors_(((e,t)=>this.output.write(processFile(e,t)+"\n")),e)}))}readline(){Cli.process.stdin.setEncoding("utf8");const e=system_external.f.extRequire("readline").createInterface({input:Cli.process.stdin,output:this.output});let t="";e.on("line",(n=>{t+=n,this.readExpression_(t)&&e.close()}).bind(this)),e.on("close",(()=>{this.runProcessors_(((t,n)=>{e.output.write(processor_factory_output(t,n)+"\n")}),t),engineReady().then((()=>debugger_Debugger.getInstance().exit((()=>exit(0)))))}).bind(this))}commandLine(){return cli_awaiter(this,void 0,void 0,(function*(){const e=Cli.commander,t=system_namespaceObject,n=(e=>(t,n)=>this.set(e,t,n)).bind(this),r=this.processor.bind(this);e.version(t.version).usage("[options] <file ...>").option("-i, --input [name]","Input file [name]. (Deprecated)").option("-o, --output [name]","Output file [name]. Defaults to stdout.").option("-d, --domain [name]","Speech rule set [name]. See --options for details.",n(Axis.DOMAIN),DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN]).option("-s, --style [name]","Speech style [name]. See --options for details.",n(Axis.STYLE),DynamicCstr.DEFAULT_VALUES[Axis.STYLE]).option("-c, --locale [code]","Locale [code].",n(Axis.LOCALE),DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]).option("-b, --modality [name]","Modality [name].",n(Axis.MODALITY),DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]).option("-k, --markup [name]","Generate speech output with markup tags.",n("markup"),"none").option("-e, --automark","Automatically set marks for external reference.",n("automark")).option("-L, --linebreaks","Linebreak marking in 2D output.",n("linebreaks")).option("-r, --rate [value]","Base rate [value] for tagged speech output.",n("rate"),"100").option("-p, --speech","Generate speech output (default).",(()=>r("speech"))).option("-a, --audit","Generate auditory descriptions (JSON format).",(()=>r("description"))).option("-j, --json","Generate JSON of semantic tree.",(()=>r("json"))).option("-x, --xml","Generate XML of semantic tree.",(()=>r("semantic"))).option("-m, --mathml","Generate enriched MathML.",(()=>r("enriched"))).option("-u, --rebuild","Rebuild semantic tree from enriched MathML.",(()=>r("rebuild"))).option("-t, --latex","Accepts LaTeX input for certain locale/modality combinations.",(()=>r("latex"))).option("-g, --generate <depth>","Include generated speech in enriched MathML (with -m option only).",n("speech"),"none").option("-w, --structure","Include structure attribute in enriched MathML (with -m option only).",n("structure")).option("-A, --aria","Include aria tree annotations MathML (with -m and -w option only).",n("aria")).option("-P, --pprint","Pretty print output whenever possible.",n("pprint")).option("-f, --rules [name]","Loads a local rule file [name].",n("rules")).option("-C, --subiso [name]","Supplementary country code (or similar) for the given locale.",n("subiso")).option("-N, --number","Translate number to word.",(()=>r("number"))).option("-O, --ordinal","Translate number to ordinal.",(()=>r("ordinal")),"ordinal").option("-S, --numeric","Translate number to numeric ordinal.",(()=>r("numericOrdinal"))).option("-F, --vulgar","Translate vulgar fraction to word. Provide vulgar fraction as slash seperated numbers.",(()=>r("vulgar"))).option("-v, --verbose","Verbose mode.").option("-l, --log [name]","Log file [name].").option("--opt","List engine setup options. Output as markdown with -P option.").option("--opt-all","List engine setup options for all available locales. Output as markdown with -P option.").on("option:opt",(()=>{this.enumerate().then((()=>exit(0)))})).on("option:opt-all",(()=>{this.enumerate(!0).then((()=>exit(0)))})).parse(Cli.process.argv),yield engineReady().then((()=>setupEngine(this.setup)));const i=Cli.commander.opts();i.output&&(this.output=system_external.f.fs.createWriteStream(i.output)),i.verbose&&(yield debugger_Debugger.getInstance().init(i.log)),i.input&&this.execute(i.input),Cli.commander.args.length?(Cli.commander.args.forEach(this.execute.bind(this)),engineReady().then((()=>debugger_Debugger.getInstance().exit((()=>exit(0)))))):this.readline()}))}runProcessors_(e,t){try{this.processors.length||this.processors.push("speech"),t&&this.processors.forEach((n=>e(n,t)))}catch(e){console.error(e.name+": "+e.message),debugger_Debugger.getInstance().exit((()=>Cli.process.exit(1)))}}readExpression_(e){try{const t=e.replace(/(&|#|;)/g,"");this.dp.parseFromString(t,"text/xml")}catch(e){return!1}return!0}}Cli.process=system_external.f.extRequire("process"),Cli.commander=system_external.f.documentSupported?null:system_external.f.extRequire("commander").program;const cli=Cli,mjs_variables=variables.u;return __webpack_exports__})()));
|