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
@@ -41,43 +41,6 @@ function mathCompose(items, width, extra = {}) {
41
41
  return mathBox(width, h, d, svg, {left, right, inkTop:Number.isFinite(inkTop)?inkTop:-h, inkBottom:Number.isFinite(inkBottom)?inkBottom:d,...glyph,...extra});
42
42
  }
43
43
 
44
- const MATH_STYLED_RANGES = {
45
- italic: [0x1d434, 0x1d44e, null], bold: [0x1d400, 0x1d41a, 0x1d7ce],
46
- 'bold-italic': [0x1d468, 0x1d482, null], script: [0x1d49c, 0x1d4b6, null],
47
- 'bold-script': [0x1d4d0, 0x1d4ea, null], fraktur: [0x1d504, 0x1d51e, null],
48
- 'bold-fraktur': [0x1d56c, 0x1d586, null], 'double-struck': [0x1d538, 0x1d552, 0x1d7d8],
49
- 'sans-serif': [0x1d5a0, 0x1d5ba, 0x1d7e2], 'sans-serif-bold': [0x1d5d4, 0x1d5ee, 0x1d7ec],
50
- 'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, null],
51
- monospace: [0x1d670, 0x1d68a, 0x1d7f6],
52
- };
53
- const MATH_STYLED_LEGACY = {
54
- italic: {104: 0x210e},
55
- script: {66:0x212c,69:0x2130,70:0x2131,72:0x210b,73:0x2110,76:0x2112,77:0x2133,82:0x211b,101:0x212f,103:0x210a,111:0x2134},
56
- fraktur: {67:0x212d,72:0x210c,73:0x2111,82:0x211c,90:0x2128},
57
- 'double-struck': {67:0x2102,72:0x210d,78:0x2115,80:0x2119,81:0x211a,82:0x211d,90:0x2124},
58
- };
59
- const MATH_STYLED_GREEK = {bold:0x1d6a8, italic:0x1d6e2, 'bold-italic':0x1d71c, 'sans-serif-bold':0x1d756, 'sans-serif-bold-italic':0x1d790};
60
- const MATH_STYLED_GREEK_SPECIAL = [0x2207,0x2202,0x3f5,0x3d1,0x3f0,0x3d5,0x3f1,0x3d6];
61
- function mathStyledCodePoint(cp, variant) {
62
- if (variant === 'normal') variant = 'italic';
63
- if (MATH_STYLED_LEGACY[variant]?.[cp] !== undefined) return MATH_STYLED_LEGACY[variant][cp];
64
- const r = MATH_STYLED_RANGES[variant];
65
- if (r) {
66
- if (cp >= 65 && cp <= 90) return r[0] + cp - 65;
67
- if (cp >= 97 && cp <= 122) return r[1] + cp - 97;
68
- if (r[2] && cp >= 48 && cp <= 57) return r[2] + cp - 48;
69
- }
70
- const greek = MATH_STYLED_GREEK[variant];
71
- if (greek !== undefined) {
72
- if (cp >= 0x391 && cp <= 0x3a9 && cp !== 0x3a2) return greek + cp - 0x391;
73
- if (cp >= 0x3b1 && cp <= 0x3c9) return greek + 26 + cp - 0x3b1;
74
- const special = MATH_STYLED_GREEK_SPECIAL.indexOf(cp);
75
- if (special === 0) return greek + 25;
76
- if (special > 0) return greek + 50 + special;
77
- }
78
- return cp;
79
- }
80
-
81
44
  function mathGlyphIndex(id, c, extra = {}) {
82
45
  if(c.dotless)id=MATH_FONT.dotless?.[id] ?? id;
83
46
  const alternates=MATH_FONT.scriptAlternates[id],scale=mathScale(c);
@@ -107,20 +70,41 @@ function mathGlyph(value, c, extra = {}) {
107
70
  if (id === undefined) {
108
71
  const composed = mathFallbackGlyph(value, c, extra);
109
72
  if (composed) return composed;
73
+ if (MATH_HOST_TEXT.test(value)) return mathHostText(value, c, {...extra, host: true});
110
74
  const e = new Error('Unsupported character U+' + cp.toString(16).toUpperCase());
111
75
  e.code = 'unsupported-glyph'; e.command = value; throw e;
112
76
  }
113
77
  return mathGlyphIndex(id, c, extra);
114
78
  }
115
79
 
80
+ // Letters, digits, marks and symbols outside the embedded font (CJK, Cyrillic, emoji...) use the reader's
81
+ // own serif font. Their advance is estimated, and textLength fits the drawn run to that box exactly.
82
+ const MATH_HOST_TEXT = /^[\p{L}\p{N}\p{M}\p{S}\p{P}]+$/u;
83
+ const MATH_WIDE_TEXT = /[\p{sc=Han}\p{sc=Hang}\p{sc=Hira}\p{sc=Kana}\p{Emoji_Presentation}\u3000-\u303f\uff01-\uff60]/u;
84
+ function mathHostText(value, c, extra = {}) {
85
+ const s = mathScale(c);
86
+ let w = 0;
87
+ 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;
88
+ const variant = c.variant || '';
89
+ return mathBox(w, 0.8 * s, 0.2 * s, '<text font-family="' + (/sans/.test(variant) ? 'sans-serif' : variant === 'monospace' ? 'monospace' : 'serif') + '"' +
90
+ (/bold/.test(variant) ? ' font-weight="bold"' : '') + (/italic/.test(variant) ? ' font-style="italic"' : '') +
91
+ ' font-size="' + mathNumber(s) + '" textLength="' + mathNumber(w) +
92
+ '" lengthAdjust="spacingAndGlyphs">' + mathEscape(value) + '</text>', {inkTop: -0.8 * s, inkBottom: 0.2 * s, ...extra});
93
+ }
94
+
116
95
  function mathText(value, c, extra = {}) {
117
- const items = []; let x = 0;
96
+ const items = [], text = {...c, variant: extra.variant || 'roman'}; let x = 0, run = '';
97
+ const flush = () => { if (run) { const b = mathHostText(run, text); items.push([b,x,0]); x += b.w; run = ''; } };
118
98
  for (const ch of String(value)) {
119
- if (/\s/u.test(ch)) { x += mathScale(c)*0.25; continue; }
120
- const b = mathGlyph(ch, {...c, variant: extra.variant || 'roman'});
121
- items.push([b,x,0]); x += b.w;
99
+ if (/\s/u.test(ch)) { flush(); x += mathScale(c)*0.25; continue; }
100
+ // A run of host-font characters stays one text element, keeping its shaping and joining.
101
+ if (run && /\p{M}/u.test(ch)) { run += ch; continue; }
102
+ const b = mathGlyph(ch, text);
103
+ if (b.host) { run += ch; continue; }
104
+ flush(); items.push([b,x,0]); x += b.w;
122
105
  }
123
- return mathCompose(items,x,{class:extra.class || 'ord',limits:extra.limits,...extra});
106
+ flush();
107
+ return mathCompose(items,x,{...extra,class:extra.class || 'ord'});
124
108
  }
125
109
 
126
110
  function mathRule(w, thickness, y = 0) {
@@ -203,12 +187,17 @@ function mathStretch(value, target, c, horizontal = false) {
203
187
  const overlap=connections.length?Math.max(minOverlap,Math.min((full-wanted)/connections.length,...connections)):0,
204
188
  length=(full-overlap*connections.length)*unit;
205
189
  const items=[]; let pos=0, width=0;
206
- for (let i=0;i<pieces.length;i++) {
190
+ for (let i=0;i<pieces.length;) {
207
191
  const p=pieces[i], b=mathGlyphIndex(p[0],c), g=MATH_FONT.glyph(b.glyph);
208
- if (horizontal) items.push([b,pos,0]);
209
- else items.push([b,0,-pos+g[2]*unit]);
192
+ let k=1; while(p[4] && pieces[i+k]===p)k++;
193
+ // One extender drawn along its axis replaces k abutting copies, whose antialiased seams read as dashes.
194
+ const span=(k*p[3]-(k-1)*overlap)*unit,f=span/(p[3]*unit);
195
+ if (k===1) items.push(horizontal?[b,pos,0]:[b,0,-pos+g[2]*unit]);
196
+ 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]);
197
+ else items.push([{...b,h:pos+span,d:0,inkTop:-pos-span,inkBottom:-pos,
198
+ svg:'<g transform="translate(0 '+mathNumber(-pos)+') scale(1 '+mathNumber(f)+') translate(0 '+mathNumber(g[2]*unit)+')">'+b.svg+'</g>'},0,0]);
210
199
  width=Math.max(width,b.w);
211
- pos+=(p[3]-overlap)*unit;
200
+ pos+=k*(p[3]-overlap)*unit; i+=k;
212
201
  }
213
202
  return mathCompose(items,horizontal?length:width,{italic:(a.italic || 0)*unit,
214
203
  ...(horizontal?{accent:length/2,stretchAxis:'horizontal'}:{h:length,d:0,extended:true})});
@@ -337,13 +326,14 @@ function mathScripts(n,c) {
337
326
  const items=[[b,0,0]]; let w=b.w;
338
327
  if (up) {
339
328
  const kern=Math.min(mathKern(base,0,rise-upDescent)+mathKern(up,3,-upDescent),mathKern(base,0,baseAscent)+mathKern(up,3,baseAscent-rise));
340
- const nominal=b.w+(b.italic || 0)+kern;
329
+ // A large operator's italic correction moves its subscript left, not its superscript right.
330
+ const nominal=b.w+(b.large?0:b.italic || 0)+kern;
341
331
  const x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,up,-rise,nominal,c);
342
332
  items.push([up,x,-rise]);w=Math.max(w,x+up.w);
343
333
  }
344
334
  if (down) {
345
335
  const kern=Math.min(mathKern(base,2,downAscent-drop)+mathKern(down,1,downAscent),mathKern(base,2,-baseDescent)+mathKern(down,1,drop-baseDescent));
346
- const nominal=b.w+kern;
336
+ const nominal=b.w-(b.large?b.italic || 0:0)+kern;
347
337
  const x=MATH_FONT.kern[base.glyph]?nominal:mathContourScript(base,down,drop,nominal,c);
348
338
  items.push([down,x,drop]);w=Math.max(w,x+down.w);
349
339
  }
@@ -365,13 +355,15 @@ function mathFraction(n,c,width) {
365
355
  const min=mathConstant(display?'StackDisplayStyleGapMin':'StackGapMin',c,display?0.4:0.15),gap=rise+drop-top.d-bottom.h;
366
356
  if (gap<min) {rise+=(min-gap)/2;drop+=(min-gap)/2;}
367
357
  }
368
- const pad=mathScale(c)*0.1,w=Math.max(top.w,bottom.w)+2*pad;
358
+ // Null delimiter space pads only an unfenced fraction; a fence's own glyphs bound \binom.
359
+ const pad=n.left || n.right?0:mathScale(c)*0.1,w=Math.max(top.w,bottom.w)+2*pad;
369
360
  const numeratorX=n.align==='l'?pad:n.align==='r'?w-pad-top.w:(w-top.w)/2;
370
361
  const items=[[top,numeratorX,-rise],[bottom,(w-bottom.w)/2,drop]];
371
362
  if (line) items.push([mathRule(w,line,-axis-line/2),0,0]);
372
363
  const b=mathCompose(items,w,{class:'inner',innerLines:top.lines || 1,fitted:!!top.fitted});
373
364
  if(width!==undefined && c.screen)b.refit=ratio=>mathFraction(n,{...c,screen:{...c.screen,fontSize:c.screen.fontSize*ratio},cache:new WeakMap()},width);
374
- if (n.left || n.right) return mathFenceBoxes(n.left || '',n.right || '',b,c);
365
+ // TeX's generalized fractions fence at least its delim1 (display) or delim2 size.
366
+ if (n.left || n.right) return mathFenceBoxes(n.left || '',n.right || '',b,c,undefined,display?2.39:1.01);
375
367
  return b;
376
368
  }
377
369
 
@@ -388,8 +380,8 @@ function mathRoot(n,c) {
388
380
  const b=mathCompose(items,w);b.h+=extra;return b;
389
381
  }
390
382
 
391
- function mathFenceBoxes(left,right,body,c,size) {
392
- 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));
383
+ function mathFenceBoxes(left,right,body,c,size,least=1) {
384
+ 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));
393
385
  const a=mathDelimiter(left,target,c),b=mathDelimiter(right,target,c);
394
386
  return mathCompose([[a,0,0],[body,a.w,0],[b,a.w+body.w,0]],a.w+body.w+b.w,{class:'inner'});
395
387
  }
@@ -403,7 +395,7 @@ function mathAccent(n,c) {
403
395
  const w=Math.max(b.w,0.2*s),line=mathConstant('FractionRuleThickness',c,0.04);
404
396
  const rising='M0 '+mathNumber(b.d)+'L'+mathNumber(w)+' '+mathNumber(-b.h),
405
397
  falling='M0 '+mathNumber(-b.h)+'L'+mathNumber(w)+' '+mathNumber(b.d);
406
- let path=n.value==='╲'?falling:n.value==='╳'?rising+falling:rising;
398
+ let path=n.value==='╲'?falling:n.value==='╳'?rising+falling:n.value==='─'?'M0 '+mathNumber(-mathConstant('AxisHeight',c,0.25))+'H'+mathNumber(w):rising;
407
399
  if(n.value==='↗') {
408
400
  const tip=0.2*s;path+='M'+mathNumber(w-tip)+' '+mathNumber(-b.h)+'H'+mathNumber(w)+'v'+mathNumber(tip);
409
401
  }
@@ -511,6 +503,11 @@ function mathLayout(n,c) {
511
503
  case 'glyph': {
512
504
  if(n.delimiterSize || (n.delimiter && c.delimiterTarget))return {...mathDelimiter(n.value,n.delimiterSize?n.delimiterSize*mathScale(c):c.delimiterTarget,c),class:n.class || 'ord'};
513
505
  if(n.stretch)return {...mathStretch(n.value,c.stretchTarget || mathScale(c),c,true),class:n.class || 'rel',limits:n.limits,stretchAxis:'horizontal'};
506
+ if(n.value==='…' || n.value==='⋯') {
507
+ // TeX's \ldots and \cdots are three punctuation dots with punctuation spacing, wider than the font's ellipses.
508
+ const dot=mathGlyph(n.value==='…'?'.':'⋅',c,{variant:'roman'}),step=dot.w+mathSpace('punct','punct',c);
509
+ return mathCompose([[dot,0,0],[dot,step,0],[dot,2*step,0]],2*step+dot.w,{class:n.class || 'inner'});
510
+ }
514
511
  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});
515
512
  if(n.large && c.display && !c.level) {
516
513
  const target=mathConstant('DisplayOperatorMinHeight',c,1.3),a=mathStretch(n.value,target,c);
@@ -578,3 +575,9 @@ function mathLayout(n,c) {
578
575
  default: throw Object.assign(new Error('Unsupported maths construct: '+n.type),{code:'unsupported-construct'});
579
576
  }
580
577
  }
578
+
579
+ import {MATH_FONT} from './font.js';
580
+ import {mathStyledCodePoint} from './variants.js';
581
+ import {mathFallbackGlyph} from './fallbacks.js';
582
+ import {mathResponsiveLayout} from './responsive.js';
583
+ export {mathNumber, mathScale, mathScreenStroke, mathConstant, mathBox, mathCompose, mathGlyphIndex, mathRule, mathStretch, mathEscape, mathScreenRelayout, mathSpace, mathRow, mathFraction, mathFenceBoxes, mathLayout, mathFontRatio, mathText};
@@ -0,0 +1,408 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // One bounded walk of the admitted TeX tree. This is Presentation MathML, not a
3
+ // second grammar, a content-math inference engine or a public AST input API.
4
+ 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;
5
+ const MATH_ML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
6
+ const MATH_ML_INVALID_XML = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ud800-\udfff\ufffe\uffff]/u;
7
+ function mathMLXML(value) {
8
+ const text = String(value);
9
+ if (MATH_ML_INVALID_XML.test(text))
10
+ throw {code: 'invalid-semantic-character', offset: 0, message: 'A generated mathematical character is not valid XML.'};
11
+ return text.replace(/[&<>"'\t\n\r]/g, character => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '\t': '&#9;', '\n': '&#10;', '\r': '&#13;'}[character]));
12
+ }
13
+
14
+ function mathML(tree, source, safeSource, options = {}) {
15
+ const metrics = {nodes: 0, depth: 0, outputCodeUnits: 0, links: 0};
16
+ const diagnostics = [], codes = new Set(), active = new WeakSet();
17
+ const sourceOmitted = source.length > 1000000 || !!safeSource?.error?.sourceOmitted;
18
+ // HAST stringifiers can emit decoded CR literally; a subsequent HTML parse
19
+ // normalizes it. ASCII custody survives that real host pipeline unchanged.
20
+ const utf16 = sourceOmitted ? null : (safeSource?.utf16 ?? null);
21
+ const encoding = sourceOmitted ? null : utf16 === null ? 'application/x-tex' : 'application/x-rapier-tex-utf16';
22
+ const sourceInfo = {encoding, ...(sourceOmitted ? {omitted: true} : {})};
23
+ let parts = [], length = 0, content = 0;
24
+ const fail = (code, message) => { throw {code, message, offset: 0}; };
25
+ const write = value => {
26
+ length += value.length;
27
+ if (length > 8 * 1024 * 1024) fail('resource-limit', 'MathML presentation exceeds its output budget.');
28
+ parts.push(value);
29
+ };
30
+ const open = (name, attributes = {}) => {
31
+ let value = '<' + name;
32
+ for (const [key, item] of Object.entries(attributes)) if (item !== undefined)
33
+ value += ' ' + key + '="' + mathMLXML(item) + '"';
34
+ write(value + '>');
35
+ };
36
+ const close = name => write('</' + name + '>');
37
+ const token = (name, value, attributes, context) => {
38
+ open(name, attributes); write(mathMLXML(value)); close(name);
39
+ if (!context?.phantom && !context?.transparent && /[^\p{White_Space}\p{Default_Ignorable_Code_Point}]/u.test(value)) content++;
40
+ };
41
+ const decimal = value => {
42
+ if (!Number.isFinite(value)) fail('invalid-semantic-value', 'A mathematical dimension is not finite.');
43
+ return String(Math.round(value * 1e6) / 1e6 || 0);
44
+ };
45
+ const em = value => decimal(value) + 'em';
46
+ const warn = (code, message) => {
47
+ if (!codes.has(code)) { codes.add(code); diagnostics.push({code, message, offset: 0}); }
48
+ };
49
+ const visit = (node, depth) => {
50
+ if (++metrics.nodes > 100000) fail('resource-limit', 'MathML traversal exceeds its work budget.');
51
+ metrics.depth = Math.max(metrics.depth, depth);
52
+ if (depth > 512) fail('resource-limit', 'MathML is nested too deeply.');
53
+ if (!node || typeof node !== 'object') fail('unsupported-semantic-node', 'A mathematical part is missing.');
54
+ };
55
+ const family = node => {
56
+ const role = node.semanticRole;
57
+ if (role === 'chemistry') warn('semantic-chemistry-presentation', 'Chemical notation retains presentation structure; chemical element, bond, charge and reaction meanings are not inferred.');
58
+ else if (role === 'physics') warn('semantic-physics-presentation', 'Physics notation retains its parsed mathematical relationships; physical and specialized operator meanings are not inferred.');
59
+ else if (role === 'units') warn('semantic-units-presentation', 'Unit notation retains the parser-expanded mathematical structure; quantities and unit identities are not inferred.');
60
+ else if (role === 'tag') warn('semantic-tag-presentation', 'An authored tag remains following content; no equation identity, numbering or cross-reference semantics are assigned.');
61
+ };
62
+ const scriptContext = context => ({...context, display: false, level: Math.min(2, context.level + 1)});
63
+ const styledContext = (context, node) => {
64
+ const next = {...context};
65
+ if (node.variant) next.variant = node.variant;
66
+ // Invalid names inherit the current color; they cannot prove visibility.
67
+ if (/^(?:transparent|#[\da-f]{3}0|#[\da-f]{6}00)$/i.test(node.color || '')) next.transparent = true;
68
+ else if (node.color && (/^#/.test(node.color) || MATH_ML_OPAQUE_COLOR.test(node.color))) next.transparent = false;
69
+ if (node.absoluteSize !== undefined) next.size = node.absoluteSize;
70
+ if (node.size !== undefined) next.size *= node.size;
71
+ if (node.mathStyle) { next.display = node.mathStyle === 'display'; next.level = {display: 0, text: 0, script: 1, scriptscript: 2}[node.mathStyle]; }
72
+ return next;
73
+ };
74
+ const variant = (node, context) => node.variant || (context.variant === 'normal' ? node.defaultVariant || (node.type === 'text' ? 'roman' : 'normal') : context.variant);
75
+ const styledText = (value, face) => {
76
+ // Native Core supports only mi mathvariant=normal. The shared pure Unicode
77
+ // mapping keeps mathematical alphabets meaningful without loading the font.
78
+ if (face === 'roman') return value;
79
+ let result = '';
80
+ for (const character of value) result += String.fromCodePoint(mathStyledCodePoint(character.codePointAt(0), face));
81
+ return result;
82
+ };
83
+ const atom = (node, value, kind, context, attributes = {}) => {
84
+ const face = variant(node, context);
85
+ if (kind === 'mtext') {
86
+ let css = '';
87
+ if (face.includes('bold')) css += 'font-weight:700;';
88
+ if (face.includes('italic')) css += 'font-style:italic;';
89
+ if (face.includes('sans-serif')) css += 'font-family:sans-serif;';
90
+ else if (face === 'monospace') css += 'font-family:monospace;';
91
+ if (/script|fraktur|double-struck/.test(face)) {
92
+ attributes.mathvariant = face;
93
+ 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.');
94
+ }
95
+ if (css) attributes.style = css;
96
+ // MathML trims token whitespace; \text{if } keeps its spaces only as no-break spaces.
97
+ token(kind, value.replace(/ /g, '\u00a0'), attributes, context); return;
98
+ }
99
+ // A single-character mi is italic by default in MathML Core; the plain letter is what assistive technology speaks.
100
+ const styled = kind === 'mi' && (face === 'normal' || face === 'italic') && [...value].length === 1 ? value : styledText(value, face);
101
+ if (kind === 'mo' && context.movableLimits !== undefined) attributes.movablelimits = String(context.movableLimits);
102
+ if (kind === 'mi' && face !== 'normal' && face !== 'italic') attributes.mathvariant = 'normal';
103
+ token(kind, styled, attributes, context);
104
+ };
105
+ const kind = node => node.tokenKind || (/^\p{Decimal_Number}+$/u.test(node.value) ? 'mn' : /^[∞∅ℵℶℷℸ]$/.test(node.value) ? 'mi' :
106
+ ['op', 'bin', 'rel', 'open', 'close', 'punct', 'inner'].includes(node.class) ||
107
+ /^[\p{Sm}\p{P}\p{Sc}\p{So}\p{Sk}\u2061-\u2064]$/u.test(node.value) ? 'mo' : 'mi');
108
+ const classOf = node => {
109
+ if (!node) return undefined;
110
+ if (node.class) return node.class;
111
+ if (node.type === 'scripts' || node.type === 'accent') return classOf(node.base);
112
+ if (node.type === 'style' || node.type === 'link') return classOf(node.body);
113
+ if (node.type === 'row' && node.children.length === 1) return classOf(node.children[0]);
114
+ return 'ord';
115
+ };
116
+ const limitsOf = node => {
117
+ if (!node) return undefined;
118
+ if (node.limits) return node.limits;
119
+ if (node.type === 'style' || node.type === 'link') return limitsOf(node.body);
120
+ if (node.type === 'row' && node.children.length === 1) return limitsOf(node.children[0]);
121
+ if (node.type === 'accent') return limitsOf(node.base);
122
+ return undefined;
123
+ };
124
+ const plain = (node, depth, strict = false) => {
125
+ visit(node, depth); family(node);
126
+ if (strict && node.variant && node.variant !== 'roman') return null;
127
+ if (node.type === 'text' || !strict && node.type === 'glyph') return node.value;
128
+ if (node.type !== 'row') return null;
129
+ const values = [];
130
+ for (const child of node.children) {
131
+ const value = plain(child, depth + 1, strict);
132
+ if (value === null) return null;
133
+ values.push(value);
134
+ }
135
+ return values.join('');
136
+ };
137
+ const fence = (value, form, context, size) => {
138
+ if (value) token('mo', value, {fence: 'true', form, stretchy: 'true', symmetric: 'true', ...(size ? {minsize: em(size), maxsize: em(size)} : {})}, context);
139
+ };
140
+ const numberPart = node => node?.type === 'glyph' && !node.semanticRole && !node.tokenKind && !node.large && !node.delimiter &&
141
+ !node.delimiterSize && (!node.class || node.class === 'ord') && /^[\p{Decimal_Number}.]$/u.test(node.value);
142
+ const sameNumberStyle = (left, right) => left.variant === right.variant && left.defaultVariant === right.defaultVariant;
143
+ const singleToken = node => {
144
+ while (node?.type === 'row' && !node.semanticRole && node.children.length === 1) node = node.children[0];
145
+ return node?.type === 'glyph' || node?.type === 'text' ? node : null;
146
+ };
147
+
148
+ function scripts(node, context, depth, base) {
149
+ const limits = node.limits || limitsOf(node.base), stacked = limits === 'always' || limits === 'display' && context.display && context.level === 0;
150
+ const name = stacked ? node.sub && node.sup ? 'munderover' : node.sub ? 'munder' : 'mover' : node.sub && node.sup ? 'msubsup' : node.sub ? 'msub' : 'msup';
151
+ open(name, stacked ? {accent: node.sup ? 'false' : undefined, accentunder: node.sub ? 'false' : undefined} : {});
152
+ if (base) base(); else emit(node.base, {...context, form: undefined, movableLimits: stacked ? false : undefined}, depth + 1);
153
+ if (node.sub) emit(node.sub, scriptContext(context), depth + 1);
154
+ if (node.sup) emit(node.sup, scriptContext(context), depth + 1);
155
+ close(name);
156
+ }
157
+
158
+ function row(children, context, depth) {
159
+ open('mrow');
160
+ let previous;
161
+ for (let index = 0; index < children.length; index++) {
162
+ const node = children[index];
163
+ if (numberPart(node)) {
164
+ let end = index + 1;
165
+ while (end < children.length && numberPart(children[end]) && sameNumberStyle(node, children[end])) end++;
166
+ const scripted = children[end]?.type === 'scripts' && !children[end].semanticRole && numberPart(children[end].base) && sameNumberStyle(node, children[end].base) ? children[end] : null;
167
+ const values = children.slice(index, end).map(child => child.value).join('') + (scripted ? scripted.base.value : '');
168
+ // A malformed multi-dot run is not silently split into apparent decimal
169
+ // numbers. Groups, explicit spaces, styles and scripts are hard borders.
170
+ if (/^(?:\p{Decimal_Number}+(?:\.\p{Decimal_Number}*)?|\.\p{Decimal_Number}+)$/u.test(values)) {
171
+ for (let at = index; at < end; at++) visit(children[at], depth + 1);
172
+ if (scripted) {
173
+ visit(scripted, depth + 1); visit(scripted.base, depth + 2);
174
+ scripts(scripted, context, depth + 1, () => atom(node, values, 'mn', context)); end++;
175
+ } else atom(node, values, 'mn', context);
176
+ previous = 'ord'; index = end - 1; continue;
177
+ }
178
+ // Consume an invalid run in one pass. Reconsidering each suffix both
179
+ // invents decimals (6.7.8 -> 6 . 7.8) and makes dot-only input quadratic.
180
+ for (let at = index; at < end; at++) emit(children[at], context, depth + 1);
181
+ if (scripted) { emit(scripted, context, depth + 1); end++; }
182
+ previous = 'ord'; index = end - 1; continue;
183
+ }
184
+ let form;
185
+ if (node.type === 'glyph' && node.class === 'bin')
186
+ form = !previous || ['bin', 'op', 'rel', 'open', 'punct'].includes(previous) ? 'prefix' : 'infix';
187
+ emit(node, {...context, form}, depth + 1);
188
+ if (node.type !== 'space') previous = classOf(node);
189
+ }
190
+ close('mrow');
191
+ }
192
+
193
+ function table(node, context, depth) {
194
+ const rows = node.rows, columns = Math.max(node.align?.length || 0, node.pairs ? node.pairs * 2 : 0, ...rows.map(cells => cells.length));
195
+ const insertions = node.columnInsertions || [], rules = (node.columnRules?.length || 0) + (node.rowRules?.length || 0);
196
+ if (columns > 256 || rows.length > 2048 || rows.length * (columns + insertions.length) + rules > 100000)
197
+ fail('resource-limit', 'MathML table composition exceeds its work budget.');
198
+ for (const boundary of node.columnRules || []) if (!Number.isInteger(boundary) || boundary < 0 || boundary > columns)
199
+ fail('invalid-rule', 'An array rule exceeds its columns.');
200
+ for (const rule of node.rowRules || []) {
201
+ const from = rule.from ?? 0, to = rule.to ?? columns;
202
+ if (!Number.isInteger(rule.before) || rule.before < 0 || rule.before > rows.length || !Number.isInteger(from) ||
203
+ !Number.isInteger(to) || from < 0 || from > to || to > columns)
204
+ fail('invalid-rule', 'An array rule exceeds its cells.');
205
+ }
206
+ 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.');
207
+ const before = Array.from({length: columns + 1}, () => []);
208
+ for (const insertion of insertions) {
209
+ if (!Number.isInteger(insertion.before) || insertion.before < 0 || insertion.before > columns)
210
+ fail('invalid-alignment', 'A MathML array insertion exceeds its columns.');
211
+ before[insertion.before].push(insertion.body);
212
+ }
213
+ const small = /smallmatrix$/.test(node.env) || node.env === 'subarray' || node.env === 'substack';
214
+ const display = /^(align(?:ed)?(?:at)?|flalign|split|gather(?:ed)?|eqnarray|multline|equation|drcases|dcases)$/.test(node.env);
215
+ const cellContext = {...context, display: small ? false : display, level: small ? Math.max(1, context.level) : context.level};
216
+ const delimiters = {pmatrix: ['(', ')'], bmatrix: ['[', ']'], Bmatrix: ['{', '}'], vmatrix: ['|', '|'], Vmatrix: ['‖', '‖'],
217
+ psmallmatrix: ['(', ')'], bsmallmatrix: ['[', ']'], Bsmallmatrix: ['{', '}'], vsmallmatrix: ['|', '|'], Vsmallmatrix: ['‖', '‖'],
218
+ cases: ['{', ''], dcases: ['{', ''], rcases: ['', '}'], drcases: ['', '}']}[node.env];
219
+ if (delimiters) { open('mrow'); fence(delimiters[0], 'prefix', context); }
220
+ open('mtable', {displaystyle: String(cellContext.display), scriptlevel: String(cellContext.level), 'data-math-environment': node.env});
221
+ for (let at = 0; at < rows.length; at++) {
222
+ open('mtr');
223
+ for (let column = 0; column < columns; column++) {
224
+ if (++metrics.nodes > 100000) fail('resource-limit', 'MathML table cells exceed its work budget.');
225
+ let align = node.env === 'eqnarray' ? ['r', 'c', 'l'][column % 3] : node.align?.[column] || 'c';
226
+ if (node.env === 'multline' && columns === 1) align = at === 0 ? 'l' : at === rows.length - 1 ? 'r' : 'c';
227
+ open('mtd', {style: 'text-align:' + ({l: 'left', r: 'right', c: 'center'}[align] || 'center')});
228
+ open('mrow');
229
+ for (const body of before[column]) emit(body, cellContext, depth + 1);
230
+ if (rows[at][column]) emit(rows[at][column], cellContext, depth + 1);
231
+ if (column === columns - 1) for (const body of before[columns]) emit(body, cellContext, depth + 1);
232
+ close('mrow'); close('mtd');
233
+ }
234
+ close('mtr');
235
+ }
236
+ close('mtable');
237
+ if (delimiters) { fence(delimiters[1], 'postfix', context); close('mrow'); }
238
+ if (node.position || node.rowGaps?.some(value => value))
239
+ warn('semantic-table-spacing', 'Table row and cell relationships are preserved; custom baseline placement and row gaps are not reproduced.');
240
+ }
241
+
242
+ function emit(node, context, depth = 0) {
243
+ visit(node, depth); family(node);
244
+ if (active.has(node)) fail('unsupported-semantic-node', 'A mathematical tree contains a cycle.');
245
+ active.add(node);
246
+ try {
247
+ switch (node.type) {
248
+ case 'row': row(node.children, context, depth); break;
249
+ case 'glyph': {
250
+ const name = kind(node), attributes = {};
251
+ if (name === 'mo') {
252
+ if (node.class === 'open' || node.class === 'close') { attributes.fence = 'true'; attributes.form = node.class === 'open' ? 'prefix' : 'postfix'; }
253
+ else if (node.class === 'punct') attributes.separator = 'true';
254
+ else if (context.form) attributes.form = context.form;
255
+ if (node.large !== undefined) attributes.largeop = String(!!node.large);
256
+ if (node.limits) attributes.movablelimits = String(node.limits === 'display');
257
+ if (node.delimiter || node.delimiterSize || node.stretch) attributes.stretchy = 'true';
258
+ else attributes.stretchy = 'false';
259
+ if (node.delimiterSize) attributes.minsize = attributes.maxsize = em(node.delimiterSize);
260
+ }
261
+ atom(node, node.value, name, context, attributes); break;
262
+ }
263
+ case 'text': atom(node, node.value, ['op', 'bin', 'rel'].includes(node.class) ? 'mo' : 'mtext', context,
264
+ node.class === 'op' ? {form: 'prefix', movablelimits: String(node.limits === 'display')} : {}); break;
265
+ case 'space': open('mspace', {width: em(Math.max(0, node.width)), style: node.width < 0 ? 'margin-left:' + em(node.width) : undefined}); close('mspace'); break;
266
+ case 'scripts': scripts(node, context, depth); break;
267
+ case 'frac': {
268
+ const local = node.style ? styledContext(context, {mathStyle: node.style}) : context;
269
+ if (node.style) open('mstyle', {displaystyle: String(local.display), scriptlevel: String(local.level)});
270
+ if (node.left || node.right) { open('mrow'); fence(node.left, 'prefix', local); }
271
+ open('mfrac', {linethickness: node.bar === false ? '0' : node.barThickness === undefined ? undefined : em(node.barThickness)});
272
+ const child = local.display && local.level === 0 ? {...local, display: false} : scriptContext(local);
273
+ emit(node.num, child, depth + 1); emit(node.den, child, depth + 1); close('mfrac');
274
+ if (node.left || node.right) { fence(node.right, 'postfix', local); close('mrow'); }
275
+ if (node.style) close('mstyle');
276
+ if (node.align) warn('semantic-fraction-alignment', 'The fraction relationship is preserved; continued-fraction numerator alignment is left to the MathML host.');
277
+ break;
278
+ }
279
+ case 'root':
280
+ open(node.index ? 'mroot' : 'msqrt'); emit(node.body, context, depth + 1);
281
+ if (node.index) emit(node.index, {...context, display: false, level: 2}, depth + 1);
282
+ close(node.index ? 'mroot' : 'msqrt'); break;
283
+ case 'fence':
284
+ 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;
285
+ case 'accent': {
286
+ if (node.overlay) {
287
+ warn('semantic-overlay', 'An overlay uses the MathML 3 menclose extension; hosts implementing only Core may omit the cancellation or negation mark.');
288
+ const notation = node.value === '╲' ? 'downdiagonalstrike' : node.value === '╳' ? 'updiagonalstrike downdiagonalstrike' : node.value === '↗' ? 'updiagonalarrow' : node.value === '─' ? 'horizontalstrike' : 'updiagonalstrike';
289
+ open('menclose', {notation}); emit(node.base, context, depth + 1); close('menclose'); break;
290
+ }
291
+ const under = node.position === 'under', name = under ? 'munder' : 'mover';
292
+ open(name, {[under ? 'accentunder' : 'accent']: 'true'}); emit(node.base, {...context, movableLimits: false}, depth + 1);
293
+ token('mo', node.value, {stretchy: String(!!node.stretch)}, context); close(name); break;
294
+ }
295
+ case 'overunder': {
296
+ const name = node.over && node.under ? 'munderover' : node.under ? 'munder' : 'mover';
297
+ open(name, {accent: node.over ? 'false' : undefined, accentunder: node.under ? 'false' : undefined}); emit(node.base, {...context, movableLimits: false}, depth + 1);
298
+ if (node.under) emit(node.under, scriptContext(context), depth + 1);
299
+ if (node.over) emit(node.over, scriptContext(context), depth + 1);
300
+ close(name); break;
301
+ }
302
+ case 'table': table(node, context, depth); break;
303
+ case 'style': {
304
+ const local = styledContext(context, node), attributes = {'data-math-class': node.class};
305
+ if (node.mathStyle) { attributes.displaystyle = String(local.display); attributes.scriptlevel = String(local.level); }
306
+ let css = '';
307
+ if (node.absoluteSize !== undefined || node.size !== undefined) css += 'font-size:' + decimal(local.size / context.size) + 'em;';
308
+ if (node.color) css += 'color:' + node.color + ';';
309
+ if (node.background) css += 'background-color:' + node.background + ';';
310
+ if (node.border) css += 'border:0.04em solid ' + node.border + ';padding:' + em(node.padding ?? .2) + ';';
311
+ if (css) attributes.style = css;
312
+ open('mstyle', attributes);
313
+ if (node.tokenKind) {
314
+ atom({variant: local.variant}, node.tokenText, node.tokenKind, local);
315
+ } else if (node.operatorName) {
316
+ const value = plain(node.body, depth + 1, true);
317
+ if (value === null) {
318
+ warn('semantic-rich-operator', 'A styled or mixed-math operator name retains its nested structure instead of becoming one plain operator token.');
319
+ emit(node.body, local, depth + 1);
320
+ } else atom({variant: 'roman'}, value, 'mo', local, {form: 'prefix', movablelimits: String(node.limits === 'display')});
321
+ } else if (node.width !== undefined) {
322
+ warn('semantic-layout-adjustment', 'A TeX layout adjustment retains its mathematical content with a bounded presentation approximation.');
323
+ open('mpadded', {width: em(node.width)}); emit(node.body, local, depth + 1); close('mpadded');
324
+ } else if (node.class) {
325
+ const leaf = singleToken(node.body);
326
+ if (leaf) emit({...leaf, class: node.class}, local, depth + 1);
327
+ else {
328
+ warn('semantic-atom-class', 'A compound expression retains its mathematical children; its TeX atom class does not create a single MathML operator.');
329
+ emit(node.body, local, depth + 1);
330
+ }
331
+ } else emit(node.body, local, depth + 1);
332
+ close('mstyle'); break;
333
+ }
334
+ case 'phantom': {
335
+ const before = content;
336
+ if (node.mode === 'h' || node.mode === 'v') open('mpadded', node.mode === 'h' ? {height: '0', depth: '0'} : {width: '0'});
337
+ open('mphantom'); emit(node.body, {...context, phantom: true}, depth + 1); close('mphantom');
338
+ if (node.mode === 'h' || node.mode === 'v') close('mpadded');
339
+ content = before; break;
340
+ }
341
+ case 'smash':
342
+ open('mpadded', {height: node.mode === 'b' ? undefined : '0', depth: node.mode === 't' ? undefined : '0'});
343
+ emit(node.body, context, depth + 1); close('mpadded'); break;
344
+ case 'raise':
345
+ open('mpadded', {voffset: em(node.amount), height: node.height === undefined ? undefined : em(node.height), depth: node.depth === undefined ? undefined : em(node.depth)});
346
+ emit(node.body, context, depth + 1); close('mpadded'); break;
347
+ case 'rule':
348
+ warn('semantic-rule-presentation', 'A rule is represented as a decorative mathematical space; no additional mathematical relationship is inferred.');
349
+ open('mspace', {width: em(node.width), height: em(node.height), depth: em(node.depth), style: 'background-color:currentColor'}); close('mspace');
350
+ if (!context.phantom && !context.transparent && node.width > 0 && node.height + node.depth > 0) content++; break;
351
+ case 'link': {
352
+ if (context.inLink) fail('semantic-nested-link', 'Nested authored mathematical links cannot be represented as valid native HTML links.');
353
+ if (context.phantom) fail('semantic-hidden-link', 'An authored link inside phantom content cannot become an invisible native focus target.');
354
+ let url;
355
+ try { url = new URL(node.href); } catch { fail('unsafe-link', 'A mathematical link has an invalid address.'); }
356
+ if (!['http:', 'https:'].includes(url.protocol) || !/^https?:\/\/[^\s<>"'\\]+$/i.test(node.href))
357
+ fail('unsafe-link', 'A mathematical link must use an HTTP or HTTPS address.');
358
+ 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.');
359
+ metrics.links++;
360
+ open('mtext'); open('a', {xmlns: 'http://www.w3.org/1999/xhtml', href: node.href, title: node.href, target: '_blank', rel: 'noopener noreferrer'});
361
+ const before = content;
362
+ open('math', {xmlns: MATH_ML_NAMESPACE, display: 'inline'}); emit(node.body, {...context, inLink: true, display: false}, depth + 1);
363
+ if (content === before) fail('semantic-empty-link', 'An authored mathematical link has no visible content for native focus.');
364
+ close('math'); close('a'); close('mtext'); break;
365
+ }
366
+ default: fail('unsupported-semantic-node', 'Unsupported mathematical node for MathML.');
367
+ }
368
+ } finally { active.delete(node); }
369
+ }
370
+
371
+ let status;
372
+ try {
373
+ if (sourceOmitted) fail('resource-limit', 'This formula is too long for MathML. Its source was not embedded; retain the original input.');
374
+ if (options.error || safeSource?.error) throw options.error || safeSource.error;
375
+ if (!tree) fail('unsupported-semantic-node', 'A parsed mathematical expression is required.');
376
+ emit(tree, {display: !!options.displayMode, level: 0, size: 1, variant: 'normal', inLink: false});
377
+ status = diagnostics.length ? 'presentation-fallback' : 'complete';
378
+ } catch (cause) {
379
+ const error = mathDiagnostic(cause);
380
+ if (sourceOmitted) error.sourceOmitted = true;
381
+ diagnostics.length = 0; diagnostics.push(error);
382
+ status = 'refused'; metrics.links = 0;
383
+ parts = ['<merror><mtext>Formula could not be represented as MathML.</mtext></merror>'];
384
+ }
385
+ const presentation = parts.join('');
386
+ const annotation = sourceOmitted ? '' : encoding === 'application/x-tex' ?
387
+ '<annotation encoding="application/x-tex">' + mathMLXML(source) + '</annotation>' :
388
+ '<annotation encoding="text/plain">' + mathMLXML(safeSource.alternative) + '</annotation>' +
389
+ '<annotation encoding="application/x-rapier-tex-utf16">' + utf16 + '</annotation>';
390
+ const wrap = body => '<math xmlns="' + MATH_ML_NAMESPACE + '" display="' + (options.displayMode ? 'block' : 'inline') +
391
+ '" data-rapier-mathml-status="' + status + '"' + (sourceOmitted ? ' data-math-source-omitted="true"' : '') +
392
+ '><semantics>' + body + annotation + '</semantics></math>';
393
+ // Source admission bounds escaping independently of the presentation budget:
394
+ // at most 6M XML-escaped source, or 6M alternative plus 4M UTF-16 carrier.
395
+ let mathml = wrap(presentation);
396
+ if (mathml.length > 16 * 1024 * 1024) {
397
+ status = 'refused'; metrics.links = 0;
398
+ diagnostics.length = 0;
399
+ diagnostics.push({code: 'resource-limit', offset: 0, message: 'Complete MathML exceeds its output budget.'});
400
+ mathml = wrap('<merror><mtext>Formula could not be represented as MathML.</mtext></merror>');
401
+ }
402
+ metrics.outputCodeUnits = mathml.length;
403
+ return {mathml, status, errors: diagnostics, metrics, source: sourceInfo};
404
+ }
405
+
406
+ import {mathDiagnostic} from './source.js';
407
+ import {mathStyledCodePoint} from './variants.js';
408
+ export {mathML};