Explainer videos and product demos made by your AI agent. Free and open source: a local voice (Kokoro), word timing (Whisper) and a canvas renderer turn a script into a narrated MP4.
JavaScript ai-agentsanimationcanvasclaude-codecodexexplainer-videoffmpegjavascriptkokoroproduct-demotext-to-speechvideo-generationwhisper
Typeset math formulas with s.math (#11)
Vincent Schmalbachf2902b2b2339
diff --git a/AGENTS.md b/AGENTS.mdindex 05b75a1..ff571a8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -791,6 +791,26 @@ with `write`, `type` (with `cps`), `words` and `sync`. `sync` shows each wordas the voice says it. Words in `*stars*` get the accent color. `\n` starts anew line.+### Math++```js+s.math('E = mc^2', { y: 420, size: 96, at: 'energy' });+s.math(String.raw`\int_0^1 x^2\,dx = \tfrac{1}{3}`, { x: 960, y: 700, size: 72, color: 'accent', at: '#integral', id: 'area' });+```++`s.math(tex, options)` draws a TeX formula. Options: `x`, `y` (the center),+`size` (72), `color` (ink), `align` (`center` or `left`, where x is the left+edge), `display` (true for display style), and the common element options.+It returns a box like text. Its `id` works with arrows and `s.annotate`.+In `paper`, `chalk` and `blueprint`, the outlines draw first, then fill in.+Other looks use their text entrance. You can also use `fade`, `pop` or `rise`.++Double each backslash in a regular JS string, for example `'\\frac{1}{2}'`.+`String.raw` keeps backslashes as written, as in the second example above.+Only fixed TeX strings work. Always call `s.math`, and use `at` and `out` for+timing. `check` reports formulas that change with `s.t` or appear only later.+Formulas are typeset on this computer and cached in `build/math/`.+### Shapes and arrows```js@@ -977,6 +997,8 @@ font roles are `display`, `body`, `hand` and `mono`.- Calling an element only sometimes, like `if (s.t > 3) s.box(...)`. Alwayscall it, and use `at` and `out` for the timing. The sound effects and thechecks depend on this.+- Changing the TeX in `s.math` over time. Use fixed strings for each formula,+ and give each one its own `at` and `out`.- An arrow or annotation that points to an `id` drawn later in the function.- `s.camera()` after other elements. It has to come first.- An `at` later than the end of the scene. Make the scene longer with@@ -1016,11 +1038,11 @@ font roles are `display`, `body`, `hand` and `mono`.them to the project's fps, so a frame can repeat or drop. Record at a fixedframe rate when the motion matters.-`check` looks at text only. It finds text off the frame, too close to the-edge (3.5%), too small, with low contrast (against the page, or against the-text's own `bg`), on top of other text, or under the captions. It does not-see shapes, arrows and icons, or drawings made with `s.draw`. Look at the-stills for those.+`check` looks at text and math formulas. It finds text off the frame, too+close to the edge (3.5%), too small, with low contrast (against the page, or+against the text's own `bg`), on top of other text, or under the captions.+It does not see shapes, arrows and icons, or drawings made with `s.draw`.+Look at the stills for those.## Working on explainroo itselfdiff --git a/engine/runtime.js b/engine/runtime.jsindex f2f2f10..5059310 100644--- a/engine/runtime.js+++ b/engine/runtime.js@@ -79,6 +79,9 @@ export class Engine {this.pen = new Pen({ rough, theme: this.theme });this.icons = icons;this.iconCache = new Map();+ this.mathCache = new Map();+ this.lateMath = new Map();+ this.collectingMath = false;this.images = images;this.clips = clips;this.clipFrames = new ClipFrames();@@ -155,6 +158,51 @@ export class Engine {this.clipFrames.trim(new Set(needed.keys()));}+ mathData(tex, display, scene, t) {+ const key = JSON.stringify([tex, display]);+ if (this.collectingMath) {+ if (!this.mathCache.has(key)) this.mathCache.set(key, null);+ return null;+ }+ if (!this.mathCache.has(key)) {+ this.lateMath.set(key, { scene, t, tex });+ // Late formulas still draw synchronously, including the frame that finds them.+ const req = new XMLHttpRequest();+ req.open('GET', this.mathURL(tex, display), false);+ req.send();+ this.mathCache.set(key, this.mathResponse(req.status, req.responseText));+ }+ return this.mathCache.get(key);+ }++ mathURL(tex, display) {+ return `/__math?tex=${encodeURIComponent(tex)}&display=${display ? '1' : '0'}`;+ }++ mathResponse(status, body) {+ if (status !== 200) {+ try { return { error: JSON.parse(body).error || body }; } catch { return { error: body }; }+ }+ return JSON.parse(body);+ }++ async loadMath() {+ this.collectingMath = true;+ try {+ for (const sc of this.timeline.scenes) {+ // Scene errors belong to check or render, as they do without formulas.+ try { this.drawScene(this.ctx, sc.index, 0); } catch {}+ }+ } finally {+ this.collectingMath = false;+ }+ await Promise.all([...this.mathCache.keys()].map(async key => {+ const [tex, display] = JSON.parse(key);+ const res = await fetch(this.mathURL(tex, display));+ this.mathCache.set(key, this.mathResponse(res.status, await res.text()));+ }));+ }+sceneAt(T) {const list = this.timeline.scenes;let i = list.length - 1;@@ -439,6 +487,7 @@ export class Engine {add('hint', c.scene, null, `cue "${c.word}" means the first of the ${c.count} times it is spoken in this scene; if you meant a later one, use s.cue("${c.word}", 2) or a [#marker]`);}this.cueNotes = null;+ for (const { scene, t, tex } of this.lateMath.values()) add('error', scene, t, `math "${tex}" was not collected at the start; keep TeX strings fixed and always call s.math with at and out for timing`);return issues;}}@@ -464,6 +513,7 @@ export async function boot({ canvas, scale = 1, version = '' }) {if (!scenes || typeof scenes !== 'object') throw new Error('scenes.js must "export default { sceneId(s) { ... } }"');const engine = new Engine({ canvas, state, scenes, icons, images, clips, scale, sfxNames: Object.keys(audio.SFX) });engine.iconTags = iconTags;+ await engine.loadMath();return { engine, audio, state };}diff --git a/engine/stage.js b/engine/stage.jsindex c410a7e..f421cd9 100644--- a/engine/stage.js+++ b/engine/stage.js@@ -608,6 +608,39 @@ export class Stage {});}+ math(tex, o = {}) {+ if (typeof tex !== 'string') throw new SceneError('math: use a fixed TeX string');+ if (o.display !== undefined && typeof o.display !== 'boolean') throw new SceneError('math: display must be true or false');+ if (o.align !== undefined && !['center', 'left'].includes(o.align)) throw new SceneError('math: align must be center or left');+ const data = this.engine.mathData(tex, o.display ?? true, this.id, this.t);+ if (data?.error) throw new SceneError(`math "${tex}": ${data.error}`);+ const size = o.size ?? 72;+ const unit = size / (data?.unitsPerEm ?? 1000);+ const [vx, vy, vw, vh] = data?.viewBox ?? [0, -1000, 0, 1000];+ const w = vw * unit;+ const h = vh * unit;+ const x = (o.x ?? this.cx) + (o.align === 'left' ? w / 2 : 0);+ const y = o.y ?? this.cy;+ this._register(o.id, x, y, w, h);+ const g = geom(x, y, w, h);+ const th = this.theme;+ const life = this._life(o, 'text', { enter: th.enter.shape === 'draw' ? 'draw' : th.enter.text, label: tex });+ if (!life || !data) return g;+ const ctx = this.ctx;+ const color = colorOf(th, o.color, 'ink');+ this._push(x, y, life, o);+ const draw = life.enter === 'draw' || life.enter === 'write';+ const stroke = draw ? ease.inOut(clamp(life.p / 0.78)) : 1;+ const fill = draw ? clamp((life.p - 0.78) / 0.22) : 1;+ for (const d of data.paths) {+ const path = scalePath(d, unit, -w / 2 - vx * unit, -h / 2 - vy * unit);+ this.pen.draw(ctx, { kind: 'path', d: path }, { stroke: draw && life.p < 1 ? color : 'none', width: Math.max(0.7, size / 72), fill: color, rough: false }, { stroke, fill });+ }+ this._logText({ text: tex, x0: -w / 2, y0: -h / 2, x1: w / 2, y1: h / 2, size, fg: color, bg: null });+ ctx.restore();+ return g;+ }+// ---------- shapes ----------box(label, o = {}) {diff --git a/package-lock.json b/package-lock.jsonindex cc8d395..653b202 100644--- a/package-lock.json+++ b/package-lock.json@@ -11,6 +11,7 @@"dependencies": {"@huggingface/transformers": "3.8.1","kokoro-js": "1.2.1",+ "mathjax": "4.1.3","playwright-core": "1.63.0","roughjs": "4.6.6"},@@ -567,6 +568,12 @@"node": ">=18.0.0"}},+ "node_modules/@mathjax/mathjax-newcm-font": {+ "version": "4.1.3",+ "resolved": "https://registry.npmjs.org/@mathjax/mathjax-newcm-font/-/mathjax-newcm-font-4.1.3.tgz",+ "integrity": "sha512-gzAB3dFHilHX1l5x2xUqRL+1jDQt3Fyza1DkEMVXWC4E8SvsGdlgEza47HYi2WhVcgfkvf4zgUGzuhbq3Pjlew==",+ "license": "Apache-2.0"+ },"node_modules/@protobufjs/aspromise": {"version": "1.1.2","resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",@@ -850,6 +857,15 @@"node": ">=10"}},+ "node_modules/mathjax": {+ "version": "4.1.3",+ "resolved": "https://registry.npmjs.org/mathjax/-/mathjax-4.1.3.tgz",+ "integrity": "sha512-BN/8Pkgn7G1pIDYJqd9md+JHsE/jydSYbyOZnSdSA0WziuVO8mRxdYiWFumkVVly/8U+hm9DpIIoWuvySverzw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@mathjax/mathjax-newcm-font": "^4.1.3"+ }+ },"node_modules/minipass": {"version": "7.1.3","resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",diff --git a/package.json b/package.jsonindex 8a367ee..1273ab6 100644--- a/package.json+++ b/package.json@@ -50,6 +50,7 @@"dependencies": {"@huggingface/transformers": "3.8.1","kokoro-js": "1.2.1",+ "mathjax": "4.1.3","playwright-core": "1.63.0","roughjs": "4.6.6"},diff --git a/src/math.js b/src/math.jsnew file mode 100644index 0000000..f08fe16--- /dev/null+++ b/src/math.js@@ -0,0 +1,74 @@+// Typesets locally in Node. The page gets paths, not fonts or SVG references.+import fs from 'node:fs';+import crypto from 'node:crypto';+import { absolutize, parsePath, serialize } from '../engine/pathdata.js';++export const MAX_TEX_LENGTH = 4096;+let ready;++export function mathHash(tex, display = true) {+ return crypto.createHash('sha256').update(JSON.stringify(['mathjax-4.1.3-1', tex, display])).digest('hex');+}++export async function typesetMath(tex, display = true, cacheFile = null) {+ if (typeof tex !== 'string' || tex.length > MAX_TEX_LENGTH) throw new Error(`math: use a TeX string of at most ${MAX_TEX_LENGTH} characters`);+ if (typeof display !== 'boolean') throw new Error('math: display must be true or false');+ if (cacheFile && fs.existsSync(cacheFile)) return JSON.parse(fs.readFileSync(cacheFile, 'utf8'));+ ready ??= import('mathjax').then(({ default: mj }) => mj.init({+ loader: { load: ['input/tex', 'output/svg'] },+ tex: {+ packages: { '[-]': ['autoload', 'require', 'noundefined'] },+ formatError: (_jax, error) => { throw new Error(error.message); },+ },+ svg: { fontCache: 'none' },+ }));+ const mj = await ready;+ // Each formula has its own macros and equation counters, whatever the order.+ const doc = mj.startup.mathjax.document('', { InputJax: mj.startup.getInputJax(), OutputJax: mj.startup.getOutputJax() });+ const node = await doc.convertPromise(tex, { display });+ const a = mj.startup.adaptor;+ const svg = a.firstChild(node);+ const viewBox = a.getAttribute(svg, 'viewBox').split(/\s+/).map(Number);+ const paths = [];+ const walk = (node, matrix) => {+ matrix = svgTransform(matrix, a.getAttribute(node, 'transform') || '');+ const kind = a.kind(node);+ let d = kind === 'path' ? a.getAttribute(node, 'd') : null;+ if (kind === 'rect') {+ const x = Number(a.getAttribute(node, 'x') || 0);+ const y = Number(a.getAttribute(node, 'y') || 0);+ const w = Number(a.getAttribute(node, 'width'));+ const h = Number(a.getAttribute(node, 'height'));+ d = `M${x} ${y}h${w}v${h}h${-w}Z`;+ }+ if (kind === 'text' || kind === 'use') throw new Error('math: this character has no glyph path; use TeX symbols');+ if (d) paths.push(serialize(absolutize(parsePath(d)).map(({ c, v }) => {+ if (c === 'A') throw new Error('math: this glyph has an unsupported arc');+ const points = [];+ for (let i = 0; i < v.length; i += 2) points.push(matrix[0] * v[i] + matrix[2] * v[i + 1] + matrix[4], matrix[1] * v[i] + matrix[3] * v[i + 1] + matrix[5]);+ return { c, v: points };+ })));+ for (const child of a.childNodes(node)) if (!a.kind(child).startsWith('#')) walk(child, matrix);+ };+ walk(svg, [1, 0, 0, 1, 0, 0]);+ const result = { paths, viewBox, unitsPerEm: 1000, ascent: -viewBox[1], descent: viewBox[1] + viewBox[3] };+ if (cacheFile) fs.writeFileSync(cacheFile, JSON.stringify(result));+ return result;+}++function multiply(a, b) {+ return [a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1], a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3], a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]];+}++function svgTransform(matrix, source) {+ for (const [, name, args] of source.matchAll(/(\w+)\(([^)]*)\)/g)) {+ const n = args.trim().split(/[\s,]+/).map(Number);+ let m;+ if (name === 'translate') m = [1, 0, 0, 1, n[0], n[1] ?? 0];+ else if (name === 'scale') m = [n[0], 0, 0, n[1] ?? n[0], 0, 0];+ else if (name === 'matrix') m = n;+ else throw new Error(`math: unsupported SVG transform "${name}"`);+ matrix = multiply(matrix, m);+ }+ return matrix;+}diff --git a/src/server.js b/src/server.jsindex 12705a4..dd7ab1f 100644--- a/src/server.js+++ b/src/server.js@@ -6,6 +6,7 @@ import path from 'node:path';import crypto from 'node:crypto';import { fileURLToPath } from 'node:url';import { extractClip, VIDEO_FILE } from './clips.js';+import { typesetMath, mathHash, MAX_TEX_LENGTH } from './math.js';export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));@@ -163,6 +164,22 @@ export function startServer({ projectDir, getState, port = 0 }) {if (origin && !hosts.some((h) => origin === `http://${h}`)) return send(res, 403, 'forbidden origin');const url = new URL(req.url, 'http://x');const p = decodeURIComponent(url.pathname);+ if (p === '/__math') {+ if (req.method !== 'GET') return send(res, 405, 'math only accepts GET');+ const tex = url.searchParams.get('tex');+ const style = url.searchParams.get('display') ?? '1';+ if (tex === null || tex.length > MAX_TEX_LENGTH) return send(res, 400, `use a TeX string of at most ${MAX_TEX_LENGTH} characters`);+ if (!['0', '1'].includes(style)) return send(res, 400, 'display must be 0 or 1');+ const display = style === '1';+ const file = uploadFile(projectDir, `build/math/${mathHash(tex, display)}.json`);+ if (!file) return send(res, 400, 'math cache must stay in build/math/');+ try {+ const result = await typesetMath(tex, display, file);+ return send(res, 200, JSON.stringify(result), TYPES['.json']);+ } catch (e) {+ return send(res, 400, JSON.stringify({ error: e.message }), TYPES['.json']);+ }+ }if (req.method === 'PUT' && p === '/__upload') {const rel = url.searchParams.get('path') || '';const dest = uploadFile(projectDir, rel);diff --git a/test/math-browser.test.js b/test/math-browser.test.jsnew file mode 100644index 0000000..3d24e08--- /dev/null+++ b/test/math-browser.test.js@@ -0,0 +1,114 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { findChrome } from '../src/browser.js';+import { loadProject } from '../src/project.js';+import { withEngine } from '../src/pipeline.js';+import { buildTimeline } from '../src/timeline.js';++let chrome;+try { chrome = findChrome(); } catch {}++function fixture(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-math-browser-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ theme: 'chalk', captions: false, sfx: false }));+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo {min=3}\n');+ fs.writeFileSync(path.join(dir, 'scenes.js'), `export default { demo(s) {+ s.math(String.raw\`\\frac{1}{2}\`, { x: 450, y: 540, size: 96, at: 0.5, id: 'fraction' });+ s.math(String.raw\`\\sum_{i=1}^n i\`, { x: 950, y: 540, at: 0.5 });+ s.math(String.raw\`\\begin{pmatrix}1 & 2 \\\\ 3 & 4\\end{pmatrix}\`, { x: 1450, y: 540, at: 0.5 });+ s.annotate('fraction', { at: 2, type: 'underline' });+ }};`);+ const project = loadProject(dir);+ return { project, timeline: buildTimeline(project, {}) };+}++test('fixed formulas preload once and render deterministically before, during and after entering', { skip: !chrome }, async t => {+ const { project, timeline } = fixture(t);+ await withEngine(project, timeline, {}, async page => {+ const result = await page.evaluate(async () => {+ const before = performance.getEntriesByType('resource').filter(r => r.name.includes('/__math?')).length;+ const a = await window.explainroo.frames([0, 28, 55]);+ const b = await window.explainroo.frames([55, 28, 0]);+ const issues = window.explainroo.check();+ const after = performance.getEntriesByType('resource').filter(r => r.name.includes('/__math?')).length;+ return { before, after, deterministic: a.every((f, i) => f === b[2 - i]), changing: new Set(a).size, issues };+ });+ assert.equal(result.before, 3);+ assert.equal(result.after, 3);+ assert.equal(result.deterministic, true);+ assert.equal(result.changing, 3);+ assert.deepEqual(result.issues, []);+ });+});++test('math boxes, transformations, text checks and late-formula errors work in the page', { skip: !chrome }, async t => {+ const { project, timeline } = fixture(t);+ await withEngine(project, timeline, {}, async page => {+ const result = await page.evaluate(async () => {+ const { Engine, fetchState } = await import('/engine/runtime.js');+ const { SceneError } = await import('/engine/stage.js');+ const state = await fetchState();+ const make = async (draw, config = {}) => {+ const engine = new Engine({ canvas: document.createElement('canvas'), state: { ...state, config: { ...state.config, ...config } }, scenes: { demo: draw }, icons: {}, images: new Map() });+ await engine.loadMath();+ return engine;+ };+ const boxes = [];+ const ids = [];+ const geometry = await make(s => {+ boxes.push(s.math('E=mc^2', { x: 400, y: 300, align: 'left', id: 'energy', at: 1 }));+ ids.push(s.get('energy'));+ s.arrow('energy', [1500, 300], { at: 1 });+ s.annotate('energy', { at: 2 });+ });+ geometry.drawScene(geometry.ctx, 0, 0.5);+ const box = boxes.at(-1);+ const id = ids.at(-1);+ const checks = await make(s => {+ s.math('x', { x: -10, y: 200, enter: 'none' });+ s.math('y', { x: 500, y: 400, size: 10, enter: 'none' });+ s.math('z', { x: 20, y: 600, align: 'left', enter: 'none' });+ s.math('a+b', { x: 900, y: 930, enter: 'none' });+ s.math('E=mc^2', { y: 800, enter: 'none' });+ s.text('Energy', { y: 800, enter: 'none' });+ }, { captions: true });+ const transformed = await make(s => s.math('x', { x: 900, y: 500, size: 72, scale: 2, rotate: 90, enter: 'none' }));+ transformed.textLog = [];+ transformed.drawScene(transformed.ctx, 0, 2);+ const log = transformed.textLog[0];+ const late = await make(s => s.math('x=' + Math.floor(s.t), { enter: 'none' }));+ const lateIssues = late.check();+ late.renderFrame(2);+ const invalid = await make(s => s.math(String.raw`\frac{1}`, { at: 1 }));+ let error;+ try { invalid.renderFrame(2); } catch (e) { error = { isSceneError: e instanceof SceneError, message: e.message }; }+ const entrances = [];+ for (const theme of ['paper', 'chalk', 'blueprint', 'clean', 'midnight']) {+ const engine = await make(s => s.math('x', { at: 1 }), { theme, sfx: true });+ const events = engine.collectEvents().events;+ const frames = [0, 1.25, 2.5].map(time => { engine.renderFrame(time); return engine.canvas.toDataURL(); });+ entrances.push({ theme, dur: events[0].dur, changing: new Set(frames).size });+ }+ return { box, id, issues: checks.check(), log, lateIssues, latePaths: [...late.mathCache.values()].every(d => d.paths.length > 0), error, entrances };+ });+ assert.equal(result.box.left, 400);+ assert.equal(result.box.y, 300);+ assert.ok(result.box.w > 0 && result.box.h > 0);+ for (const key of ['x', 'y', 'w', 'h', 'left', 'right', 'top', 'bottom']) assert.ok(Math.abs(result.id[key] - result.box[key]) < 1e-8, key);+ for (const pattern of [/runs off the frame/, /hard to read/, /closer.*edge/, /caption band/, /overlaps/]) assert.ok(result.issues.some(i => pattern.test(i.message)), String(pattern));+ assert.equal(result.log.size, 144);+ assert.ok(result.log.y1 - result.log.y0 > result.log.x1 - result.log.x0);+ assert.ok(result.lateIssues.some(i => i.level === 'error' && /keep TeX strings fixed/.test(i.message)));+ assert.equal(result.latePaths, true);+ assert.equal(result.error.isSceneError, true);+ assert.match(result.error.message, /\\frac\{1\}.*Missing argument/);+ for (const r of result.entrances) {+ assert.equal(r.changing, 3, r.theme);+ assert.equal(r.dur, ['clean', 'midnight'].includes(r.theme) ? 0.55 : 0.9, r.theme);+ }+ });+});diff --git a/test/math.test.js b/test/math.test.jsnew file mode 100644index 0000000..fc04636--- /dev/null+++ b/test/math.test.js@@ -0,0 +1,54 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { typesetMath, mathHash, MAX_TEX_LENGTH } from '../src/math.js';++test('math returns standalone paths, a viewBox and baseline metrics', async () => {+ for (const tex of [String.raw`\frac{1}{2}`, String.raw`\int_0^1 x^2\,dx = \tfrac{1}{3}`, String.raw`\begin{pmatrix}1 & 2 \\ 3 & 4\end{pmatrix}`]) {+ const result = await typesetMath(tex);+ assert.equal(result.unitsPerEm, 1000);+ assert.equal(result.viewBox.length, 4);+ assert.ok(result.viewBox.every(Number.isFinite));+ assert.ok(result.viewBox[2] > 0 && result.viewBox[3] > 0);+ assert.ok(result.ascent > 0 && result.descent >= 0);+ assert.equal(result.ascent + result.descent, result.viewBox[3]);+ assert.ok(result.paths.length >= 3);+ for (const d of result.paths) {+ assert.match(d, /^M/);+ assert.doesNotMatch(d, /(?:NaN|Infinity|href|<)/);+ }+ }+ const fraction = await typesetMath(String.raw`\frac{1}{2}`);+ assert.ok(fraction.paths.some(d => /^M120 -220L820 -220L820 -280L120 -280Z$/.test(d)), 'fraction bar includes the flipped SVG coordinates');+ const inline = await typesetMath(String.raw`\frac{1}{2}`, false);+ assert.ok(inline.viewBox[3] < fraction.viewBox[3]);+});++test('math caches by TeX and display style and reuses the disk result', async t => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-math-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const tex = String.raw`\sum_{i=1}^n i`;+ const hash = mathHash(tex);+ assert.match(hash, /^[0-9a-f]{64}$/);+ assert.notEqual(hash, mathHash(tex, false));+ assert.notEqual(hash, mathHash('x'));+ const file = path.join(dir, `${hash}.json`);+ const result = await typesetMath(tex, true, file);+ assert.deepEqual(JSON.parse(fs.readFileSync(file)), result);+ fs.utimesSync(file, 1, 1);+ assert.deepEqual(await typesetMath(tex, true, file), result);+ assert.equal(fs.statSync(file).mtimeMs, 1000);+});++test('math errors keep the TeX message and do not leak macros between formulas', async () => {+ await assert.rejects(typesetMath(String.raw`\frac{1}`), /Missing argument for \\frac/);+ await assert.rejects(typesetMath(String.raw`\unknown`), /Undefined control sequence \\unknown/);+ await typesetMath(String.raw`\newcommand{\localmacro}{x}\localmacro`);+ await assert.rejects(typesetMath(String.raw`\localmacro`), /Undefined control sequence/);+ await assert.rejects(typesetMath(String.raw`\require{html}`), /Undefined control sequence/);+ await assert.rejects(typesetMath('x'.repeat(MAX_TEX_LENGTH + 1)), /at most 4096 characters/);+ await assert.rejects(typesetMath(null), /TeX string/);+ await assert.rejects(typesetMath('x', 'false'), /display must be true or false/);+});diff --git a/test/server.test.js b/test/server.test.jsindex 8723178..849c201 100644--- a/test/server.test.js+++ b/test/server.test.js@@ -5,6 +5,7 @@ import os from 'node:os';import path from 'node:path';import http from 'node:http';import { startServer } from '../src/server.js';+import { mathHash, MAX_TEX_LENGTH } from '../src/math.js';function request(port, { method = 'GET', path: p, host = `127.0.0.1:${port}`, origin, body }) {return new Promise((resolve, reject) => {@@ -20,6 +21,38 @@ function request(port, { method = 'GET', path: p, host = `127.0.0.1:${port}`, or});}+test('math only accepts bounded GET input and keeps the cache inside build/math', async t => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-math-server-'));+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-math-outside-'));+ t.after(() => { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(outside, { recursive: true, force: true }); });+ const server = await startServer({ projectDir: dir, getState: () => ({}) });+ t.after(() => server.close());+ const get = (tex, extra = {}) => request(server.port, { path: `/__math?tex=${encodeURIComponent(tex)}`, ...extra });+ const result = await get(String.raw`\frac{1}{2}`);+ assert.equal(result.status, 200);+ assert.equal(JSON.parse(result.body).paths.length, 3);+ const file = path.join(dir, 'build/math', `${mathHash(String.raw`\frac{1}{2}`)}.json`);+ assert.equal(fs.readFileSync(file, 'utf8'), result.body);+ assert.equal((await get('x'.repeat(MAX_TEX_LENGTH))).status, 200);+ assert.equal((await get('x'.repeat(MAX_TEX_LENGTH + 1))).status, 400);+ assert.equal((await request(server.port, { path: '/__math' })).status, 400);+ assert.equal((await request(server.port, { path: '/__math?tex=x&display=false' })).status, 400);+ for (const method of ['POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']) assert.equal((await get('x', { method })).status, 405);+ assert.equal((await get('x', { host: 'evil.example:80' })).status, 403);+ assert.equal((await get('x', { origin: 'https://evil.example' })).status, 403);+ const bad = await get(String.raw`\unknown`);+ assert.equal(bad.status, 400);+ assert.match(JSON.parse(bad.body).error, /Undefined control sequence/);+ assert.equal((await request(server.port, { path: '/project/build/math/' + path.basename(file) })).status, 404);+ fs.symlinkSync(path.join(outside, 'cache.json'), path.join(dir, 'build/math', `${mathHash('x')}.json`));+ assert.equal((await get('x')).status, 400);+ assert.deepEqual(fs.readdirSync(outside), []);+ fs.rmSync(path.join(dir, 'build/math'), { recursive: true });+ fs.symlinkSync(outside, path.join(dir, 'build/math'));+ assert.equal((await get('x')).status, 400);+ assert.deepEqual(fs.readdirSync(outside), []);+});+test('chunked uploads are assembled in order and appear only when complete', async () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-chunks-'));fs.writeFileSync(path.join(dir, 'scenes.js'), 'export default {};');