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.
- package/README.md +15 -5
- package/dist/accessible.css +6 -0
- package/dist/accessible.d.ts +10 -0
- package/dist/accessible.mjs +18 -0
- package/dist/classic.d.ts +8 -2
- package/dist/combined.d.ts +4 -0
- package/dist/combined.mjs +2 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.mjs +6 -2980
- package/dist/integration.d.ts +3 -1
- package/dist/integration.mjs +13 -19
- package/dist/markdown-it.mjs +7 -4
- package/dist/mathml.d.ts +5 -0
- package/dist/mathml.mjs +3 -0
- package/dist/rapier-math.js +674 -173
- package/dist/rehype.mjs +13 -3
- package/docs/api.md +42 -4
- package/docs/math-components.json +6 -5
- package/docs/math-resources.json +150 -54
- package/docs/semantics.md +228 -0
- package/examples/README.md +10 -0
- package/examples/accessible.html +27 -0
- package/examples/accessible.mjs +42 -0
- package/examples/semantic.mjs +11 -0
- package/package.json +16 -2
- package/src/math/api.js +16 -55
- package/src/math/browser.js +4 -0
- package/src/math/classic.js +7 -0
- package/src/math/combined.js +13 -0
- package/src/math/fallbacks.js +5 -0
- package/src/math/font.js +3 -0
- package/src/math/layout.js +56 -53
- package/src/math/mathml.js +408 -0
- package/src/math/package-build.mjs +24 -11
- package/src/math/package-layout.mjs +3 -0
- package/src/math/package-readme.mjs +14 -4
- package/src/math/parser.js +36 -20
- package/src/math/responsive.js +4 -0
- package/src/math/semantic-api.js +12 -0
- package/src/math/source.js +67 -0
- package/src/math/symbols.js +6 -3
- package/src/math/variants.js +41 -0
- package/src/tools/build-math.mjs +18 -10
- package/tests/adoption.mjs +34 -0
- package/tests/check.mjs +13 -5
- package/tests/semantics.mjs +340 -0
- package/tests/verify.mjs +3 -3
|
@@ -1,14 +1,27 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
//
|
|
2
|
+
// Native entries execute the carried source modules directly. The complete
|
|
3
|
+
// classic distribution concatenates these same owners without module syntax.
|
|
4
|
+
export function mathClassicSource(text) {
|
|
5
|
+
return text.replace(/^import \{[^\n]+\} from '\.\/[\w-]+\.js';\n/gm, '')
|
|
6
|
+
.replace(/^export \{[^\n]+\};\n/gm, '').trimEnd();
|
|
7
|
+
}
|
|
3
8
|
|
|
4
|
-
export function
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
9
|
+
export function mathModules(version) {
|
|
10
|
+
return new Map([
|
|
11
|
+
['dist/index.mjs', `// SPDX-License-Identifier: MIT
|
|
12
|
+
import {parseMathTex as parse} from '../src/math/parser.js';
|
|
13
|
+
import {renderMath as render, mathRenderToString as renderToString} from '../src/math/api.js';
|
|
14
|
+
import {mathFit as fit, mathObserve as observe} from '../src/math/browser.js';
|
|
15
|
+
const version = ${JSON.stringify(version)};
|
|
16
|
+
export {version, parse, render, renderToString, fit, observe};
|
|
17
|
+
export default Object.freeze({version, parse, render, renderToString, fit, observe});
|
|
18
|
+
`],
|
|
19
|
+
['dist/mathml.mjs', `// SPDX-License-Identifier: MIT
|
|
20
|
+
export {parseMathTex as parse} from '../src/math/parser.js';
|
|
21
|
+
export {mathToMathML as toMathML} from '../src/math/semantic-api.js';
|
|
22
|
+
`],
|
|
23
|
+
['dist/combined.mjs', `// SPDX-License-Identifier: MIT
|
|
24
|
+
export {mathRenderWithMathML as renderWithMathML} from '../src/math/combined.js';
|
|
25
|
+
`],
|
|
26
|
+
]);
|
|
14
27
|
}
|
|
@@ -5,6 +5,9 @@ export const MATH_CLASSIC = 'dist/rapier-math.js';
|
|
|
5
5
|
export function mathPackagePath(file) {
|
|
6
6
|
const owners = {
|
|
7
7
|
'math/README.md': 'docs/api.md',
|
|
8
|
+
'math/SEMANTICS.md': 'docs/semantics.md',
|
|
9
|
+
'math/semantic-verify.mjs': 'tests/semantics.mjs',
|
|
10
|
+
'math/accessible.css': 'dist/accessible.css',
|
|
8
11
|
'math/FONT-SOURCE.md': 'docs/font-source.md',
|
|
9
12
|
'math/package-check.mjs': 'tests/check.mjs',
|
|
10
13
|
'math/package-verify.mjs': 'tests/verify.mjs',
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
export function mathReadme(resources) {
|
|
3
3
|
return `# Rapier Math
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Offline TeX formulas as SVG or structured MathML. Embedded Latin Modern outlines for SVG; font-free native MathML. Synchronous, with no runtime downloads.
|
|
6
6
|
|
|
7
7
|
## Use
|
|
8
8
|
|
|
@@ -17,16 +17,26 @@ const svg = renderToString(String.raw\`\\frac{a}{b}\`);
|
|
|
17
17
|
|
|
18
18
|
For a browser script, load [${resources.packageBundle}](${resources.packageBundle}) and use
|
|
19
19
|
\`globalThis.RapierMath\`. The native ESM entry is [dist/index.mjs](dist/index.mjs).
|
|
20
|
-
|
|
20
|
+
For one-file copying or inline-script embedding, use the classic file above. The native
|
|
21
|
+
ESM entry imports relative \`src/math/\` modules: install/serve the whole package or bundle
|
|
22
|
+
that import; copying only \`dist/index.mjs\` is insufficient. A CDN must retain that graph
|
|
23
|
+
or bundle it. Formula rendering stays synchronous and offline after its chosen script
|
|
24
|
+
or module graph has loaded.
|
|
25
|
+
|
|
26
|
+
The SVG entry and classic script include the font. Use \`rapier-math/mathml\` for font-free MathML,
|
|
27
|
+
\`rapier-math/combined\` for one-parse SVG and MathML, or \`rapier-math/accessible\` with its stylesheet
|
|
28
|
+
for host composition. All return synchronously. Type declarations accompany the runtime files.
|
|
21
29
|
|
|
22
30
|
- [API and integration guide](docs/api.md)
|
|
31
|
+
- [MathML, accessibility and source contracts](docs/semantics.md)
|
|
23
32
|
- [Runnable examples](examples/README.md)
|
|
24
33
|
- [Font source and regeneration](docs/font-source.md)
|
|
25
34
|
|
|
26
35
|
## Develop
|
|
27
36
|
|
|
28
|
-
The
|
|
29
|
-
\`src
|
|
37
|
+
The classic script and native entry points live in \`dist/\`. Native entries import the editable
|
|
38
|
+
modules in \`src/math/\` directly, sharing one parser without a duplicate generated renderer. Build
|
|
39
|
+
tools live in \`src/tools/\`. Optional adapters have one source copy in \`dist/\`. Examples, documentation and tests each
|
|
30
40
|
have their own directory. Only the current release is kept in this checkout.
|
|
31
41
|
|
|
32
42
|
From a repository checkout, run \`node tests/check.mjs\` and \`node tests/verify.mjs\` to check the package and rebuild its exact bytes.
|
package/src/math/parser.js
CHANGED
|
@@ -44,7 +44,7 @@ function mathTexTokens(source, offset = 0) {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
const MATH_TEX_VARIANTS = Object.freeze({
|
|
47
|
-
mathrm: 'roman', mathnormal: 'normal', mathit: 'italic', mathbf: 'bold', boldsymbol: 'bold-italic', bm: 'bold-italic',
|
|
47
|
+
mathrm: 'roman', mathnormal: 'normal', mathit: 'italic', mathbf: 'bold', boldsymbol: 'bold-italic', bm: 'bold-italic', pmb: 'bold-italic',
|
|
48
48
|
mathbb: 'double-struck', mathbbm: 'double-struck', mathbbmss: 'double-struck', mathbbmtt: 'double-struck', mathds: 'double-struck',
|
|
49
49
|
Bbb: 'double-struck', mathcal: 'script', mathscr: 'script', mathfrak: 'fraktur', frak: 'fraktur',
|
|
50
50
|
mathsf: 'sans-serif', mathss: 'sans-serif', mathtt: 'monospace', mathbfit: 'bold-italic',
|
|
@@ -113,9 +113,10 @@ class MathTexParser {
|
|
|
113
113
|
this.reserveParts(1);
|
|
114
114
|
return {type, ...fields};
|
|
115
115
|
}
|
|
116
|
-
reserveParts(count, token
|
|
116
|
+
reserveParts(count, token) {
|
|
117
|
+
// Peeking only on refusal: a skipping peek here would consume the spaces that \ce reads.
|
|
117
118
|
if (!Number.isSafeInteger(count) || count < 0 || this.budget.nodes + count > 50000)
|
|
118
|
-
this.error('resource-limit', 'This formula has too many parts to render safely.', token);
|
|
119
|
+
this.error('resource-limit', 'This formula has too many parts to render safely.', token || this.rawPeek());
|
|
119
120
|
this.budget.nodes += count;
|
|
120
121
|
}
|
|
121
122
|
row(children) { return this.node('row', {children: children.filter(Boolean)}); }
|
|
@@ -175,7 +176,7 @@ class MathTexParser {
|
|
|
175
176
|
for (;;) {
|
|
176
177
|
const token = this.peek();
|
|
177
178
|
if (token.kind === 'eof' || stop(token)) break;
|
|
178
|
-
if (token.kind === 'command' && (MATH_TEX_DECLARATIONS
|
|
179
|
+
if (token.kind === 'command' && (Object.hasOwn(MATH_TEX_DECLARATIONS, token.value) || token.value === 'color')) {
|
|
179
180
|
this.take();
|
|
180
181
|
const fields = token.value === 'color' ? {color: this.readColor()} : MATH_TEX_DECLARATIONS[token.value];
|
|
181
182
|
children.push(this.node('style', {...fields, body: this.nested(() => this.parseRow(stop, allowFraction))}));
|
|
@@ -208,7 +209,9 @@ class MathTexParser {
|
|
|
208
209
|
const atom = this.parseAtom();
|
|
209
210
|
if (atom) children.push(this.readScripts(atom));
|
|
210
211
|
}
|
|
211
|
-
|
|
212
|
+
// An equation tag follows its equation wherever \tag was written.
|
|
213
|
+
const tags = children.filter(child => child?.semanticRole === 'tag');
|
|
214
|
+
return this.row(tags.length ? [...children.filter(child => child?.semanticRole !== 'tag'), ...tags] : children);
|
|
212
215
|
}
|
|
213
216
|
readScripts(base) {
|
|
214
217
|
let result = base;
|
|
@@ -224,8 +227,11 @@ class MathTexParser {
|
|
|
224
227
|
if (result.type !== 'scripts') result = this.node('scripts', {base: result, limits: result.limits});
|
|
225
228
|
const key = token.value === '_' ? 'sub' : 'sup';
|
|
226
229
|
if (token.value === "'") {
|
|
227
|
-
|
|
228
|
-
|
|
230
|
+
// Runs of primes use the font's joined double, triple and quadruple prime glyphs.
|
|
231
|
+
let count = 1;
|
|
232
|
+
while (this.is("'")) { this.take(); count++; }
|
|
233
|
+
const primes = [];
|
|
234
|
+
for (; count > 0; count -= 4) primes.push(this.node('glyph', {value: '′″‴⁗'[Math.min(count, 4) - 1], class: 'ord', variant: 'roman'}));
|
|
229
235
|
if (this.is('^')) { this.take(); primes.push(this.argument()); }
|
|
230
236
|
if (result.sup) this.error('duplicate-script', 'A base cannot have two superscripts.', token);
|
|
231
237
|
result.sup = this.row(primes);
|
|
@@ -326,7 +332,7 @@ class MathTexParser {
|
|
|
326
332
|
if (token.kind === 'command') {
|
|
327
333
|
if (token.value === '{' || token.value === '}') return token.value;
|
|
328
334
|
if (token.value === '|') return '‖';
|
|
329
|
-
const symbol = MATH_SYMBOLS[token.value];
|
|
335
|
+
const symbol = Object.hasOwn(MATH_SYMBOLS, token.value) ? MATH_SYMBOLS[token.value] : null;
|
|
330
336
|
if (symbol && (['open', 'close'].includes(symbol.class) || /^(vert|Vert|backslash|slash|[uUdD].*arrow)$/.test(token.value))) return symbol.value;
|
|
331
337
|
}
|
|
332
338
|
if (token.kind === 'char' && '.()[]{}|/<>‖⌈⌉⌊⌋⟨⟩↑↓↕⇑⇓⇕'.includes(token.value))
|
|
@@ -340,7 +346,7 @@ class MathTexParser {
|
|
|
340
346
|
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})])});
|
|
341
347
|
// amsmath \dots: centred dots before a binary operator, a relation or an integral, low dots otherwise.
|
|
342
348
|
if (name === 'dots') {
|
|
343
|
-
const next = this.rawPeek(), after = next.kind === 'command' ? MATH_SYMBOLS[next.value] : null;
|
|
349
|
+
const next = this.rawPeek(), after = next.kind === 'command' && Object.hasOwn(MATH_SYMBOLS, next.value) ? MATH_SYMBOLS[next.value] : null;
|
|
344
350
|
const centred = next.kind === 'char' ? '+-=<>*:'.includes(next.value) : !!after && (['bin', 'rel'].includes(after.class) || /^(?:int|iint|iiint|oint)$/.test(next.value));
|
|
345
351
|
if (centred) return this.node('glyph', MATH_SYMBOLS.cdots);
|
|
346
352
|
}
|
|
@@ -406,7 +412,7 @@ class MathTexParser {
|
|
|
406
412
|
if (name === 'operatorname') {
|
|
407
413
|
const starred = this.is('*'); if (starred) this.take();
|
|
408
414
|
const body = this.subparse(this.rawArgument(), true, 'roman');
|
|
409
|
-
return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never'});
|
|
415
|
+
return this.node('style', {body, variant: 'roman', class: 'op', limits: starred ? 'display' : 'never', operatorName: true});
|
|
410
416
|
}
|
|
411
417
|
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'} : {})});
|
|
412
418
|
if (name === 'overset' || name === 'underset' || name === 'stackrel' || name === 'stackbin') {
|
|
@@ -458,7 +464,7 @@ class MathTexParser {
|
|
|
458
464
|
this.colors[colorName] = this.color(value, model, token); return null;
|
|
459
465
|
}
|
|
460
466
|
if (name === 'boxed' || name === 'fbox') return this.node('style', {body: name === 'fbox' ? this.subparse(this.rawArgument(), true, 'roman') : this.argument(), border: 'currentColor', padding: .25});
|
|
461
|
-
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});
|
|
467
|
+
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});
|
|
462
468
|
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}); }
|
|
463
469
|
if (['newcommand', 'renewcommand', 'providecommand', 'def', 'gdef', 'DeclareMathOperator', 'let'].includes(name)) { this.define(name, token); return null; }
|
|
464
470
|
if (name === 'require') {
|
|
@@ -479,14 +485,14 @@ class MathTexParser {
|
|
|
479
485
|
if (name === 'tag') {
|
|
480
486
|
const starred = this.is('*'); if (starred) this.take();
|
|
481
487
|
const body = this.subparse(this.rawArgument(), true);
|
|
482
|
-
return this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]);
|
|
488
|
+
return {...this.row([this.node('space', {width: 2}), starred ? body : this.node('fence', {left: '(', right: ')', body})]), semanticRole: 'tag'};
|
|
483
489
|
}
|
|
484
490
|
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})]);
|
|
485
491
|
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()])})]);
|
|
486
492
|
if (name === 'bmod') return this.node('text', {value: 'mod', variant: 'roman', class: 'bin'});
|
|
487
|
-
if (name === 'ce') return this.chemistry(this.rawArgument());
|
|
488
|
-
if (name === 'pu') return this.units(this.rawArgument());
|
|
489
|
-
if (this.physicsCommand(name)) return this.physics(name, token);
|
|
493
|
+
if (name === 'ce') return {...this.chemistry(this.rawArgument()), semanticRole: 'chemistry'};
|
|
494
|
+
if (name === 'pu') return {...this.units(this.rawArgument()), semanticRole: 'units'};
|
|
495
|
+
if (this.physicsCommand(name)) return {...this.physics(name, token), semanticRole: 'physics'};
|
|
490
496
|
if (name === 'mmlToken') return this.mathmlToken(token);
|
|
491
497
|
if (name === 'unicode' || name === 'char') return this.character(name, token);
|
|
492
498
|
if (name === 'TeX' || name === 'LaTeX') return this.node('text', {value: name, variant: 'roman'});
|
|
@@ -711,7 +717,7 @@ class MathTexParser {
|
|
|
711
717
|
if (!next || next.kind !== 'char' || !(next.value === '#' || (/^[1-9]$/.test(next.value) && Number(next.value) <= params.length)))
|
|
712
718
|
this.error('invalid-macro', 'A replacement refers to a missing macro parameter.', body[i - 1]);
|
|
713
719
|
}
|
|
714
|
-
const existing = this.macro(macroName) || MATH_SYMBOLS
|
|
720
|
+
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);
|
|
715
721
|
if (name === 'providecommand' && existing) return;
|
|
716
722
|
if (name === 'newcommand' && existing) this.error('duplicate-macro', '\\' + macroName + ' is already defined.', token);
|
|
717
723
|
this.scopes[name === 'gdef' ? 0 : this.scopes.length - 1][macroName] = {params, prefix, body, optional};
|
|
@@ -844,7 +850,7 @@ class MathTexParser {
|
|
|
844
850
|
if ([...letters].length !== 1) this.error('invalid-accent', 'A text accent needs one character.', token);
|
|
845
851
|
value += (letters + marks[name]).normalize('NFC'); continue;
|
|
846
852
|
}
|
|
847
|
-
if (MATH_SYMBOLS
|
|
853
|
+
if (Object.hasOwn(MATH_SYMBOLS, name) && !MATH_SYMBOLS[name].large) { value += MATH_SYMBOLS[name].value; continue; }
|
|
848
854
|
flush();
|
|
849
855
|
const body = this.command(token);
|
|
850
856
|
if (body) children.push(body);
|
|
@@ -932,7 +938,13 @@ class MathTexParser {
|
|
|
932
938
|
const next = this.peek(false);
|
|
933
939
|
if (next.kind === 'eof' || stop(next)) break;
|
|
934
940
|
const token = this.take(false);
|
|
935
|
-
if (token.kind === 'space') {
|
|
941
|
+
if (token.kind === 'space') {
|
|
942
|
+
spaced = true; subAllowed = false; moleculeParts = 0;
|
|
943
|
+
// An operator or arrow already carries its own spacing; a separating space adds none beside it.
|
|
944
|
+
const after = this.rawPeek(false), before = children.at(-1)?.class;
|
|
945
|
+
if (before !== 'bin' && before !== 'rel' && !(after.kind === 'char' && /^[+<=-]$/.test(after.value))) children.push(this.node('space', {width: 3 / 18}));
|
|
946
|
+
continue;
|
|
947
|
+
}
|
|
936
948
|
if (token.kind === 'command') {
|
|
937
949
|
if (token.value === 'bond') {
|
|
938
950
|
const value = this.plainArgument(), bonds = {'-': '−', '=': '=', '#': '≡', '~': '∼', '->': '→', '<-': '←', '...': '⋯'};
|
|
@@ -988,7 +1000,8 @@ class MathTexParser {
|
|
|
988
1000
|
while (this.rawPeek(false).kind === 'char' && /^[<=>-]$/.test(this.rawPeek(false).value) && arrow.length < 5) arrow += this.rawTake(false).value;
|
|
989
1001
|
const arrows = {'->': '→', '<-': '←', '<->': '↔', '<=>': '⇌', '=>': '⇒', '<=': '⇐', '<<=>': '⇋', '<=>>': '⇌'};
|
|
990
1002
|
if (arrows[arrow]) {
|
|
991
|
-
|
|
1003
|
+
// Only an adjacent bracket labels the arrow; a peek that skips spaces would drop the next one.
|
|
1004
|
+
const over = this.rawPeek(false).value === '[' ? this.optionalRaw() : null, under = over && this.rawPeek(false).value === '[' ? this.optionalRaw() : null;
|
|
992
1005
|
const base = this.literal(arrows[arrow], {class: 'rel', variant: 'roman', stretch: true});
|
|
993
1006
|
children.push(over || under ? this.node('overunder', {base, ...(over ? {over: this.chemistry(over)} : {}), ...(under ? {under: this.chemistry(under)} : {}), class: 'rel'}) : base);
|
|
994
1007
|
spaced = true; subAllowed = false; moleculeParts = 0; continue;
|
|
@@ -1035,7 +1048,7 @@ class MathTexParser {
|
|
|
1035
1048
|
if (!match || !variants.has(match[1])) this.error('unsupported-attribute', 'Only a mathematical font variant is supported on a token.', token);
|
|
1036
1049
|
variant = match[1] === 'normal' ? 'roman' : match[1] === 'bold-sans-serif' ? 'sans-serif-bold' : match[1];
|
|
1037
1050
|
}
|
|
1038
|
-
return this.node('style', {variant, body: kind === 'mtext' ? this.node('text', {value: text, variant}) : this.row([...text].map(value => this.literal(value, {variant})))});
|
|
1051
|
+
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})))});
|
|
1039
1052
|
}
|
|
1040
1053
|
character(name, token) {
|
|
1041
1054
|
let raw;
|
|
@@ -1062,3 +1075,6 @@ function parseMathTex(source) {
|
|
|
1062
1075
|
if (source.length > 1000000) throw new MathTexError('resource-limit', 'This formula is too long to render safely.');
|
|
1063
1076
|
return new MathTexParser(source).parse();
|
|
1064
1077
|
}
|
|
1078
|
+
|
|
1079
|
+
import {MATH_SYMBOLS, MATH_NAMED_OPERATORS, MATH_LIMIT_OPERATORS} from './symbols.js';
|
|
1080
|
+
export {parseMathTex};
|
package/src/math/responsive.js
CHANGED
|
@@ -249,3 +249,7 @@ function mathResponsiveLayout(n,c,width,natural=mathLayout(n,c)) {
|
|
|
249
249
|
}
|
|
250
250
|
return mathFitBox(natural,width,c);
|
|
251
251
|
}
|
|
252
|
+
|
|
253
|
+
import {MATH_FONT} from './font.js';
|
|
254
|
+
import {mathNumber, mathEscape, mathScale, mathScreenStroke, mathConstant, mathScreenRelayout, mathCompose, mathSpace, mathRow, mathFraction, mathFenceBoxes, mathLayout} from './layout.js';
|
|
255
|
+
export {mathResponsiveLayout, mathInkWidth};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
function mathSemanticPrepared(prepared, options = {}) {
|
|
3
|
+
const {text, safe, tree, error} = prepared;
|
|
4
|
+
return mathML(tree, text, safe, {displayMode: !!options?.displayMode, error});
|
|
5
|
+
}
|
|
6
|
+
function mathToMathML(source, options = {}) {
|
|
7
|
+
return mathSemanticPrepared(mathPrepare(source), options);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
import {mathPrepare} from './source.js';
|
|
11
|
+
import {mathML} from './mathml.js';
|
|
12
|
+
export {mathSemanticPrepared, mathToMathML};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Source custody and bounded diagnostics shared by SVG and MathML.
|
|
3
|
+
function mathSourceUTF16(source) {
|
|
4
|
+
// Four ASCII hex digits retain each original UTF-16 code unit across XML/HTML hosts.
|
|
5
|
+
const encoded=[],parts=[];
|
|
6
|
+
for(let i=0;i<source.length;i++) {
|
|
7
|
+
parts.push(source.charCodeAt(i).toString(16).padStart(4,'0'));
|
|
8
|
+
if(parts.length===1024) {encoded.push(parts.join(''));parts.length=0;}
|
|
9
|
+
}
|
|
10
|
+
encoded.push(parts.join(''));
|
|
11
|
+
return encoded.join('');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function mathSourceAlternative(source) {
|
|
15
|
+
const alternatives=[],parts=[];
|
|
16
|
+
let first=-1,kept=0,hasCR=false;
|
|
17
|
+
for(let i=0;i<source.length;i++) {
|
|
18
|
+
const code=source.charCodeAt(i);
|
|
19
|
+
if(code===13)hasCR=true;
|
|
20
|
+
if(code>=0xd800 && code<=0xdbff && i+1<source.length) {
|
|
21
|
+
const next=source.charCodeAt(i+1);
|
|
22
|
+
if(next>=0xdc00 && next<=0xdfff) {i++;continue;}
|
|
23
|
+
}
|
|
24
|
+
if((code>=0x20 && code<=0xd7ff) || (code>=0xe000 && code<=0xfffd) || code===9 || code===10 || code===13)continue;
|
|
25
|
+
if(first<0)first=i;
|
|
26
|
+
if(i>kept)parts.push(source.slice(kept,i));
|
|
27
|
+
parts.push('\\u'+code.toString(16).toUpperCase().padStart(4,'0'));kept=i+1;
|
|
28
|
+
// Flatten small batches instead of retaining one rope node per bad code unit.
|
|
29
|
+
if(parts.length>=1024) {alternatives.push(parts.join(''));parts.length=0;}
|
|
30
|
+
}
|
|
31
|
+
if(first<0)return {alternative:source,...(hasCR?{utf16:mathSourceUTF16(source)}:{})};
|
|
32
|
+
parts.push(source.slice(kept));alternatives.push(parts.join(''));
|
|
33
|
+
return {alternative:alternatives.join(''),utf16:mathSourceUTF16(source),error:{code:'invalid-source-character',offset:first,
|
|
34
|
+
message:'A source character cannot be embedded in XML. The text alternative shows Unicode escapes; the UTF-16 carrier keeps the original source.'}};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function mathAdmitSource(text) {
|
|
38
|
+
// Reject before scanning, escaping, parsing or constructing a source carrier.
|
|
39
|
+
return text.length>1000000?{alternative:'Formula source omitted: source limit exceeded.',error:{
|
|
40
|
+
code:'resource-limit',offset:0,sourceOmitted:true,
|
|
41
|
+
message:'This formula is too long to render safely. Its source was not embedded; retain the original input.'
|
|
42
|
+
}}:mathSourceAlternative(text);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function mathDiagnostic(cause) {
|
|
46
|
+
const message=String(cause?.message ?? cause),code=cause?.code,rawCommand=cause?.command;
|
|
47
|
+
const error={code:typeof code==='string'?code:'invalid-tex',message:message.length>1024?message.slice(0,1024).replace(/[\ud800-\udbff]$/,'')+'…':message,
|
|
48
|
+
offset:Number.isFinite(cause?.offset)?cause.offset:0};
|
|
49
|
+
if(message.length>1024 || cause?.messageTruncated)error.messageTruncated=true;
|
|
50
|
+
if(cause?.sourceOmitted)error.sourceOmitted=true;
|
|
51
|
+
if(rawCommand!==undefined) {
|
|
52
|
+
const command=String(rawCommand);
|
|
53
|
+
error.command=command.slice(0,128).replace(/[\ud800-\udbff]$/,'');
|
|
54
|
+
if(command.length>128 || cause.commandTruncated)error.commandTruncated=true;
|
|
55
|
+
}
|
|
56
|
+
return error;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function mathPrepare(source) {
|
|
60
|
+
const text = String(source ?? ''), safe = mathAdmitSource(text);
|
|
61
|
+
let tree, error = safe.error;
|
|
62
|
+
if (!error) try { tree = parseMathTex(text); } catch (cause) { error = mathDiagnostic(cause); }
|
|
63
|
+
return {text, safe, tree, error};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
import {parseMathTex} from './parser.js';
|
|
67
|
+
export {mathDiagnostic, mathPrepare, mathSourceUTF16};
|
package/src/math/symbols.js
CHANGED
|
@@ -18,7 +18,7 @@ varGamma=Γ varDelta=Δ varTheta=Θ varLambda=Λ varXi=Ξ varPi=Π varSigma=Σ v
|
|
|
18
18
|
aleph=ℵ beth=ℶ gimel=ℷ daleth=ℸ ell=ℓ hbar=ℏ hslash=ℏ imath=𝚤 jmath=𝚥
|
|
19
19
|
Re=ℜ Im=ℑ wp=℘ partial=∂ nabla=∇ infty=∞ emptyset=∅ varnothing=∅ complement=∁
|
|
20
20
|
top=⊤ bot=⊥ forall=∀ exists=∃ nexists=∄ neg/lnot=¬ angle=∠ measuredangle=∡ sphericalangle=∢
|
|
21
|
-
triangle=△ blacktriangle=▴ triangledown=▽ blacktriangledown=▾ square/Box=□ blacksquare=■ Diamond=◇ blacklozenge=◆ lozenge=◊
|
|
21
|
+
triangle/vartriangle=△ blacktriangle=▴ triangledown=▽ blacktriangledown=▾ square/Box=□ blacksquare=■ Diamond=◇ blacklozenge=◆ lozenge=◊
|
|
22
22
|
clubsuit=♣ diamondsuit=♢ heartsuit=♡ spadesuit=♠ checkmark=✓ maltese=✠ yen=¥ pounds=£ euro=€
|
|
23
23
|
S=§ P=¶ copyright=© circledR=® circledS=Ⓢ mho=℧ Finv=Ⅎ Game=⅁ eth=ð
|
|
24
24
|
prime=′ backprime=‵ doubleprime=″ tripleprime=‴ degree=° flat=♭ natural=♮ sharp=♯
|
|
@@ -83,8 +83,8 @@ intclockwise=∱ varointclockwise=∲ ointctrclockwise=∳ sumint=⨋
|
|
|
83
83
|
`, {large: true, limits: 'never', variant: 'roman'});
|
|
84
84
|
MATH_SYMBOLS.intop = Object.freeze({...MATH_SYMBOLS.intop, limits: 'display'});
|
|
85
85
|
MATH_SYMBOLS.smallint = Object.freeze({...MATH_SYMBOLS.smallint, large: false});
|
|
86
|
-
mathSymbolGroup('open', 'langle=⟨ lbrace={ lgroup=⟮ lbrack=[ lfloor=⌊ lceil=⌈ lvert=| lVert=‖ lmoustache=⎰', {variant: 'roman'});
|
|
87
|
-
mathSymbolGroup('close', 'rangle=⟩ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱', {variant: 'roman'});
|
|
86
|
+
mathSymbolGroup('open', 'langle=⟨ lbrace={ lgroup=⟮ lbrack=[ lfloor=⌊ lceil=⌈ lvert=| lVert=‖ lmoustache=⎰ llbracket=⟦ ulcorner=⌜ llcorner=⌞', {variant: 'roman'});
|
|
87
|
+
mathSymbolGroup('close', 'rangle=⟩ rbrace=} rgroup=⟯ rbrack=] rfloor=⌋ rceil=⌉ rvert=| rVert=‖ rmoustache=⎱ rrbracket=⟧ urcorner=⌝ lrcorner=⌟', {variant: 'roman'});
|
|
88
88
|
mathSymbolGroup('ord', 'vert=| Vert=‖ backslash=∖ slash=/', {variant: 'roman'});
|
|
89
89
|
mathSymbolGroup('inner', 'dotsc=… cdots=⋯ dotsb=⋯ dotsm=⋯ dotsi=⋯ dotso=… ddots=⋱ mathellipsis=…', {variant: 'roman'});
|
|
90
90
|
mathSymbolGroup('ord', 'vdots=⋮', {variant: 'roman'});
|
|
@@ -96,3 +96,6 @@ for (const [name, symbol] of Object.entries(MATH_SYMBOLS)) {
|
|
|
96
96
|
}
|
|
97
97
|
const MATH_NAMED_OPERATORS = new Set(('arccos arcsin arctan arccot arcsec arccsc cos cosh cot coth csc csch sec sech sin sinh tan tanh exp log ln lg lb det dim gcd hom ker arg deg Pr erf erfc mod').split(' '));
|
|
98
98
|
const MATH_LIMIT_OPERATORS = new Set(('lim limsup liminf sup inf max min injlim projlim varlimsup varliminf varinjlim varprojlim').split(' '));
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
export {MATH_SYMBOLS, MATH_NAMED_OPERATORS, MATH_LIMIT_OPERATORS};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Unicode mathematical alphabets shared by SVG and MathML. No font lookup.
|
|
3
|
+
const MATH_STYLED_RANGES = {
|
|
4
|
+
italic: [0x1d434, 0x1d44e, null], bold: [0x1d400, 0x1d41a, 0x1d7ce],
|
|
5
|
+
'bold-italic': [0x1d468, 0x1d482, null], script: [0x1d49c, 0x1d4b6, null],
|
|
6
|
+
'bold-script': [0x1d4d0, 0x1d4ea, null], fraktur: [0x1d504, 0x1d51e, null],
|
|
7
|
+
'bold-fraktur': [0x1d56c, 0x1d586, null], 'double-struck': [0x1d538, 0x1d552, 0x1d7d8],
|
|
8
|
+
'sans-serif': [0x1d5a0, 0x1d5ba, 0x1d7e2], 'sans-serif-bold': [0x1d5d4, 0x1d5ee, 0x1d7ec],
|
|
9
|
+
'sans-serif-italic': [0x1d608, 0x1d622, null], 'sans-serif-bold-italic': [0x1d63c, 0x1d656, null],
|
|
10
|
+
monospace: [0x1d670, 0x1d68a, 0x1d7f6],
|
|
11
|
+
};
|
|
12
|
+
const MATH_STYLED_LEGACY = {
|
|
13
|
+
italic: {104: 0x210e},
|
|
14
|
+
script: {66:0x212c,69:0x2130,70:0x2131,72:0x210b,73:0x2110,76:0x2112,77:0x2133,82:0x211b,101:0x212f,103:0x210a,111:0x2134},
|
|
15
|
+
fraktur: {67:0x212d,72:0x210c,73:0x2111,82:0x211c,90:0x2128},
|
|
16
|
+
'double-struck': {67:0x2102,72:0x210d,78:0x2115,80:0x2119,81:0x211a,82:0x211d,90:0x2124},
|
|
17
|
+
};
|
|
18
|
+
const MATH_STYLED_GREEK = {bold:0x1d6a8, italic:0x1d6e2, 'bold-italic':0x1d71c, 'sans-serif-bold':0x1d756, 'sans-serif-bold-italic':0x1d790};
|
|
19
|
+
const MATH_STYLED_GREEK_SPECIAL = [0x2207,0x2202,0x3f5,0x3d1,0x3f0,0x3d5,0x3f1,0x3d6];
|
|
20
|
+
function mathStyledCodePoint(cp, variant) {
|
|
21
|
+
if (variant === 'normal') variant = 'italic';
|
|
22
|
+
if (MATH_STYLED_LEGACY[variant]?.[cp] !== undefined) return MATH_STYLED_LEGACY[variant][cp];
|
|
23
|
+
const r = MATH_STYLED_RANGES[variant];
|
|
24
|
+
if (r) {
|
|
25
|
+
if (cp >= 65 && cp <= 90) return r[0] + cp - 65;
|
|
26
|
+
if (cp >= 97 && cp <= 122) return r[1] + cp - 97;
|
|
27
|
+
if (r[2] && cp >= 48 && cp <= 57) return r[2] + cp - 48;
|
|
28
|
+
}
|
|
29
|
+
const greek = MATH_STYLED_GREEK[variant];
|
|
30
|
+
if (greek !== undefined) {
|
|
31
|
+
if (cp >= 0x391 && cp <= 0x3a9 && cp !== 0x3a2) return greek + cp - 0x391;
|
|
32
|
+
if (cp >= 0x3b1 && cp <= 0x3c9) return greek + 26 + cp - 0x3b1;
|
|
33
|
+
const special = MATH_STYLED_GREEK_SPECIAL.indexOf(cp);
|
|
34
|
+
if (special === 0) return greek + 25;
|
|
35
|
+
if (special > 0) return greek + 50 + special;
|
|
36
|
+
}
|
|
37
|
+
return cp;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
export {mathStyledCodePoint};
|
package/src/tools/build-math.mjs
CHANGED
|
@@ -8,17 +8,18 @@ import {createHash} from 'node:crypto';
|
|
|
8
8
|
import {gzipSync} from 'node:zlib';
|
|
9
9
|
import {Script} from 'node:vm';
|
|
10
10
|
import {mathPackagePath, MATH_CLASSIC} from '../math/package-layout.mjs';
|
|
11
|
-
import {
|
|
11
|
+
import {mathModules, mathClassicSource} from '../math/package-build.mjs';
|
|
12
12
|
import {mathReadme} from '../math/package-readme.mjs';
|
|
13
13
|
|
|
14
14
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
15
|
-
export const MATH_VERSION = '2.
|
|
15
|
+
export const MATH_VERSION = '2.2.0';
|
|
16
16
|
export const MATH_BUNDLE = 'rapier-math-' + MATH_VERSION + '.js';
|
|
17
|
-
export const MATH_SOURCES = ['font.js', 'symbols.js', 'parser.js', 'layout.js', 'fallbacks.js', 'responsive.js', 'browser.js', 'api.js'].map(name => 'math/' + name);
|
|
18
|
-
export const MATH_RECIPE = ['math/build-font.py', 'math/FONT-SOURCE.md', 'math/FONT-LICENSE.txt', 'math/package-verify.mjs', 'tools/build-math.mjs', 'math/LICENSE-MIT', 'math/adoption-verify.mjs', 'math/package-build.mjs', 'math/package-layout.mjs', 'math/package-check.mjs', 'math/package-readme.mjs', 'math/README.md'];
|
|
17
|
+
export const MATH_SOURCES = ['font.js', 'symbols.js', 'parser.js', 'source.js', 'variants.js', 'layout.js', 'fallbacks.js', 'responsive.js', 'api.js', 'browser.js', 'mathml.js', 'semantic-api.js', 'combined.js', 'classic.js'].map(name => 'math/' + name);
|
|
18
|
+
export const MATH_RECIPE = ['math/build-font.py', 'math/FONT-SOURCE.md', 'math/FONT-LICENSE.txt', 'math/package-verify.mjs', 'tools/build-math.mjs', 'math/LICENSE-MIT', 'math/adoption-verify.mjs', 'math/package-build.mjs', 'math/package-layout.mjs', 'math/package-check.mjs', 'math/package-readme.mjs', 'math/README.md', 'math/SEMANTICS.md', 'math/semantic-verify.mjs'];
|
|
19
19
|
export const MATH_ADOPTION = ['delimiters.mjs', 'markdown-rules.mjs', 'reuse.mjs', 'integration.mjs', 'markdown-it.mjs', 'rehype.mjs', 'stream.mjs',
|
|
20
|
+
'accessible.mjs', 'accessible.css', 'mathml.d.ts', 'combined.d.ts', 'accessible.d.ts',
|
|
20
21
|
'index.d.ts', 'classic.d.ts', 'delimiters.d.ts', 'integration.d.ts', 'markdown-it.d.ts', 'rehype.d.ts', 'stream.d.ts',
|
|
21
|
-
'examples/formula.mjs', 'examples/markdown.mjs', 'examples/stream.mjs', 'examples/unified.mjs',
|
|
22
|
+
'examples/semantic.mjs', 'examples/accessible.html', 'examples/accessible.mjs', 'examples/formula.mjs', 'examples/markdown.mjs', 'examples/stream.mjs', 'examples/unified.mjs',
|
|
22
23
|
'examples/browser.html', 'examples/browser.mjs', 'examples/react.tsx', 'examples/worker.mjs', 'examples/README.md']
|
|
23
24
|
.map(file => ({file: 'math/' + file, packageFile: mathPackagePath('math/' + file)}));
|
|
24
25
|
const FONT = {
|
|
@@ -57,7 +58,7 @@ export async function assembleMath({root = ROOT, packageLayout = false} = {}) {
|
|
|
57
58
|
const license = await fontLicense(root, packageLayout);
|
|
58
59
|
if (!inputs[0].text.includes(license.toString('utf8').trim())) throw new Error('The embedded math font is missing its complete license');
|
|
59
60
|
const ownLicense = (await read('math/LICENSE-MIT')).toString('utf8');
|
|
60
|
-
const bytes = Buffer.from('/*!\n' + ownLicense.trim() + '\n*/\n(function(){\n\'use strict\';\n' + inputs.map(input => input.text
|
|
61
|
+
const bytes = Buffer.from('/*!\n' + ownLicense.trim() + '\n*/\n(function(){\n\'use strict\';\n' + inputs.map(input => mathClassicSource(input.text)).join('\n\n') + '\n})();\n');
|
|
61
62
|
new Script(bytes.toString('utf8'), {filename: MATH_BUNDLE});
|
|
62
63
|
const gzipBytes = gzipSync(bytes, {level: 9}).length;
|
|
63
64
|
if (gzipBytes >= 500_000) throw new Error('The math plugin exceeds its 500 KB gzip budget: ' + gzipBytes);
|
|
@@ -80,15 +81,18 @@ export async function assembleMath({root = ROOT, packageLayout = false} = {}) {
|
|
|
80
81
|
const content = await read(file);
|
|
81
82
|
resources.adoption.push({file, packageFile, bytes: content.length, sha256: digest(content)});
|
|
82
83
|
}
|
|
83
|
-
return {resources, bytes};
|
|
84
|
+
return {resources, bytes, modules: mathModules(MATH_VERSION)};
|
|
84
85
|
}
|
|
85
86
|
|
|
86
87
|
export async function buildMath({root = ROOT, updatePins = true, packageLayout = false} = {}) {
|
|
87
|
-
const {resources, bytes} = await assembleMath({root, packageLayout});
|
|
88
|
+
const {resources, bytes, modules} = await assembleMath({root, packageLayout});
|
|
88
89
|
if (packageLayout) {
|
|
89
90
|
await mkdir(resolve(root, 'dist'), {recursive: true});
|
|
90
91
|
await writeFile(resolve(root, MATH_CLASSIC), bytes);
|
|
91
|
-
|
|
92
|
+
for (const [file, content] of modules) {
|
|
93
|
+
await mkdir(dirname(resolve(root, file)), {recursive: true});
|
|
94
|
+
await writeFile(resolve(root, file), content);
|
|
95
|
+
}
|
|
92
96
|
await writeFile(resolve(root, 'docs/math-resources.json'), JSON.stringify(resources, null, 2) + '\n');
|
|
93
97
|
await writeFile(resolve(root, 'README.md'), mathReadme(resources));
|
|
94
98
|
const sbomPath = resolve(root, 'docs/math-components.json');
|
|
@@ -117,8 +121,12 @@ export async function buildMath({root = ROOT, updatePins = true, packageLayout =
|
|
|
117
121
|
if (!block.test(loader)) throw new Error('The math loader pin could not be located');
|
|
118
122
|
const version = /var MATH_VERSION = '[^']+';/;
|
|
119
123
|
if (!version.test(loader)) throw new Error('The math loader version could not be located');
|
|
124
|
+
// The route keeps its release-tagged origin (tools/version-sync.mjs); only the bundle's filename changes.
|
|
125
|
+
const cdn = /(key: 'math',[\s\S]*?cdn: '(https:\/\/cdn\.jsdelivr\.net\/gh\/jackskip22\/rapier-plugins@[^/']+\/)math\/)[^']+(')/;
|
|
126
|
+
if (!cdn.test(loader)) throw new Error('The math loader CDN pin could not be located');
|
|
120
127
|
await writeFile(loaderPath, loader.replace(version, "var MATH_VERSION = '" + MATH_VERSION + "';")
|
|
121
|
-
.replace(block, (_, before, middle, after) => before + bytes.length + middle + sha384 + after)
|
|
128
|
+
.replace(block, (_, before, middle, after) => before + bytes.length + middle + sha384 + after)
|
|
129
|
+
.replace(cdn, (_, before, origin, after) => before + MATH_BUNDLE + after));
|
|
122
130
|
}
|
|
123
131
|
return {bundle: MATH_BUNDLE, bytes: bytes.length, gzipBytes, sha256, sha384};
|
|
124
132
|
}
|
package/tests/adoption.mjs
CHANGED
|
@@ -213,6 +213,40 @@ changingOptions.renderOptions.maxWidth = 1;
|
|
|
213
213
|
const changingSession = createMathSession();
|
|
214
214
|
assert.equal(changingHost.render(changingSource, {rapierMathSession: changingSession}), '<p>' + narrow + ' then ' + narrow + '</p>\n');
|
|
215
215
|
changingSession.dispose();
|
|
216
|
+
// A host may throw a non-Error value while options are read. Normalize it before
|
|
217
|
+
// adapter serialization, including falsy message/command values and non-string codes.
|
|
218
|
+
for (const accessible of [false, true]) for (const cached of [false, true]) {
|
|
219
|
+
const mathSession = cached ? createMathSession() : undefined;
|
|
220
|
+
const host = new MarkdownIt().use(rapierMath, {accessible,
|
|
221
|
+
renderOptions: {get maxWidth() { throw {code: 7, message: '', command: 0}; }}});
|
|
222
|
+
const env = {rapierMathSession: mathSession};
|
|
223
|
+
const html = host.render(String.raw`\(x\)`, env);
|
|
224
|
+
assert(html.includes('data-math-error="invalid-tex"'));
|
|
225
|
+
assert.deepEqual(env.rapierMathErrors[0].errors, [{code: 'invalid-tex', message: '', offset: 0, command: '0'}]);
|
|
226
|
+
mathSession?.dispose();
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
// MathML can leave a containing link unnamed even though its nested structure
|
|
231
|
+
// remains accessible. Give only the new composed route a destination fallback;
|
|
232
|
+
// retain authored names and leave ordinary SVG and rejected insertions unchanged.
|
|
233
|
+
const linkedCode = source => ({type: 'element', tagName: 'code', properties: {className: ['language-math', 'math-inline']}, children: [{type: 'text', value: source}]});
|
|
234
|
+
for (const accessible of [false, true]) for (const authored of [{}, {title: 'Open the derivation'}, {ariaLabel: 'Read proof'}, {ariaLabelledBy: ['purpose']}]) {
|
|
235
|
+
const properties = {href: 'https://example.test/proof?a=1&b=2', ...authored};
|
|
236
|
+
const link = {type: 'element', tagName: 'a', properties, children: [{type: 'element', tagName: 'strong', properties: {}, children: [linkedCode(String.raw`\frac{x}{y}`)]}]};
|
|
237
|
+
rehypeMath({accessible})({type: 'root', children: [link]});
|
|
238
|
+
const expected = accessible && Object.keys(authored).length === 0 ? {...properties, title: properties.href} : {href: properties.href, ...authored};
|
|
239
|
+
assert.deepEqual(link.properties, expected, 'host-owned accessible names remain authoritative');
|
|
240
|
+
const tags = [], walk = node => { if (node.tagName) tags.push(node.tagName); for (const child of node.children || []) walk(child); }; walk(link);
|
|
241
|
+
assert.equal(tags.filter(tag => tag === 'svg').length, 1, 'destination fallback preserves visual SVG');
|
|
242
|
+
assert.equal(tags.filter(tag => tag === 'math').length, accessible ? 1 : 0, 'destination fallback preserves native MathML');
|
|
243
|
+
}
|
|
244
|
+
for (const source of [String.raw`\unsupported{x}`, String.raw`\href{https://example.test/inner}{x}`]) {
|
|
245
|
+
const link = {type: 'element', tagName: 'a', properties: {href: 'https://example.test/outer'}, children: [linkedCode(source)]};
|
|
246
|
+
rehypeMath({accessible: true})({type: 'root', children: [link]});
|
|
247
|
+
assert.equal(link.properties.title, undefined, 'rejected insertion does not mutate the host link');
|
|
248
|
+
}
|
|
249
|
+
|
|
216
250
|
console.log(JSON.stringify({sourceCustodyRows: rows.length, splitAgreement: 'all two-piece boundaries',
|
|
217
251
|
lifetimes: 'abort, replacement handles, rejection, interleaved messages, explicit bounded reuse', adapters: 'markdown-it and sanitized unified',
|
|
218
252
|
security: 'hostile source stays inert; document math budgets fall back'}));
|
package/tests/check.mjs
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
import assert from 'node:assert/strict';
|
|
4
4
|
import {readFile} from 'node:fs/promises';
|
|
5
5
|
import {Script, createContext} from 'node:vm';
|
|
6
|
-
import {
|
|
6
|
+
import {assembleMath} from '../src/tools/build-math.mjs';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
7
8
|
|
|
8
9
|
const read = path => readFile(new URL('../' + path, import.meta.url), 'utf8');
|
|
9
10
|
const pkg = JSON.parse(await read('./package.json'));
|
|
@@ -15,11 +16,12 @@ assert.equal(pkg.type, 'module');
|
|
|
15
16
|
assert.equal(pkg.license, 'SEE LICENSE IN LICENSE');
|
|
16
17
|
assert.equal(Object.keys(pkg.dependencies || {}).length, 0);
|
|
17
18
|
assert.equal(Object.keys(pkg.scripts || {}).length, 0);
|
|
18
|
-
|
|
19
|
+
const rebuilt = await assembleMath({root: fileURLToPath(new URL('..', import.meta.url)), packageLayout: true});
|
|
20
|
+
for (const [file, content] of rebuilt.modules) assert.equal(await read(file), content, 'exact native module: ' + file);
|
|
19
21
|
const rendererLicense = await read('./src/math/LICENSE-MIT'), fontLicense = await read('./src/math/FONT-LICENSE.txt');
|
|
20
|
-
for (const name of ['./LICENSE', './
|
|
22
|
+
for (const name of ['./LICENSE', './src/math/font.js', './' + resources.packageBundle]) {
|
|
21
23
|
const text = await read(name);
|
|
22
|
-
assert(text.includes(rendererLicense.trim()), name + ': renderer license');
|
|
24
|
+
if (!name.endsWith('font.js')) assert(text.includes(rendererLicense.trim()), name + ': renderer license');
|
|
23
25
|
assert(text.includes(fontLicense.trim()), name + ': complete font license');
|
|
24
26
|
}
|
|
25
27
|
|
|
@@ -35,6 +37,12 @@ assert(Object.isFrozen(session), 'message session handle is immutable');
|
|
|
35
37
|
session.clear(); session.dispose();
|
|
36
38
|
assert.equal(typeof (await import('../dist/integration.mjs')).createFormulaRenderer, 'function', 'internal adapter import closure');
|
|
37
39
|
const module = await import('../dist/index.mjs');
|
|
40
|
+
const semantic = await import('rapier-math/mathml'), combined = await import('rapier-math/combined');
|
|
41
|
+
assert.deepEqual(Object.keys(semantic).sort(), ['parse', 'toMathML']);
|
|
42
|
+
assert.deepEqual(Object.keys(combined), ['renderWithMathML']);
|
|
43
|
+
assert.equal(typeof (await import('rapier-math/accessible')).renderAccessible, 'function');
|
|
44
|
+
assert.equal(pkg.exports['./accessible.css'], './dist/accessible.css');
|
|
45
|
+
assert(pkg.sideEffects.includes('./dist/accessible.css'));
|
|
38
46
|
const afterImport = Object.getOwnPropertyDescriptors(globalThis);
|
|
39
47
|
assert.deepEqual(Reflect.ownKeys(afterImport), Reflect.ownKeys(globals), 'module adds no globals');
|
|
40
48
|
for (const key of Reflect.ownKeys(globals)) for (const field of Object.keys(globals[key]))
|
|
@@ -122,4 +130,4 @@ const unicodeFailure = module.render('\\begin{' + '😀'.repeat(600) + '}x');
|
|
|
122
130
|
assert(unicodeFailure.errors[0].message.isWellFormed(), 'diagnostic admission cannot split a source surrogate pair');
|
|
123
131
|
assert.equal(module.render('x+1').errors.length, 0, 'refused input cannot poison later rendering');
|
|
124
132
|
console.log(JSON.stringify({name: pkg.name, version: module.version, module: 'native ESM; no global changes',
|
|
125
|
-
rebuild: 'exact
|
|
133
|
+
rebuild: 'exact static native graph', classicAgreement: examples.length + hostile.length, sourceAlternatives: 'exact', hostileContent: 'inert', licenses: 'complete'}));
|