rapier-math 1.1.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +15 -5
  2. package/dist/accessible.css +6 -0
  3. package/dist/accessible.d.ts +10 -0
  4. package/dist/accessible.mjs +18 -0
  5. package/dist/classic.d.ts +8 -2
  6. package/dist/combined.d.ts +4 -0
  7. package/dist/combined.mjs +2 -0
  8. package/dist/index.d.ts +11 -0
  9. package/dist/index.mjs +6 -2980
  10. package/dist/integration.d.ts +11 -2
  11. package/dist/integration.mjs +96 -13
  12. package/dist/markdown-it.d.ts +7 -0
  13. package/dist/markdown-it.mjs +33 -19
  14. package/dist/mathml.d.ts +5 -0
  15. package/dist/mathml.mjs +3 -0
  16. package/dist/rapier-math.js +595 -143
  17. package/dist/rehype.d.ts +7 -0
  18. package/dist/rehype.mjs +28 -7
  19. package/dist/reuse.mjs +110 -0
  20. package/dist/stream.d.ts +36 -3
  21. package/dist/stream.mjs +63 -38
  22. package/docs/api.md +155 -26
  23. package/docs/math-components.json +6 -5
  24. package/docs/math-resources.json +170 -68
  25. package/docs/semantics.md +228 -0
  26. package/examples/README.md +15 -2
  27. package/examples/accessible.html +27 -0
  28. package/examples/accessible.mjs +42 -0
  29. package/examples/markdown.mjs +21 -4
  30. package/examples/semantic.mjs +11 -0
  31. package/examples/stream.mjs +31 -11
  32. package/examples/unified.mjs +17 -3
  33. package/package.json +16 -2
  34. package/src/math/api.js +16 -55
  35. package/src/math/browser.js +4 -0
  36. package/src/math/classic.js +7 -0
  37. package/src/math/combined.js +13 -0
  38. package/src/math/fallbacks.js +5 -0
  39. package/src/math/font.js +3 -0
  40. package/src/math/layout.js +6 -37
  41. package/src/math/mathml.js +406 -0
  42. package/src/math/package-build.mjs +24 -11
  43. package/src/math/package-layout.mjs +3 -0
  44. package/src/math/package-readme.mjs +14 -4
  45. package/src/math/parser.js +14 -11
  46. package/src/math/responsive.js +4 -0
  47. package/src/math/semantic-api.js +12 -0
  48. package/src/math/source.js +67 -0
  49. package/src/math/symbols.js +3 -0
  50. package/src/math/variants.js +41 -0
  51. package/src/tools/build-math.mjs +20 -11
  52. package/tests/adoption.mjs +112 -9
  53. package/tests/check.mjs +20 -5
  54. package/tests/semantics.mjs +340 -0
  55. package/tests/verify.mjs +6 -3
@@ -1,9 +1,18 @@
1
1
  // SPDX-License-Identifier: MIT
2
- import type {RenderOptions} from './index.js';
2
+ import type {RenderOptions, RenderResult, MathError} from './index.js';
3
+ import type {MathSession} from './stream.js';
3
4
  export interface IntegrationOptions {
5
+ /** Insert SVG with assistive MathML. Include accessible.css. */
6
+ accessible?: boolean;
7
+ /** With an explicit session, plain-data options and screen are captured once per document render. */
4
8
  renderOptions?: RenderOptions;
5
9
  /** Per document. Default 1024. Exhaustion leaves subsequent math as source. */
6
10
  maxFormulas?: number;
7
- /** Combined successful SVG code units per document. Default 16 * 1024 * 1024. */
11
+ /** Combined successful insertion markup code units per document. Default 16 Mi. */
8
12
  maxOutputLength?: number;
9
13
  }
14
+ export type FormulaResult = (RenderResult & {markup: string}) | {errors: MathError[]};
15
+ /** Internal adapter owner; every call creates a fresh document admission budget. */
16
+ export function createFormulaRenderer(options?: IntegrationOptions, session?: MathSession):
17
+ (source: string, displayMode: boolean, inLink?: boolean) => FormulaResult;
18
+ export function escapeText(text: string): string;
@@ -1,28 +1,111 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  import {render} from './index.mjs';
3
+ import {renderAccessible} from './accessible.mjs';
4
+ import {mathDiagnostic} from '../src/math/source.js';
5
+ import {assertMathSession, reuseFormula} from './reuse.mjs';
3
6
 
4
7
  export const escapeText = text => text.replace(/[&<>"'\r]/g, char =>
5
8
  ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '\r': '&#13;'}[char]));
6
9
 
7
- // One budget per document render. Rejection leaves the host's text node intact.
8
- export function createFormulaRenderer(options = {}) {
10
+ function dataOptions(value, allowed, order) {
11
+ if (value === undefined || value === null) return {};
12
+ if (typeof value !== 'object') return null;
13
+ let fields;
14
+ try {
15
+ const prototype = Object.getPrototypeOf(value);
16
+ if (prototype !== Object.prototype && prototype !== null) return null;
17
+ } catch { return null; } // Prototype inspection is optional.
18
+ try { fields = Object.getOwnPropertyDescriptors(value); }
19
+ catch (error) {
20
+ if (!order) throw error; // Top-level spread would enumerate these fields.
21
+ return null; // Core screen access does not enumerate.
22
+ }
23
+ for (const key of Reflect.ownKeys(fields)) {
24
+ const field = fields[key];
25
+ if (!allowed.includes(key) || !field.enumerable || !('value' in field)) return null;
26
+ }
27
+ const output = {};
28
+ // Descriptor values need not equal Get values on a Proxy. Read each admitted
29
+ // property once and render exactly that captured value; derive the key from it.
30
+ // Actual Get failures propagate, rather than being silently retried as inspection.
31
+ for (const key of order || Reflect.ownKeys(fields)) output[key] = value[key];
32
+ return output;
33
+ }
34
+
35
+ // A root captures plain-data options once, including any invalid acquired value.
36
+ // The key is a fixed tuple of finite numbers/booleans, followed by exact source.
37
+ // Structural unknown/accessor shapes bypass without evaluating their getters for
38
+ // a key. Proxies that disclose a data shape render their actual captured values.
39
+ function configuration(input) {
40
+ let options;
41
+ try { options = dataOptions(input, ['displayMode', 'maxWidth', 'screen']); }
42
+ catch (error) { return {key: null, error}; }
43
+ if (!options) return {options: input, key: null};
44
+ let cacheable = (options.displayMode === undefined || typeof options.displayMode === 'boolean') &&
45
+ (options.maxWidth === undefined || Number.isFinite(options.maxWidth));
46
+ let screenKey = '-';
47
+ if (options.screen !== undefined) {
48
+ let screen;
49
+ try { screen = dataOptions(options.screen, ['fontSize', 'pixelRatio', 'dark'], ['fontSize', 'pixelRatio', 'dark']); }
50
+ catch (error) {
51
+ // Screen access belongs inside the core's source/diagnostic admission. Keep
52
+ // that ordering, including when source itself is refused before screen use.
53
+ options.screen = Object.freeze({get fontSize() { throw error; }});
54
+ return {options: Object.freeze(options), key: null};
55
+ }
56
+ if (!screen) cacheable = false;
57
+ else {
58
+ options.screen = Object.freeze(screen);
59
+ cacheable &&= Number.isFinite(screen.fontSize) && Number.isFinite(screen.pixelRatio) && typeof screen.dark === 'boolean';
60
+ if (cacheable) screenKey = screen.fontSize + '|' + screen.pixelRatio + '|' + Number(screen.dark);
61
+ }
62
+ }
63
+ return {options: Object.freeze(options), key: cacheable ? (options.maxWidth === undefined ? '-' : options.maxWidth) + '|' + screenKey : null};
64
+ }
65
+
66
+ function failure(message) {
67
+ return {errors: [{code: 'resource-limit', offset: 0, message}]};
68
+ }
69
+
70
+ // One insertion boundary preserves the renderer payload and supplies the complete
71
+ // markup consumed by both adapters. Admission is charged after materialization.
72
+ function materialize(result) {
73
+ return {...result, markup: result.html ?? result.svg};
74
+ }
75
+
76
+ // One budget per document render, never per env/session/parser instance.
77
+ export function createFormulaRenderer(options = {}, session) {
78
+ assertMathSession(session);
9
79
  const maxFormulas = options.maxFormulas ?? 1024, maxOutputLength = options.maxOutputLength ?? 16 * 1024 * 1024;
10
80
  for (const value of [maxFormulas, maxOutputLength])
11
81
  if (!Number.isSafeInteger(value) || value < 0) throw new RangeError('Math integration budgets must be finite nonnegative integers.');
82
+ const accessible = !!options.accessible;
83
+ const captured = session === undefined ? null : configuration(options.renderOptions);
12
84
  let count = 0, length = 0;
13
- return (source, displayMode) => {
14
- let result;
15
- if (count >= maxFormulas || length >= maxOutputLength) return {errors: [{code: 'resource-limit', offset: 0,
16
- message: 'The document math budget is exhausted.'}]};
85
+ return (source, displayMode, inLink = false) => {
86
+ assertMathSession(session);
87
+ if (count >= maxFormulas || length >= maxOutputLength) return failure('The document math budget is exhausted.');
17
88
  count++;
18
- try { result = render(source, {...options.renderOptions, displayMode}); }
19
- catch (error) { return {errors: [{code: error.code || 'invalid-tex', message: String(error.message), offset: error.offset || 0}]}; }
20
- if (result.errors.length) return {errors: result.errors};
21
- if (result.svg.length > maxOutputLength - length) {
89
+ let result;
90
+ try {
91
+ result = reuseFormula(session, source, captured?.key == null ? null : Number(accessible) + '|' + Number(!!displayMode) + '|' + captured.key,
92
+ () => {
93
+ if (captured && Object.hasOwn(captured, 'error')) throw captured.error;
94
+ const renderOptions = {...(captured ? captured.options : options.renderOptions), displayMode};
95
+ if (!accessible) return render(source, renderOptions);
96
+ const {semantics, ...artifact} = renderAccessible(source, renderOptions);
97
+ return artifact;
98
+ });
99
+ } catch (error) { return {errors: [mathDiagnostic(error)]}; }
100
+ if (result.errors.length) return {errors: result.errors.map(error => ({...error}))};
101
+ const output = materialize(result);
102
+ if (inLink && /<a\s/.test(output.markup)) return {errors: [{code: 'nested-link', offset: 0,
103
+ message: 'A formula inside a link cannot contain another authored link.'}]};
104
+ if (output.markup.length > maxOutputLength - length) {
22
105
  length = maxOutputLength;
23
- return {errors: [{code: 'resource-limit', offset: 0, message: 'The document math output budget is exhausted.'}]};
106
+ return failure('The document math output budget is exhausted.');
24
107
  }
25
- length += result.svg.length;
26
- return result;
108
+ length += output.markup.length;
109
+ return output;
27
110
  };
28
111
  }
@@ -2,5 +2,12 @@
2
2
  import type MarkdownIt from 'markdown-it';
3
3
  import type {DelimiterOptions} from './delimiters.js';
4
4
  import type {IntegrationOptions} from './integration.js';
5
+ import type {MathError} from './index.js';
6
+ import type {MathSession} from './stream.js';
5
7
  export interface MarkdownMathOptions extends DelimiterOptions, IntegrationOptions {}
8
+ export interface MarkdownMathEnv {
9
+ /** Optional formula reuse for one message; each render still owns fresh budgets. */
10
+ rapierMathSession?: MathSession;
11
+ rapierMathErrors?: {source: string; errors: MathError[]}[];
12
+ }
6
13
  export default function rapierMath(md: InstanceType<typeof MarkdownIt>, options?: MarkdownMathOptions): void;
@@ -1,41 +1,55 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  import {installMathRules} from './markdown-rules.mjs';
3
3
  import {createFormulaRenderer, escapeText} from './integration.mjs';
4
+ import {assertMathSession} from './reuse.mjs';
4
5
 
5
6
  export default function rapierMath(md, options = {}) {
6
7
  installMathRules(md, options);
7
- let session;
8
- function withSession(renderer, render, tokens, opts, env) {
9
- const previous = session, current = {render: createFormulaRenderer(options), children: new WeakSet()};
10
- const visit = tokens => {
11
- for (const token of tokens) {
12
- if (token.children) { current.children.add(token.children); visit(token.children); }
13
- }
14
- };
15
- visit(tokens);
16
- session = current;
17
- try { return render.call(renderer, tokens, opts, env); }
18
- finally { session = previous; }
8
+ let document;
9
+ function withDocument(renderer, render, tokens, opts, env) {
10
+ const previous = document, mathSession = env?.rapierMathSession;
11
+ assertMathSession(mathSession);
12
+ try {
13
+ const current = {render: createFormulaRenderer(options, mathSession), parents: new WeakMap(), linked: new WeakSet(), activeTokens: tokens};
14
+ const visit = (tokens, depth = 0) => {
15
+ for (const token of tokens) {
16
+ if (token.type === 'link_close') depth--;
17
+ if (depth > 0) current.linked.add(token);
18
+ if (token.type === 'link_open') depth++;
19
+ if (token.children) { current.parents.set(token.children, tokens); visit(token.children, depth); }
20
+ }
21
+ };
22
+ visit(tokens);
23
+ document = current;
24
+ return render.call(renderer, tokens, opts, env);
25
+ }
26
+ catch (error) { mathSession?.clear(); throw error; }
27
+ finally { document = previous; }
19
28
  }
20
29
  const render = md.renderer.render, renderInline = md.renderer.renderInline;
21
30
  md.renderer.render = function(tokens, opts, env) {
22
- return withSession(this, render, tokens, opts, env);
31
+ return withDocument(this, render, tokens, opts, env);
23
32
  };
24
33
  md.renderer.renderInline = function(tokens, opts, env) {
25
- // The block renderer's inline children share its document budget. A separate
26
- // inline tree, including a nested host renderInline call, owns a fresh one.
27
- if (session?.children.has(tokens)) return renderInline.call(this, tokens, opts, env);
28
- return withSession(this, renderInline, tokens, opts, env);
34
+ // Only descent from the active parent shares its budget. Reentering an
35
+ // already active inline tree (or its sibling) owns a fresh document budget.
36
+ if (document && document.parents.get(tokens) === document.activeTokens) {
37
+ const current = document, previous = current.activeTokens;
38
+ current.activeTokens = tokens;
39
+ try { return renderInline.call(this, tokens, opts, env); }
40
+ finally { current.activeTokens = previous; }
41
+ }
42
+ return withDocument(this, renderInline, tokens, opts, env);
29
43
  };
30
44
  function formula(tokens, index, _options, env) {
31
45
  const token = tokens[index], display = token.type === 'math_block';
32
- const result = (session?.render || createFormulaRenderer(options))(token.content, display);
46
+ const result = (document?.render || createFormulaRenderer(options, env?.rapierMathSession))(token.content, display, document?.linked.has(token));
33
47
  if (result.errors.length) {
34
48
  (env.rapierMathErrors ||= []).push({source: token.content, errors: result.errors});
35
49
  return '<code data-math-error="' + escapeText(result.errors[0].code) + '">' +
36
50
  escapeText(token.meta?.mathSource ?? token.content) + '</code>';
37
51
  }
38
- return result.svg;
52
+ return result.markup;
39
53
  }
40
54
  md.renderer.rules.math_inline = formula;
41
55
  md.renderer.rules.math_block = (tokens, index, opts, env) => {
@@ -0,0 +1,5 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import type {MathMLOptions, MathMLResult} from './index.js';
3
+ export {parse} from './index.js';
4
+ export type {MathNode, MathError, MathMLOptions, MathMLResult} from './index.js';
5
+ export function toMathML(source: unknown, options?: MathMLOptions): MathMLResult;
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: MIT
2
+ export {parseMathTex as parse} from '../src/math/parser.js';
3
+ export {mathToMathML as toMathML} from '../src/math/semantic-api.js';