rapier-math 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +15 -5
  2. package/dist/accessible.css +6 -0
  3. package/dist/accessible.d.ts +10 -0
  4. package/dist/accessible.mjs +18 -0
  5. package/dist/classic.d.ts +8 -2
  6. package/dist/combined.d.ts +4 -0
  7. package/dist/combined.mjs +2 -0
  8. package/dist/index.d.ts +11 -0
  9. package/dist/index.mjs +6 -2980
  10. package/dist/integration.d.ts +3 -1
  11. package/dist/integration.mjs +13 -19
  12. package/dist/markdown-it.mjs +7 -4
  13. package/dist/mathml.d.ts +5 -0
  14. package/dist/mathml.mjs +3 -0
  15. package/dist/rapier-math.js +674 -173
  16. package/dist/rehype.mjs +13 -3
  17. package/docs/api.md +42 -4
  18. package/docs/math-components.json +6 -5
  19. package/docs/math-resources.json +150 -54
  20. package/docs/semantics.md +228 -0
  21. package/examples/README.md +10 -0
  22. package/examples/accessible.html +27 -0
  23. package/examples/accessible.mjs +42 -0
  24. package/examples/semantic.mjs +11 -0
  25. package/package.json +16 -2
  26. package/src/math/api.js +16 -55
  27. package/src/math/browser.js +4 -0
  28. package/src/math/classic.js +7 -0
  29. package/src/math/combined.js +13 -0
  30. package/src/math/fallbacks.js +5 -0
  31. package/src/math/font.js +3 -0
  32. package/src/math/layout.js +56 -53
  33. package/src/math/mathml.js +408 -0
  34. package/src/math/package-build.mjs +24 -11
  35. package/src/math/package-layout.mjs +3 -0
  36. package/src/math/package-readme.mjs +14 -4
  37. package/src/math/parser.js +36 -20
  38. package/src/math/responsive.js +4 -0
  39. package/src/math/semantic-api.js +12 -0
  40. package/src/math/source.js +67 -0
  41. package/src/math/symbols.js +6 -3
  42. package/src/math/variants.js +41 -0
  43. package/src/tools/build-math.mjs +18 -10
  44. package/tests/adoption.mjs +34 -0
  45. package/tests/check.mjs +13 -5
  46. package/tests/semantics.mjs +340 -0
  47. package/tests/verify.mjs +3 -3
@@ -591,7 +591,7 @@ varGamma=Γ varDelta=Δ varTheta=Θ varLambda=Λ varXi=Ξ varPi=Π varSigma=Σ v
591
591
  aleph=ℵ beth=ℶ gimel=ℷ daleth=ℸ ell=ℓ hbar=ℏ hslash=ℏ imath=𝚤 jmath=𝚥
592
592
  Re=ℜ Im=ℑ wp=℘ partial=∂ nabla=∇ infty=∞ emptyset=∅ varnothing=∅ complement=∁
593
593
  top=⊤ bot=⊥ forall=∀ exists=∃ nexists=∄ neg/lnot=¬ angle=∠ measuredangle=∡ sphericalangle=∢
594
- triangle=△ blacktriangle=▴ triangledown=▽ blacktriangledown=▾ square/Box=□ blacksquare=■ Diamond=◇ blacklozenge=◆ lozenge=◊
594
+ triangle/vartriangle=△ blacktriangle=▴ triangledown=▽ blacktriangledown=▾ square/Box=□ blacksquare=■ Diamond=◇ blacklozenge=◆ lozenge=◊
595
595
  clubsuit=♣ diamondsuit=♢ heartsuit=♡ spadesuit=♠ checkmark=✓ maltese=✠ yen=¥ pounds=£ euro=€
596
596
  S=§ P=¶ copyright=© circledR=® circledS=Ⓢ mho=℧ Finv=Ⅎ Game=⅁ eth=ð
597
597
  prime=′ backprime=‵ doubleprime=″ tripleprime=‴ degree=° flat=♭ natural=♮ sharp=♯
@@ -656,8 +656,8 @@ intclockwise=∱ varointclockwise=∲ ointctrclockwise=∳ sumint=⨋
656
656
  `, {large: true, limits: 'never', variant: 'roman'});
657
657
  MATH_SYMBOLS.intop = Object.freeze({...MATH_SYMBOLS.intop, limits: 'display'});
658
658
  MATH_SYMBOLS.smallint = Object.freeze({...MATH_SYMBOLS.smallint, large: false});
659
- mathSymbolGroup('open', 'langle=⟨ lbrace={ lgroup=⟮ lbrack=[ lfloor=⌊ lceil=⌈ lvert=| lVert=‖ lmoustache=⎰', {variant: 'roman'});
660
- mathSymbolGroup('close', 'rangle=⟩ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱', {variant: 'roman'});
659
+ mathSymbolGroup('open', 'langle=⟨ lbrace={ lgroup=⟮ lbrack=[ lfloor=⌊ lceil=⌈ lvert=| lVert=‖ lmoustache=⎰ llbracket=⟦ ulcorner=⌜ llcorner=⌞', {variant: 'roman'});
660
+ mathSymbolGroup('close', 'rangle=⟩ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱ rrbracket=⟧ urcorner=⌝ lrcorner=⌟', {variant: 'roman'});
661
661
  mathSymbolGroup('ord', 'vert=| Vert=‖ backslash=∖ slash=/', {variant: 'roman'});
662
662
  mathSymbolGroup('inner', 'dotsc=… cdots=⋯ dotsb=⋯ dotsm=⋯ dotsi=⋯ dotso=… ddots=⋱ mathellipsis=…', {variant: 'roman'});
663
663
  mathSymbolGroup('ord', 'vdots=⋮', {variant: 'roman'});
@@ -716,7 +716,7 @@ function mathTexTokens(source, offset = 0) {
716
716
  }
717
717
 
718
718
  const MATH_TEX_VARIANTS = Object.freeze({
719
- mathrm: 'roman', mathnormal: 'normal', mathit: 'italic', mathbf: 'bold', boldsymbol: 'bold-italic', bm: 'bold-italic',
719
+ mathrm: 'roman', mathnormal: 'normal', mathit: 'italic', mathbf: 'bold', boldsymbol: 'bold-italic', bm: 'bold-italic', pmb: 'bold-italic',
720
720
  mathbb: 'double-struck', mathbbm: 'double-struck', mathbbmss: 'double-struck', mathbbmtt: 'double-struck', mathds: 'double-struck',
721
721
  Bbb: 'double-struck', mathcal: 'script', mathscr: 'script', mathfrak: 'fraktur', frak: 'fraktur',
722
722
  mathsf: 'sans-serif', mathss: 'sans-serif', mathtt: 'monospace', mathbfit: 'bold-italic',
@@ -785,9 +785,10 @@ class MathTexParser {
785
785
  this.reserveParts(1);
786
786
  return {type, ...fields};
787
787
  }
788
- reserveParts(count, token = this.rawPeek()) {
788
+ reserveParts(count, token) {
789
+ // Peeking only on refusal: a skipping peek here would consume the spaces that \ce reads.
789
790
  if (!Number.isSafeInteger(count) || count < 0 || this.budget.nodes + count > 50000)
790
- this.error('resource-limit', 'This formula has too many parts to render safely.', token);
791
+ this.error('resource-limit', 'This formula has too many parts to render safely.', token || this.rawPeek());
791
792
  this.budget.nodes += count;
792
793
  }
793
794
  row(children) { return this.node('row', {children: children.filter(Boolean)}); }
@@ -847,7 +848,7 @@ class MathTexParser {
847
848
  for (;;) {
848
849
  const token = this.peek();
849
850
  if (token.kind === 'eof' || stop(token)) break;
850
- if (token.kind === 'command' && (MATH_TEX_DECLARATIONS[token.value] || token.value === 'color')) {
851
+ if (token.kind === 'command' && (Object.hasOwn(MATH_TEX_DECLARATIONS, token.value) || token.value === 'color')) {
851
852
  this.take();
852
853
  const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
853
854
  children.push(this.node('style', {...fields, body: this.nested(() => this.parseRow(stop, allowFraction))}));
@@ -880,7 +881,9 @@ class MathTexParser {
880
881
  const atom = this.parseAtom();
881
882
  if (atom) children.push(this.readScripts(atom));
882
883
  }
883
- return this.row(children);
884
+ // An equation tag follows its equation wherever \tag was written.
885
+ const tags = children.filter(child => child?.semanticRole === 'tag');
886
+ return this.row(tags.length ? [...children.filter(child => child?.semanticRole !== 'tag'), ...tags] : children);
884
887
  }
885
888
  readScripts(base) {
886
889
  let result = base;
@@ -896,8 +899,11 @@ class MathTexParser {
896
899
  if (result.type !== 'scripts') result = this.node('scripts', {base: result, limits: result.limits});
897
900
  const key = token.value === '_' ? 'sub' : 'sup';
898
901
  if (token.value === "'") {
899
- const primes = [this.node('glyph', {value: '′', class: 'ord', variant: 'roman'})];
900
- while (this.is("'")) { this.take(); primes.push(this.node('glyph', {value: '′', class: 'ord', variant: 'roman'})); }
902
+ // Runs of primes use the font's joined double, triple and quadruple prime glyphs.
903
+ let count = 1;
904
+ while (this.is("'")) { this.take(); count++; }
905
+ const primes = [];
906
+ for (; count > 0; count -= 4) primes.push(this.node('glyph', {value: '′″‴⁗'[Math.min(count, 4) - 1], class: 'ord', variant: 'roman'}));
901
907
  if (this.is('^')) { this.take(); primes.push(this.argument()); }
902
908
  if (result.sup) this.error('duplicate-script', 'A base cannot have two superscripts.', token);
903
909
  result.sup = this.row(primes);
@@ -998,7 +1004,7 @@ class MathTexParser {
998
1004
  if (token.kind === 'command') {
999
1005
  if (token.value === '{' || token.value === '}') return token.value;
1000
1006
  if (token.value === '|') return '‖';
1001
- const symbol = MATH_SYMBOLS[token.value];
1007
+ const symbol = Object.hasOwn(MATH_SYMBOLS, token.value) ? MATH_SYMBOLS[token.value] : null;
1002
1008
  if (symbol && (['open', 'close'].includes(symbol.class) || /^(vert|Vert|backslash|slash|[uUdD].*arrow)$/.test(token.value))) return symbol.value;
1003
1009
  }
1004
1010
  if (token.kind === 'char' && '.()[]{}|/<>‖⌈⌉⌊⌋⟨⟩↑↓↕⇑⇓⇕'.includes(token.value))
@@ -1012,7 +1018,7 @@ class MathTexParser {
1012
1018
  if (Object.hasOwn(MATH_TEX_LONG_ARROWS, name)) return this.node('style', {class: 'rel', body: this.row([this.node('space', {width: 5 / 18}), this.node('glyph', MATH_SYMBOLS[MATH_TEX_LONG_ARROWS[name]]), this.node('space', {width: 5 / 18})])});
1013
1019
  // amsmath \dots: centred dots before a binary operator, a relation or an integral, low dots otherwise.
1014
1020
  if (name === 'dots') {
1015
- const next = this.rawPeek(), after = next.kind === 'command' ? MATH_SYMBOLS[next.value] : null;
1021
+ const next = this.rawPeek(), after = next.kind === 'command' && Object.hasOwn(MATH_SYMBOLS, next.value) ? MATH_SYMBOLS[next.value] : null;
1016
1022
  const centred = next.kind === 'char' ? '+-=<>*:'.includes(next.value) : !!after && (['bin', 'rel'].includes(after.class) || /^(?:int|iint|iiint|oint)$/.test(next.value));
1017
1023
  if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
1018
1024
  }
@@ -1078,7 +1084,7 @@ class MathTexParser {
1078
1084
  if (name === 'operatorname') {
1079
1085
  const starred = this.is('*'); if (starred) this.take();
1080
1086
  const body = this.subparse(this.rawArgument(), true, 'roman');
1081
- return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never'});
1087
+ return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
1082
1088
  }
1083
1089
  if (/^math(ord|op|bin|rel|open|close|punct|inner)$/.test(name)) return this.node('style', {body: this.argument(), class: name.slice(4), ...(name === 'mathop' ? {limits: 'display'} : {})});
1084
1090
  if (name === 'overset' || name === 'underset' || name === 'stackrel' || name === 'stackbin') {
@@ -1130,7 +1136,7 @@ class MathTexParser {
1130
1136
  this.colors[colorName] = this.color(value, model, token); return null;
1131
1137
  }
1132
1138
  if (name === 'boxed' || name === 'fbox') return this.node('style', {body: name === 'fbox' ? this.subparse(this.rawArgument(), true, 'roman') : this.argument(), border: 'currentColor', padding: .25});
1133
- if (name === 'cancel' || name === 'bcancel' || name === 'xcancel') return this.node('accent', {base: this.argument(), value: name === 'bcancel' ? '╲' : name === 'xcancel' ? '╳' : '╱', position: 'over', overlay: true, stretch: true});
1139
+ if (name === 'cancel' || name === 'bcancel' || name === 'xcancel' || name === 'sout') return this.node('accent', {base: this.argument(), value: name === 'bcancel' ? '╲' : name === 'xcancel' ? '╳' : name === 'sout' ? '─' : '╱', position: 'over', overlay: true, stretch: true});
1134
1140
  if (name === 'cancelto') { const over = this.argument(); return this.node('overunder', {base: this.node('accent', {base: this.argument(), value: '↗', position: 'over', overlay: true, stretch: true}), over}); }
1135
1141
  if (['newcommand', 'renewcommand', 'providecommand', 'def', 'gdef', 'DeclareMathOperator', 'let'].includes(name)) { this.define(name, token); return null; }
1136
1142
  if (name === 'require') {
@@ -1151,14 +1157,14 @@ class MathTexParser {
1151
1157
  if (name === 'tag') {
1152
1158
  const starred = this.is('*'); if (starred) this.take();
1153
1159
  const body = this.subparse(this.rawArgument(), true);
1154
- return this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]);
1160
+ return {...this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]), semanticRole: 'tag'};
1155
1161
  }
1156
1162
  if (name === 'mod' || name === 'bmod') return this.row([this.node('space', {width: name === 'bmod' ? 5 / 18 : 1}), this.node('text', {value: 'mod', variant: 'roman', class: name === 'bmod' ? 'bin' : 'op'}), this.node('space', {width: name === 'bmod' ? 5 / 18 : 1 / 3})]);
1157
1163
  if (name === 'pmod' || name === 'pod') return this.row([this.node('space', {width: 1}), this.node('fence', {left: '(', right: ')', body: this.row([...(name === 'pmod' ? [this.node('text', {value: 'mod', variant: 'roman'}), this.node('space', {width: 1 / 3})] : []), this.argument()])})]);
1158
1164
  if (name === 'bmod') return this.node('text', {value: 'mod', variant: 'roman', class: 'bin'});
1159
- if (name === 'ce') return this.chemistry(this.rawArgument());
1160
- if (name === 'pu') return this.units(this.rawArgument());
1161
- if (this.physicsCommand(name)) return this.physics(name, token);
1165
+ if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
1166
+ if (name === 'pu') return {...this.units(this.rawArgument()), semanticRole: 'units'};
1167
+ if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
1162
1168
  if (name === 'mmlToken') return this.mathmlToken(token);
1163
1169
  if (name === 'unicode' || name === 'char') return this.character(name, token);
1164
1170
  if (name === 'TeX' || name === 'LaTeX') return this.node('text', {value: name, variant: 'roman'});
@@ -1383,7 +1389,7 @@ class MathTexParser {
1383
1389
  if (!next || next.kind !== 'char' || !(next.value === '#' || (/^[1-9]$/.test(next.value) && Number(next.value) <= params.length)))
1384
1390
  this.error('invalid-macro', 'A replacement refers to a missing macro parameter.', body[i - 1]);
1385
1391
  }
1386
- const existing = this.macro(macroName) || MATH_SYMBOLS[macroName] || MATH_TEX_VARIANTS[macroName] || MATH_NAMED_OPERATORS.has(macroName) || MATH_LIMIT_OPERATORS.has(macroName);
1392
+ const existing = this.macro(macroName) || Object.hasOwn(MATH_SYMBOLS, macroName) || Object.hasOwn(MATH_TEX_VARIANTS, macroName) || MATH_NAMED_OPERATORS.has(macroName) || MATH_LIMIT_OPERATORS.has(macroName);
1387
1393
  if (name === 'providecommand' && existing) return;
1388
1394
  if (name === 'newcommand' && existing) this.error('duplicate-macro', '\\' + macroName + ' is already defined.', token);
1389
1395
  this.scopes[name === 'gdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
@@ -1516,7 +1522,7 @@ class MathTexParser {
1516
1522
  if ([...letters].length !== 1) this.error('invalid-accent', 'A text accent needs one character.', token);
1517
1523
  value += (letters + marks[name]).normalize('NFC'); continue;
1518
1524
  }
1519
- if (MATH_SYMBOLS[name] && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
1525
+ if (Object.hasOwn(MATH_SYMBOLS, name) && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
1520
1526
  flush();
1521
1527
  const body = this.command(token);
1522
1528
  if (body) children.push(body);
@@ -1604,7 +1610,13 @@ class MathTexParser {
1604
1610
  const next = this.peek(false);
1605
1611
  if (next.kind === 'eof' || stop(next)) break;
1606
1612
  const token = this.take(false);
1607
- if (token.kind === 'space') { spaced = true; subAllowed = false; moleculeParts = 0; children.push(this.node('space', {width: 3 / 18})); continue; }
1613
+ if (token.kind === 'space') {
1614
+ spaced = true; subAllowed = false; moleculeParts = 0;
1615
+ // An operator or arrow already carries its own spacing; a separating space adds none beside it.
1616
+ const after = this.rawPeek(false), before = children.at(-1)?.class;
1617
+ if (before !== 'bin' && before !== 'rel' && !(after.kind === 'char' && /^[+<=-]$/.test(after.value))) children.push(this.node('space', {width: 3 / 18}));
1618
+ continue;
1619
+ }
1608
1620
  if (token.kind === 'command') {
1609
1621
  if (token.value === 'bond') {
1610
1622
  const value = this.plainArgument(), bonds = {'-': '−', '=': '=', '#': '≡', '~': '∼', '->': '→', '<-': '←', '...': '⋯'};
@@ -1660,7 +1672,8 @@ class MathTexParser {
1660
1672
  while (this.rawPeek(false).kind === 'char' && /^[<=>-]$/.test(this.rawPeek(false).value) && arrow.length < 5) arrow += this.rawTake(false).value;
1661
1673
  const arrows = {'->': '→', '<-': '←', '<->': '↔', '<=>': '⇌', '=>': '⇒', '<=': '⇐', '<<=>': '⇋', '<=>>': '⇌'};
1662
1674
  if (arrows[arrow]) {
1663
- const over = this.optionalRaw(), under = this.optionalRaw();
1675
+ // Only an adjacent bracket labels the arrow; a peek that skips spaces would drop the next one.
1676
+ const over = this.rawPeek(false).value === '[' ? this.optionalRaw() : null, under = over && this.rawPeek(false).value === '[' ? this.optionalRaw() : null;
1664
1677
  const base = this.literal(arrows[arrow], {class: 'rel', variant: 'roman', stretch: true});
1665
1678
  children.push(over || under ? this.node('overunder', {base, ...(over ? {over: this.chemistry(over)} : {}), ...(under ? {under: this.chemistry(under)} : {}), class: 'rel'}) : base);
1666
1679
  spaced = true; subAllowed = false; moleculeParts = 0; continue;
@@ -1707,7 +1720,7 @@ class MathTexParser {
1707
1720
  if (!match || !variants.has(match[1])) this.error('unsupported-attribute', 'Only a mathematical font variant is supported on a token.', token);
1708
1721
  variant = match[1] === 'normal' ? 'roman' : match[1] === 'bold-sans-serif' ? 'sans-serif-bold' : match[1];
1709
1722
  }
1710
- return this.node('style', {variant, body: kind === 'mtext' ? this.node('text', {value: text, variant}) : this.row([...text].map(value => this.literal(value, {variant})))});
1723
+ return this.node('style', {variant, tokenKind: kind, tokenText: text, body: kind === 'mtext' ? this.node('text', {value: text, variant}) : this.row([...text].map(value => this.literal(value, {variant})))});
1711
1724
  }
1712
1725
  character(name, token) {
1713
1726
  let raw;
@@ -1736,48 +1749,72 @@ function parseMathTex(source) {
1736
1749
  }
1737
1750
 
1738
1751
  // SPDX-License-Identifier: MIT
1739
- // Boxes use ems, a baseline at y=0 and a downward SVG axis. Font outlines stay in font units.
1740
- const mathNumber = n => {
1741
- if (!Number.isFinite(n)) throw new Error('Math geometry is not finite');
1742
- const scaled = n * 1e6;
1743
- return String((Number.isFinite(scaled) ? Math.round(scaled) / 1e6 : n) || 0);
1744
- };
1745
- const mathEscape = s => String(s).replace(/[&<>"'\t\n\r]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','\t':'&#9;','\n':'&#10;','\r':'&#13;'}[c]));
1746
- const mathFontRatio = (MATH_FONT.textXHeight / MATH_FONT.textUnits) / (MATH_FONT.xHeight / MATH_FONT.units);
1747
- function mathScale(c) {
1748
- if (!c.level) return c.size;
1749
- const scale = MATH_FONT.constants[c.level === 1 ? 'ScriptPercentScaleDown' : 'ScriptScriptPercentScaleDown'] / 100;
1750
- return c.size * (c.screen ? Math.max(scale, Math.min(1, (c.level === 1 ? 12 : 10) / c.screen.fontSize)) : scale);
1752
+ // Source custody and bounded diagnostics shared by SVG and MathML.
1753
+ function mathSourceUTF16(source) {
1754
+ // Four ASCII hex digits retain each original UTF-16 code unit across XML/HTML hosts.
1755
+ const encoded=[],parts=[];
1756
+ for(let i=0;i<source.length;i++) {
1757
+ parts.push(source.charCodeAt(i).toString(16).padStart(4,'0'));
1758
+ if(parts.length===1024) {encoded.push(parts.join(''));parts.length=0;}
1759
+ }
1760
+ encoded.push(parts.join(''));
1761
+ return encoded.join('');
1751
1762
  }
1752
1763
 
1753
- function mathScreenStroke(c, scale) {
1754
- if (!c.screen) return 0;
1755
- const {fontSize, pixelRatio, dark} = c.screen, size = fontSize * (scale ?? mathScale(c));
1756
- if (!(size > 0)) return 0;
1757
- const small = Math.max(0, Math.min(1, (32 - size) / 16));
1758
- const hairline = MATH_FONT.constants.FractionRuleThickness / MATH_FONT.units * size;
1759
- return small * ((dark ? .18 : .09) / Math.sqrt(pixelRatio) + Math.max(0, (dark ? 1 : .85) / pixelRatio - hairline) * .35) / fontSize;
1764
+ function mathSourceAlternative(source) {
1765
+ const alternatives=[],parts=[];
1766
+ let first=-1,kept=0,hasCR=false;
1767
+ for(let i=0;i<source.length;i++) {
1768
+ const code=source.charCodeAt(i);
1769
+ if(code===13)hasCR=true;
1770
+ if(code>=0xd800 && code<=0xdbff && i+1<source.length) {
1771
+ const next=source.charCodeAt(i+1);
1772
+ if(next>=0xdc00 && next<=0xdfff) {i++;continue;}
1773
+ }
1774
+ if((code>=0x20 && code<=0xd7ff) || (code>=0xe000 && code<=0xfffd) || code===9 || code===10 || code===13)continue;
1775
+ if(first<0)first=i;
1776
+ if(i>kept)parts.push(source.slice(kept,i));
1777
+ parts.push('\\u'+code.toString(16).toUpperCase().padStart(4,'0'));kept=i+1;
1778
+ // Flatten small batches instead of retaining one rope node per bad code unit.
1779
+ if(parts.length>=1024) {alternatives.push(parts.join(''));parts.length=0;}
1780
+ }
1781
+ if(first<0)return {alternative:source,...(hasCR?{utf16:mathSourceUTF16(source)}:{})};
1782
+ parts.push(source.slice(kept));alternatives.push(parts.join(''));
1783
+ return {alternative:alternatives.join(''),utf16:mathSourceUTF16(source),error:{code:'invalid-source-character',offset:first,
1784
+ message:'A source character cannot be embedded in XML. The text alternative shows Unicode escapes; the UTF-16 carrier keeps the original source.'}};
1760
1785
  }
1761
- const mathConstant = (name, c, fallback) => (MATH_FONT.constants[name] ?? fallback * MATH_FONT.units) / MATH_FONT.units * mathScale(c);
1762
- const mathScriptStyle = (c, cramped = c.cramped) => ({...c, level: Math.min(2, c.level + 1), display: false, cramped});
1763
- const mathScreenRelayout = (n,c,ratio) => mathLayout(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()});
1764
- const mathBox = (w = 0, h = 0, d = 0, svg = '', extra = {}) => ({w, h, d, svg, left: 0, right: w, inkTop: -h, inkBottom: d, class: 'ord', ...extra});
1765
- const mathMove = (b, x, y) => b.svg ? '<g transform="translate(' + mathNumber(x) + ' ' + mathNumber(y) + ')">' + b.svg + '</g>' : '';
1766
1786
 
1767
- function mathCompose(items, width, extra = {}) {
1768
- let h = 0, d = 0, left = 0, right = width, inkTop=Infinity, inkBottom=-Infinity, svg = '';
1769
- for (const [b, x, y] of items) {
1770
- if(svg.length+b.svg.length+128>8*1024*1024)throw Object.assign(new Error('Mathematical composition exceeds the SVG budget'),{code:'resource-limit'});
1771
- h = Math.max(h, b.h - y); d = Math.max(d, b.d + y);
1772
- left = Math.min(left, x + b.left); right = Math.max(right, x + b.right);
1773
- if(b.svg) {inkTop=Math.min(inkTop,b.inkTop+y);inkBottom=Math.max(inkBottom,b.inkBottom+y);}
1774
- svg += mathMove(b, x, y);
1775
- }
1776
- const single=items.length===1?items[0]:null,b=single?.[0];
1777
- const glyph=b?.glyph===undefined?{}:{glyph:b.glyph,unitScale:b.unitScale,glyphX:(b.glyphX || 0)+single[1],glyphY:(b.glyphY || 0)+single[2],extended:b.extended,scriptBase:b.scriptBase,stroke:b.stroke};
1778
- return mathBox(width, h, d, svg, {left, right, inkTop:Number.isFinite(inkTop)?inkTop:-h, inkBottom:Number.isFinite(inkBottom)?inkBottom:d,...glyph,...extra});
1787
+ function mathAdmitSource(text) {
1788
+ // Reject before scanning, escaping, parsing or constructing a source carrier.
1789
+ return text.length>1000000?{alternative:'Formula source omitted: source limit exceeded.',error:{
1790
+ code:'resource-limit',offset:0,sourceOmitted:true,
1791
+ message:'This formula is too long to render safely. Its source was not embedded; retain the original input.'
1792
+ }}:mathSourceAlternative(text);
1779
1793
  }
1780
1794
 
1795
+ function mathDiagnostic(cause) {
1796
+ const message=String(cause?.message ?? cause),code=cause?.code,rawCommand=cause?.command;
1797
+ const error={code:typeof code==='string'?code:'invalid-tex',message:message.length>1024?message.slice(0,1024).replace(/[\ud800-\udbff]$/,'')+'…':message,
1798
+ offset:Number.isFinite(cause?.offset)?cause.offset:0};
1799
+ if(message.length>1024 || cause?.messageTruncated)error.messageTruncated=true;
1800
+ if(cause?.sourceOmitted)error.sourceOmitted=true;
1801
+ if(rawCommand!==undefined) {
1802
+ const command=String(rawCommand);
1803
+ error.command=command.slice(0,128).replace(/[\ud800-\udbff]$/,'');
1804
+ if(command.length>128 || cause.commandTruncated)error.commandTruncated=true;
1805
+ }
1806
+ return error;
1807
+ }
1808
+
1809
+ function mathPrepare(source) {
1810
+ const text = String(source ?? ''), safe = mathAdmitSource(text);
1811
+ let tree, error = safe.error;
1812
+ if (!error) try { tree = parseMathTex(text); } catch (cause) { error = mathDiagnostic(cause); }
1813
+ return {text, safe, tree, error};
1814
+ }
1815
+
1816
+ // SPDX-License-Identifier: MIT
1817
+ // Unicode mathematical alphabets shared by SVG and MathML. No font lookup.
1781
1818
  const MATH_STYLED_RANGES = {
1782
1819
  italic: [0x1d434, 0x1d44e, null], bold: [0x1d400, 0x1d41a, 0x1d7ce],
1783
1820
  'bold-italic': [0x1d468, 0x1d482, null], script: [0x1d49c, 0x1d4b6, null],
@@ -1815,6 +1852,49 @@ function mathStyledCodePoint(cp, variant) {
1815
1852
  return cp;
1816
1853
  }
1817
1854
 
1855
+ // SPDX-License-Identifier: MIT
1856
+ // Boxes use ems, a baseline at y=0 and a downward SVG axis. Font outlines stay in font units.
1857
+ const mathNumber = n => {
1858
+ if (!Number.isFinite(n)) throw new Error('Math geometry is not finite');
1859
+ const scaled = n * 1e6;
1860
+ return String((Number.isFinite(scaled) ? Math.round(scaled) / 1e6 : n) || 0);
1861
+ };
1862
+ const mathEscape = s => String(s).replace(/[&<>"'\t\n\r]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','\t':'&#9;','\n':'&#10;','\r':'&#13;'}[c]));
1863
+ const mathFontRatio = (MATH_FONT.textXHeight / MATH_FONT.textUnits) / (MATH_FONT.xHeight / MATH_FONT.units);
1864
+ function mathScale(c) {
1865
+ if (!c.level) return c.size;
1866
+ const scale = MATH_FONT.constants[c.level === 1 ? 'ScriptPercentScaleDown' : 'ScriptScriptPercentScaleDown'] / 100;
1867
+ return c.size * (c.screen ? Math.max(scale, Math.min(1, (c.level === 1 ? 12 : 10) / c.screen.fontSize)) : scale);
1868
+ }
1869
+
1870
+ function mathScreenStroke(c, scale) {
1871
+ if (!c.screen) return 0;
1872
+ const {fontSize, pixelRatio, dark} = c.screen, size = fontSize * (scale ?? mathScale(c));
1873
+ if (!(size > 0)) return 0;
1874
+ const small = Math.max(0, Math.min(1, (32 - size) / 16));
1875
+ const hairline = MATH_FONT.constants.FractionRuleThickness / MATH_FONT.units * size;
1876
+ return small * ((dark ? .18 : .09) / Math.sqrt(pixelRatio) + Math.max(0, (dark ? 1 : .85) / pixelRatio - hairline) * .35) / fontSize;
1877
+ }
1878
+ const mathConstant = (name, c, fallback) => (MATH_FONT.constants[name] ?? fallback * MATH_FONT.units) / MATH_FONT.units * mathScale(c);
1879
+ const mathScriptStyle = (c, cramped = c.cramped) => ({...c, level: Math.min(2, c.level + 1), display: false, cramped});
1880
+ const mathScreenRelayout = (n,c,ratio) => mathLayout(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()});
1881
+ const mathBox = (w = 0, h = 0, d = 0, svg = '', extra = {}) => ({w, h, d, svg, left: 0, right: w, inkTop: -h, inkBottom: d, class: 'ord', ...extra});
1882
+ const mathMove = (b, x, y) => b.svg ? '<g transform="translate(' + mathNumber(x) + ' ' + mathNumber(y) + ')">' + b.svg + '</g>' : '';
1883
+
1884
+ function mathCompose(items, width, extra = {}) {
1885
+ let h = 0, d = 0, left = 0, right = width, inkTop=Infinity, inkBottom=-Infinity, svg = '';
1886
+ for (const [b, x, y] of items) {
1887
+ if(svg.length+b.svg.length+128>8*1024*1024)throw Object.assign(new Error('Mathematical composition exceeds the SVG budget'),{code:'resource-limit'});
1888
+ h = Math.max(h, b.h - y); d = Math.max(d, b.d + y);
1889
+ left = Math.min(left, x + b.left); right = Math.max(right, x + b.right);
1890
+ if(b.svg) {inkTop=Math.min(inkTop,b.inkTop+y);inkBottom=Math.max(inkBottom,b.inkBottom+y);}
1891
+ svg += mathMove(b, x, y);
1892
+ }
1893
+ const single=items.length===1?items[0]:null,b=single?.[0];
1894
+ const glyph=b?.glyph===undefined?{}:{glyph:b.glyph,unitScale:b.unitScale,glyphX:(b.glyphX || 0)+single[1],glyphY:(b.glyphY || 0)+single[2],extended:b.extended,scriptBase:b.scriptBase,stroke:b.stroke};
1895
+ return mathBox(width, h, d, svg, {left, right, inkTop:Number.isFinite(inkTop)?inkTop:-h, inkBottom:Number.isFinite(inkBottom)?inkBottom:d,...glyph,...extra});
1896
+ }
1897
+
1818
1898
  function mathGlyphIndex(id, c, extra = {}) {
1819
1899
  if(c.dotless)id=MATH_FONT.dotless?.[id] ?? id;
1820
1900
  const alternates=MATH_FONT.scriptAlternates[id],scale=mathScale(c);
@@ -1844,20 +1924,41 @@ function mathGlyph(value, c, extra = {}) {
1844
1924
  if (id === undefined) {
1845
1925
  const composed = mathFallbackGlyph(value, c, extra);
1846
1926
  if (composed) return composed;
1927
+ if (MATH_HOST_TEXT.test(value)) return mathHostText(value, c, {...extra, host: true});
1847
1928
  const e = new Error('Unsupported character U+' + cp.toString(16).toUpperCase());
1848
1929
  e.code = 'unsupported-glyph'; e.command = value; throw e;
1849
1930
  }
1850
1931
  return mathGlyphIndex(id, c, extra);
1851
1932
  }
1852
1933
 
1934
+ // Letters, digits, marks and symbols outside the embedded font (CJK, Cyrillic, emoji...) use the reader's
1935
+ // own serif font. Their advance is estimated, and textLength fits the drawn run to that box exactly.
1936
+ const MATH_HOST_TEXT = /^[\p{L}\p{N}\p{M}\p{S}\p{P}]+$/u;
1937
+ const MATH_WIDE_TEXT = /[\p{sc=Han}\p{sc=Hang}\p{sc=Hira}\p{sc=Kana}\p{Emoji_Presentation}\u3000-\u303f\uff01-\uff60]/u;
1938
+ function mathHostText(value, c, extra = {}) {
1939
+ const s = mathScale(c);
1940
+ let w = 0;
1941
+ for (const ch of value) if (!/\p{M}/u.test(ch)) w += (MATH_WIDE_TEXT.test(ch) ? 1 : /\p{Lu}/u.test(ch) ? 0.72 : 0.52) * s;
1942
+ const variant = c.variant || '';
1943
+ return mathBox(w, 0.8 * s, 0.2 * s, '<text font-family="' + (/sans/.test(variant) ? 'sans-serif' : variant === 'monospace' ? 'monospace' : 'serif') + '"' +
1944
+ (/bold/.test(variant) ? ' font-weight="bold"' : '') + (/italic/.test(variant) ? ' font-style="italic"' : '') +
1945
+ ' font-size="' + mathNumber(s) + '" textLength="' + mathNumber(w) +
1946
+ '" lengthAdjust="spacingAndGlyphs">' + mathEscape(value) + '</text>', {inkTop: -0.8 * s, inkBottom: 0.2 * s, ...extra});
1947
+ }
1948
+
1853
1949
  function mathText(value, c, extra = {}) {
1854
- const items = []; let x = 0;
1950
+ const items = [], text = {...c, variant: extra.variant || 'roman'}; let x = 0, run = '';
1951
+ const flush = () => { if (run) { const b = mathHostText(run, text); items.push([b,x,0]); x += b.w; run = ''; } };
1855
1952
  for (const ch of String(value)) {
1856
- if (/\s/u.test(ch)) { x += mathScale(c)*0.25; continue; }
1857
- const b = mathGlyph(ch, {...c, variant: extra.variant || 'roman'});
1858
- items.push([b,x,0]); x += b.w;
1859
- }
1860
- return mathCompose(items,x,{class:extra.class || 'ord',limits:extra.limits,...extra});
1953
+ if (/\s/u.test(ch)) { flush(); x += mathScale(c)*0.25; continue; }
1954
+ // A run of host-font characters stays one text element, keeping its shaping and joining.
1955
+ if (run && /\p{M}/u.test(ch)) { run += ch; continue; }
1956
+ const b = mathGlyph(ch, text);
1957
+ if (b.host) { run += ch; continue; }
1958
+ flush(); items.push([b,x,0]); x += b.w;
1959
+ }
1960
+ flush();
1961
+ return mathCompose(items,x,{...extra,class:extra.class || 'ord'});
1861
1962
  }
1862
1963
 
1863
1964
  function mathRule(w, thickness, y = 0) {
@@ -1940,12 +2041,17 @@ function mathStretch(value, target, c, horizontal = false) {
1940
2041
  const overlap=connections.length?Math.max(minOverlap,Math.min((full-wanted)/connections.length,...connections)):0,
1941
2042
  length=(full-overlap*connections.length)*unit;
1942
2043
  const items=[]; let pos=0, width=0;
1943
- for (let i=0;i<pieces.length;i++) {
2044
+ for (let i=0;i<pieces.length;) {
1944
2045
  const p=pieces[i], b=mathGlyphIndex(p[0],c), g=MATH_FONT.glyph(b.glyph);
1945
- if (horizontal) items.push([b,pos,0]);
1946
- else items.push([b,0,-pos+g[2]*unit]);
2046
+ let k=1; while(p[4] && pieces[i+k]===p)k++;
2047
+ // One extender drawn along its axis replaces k abutting copies, whose antialiased seams read as dashes.
2048
+ const span=(k*p[3]-(k-1)*overlap)*unit,f=span/(p[3]*unit);
2049
+ if (k===1) items.push(horizontal?[b,pos,0]:[b,0,-pos+g[2]*unit]);
2050
+ else if (horizontal) items.push([{...b,w:b.w*f,left:b.left*f,right:b.right*f,svg:'<g transform="scale('+mathNumber(f)+' 1)">'+b.svg+'</g>'},pos,0]);
2051
+ else items.push([{...b,h:pos+span,d:0,inkTop:-pos-span,inkBottom:-pos,
2052
+ svg:'<g transform="translate(0 '+mathNumber(-pos)+') scale(1 '+mathNumber(f)+') translate(0 '+mathNumber(g[2]*unit)+')">'+b.svg+'</g>'},0,0]);
1947
2053
  width=Math.max(width,b.w);
1948
- pos+=(p[3]-overlap)*unit;
2054
+ pos+=k*(p[3]-overlap)*unit; i+=k;
1949
2055
  }
1950
2056
  return mathCompose(items,horizontal?length:width,{italic:(a.italic || 0)*unit,
1951
2057
  ...(horizontal?{accent:length/2,stretchAxis:'horizontal'}:{h:length,d:0,extended:true})});
@@ -2074,13 +2180,14 @@ function mathScripts(n,c) {
2074
2180
  const items=[[b,0,0]]; let w=b.w;
2075
2181
  if (up) {
2076
2182
  const kern=Math.min(mathKern(base,0,rise-upDescent)+mathKern(up,3,-upDescent),mathKern(base,0,baseAscent)+mathKern(up,3,baseAscent-rise));
2077
- const nominal=b.w+(b.italic || 0)+kern;
2183
+ // A large operator's italic correction moves its subscript left, not its superscript right.
2184
+ const nominal=b.w+(b.large?0:b.italic || 0)+kern;
2078
2185
  const x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,up,-rise,nominal,c);
2079
2186
  items.push([up,x,-rise]);w=Math.max(w,x+up.w);
2080
2187
  }
2081
2188
  if (down) {
2082
2189
  const kern=Math.min(mathKern(base,2,downAscent-drop)+mathKern(down,1,downAscent),mathKern(base,2,-baseDescent)+mathKern(down,1,drop-baseDescent));
2083
- const nominal=b.w+kern;
2190
+ const nominal=b.w-(b.large?b.italic || 0:0)+kern;
2084
2191
  const x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,down,drop,nominal,c);
2085
2192
  items.push([down,x,drop]);w=Math.max(w,x+down.w);
2086
2193
  }
@@ -2102,13 +2209,15 @@ function mathFraction(n,c,width) {
2102
2209
  const min=mathConstant(display?'StackDisplayStyleGapMin':'StackGapMin',c,display?0.4:0.15),gap=rise+drop-top.d-bottom.h;
2103
2210
  if (gap<min) {rise+=(min-gap)/2;drop+=(min-gap)/2;}
2104
2211
  }
2105
- const pad=mathScale(c)*0.1,w=Math.max(top.w,bottom.w)+2*pad;
2212
+ // Null delimiter space pads only an unfenced fraction; a fence's own glyphs bound \binom.
2213
+ const pad=n.left || n.right?0:mathScale(c)*0.1,w=Math.max(top.w,bottom.w)+2*pad;
2106
2214
  const numeratorX=n.align==='l'?pad:n.align==='r'?w-pad-top.w:(w-top.w)/2;
2107
2215
  const items=[[top,numeratorX,-rise],[bottom,(w-bottom.w)/2,drop]];
2108
2216
  if (line) items.push([mathRule(w,line,-axis-line/2),0,0]);
2109
2217
  const b=mathCompose(items,w,{class:'inner',innerLines:top.lines || 1,fitted:!!top.fitted});
2110
2218
  if(width!==undefined && c.screen)b.refit=ratio=>mathFraction(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()},width);
2111
- if (n.left || n.right) return mathFenceBoxes(n.left || '',n.right || '',b,c);
2219
+ // TeX's generalized fractions fence at least its delim1 (display) or delim2 size.
2220
+ if (n.left || n.right) return mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.39:1.01);
2112
2221
  return b;
2113
2222
  }
2114
2223
 
@@ -2125,8 +2234,8 @@ function mathRoot(n,c) {
2125
2234
  const b=mathCompose(items,w);b.h+=extra;return b;
2126
2235
  }
2127
2236
 
2128
- function mathFenceBoxes(left,right,body,c,size) {
2129
- const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(body.h-axis,body.d+axis),target=size?size*mathScale(c):Math.max(1*mathScale(c),2*reach*0.901,2*reach-0.5*mathScale(c));
2237
+ function mathFenceBoxes(left,right,body,c,size,least=1) {
2238
+ const axis=mathConstant('AxisHeight',c,0.25),reach=Math.max(body.h-axis,body.d+axis),target=size?size*mathScale(c):Math.max(least*mathScale(c),2*reach*0.901,2*reach-0.5*mathScale(c));
2130
2239
  const a=mathDelimiter(left,target,c),b=mathDelimiter(right,target,c);
2131
2240
  return mathCompose([[a,0,0],[body,a.w,0],[b,a.w+body.w,0]],a.w+body.w+b.w,{class:'inner'});
2132
2241
  }
@@ -2140,7 +2249,7 @@ function mathAccent(n,c) {
2140
2249
  const w=Math.max(b.w,0.2*s),line=mathConstant('FractionRuleThickness',c,0.04);
2141
2250
  const rising='M0 '+mathNumber(b.d)+'L'+mathNumber(w)+' '+mathNumber(-b.h),
2142
2251
  falling='M0 '+mathNumber(-b.h)+'L'+mathNumber(w)+' '+mathNumber(b.d);
2143
- let path=n.value==='╲'?falling:n.value==='╳'?rising+falling:rising;
2252
+ let path=n.value==='╲'?falling:n.value==='╳'?rising+falling:n.value==='─'?'M0 '+mathNumber(-mathConstant('AxisHeight',c,0.25))+'H'+mathNumber(w):rising;
2144
2253
  if(n.value==='↗') {
2145
2254
  const tip=0.2*s;path+='M'+mathNumber(w-tip)+' '+mathNumber(-b.h)+'H'+mathNumber(w)+'v'+mathNumber(tip);
2146
2255
  }
@@ -2248,6 +2357,11 @@ function mathLayout(n,c) {
2248
2357
  case 'glyph': {
2249
2358
  if(n.delimiterSize || (n.delimiter && c.delimiterTarget))return {...mathDelimiter(n.value,n.delimiterSize?n.delimiterSize*mathScale(c):c.delimiterTarget,c),class:n.class || 'ord'};
2250
2359
  if(n.stretch)return {...mathStretch(n.value,c.stretchTarget || mathScale(c),c,true),class:n.class || 'rel',limits:n.limits,stretchAxis:'horizontal'};
2360
+ if(n.value==='…' || n.value==='⋯') {
2361
+ // TeX's \ldots and \cdots are three punctuation dots with punctuation spacing, wider than the font's ellipses.
2362
+ const dot=mathGlyph(n.value==='…'?'.':'⋅',c,{variant:'roman'}),step=dot.w+mathSpace('punct','punct',c);
2363
+ return mathCompose([[dot,0,0],[dot,step,0],[dot,2*step,0]],2*step+dot.w,{class:n.class || 'inner'});
2364
+ }
2251
2365
  let b=mathGlyph(n.value,c,{class:n.class || 'ord',variant:n.variant || (c.variant==='normal'?n.defaultVariant || 'normal':c.variant),large:n.large,limits:n.limits});
2252
2366
  if(n.large && c.display && !c.level) {
2253
2367
  const target=mathConstant('DisplayOperatorMinHeight',c,1.3),a=mathStretch(n.value,target,c);
@@ -2680,6 +2794,72 @@ function mathResponsiveLayout(n,c,width,natural=mathLayout(n,c)) {
2680
2794
  return mathFitBox(natural,width,c);
2681
2795
  }
2682
2796
 
2797
+ // SPDX-License-Identifier: MIT
2798
+ function mathSvg(box,source,error,utf16,options={}) {
2799
+ if(box.svg.length>8*1024*1024)throw Object.assign(new Error('This formula produces too much SVG to render safely.'),{code:'resource-limit'});
2800
+ const pad=0.025,left=Math.min(0,box.left)-pad,right=Math.max(box.w,box.right)+pad;
2801
+ const width=Math.max(0.05,right-left),height=Math.max(0.025,box.h+pad,-box.inkTop+pad),depth=Math.max(0.025,box.d+pad,box.inkBottom+pad);
2802
+ const viewBox=[left*1000,-height*1000,width*1000,(height+depth)*1000];
2803
+ const opacity=options.screen?.dark ? .94 : 1;
2804
+ if (![width,height,depth,left,...viewBox].every(Number.isFinite)) throw new Error('Mathematical dimensions are not finite');
2805
+ const escapedSource=mathEscape(source);
2806
+ // A group exposes authored links to accessibility APIs; an image would hide them.
2807
+ const svg='<svg xmlns="http://www.w3.org/2000/svg" role="'+(box.svg.includes('<a ')?'group':'img')+'" aria-label="'+escapedSource+'"'+
2808
+ ' data-rapier-math="'+(options.displayMode?'display':'inline')+'" data-math-lines="'+(box.lines || 1)+'"'+
2809
+ ' data-math-natural-width="'+mathNumber(options.naturalWidth ?? width)+'"'+
2810
+ (options.screen?' data-math-screen="'+mathNumber(options.screen.fontSize)+'|'+mathNumber(options.screen.pixelRatio)+'|'+options.screen.dark+'"':'')+
2811
+ (options.maxWidth?' data-math-max-width="'+mathNumber(options.maxWidth)+'"':'')+
2812
+ (utf16?' data-tex-utf16="'+utf16+'"':'')+
2813
+ (error?.sourceOmitted?' data-math-source-omitted="true"':'')+
2814
+ (error?' data-math-error="'+mathEscape(error.code)+'"':'')+' width="'+mathNumber(width)+'em" height="'+mathNumber(height+depth)+'em"'+
2815
+ ' viewBox="'+viewBox.map(mathNumber).join(' ')+'"'+
2816
+ ' style="font-size:'+mathNumber(mathFontRatio)+'em;max-width:100%;height:auto;vertical-align:-'+mathNumber(depth)+'em;'+
2817
+ 'fill-opacity:'+opacity+';stroke-opacity:'+opacity+'" fill="currentColor">'+
2818
+ '<title>'+escapedSource+'</title>'+(error?'<desc>'+mathEscape(error.message)+'</desc>':'')+
2819
+ '<g transform="scale(1000)">'+box.svg+'</g></svg>';
2820
+ if(svg.length>24*1024*1024)throw Object.assign(new Error('The complete formula markup exceeds its output budget.'),{code:'resource-limit'});
2821
+ return {svg,width,height,depth,lines:box.lines || 1,fitted:!!box.fitted,errors:error?[error]:[]};
2822
+ }
2823
+
2824
+ function mathRenderPrepared(prepared,options={}) {
2825
+ const {text,safe,tree,error:parseError}=prepared;
2826
+ const context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
2827
+ try {
2828
+ if(safe.error)throw safe.error;
2829
+ if(options?.screen!==undefined) {
2830
+ const {fontSize,pixelRatio,dark}=options.screen || {},scaled=Number.isFinite(fontSize)?fontSize*mathFontRatio:NaN;
2831
+ if(!Number.isFinite(fontSize) || fontSize<=0 || !Number.isFinite(pixelRatio) || pixelRatio<=0 ||
2832
+ typeof dark!=='boolean' || !Number.isFinite(scaled) || scaled<=0 || !Number.isFinite(scaled*pixelRatio) || scaled*pixelRatio<=0 ||
2833
+ !Number.isFinite(1/scaled) || !Number.isFinite(1/pixelRatio) || !Number.isFinite(1/(scaled*pixelRatio)))
2834
+ throw Object.assign(new Error('Screen font size, pixel ratio and device scale must be positive and finite; dark must be a boolean.'),{code:'invalid-screen'});
2835
+ context.screen={fontSize:scaled,pixelRatio,dark};
2836
+ }
2837
+ if(parseError)throw parseError;
2838
+ const natural=mathLayout(tree,context),limit=Number(options?.maxWidth);
2839
+ const maxWidth=Number.isFinite(limit) && limit>.1?limit:undefined;
2840
+ const box=maxWidth && mathInkWidth(natural)>maxWidth-.05?mathResponsiveLayout(tree,context,maxWidth-.05,natural):natural;
2841
+ return mathSvg(box,safe.alternative,undefined,safe.utf16,{displayMode:context.display,maxWidth,naturalWidth:mathInkWidth(natural)+.05,screen:context.screen});
2842
+ }
2843
+ catch (cause) {
2844
+ const error=mathDiagnostic(cause);
2845
+ // A diagnostic is visible, but remains distinct from a successfully typeset formula.
2846
+ // Diagnostics have an explicit bound. Exact input stays in the source alternative.
2847
+ const label=error.message.length>240?'This formula could not be rendered. The complete diagnostic is in its text description.':error.message.replace(/[^\x20-\x7e]/g,'?');
2848
+ const diagnostic={...context,variant:'roman',size:0.8,budget:{nodes:0,outlineBytes:0}};
2849
+ try {
2850
+ return mathSvg(mathText(label,diagnostic),safe.alternative,error,safe.utf16,{displayMode:context.display,screen:context.screen});
2851
+ } catch {
2852
+ diagnostic.screen=undefined;
2853
+ return mathSvg(mathText(label,diagnostic),safe.alternative,error,safe.utf16,{displayMode:context.display});
2854
+ }
2855
+ }
2856
+ }
2857
+
2858
+ function renderMath(source,options={}) {
2859
+ return mathRenderPrepared(mathPrepare(source),options);
2860
+ }
2861
+ function mathRenderToString(source,options) { return renderMath(source,options).svg; }
2862
+
2683
2863
  // SPDX-License-Identifier: MIT
2684
2864
  // The browser supplies the column and physical pixel grid; rendering remains synchronous and pure.
2685
2865
  const mathBrowserStates=new WeakMap(),mathBrowserDocuments=new WeakMap(),mathRuleOriginals=new WeakMap();
@@ -2869,112 +3049,433 @@ function mathObserve(root) {
2869
3049
  }
2870
3050
 
2871
3051
  // SPDX-License-Identifier: MIT
2872
- function mathSvg(box,source,error,utf16,options={}) {
2873
- if(box.svg.length>8*1024*1024)throw Object.assign(new Error('This formula produces too much SVG to render safely.'),{code:'resource-limit'});
2874
- const pad=0.025,left=Math.min(0,box.left)-pad,right=Math.max(box.w,box.right)+pad;
2875
- const width=Math.max(0.05,right-left),height=Math.max(0.025,box.h+pad,-box.inkTop+pad),depth=Math.max(0.025,box.d+pad,box.inkBottom+pad);
2876
- const viewBox=[left*1000,-height*1000,width*1000,(height+depth)*1000];
2877
- const opacity=options.screen?.dark ? .94 : 1;
2878
- if (![width,height,depth,left,...viewBox].every(Number.isFinite)) throw new Error('Mathematical dimensions are not finite');
2879
- const escapedSource=mathEscape(source);
2880
- // A group exposes authored links to accessibility APIs; an image would hide them.
2881
- const svg='<svg xmlns="http://www.w3.org/2000/svg" role="'+(box.svg.includes('<a ')?'group':'img')+'" aria-label="'+escapedSource+'"'+
2882
- ' data-rapier-math="'+(options.displayMode?'display':'inline')+'" data-math-lines="'+(box.lines || 1)+'"'+
2883
- ' data-math-natural-width="'+mathNumber(options.naturalWidth ?? width)+'"'+
2884
- (options.screen?' data-math-screen="'+mathNumber(options.screen.fontSize)+'|'+mathNumber(options.screen.pixelRatio)+'|'+options.screen.dark+'"':'')+
2885
- (options.maxWidth?' data-math-max-width="'+mathNumber(options.maxWidth)+'"':'')+
2886
- (utf16?' data-tex-utf16="'+utf16+'"':'')+
2887
- (error?.sourceOmitted?' data-math-source-omitted="true"':'')+
2888
- (error?' data-math-error="'+mathEscape(error.code)+'"':'')+' width="'+mathNumber(width)+'em" height="'+mathNumber(height+depth)+'em"'+
2889
- ' viewBox="'+viewBox.map(mathNumber).join(' ')+'"'+
2890
- ' style="font-size:'+mathNumber(mathFontRatio)+'em;max-width:100%;height:auto;vertical-align:-'+mathNumber(depth)+'em;'+
2891
- 'fill-opacity:'+opacity+';stroke-opacity:'+opacity+'" fill="currentColor">'+
2892
- '<title>'+escapedSource+'</title>'+(error?'<desc>'+mathEscape(error.message)+'</desc>':'')+
2893
- '<g transform="scale(1000)">'+box.svg+'</g></svg>';
2894
- if(svg.length>24*1024*1024)throw Object.assign(new Error('The complete formula markup exceeds its output budget.'),{code:'resource-limit'});
2895
- return {svg,width,height,depth,lines:box.lines || 1,fitted:!!box.fitted,errors:error?[error]:[]};
3052
+ // One bounded walk of the admitted TeX tree. This is Presentation MathML, not a
3053
+ // second grammar, a content-math inference engine or a public AST input API.
3054
+ const MATH_ML_OPAQUE_COLOR = /^(?:aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen)$/i;
3055
+ const MATH_ML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
3056
+ const MATH_ML_INVALID_XML = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ud800-\udfff\ufffe\uffff]/u;
3057
+ function mathMLXML(value) {
3058
+ const text = String(value);
3059
+ if (MATH_ML_INVALID_XML.test(text))
3060
+ throw {code: 'invalid-semantic-character', offset: 0, message: 'A generated mathematical character is not valid XML.'};
3061
+ return text.replace(/[&<>"'\t\n\r]/g, character => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '\t': '&#9;', '\n': '&#10;', '\r': '&#13;'}[character]));
2896
3062
  }
2897
3063
 
2898
- function mathSourceAlternative(source) {
2899
- const alternatives=[],parts=[];
2900
- let first=-1,kept=0;
2901
- for(let i=0;i<source.length;i++) {
2902
- const code=source.charCodeAt(i);
2903
- if(code>=0xd800 && code<=0xdbff && i+1<source.length) {
2904
- const next=source.charCodeAt(i+1);
2905
- if(next>=0xdc00 && next<=0xdfff) {i++;continue;}
2906
- }
2907
- if((code>=0x20 && code<=0xd7ff) || (code>=0xe000 && code<=0xfffd) || code===9 || code===10 || code===13)continue;
2908
- if(first<0)first=i;
2909
- if(i>kept)parts.push(source.slice(kept,i));
2910
- parts.push('\\u'+code.toString(16).toUpperCase().padStart(4,'0'));kept=i+1;
2911
- // Flatten small batches instead of retaining one rope node per bad code unit.
2912
- if(parts.length>=1024) {alternatives.push(parts.join(''));parts.length=0;}
2913
- }
2914
- if(first<0)return {alternative:source};
2915
- parts.push(source.slice(kept));alternatives.push(parts.join(''));
2916
- // Only malformed XML text needs a separate carrier; each four hex digits keep one original code unit.
2917
- const encoded=[];parts.length=0;
2918
- for(let i=0;i<source.length;i++) {
2919
- parts.push(source.charCodeAt(i).toString(16).padStart(4,'0'));
2920
- if(parts.length===1024) {encoded.push(parts.join(''));parts.length=0;}
2921
- }
2922
- encoded.push(parts.join(''));
2923
- return {alternative:alternatives.join(''),utf16:encoded.join(''),error:{code:'invalid-source-character',offset:first,
2924
- message:'A source character cannot be embedded in SVG. The text alternative shows Unicode escapes; data-tex-utf16 keeps the original source.'}};
2925
- }
3064
+ function mathML(tree, source, safeSource, options = {}) {
3065
+ const metrics = {nodes: 0, depth: 0, outputCodeUnits: 0, links: 0};
3066
+ const diagnostics = [], codes = new Set(), active = new WeakSet();
3067
+ const sourceOmitted = source.length > 1000000 || !!safeSource?.error?.sourceOmitted;
3068
+ // HAST stringifiers can emit decoded CR literally; a subsequent HTML parse
3069
+ // normalizes it. ASCII custody survives that real host pipeline unchanged.
3070
+ const utf16 = sourceOmitted ? null : (safeSource?.utf16 ?? null);
3071
+ const encoding = sourceOmitted ? null : utf16 === null ? 'application/x-tex' : 'application/x-rapier-tex-utf16';
3072
+ const sourceInfo = {encoding, ...(sourceOmitted ? {omitted: true} : {})};
3073
+ let parts = [], length = 0, content = 0;
3074
+ const fail = (code, message) => { throw {code, message, offset: 0}; };
3075
+ const write = value => {
3076
+ length += value.length;
3077
+ if (length > 8 * 1024 * 1024) fail('resource-limit', 'MathML presentation exceeds its output budget.');
3078
+ parts.push(value);
3079
+ };
3080
+ const open = (name, attributes = {}) => {
3081
+ let value = '<' + name;
3082
+ for (const [key, item] of Object.entries(attributes)) if (item !== undefined)
3083
+ value += ' ' + key + '="' + mathMLXML(item) + '"';
3084
+ write(value + '>');
3085
+ };
3086
+ const close = name => write('</' + name + '>');
3087
+ const token = (name, value, attributes, context) => {
3088
+ open(name, attributes); write(mathMLXML(value)); close(name);
3089
+ if (!context?.phantom && !context?.transparent && /[^\p{White_Space}\p{Default_Ignorable_Code_Point}]/u.test(value)) content++;
3090
+ };
3091
+ const decimal = value => {
3092
+ if (!Number.isFinite(value)) fail('invalid-semantic-value', 'A mathematical dimension is not finite.');
3093
+ return String(Math.round(value * 1e6) / 1e6 || 0);
3094
+ };
3095
+ const em = value => decimal(value) + 'em';
3096
+ const warn = (code, message) => {
3097
+ if (!codes.has(code)) { codes.add(code); diagnostics.push({code, message, offset: 0}); }
3098
+ };
3099
+ const visit = (node, depth) => {
3100
+ if (++metrics.nodes > 100000) fail('resource-limit', 'MathML traversal exceeds its work budget.');
3101
+ metrics.depth = Math.max(metrics.depth, depth);
3102
+ if (depth > 512) fail('resource-limit', 'MathML is nested too deeply.');
3103
+ if (!node || typeof node !== 'object') fail('unsupported-semantic-node', 'A mathematical part is missing.');
3104
+ };
3105
+ const family = node => {
3106
+ const role = node.semanticRole;
3107
+ if (role === 'chemistry') warn('semantic-chemistry-presentation', 'Chemical notation retains presentation structure; chemical element, bond, charge and reaction meanings are not inferred.');
3108
+ else if (role === 'physics') warn('semantic-physics-presentation', 'Physics notation retains its parsed mathematical relationships; physical and specialized operator meanings are not inferred.');
3109
+ else if (role === 'units') warn('semantic-units-presentation', 'Unit notation retains the parser-expanded mathematical structure; quantities and unit identities are not inferred.');
3110
+ else if (role === 'tag') warn('semantic-tag-presentation', 'An authored tag remains following content; no equation identity, numbering or cross-reference semantics are assigned.');
3111
+ };
3112
+ const scriptContext = context => ({...context, display: false, level: Math.min(2, context.level + 1)});
3113
+ const styledContext = (context, node) => {
3114
+ const next = {...context};
3115
+ if (node.variant) next.variant = node.variant;
3116
+ // Invalid names inherit the current color; they cannot prove visibility.
3117
+ if (/^(?:transparent|#[\da-f]{3}0|#[\da-f]{6}00)$/i.test(node.color || '')) next.transparent = true;
3118
+ else if (node.color && (/^#/.test(node.color) || MATH_ML_OPAQUE_COLOR.test(node.color))) next.transparent = false;
3119
+ if (node.absoluteSize !== undefined) next.size = node.absoluteSize;
3120
+ if (node.size !== undefined) next.size *= node.size;
3121
+ if (node.mathStyle) { next.display = node.mathStyle === 'display'; next.level = {display: 0, text: 0, script: 1, scriptscript: 2}[node.mathStyle]; }
3122
+ return next;
3123
+ };
3124
+ const variant = (node, context) => node.variant || (context.variant === 'normal' ? node.defaultVariant || (node.type === 'text' ? 'roman' : 'normal') : context.variant);
3125
+ const styledText = (value, face) => {
3126
+ // Native Core supports only mi mathvariant=normal. The shared pure Unicode
3127
+ // mapping keeps mathematical alphabets meaningful without loading the font.
3128
+ if (face === 'roman') return value;
3129
+ let result = '';
3130
+ for (const character of value) result += String.fromCodePoint(mathStyledCodePoint(character.codePointAt(0), face));
3131
+ return result;
3132
+ };
3133
+ const atom = (node, value, kind, context, attributes = {}) => {
3134
+ const face = variant(node, context);
3135
+ if (kind === 'mtext') {
3136
+ let css = '';
3137
+ if (face.includes('bold')) css += 'font-weight:700;';
3138
+ if (face.includes('italic')) css += 'font-style:italic;';
3139
+ if (face.includes('sans-serif')) css += 'font-family:sans-serif;';
3140
+ else if (face === 'monospace') css += 'font-family:monospace;';
3141
+ if (/script|fraktur|double-struck/.test(face)) {
3142
+ attributes.mathvariant = face;
3143
+ warn('semantic-text-variant', 'This text alphabet uses the MathML 3 mathvariant extension; a Core host may show ordinary text while preserving the text content.');
3144
+ }
3145
+ if (css) attributes.style = css;
3146
+ // MathML trims token whitespace; \text{if } keeps its spaces only as no-break spaces.
3147
+ token(kind, value.replace(/ /g, '\u00a0'), attributes, context); return;
3148
+ }
3149
+ // A single-character mi is italic by default in MathML Core; the plain letter is what assistive technology speaks.
3150
+ const styled = kind === 'mi' && (face === 'normal' || face === 'italic') && [...value].length === 1 ? value : styledText(value, face);
3151
+ if (kind === 'mo' && context.movableLimits !== undefined) attributes.movablelimits = String(context.movableLimits);
3152
+ if (kind === 'mi' && face !== 'normal' && face !== 'italic') attributes.mathvariant = 'normal';
3153
+ token(kind, styled, attributes, context);
3154
+ };
3155
+ const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[∞∅ℵℶℷℸ]$/.test(node.value) ? 'mi' :
3156
+ ['op', 'bin', 'rel', 'open', 'close', 'punct', 'inner'].includes(node.class) ||
3157
+ /^[\p{Sm}\p{P}\p{Sc}\p{So}\p{Sk}\u2061-\u2064]$/u.test(node.value) ? 'mo' : 'mi');
3158
+ const classOf = node => {
3159
+ if (!node) return undefined;
3160
+ if (node.class) return node.class;
3161
+ if (node.type === 'scripts' || node.type === 'accent') return classOf(node.base);
3162
+ if (node.type === 'style' || node.type === 'link') return classOf(node.body);
3163
+ if (node.type === 'row' && node.children.length === 1) return classOf(node.children[0]);
3164
+ return 'ord';
3165
+ };
3166
+ const limitsOf = node => {
3167
+ if (!node) return undefined;
3168
+ if (node.limits) return node.limits;
3169
+ if (node.type === 'style' || node.type === 'link') return limitsOf(node.body);
3170
+ if (node.type === 'row' && node.children.length === 1) return limitsOf(node.children[0]);
3171
+ if (node.type === 'accent') return limitsOf(node.base);
3172
+ return undefined;
3173
+ };
3174
+ const plain = (node, depth, strict = false) => {
3175
+ visit(node, depth); family(node);
3176
+ if (strict && node.variant && node.variant !== 'roman') return null;
3177
+ if (node.type === 'text' || !strict && node.type === 'glyph') return node.value;
3178
+ if (node.type !== 'row') return null;
3179
+ const values = [];
3180
+ for (const child of node.children) {
3181
+ const value = plain(child, depth + 1, strict);
3182
+ if (value === null) return null;
3183
+ values.push(value);
3184
+ }
3185
+ return values.join('');
3186
+ };
3187
+ const fence = (value, form, context, size) => {
3188
+ if (value) token('mo', value, {fence: 'true', form, stretchy: 'true', symmetric: 'true', ...(size ? {minsize: em(size), maxsize: em(size)} : {})}, context);
3189
+ };
3190
+ const numberPart = node => node?.type === 'glyph' && !node.semanticRole && !node.tokenKind && !node.large && !node.delimiter &&
3191
+ !node.delimiterSize && (!node.class || node.class === 'ord') && /^[\p{Decimal_Number}.]$/u.test(node.value);
3192
+ const sameNumberStyle = (left, right) => left.variant === right.variant && left.defaultVariant === right.defaultVariant;
3193
+ const singleToken = node => {
3194
+ while (node?.type === 'row' && !node.semanticRole && node.children.length === 1) node = node.children[0];
3195
+ return node?.type === 'glyph' || node?.type === 'text' ? node : null;
3196
+ };
2926
3197
 
2927
- function renderMath(source,options={}) {
2928
- const text=String(source ?? '');
2929
- // Reject before scanning, escaping or parsing. Keep the diagnostic-return
2930
- // contract, but explicitly omit refused source instead of expanding it.
2931
- const safe=text.length>1000000?{alternative:'Formula source omitted: source limit exceeded.',error:{
2932
- code:'resource-limit',offset:0,sourceOmitted:true,
2933
- message:'This formula is too long to render safely. Its source was not embedded; retain the original input.'
2934
- }}:mathSourceAlternative(text),context={size:1,level:0,variant:'normal',cramped:false,display:!!options?.displayMode,cache:new WeakMap(),budget:{nodes:0,outlineBytes:0}};
2935
- try {
2936
- if(safe.error)throw safe.error;
2937
- if(options?.screen!==undefined) {
2938
- const {fontSize,pixelRatio,dark}=options.screen || {},scaled=Number.isFinite(fontSize)?fontSize*mathFontRatio:NaN;
2939
- if(!Number.isFinite(fontSize) || fontSize<=0 || !Number.isFinite(pixelRatio) || pixelRatio<=0 ||
2940
- typeof dark!=='boolean' || !Number.isFinite(scaled) || scaled<=0 || !Number.isFinite(scaled*pixelRatio) || scaled*pixelRatio<=0 ||
2941
- !Number.isFinite(1/scaled) || !Number.isFinite(1/pixelRatio) || !Number.isFinite(1/(scaled*pixelRatio)))
2942
- throw Object.assign(new Error('Screen font size, pixel ratio and device scale must be positive and finite; dark must be a boolean.'),{code:'invalid-screen'});
2943
- context.screen={fontSize:scaled,pixelRatio,dark};
3198
+ function scripts(node, context, depth, base) {
3199
+ const limits = node.limits || limitsOf(node.base), stacked = limits === 'always' || limits === 'display' && context.display && context.level === 0;
3200
+ const name = stacked ? node.sub && node.sup ? 'munderover' : node.sub ? 'munder' : 'mover' : node.sub && node.sup ? 'msubsup' : node.sub ? 'msub' : 'msup';
3201
+ open(name, stacked ? {accent: node.sup ? 'false' : undefined, accentunder: node.sub ? 'false' : undefined} : {});
3202
+ if (base) base(); else emit(node.base, {...context, form: undefined, movableLimits: stacked ? false : undefined}, depth + 1);
3203
+ if (node.sub) emit(node.sub, scriptContext(context), depth + 1);
3204
+ if (node.sup) emit(node.sup, scriptContext(context), depth + 1);
3205
+ close(name);
3206
+ }
3207
+
3208
+ function row(children, context, depth) {
3209
+ open('mrow');
3210
+ let previous;
3211
+ for (let index = 0; index < children.length; index++) {
3212
+ const node = children[index];
3213
+ if (numberPart(node)) {
3214
+ let end = index + 1;
3215
+ while (end < children.length && numberPart(children[end]) && sameNumberStyle(node, children[end])) end++;
3216
+ const scripted = children[end]?.type === 'scripts' && !children[end].semanticRole && numberPart(children[end].base) && sameNumberStyle(node, children[end].base) ? children[end] : null;
3217
+ const values = children.slice(index, end).map(child => child.value).join('') + (scripted ? scripted.base.value : '');
3218
+ // A malformed multi-dot run is not silently split into apparent decimal
3219
+ // numbers. Groups, explicit spaces, styles and scripts are hard borders.
3220
+ if (/^(?:\p{Decimal_Number}+(?:\.\p{Decimal_Number}*)?|\.\p{Decimal_Number}+)$/u.test(values)) {
3221
+ for (let at = index; at < end; at++) visit(children[at], depth + 1);
3222
+ if (scripted) {
3223
+ visit(scripted, depth + 1); visit(scripted.base, depth + 2);
3224
+ scripts(scripted, context, depth + 1, () => atom(node, values, 'mn', context)); end++;
3225
+ } else atom(node, values, 'mn', context);
3226
+ previous = 'ord'; index = end - 1; continue;
3227
+ }
3228
+ // Consume an invalid run in one pass. Reconsidering each suffix both
3229
+ // invents decimals (6.7.8 -> 6 . 7.8) and makes dot-only input quadratic.
3230
+ for (let at = index; at < end; at++) emit(children[at], context, depth + 1);
3231
+ if (scripted) { emit(scripted, context, depth + 1); end++; }
3232
+ previous = 'ord'; index = end - 1; continue;
3233
+ }
3234
+ let form;
3235
+ if (node.type === 'glyph' && node.class === 'bin')
3236
+ form = !previous || ['bin', 'op', 'rel', 'open', 'punct'].includes(previous) ? 'prefix' : 'infix';
3237
+ emit(node, {...context, form}, depth + 1);
3238
+ if (node.type !== 'space') previous = classOf(node);
3239
+ }
3240
+ close('mrow');
3241
+ }
3242
+
3243
+ function table(node, context, depth) {
3244
+ const rows = node.rows, columns = Math.max(node.align?.length || 0, node.pairs ? node.pairs * 2 : 0, ...rows.map(cells => cells.length));
3245
+ const insertions = node.columnInsertions || [], rules = (node.columnRules?.length || 0) + (node.rowRules?.length || 0);
3246
+ if (columns > 256 || rows.length > 2048 || rows.length * (columns + insertions.length) + rules > 100000)
3247
+ fail('resource-limit', 'MathML table composition exceeds its work budget.');
3248
+ for (const boundary of node.columnRules || []) if (!Number.isInteger(boundary) || boundary < 0 || boundary > columns)
3249
+ fail('invalid-rule', 'An array rule exceeds its columns.');
3250
+ for (const rule of node.rowRules || []) {
3251
+ const from = rule.from ?? 0, to = rule.to ?? columns;
3252
+ if (!Number.isInteger(rule.before) || rule.before < 0 || rule.before > rows.length || !Number.isInteger(from) ||
3253
+ !Number.isInteger(to) || from < 0 || from > to || to > columns)
3254
+ fail('invalid-rule', 'An array rule exceeds its cells.');
3255
+ }
3256
+ if (insertions.length || rules) warn('semantic-array-presentation', 'Array insertion content is preserved in adjacent cells; decorative row and column rules have no additional mathematical meaning and are omitted.');
3257
+ const before = Array.from({length: columns + 1}, () => []);
3258
+ for (const insertion of insertions) {
3259
+ if (!Number.isInteger(insertion.before) || insertion.before < 0 || insertion.before > columns)
3260
+ fail('invalid-alignment', 'A MathML array insertion exceeds its columns.');
3261
+ before[insertion.before].push(insertion.body);
3262
+ }
3263
+ const small = /smallmatrix$/.test(node.env) || node.env === 'subarray' || node.env === 'substack';
3264
+ const display = /^(align(?:ed)?(?:at)?|flalign|split|gather(?:ed)?|eqnarray|multline|equation|drcases|dcases)$/.test(node.env);
3265
+ const cellContext = {...context, display: small ? false : display, level: small ? Math.max(1, context.level) : context.level};
3266
+ const delimiters = {pmatrix: ['(', ')'], bmatrix: ['[', ']'], Bmatrix: ['{', '}'], vmatrix: ['|', '|'], Vmatrix: ['‖', '‖'],
3267
+ psmallmatrix: ['(', ')'], bsmallmatrix: ['[', ']'], Bsmallmatrix: ['{', '}'], vsmallmatrix: ['|', '|'], Vsmallmatrix: ['‖', '‖'],
3268
+ cases: ['{', ''], dcases: ['{', ''], rcases: ['', '}'], drcases: ['', '}']}[node.env];
3269
+ if (delimiters) { open('mrow'); fence(delimiters[0], 'prefix', context); }
3270
+ open('mtable', {displaystyle: String(cellContext.display), scriptlevel: String(cellContext.level), 'data-math-environment': node.env});
3271
+ for (let at = 0; at < rows.length; at++) {
3272
+ open('mtr');
3273
+ for (let column = 0; column < columns; column++) {
3274
+ if (++metrics.nodes > 100000) fail('resource-limit', 'MathML table cells exceed its work budget.');
3275
+ let align = node.env === 'eqnarray' ? ['r', 'c', 'l'][column % 3] : node.align?.[column] || 'c';
3276
+ if (node.env === 'multline' && columns === 1) align = at === 0 ? 'l' : at === rows.length - 1 ? 'r' : 'c';
3277
+ open('mtd', {style: 'text-align:' + ({l: 'left', r: 'right', c: 'center'}[align] || 'center')});
3278
+ open('mrow');
3279
+ for (const body of before[column]) emit(body, cellContext, depth + 1);
3280
+ if (rows[at][column]) emit(rows[at][column], cellContext, depth + 1);
3281
+ if (column === columns - 1) for (const body of before[columns]) emit(body, cellContext, depth + 1);
3282
+ close('mrow'); close('mtd');
3283
+ }
3284
+ close('mtr');
2944
3285
  }
2945
- const tree=parseMathTex(text),natural=mathLayout(tree,context),limit=Number(options?.maxWidth);
2946
- const maxWidth=Number.isFinite(limit) && limit>.1?limit:undefined;
2947
- const box=maxWidth && mathInkWidth(natural)>maxWidth-.05?mathResponsiveLayout(tree,context,maxWidth-.05,natural):natural;
2948
- return mathSvg(box,safe.alternative,undefined,undefined,{displayMode:context.display,maxWidth,naturalWidth:mathInkWidth(natural)+.05,screen:context.screen});
3286
+ close('mtable');
3287
+ if (delimiters) { fence(delimiters[1], 'postfix', context); close('mrow'); }
3288
+ if (node.position || node.rowGaps?.some(value => value))
3289
+ warn('semantic-table-spacing', 'Table row and cell relationships are preserved; custom baseline placement and row gaps are not reproduced.');
2949
3290
  }
2950
- catch (cause) {
2951
- const message=String(cause.message || cause);
2952
- const error={code:cause.code || 'invalid-tex',message:message.length>1024?message.slice(0,1024).replace(/[\ud800-\udbff]$/,'')+'…':message,offset:Number.isFinite(cause.offset)?cause.offset:0};
2953
- if(message.length>1024)error.messageTruncated=true;
2954
- if(cause.sourceOmitted)error.sourceOmitted=true;
2955
- if(cause.command) {
2956
- error.command=String(cause.command).slice(0,128);
2957
- if(cause.command.length>128)error.commandTruncated=true;
2958
- }
2959
- // A diagnostic is visible, but remains distinct from a successfully typeset formula.
2960
- // Diagnostics have an explicit bound. Exact input stays in the source alternative.
2961
- const label=error.message.length>240?'This formula could not be rendered. The complete diagnostic is in its text description.':error.message.replace(/[^\x20-\x7e]/g,'?');
2962
- const diagnostic={...context,variant:'roman',size:0.8,budget:{nodes:0,outlineBytes:0}};
3291
+
3292
+ function emit(node, context, depth = 0) {
3293
+ visit(node, depth); family(node);
3294
+ if (active.has(node)) fail('unsupported-semantic-node', 'A mathematical tree contains a cycle.');
3295
+ active.add(node);
2963
3296
  try {
2964
- return mathSvg(mathText(label,diagnostic),safe.alternative,error,safe.utf16,{displayMode:context.display,screen:context.screen});
2965
- } catch {
2966
- diagnostic.screen=undefined;
2967
- return mathSvg(mathText(label,diagnostic),safe.alternative,error,safe.utf16,{displayMode:context.display});
2968
- }
3297
+ switch (node.type) {
3298
+ case 'row': row(node.children, context, depth); break;
3299
+ case 'glyph': {
3300
+ const name = kind(node), attributes = {};
3301
+ if (name === 'mo') {
3302
+ if (node.class === 'open' || node.class === 'close') { attributes.fence = 'true'; attributes.form = node.class === 'open' ? 'prefix' : 'postfix'; }
3303
+ else if (node.class === 'punct') attributes.separator = 'true';
3304
+ else if (context.form) attributes.form = context.form;
3305
+ if (node.large !== undefined) attributes.largeop = String(!!node.large);
3306
+ if (node.limits) attributes.movablelimits = String(node.limits === 'display');
3307
+ if (node.delimiter || node.delimiterSize || node.stretch) attributes.stretchy = 'true';
3308
+ else attributes.stretchy = 'false';
3309
+ if (node.delimiterSize) attributes.minsize = attributes.maxsize = em(node.delimiterSize);
3310
+ }
3311
+ atom(node, node.value, name, context, attributes); break;
3312
+ }
3313
+ case 'text': atom(node, node.value, ['op', 'bin', 'rel'].includes(node.class) ? 'mo' : 'mtext', context,
3314
+ node.class === 'op' ? {form: 'prefix', movablelimits: String(node.limits === 'display')} : {}); break;
3315
+ case 'space': open('mspace', {width: em(Math.max(0, node.width)), style: node.width < 0 ? 'margin-left:' + em(node.width) : undefined}); close('mspace'); break;
3316
+ case 'scripts': scripts(node, context, depth); break;
3317
+ case 'frac': {
3318
+ const local = node.style ? styledContext(context, {mathStyle: node.style}) : context;
3319
+ if (node.style) open('mstyle', {displaystyle: String(local.display), scriptlevel: String(local.level)});
3320
+ if (node.left || node.right) { open('mrow'); fence(node.left, 'prefix', local); }
3321
+ open('mfrac', {linethickness: node.bar === false ? '0' : node.barThickness === undefined ? undefined : em(node.barThickness)});
3322
+ const child = local.display && local.level === 0 ? {...local, display: false} : scriptContext(local);
3323
+ emit(node.num, child, depth + 1); emit(node.den, child, depth + 1); close('mfrac');
3324
+ if (node.left || node.right) { fence(node.right, 'postfix', local); close('mrow'); }
3325
+ if (node.style) close('mstyle');
3326
+ if (node.align) warn('semantic-fraction-alignment', 'The fraction relationship is preserved; continued-fraction numerator alignment is left to the MathML host.');
3327
+ break;
3328
+ }
3329
+ case 'root':
3330
+ open(node.index ? 'mroot' : 'msqrt'); emit(node.body, context, depth + 1);
3331
+ if (node.index) emit(node.index, {...context, display: false, level: 2}, depth + 1);
3332
+ close(node.index ? 'mroot' : 'msqrt'); break;
3333
+ case 'fence':
3334
+ open('mrow'); fence(node.left, 'prefix', context, node.size); emit(node.body, context, depth + 1); fence(node.right, 'postfix', context, node.size); close('mrow'); break;
3335
+ case 'accent': {
3336
+ if (node.overlay) {
3337
+ warn('semantic-overlay', 'An overlay uses the MathML 3 menclose extension; hosts implementing only Core may omit the cancellation or negation mark.');
3338
+ const notation = node.value === '╲' ? 'downdiagonalstrike' : node.value === '╳' ? 'updiagonalstrike downdiagonalstrike' : node.value === '↗' ? 'updiagonalarrow' : node.value === '─' ? 'horizontalstrike' : 'updiagonalstrike';
3339
+ open('menclose', {notation}); emit(node.base, context, depth + 1); close('menclose'); break;
3340
+ }
3341
+ const under = node.position === 'under', name = under ? 'munder' : 'mover';
3342
+ open(name, {[under ? 'accentunder' : 'accent']: 'true'}); emit(node.base, {...context, movableLimits: false}, depth + 1);
3343
+ token('mo', node.value, {stretchy: String(!!node.stretch)}, context); close(name); break;
3344
+ }
3345
+ case 'overunder': {
3346
+ const name = node.over && node.under ? 'munderover' : node.under ? 'munder' : 'mover';
3347
+ open(name, {accent: node.over ? 'false' : undefined, accentunder: node.under ? 'false' : undefined}); emit(node.base, {...context, movableLimits: false}, depth + 1);
3348
+ if (node.under) emit(node.under, scriptContext(context), depth + 1);
3349
+ if (node.over) emit(node.over, scriptContext(context), depth + 1);
3350
+ close(name); break;
3351
+ }
3352
+ case 'table': table(node, context, depth); break;
3353
+ case 'style': {
3354
+ const local = styledContext(context, node), attributes = {'data-math-class': node.class};
3355
+ if (node.mathStyle) { attributes.displaystyle = String(local.display); attributes.scriptlevel = String(local.level); }
3356
+ let css = '';
3357
+ if (node.absoluteSize !== undefined || node.size !== undefined) css += 'font-size:' + decimal(local.size / context.size) + 'em;';
3358
+ if (node.color) css += 'color:' + node.color + ';';
3359
+ if (node.background) css += 'background-color:' + node.background + ';';
3360
+ if (node.border) css += 'border:0.04em solid ' + node.border + ';padding:' + em(node.padding ?? .2) + ';';
3361
+ if (css) attributes.style = css;
3362
+ open('mstyle', attributes);
3363
+ if (node.tokenKind) {
3364
+ atom({variant: local.variant}, node.tokenText, node.tokenKind, local);
3365
+ } else if (node.operatorName) {
3366
+ const value = plain(node.body, depth + 1, true);
3367
+ if (value === null) {
3368
+ warn('semantic-rich-operator', 'A styled or mixed-math operator name retains its nested structure instead of becoming one plain operator token.');
3369
+ emit(node.body, local, depth + 1);
3370
+ } else atom({variant: 'roman'}, value, 'mo', local, {form: 'prefix', movablelimits: String(node.limits === 'display')});
3371
+ } else if (node.width !== undefined) {
3372
+ warn('semantic-layout-adjustment', 'A TeX layout adjustment retains its mathematical content with a bounded presentation approximation.');
3373
+ open('mpadded', {width: em(node.width)}); emit(node.body, local, depth + 1); close('mpadded');
3374
+ } else if (node.class) {
3375
+ const leaf = singleToken(node.body);
3376
+ if (leaf) emit({...leaf, class: node.class}, local, depth + 1);
3377
+ else {
3378
+ warn('semantic-atom-class', 'A compound expression retains its mathematical children; its TeX atom class does not create a single MathML operator.');
3379
+ emit(node.body, local, depth + 1);
3380
+ }
3381
+ } else emit(node.body, local, depth + 1);
3382
+ close('mstyle'); break;
3383
+ }
3384
+ case 'phantom': {
3385
+ const before = content;
3386
+ if (node.mode === 'h' || node.mode === 'v') open('mpadded', node.mode === 'h' ? {height: '0', depth: '0'} : {width: '0'});
3387
+ open('mphantom'); emit(node.body, {...context, phantom: true}, depth + 1); close('mphantom');
3388
+ if (node.mode === 'h' || node.mode === 'v') close('mpadded');
3389
+ content = before; break;
3390
+ }
3391
+ case 'smash':
3392
+ open('mpadded', {height: node.mode === 'b' ? undefined : '0', depth: node.mode === 't' ? undefined : '0'});
3393
+ emit(node.body, context, depth + 1); close('mpadded'); break;
3394
+ case 'raise':
3395
+ open('mpadded', {voffset: em(node.amount), height: node.height === undefined ? undefined : em(node.height), depth: node.depth === undefined ? undefined : em(node.depth)});
3396
+ emit(node.body, context, depth + 1); close('mpadded'); break;
3397
+ case 'rule':
3398
+ warn('semantic-rule-presentation', 'A rule is represented as a decorative mathematical space; no additional mathematical relationship is inferred.');
3399
+ open('mspace', {width: em(node.width), height: em(node.height), depth: em(node.depth), style: 'background-color:currentColor'}); close('mspace');
3400
+ if (!context.phantom && !context.transparent && node.width > 0 && node.height + node.depth > 0) content++; break;
3401
+ case 'link': {
3402
+ if (context.inLink) fail('semantic-nested-link', 'Nested authored mathematical links cannot be represented as valid native HTML links.');
3403
+ if (context.phantom) fail('semantic-hidden-link', 'An authored link inside phantom content cannot become an invisible native focus target.');
3404
+ let url;
3405
+ try { url = new URL(node.href); } catch { fail('unsafe-link', 'A mathematical link has an invalid address.'); }
3406
+ if (!['http:', 'https:'].includes(url.protocol) || !/^https?:\/\/[^\s<>"'\\]+$/i.test(node.href))
3407
+ fail('unsafe-link', 'A mathematical link must use an HTTP or HTTPS address.');
3408
+ warn('semantic-link-embedding', 'The authored link uses native HTML inside MathML text, with a nested MathML expression; assistive-technology interaction depends on the host.');
3409
+ metrics.links++;
3410
+ open('mtext'); open('a', {xmlns: 'http://www.w3.org/1999/xhtml', href: node.href, title: node.href, target: '_blank', rel: 'noopener noreferrer'});
3411
+ const before = content;
3412
+ open('math', {xmlns: MATH_ML_NAMESPACE, display: 'inline'}); emit(node.body, {...context, inLink: true, display: false}, depth + 1);
3413
+ if (content === before) fail('semantic-empty-link', 'An authored mathematical link has no visible content for native focus.');
3414
+ close('math'); close('a'); close('mtext'); break;
3415
+ }
3416
+ default: fail('unsupported-semantic-node', 'Unsupported mathematical node for MathML.');
3417
+ }
3418
+ } finally { active.delete(node); }
2969
3419
  }
3420
+
3421
+ let status;
3422
+ try {
3423
+ if (sourceOmitted) fail('resource-limit', 'This formula is too long for MathML. Its source was not embedded; retain the original input.');
3424
+ if (options.error || safeSource?.error) throw options.error || safeSource.error;
3425
+ if (!tree) fail('unsupported-semantic-node', 'A parsed mathematical expression is required.');
3426
+ emit(tree, {display: !!options.displayMode, level: 0, size: 1, variant: 'normal', inLink: false});
3427
+ status = diagnostics.length ? 'presentation-fallback' : 'complete';
3428
+ } catch (cause) {
3429
+ const error = mathDiagnostic(cause);
3430
+ if (sourceOmitted) error.sourceOmitted = true;
3431
+ diagnostics.length = 0; diagnostics.push(error);
3432
+ status = 'refused'; metrics.links = 0;
3433
+ parts = ['<merror><mtext>Formula could not be represented as MathML.</mtext></merror>'];
3434
+ }
3435
+ const presentation = parts.join('');
3436
+ const annotation = sourceOmitted ? '' : encoding === 'application/x-tex' ?
3437
+ '<annotation encoding="application/x-tex">' + mathMLXML(source) + '</annotation>' :
3438
+ '<annotation encoding="text/plain">' + mathMLXML(safeSource.alternative) + '</annotation>' +
3439
+ '<annotation encoding="application/x-rapier-tex-utf16">' + utf16 + '</annotation>';
3440
+ const wrap = body => '<math xmlns="' + MATH_ML_NAMESPACE + '" display="' + (options.displayMode ? 'block' : 'inline') +
3441
+ '" data-rapier-mathml-status="' + status + '"' + (sourceOmitted ? ' data-math-source-omitted="true"' : '') +
3442
+ '><semantics>' + body + annotation + '</semantics></math>';
3443
+ // Source admission bounds escaping independently of the presentation budget:
3444
+ // at most 6M XML-escaped source, or 6M alternative plus 4M UTF-16 carrier.
3445
+ let mathml = wrap(presentation);
3446
+ if (mathml.length > 16 * 1024 * 1024) {
3447
+ status = 'refused'; metrics.links = 0;
3448
+ diagnostics.length = 0;
3449
+ diagnostics.push({code: 'resource-limit', offset: 0, message: 'Complete MathML exceeds its output budget.'});
3450
+ mathml = wrap('<merror><mtext>Formula could not be represented as MathML.</mtext></merror>');
3451
+ }
3452
+ metrics.outputCodeUnits = mathml.length;
3453
+ return {mathml, status, errors: diagnostics, metrics, source: sourceInfo};
2970
3454
  }
2971
3455
 
3456
+ // SPDX-License-Identifier: MIT
3457
+ function mathSemanticPrepared(prepared, options = {}) {
3458
+ const {text, safe, tree, error} = prepared;
3459
+ return mathML(tree, text, safe, {displayMode: !!options?.displayMode, error});
3460
+ }
3461
+ function mathToMathML(source, options = {}) {
3462
+ return mathSemanticPrepared(mathPrepare(source), options);
3463
+ }
3464
+
3465
+ // SPDX-License-Identifier: MIT
3466
+ // The prepared tree never crosses the public boundary. Both outputs consume it
3467
+ // within this call, before any result or caller-mutable parse tree is exposed.
3468
+ function mathRenderWithMathML(source, options = {}) {
3469
+ const prepared = mathPrepare(source), displayMode = !!options?.displayMode;
3470
+ const semantics = mathSemanticPrepared(prepared, {displayMode});
3471
+ return {...mathRenderPrepared(prepared, {...options, displayMode}), semantics};
3472
+ }
3473
+
3474
+ // SPDX-License-Identifier: MIT
2972
3475
  globalThis.RapierMath=Object.freeze({
2973
- version:'2.0.0',
2974
- parse:parseMathTex,
2975
- render:renderMath,
2976
- fit:mathFit,
2977
- observe:mathObserve,
2978
- renderToString(source,options) {return renderMath(source,options).svg;},
3476
+ version:'2.2.0', parse:parseMathTex,
3477
+ render:renderMath, renderToString:mathRenderToString,
3478
+ fit:mathFit, observe:mathObserve,
3479
+ toMathML:mathToMathML, renderWithMathML:mathRenderWithMathML,
2979
3480
  });
2980
3481
  })();