rapier-math 2.4.1 → 2.6.1
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/CHANGELOG.md +10 -0
- package/LICENSE +10 -3
- package/README.md +4 -5
- package/dist/index.mjs +1 -1
- package/dist/markdown-rules.mjs +47 -0
- package/dist/rapier-math.js +671 -222
- package/docs/api.md +6 -2
- package/docs/font-source.md +37 -29
- package/docs/math-components.json +51 -7
- package/docs/math-resources.json +59 -64
- package/package.json +3 -3
- package/src/math/FONT-LICENSE.txt +9 -2
- package/src/math/build-font.py +61 -65
- package/src/math/classic.js +1 -1
- package/src/math/font.js +23 -487
- package/src/math/layout.js +302 -112
- package/src/math/mathml.js +26 -7
- package/src/math/package-layout.mjs +1 -0
- package/src/math/package-readme.mjs +3 -4
- package/src/math/parser.js +299 -60
- package/src/tools/build-math.mjs +22 -7
- package/tests/adoption.mjs +0 -252
- package/tests/check.mjs +0 -134
- package/tests/semantics.mjs +0 -340
- package/tests/typeset.mjs +0 -172
- package/tests/verify.mjs +0 -49
package/tests/semantics.mjs
DELETED
|
@@ -1,340 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Structural MathML, exact-source custody and hostile-content checks against a staged package.
|
|
3
|
-
// Replay: node semantic-check.mjs [package-root]. Requires Python 3 with lxml for strict XML parsing.
|
|
4
|
-
// This exercises generated native ESM/classic entries. It makes no appearance or AT speech claims.
|
|
5
|
-
import assert from 'node:assert/strict';
|
|
6
|
-
import {readFile} from 'node:fs/promises';
|
|
7
|
-
import {dirname, resolve} from 'node:path';
|
|
8
|
-
import {fileURLToPath, pathToFileURL} from 'node:url';
|
|
9
|
-
import {spawnSync} from 'node:child_process';
|
|
10
|
-
import {Script, createContext} from 'node:vm';
|
|
11
|
-
|
|
12
|
-
const root = resolve(process.argv[2] || resolve(dirname(fileURLToPath(import.meta.url)), '..'));
|
|
13
|
-
const read = path => readFile(resolve(root, path), 'utf8');
|
|
14
|
-
const pkg = JSON.parse(await read('package.json'));
|
|
15
|
-
const resources = JSON.parse(await read('docs/math-resources.json'));
|
|
16
|
-
const entry = key => pathToFileURL(resolve(root, pkg.exports[key].default)).href;
|
|
17
|
-
const module = {...await import(entry('.')), ...await import(entry('./mathml'))};
|
|
18
|
-
const {renderWithMathML} = await import(entry('./combined'));
|
|
19
|
-
const standalone = await import(entry('./mathml'));
|
|
20
|
-
const {renderAccessible} = await import(entry('./accessible'));
|
|
21
|
-
const classicSource = await read(resources.packageBundle);
|
|
22
|
-
const context = createContext({atob, URL});
|
|
23
|
-
new Script(classicSource, {filename: resources.bundle}).runInContext(context);
|
|
24
|
-
const classic = context.RapierMath;
|
|
25
|
-
const plain = value => JSON.parse(JSON.stringify(value));
|
|
26
|
-
|
|
27
|
-
const corpus = [
|
|
28
|
-
{id: 'fraction-roots', source: String.raw`\frac{12.5}{\sqrt[3]{1+\sqrt{x_2^4}}}`, status: 'complete'},
|
|
29
|
-
{id: 'numbers-signs', source: '-12.34+56-7', status: 'complete'},
|
|
30
|
-
{id: 'number-boundaries', source: String.raw`1{2}3+4\,5+6.7.8+2e3+9\text{ten}0`, status: 'complete'},
|
|
31
|
-
{id: 'number-scripts', source: String.raw`12.3^4+1{2}^3+4\,5^6`, status: 'complete'},
|
|
32
|
-
{id: 'scripts-inline', source: String.raw`x_{12}^{34}+\sum_{i=1}^{20}i`, status: 'complete'},
|
|
33
|
-
{id: 'scripts-display', source: String.raw`x_{12}^{34}+\sum_{i=1}^{20}i`, options: {displayMode: true}, status: 'complete'},
|
|
34
|
-
{id: 'explicit-limits', source: String.raw`\int\limits_0^1 f(x)\,dx+\sum\nolimits_i^n a_i`, options: {displayMode: true}, status: 'complete'},
|
|
35
|
-
{id: 'operators', source: String.raw`\sin x+\operatorname{arg max}_{x}f(x)`, status: 'complete'},
|
|
36
|
-
{id: 'atom-class-limits', source: String.raw`\mathrel{x}+\mathop{xy}+\sum_0^1\limits`, status: 'presentation-fallback'},
|
|
37
|
-
{id: 'fences-accents', source: String.raw`\left(\hat{x}+\underline{y}\middle|z\right)+\overunderset{u}{v}{=}`, status: 'complete'},
|
|
38
|
-
{id: 'matrix', source: String.raw`\begin{pmatrix}1&2\\3&4\end{pmatrix}`, status: 'complete'},
|
|
39
|
-
{id: 'cases', source: String.raw`\begin{cases}x&x\ge0\\-x&\text{otherwise}\end{cases}`, status: 'complete'},
|
|
40
|
-
{id: 'aligned', source: String.raw`\begin{aligned}a&=b+c\\d&=e\end{aligned}`, status: 'complete'},
|
|
41
|
-
{id: 'array-insertion', source: String.raw`\begin{array}{r@{=}l}x&1\\y&2\end{array}`, status: 'presentation-fallback'},
|
|
42
|
-
{id: 'style-text', source: String.raw`\mathbf{x}+\mathbb{R}+\text{speed 12.5}`, status: 'complete'},
|
|
43
|
-
{id: 'macro', source: String.raw`\newcommand{\ratio}[2]{\frac{#1}{#2}}\ratio{12}{34}`, status: 'complete'},
|
|
44
|
-
{id: 'explicit-tokens', source: String.raw`\mmlToken{mi}{speed}+\mmlToken{mn}{12.34}+\mmlToken{mo}{lim}+\mmlToken{mtext}{word}`, status: 'complete'},
|
|
45
|
-
{id: 'links', source: String.raw`\href{https://example.com/?a=1&b=2}{\frac{x}{2}}`, status: 'presentation-fallback'},
|
|
46
|
-
{id: 'nested-link', source: String.raw`\href{https://example.com/outer}{\href{https://example.com/inner}{x}}`, status: 'refused', code: 'semantic-nested-link'},
|
|
47
|
-
{id: 'hidden-link', source: String.raw`\phantom{\href{https://example.com/}{x}}`, status: 'refused', code: 'semantic-hidden-link'},
|
|
48
|
-
{id: 'chemistry', source: String.raw`\ce{2 H2 + O2 -> 2 H2O}`, status: 'presentation-fallback'},
|
|
49
|
-
{id: 'physics-units', source: String.raw`\dv[2]{x}{t}+\pu{1.2e-3 m s-1}`, status: 'presentation-fallback'},
|
|
50
|
-
{id: 'tags-labels', source: String.raw`x=1\label{eq:sample}\tag{A}`, status: 'presentation-fallback'},
|
|
51
|
-
{id: 'presentation', source: String.raw`\cancel{x}+\phantom{a}+\smash{b}+\raisebox{1em}{c}`, status: 'presentation-fallback'},
|
|
52
|
-
{id: 'xml-text', source: String.raw`\text{A < B \& "C" 'D' </mtext><script>run</script>}`, status: 'complete'},
|
|
53
|
-
{id: 'source-lines', source: '\ufeffx% authored 😀 comment\r\n+\t1\r', status: 'complete'},
|
|
54
|
-
{id: 'source-invalid', source: 'x\u0000y\ud800z\udfff\ufffe', status: 'refused', code: 'invalid-source-character'},
|
|
55
|
-
{id: 'generated-invalid', source: String.raw`\unicode{0xffff}`, status: 'refused', code: 'invalid-semantic-character'},
|
|
56
|
-
{id: 'unsupported', source: String.raw`\unsupported{x}`, status: 'refused', code: 'unsupported-command'},
|
|
57
|
-
{id: 'bounded-diagnostic', source: '\\' + 'q'.repeat(5000), status: 'refused', code: 'unsupported-command'},
|
|
58
|
-
{id: 'url-script', source: String.raw`\href{javascript:alert(1)}{x}`, status: 'refused'},
|
|
59
|
-
{id: 'url-data', source: String.raw`\href{data:text/html,payload}{x}`, status: 'refused'},
|
|
60
|
-
{id: 'url-attribute', source: String.raw`\href{https://example.com/" onclick="alert(1)}{x}`, status: 'refused'},
|
|
61
|
-
{id: 'token-attribute', source: String.raw`\mmlToken{mi}[onclick="alert(1)"]{x}`, status: 'refused'},
|
|
62
|
-
{id: 'color-url', source: String.raw`\textcolor{url(https://example.com/payload)}{x}`, status: 'refused'},
|
|
63
|
-
{id: 'macro-exhaustion', source: String.raw`\def\again{\again}\again`, status: 'refused', code: 'resource-limit'},
|
|
64
|
-
{id: 'depth-exhaustion', source: '\\sqrt{'.repeat(200) + 'x' + '}'.repeat(200), status: 'refused', code: 'resource-limit'},
|
|
65
|
-
{id: 'parts-exhaustion', source: 'x'.repeat(50_001), status: 'refused', code: 'resource-limit'},
|
|
66
|
-
];
|
|
67
|
-
|
|
68
|
-
// Array insertions amplify shared AST content without a large authored source.
|
|
69
|
-
// These reach serializer work/output admission, independently of the parser's own limits.
|
|
70
|
-
for (const [id, insertion, rows] of [['table-work', 'x', 500], ['table-output', '\\text{' + 'A'.repeat(1000) + '}', 40]])
|
|
71
|
-
corpus.push({id, source: '\\begin{array}{*{256}{@{' + insertion + '}c}}' + Array(rows).fill('a').join('\\\\') + '\\end{array}', status: 'refused', code: 'resource-limit', semanticOnly: true});
|
|
72
|
-
// Neither source admission nor presentation alone reaches its own bound. Their
|
|
73
|
-
// aggregate must refuse without throwing or discarding the exact CR-sensitive source.
|
|
74
|
-
corpus.push({id: 'complete-output', source: '%' + '&'.repeat(995000) + '\r\n' +
|
|
75
|
-
'\\begin{array}{*{256}{@{\\text{' + 'A'.repeat(900) + '}}c}}' + Array(32).fill('a').join('\\\\') + '\\end{array}',
|
|
76
|
-
status: 'refused', code: 'resource-limit', semanticOnly: true});
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
// Counterexamples at admission and normalization boundaries. These check source
|
|
80
|
-
// authority, truthful semantic status and focus safety rather than appearance.
|
|
81
|
-
for (const name of ['constructor', 'toString', 'hasOwnProperty'])
|
|
82
|
-
corpus.push({id: 'inherited-' + name, source: '\\' + name + '{x}', status: 'refused', code: 'unsupported-command'});
|
|
83
|
-
corpus.push({id: 'inherited-text', source: String.raw`\text{\toString}`, status: 'refused', code: 'unsupported-command'});
|
|
84
|
-
corpus.push({id: 'own-macro-name', source: String.raw`\newcommand{\constructor}{x}\constructor`, status: 'complete'});
|
|
85
|
-
corpus.push({id: 'invalid-color-link', source: String.raw`\href{https://example.com}{\textcolor{transparent}{\textcolor{notacolor}{x}}}`, status: 'refused', code: 'semantic-empty-link'});
|
|
86
|
-
corpus.push({id: 'known-color-link', source: String.raw`\href{https://example.com}{\textcolor{transparent}{\textcolor{RebeccaPurple}{x}}}`, status: 'presentation-fallback'});
|
|
87
|
-
corpus.push({id: 'operator-domain', source: String.raw`\operatorname{\Tr}+\mathop{\grad}`, status: 'presentation-fallback', code: 'semantic-physics-presentation'});
|
|
88
|
-
corpus.push({id: 'unicode-numbers', source: '𝟙𝟚.𝟛^4+١٢', status: 'complete'});
|
|
89
|
-
corpus.push({id: 'authored-invisible-operator', source: String.raw`f\unicode{0x2061}(x)`, status: 'complete'});
|
|
90
|
-
|
|
91
|
-
const records = corpus.map(item => {
|
|
92
|
-
const result = module.toMathML(item.source, item.options);
|
|
93
|
-
assert.equal(result.status, item.status, item.id + ': explicit semantic status');
|
|
94
|
-
if (item.code) assert(result.errors.some(error => error.code === item.code), item.id + ': refusal reason');
|
|
95
|
-
assert.equal(result.status === 'complete', result.errors.length === 0, item.id + ': incomplete mapping is disclosed');
|
|
96
|
-
assert.deepEqual(plain(classic.toMathML(item.source, item.options)), result, item.id + ': classic/ESM semantic agreement');
|
|
97
|
-
assert.deepEqual(standalone.toMathML(item.source, item.options), result, item.id + ': font-free/full semantic agreement');
|
|
98
|
-
if (!item.semanticOnly) {
|
|
99
|
-
const combined = renderWithMathML(item.source, item.options);
|
|
100
|
-
assert.deepEqual(combined.semantics, result, item.id + ': combined path preserves semantic result');
|
|
101
|
-
}
|
|
102
|
-
for (const value of Object.values(result.metrics)) assert(Number.isSafeInteger(value) && value >= 0, item.id + ': finite bounded work');
|
|
103
|
-
assert.equal(result.metrics.outputCodeUnits, result.mathml.length, item.id + ': complete returned-output accounting');
|
|
104
|
-
assert(result.mathml.length <= 16 * 1024 * 1024, item.id + ': complete output bound');
|
|
105
|
-
return {...item, result};
|
|
106
|
-
});
|
|
107
|
-
const diagnostic = records.find(record => record.id === 'bounded-diagnostic').result.errors[0];
|
|
108
|
-
assert.equal(diagnostic.messageTruncated, true, 'semantic diagnostic retains its truncation marker');
|
|
109
|
-
assert.equal(diagnostic.commandTruncated, true, 'semantic command retains its truncation marker');
|
|
110
|
-
assert(diagnostic.message.length <= 1025 && diagnostic.command.length <= 128, 'bounded diagnostic fields');
|
|
111
|
-
assert.equal(records.find(record => record.id === 'source-lines').result.source.encoding, 'application/x-rapier-tex-utf16', 'CR source declares its HTML-stable exact carrier');
|
|
112
|
-
|
|
113
|
-
// Oversized text never enters source escaping or becomes an apparent truncated source archive.
|
|
114
|
-
for (const [id, source] of [['source-omitted', 'x'.repeat(1_000_001)], ['invalid-omitted', '\ud800'.repeat(1_000_001)]]) {
|
|
115
|
-
const result = standalone.toMathML(source);
|
|
116
|
-
assert.equal(result.status, 'refused');
|
|
117
|
-
assert.equal(result.source.omitted, true);
|
|
118
|
-
assert(result.errors.some(error => error.code === 'resource-limit' && error.sourceOmitted));
|
|
119
|
-
assert(result.mathml.length < 100_000, id + ': bounded refusal');
|
|
120
|
-
records.push({id, source, result});
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// A returned inspectable tree is caller-owned data; mutations cannot alter another parse or render.
|
|
124
|
-
const detached = module.parse('x+1');
|
|
125
|
-
detached.children[0].value = '</mi><script>run</script>';
|
|
126
|
-
detached.children.push(detached);
|
|
127
|
-
assert.equal(module.parse('x+1').children[0].value, 'x', 'parse has no shared mutable tree');
|
|
128
|
-
assert.deepEqual(module.toMathML('x+1'), standalone.toMathML('x+1'), 'detached mutation cannot poison rendering');
|
|
129
|
-
assert.equal(module.toMathML(String.raw`\ratio{1}{2}`).status, 'refused', 'local macro scope cannot leak');
|
|
130
|
-
const good = module.toMathML('x+1');
|
|
131
|
-
good.errors.push({code: 'caller-change'});
|
|
132
|
-
assert.equal(module.toMathML('x+1').status, 'complete', 'returned diagnostic arrays are not shared');
|
|
133
|
-
|
|
134
|
-
const hosts = ['fraction-roots', 'links', 'unsupported'].map(id => {
|
|
135
|
-
const item = records.find(record => record.id === id);
|
|
136
|
-
const result = renderAccessible(item.source, item.options);
|
|
137
|
-
assert.deepEqual(result.semantics, item.result, id + ': composition preserves semantic payload');
|
|
138
|
-
if (id === 'unsupported') {
|
|
139
|
-
assert.equal(result.presentation, 'refused');
|
|
140
|
-
assert.equal(result.html, '');
|
|
141
|
-
assert(result.errors.length > 0);
|
|
142
|
-
} else assert.equal(result.presentation, id === 'links' ? 'mathml' : 'svg-mathml');
|
|
143
|
-
return {id, html: result.html};
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
// A real XML parser catches unescaped text, wrong namespaces, injected children and attribute splitting.
|
|
147
|
-
const xmlReader = String.raw`
|
|
148
|
-
import json, re, sys
|
|
149
|
-
from lxml import etree
|
|
150
|
-
MATH = 'http://www.w3.org/1998/Math/MathML'
|
|
151
|
-
HTML = 'http://www.w3.org/1999/xhtml'
|
|
152
|
-
SVG = 'http://www.w3.org/2000/svg'
|
|
153
|
-
admitted = set('math semantics annotation mrow mi mn mo mtext mfrac msqrt mroot msub msup msubsup mover munder munderover mtable mtr mtd mstyle mspace mphantom mpadded menclose merror'.split())
|
|
154
|
-
def read_node(node, semantic):
|
|
155
|
-
q = etree.QName(node)
|
|
156
|
-
if semantic:
|
|
157
|
-
assert q.namespace == MATH or (q.namespace == HTML and q.localname == 'a'), 'unexpected semantic namespace'
|
|
158
|
-
assert q.localname in admitted or (q.namespace == HTML and q.localname == 'a'), 'unadmitted semantic element'
|
|
159
|
-
if q.namespace == HTML:
|
|
160
|
-
assert etree.QName(node.getparent()).namespace == MATH and etree.QName(node.getparent()).localname == 'mtext', 'HTML link only within MathML mtext'
|
|
161
|
-
assert q.localname.lower() not in ('script', 'iframe', 'object', 'embed', 'image', 'foreignobject', 'style', 'animate', 'set'), 'active or remote element'
|
|
162
|
-
attrs = dict(node.attrib)
|
|
163
|
-
for name, value in attrs.items():
|
|
164
|
-
local = etree.QName(name).localname
|
|
165
|
-
assert not local.lower().startswith('on'), 'event attribute'
|
|
166
|
-
assert local not in ('src', 'srcdoc', 'action', 'formaction'), 'active attribute'
|
|
167
|
-
if local == 'href':
|
|
168
|
-
assert re.match(r'^https?://[^\s<>"\x27\\]+$', value, re.I), 'link must remain a single HTTP(S) URL'
|
|
169
|
-
if local not in ('href', 'aria-label', 'data-tex-utf16'):
|
|
170
|
-
assert not re.search(r'url\s*\(|javascript:|vbscript:|expression\s*\(', value, re.I), 'executable attribute value'
|
|
171
|
-
if semantic:
|
|
172
|
-
assert local != 'id', 'semantic output must not invent occurrence identity'
|
|
173
|
-
assert not re.search(r'(?<![A-Za-z])(?:NaN|Infinity)(?![A-Za-z])', value), 'nonfinite semantic attribute'
|
|
174
|
-
return {'tag': q.localname, 'ns': q.namespace, 'attrs': attrs, 'text': node.text or '', 'children': [read_node(child, semantic) for child in node], 'tail': node.tail or ''}
|
|
175
|
-
def parse(text, semantic):
|
|
176
|
-
assert '<!DOCTYPE' not in text and '<!ENTITY' not in text, 'DTD/entity injection'
|
|
177
|
-
parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True, recover=False)
|
|
178
|
-
node = etree.fromstring(text.encode('utf-8'), parser)
|
|
179
|
-
return read_node(node, semantic)
|
|
180
|
-
data = json.load(sys.stdin)
|
|
181
|
-
result = {'xml': '.'.join(map(str, etree.LXML_VERSION)), 'libxml': '.'.join(map(str, etree.LIBXML_VERSION)), 'python': sys.version.split()[0], 'records': [], 'hosts': []}
|
|
182
|
-
for item in data['records']:
|
|
183
|
-
tree = parse(item['mathml'], True)
|
|
184
|
-
assert tree['tag'] == 'math' and tree['ns'] == MATH, item['id'] + ': namespace-correct root'
|
|
185
|
-
result['records'].append({'id': item['id'], 'tree': tree})
|
|
186
|
-
for item in data['hosts']:
|
|
187
|
-
tree = parse('<div xmlns="' + HTML + '">' + item['html'] + '</div>', False)
|
|
188
|
-
result['hosts'].append({'id': item['id'], 'tree': tree})
|
|
189
|
-
print(json.dumps(result, ensure_ascii=True))
|
|
190
|
-
`;
|
|
191
|
-
const xml = spawnSync(process.env.RAPIER_MATH_PYTHON || 'python3', ['-c', xmlReader], {
|
|
192
|
-
input: JSON.stringify({records: records.map(({id, result}) => ({id, mathml: result.mathml})), hosts}),
|
|
193
|
-
encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
|
|
194
|
-
});
|
|
195
|
-
assert.equal(xml.status, 0, 'strict XML reader: ' + (xml.error?.message || xml.stderr));
|
|
196
|
-
const parsed = JSON.parse(xml.stdout);
|
|
197
|
-
const trees = new Map(parsed.records.map(({id, tree}) => [id, tree]));
|
|
198
|
-
const walk = function*(node) {yield node; for (const child of node.children) yield* walk(child);};
|
|
199
|
-
const find = (tree, tag) => [...walk(tree)].filter(node => node.tag === tag);
|
|
200
|
-
const one = (tree, tag) => {const nodes = find(tree, tag); assert.equal(nodes.length, 1, 'one ' + tag); return nodes[0];};
|
|
201
|
-
// Compare relationships by Unicode base characters while allowing standard mathematical alphabets.
|
|
202
|
-
// Exact authored text is checked separately from the raw parsed annotation, without normalization.
|
|
203
|
-
const textOf = node => node.tag === 'annotation' ? '' : (node.text + node.children.map(child => textOf(child) + child.tail).join('')).normalize('NFKC');
|
|
204
|
-
const tokens = tree => [...walk(tree)].filter(node => ['mi', 'mn', 'mo', 'mtext'].includes(node.tag) && !node.children.length).map(node => [node.tag, node.text.normalize('NFKC')]);
|
|
205
|
-
const rowTexts = tree => one(tree, 'mtable').children.filter(node => node.tag === 'mtr').map(row => row.children.filter(node => node.tag === 'mtd').map(textOf));
|
|
206
|
-
|
|
207
|
-
for (const {id, source, result} of records) {
|
|
208
|
-
const annotations = find(trees.get(id), 'annotation');
|
|
209
|
-
if (result.source.omitted) assert(!annotations.some(node => /(?:tex|utf16)/.test(node.attrs.encoding || '')), id + ': omitted source has no source carrier');
|
|
210
|
-
else {
|
|
211
|
-
const carriers = annotations.filter(node => node.attrs.encoding === result.source.encoding);
|
|
212
|
-
assert.equal(carriers.length, 1, id + ': one declared exact-source carrier');
|
|
213
|
-
if (result.source.encoding === 'application/x-tex') assert.equal(carriers[0].text, source, id + ': exact XML-decoded TeX including CRLF/BOM');
|
|
214
|
-
else {
|
|
215
|
-
assert.equal(result.source.encoding, 'application/x-rapier-tex-utf16');
|
|
216
|
-
assert.match(carriers[0].text, /^(?:[\da-f]{4})*$/i);
|
|
217
|
-
const original = (carriers[0].text.match(/.{4}/g) || []).map(value => String.fromCharCode(parseInt(value, 16))).join('');
|
|
218
|
-
assert.equal(original, source, id + ': exact UTF-16 custody across invalid XML or CR-sensitive hosts');
|
|
219
|
-
assert(!annotations.some(node => node.attrs.encoding === 'application/x-tex'), id + ': escaped substitute is never labelled original TeX');
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
assert.deepEqual(tokens(trees.get('unicode-numbers')).filter(([tag]) => tag === 'mn').map(([,value]) => value),
|
|
225
|
-
['12.3', '4', '١٢'], 'authored Unicode decimal digits retain numerical roles and grouping');
|
|
226
|
-
assert(tokens(trees.get('authored-invisible-operator')).some(([tag, value]) => tag === 'mo' && value === '\u2061'),
|
|
227
|
-
'explicit invisible function application stays an operator');
|
|
228
|
-
const fraction = one(trees.get('fraction-roots'), 'mfrac');
|
|
229
|
-
assert.equal(fraction.children.length, 2);
|
|
230
|
-
assert.equal(textOf(fraction.children[0]), '12.5', 'numerator owns decimal token');
|
|
231
|
-
const rootNode = one(fraction.children[1], 'mroot');
|
|
232
|
-
assert.equal(rootNode.children.length, 2);
|
|
233
|
-
assert.equal(textOf(rootNode.children[1]), '3', 'root index is second child');
|
|
234
|
-
const nestedRoot = one(rootNode.children[0], 'msqrt');
|
|
235
|
-
const rootScripts = one(nestedRoot, 'msubsup');
|
|
236
|
-
assert.deepEqual(rootScripts.children.map(textOf), ['x', '2', '4'], 'script order is base/sub/sup');
|
|
237
|
-
assert.deepEqual(tokens(trees.get('numbers-signs')), [['mo', '−'], ['mn', '12.34'], ['mo', '+'], ['mn', '56'], ['mo', '−'], ['mn', '7']], 'signs stay operators and decimal digits stay one number');
|
|
238
|
-
const boundedNumbers = tokens(trees.get('number-boundaries'));
|
|
239
|
-
for (const forbidden of ['123', '45', '6.7.8', '2e3', '90']) assert(!boundedNumbers.some(([tag, text]) => tag === 'mn' && text === forbidden), 'no false number across explicit boundary: ' + forbidden);
|
|
240
|
-
assert(!boundedNumbers.some(([tag, text]) => tag === 'mn' && text.includes('.')), 'malformed multi-dot run never invents a decimal suffix');
|
|
241
|
-
assert(boundedNumbers.some(([tag, text]) => tag === 'mi' && text === 'e'), 'ordinary e is not guessed as scientific notation');
|
|
242
|
-
assert.deepEqual(find(trees.get('number-scripts'), 'msup').map(node => node.children.map(textOf)), [['12.3', '4'], ['2', '3'], ['5', '6']], 'numerical script bases coalesce only within their group/space boundary');
|
|
243
|
-
assert.equal(find(trees.get('scripts-inline'), 'munderover').length, 0, 'display-only limits are side scripts inline');
|
|
244
|
-
const sumLimits = one(trees.get('scripts-display'), 'munderover');
|
|
245
|
-
assert.deepEqual(sumLimits.children.map(textOf), ['∑', 'i=1', '20'], 'operator limits retain base/lower/upper order');
|
|
246
|
-
const explicitLimits = trees.get('explicit-limits');
|
|
247
|
-
assert.deepEqual(one(explicitLimits, 'munderover').children.map(textOf), ['∫', '0', '1'], 'explicit integral limits survive');
|
|
248
|
-
assert(find(explicitLimits, 'msubsup').some(node => textOf(node.children[0]) === '∑'), 'nolimits keeps side scripts');
|
|
249
|
-
const operatorTokens = tokens(trees.get('operators'));
|
|
250
|
-
for (const name of ['sin', 'arg max']) assert(operatorTokens.some(([tag, text]) => tag === 'mo' && text === name), 'one named-operator token: ' + name);
|
|
251
|
-
const overridden = trees.get('atom-class-limits');
|
|
252
|
-
assert(tokens(overridden).some(([tag, text]) => tag === 'mo' && text === 'x'), 'explicit simple relation class is retained');
|
|
253
|
-
assert(tokens(overridden).some(([tag, text]) => tag === 'mi' && text === 'y'), 'compound operator class preserves inner mathematical structure');
|
|
254
|
-
const fixedLimits = one(overridden, 'munderover');
|
|
255
|
-
assert.deepEqual(fixedLimits.children.map(textOf), ['∑', '0', '1']);
|
|
256
|
-
assert.equal(one(fixedLimits.children[0], 'mo').attrs.movablelimits, 'false', 'Core cannot undo explicit limits applied after scripts');
|
|
257
|
-
const decorations = trees.get('fences-accents');
|
|
258
|
-
assert.equal(textOf(one(decorations, 'mover').children[0]), 'x', 'accent owns its base');
|
|
259
|
-
assert.equal(textOf(one(decorations, 'munder').children[0]), 'y', 'under-accent owns its base');
|
|
260
|
-
assert.deepEqual(one(decorations, 'munderover').children.map(textOf), ['=', 'v', 'u'], 'under/over follows base/under/over order');
|
|
261
|
-
assert.deepEqual(rowTexts(trees.get('matrix')), [['1', '2'], ['3', '4']], 'matrix row/cell order');
|
|
262
|
-
assert.deepEqual(rowTexts(trees.get('cases')), [['x', 'x≥0'], ['−x', 'otherwise']], 'cases retain expression/condition pairing');
|
|
263
|
-
assert.deepEqual(rowTexts(trees.get('aligned')), [['a', '=b+c'], ['d', '=e']], 'alignment retains equation cells');
|
|
264
|
-
assert.deepEqual(rowTexts(trees.get('array-insertion')).map(row => row.join('')), ['x=1', 'y=2'], 'array insertions remain mathematical content');
|
|
265
|
-
assert(tokens(trees.get('style-text')).some(([tag, text]) => tag === 'mtext' && text === 'speed 12.5'), 'text is not retokenized as a product');
|
|
266
|
-
assert.deepEqual(one(trees.get('macro'), 'mfrac').children.map(textOf), ['12', '34'], 'macro-expanded mathematical relationships survive');
|
|
267
|
-
const explicit = tokens(trees.get('explicit-tokens'));
|
|
268
|
-
for (const expected of [['mi', 'speed'], ['mn', '12.34'], ['mo', 'lim'], ['mtext', 'word']]) assert(explicit.some(token => token[0] === expected[0] && token[1] === expected[1]), 'explicit token identity: ' + expected.join(':'));
|
|
269
|
-
const link = one(trees.get('links'), 'a');
|
|
270
|
-
assert.equal(link.attrs.href, 'https://example.com/?a=1&b=2');
|
|
271
|
-
assert.deepEqual(one(link, 'mfrac').children.map(textOf), ['x', '2'], 'link retains nested mathematical structure');
|
|
272
|
-
assert(find(trees.get('chemistry'), 'msub').some(node => textOf(node.children[1]) === '2'), 'chemistry retains lowered subscript structure');
|
|
273
|
-
assert(tokens(trees.get('chemistry')).some(([tag, text]) => tag === 'mo' && text === '→'), 'chemistry retains reaction-arrow presentation');
|
|
274
|
-
assert.equal(find(trees.get('physics-units'), 'mfrac').length, 1, 'derivative fraction is structured');
|
|
275
|
-
assert(find(trees.get('physics-units'), 'msup').some(node => textOf(node.children[0]) === '10' && textOf(node.children[1]) === '−3'), 'unit scientific notation retains lowered power structure');
|
|
276
|
-
assert(textOf(trees.get('tags-labels')).includes('A'), 'authored tag is retained');
|
|
277
|
-
assert(![...walk(trees.get('tags-labels'))].some(node => node.attrs.id || node.attrs.href), 'label does not invent equation identity or references');
|
|
278
|
-
assert.equal(textOf(one(trees.get('presentation'), 'mphantom')), 'a', 'intentional phantom content is not discarded');
|
|
279
|
-
|
|
280
|
-
for (const {id, tree} of parsed.hosts) {
|
|
281
|
-
if (id === 'unsupported') continue;
|
|
282
|
-
const descend = (node, hidden = false) => {
|
|
283
|
-
const isHidden = hidden || node.attrs['aria-hidden'] === 'true';
|
|
284
|
-
assert(!(isHidden && (node.attrs.href || (node.attrs.tabindex !== undefined && Number(node.attrs.tabindex) >= 0))), id + ': no focus target in hidden output');
|
|
285
|
-
if (node.tag === 'svg') assert(isHidden, id + ': visual SVG excluded from duplicate announcements');
|
|
286
|
-
if (node.tag === 'math') assert(!isHidden, id + ': semantic math remains exposed');
|
|
287
|
-
for (const child of node.children) descend(child, isHidden);
|
|
288
|
-
};
|
|
289
|
-
descend(tree);
|
|
290
|
-
if (id === 'links') {
|
|
291
|
-
assert.equal(find(tree, 'svg').length, 0, 'linked composition exposes one native MathML presentation');
|
|
292
|
-
assert.equal(find(tree, 'a').length, 1, 'one authored link produces one focus target');
|
|
293
|
-
} else {
|
|
294
|
-
assert.equal(find(tree, 'svg').length, 1);
|
|
295
|
-
assert.equal(find(tree, 'math').length, 1);
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// Observe work in the exact classic body; counters delegate every real operation unchanged.
|
|
300
|
-
const work = {parses: 0, layoutVisits: 0, fontDecodes: 0};
|
|
301
|
-
let instrumented = classicSource;
|
|
302
|
-
for (const [signature, counter] of [['function parseMathTex(source) {', 'parses'], ['function mathLayout(n,c) {', 'layoutVisits']]) {
|
|
303
|
-
assert.equal(instrumented.split(signature).length, 2, 'one known observation seam');
|
|
304
|
-
instrumented = instrumented.replace(signature, signature + '\nglobalThis.__semanticWork.' + counter + '++;');
|
|
305
|
-
}
|
|
306
|
-
const observed = createContext({URL, __semanticWork: work, atob(value) {work.fontDecodes++; return atob(value);}});
|
|
307
|
-
new Script(instrumented, {filename: resources.bundle}).runInContext(observed);
|
|
308
|
-
const importFontDecodes = work.fontDecodes;
|
|
309
|
-
const formula = corpus[0].source;
|
|
310
|
-
Object.assign(work, {parses: 0, layoutVisits: 0, fontDecodes: 0});
|
|
311
|
-
assert.equal(observed.RapierMath.toMathML(formula).status, 'complete');
|
|
312
|
-
assert.deepEqual(work, {parses: 1, layoutVisits: 0, fontDecodes: 0}, 'semantic call parses once and performs no layout or lazy font decoding');
|
|
313
|
-
Object.assign(work, {parses: 0, layoutVisits: 0, fontDecodes: 0});
|
|
314
|
-
const combined = observed.RapierMath.renderWithMathML(formula);
|
|
315
|
-
assert.equal(combined.errors.length, 0);
|
|
316
|
-
assert.equal(work.parses, 1, 'combined SVG and MathML share one parse');
|
|
317
|
-
assert(work.layoutVisits > 0, 'combined probe exercises actual layout');
|
|
318
|
-
const combinedWork = {...work};
|
|
319
|
-
|
|
320
|
-
// Cold native semantic entry executes with font/network/DOM access guards, without a mocked renderer.
|
|
321
|
-
const cold = spawnSync(process.execPath, ['--input-type=module', '-e', `
|
|
322
|
-
import assert from 'node:assert/strict';
|
|
323
|
-
for (const name of ['atob', 'fetch', 'document', 'window'])
|
|
324
|
-
Object.defineProperty(globalThis, name, {configurable: true, get() {throw new Error('Unexpected semantic dependency: ' + name);}});
|
|
325
|
-
const math = await import(process.argv[1]);
|
|
326
|
-
const result = math.toMathML(process.argv[2]);
|
|
327
|
-
assert.equal(result.status, 'complete');
|
|
328
|
-
assert.equal(math.parse(process.argv[2]).type, 'row');
|
|
329
|
-
process.stdout.write(JSON.stringify(result));
|
|
330
|
-
`, entry('./mathml'), formula], {encoding: 'utf8', maxBuffer: 2 * 1024 * 1024});
|
|
331
|
-
assert.equal(cold.status, 0, 'cold font-free native entry: ' + (cold.error?.message || cold.stderr));
|
|
332
|
-
assert.deepEqual(JSON.parse(cold.stdout), module.toMathML(formula), 'cold entry preserves real semantic output');
|
|
333
|
-
|
|
334
|
-
console.log(JSON.stringify({name: pkg.name, version: module.version, runtime: process.version,
|
|
335
|
-
xml: {python: parsed.python, lxml: parsed.xml, libxml: parsed.libxml}, corpus: corpus.length,
|
|
336
|
-
sourceOmissions: 2, sourceCustody: 'exact after XML parsing; reversible UTF-16 carrier for invalid XML',
|
|
337
|
-
entryAgreement: 'native ESM, classic, font-free ESM, combined render',
|
|
338
|
-
composition: 'one exposed semantic presentation; no hidden or duplicate authored link focus targets',
|
|
339
|
-
work: {fullImportFontDecodes: importFontDecodes, standaloneCall: {parses: 1, layoutVisits: 0, fontDecodes: 0}, combined: combinedWork},
|
|
340
|
-
coldSemanticEntry: 'no font, network or DOM access', assistiveTechnology: 'not exercised'}));
|
package/tests/typeset.mjs
DELETED
|
@@ -1,172 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Typesetting faults, each with its reproducer. Where the TeXbook's Appendix G decides, the expected
|
|
3
|
-
// value is LuaTeX's own output for the same formula (unicode-math, Latin Modern Math 1.959), in ems.
|
|
4
|
-
// Replay: node tests/typeset.mjs [package-root]. Ink is measured from the font's own contour strips.
|
|
5
|
-
import assert from 'node:assert/strict';
|
|
6
|
-
import {dirname, resolve} from 'node:path';
|
|
7
|
-
import {fileURLToPath, pathToFileURL} from 'node:url';
|
|
8
|
-
|
|
9
|
-
const root = resolve(process.argv[2] || resolve(dirname(fileURLToPath(import.meta.url)), '..'));
|
|
10
|
-
const load = file => import(pathToFileURL(resolve(root, 'src/math', file)).href);
|
|
11
|
-
const {MATH_FONT} = await load('font.js'), L = await load('layout.js');
|
|
12
|
-
const {mathPrepare} = await load('source.js'), {mathToMathML} = await load('semantic-api.js'), {renderMath} = await load('api.js');
|
|
13
|
-
const context = (display = false) => ({size: 1, level: 0, variant: 'normal', cramped: false, display, cache: new WeakMap(), budget: {nodes: 0, outlineBytes: 0}});
|
|
14
|
-
function layout(tex, display = false) {
|
|
15
|
-
const {tree, error} = mathPrepare(tex);
|
|
16
|
-
assert(!error, tex + ': ' + error?.message);
|
|
17
|
-
return L.mathLayout(tree, context(display));
|
|
18
|
-
}
|
|
19
|
-
const mathml = tex => mathToMathML(tex).mathml;
|
|
20
|
-
|
|
21
|
-
// Every outline in an SVG fragment: its glyph, origin and scale, from the transforms that place it.
|
|
22
|
-
const paths = new Map();
|
|
23
|
-
function glyphOf(d) {
|
|
24
|
-
if (!paths.size) for (let id = 0, g; (g = MATH_FONT.glyph(id)); id++) { if (g?.[7] && !paths.has(g[7])) paths.set(g[7], id); }
|
|
25
|
-
return paths.get(d);
|
|
26
|
-
}
|
|
27
|
-
function glyphs(svg) {
|
|
28
|
-
const found = [], stack = [[0, 0, 1, 1]];
|
|
29
|
-
for (const [tag] of svg.matchAll(/<\/?g\b[^>]*>|<path\b[^>]*>/g)) {
|
|
30
|
-
if (tag === '</g>') { stack.pop(); continue; }
|
|
31
|
-
const [x, y, sx, sy] = stack.at(-1), t = /translate\(([-\d.e]+) ([-\d.e]+)\)/.exec(tag), s = /scale\(([-\d.e]+) ([-\d.e]+)\)/.exec(tag);
|
|
32
|
-
let next = [x, y, sx, sy];
|
|
33
|
-
if (tag.startsWith('<g')) {
|
|
34
|
-
if (t) next = [x + sx * +t[1], y + sy * +t[2], sx, sy];
|
|
35
|
-
if (s) next = [next[0], next[1], sx * +s[1], sy * +s[2]];
|
|
36
|
-
stack.push(next);
|
|
37
|
-
} else {
|
|
38
|
-
const d = /\bd="([^"]+)"/.exec(tag)?.[1], id = d && glyphOf(d);
|
|
39
|
-
if (id !== undefined && s) found.push({id, x, y, sx: sx * +s[1], sy: sy * -s[2]});
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
return found;
|
|
43
|
-
}
|
|
44
|
-
// Horizontal ink strips of a placed glyph (its contour profile; its bounds when unprofiled).
|
|
45
|
-
function strips({id, x, y, sx, sy}) {
|
|
46
|
-
const g = MATH_FONT.glyph(id), p = MATH_FONT.profile(id), out = [];
|
|
47
|
-
if (!p) return [{top: y - g[4] * sy, bottom: y - g[2] * sy, left: x + g[1] * sx, right: x + g[3] * sx}];
|
|
48
|
-
for (let i = 1; i < p.length; i++) if (p[i])
|
|
49
|
-
out.push({top: y - (p[0] + i * MATH_FONT.edgeStep) * sy, bottom: y - (p[0] + (i - 1) * MATH_FONT.edgeStep) * sy, left: x + p[i][0] * sx, right: x + p[i][1] * sx});
|
|
50
|
-
return out;
|
|
51
|
-
}
|
|
52
|
-
// Smallest horizontal gap between two glyphs' ink where they share a height; negative when the ink overlaps.
|
|
53
|
-
function inkGap(a, b) {
|
|
54
|
-
let gap = Infinity;
|
|
55
|
-
for (const s of strips(a)) for (const t of strips(b))
|
|
56
|
-
if (s.top < t.bottom && t.top < s.bottom) gap = Math.min(gap, Math.max(t.left - s.right, s.left - t.right) <= 0 ? -Math.min(s.right - t.left, t.right - s.left) : Math.max(t.left - s.right, s.left - t.right));
|
|
57
|
-
return gap;
|
|
58
|
-
}
|
|
59
|
-
const ink = item => strips(item).reduce((r, s) => ({left: Math.min(r.left, s.left), right: Math.max(r.right, s.right), top: Math.min(r.top, s.top), bottom: Math.max(r.bottom, s.bottom)}), {left: Infinity, right: -Infinity, top: Infinity, bottom: -Infinity});
|
|
60
|
-
const near = (actual, expected, message, tolerance = 0.01) => assert(Math.abs(actual - expected) <= tolerance, message + ': ' + actual.toFixed(3) + ' (TeX ' + expected + ')');
|
|
61
|
-
|
|
62
|
-
const cells = [];
|
|
63
|
-
const cell = (id, claim, check) => cells.push({id, claim, check});
|
|
64
|
-
|
|
65
|
-
cell('F1', 'a superscript clears an over-accent', () => {
|
|
66
|
-
for (const tex of [String.raw`\hat{i}^2`, String.raw`\vec{x}^2`, String.raw`\tilde{\jmath}^2`, String.raw`\dot{x}^n`]) {
|
|
67
|
-
const [, accent, script] = glyphs(layout(tex).svg);
|
|
68
|
-
assert(inkGap(accent, script) > 0, tex + ': superscript ink meets the accent');
|
|
69
|
-
}
|
|
70
|
-
// TeX's rule 18a keeps \hat{x}^2 where x^2 is.
|
|
71
|
-
near(glyphs(layout(String.raw`\hat{x}^2`).svg)[2].x, glyphs(layout('x^2').svg)[1].x, String.raw`\hat{x}^2 script`, 0.08);
|
|
72
|
-
});
|
|
73
|
-
cell('F2', 'a subscript keeps the slanted letter clear of the next', () => {
|
|
74
|
-
for (const tex of ['V_i H', 'V_i T', 'W_i Y']) {
|
|
75
|
-
const items = glyphs(layout(tex).svg);
|
|
76
|
-
assert(inkGap(items[0], items.at(-1)) >= 0, tex + ': the next letter meets the slanted letter');
|
|
77
|
-
}
|
|
78
|
-
});
|
|
79
|
-
cell('F3', 'an under-accent adds only its own depth', () => {
|
|
80
|
-
assert(layout(String.raw`\utilde{x}`).d <= 0.492, String.raw`\utilde{x} depth exceeds TeX's 0.492`);
|
|
81
|
-
assert(layout(String.raw`\underaccent{\bar}{x}`).d <= 0.439, String.raw`\underaccent{\bar}{x} depth exceeds TeX's 0.439`);
|
|
82
|
-
});
|
|
83
|
-
cell('F4', 'braces centre on slanted letters', () => {
|
|
84
|
-
const over = glyphs(layout(String.raw`\overbrace{f}`, true).svg), f = over.find(item => item.id === MATH_FONT.chars[0x1d453]);
|
|
85
|
-
const middle = item => (ink(item).left + ink(item).right) / 2;
|
|
86
|
-
near(middle(over.find(item => item !== f)) - f.x, layout('f', true).w / 2, String.raw`\overbrace{f} brace centre`, 0.01);
|
|
87
|
-
const v = layout(String.raw`\underbrace{V}_n`, true), items = glyphs(v.svg), n = items.at(-1), nW = MATH_FONT.glyph(n.id)[0] * n.sx;
|
|
88
|
-
const vItem = items.find(item => item.id === MATH_FONT.chars[0x1d449]);
|
|
89
|
-
near(n.x + nW / 2 - vItem.x, layout('V', true).w / 2, String.raw`\underbrace{V}_n label centre`, 0.01);
|
|
90
|
-
});
|
|
91
|
-
cell('F5', 'a radical degree kerns into the sign', () => {
|
|
92
|
-
const sign = glyphs(layout(String.raw`\sqrt[3]{x}`).svg).find(item => item.id === MATH_FONT.chars[0x221a]);
|
|
93
|
-
near(sign.x, 0.062, String.raw`\sqrt[3]{x} sign x`, 0.003);
|
|
94
|
-
});
|
|
95
|
-
cell('F6', 'corner delimiters sit where TeX puts them', () => {
|
|
96
|
-
const items = glyphs(layout(String.raw`\left\ulcorner\frac{a}{b}\right\urcorner`, true).svg);
|
|
97
|
-
near(items[0].y, 0.135, String.raw`\ulcorner origin y`);
|
|
98
|
-
const low = glyphs(layout(String.raw`\left\llcorner\frac{a}{b}\right\lrcorner`, true).svg);
|
|
99
|
-
near(low[0].y, -0.380, String.raw`\llcorner origin y`);
|
|
100
|
-
});
|
|
101
|
-
cell('F7', 'starred cases set conditions as text', () => {
|
|
102
|
-
const {tree, error} = mathPrepare(String.raw`\begin{cases*} x & if $x > 0$ \\ 0 & otherwise \end{cases*}`);
|
|
103
|
-
assert(!error, 'cases*: ' + error?.message);
|
|
104
|
-
const condition = JSON.stringify(tree.children[0].body ?? tree.children[0]);
|
|
105
|
-
assert(/"type":"text","value":"if/.test(condition) && /"value":"otherwise"/.test(condition), 'cases* condition is text');
|
|
106
|
-
});
|
|
107
|
-
cell('F8', 'mhchem isotopes', () => {
|
|
108
|
-
const {tree, error} = mathPrepare(String.raw`\ce{^{235}_{92}U + ^1_0n}`);
|
|
109
|
-
assert(!error);
|
|
110
|
-
assert(!/"base":\{"type":"glyph","value":"\+"/.test(JSON.stringify(tree)), String.raw`\ce: the scripts before n stay on n, not on +`);
|
|
111
|
-
const items = glyphs(layout(String.raw`\ce{^{235}_{92}U}`).svg), right = item => item.x + MATH_FONT.glyph(item.id)[0] * item.sx;
|
|
112
|
-
near(right(items[2]), right(items[4]), String.raw`\ce isotope scripts end together (TeX)`, 0.002);
|
|
113
|
-
});
|
|
114
|
-
cell('F9', 'bold digits and bold dotless letters', () => {
|
|
115
|
-
assert.equal(layout(String.raw`\boldsymbol{0}`).glyph, MATH_FONT.chars[0x1d7ce], String.raw`\boldsymbol{0} is a bold digit`);
|
|
116
|
-
assert.equal(layout(String.raw`\bm{1}`).glyph, MATH_FONT.chars[0x1d7cf], String.raw`\bm{1} is a bold digit`);
|
|
117
|
-
assert.equal(layout(String.raw`\boldsymbol{\imath}`).glyph, MATH_FONT.dotless[MATH_FONT.chars[0x1d48a]], String.raw`\boldsymbol{\imath} is bold dotless`);
|
|
118
|
-
assert.equal(layout(String.raw`\mathbf{\jmath}`).glyph, MATH_FONT.dotless[MATH_FONT.chars[0x1d423]], String.raw`\mathbf{\jmath} is bold dotless`);
|
|
119
|
-
});
|
|
120
|
-
cell('F10', 'binary and fraction spacing, matrix cells', () => {
|
|
121
|
-
near(layout(String.raw`a\boldsymbol{+}b`).w, 2.180, String.raw`a\boldsymbol{+}b width`, 0.002);
|
|
122
|
-
near(layout(String.raw`a\textcolor{red}{+}b`).w, 1.736, String.raw`a\textcolor{red}{+}b width (a braced group is ordinary)`, 0.002);
|
|
123
|
-
const f = layout(String.raw`\frac{1}{2},`);
|
|
124
|
-
near(f.rowItems[1][1] - f.rowItems[0][0].w, 0, String.raw`\frac{1}{2}, space before the comma`, 0.002);
|
|
125
|
-
const cramped = layout(String.raw`\frac{1}{\begin{matrix}x^2\end{matrix}}`, true), plain = layout(String.raw`\begin{matrix}x^2\end{matrix}`);
|
|
126
|
-
near(glyphs(cramped.svg).at(-1).y - glyphs(cramped.svg).at(-2).y, glyphs(plain.svg).at(-1).y - glyphs(plain.svg).at(-2).y, 'matrix cell superscript rise inside a denominator', 0.001);
|
|
127
|
-
});
|
|
128
|
-
cell('F11', 'MathML Core attributes', () => {
|
|
129
|
-
assert(!/movablelimits="false">max/.test(mathml(String.raw`\overline{A_{\max}}`)), String.raw`\max in a script keeps its own limits`);
|
|
130
|
-
assert(/<mtable displaystyle="true"[^>]*data-math-environment="darray"/.test(mathml(String.raw`\begin{darray}{c}x\end{darray}`)), 'darray is display style');
|
|
131
|
-
assert(/<mi[^>]*>℧<\/mi><mi[^>]*>⅁<\/mi>/.test(mathml(String.raw`\mho\Game`)), String.raw`\mho and \Game are identifiers`);
|
|
132
|
-
assert(!/form="infix"[^>]*>\+/.test(mathml('(a+)')), 'a trailing plus is not infix');
|
|
133
|
-
});
|
|
134
|
-
cell('F12', 'colour paints once; a fence without \\middle lays out once', () => {
|
|
135
|
-
const svg = renderMath(String.raw`\color{red}a+b+c=1+2+3`, {maxWidth: 3}).svg;
|
|
136
|
-
assert(!/<g fill="red"[^>]*><g fill="red"/.test(svg), 'colour is painted twice');
|
|
137
|
-
const {tree} = mathPrepare(String.raw`\left(a+b\right)`), c = context();
|
|
138
|
-
L.mathLayout(tree, c);
|
|
139
|
-
const {tree: body} = mathPrepare('(a+b)'), d = context();
|
|
140
|
-
L.mathLayout(body, d);
|
|
141
|
-
assert(c.budget.nodes <= d.budget.nodes, 'fence body laid out twice: ' + c.budget.nodes + ' visits for ' + d.budget.nodes);
|
|
142
|
-
});
|
|
143
|
-
cell('F13', 'what people write most', () => {
|
|
144
|
-
const inputs = [String.raw`\SI{9.81}{m.s^{-2}}`, String.raw`\SI{3}{\kilo\gram\metre\per\second\squared}`, String.raw`\num{12345.678}`, String.raw`\si{\ohm}`, String.raw`\unit{\micro\metre}`, String.raw`\ang{30;15;10}`,
|
|
145
|
-
String.raw`\mel{n}{H}{m}`, String.raw`\ev{x}`, String.raw`\ip{a}{b}`, String.raw`\op{a}{b}`, String.raw`\pb{f}{g}`, String.raw`\qq{if}`, String.raw`\qc`, String.raw`\Res`,
|
|
146
|
-
String.raw`\idotsint`, String.raw`\smashoperator{\sum_{i=1}^n}`, String.raw`\begin{multlined}a\\b\end{multlined}`, String.raw`\begin{lgathered}a\\b\end{lgathered}`, String.raw`\begin{rgathered}a\\b\end{rgathered}`,
|
|
147
|
-
String.raw`\mathmakebox[2em][l]{x}`, String.raw`\not\in`, String.raw`\not\subset`];
|
|
148
|
-
const rejected = inputs.filter(tex => mathPrepare(tex).error);
|
|
149
|
-
assert.deepEqual(rejected, [], 'rejected');
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
cell('P1', 'a formula being typed previews without an error', () => {
|
|
153
|
-
for (const tex of [String.raw`\frac{-b\pm\sqrt{b^2-4ac}}{2a}`, String.raw`\begin{pmatrix}1 & 2\\3 & 4\end{pmatrix}`, String.raw`\left(x+1\right)^{\sqrt[3]{y}}`])
|
|
154
|
-
for (let i = 1; i <= tex.length; i++) {
|
|
155
|
-
const prefix = tex.slice(0, i), result = renderMath(prefix, {preview: true});
|
|
156
|
-
assert.deepEqual(result.errors, [], 'preview of ' + prefix);
|
|
157
|
-
assert(result.svg.includes('<title>' + prefix.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>') + '</title>'), 'exact source of ' + prefix);
|
|
158
|
-
}
|
|
159
|
-
for (const [tex, caret] of [[String.raw`\sqrt{x^}`, 8], [String.raw`\sqrt{x+\}`, 9], [String.raw`a+\fra{}`, 6]])
|
|
160
|
-
assert.deepEqual(renderMath(tex, {preview: true, caret}).errors, [], 'preview at the caret of ' + tex);
|
|
161
|
-
assert.equal(renderMath(String.raw`\frac{1}{`).errors.length, 1, 'strict rendering is unchanged');
|
|
162
|
-
assert.equal(renderMath(String.raw`\frac{a}{b} \farc + 1`, {preview: true}).errors[0]?.suggestion, String.raw`\frac`, 'a fault before the end stays, with a suggestion');
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
const results = [];
|
|
166
|
-
for (const {id, claim, check} of cells) {
|
|
167
|
-
try { check(); results.push([id, 'green', claim]); }
|
|
168
|
-
catch (error) { results.push([id, 'red', claim + ': ' + error.message]); }
|
|
169
|
-
}
|
|
170
|
-
for (const row of results) console.log(row.join('\t'));
|
|
171
|
-
assert(results.every(row => row[1] === 'green'), 'red cells');
|
|
172
|
-
console.log(JSON.stringify({cells: results.length, typesetting: 'TeX where Appendix G decides'}));
|
package/tests/verify.mjs
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Verify each carried owner once and rebuild both current runtime formats.
|
|
3
|
-
import assert from 'node:assert/strict';
|
|
4
|
-
import {readFile} from 'node:fs/promises';
|
|
5
|
-
import {createHash} from 'node:crypto';
|
|
6
|
-
import {dirname, resolve} from 'node:path';
|
|
7
|
-
import {fileURLToPath} from 'node:url';
|
|
8
|
-
import {assembleMath} from '../src/tools/build-math.mjs';
|
|
9
|
-
import {mathReadme} from '../src/math/package-readme.mjs';
|
|
10
|
-
|
|
11
|
-
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
12
|
-
const read = path => readFile(resolve(root, path));
|
|
13
|
-
const hash = (bytes, algorithm = 'sha256', encoding = 'hex') => createHash(algorithm).update(bytes).digest(encoding);
|
|
14
|
-
const resources = JSON.parse(await read('docs/math-resources.json'));
|
|
15
|
-
const payload = await read(resources.packageBundle);
|
|
16
|
-
assert.equal(payload.length, resources.bytes, 'payload length');
|
|
17
|
-
assert.equal(hash(payload), resources.sha256, 'payload SHA-256');
|
|
18
|
-
assert.equal(hash(payload, 'sha384', 'base64'), resources.sha384, 'payload SHA-384');
|
|
19
|
-
const paths = new Set();
|
|
20
|
-
for (const file of ['stream.mjs', 'stream.d.ts', 'reuse.mjs', 'integration.mjs'])
|
|
21
|
-
assert.equal(resources.adoption.filter(input => input.file === 'math/' + file && input.packageFile === 'dist/' + file).length,
|
|
22
|
-
1, file + ': one required package/source owner');
|
|
23
|
-
for (const input of [...resources.sources, ...resources.recipe, ...resources.adoption]) {
|
|
24
|
-
assert(!paths.has(input.packageFile), 'one public location per owner');
|
|
25
|
-
paths.add(input.packageFile);
|
|
26
|
-
const bytes = await read(input.packageFile);
|
|
27
|
-
assert.equal(bytes.length, input.bytes, input.file + ': length');
|
|
28
|
-
assert.equal(hash(bytes), input.sha256, input.file + ': SHA-256');
|
|
29
|
-
}
|
|
30
|
-
const rendererLicense = await read('src/math/LICENSE-MIT');
|
|
31
|
-
const fontLicense = await read('src/math/FONT-LICENSE.txt');
|
|
32
|
-
assert.equal(hash(fontLicense), resources.font.licenseSha256, 'font license SHA-256');
|
|
33
|
-
for (const text of [payload, await read('LICENSE')]) {
|
|
34
|
-
assert(text.includes(rendererLicense.toString('utf8').trim()), 'complete renderer license');
|
|
35
|
-
assert(text.includes(fontLicense.toString('utf8').trim()), 'complete font license');
|
|
36
|
-
}
|
|
37
|
-
const sbom = JSON.parse(await read('docs/math-components.json'));
|
|
38
|
-
const font = sbom.packages.find(item => item.name === resources.font.name);
|
|
39
|
-
assert.equal(font?.copyrightText, resources.font.copyright, 'font copyright');
|
|
40
|
-
assert.equal(font.licenseDeclared, resources.font.license, 'font license identity');
|
|
41
|
-
assert.equal(sbom.hasExtractedLicensingInfos.find(item => item.licenseId === resources.font.license)?.extractedText,
|
|
42
|
-
fontLicense.toString('utf8'), 'complete extracted font license');
|
|
43
|
-
assert.equal((await read('README.md')).toString('utf8'), mathReadme(resources), 'generated README');
|
|
44
|
-
const rebuilt = await assembleMath({root, packageLayout: true});
|
|
45
|
-
assert.deepEqual(rebuilt.bytes, payload, 'rebuilt classic payload');
|
|
46
|
-
for (const [file, content] of rebuilt.modules)
|
|
47
|
-
assert.equal((await read(file)).toString('utf8'), content, 'rebuilt native module: ' + file);
|
|
48
|
-
console.log(JSON.stringify({file: resources.packageBundle, bytes: payload.length, sha256: resources.sha256,
|
|
49
|
-
sourceFiles: paths.size, rebuild: 'exact', licenses: 'complete'}));
|