JavaScriptJavaScript API

JavaScript API

Python

JavaScript conventions, WASM loading, the error hierarchy, and a map of the texform module.

Conventions#

The texform npm package exposes the parser, document model, transform engine, and serializer from one Rust core, compiled to WebAssembly. Install it with npm install texform; see Installation for supported runtimes and per-bundler notes. Methods, function names, and option keys use camelCase; the Python binding uses snake_case. Both bindings share the parsing and transform core, but configuration interfaces and some exception types differ.

The package ships Node, bundler, and lazy web builds behind one exports map. Importing the bare specifier texform resolves to texform/node under Node.js and texform/bundler under a bundler or browser; import a subpath only to force a build. The Node build loads the WebAssembly module through the filesystem and offers both ESM and CommonJS entry points, and needs no setup. The bundler build initializes WebAssembly during module evaluation, so it runs top-level await and your toolchain must treat .wasm as an asset. TypeScript declarations are bundled and shared by both builds.

Structured data crosses the boundary as plain objects described by interfaces in the bundled declarations, never custom wrapper classes. Document, Node, Parser, and TransformEngine are live class instances holding a WASM handle, and each exposes free() and [Symbol.dispose]() — under a using declaration the handle is released at scope exit, otherwise garbage collection reclaims it. A SyntaxNode is a plain object snapshot. A Node's kind is a lowercase property, unlike Python's capitalized kind(); the discriminators inside argument and group views keep their capitalized form (arg.kind === "Math").

Configuration is a single overlay layer: ParseConfig, TransformConfig, and NormalizeConfig are plain objects whose keys are all optional, and an omitted key keeps the profile or parser default. Unknown keys, snake_case keys, and wrong scalar types throw TexformConfigError with a field path. Enum values stay snake_case ("sub_first") even though the keys are camelCase. The parse baseline is lenient.

The structured library errors derive from TexformError (which extends Error) and carry a kind discriminator: TexformParseError, TexformEditError, TexformConfigError, and TexformTransformError. Parser.parse returns malformed-input diagnostics and a document that may be null; invalid configuration still throws TexformConfigError.

Module map#

Parser#

SymbolKindDescription
ParserclassA knowledge-driven LaTeX parser.
ParserOptionsinterface
ParseConfiginterfaceParser strictness configuration overlay, as a plain object with camelCase keys. All fields are optional; null / undefined means not set. Unknown keys, snake_case keys, arrays in object positions, and wrong scalar types throw TexformConfigError with a path.
ParseResultinterfaceThe outcome of Parser.parse (and TransformEngine.parse): an optional Document plus the diagnostics emitted while parsing.
ParseDiagnosticinterfaceOne diagnostic emitted while parsing, describing a recovered or rejected condition.
ParseDiagnosticContextinterfaceOne nested context frame attached to a ParseDiagnostic, locating the enclosing construct (such as the command or environment) the error occurred within.
ParseDiagnosticKindtypeThe category of a ParseDiagnostic, or null when the parser emits a diagnostic without a specific category.
SpaninterfaceA source byte range, half-open as [start, end), indexing into the original LaTeX input.
SyntaxNodetypeThe lossless, immutable parse snapshot — the single serde wire format.
ContextItemtypeOne custom knowledge entry supplied to KnowledgeBase through the items option, discriminated by target.
CommandInfointerfaceThe knowledge-base entry for a command, returned by KnowledgeBase.lookupCommand and related lookups.
EnvInfointerfaceThe knowledge-base entry for an environment, returned by KnowledgeBase.lookupEnv.
CharacterInfointerfaceThe knowledge-base entry for a special character, returned by KnowledgeBase.lookupCharacter.
CharacterAttributesInfointerfaceRendering attributes for a special character in the knowledge base.
AllowedModetypeThe content modes a command, environment, or character is allowed in: "math", "text", or "both".
CommandKindtypeThe syntactic role of a command in the knowledge base: "prefix" (takes its arguments after the control sequence), "infix" (binds operands on both sides, like \over), or "declarative" (a scope-affecting declaration).
ArgSpecKindInfotypeThe value kind one parsed argument slot accepts, with a type discriminator.
DelimiterTokenInfotypeA single delimiter token in an argspec form: a literal char (such as () or a control-seq (such as langle).
ArgSpecFormInfotypeThe syntactic form one parsed argument slot takes, with a type discriminator: a standard argument, a star flag, a brace group, a delimited argument bounded by an open/close pair, or a paired argument accepting any of several interchangeable delimiter pairs.

KnowledgeBase#

SymbolKindDescription
KnowledgeBaseclassImmutable knowledge shared by parsers, engines and documents.
KnowledgeBaseOptionsinterfaceConstruction options for an immutable KnowledgeBase.
DelimiterInfointerface
ConstructionOptionsinterfaceOptions for the create* methods. mode is the context mode of the detached subtree. It defaults to text for createInlineMath, math for createDelimitedGroup, createScripted, createPrime, and createInfix, the group's own mode for createGroup, and the document root mode otherwise.

Document#

SymbolKindDescription
DocumentclassThe editable LaTeX document tree — the working format you read, mutate, serialize, and transform.
NodeSpanEntryinterfaceOne entry of Document.nodeSpans: a node identifier paired with its recorded source Span.
TokenizedLatexinterfaceSerialized LaTeX and tokens produced by the same serializer traversal.
SerializationTokeninterfaceOne non-empty serialization fragment.
SerializationTokenKindtypeClosed semantic categories emitted by tokenized serialization.
NodeTableinterfacePreorder node columns; field names stay snake_case in both bindings.
ArgumentTableinterfaceAll argument slots, ordered by owner row and slot index.
ColumnarTreeinterfaceTree columns for bulk structural analysis with Arrow or DataFrame tools.

Node#

SymbolKindDescription
NodeclassA read-only handle into a Document.
NodeKindtypeThe runtime kind of a Node, read from the lowercase Node.kind property.
SyntaxContentModetypeContent mode as it appears in a SyntaxNode snapshot: "Math" or "Text" (capitalized snapshot form).
RuntimeContentModetypeContent mode as reported by the runtime tree API: "math" or "text" (lowercase form used by Node.contentMode and the mode arguments of lookup methods).
GroupKindtypeThe kind of a group in SyntaxNode snapshot form: an Explicit brace group, an Implicit group, a Delimited group carrying its left/right delimiters, or an InlineMath group.
GroupKindReftypeThe kind of a group in runtime view form, with a kind discriminator. Returned by Node.groupKind; the discriminator keeps its capitalized form ('Explicit', 'Delimited', ...). A Delimited group carries left and right delimiter strings.
DelimitertypeA delimiter token in SyntaxNode snapshot form: the literal "None", a single character ({ Char }), or a control sequence ({ Control }). Runtime views use delimiter strings instead: ., one character, or a backslash-prefixed control sequence such as \langle.
ArgumentinterfaceA present command/environment argument in SyntaxNode snapshot form, pairing its syntactic ArgumentKind with its parsed ArgumentValue.
ArgumentKindtypeThe syntactic kind of a command argument in SyntaxNode snapshot form (mandatory, optional, starred, group, until, or delimited/paired). Until forms carry close; delimited/paired forms carry open and close.
ArgumentValuetypeThe parsed value carried by an Argument in snapshot form: math or text content, a delimiter, a control-sequence name, a dimension, an integer, a key=value list, a column spec, or a boolean flag.
ArgumentSlottypeAn argument slot of a Node's argument list: either a present Argument or an empty slot (null/undefined).
ArgReftypeA command/environment argument in runtime view form, returned by Node.arg and Node.argSlots.
ArgFormtypeThe delimiter form of an argument slot; close is present for until, and both open and close for delimited and paired forms.
NodeSlottypeThe parent slot a Node fills; index is set for indexed slots such as children and arguments.
ArgtypeA slot value accepted by construction and editing methods: a string is the source written inside the slot's boundaries, a detached Node is content, boolean sets a star slot, null omits an optional slot, and { value, open, close } selects an explicit delimiter pair.

TransformEngine#

SymbolKindDescription
TransformEngineclassA profile-based normalization engine: a parser paired with a transform pipeline.
TransformEngineOptionsinterfaceConstruction options for TransformEngine: a shared knowledge base, the required normalization Profile, and optional rule disabling.
NormalizeConfiginterfacePer-run overlay for TransformEngine.normalize: parse keys from ParseConfig plus transform keys from TransformConfig, flattened together. null / undefined / omitted means not set.
TransformConfiginterfaceThe nested, per-phase transform configuration, overriding a profile's transform defaults.
RewriteConfiginterfacePer-run switches for the fixed-point Rewrite phase.
LowerAttributesConfiginterfacePer-run switches for the LowerAttributes phase.
FinalizeAstConfiginterfacePer-run switches for the FinalizeAst phase.
FlattenGroupsConfiginterfacePer-run switches for the FlattenGroups phase (redundant-brace removal).
NormalizeReportResultinterfaceText plus the diagnostic report from TransformEngine.normalizeWithReport.
TransformReportinterfaceDiagnostic report for one explicit report call.
TransformWarninginterfaceAn unknown input name whose arguments or scope cannot be guaranteed.
LowerAttributesReportinterfaceThe LowerAttributes phase report.
AttributeStatinterfaceActivity for one (attr, value) pair in LowerAttributes.
AttributeFormCountsinterfaceCounts of an attribute form split by carrier: declaratives (scope-affecting declarations such as {\bf ...}) and prefixes (prefix commands such as \mathbf{...}).
RewriteRuleStatinterfaceOne rewrite rule's outcome for a single call.
RewriteReportinterfaceThe Rewrite phase report.
FinalizeAstReportinterfaceThe FinalizeAst phase report.
FlattenGroupsActionCountsinterfaceFlatten actions that changed the tree.
FlattenGroupsGuardCountsinterfacePreserve-guard hits for one FlattenGroups run.
FlattenGroupsReportinterfaceThe FlattenGroups phase report.
TransformProfiletypeNormalization profile selecting the canonical form for one downstream scenario: authoring (polished author-facing output), faithful (same rendered formula, convenience macros expanded), corpus (training-data normalization, layout hints dropped), or equiv (aggressive canonicalization for equivalence comparison).
ProfiletypeNormalization profile passed to TransformEngineOptions: "authoring", "faithful", "corpus", or "equiv".
RuleLeveltypeHow aggressively a transform rule may rewrite, layered from least to most destructive of stylistic detail.

serialize#

SymbolKindDescription
serializefunctionDeprecated. Prefer Document.fromSyntax(node).toLatex(options) or document.toLatex(options). This remains exported as a compatibility helper for older snapshot call sites and takes the same options as toLatex.
SerializeOptionsinterfaceOptions for Document.toLatex, Document.toTokenizedLatex, and serialize. Unknown keys and invalid values throw TexformConfigError. For a task-oriented walkthrough, see the Serialization guide.
StyletypeSpaced output is byte-stable; compact preserves structure and text idempotency.

validateArgspec#

SymbolKindDescription
validateArgspecfunctionValidate an xparse-style argspec string and report its parsed slots.
ValidateArgspecResultinterfaceThe outcome of validateArgspec: whether the spec is well-formed and, when valid, its parsed slots.
ParsedArgSpecSlotinterfaceOne parsed argument slot of an argspec, as reported by validateArgspec and by the parser's command/environment lookups.

Utilities#

SymbolKindDescription
listPackagesfunctionList all built-in knowledge packages with record counts.
PackageInfointerfaceSummary of one built-in knowledge package, returned by listPackages.
TexformErrorexceptionBase class for every error the library throws.
TexformParseErrorexceptionThrown when source could not be parsed into a complete tree.
TexformEditErrorexceptionThrown by Document editing methods on an invalid edit: editing a read-only (error) tree, detaching or removing the root, an out-of-bounds index, or mixing nodes across documents.
TexformConfigErrorexceptionThrown on invalid construction or per-call configuration: unknown package or profile names, unknown or snake_case keys, arrays in object positions, and wrong scalar types. Messages include a camelCase field path.
TexformTransformErrorexceptionThrown on a transform-engine failure, such as an eliminated-form contract violation, or passing TransformEngine.transform a document that Document.hasErrors or that is bound to a different KnowledgeBase instance.
TexformConformanceErrorexceptionThrown when a construction, edit, or syntax import violates the knowledge base or the document's structure.
listRulesfunctionList all built-in rewrite rules, sorted by key.
RuleInfointerfaceSummary of one built-in rewrite rule, returned by listRules.
RuleFidelitytypeA rewrite rule's worst-case equivalence guarantee over its declared input domain, ordered least to most faithful: math (mathematical meaning is preserved, rendering may change), reading (notation content, reading order, and structural roles are preserved), render (rendering is equivalent under the reference renderer).