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
package/dist/rehype.d.ts CHANGED
@@ -2,5 +2,12 @@
2
2
  import type {Root} from 'hast';
3
3
  import type {VFile} from 'vfile';
4
4
  import type {IntegrationOptions} from './integration.js';
5
+ import type {MathSession} from './stream.js';
6
+ declare module 'vfile' {
7
+ interface DataMap {
8
+ /** Explicit reuse for one message; each transformed tree has fresh budgets. */
9
+ rapierMathSession?: MathSession;
10
+ }
11
+ }
5
12
  /** Install after sanitization. Recognizes remark-rehype math code nodes. */
6
13
  export default function rehypeRapierMath(options?: IntegrationOptions): (tree: Root, file: VFile) => void;
package/dist/rehype.mjs CHANGED
@@ -1,12 +1,15 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  import {fromHtml} from 'hast-util-from-html';
3
3
  import {createFormulaRenderer} from './integration.mjs';
4
+ import {assertMathSession} from './reuse.mjs';
4
5
 
5
6
  // Run AFTER the host sanitizer. Only known math code nodes are replaced, using
6
7
  // fresh renderer output parsed into HAST. Authored raw nodes never become HTML here.
7
8
  export default function rehypeRapierMath(options = {}) {
8
9
  return (tree, file) => {
9
- const render = createFormulaRenderer(options);
10
+ const mathSession = file?.data?.rapierMathSession;
11
+ assertMathSession(mathSession);
12
+ let render;
10
13
  function math(node) {
11
14
  const names = node?.properties?.className;
12
15
  if (node?.type !== 'element' || node.tagName !== 'code' || !Array.isArray(names) ||
@@ -14,13 +17,14 @@ export default function rehypeRapierMath(options = {}) {
14
17
  !Array.isArray(node.children) || !node.children.every(child => child.type === 'text' && typeof child.value === 'string')) return null;
15
18
  return {source: node.children.map(child => child.value).join(''), display: names.includes('math-display')};
16
19
  }
17
- function visit(parent) {
20
+ function visit(parent, hostLink = null) {
21
+ if (parent.type === 'element' && parent.tagName === 'a') hostLink = parent;
18
22
  for (let index = 0; index < (parent.children?.length || 0); index++) {
19
23
  const node = parent.children[index];
20
24
  const code = node.type === 'element' && node.tagName === 'pre' && node.children?.length === 1 ? node.children[0] : node;
21
25
  const input = math(code);
22
- if (!input) { visit(node); continue; }
23
- const result = render(input.source, input.display);
26
+ if (!input) { visit(node, hostLink); continue; }
27
+ const result = render(input.source, input.display, !!hostLink);
24
28
  if (result.errors.length) {
25
29
  for (const error of result.errors) {
26
30
  const message = file?.message(error.message, {place: code.position, source: 'rapier-math', ruleId: error.code});
@@ -28,10 +32,27 @@ export default function rehypeRapierMath(options = {}) {
28
32
  }
29
33
  continue;
30
34
  }
31
- const svg = fromHtml(result.svg, {fragment: true}).children[0];
32
- parent.children[index] = input.display ? {type: 'element', tagName: 'div', properties: {className: ['math-display']}, children: [svg]} : svg;
35
+ // Native MathML descendants do not supply a link name in every host.
36
+ // Match internal formula links' destination fallback without inventing
37
+ // mathematical speech or replacing an authored accessible name.
38
+ if (result.presentation && hostLink) {
39
+ const properties = hostLink.properties ||= {};
40
+ if (!properties.ariaLabel && !properties.ariaLabelledBy && !properties.title &&
41
+ typeof properties.href === 'string' && properties.href)
42
+ properties.title = properties.href;
43
+ }
44
+ // Every occurrence gets fresh nodes, including every part of a composed
45
+ // result. Reusable formula artifacts never own host HAST identity.
46
+ const children = fromHtml(result.markup, {fragment: true}).children;
47
+ const replacement = input.display ? [{type: 'element', tagName: 'div', properties: {className: ['math-display']}, children}] : children;
48
+ parent.children.splice(index, 1, ...replacement);
49
+ index += replacement.length - 1;
33
50
  }
34
51
  }
35
- visit(tree);
52
+ try {
53
+ render = createFormulaRenderer(options, mathSession);
54
+ visit(tree);
55
+ }
56
+ catch (error) { mathSession?.clear(); throw error; }
36
57
  };
37
58
  }
package/dist/reuse.mjs ADDED
@@ -0,0 +1,110 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Message artifacts have a different lifetime from document admission. This
3
+ // module has no renderer, host, timer or DOM imports and retains no callbacks.
4
+ const sessions = new WeakMap();
5
+ const ENTRY_BYTES = 128;
6
+
7
+ export function createMathSession({maxEntries = 128, maxRetainedBytes = 2 * 1024 * 1024,
8
+ maxEntryBytes = 256 * 1024} = {}) {
9
+ for (const value of [maxEntries, maxRetainedBytes, maxEntryBytes])
10
+ if (!Number.isSafeInteger(value) || value < 0)
11
+ throw new RangeError('Math reuse limits must be finite nonnegative integers.');
12
+ const state = {entries: new Map(), maxEntries, maxRetainedBytes,
13
+ maxEntryBytes: Math.min(maxEntryBytes, maxRetainedBytes), keyBytes: 0, artifactBytes: 0,
14
+ peakRetainedBytes: 0, hits: 0, evaluations: 0, bypasses: 0, evictions: 0, epoch: 0, disposed: false};
15
+ const clear = () => {
16
+ state.entries.clear(); state.keyBytes = state.artifactBytes = 0; state.epoch++;
17
+ };
18
+ const session = Object.freeze({
19
+ clear,
20
+ dispose() { clear(); state.disposed = true; },
21
+ get stats() {
22
+ return Object.freeze({entries: state.entries.size, retainedBytes: state.keyBytes + state.artifactBytes,
23
+ keyBytes: state.keyBytes, artifactBytes: state.artifactBytes, peakRetainedBytes: state.peakRetainedBytes,
24
+ hits: state.hits, evaluations: state.evaluations, bypasses: state.bypasses, evictions: state.evictions,
25
+ disposed: state.disposed});
26
+ },
27
+ });
28
+ sessions.set(session, state);
29
+ return session;
30
+ }
31
+
32
+ export function assertMathSession(session) {
33
+ if (session === undefined) return;
34
+ const state = sessions.get(session);
35
+ if (!state || state.disposed) throw new TypeError('Supply a live Math session created by createMathSession.');
36
+ }
37
+
38
+ // Only immutable scalar/string results are retained. A new nested payload needs
39
+ // its own concrete ownership/size contract. Errors and in-progress work never enter.
40
+ function artifactSize(result) {
41
+ if (!result || !Array.isArray(result.errors) || result.errors.length || typeof result.svg !== 'string') return null;
42
+ const fields = Reflect.ownKeys(result);
43
+ if (fields.length > 32) return null;
44
+ let bytes = ENTRY_BYTES;
45
+ for (const key of fields) {
46
+ if (typeof key !== 'string') return null;
47
+ const field = Object.getOwnPropertyDescriptor(result, key);
48
+ if (!field.enumerable || !('value' in field)) return null;
49
+ bytes += 2 * key.length;
50
+ const value = field.value;
51
+ if (key === 'errors') continue;
52
+ if (typeof value === 'string') bytes += 2 * value.length;
53
+ else if (typeof value === 'number' && Number.isFinite(value)) bytes += 8;
54
+ else if (typeof value === 'boolean' || value === null || value === undefined) bytes += 8;
55
+ else return null;
56
+ }
57
+ return bytes;
58
+ }
59
+
60
+ function occurrenceNeutral(result) {
61
+ // Current expanded output has no occurrence IDs. A compact/semantic join must
62
+ // supply neutral preparation + per-insertion materialization before it can be
63
+ // cached. Default changes are guarded too, even without a new option key.
64
+ for (const value of Object.values(result)) if (typeof value === 'string' &&
65
+ /\s(?:id|aria-labelledby|aria-describedby)\s*=|\s(?:xlink:)?href\s*=\s*["']#|url\s*\(\s*["']?#/i.test(value)) return false;
66
+ return true;
67
+ }
68
+
69
+ const copyResult = result => ({...result, errors: result.errors.map(error => ({...error}))});
70
+
71
+ // Internal integration seam. `configuration` encodes a complete captured option
72
+ // tuple, or null for a no-cache shape. `calculate` is invoked once on a miss and
73
+ // is never stored. Source/keys are strings, never JSON-serialized caller objects.
74
+ export function reuseFormula(session, source, configuration, calculate) {
75
+ if (session === undefined) return calculate();
76
+ assertMathSession(session);
77
+ const state = sessions.get(session), epoch = state.epoch;
78
+ const keyBytes = configuration === null || typeof source !== 'string' || source.length > 1_000_000
79
+ ? Infinity : 2 * (configuration.length + 1 + source.length);
80
+ const eligible = state.maxEntries > 0 && keyBytes + ENTRY_BYTES <= state.maxEntryBytes;
81
+ // Do not construct an oversized key just to refuse it.
82
+ const key = eligible ? configuration + '\n' + source : null;
83
+ if (key !== null && state.entries.has(key)) {
84
+ const entry = state.entries.get(key);
85
+ state.entries.delete(key); state.entries.set(key, entry);
86
+ state.hits++;
87
+ return copyResult(entry.result);
88
+ }
89
+ state.evaluations++;
90
+ const result = calculate();
91
+ const bytes = eligible ? artifactSize(result) : null;
92
+ if (state.disposed || state.epoch !== epoch) return result;
93
+ if (bytes === null || keyBytes + bytes > state.maxEntryBytes || !occurrenceNeutral(result)) {
94
+ state.bypasses++;
95
+ return result;
96
+ }
97
+ // Reentrant work may have populated the same key. Do not double-charge it or
98
+ // resurrect an artifact after clear/dispose while calculation was in progress.
99
+ if (state.entries.has(key)) return result;
100
+ while (state.entries.size >= state.maxEntries ||
101
+ state.keyBytes + state.artifactBytes + keyBytes + bytes > state.maxRetainedBytes) {
102
+ const oldest = state.entries.keys().next().value, entry = state.entries.get(oldest);
103
+ state.entries.delete(oldest); state.keyBytes -= entry.keyBytes; state.artifactBytes -= entry.bytes; state.evictions++;
104
+ }
105
+ const saved = Object.freeze({...result, errors: Object.freeze([])});
106
+ state.entries.set(key, {result: saved, keyBytes, bytes});
107
+ state.keyBytes += keyBytes; state.artifactBytes += bytes;
108
+ state.peakRetainedBytes = Math.max(state.peakRetainedBytes, state.keyBytes + state.artifactBytes);
109
+ return copyResult(saved);
110
+ }
package/dist/stream.d.ts CHANGED
@@ -1,14 +1,47 @@
1
1
  // SPDX-License-Identifier: MIT
2
+ export interface MathReuseLimits {
3
+ /** Maximum retained successful artifacts, including each source/configuration key. Default 128. */
4
+ maxEntries?: number;
5
+ /** Accounted UTF-16 string bytes + scalar/entry allowance, not physical heap. Default 2 MiB. */
6
+ maxRetainedBytes?: number;
7
+ /** Maximum accounted bytes for one entry, capped by maxRetainedBytes. Default 256 KiB. */
8
+ maxEntryBytes?: number;
9
+ }
10
+ export interface MathReuseStats {
11
+ readonly entries: number;
12
+ readonly retainedBytes: number;
13
+ readonly keyBytes: number;
14
+ readonly artifactBytes: number;
15
+ readonly peakRetainedBytes: number;
16
+ readonly hits: number;
17
+ readonly evaluations: number;
18
+ readonly bypasses: number;
19
+ readonly evictions: number;
20
+ readonly disposed: boolean;
21
+ }
22
+ export interface MathSession {
23
+ /** Release all artifacts. Lifetime counters remain; this session stays open. */
24
+ clear(): void;
25
+ /** Release artifacts and permanently close this message owner. Idempotent. */
26
+ dispose(): void;
27
+ /** Fresh immutable counters; no source, options, or rendered objects are exposed. */
28
+ readonly stats: MathReuseStats;
29
+ }
30
+ /** One explicit message lifetime for supported adapter renders, independent of document budgets. */
31
+ export function createMathSession(limits?: MathReuseLimits): MathSession;
2
32
  export interface MarkdownSnapshot {source: string; html: string; revision: number; final: boolean}
3
33
  export interface MarkdownStream {
4
34
  /** null means keep the previous preview; the chunk was still accepted. */
5
35
  write(chunk: string): MarkdownSnapshot | null;
36
+ /** Always run a complete batch render. A failure preserves accepted source for retry. */
6
37
  finish(): MarkdownSnapshot;
7
38
  abort(): void;
8
- /** Replace a message by resetting, then writing the replacement source. */
9
- reset(): number;
39
+ /** Close this handle and return a fresh replacement. Old producers remain closed. */
40
+ reset(): MarkdownStream;
10
41
  readonly revision: number;
11
42
  }
12
- export function createMarkdownStream(renderMarkdown: (source: string) => string, options?: {
43
+ export function createMarkdownStream(renderMarkdown: (source: string, session: MathSession) => string, options?: {
13
44
  maxSourceLength?: number; previewEvery?: number;
45
+ /** Bounded per-message formula reuse by default. false disables retention. */
46
+ reuse?: MathReuseLimits | false;
14
47
  }): MarkdownStream;
package/dist/stream.mjs CHANGED
@@ -1,46 +1,71 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Full Markdown previews have no append-only promise. Geometric admission bounds
3
3
  // the total source passed to a synchronous host, including the final batch pass.
4
- export function createMarkdownStream(renderMarkdown, {maxSourceLength = 1_000_000, previewEvery = 256} = {}) {
4
+ import {createMathSession} from './reuse.mjs';
5
+ export {createMathSession} from './reuse.mjs';
6
+
7
+ export function createMarkdownStream(renderMarkdown, {maxSourceLength = 1_000_000, previewEvery = 256, reuse = {}} = {}) {
5
8
  if (typeof renderMarkdown !== 'function') throw new TypeError('Supply a synchronous Markdown renderer.');
6
9
  for (const value of [maxSourceLength, previewEvery])
7
10
  if (!Number.isSafeInteger(value) || value < 1) throw new RangeError('Stream limits must be positive finite integers.');
8
- let chunks = [], length = 0, threshold = previewEvery, closed = false, revision = 0, rendering = false;
9
- function open() {
10
- if (closed || rendering) throw new Error(closed ? 'This stream is closed; reset it before writing.' : 'A stream renderer cannot reenter its stream.');
11
+ if (reuse !== false && (reuse === null || typeof reuse !== 'object'))
12
+ throw new TypeError('Stream reuse must be false or a Math reuse limits object.');
13
+ // Only limits are retained. Caller mutation cannot reconfigure this message or
14
+ // its replacement. The session itself contains no source until a host uses it.
15
+ const limits = Object.freeze(reuse === false ? {maxEntries: 0} : {
16
+ maxEntries: reuse.maxEntries, maxRetainedBytes: reuse.maxRetainedBytes, maxEntryBytes: reuse.maxEntryBytes,
17
+ });
18
+ function start(revision = 0) {
19
+ let chunks = [], length = 0, threshold = previewEvery, closed = false, rendering = false;
20
+ let session = createMathSession(limits);
21
+ function open() {
22
+ if (closed || rendering) throw new Error(closed ? 'This stream is closed; use the new handle returned by reset.' : 'A stream renderer cannot reenter its stream.');
23
+ }
24
+ function release() { session?.dispose(); session = null; }
25
+ function snapshot(final) {
26
+ const source = chunks.join('');
27
+ chunks = source ? [source] : [];
28
+ // Failed previews consumed work too. Further chunks must still wait for the
29
+ // next geometric threshold; only an explicit finish retries immediately.
30
+ threshold = Math.max(previewEvery, length * 2);
31
+ session ||= createMathSession(limits);
32
+ rendering = true;
33
+ let html;
34
+ try {
35
+ html = renderMarkdown(source, session);
36
+ if (typeof html !== 'string') throw new TypeError('The Markdown renderer must return a string synchronously.');
37
+ } catch (error) {
38
+ release(); // Keep exact accepted source; retry gets a fresh artifact owner.
39
+ throw error;
40
+ } finally { rendering = false; }
41
+ if (final) { release(); closed = true; chunks = []; length = 0; }
42
+ return {source, html, revision, final};
43
+ }
44
+ return Object.freeze({
45
+ write(chunk) {
46
+ open();
47
+ if (typeof chunk !== 'string') throw new TypeError('Decode transport bytes to strings before writing.');
48
+ if (chunk.length > maxSourceLength - length)
49
+ throw Object.assign(new RangeError('The message exceeds its source budget; this chunk was not accepted.'), {code: 'resource-limit'});
50
+ if (!chunk.length) return null;
51
+ chunks.push(chunk); length += chunk.length; revision++;
52
+ return length >= threshold ? snapshot(false) : null;
53
+ },
54
+ finish() { open(); revision++; return snapshot(true); },
55
+ abort() {
56
+ if (rendering) throw new Error('A stream renderer cannot abort its stream.');
57
+ if (closed) return;
58
+ release(); chunks = []; length = 0; closed = true; revision++;
59
+ },
60
+ reset() {
61
+ if (rendering) throw new Error('A stream renderer cannot reset its stream.');
62
+ release(); chunks = []; length = 0; closed = true;
63
+ // A producer must capture its own handle. Replaced producers can neither
64
+ // append to nor finish the new message, even if transport cancellation races.
65
+ return start(++revision);
66
+ },
67
+ get revision() { return revision; },
68
+ });
11
69
  }
12
- function snapshot(final) {
13
- const source = chunks.join('');
14
- chunks = source ? [source] : [];
15
- // Failed previews consumed work too. Further chunks must still wait for the
16
- // next geometric threshold; only an explicit finish retries immediately.
17
- threshold = Math.max(previewEvery, length * 2);
18
- rendering = true;
19
- let html;
20
- try {
21
- html = renderMarkdown(source);
22
- if (typeof html !== 'string') throw new TypeError('The Markdown renderer must return a string synchronously.');
23
- } finally { rendering = false; }
24
- if (final) { closed = true; chunks = []; length = 0; }
25
- return {source, html, revision, final};
26
- }
27
- return {
28
- write(chunk) {
29
- open();
30
- if (typeof chunk !== 'string') throw new TypeError('Decode transport bytes to strings before writing.');
31
- if (chunk.length > maxSourceLength - length)
32
- throw Object.assign(new RangeError('The message exceeds its source budget; this chunk was not accepted.'), {code: 'resource-limit'});
33
- if (!chunk.length) return null;
34
- chunks.push(chunk); length += chunk.length; revision++;
35
- return length >= threshold ? snapshot(false) : null;
36
- },
37
- finish() { open(); revision++; return snapshot(true); },
38
- abort() {
39
- if (rendering) throw new Error('A stream renderer cannot abort its stream.');
40
- if (closed) return;
41
- chunks = []; length = 0; closed = true; revision++;
42
- },
43
- reset() { if (rendering) throw new Error('A stream renderer cannot reset its stream.'); chunks = []; length = 0; threshold = previewEvery; closed = false; return ++revision; },
44
- get revision() { return revision; },
45
- };
70
+ return start();
46
71
  }
package/docs/api.md CHANGED
@@ -23,6 +23,42 @@ Keep `source` for editing and copying. A formula API accepts TeX without Markdow
23
23
  the TeX a second time. Native ESM works in Node 22+, current browsers and module workers; no CommonJS wrapper
24
24
  is provided. Server output needs no client renderer unless fitting or further rendering is wanted.
25
25
 
26
+ ## One file or native modules
27
+
28
+ For a one-file browser or inline-script integration, use `dist/rapier-math.js` and
29
+ `globalThis.RapierMath.renderToString(source)`. This classic file contains the complete
30
+ formula renderer and font; it needs no sibling modules or runtime download.
31
+
32
+ The native `dist/index.mjs` entry is a small facade importing the relative `src/math/`
33
+ module graph. It is not a standalone file to copy or inline. Install the whole package,
34
+ serve its `dist/` and `src/` directories together, or bundle the native import in your
35
+ application. A CDN must serve that package graph or bundle the entry. The browser and
36
+ module-worker examples assume the complete package is served from its root.
37
+
38
+ ## Structured and accessible output
39
+
40
+ ```js
41
+ import {toMathML} from 'rapier-math/mathml'; // no embedded font or SVG layout
42
+ import {renderWithMathML} from 'rapier-math/combined'; // one admitted parse
43
+ import {renderAccessible} from 'rapier-math/accessible';
44
+ const semantic = toMathML(String.raw`\frac{a}{b}`);
45
+ const both = renderWithMathML(String.raw`\frac{a}{b}`);
46
+ const accessible = renderAccessible(String.raw`\frac{a}{b}`);
47
+ ```
48
+
49
+ Include `rapier-math/accessible.css` when inserting `accessible.html`. Ordinary formulas retain
50
+ visual SVG with one assistive MathML sibling. Internally linked formulas use visible native
51
+ MathML once and return their standalone SVG separately. Check `semantics.status`: `complete`,
52
+ `presentation-fallback`, or `refused`. On refusal, insert original source through a text sink.
53
+ The [semantic contract](semantics.md) describes mappings, exact-source annotations, link
54
+ tradeoffs, sanitizer/CSP order and the separate manual screen-reader acceptance steps.
55
+
56
+ Both Markdown adapters accept `accessible: true`; their normal grammar is unchanged. Cache
57
+ entries retain only immutable scalar/string output, never a shared semantic tree or HAST.
58
+ Native entries execute the carried source modules directly, sharing one parser and alphabet
59
+ mapping. SVG-only imports do not reach MathML; MathML-only imports do not reach fonts, layout or
60
+ browser observers. The classic offline script includes all formula outputs.
61
+
26
62
  ## Markdown
27
63
 
28
64
  ```sh
@@ -66,7 +102,8 @@ adapter or renderer imports the app's AGPL Markdown implementation.
66
102
  Use `remark-math`, `remark-rehype`, then `rehype-sanitize`, then `rapier-math/rehype`, then `rehype-stringify`.
67
103
  The complete [unified example](../examples/unified.mjs) grants only the math classes on sanitized code nodes.
68
104
  The adapter replaces supported `language-math` + `math-inline`/`math-display` nodes with HAST parsed from
69
- fresh renderer SVG. It does not turn authored raw HTML into trusted markup or loosen the global SVG sanitizer.
105
+ the complete renderer insertion markup. Every occurrence receives fresh HAST nodes, including on reuse.
106
+ It does not turn authored raw HTML into trusted markup or loosen the global SVG sanitizer.
70
107
  The optional `hast-util-from-html` peer is used only by this entrypoint.
71
108
 
72
109
  Choose `remarkMath({singleDollarTextMath: false})` to avoid single-dollar ambiguity. Remark owns delimiter,
@@ -74,39 +111,131 @@ whitespace and code rules in this pipeline; its grammar is different from the ma
74
111
  not enable backslash delimiters. Unsupported formulas remain copyable code and produce VFile messages
75
112
  with `ruleId`, `mathOffset` and `mathSource`.
76
113
 
77
- Both rendering adapters accept `renderOptions`, `maxFormulas` (default 1024) and `maxOutputLength` (default
78
- 16 Mi UTF-16 code units of successful SVG per document render). Rendering a cached markdown-it token tree
79
- again starts a fresh budget; inline children share their enclosing document's budget. Exhaustion leaves subsequent source literal with
80
- diagnostics. The host owns its own source, tree, prose and final HTML budgets. These are synchronous adapters.
114
+ Both rendering adapters accept `accessible` (default false), `renderOptions`, `maxFormulas` (default 1024) and `maxOutputLength` (default
115
+ 16 Mi UTF-16 code units of successful formula insertion markup per document render, excluding the host's
116
+ display wrapper). Each occurrence spends both count and output admission, including cache hits. Rendering
117
+ an already parsed markdown-it tree again starts a fresh budget. Ordinary inline descendants share their
118
+ active parent's budget; independent reentrant renders receive their own. Reusing an `env` object does
119
+ not extend a budget. Exhaustion leaves source literal with diagnostics. The host owns its source, tree,
120
+ prose and final HTML budgets. These are synchronous adapters.
81
121
 
82
- ## Streaming
122
+ ## Streaming and message reuse
83
123
 
84
124
  ```js
125
+ import MarkdownIt from 'markdown-it';
126
+ import rapierMath from 'rapier-math/markdown-it';
85
127
  import {createMarkdownStream} from 'rapier-math/stream';
86
- const stream = createMarkdownStream(source => md.render(source, {}));
87
- const preview = stream.write('The answer is \\(x'); // may return null
88
- stream.write('^2\\).');
89
- const completed = stream.finish(); // {source, html, revision, final: true}
128
+
129
+ const md = new MarkdownIt({html: false}).use(rapierMath);
130
+ const renderMarkdown = (source, session) => md.render(source, {rapierMathSession: session});
131
+ let stream = createMarkdownStream(renderMarkdown, {previewEvery: 256});
132
+ let shown; // The host replaces its whole preview with each returned snapshot.
133
+ try {
134
+ for (const chunk of ['The answer is \\(', 'x^2', '\\).']) {
135
+ const preview = stream.write(chunk);
136
+ if (preview) shown = preview;
137
+ }
138
+ shown = stream.finish(); // {source, html, revision, final: true}; releases reuse.
139
+ } finally {
140
+ stream.abort(); // Also releases retained source/artifacts after an exception.
141
+ }
90
142
  ```
91
143
 
92
- Use one stream per message. `write` accepts decoded strings and returns either a whole preview or `null`;
93
- `finish` always runs the same batch renderer on the complete exact source. `abort` releases pending text.
94
- `reset` starts a replacement and advances the revision. Cancel the old producer before reset, or reject its
95
- chunks using your conversation generation. No callbacks, timers, DOM mutations or shared conversation state
96
- are installed. See the [stream example](../examples/stream.mjs).
144
+ Use one stream handle per message and associate the supplied session deliberately. `write` accepts
145
+ decoded strings and returns a whole preview or `null`; `finish` always runs the batch renderer on the
146
+ complete exact source. The host replaces its previous preview and retains `source` for editing/copying.
147
+ Show incoming chunks with text rendering for immediate progress; never concatenate them into HTML.
148
+ The stream owns no DOM, timers, transport callbacks or global conversation cache. Importing the stream
149
+ entry alone does not load the formula renderer. See the complete [stream example](../examples/stream.mjs).
150
+
151
+ `stream = stream.reset()` closes the old handle, releases its source and artifacts, and returns a fresh
152
+ replacement with an advanced revision. Each producer must capture its own handle. Old producers' `write`
153
+ and `finish` then refuse even if cancellation races; do not let an old producer read a mutable variable
154
+ holding the replacement. Cancel transport as well. `abort` closes a handle and releases its pending work;
155
+ it is idempotent. A completed handle cannot accept more chunks. Stream handles cannot reenter themselves.
156
+
157
+ A renderer throw or a non-string result disposes the current reuse session immediately while preserving
158
+ all accepted chunks. Retry `finish()` explicitly to render them with a fresh session, or reset/abort. A
159
+ source-budget rejection never accepts or silently truncates the rejected chunk; the caller still owns it.
160
+ A rejected chunk does not discard earlier admitted source or its valid artifacts.
97
161
 
98
162
  Markdown references, setext headings and fences can change earlier interpretation, so previews are
99
- replaceable, not committed prefixes. An open formula remains literal. Defaults: at most 1,000,000 retained
100
- source code units; first preview at 256 units, then only after the source has at least doubled. Including
101
- one `finish`, the total source sent to the host is less than three times final length, even if previews fail.
102
- Explicit retries of `finish` are additional host calls. There is no full-prefix
103
- render on every token. Late previews are consequently less frequent; show incoming chunks as text for
104
- immediate progress. `previewEvery` sets the first threshold, not a fixed per-chunk interval.
105
-
106
- Retained state is O(message length), not a claimed constant-memory Markdown parser. Stream chunks can split
107
- delimiters, CRLF, escapes or surrogate pairs. Final interpretation is batch-equivalent; interim previews
108
- may show an incomplete code unit. A rejected oversized chunk is not accepted or silently truncated; the
109
- caller still owns it. A failed renderer leaves accumulated source available for retry or reset.
163
+ replaceable. An open formula remains literal under its host's grammar. Defaults: at most 1,000,000 retained
164
+ source code units; first preview at 256 units, then only after source length has at least doubled. Including
165
+ one `finish`, the source passed to the host is less than three times the final nonempty length, even when
166
+ previews fail. Explicit finish retries add host calls. `previewEvery` sets the first threshold, not a fixed
167
+ per-chunk interval. Parsing, prose rendering and HTML/HAST production still run for every whole preview.
168
+ This does not promise constant-time streaming, append-only DOM or arbitrary incremental Markdown parsing.
169
+
170
+ ### Deliberate reuse outside the stream
171
+
172
+ ```js
173
+ import {createMathSession} from 'rapier-math/stream';
174
+ const session = createMathSession();
175
+ try {
176
+ md.render(firstWholeSource, {rapierMathSession: session});
177
+ md.render(nextWholeSource, {rapierMathSession: session});
178
+ console.log(session.stats); // Counters only; no source or mutable artifacts.
179
+ } finally {
180
+ session.dispose();
181
+ }
182
+ ```
183
+
184
+ For rehype, put the same session in each VFile's `data.rapierMathSession`. For example,
185
+ `processor.processSync({value: source, data: {rapierMathSession: session}})` uses the sanitized pipeline
186
+ in the [unified example](../examples/unified.mjs). Each transformed tree starts fresh admission. Do not put
187
+ the session into long-lived processor options or reuse it across messages. Omitting the explicit session
188
+ keeps ordinary adapter rendering free of persistent formula retention. A session is not a document budget,
189
+ parser, source archive or permission to change any document.
190
+
191
+ `session.clear()` releases artifacts while leaving that message owner open; counters remain cumulative.
192
+ `session.dispose()` permanently closes it and is idempotent. Use a new session for a replacement message.
193
+ A disposed or unrecognized session refuses. Adapter throws clear artifacts and restore the enclosing
194
+ render frame; the stream additionally disposes its failed lifetime. Interleaved messages keep separate
195
+ sessions. Each successful occurrence receives a fresh result object and, for rehype, fresh HAST nodes.
196
+
197
+ ### Configuration, retention and costs
198
+
199
+ With an explicit reuse session, a document captures supported plain-data `renderOptions` and a copy of
200
+ `screen` when its root render starts. Without a session, options retain ordinary per-occurrence reads. Its exact source, output mode, display mode, width and every screen field form the reuse key. Later root
201
+ renders see option changes; an active outer render keeps its captured options during nested renders.
202
+ Data-shaped proxies use their actual acquired values for both the key and renderer, including invalid
203
+ values or failed acquisition; a failure is not silently retried to obtain a different option. Snapshot
204
+ inspection may invoke prototype or descriptor traps before property reads, so side-effectful Proxy traps
205
+ need not observe ordinary spread order. Use stable data options for predictable message reuse. Structurally unsupported accessors retain
206
+ the ordinary per-occurrence path. Keys use a fixed tuple of numbers/booleans followed by exact source, with no arbitrary-object JSON
207
+ serialization. Accessors, exotic prototypes, coercible nonnumeric widths, unknown keys and unsupported
208
+ option shapes take the ordinary uncached renderer path. Their accessors are not read just to form a key.
209
+ New output/semantic/representation options must join this configuration contract before reuse is enabled.
210
+
211
+ Default limits are 128 entries, `maxRetainedBytes: 2097152` and `maxEntryBytes: 262144`; the entry limit is
212
+ capped by the total. All limits are finite nonnegative integers. Pass them to `createMathSession(limits)`
213
+ or `createMarkdownStream(renderMarkdown, {reuse: limits})`. `reuse: false` disables stream retention while
214
+ keeping the same host and admission path. Least recently used successes are evicted. An entry too large
215
+ is rendered once for the current occurrence and not retained: there is no trial rendering followed by a
216
+ second rendering. It must be evaluated again if another preview needs it. Failed or in-progress formula
217
+ results are never retained, nor are document-dependent resource rejections.
218
+
219
+ The accounting includes two bytes per source/configuration key code unit, every retained output string
220
+ and field name, eight bytes per scalar field, and a 128-byte entry allowance. There are no retained error
221
+ payloads. `stats` reports entries, key/artifact/total bytes, peak accounted bytes, hits, evaluations,
222
+ bypasses, evictions and disposal. These are logical payload/work counters, not physical heap or device
223
+ memory limits. JavaScript engines may use sliced strings, ropes and different object overheads. Stream
224
+ source retention is separate and grows with admitted message length; caller-held snapshots remain the
225
+ caller's responsibility. Sessions never retain calculated HAST trees or renderer callbacks.
226
+
227
+ The current expanded SVG is safe to reuse because it contains no occurrence identity. Serialized results
228
+ with IDs, local references or accessibility ID references bypass retention, including if a renderer's
229
+ default changes. Compact SVG/semantic composition must cache an occurrence-neutral prepared artifact and
230
+ materialize the caller's namespace for every insertion; already namespaced output must never enter this
231
+ cache. Output admission runs after the complete insertion payload is materialized. Unknown nested result
232
+ payloads also bypass until they have an explicit ownership and accounting contract.
233
+
234
+ Retained state is bounded by configured logical budgets plus the admitted source, not constant memory.
235
+ Repeated formulas can avoid parse/layout/serialization; mostly unique, oversized and failing formulas
236
+ pay cache bookkeeping without that benefit. Whole-host parsing may dominate prose-heavy documents.
237
+ Transport chunks may split delimiters, CRLF, escapes or surrogate pairs. Final source remains the exact
238
+ concatenation without normalization; an interim preview may contain an incomplete code unit.
110
239
 
111
240
  ## Formula API and browser lifetime
112
241
 
@@ -2,10 +2,10 @@
2
2
  "spdxVersion": "SPDX-2.3",
3
3
  "dataLicense": "CC0-1.0",
4
4
  "SPDXID": "SPDXRef-DOCUMENT",
5
- "name": "rapier-math-1.1.1",
6
- "documentNamespace": "https://rapier.website/spdx/rapier-math-1.1.1-050f4ebfb7c78beaefb01c9d6aa62192fd03757fc677134850bdb1f090033b81",
5
+ "name": "rapier-math-2.1.0",
6
+ "documentNamespace": "https://rapier.website/spdx/rapier-math-2.1.0-e1667405881f03e4757563ad9ea34202ba6d3413944b5cc648dc4280b66d567a",
7
7
  "creationInfo": {
8
- "created": "2026-10-12T17:29:00Z",
8
+ "created": "2026-10-13T12:38:30.961Z",
9
9
  "creators": [
10
10
  "Tool: rapier-math-components",
11
11
  "Organization: rapier.website"
@@ -15,16 +15,17 @@
15
15
  {
16
16
  "name": "rapier-math",
17
17
  "SPDXID": "SPDXRef-rapier-math",
18
- "versionInfo": "1.1.1",
18
+ "versionInfo": "2.1.0",
19
19
  "downloadLocation": "NOASSERTION",
20
20
  "filesAnalyzed": false,
21
21
  "licenseConcluded": "MIT AND LicenseRef-GUST-Font-License",
22
22
  "licenseDeclared": "MIT AND LicenseRef-GUST-Font-License",
23
23
  "copyrightText": "NOASSERTION",
24
+ "sourceInfo": "Verified current build inputs: math-resources.json (SHA-256 1ccf57bc76f95815cb2b9d40b44505e91cd14abe268d9f93d0ea28fb59308eca).",
24
25
  "checksums": [
25
26
  {
26
27
  "algorithm": "SHA256",
27
- "checksumValue": "050f4ebfb7c78beaefb01c9d6aa62192fd03757fc677134850bdb1f090033b81"
28
+ "checksumValue": "e1667405881f03e4757563ad9ea34202ba6d3413944b5cc648dc4280b66d567a"
28
29
  }
29
30
  ]
30
31
  },