Plurimath TypeScript
Purpose
Plurimath provides a common data model for mathematical representation
languages and allows conversion between them. This is its native TypeScript
implementation, replacing the Opal-compiled
plurimath-js.
Target math representational languages:
The Ruby gem remains the source of
truth. Correctness is proven against a conformance corpus generated from it —
parse tree, model, and every rendered output must match — so the two cannot
drift apart silently.
Status
The initial release is @plurimath/plurimath@0.1.0, with native TypeScript parsers
and renderers for all six formats. This release exposes format subpaths within
one npm package. Separate language packages and remaining shared-fixture
organization are deferred.
The current source and package entries provide:
- Parsers exist for all six math formats, exposed on their subpaths and through
the root
parse function and compat constructor. The root and constructor
also accept standalone UnitsML input.
- Default HTML parsing uses the checked Ruby-derived PARG artifacts on the
Parsanol runtime, with one lazy runtime per decimal marker. Browser callers
can supply an initialized runtime through
./html/parsanol.
- Renderers exist for all six output formats: AsciiMath, LaTeX, MathML, HTML,
UnicodeMath and OMML.
- Nine package subpaths are built:
./core, ./asciimath, ./latex,
./mathml, ./html, ./omml, ./unicodemath, ./mathml/leptris and
./omml/leptris, plus the root entry and a plurimath executable. The two
Leptris entries require a caller-initialized binding, as described below.
- The HTML parity fixture covers 664 gem-renderable cases written in
AsciiMath, LaTeX, UnicodeMath, MathML or OMML. All 664 now match, including
the six MathML text cases that previously refused Unicode substitutions
(see
test/formats/html/parity-target.ts). Native UnitsML expansion replaces
the former text-unitsml-valid plain-text divergence. The corpus is not the
whole language:
a construct it does not cover can still raise RenderError.
- UnicodeMath input uses the pinned gem's grammar and 484 reachable transform
rules. The other 35 rules have source-based unreachability proofs (see
rule reachability). The parser
preserves raw trees that Ruby leaves unmatched; those models may refuse
rendering in both implementations. Conformance is measured against the
generated fixtures, rather than inferred from the rule count.
Correctness is gated rather than asserted: a registry of quality gates activates
in milestones. The current one is recorded as currentMilestone in
gates.json, and is P2.
TODO.plan/ — every phase from here to 1.0, what each
contains, and which decisions are still open.
ARCHITECTURE.md — how the code is structured and what
proves it correct.
Usage
Install the package with Node.js 22 or later:
npm install @plurimath/plurimath
Both ESM (import) and CommonJS (require) entries are provided. The CLI file
example assumes a formula.txt you create.
Input and output formats
| Format |
Read (parse) |
Write (render) |
Subpath |
| AsciiMath |
parseAsciimath |
toAsciimath |
./asciimath |
| LaTeX |
parseLatex |
toLatex |
./latex |
| HTML |
parseHtml |
toHtml |
./html |
| UnicodeMath |
parseUnicodemath |
toUnicodemath |
./unicodemath |
| MathML |
parseMathml |
toMathml |
./mathml |
| OMML |
parseOmml |
toOmml |
./omml |
Each parser returns a FormulaNode (from ./core); each renderer takes one.
The root also exports parse(input, format, options?), returning a
FormulaNode. It uses the compat format tokens: asciimath, latex, html,
unicode, mathml, omml and unitsml (unicode, not unicodemath). Text formats
accept their existing locale and onUnsupported options. MathML, OMML
and standalone UnitsML accept absent, null or empty options and reject
nonempty option keys with ParseOptionError. The exported ParseOptions<F> type selects the options
for format F; the compat constructor keeps its existing two arguments.
import { parse } from "@plurimath/plurimath";
const formula = parse("1,5", "asciimath", { locale: "de" });
Per-format subpaths
import { parseAsciimath } from "@plurimath/plurimath/asciimath";
import { toLatex } from "@plurimath/plurimath/latex";
toLatex(parseAsciimath("x^2 + frac(1)(2)")); // x^{2} + \frac{1}{2}
Converting the other way, parseLatex("\\frac{1}{2}") rendered with
toAsciimath gives frac(1)(2). Subpaths are built so that importing one
does not pull in the other formats' renderers (pnpm gate:package inspects the
built artifacts for this); only the root entry is batteries-included.
Evaluation
The root entry's evaluate(formula, bindings, options) returns the numeric
value of a formula as a number. evaluateResult takes the same arguments
and returns the gem's whole evaluation result instead: the value with its Ruby
class, every accuracy boundary the evaluation crossed or deferred, and the
formula left unevaluated. With mode: "strict", decimal literals and division
stay exact, and the first inexact operation stops the evaluation. Adding
guardDigits computes sin, cos, exp, ln, log, lg, sqrt and
arctan of exact integer arguments as BigDecimals to that many digits, using
the same algorithms as Ruby's bigdecimal gem, so the last digit matches the
gem's.
import { evaluateResult, parse } from "@plurimath/plurimath";
const options = { mode: "strict", guardDigits: 20 };
evaluateResult(parse("sin(1)", "asciimath"), {}, options).value;
// { kind: "decimal", value: "0.84147098480789650665e0", precision: 20 }
evaluate refuses with UnsupportedFeatureError where the value is not a
JavaScript number: a Rational, a BigDecimal, an integer beyond the safe range,
or a strict evaluation that stopped.
For exact quantities, call evaluateQuantity(formula, { runtime, bindings, target })
with the UnitsML module as runtime. It uses UnitsML for dimension checks,
scale-aware arithmetic, and conversion. For example, a formula multiplying
2 unitsml(kV) by 3 unitsml(A) evaluates to 6 kW with target: "kW".
The runtime is supplied by the caller so numeric-only consumers need no
additional dependency.
Optional Leptris XML input
./mathml/leptris and ./omml/leptris expose parser factories for an
already initialized Leptris binding. The regular package and format entries
use the native reader and do not require a Leptris installation. The optional
entries also leave loading and initialization of WASM to your application.
This requires the structured-tree binding API added in
leptris-ts#9, backed by an
engine containing leptris#1742.
Both changes are merged. Published leptris@0.1.16 still lacks the required
WASM tree export; leptris-ts#21
tracks that build fix. With a binding containing the export fix:
import * as leptris from "leptris";
import { createMathmlParser } from "@plurimath/plurimath/mathml/leptris";
import { createOmmlParser } from "@plurimath/plurimath/omml/leptris";
import { toMathml } from "@plurimath/plurimath/mathml";
await leptris.init();
const parseMathml = createMathmlParser(leptris);
const parseOmml = createOmmlParser(leptris);
const formula = parseMathml("<math><mfrac><mi>x</mi><mn>2</mn></mfrac></math>");
console.log(toMathml(formula));
Both factories return synchronous parsers with the usual FormulaNode result
and ParseError failures. Creating a parser does not initialize the binding
or load XML. Each parse closes its document after copying the tree, including
when snapshot retrieval fails. There is no native-reader fallback. Plurimath
keeps its named-entity compatibility in the adapter; other XML semantics come
from Leptris. See the integration notes for the
binding contract and real-WASM verification command.
Serialized evaluation with WASM
Import initNumericWasm from @plurimath/plurimath/evaluation/wasm
and pass the bundled @plurimath/plurimath/evaluation/plurimath_numeric.wasm
bytes or a URL object pointing to them. The evaluator's evaluateRequest(json) accepts
numeric, quantity, and GUM v1 requests. The kernel supports uncertainty
propagation, series statistics, coverage factors, conformance decisions, and
Monte Carlo propagation for independent and joint-normal inputs, including the
supported certified rational models. Caller registers supply exact conversion
factors, offsets and dimensions in the quantity request. Conformance results
include signed residuals and the selected rule's boundary decision. The
kernel returns typed refusals for unsupported sampling profiles. The pinned request and response examples are in
test/fixtures/evaluation-wasm.
Native format facade with WASM
@plurimath/plurimath/facade/wasm loads the Rust plurimath-facade crate
compiled to WebAssembly. It parses AsciiMath, HTML, LaTeX, MathML, OMML, PMA,
UnicodeMath and UnitsML, keeps the common {class, fields} model, and writes
AsciiMath, LaTeX, UnicodeMath, HTML, MathML and OMML. Parsing, options and
writers all run in the native facade; this entry only moves JSON requests in
and out of the module. It does not use the TypeScript parsers or renderers.
Initialize it once with the bundled
@plurimath/plurimath/facade/plurimath_facade.wasm bytes, a fetch
response or a URL. The SHA-256 of the asset is checked before it is
compiled. Calling initFacadeWasm again with the same asset returns the same
kernel.
import { FacadeError, initFacadeWasm } from "@plurimath/plurimath/facade/wasm";
const kernel = await initFacadeWasm(wasmBytes);
const formula = kernel.parse("x^2", "asciimath");
console.log(formula.toMathml());
console.log(formula.write("latex", { formatterOptions: null }));
try {
kernel.parse("\\frac{", "latex");
} catch (error) {
if (error instanceof FacadeError) console.error(error.code, error.sourceClass);
}
Parse and writer options are passed to the native facade unchanged. A refusal
from the facade throws FacadeError with the native code, the Ruby
sourceClass when there is one, and the complete error object in details.
Loading and transport problems throw FacadeWasmError. kernel.requestJson
sends one raw JSON request and returns the native envelope unchanged.
kernel.fromModel(model) accepts a common model, and kernel.fromSourceModel
accepts a plurimath.ruby-values/1 document. formula.model returns a fresh
copy each time. A request can be at most 16 MiB. The kernel allocates the input
for each call and frees the input and the result exactly once;
kernel.accounting() reports these counts.
The asset, its official wasm-bindgen glue, licences, notices, the notices of
every Rust dependency and the source Cargo.lock are pinned in
assets/facade/manifest.json. The package test
replays the frozen source corpus in
test/fixtures/facade through the packed package in
Node and Chrome: node scripts/check-facade-packed.mjs all.
Typed quantity values
Use evaluateQuantityRequest(kernel, request) from the same WASM entry after
explicitly initializing the kernel. It preserves the complete request and native
response, including the numeric class and accuracy. The raw evaluateRequest(json)
API and the separate UnitsML-runtime evaluateQuantity API remain unchanged.
import {
initNumericWasm,
evaluateQuantityRequest,
} from "@plurimath/plurimath/evaluation/wasm";
const kernel = await initNumericWasm(wasmBytes);
const response = evaluateQuantityRequest(kernel, {
schema: "plurimath.evaluate.quantity/1",
ast: {
type: "binary", operator: "*",
left: { type: "variable", name: "x" },
right: { type: "variable", name: "y" },
},
bindings: {
x: { value: { decimal: "2.5" }, unit: "m" },
y: { value: "3", unit: "s" },
},
});
if (response.ok) {
console.log(response.result.value.numeric_value, response.result.accuracy.symbol);
} else {
console.error(response.error.code);
}
Binding values are plain strings for exact Rational values (including integers),
{ decimal: "2.5" } for a BigDecimal, { rational: ["5", "2"] } for an exact
Rational, or { binary64: "4004000000000000" } for a Float. Binary64 tags contain
16 big-endian IEEE 754 hexadecimal digits. Decimal text and rational components
stay strings; the client does not convert them to JavaScript numbers.
On a kernel supporting these explicit tags, a tagged request includes
numeric_value on result.value and on a non-null result.converted. The value
has kind: "rational" with string numerator/denominator, kind: "decimal"
with the source BigDecimal's scientific value string and integer precision,
or kind: "float" with its bits. It describes the snapshot's magnitude,
not canonical_magnitude; converted values can have a different numeric kind.
Accuracy remains the separate result.accuracy object. Plain-string requests
retain their legacy response without the new field. Unsupported or invalid
requests return the kernel's error response; this helper does not fall back to
another evaluator.
The compat class
The root entry also default-exports Plurimath, shaped after the
plurimath-js class: construct it from a string and a format, then call a
to* method.
import Plurimath from "@plurimath/plurimath";
const p = new Plurimath("x^2", "asciimath");
p.toLatex(); // x^{2}
p.toHtml(); // <i>x</i><sup>2</sup>
p.toUnicodemath(); // x^(2)
The constructor names seven formats (FORMATS): asciimath, latex, mathml,
html, unicode, omml and unitsml. Note unicode, not unicodemath.
Standalone UnitsML is input only; all six output formats work with it.
Its Formula wrapper follows Ruby commit 142bc513, after the frozen 0.11.20
reference. For example, new Plurimath("kg*m*s^-2", "unitsml").toLatex()
uses the same UnitsML service as embedded unit expressions.
An unrecognized input name, including unicodemath,
throws InvalidTypeError.
Methods: toAsciimath, toLatex, toMathml, toHtml, toOmml,
toUnicodemath all work. toMathml(true) renders the gem's intent
attributes (#136). toDisplay(lang) returns the gem's tree dump (#139, #150),
throws InvalidTypeError for a lang the gem rejects (html, unicode), and
throws UnsupportedFeatureError for the few node kinds it refuses
(src/compat/to-display.ts, module doc).
Command line
pnpm build produces dist/cli.mjs, which package.json#bin exposes as
plurimath. Run it directly with node dist/cli.mjs, or as plurimath once
the package is linked or installed.
plurimath convert --from asciimath --to latex formula.txt
printf 'frac(1)(2)' | plurimath convert --from asciimath --to mathml
plurimath convert --from mathml --to latex formula.mml
plurimath convert --from omml --to asciimath formula.omml
--from and --to accept asciimath, latex, mathml, html,
unicodemath and omml. Input comes from the file argument, or from
stdin when there is none. Exit codes: 0 success, 2 usage error (missing or
unknown option or format, unknown command), 1 for anything else (unreadable
file, ParseError, RenderError). Conversion errors print as
plurimath: [CODE] message on stderr; usage and file-read errors print
plurimath: <message> without a code. The only command is convert, and there is no --version.
Render options, named as in the gem's plurimath convert where it has them: