@mathconv/mathconv 0.0.0-stage → 0.1.0-alpha.4

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Viktor Shcherbakov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,165 @@
1
+ mathconv includes data derived from unicode.xml of the W3C xml-entities
2
+ repository (https://github.com/w3c/xml-entities), commit
3
+ efed20d963c6f4f9f26645f385b28439f069f4e3:
4
+
5
+ unicode.xml
6
+ Copyright David Carlisle 1999-2025
7
+ Use and distribution of this code are permitted under the terms of the
8
+ W3C Software Notice and License.
9
+ http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231.html
10
+
11
+ The derived files are crates/mathconv/src/tables/symbols.rs, letters.rs,
12
+ entities.rs and operators.rs. `cargo xtask tables` produces them from
13
+ unicode.xml by selecting the LaTeX commands, styled letters, entity
14
+ names and operator dictionary entries and writing them as Rust arrays.
15
+ They were produced on 2026-12-03.
16
+
17
+ The W3C Software Notice and License (2002-12-31) follows.
18
+
19
+ By obtaining, using and/or copying this work, you (the licensee) agree
20
+ that you have read, understood, and will comply with the following
21
+ terms and conditions.
22
+
23
+ Permission to copy, modify, and distribute this software and its
24
+ documentation, with or without modification, for any purpose and
25
+ without fee or royalty is hereby granted, provided that you include
26
+ the following on ALL copies of the software and documentation or
27
+ portions thereof, including modifications:
28
+
29
+ 1. The full text of this NOTICE in a location viewable to users of the
30
+ redistributed or derivative work.
31
+ 2. Any pre-existing intellectual property disclaimers, notices, or
32
+ terms and conditions. If none exist, the W3C Software Short Notice
33
+ should be included (hypertext is preferred, text is permitted)
34
+ within the body of any redistributed or derivative code.
35
+ 3. Notice of any changes or modifications to the files, including the
36
+ date changes were made. (We recommend you provide URIs to the
37
+ location from which the code is derived.)
38
+
39
+ THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT
40
+ HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,
41
+ INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS
42
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR
43
+ DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
44
+ TRADEMARKS OR OTHER RIGHTS.
45
+
46
+ COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL
47
+ OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR
48
+ DOCUMENTATION.
49
+
50
+ The name and trademarks of copyright holders may NOT be used in
51
+ advertising or publicity pertaining to the software without specific,
52
+ written prior permission. Title to copyright in this software and any
53
+ associated documentation will at all times remain with copyright
54
+ holders.
55
+
56
+
57
+ The website in site/ and its build add the following third-party
58
+ material. None of it is part of the Python package.
59
+
60
+ site/assets/fonts/ibm-plex-sans-latin.woff2, the Latin subset of IBM Plex
61
+ Sans (variable weight), as packaged by Fontsource 5.3.0
62
+ Copyright 2019 IBM Corp. All rights reserved.
63
+
64
+ site/assets/fonts/jetbrains-mono-latin.woff2, the Latin subset of JetBrains
65
+ Mono (variable weight), as packaged by Fontsource 5.3.0
66
+ Copyright 2020 The JetBrains Mono Project Authors
67
+ (https://github.com/JetBrains/JetBrainsMono)
68
+
69
+ The wordmark in site/assets/logo/ is set in JetBrains Mono and converted to
70
+ outlines.
71
+
72
+ These fonts are licensed under the SIL Open Font License, Version 1.1,
73
+ which follows.
74
+
75
+ -----------------------------------------------------------
76
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
77
+ -----------------------------------------------------------
78
+
79
+ PREAMBLE
80
+ The goals of the Open Font License (OFL) are to stimulate worldwide
81
+ development of collaborative font projects, to support the font creation
82
+ efforts of academic and linguistic communities, and to provide a free and
83
+ open framework in which fonts may be shared and improved in partnership
84
+ with others.
85
+
86
+ The OFL allows the licensed fonts to be used, studied, modified and
87
+ redistributed freely as long as they are not sold by themselves. The
88
+ fonts, including any derivative works, can be bundled, embedded,
89
+ redistributed and/or sold with any software provided that any reserved
90
+ names are not used by derivative works. The fonts and derivatives,
91
+ however, cannot be released under any other type of license. The
92
+ requirement for fonts to remain under this license does not apply
93
+ to any document created using the fonts or their derivatives.
94
+
95
+ DEFINITIONS
96
+ "Font Software" refers to the set of files released by the Copyright
97
+ Holder(s) under this license and clearly marked as such. This may
98
+ include source files, build scripts and documentation.
99
+
100
+ "Reserved Font Name" refers to any names specified as such after the
101
+ copyright statement(s).
102
+
103
+ "Original Version" refers to the collection of Font Software components as
104
+ distributed by the Copyright Holder(s).
105
+
106
+ "Modified Version" refers to any derivative made by adding to, deleting,
107
+ or substituting -- in part or in whole -- any of the components of the
108
+ Original Version, by changing formats or by porting the Font Software to a
109
+ new environment.
110
+
111
+ "Author" refers to any designer, engineer, programmer, technical
112
+ writer or other person who contributed to the Font Software.
113
+
114
+ PERMISSION & CONDITIONS
115
+ Permission is hereby granted, free of charge, to any person obtaining
116
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
117
+ redistribute, and sell modified and unmodified copies of the Font
118
+ Software, subject to the following conditions:
119
+
120
+ 1) Neither the Font Software nor any of its individual components,
121
+ in Original or Modified Versions, may be sold by itself.
122
+
123
+ 2) Original or Modified Versions of the Font Software may be bundled,
124
+ redistributed and/or sold with any software, provided that each copy
125
+ contains the above copyright notice and this license. These can be
126
+ included either as stand-alone text files, human-readable headers or
127
+ in the appropriate machine-readable metadata fields within text or
128
+ binary files as long as those fields can be easily viewed by the user.
129
+
130
+ 3) No Modified Version of the Font Software may use the Reserved Font
131
+ Name(s) unless explicit written permission is granted by the corresponding
132
+ Copyright Holder. This restriction only applies to the primary font name as
133
+ presented to the users.
134
+
135
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
136
+ Software shall not be used to promote, endorse or advertise any
137
+ Modified Version, except to acknowledge the contribution(s) of the
138
+ Copyright Holder(s) and the Author(s) or with their explicit written
139
+ permission.
140
+
141
+ 5) The Font Software, modified or unmodified, in part or in whole,
142
+ must be distributed entirely under this license, and must not be
143
+ distributed under any other license. The requirement for fonts to
144
+ remain under this license does not apply to any document created
145
+ using the Font Software.
146
+
147
+ TERMINATION
148
+ This license becomes null and void if any of the above conditions are
149
+ not met.
150
+
151
+ DISCLAIMER
152
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
153
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
154
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
155
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
156
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
157
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
158
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
159
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
160
+ OTHER DEALINGS IN THE FONT SOFTWARE.
161
+
162
+ `cargo xtask site` copies KaTeX (MIT License) and MathJax with its
163
+ MathJax New Computer Modern font (Apache License 2.0), at the versions
164
+ pinned in tools/render-check/package.json, into vendor/ of the built
165
+ site, together with the licence files of KaTeX and MathJax.
package/README.md CHANGED
@@ -1,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # @mathconv/mathconv
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ mathconv converts math formulas from MathML, the markup that web pages,
4
+ e-books and journal articles use for mathematics, into LaTeX or plain
5
+ text. This package is the WebAssembly build of its Rust core, with
6
+ TypeScript declarations, for Node.js 22.12 and later, Deno 2.9 and
7
+ later, bundlers and browsers.
8
+ It converts a formula the same way as the Python package and the
9
+ [playground](https://mathconv.dev/).
10
+
11
+ ## Installation
12
+
13
+ ```sh
14
+ npm install @mathconv/mathconv
15
+ ```
16
+
17
+ mathconv is in early development: until 1.0, output and API can change
18
+ between releases, so pin a version if you need reproducible output.
19
+
20
+ ## Usage
21
+
22
+ ```js
23
+ import { convert, Converter } from "@mathconv/mathconv";
24
+
25
+ const mathml = "<math><msqrt><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mn>1</mn></msqrt></math>";
26
+ convert(mathml); // "\\sqrt{x^2 + 1}"
27
+ convert(mathml, { target: "text" }); // "sqrt(x^2 + 1)"
28
+
29
+ const converter = new Converter({ delimiters: "dollar" });
30
+ converter.convertBatch(["<math><mi>a</mi></math>", '<math display="block"><mi>b</mi></math>']);
31
+ // ["$a$", "$$b$$"]
32
+ const result = converter.result("<math><mi>E</mi><mo>=</mo><mi>m</mi><msup><mi>c</mi><mn>2</mn></msup></math>");
33
+ result.output; // "$E = mc^2$"
34
+ result.fallbacks; // []: anything left unconverted would be listed here
35
+ ```
36
+
37
+ In Node.js and Deno the WebAssembly module loads when the package is
38
+ imported, and in Node.js `require("@mathconv/mathconv")` works as well.
39
+ Deno needs permission to read the package's `.wasm` file, granted with
40
+ `--allow-read`. Other runtimes that follow the `node` export condition
41
+ are expected to work but are not tested. In browsers and bundlers, load
42
+ the module once before converting:
43
+
44
+ ```js
45
+ import { init, convert } from "@mathconv/mathconv";
46
+
47
+ await init();
48
+ ```
49
+
50
+ `init()` fetches the module from next to the package's JavaScript, which
51
+ works with webpack, Vite and ES modules loaded directly in the browser.
52
+ With other setups, such as esbuild, pass the address or the bytes of the
53
+ module, which the package exports as `@mathconv/mathconv/mathconv.wasm`.
54
+
55
+ ## Documentation
56
+
57
+ The [JavaScript API reference](https://mathconv.dev/docs/guide/javascript-api/)
58
+ describes the API, its errors and loading the module in each
59
+ environment, and [Conversion options](https://mathconv.dev/docs/guide/options/)
60
+ the options. The [documentation](https://mathconv.dev/docs/) covers
61
+ what mathconv does and how well, and what the output looks like.
62
+
63
+ ## Licence
64
+
65
+ mathconv is released under the MIT licence. `NOTICE` covers the W3C
66
+ data its symbol tables are generated from.
package/index.d.ts ADDED
@@ -0,0 +1,113 @@
1
+ /** The version of the package, such as `0.1.0` or `0.1.0-alpha.4`. */
2
+ export const version: string;
3
+
4
+ /**
5
+ * Where `init` loads the WebAssembly module from: its address, a fetch
6
+ * `Request` or `Response`, its bytes, or the compiled module, or a promise
7
+ * of any of these.
8
+ */
9
+ export type ModuleSource =
10
+ | string
11
+ | URL
12
+ | Request
13
+ | Response
14
+ | BufferSource
15
+ | WebAssembly.Module
16
+ | Promise<string | URL | Request | Response | BufferSource | WebAssembly.Module>;
17
+
18
+ /**
19
+ * Loads the WebAssembly module, by default from its file next to the
20
+ * package's JavaScript. Call it once before converting; later calls do
21
+ * nothing. In Node.js and Deno the module is loaded on import.
22
+ */
23
+ export function init(source?: ModuleSource): Promise<void>;
24
+
25
+ /**
26
+ * Loads the WebAssembly module from its bytes or the compiled module,
27
+ * synchronously. Later calls do nothing.
28
+ */
29
+ export function initSync(source: BufferSource | WebAssembly.Module): void;
30
+
31
+ /** The source formats. */
32
+ export type Source = "mathml";
33
+
34
+ /** The target formats. */
35
+ export type Target = "latex" | "text";
36
+
37
+ /** The formats of a conversion and the options of the engine. */
38
+ export interface Options {
39
+ /** The source format; `mathml` by default. */
40
+ source?: Source;
41
+ /** The target format; `latex` by default. */
42
+ target?: Target;
43
+ /** Returns the formula's carried TeX, when it has suitable carried TeX, instead of converting the markup; target `latex` only. */
44
+ prefer_carried_tex?: boolean;
45
+ /** Leaves out the labels of table rows, such as equation numbers. */
46
+ drop_labels?: boolean;
47
+ /** The math delimiters around the body; `none` by default; target `latex` only. */
48
+ delimiters?: "none" | "dollar" | "paren";
49
+ }
50
+
51
+ /** The codes of the fallbacks. */
52
+ export type FallbackCode =
53
+ | "no-math"
54
+ | "extra-math"
55
+ | "unknown-element"
56
+ | "content-markup"
57
+ | "elementary-math"
58
+ | "glyph"
59
+ | "child-count"
60
+ | "error-element"
61
+ | "unknown-entity"
62
+ | "unmapped-character"
63
+ | "unsupported-notation"
64
+ | "depth-limit"
65
+ | "size-limit";
66
+
67
+ /** A part of the input that a conversion could not convert. */
68
+ export interface Fallback {
69
+ /** The fallback code, such as `unknown-element`. */
70
+ code: FallbackCode;
71
+ /** The element, entity, character or notation concerned. */
72
+ detail: string;
73
+ }
74
+
75
+ /** The result of one conversion. */
76
+ export interface Result {
77
+ /** The formula in the target format. */
78
+ output: string;
79
+ /** Whether the formula is a display formula. */
80
+ display: boolean;
81
+ /** Where the output came from: converted markup, or carried TeX from an annotation or `alttext`. */
82
+ takenFrom: "markup" | "annotation" | "alttext";
83
+ /** Every fallback, in input order; empty for carried TeX. */
84
+ fallbacks: Fallback[];
85
+ }
86
+
87
+ /**
88
+ * Converts one formula to a string.
89
+ *
90
+ * @throws {TypeError} for an input that is not a string or an option value of the wrong type.
91
+ * @throws {Error} for an unknown format, option or value, or an option that does not belong to the formats.
92
+ */
93
+ export function convert(text: string, options?: Options): string;
94
+
95
+ /**
96
+ * Converts formulas from a source format to a target format. Converters
97
+ * are immutable.
98
+ */
99
+ export class Converter {
100
+ /**
101
+ * @throws {TypeError} for an option value of the wrong type.
102
+ * @throws {Error} for an unknown format, option or value, or an option that does not belong to the formats.
103
+ */
104
+ constructor(options?: Options);
105
+ /** Converts one formula to a string. */
106
+ convert(text: string): string;
107
+ /** Converts one formula to a `Result`. */
108
+ result(text: string): Result;
109
+ /** Converts formulas to strings, in input order. */
110
+ convertBatch(texts: Iterable<string>): string[];
111
+ /** Converts formulas to `Result` objects, in input order. */
112
+ resultBatch(texts: Iterable<string>): Result[];
113
+ }
package/index.js ADDED
@@ -0,0 +1,179 @@
1
+ // The public module of the npm package. The WebAssembly module is loaded
2
+ // by `init` or `initSync`; `node.js` loads it on import.
3
+
4
+ import load, {
5
+ Converter as Engine,
6
+ convert as convertWith,
7
+ initSync as loadSync,
8
+ input,
9
+ } from "./mathconv_glue.js";
10
+
11
+ export const version = "0.1.0-alpha.4";
12
+
13
+ /** The memory of the instantiated module, or `undefined` before `init`. */
14
+ let memory;
15
+ /** The input buffer in `memory`, as its address and size in bytes. */
16
+ let address = 0;
17
+ let size = 0;
18
+ let bytes = new Uint8Array(0);
19
+ const encoder = new TextEncoder();
20
+
21
+ export async function init(source) {
22
+ if (memory === undefined) {
23
+ const exports = await load(source === undefined ? undefined : { module_or_path: source });
24
+ memory = exports.memory;
25
+ }
26
+ }
27
+
28
+ export function initSync(source) {
29
+ if (memory === undefined) {
30
+ memory = loadSync({ module: source }).memory;
31
+ }
32
+ }
33
+
34
+ function loaded() {
35
+ if (memory === undefined) {
36
+ throw new Error("mathconv is not initialised; call `await init()` first");
37
+ }
38
+ }
39
+
40
+ /** The input buffer, at least `needed` bytes long. */
41
+ function buffer(needed) {
42
+ if (needed > size) {
43
+ size = Math.max(needed, 2 * size);
44
+ address = input(size);
45
+ bytes = new Uint8Array(memory.buffer, address, size);
46
+ } else if (bytes.byteLength === 0) {
47
+ // Growing the memory detaches the views of its old buffer.
48
+ bytes = new Uint8Array(memory.buffer, address, size);
49
+ }
50
+ return bytes;
51
+ }
52
+
53
+ /**
54
+ * Writes `text` as UTF-8 to the input buffer at `offset` and returns its
55
+ * length in bytes. The buffer is first made as long as the text in code
56
+ * units, which fits ASCII, and grows if the rest does not fit.
57
+ */
58
+ function encode(text, offset) {
59
+ let { read, written } = encoder.encodeInto(text, buffer(offset + text.length).subarray(offset));
60
+ if (read < text.length) {
61
+ // A UTF-16 code unit takes at most three bytes in UTF-8.
62
+ const end = offset + written;
63
+ const rest = buffer(end + 3 * (text.length - read)).subarray(end);
64
+ written += encoder.encodeInto(text.slice(read), rest).written;
65
+ }
66
+ return written;
67
+ }
68
+
69
+ function notString(value, where) {
70
+ return new TypeError(`${where} must be a string, not ${value === null ? "null" : typeof value}`);
71
+ }
72
+
73
+ /** Writes one input to the input buffer and returns its length in bytes. */
74
+ function write(text) {
75
+ loaded();
76
+ if (typeof text !== "string") {
77
+ throw notString(text, "the input");
78
+ }
79
+ return encode(text, 0);
80
+ }
81
+
82
+ /** Writes the inputs to the input buffer and returns their lengths in bytes. */
83
+ function writeAll(texts) {
84
+ loaded();
85
+ if (!Array.isArray(texts)) {
86
+ if (typeof texts === "string" || typeof texts?.[Symbol.iterator] !== "function") {
87
+ throw new TypeError("the batch must be an array or another iterable of strings");
88
+ }
89
+ texts = Array.from(texts);
90
+ }
91
+ let units = 0;
92
+ for (let index = 0; index < texts.length; index += 1) {
93
+ const text = texts[index];
94
+ if (typeof text !== "string") {
95
+ throw notString(text, `item ${index} of the batch`);
96
+ }
97
+ units += text.length;
98
+ }
99
+ buffer(units);
100
+ const lengths = new Uint32Array(texts.length);
101
+ let used = 0;
102
+ for (let index = 0; index < texts.length; index += 1) {
103
+ const written = encode(texts[index], used);
104
+ lengths[index] = written;
105
+ used += written;
106
+ }
107
+ return lengths;
108
+ }
109
+
110
+ /** Cuts the joined outputs of a batch into the outputs. */
111
+ function split(joined, lengths) {
112
+ const outputs = new Array(lengths.length);
113
+ let start = 0;
114
+ for (let index = 0; index < lengths.length; index += 1) {
115
+ const end = start + lengths[index];
116
+ outputs[index] = joined.slice(start, end);
117
+ start = end;
118
+ }
119
+ return outputs;
120
+ }
121
+
122
+ /** The results of a batch from the text and the records of `Engine.results`. */
123
+ function results([text, records], count) {
124
+ const all = new Array(count);
125
+ let start = 0;
126
+ let record = 0;
127
+ const part = () => {
128
+ const end = start + records[record];
129
+ record += 1;
130
+ const value = text.slice(start, end);
131
+ start = end;
132
+ return value;
133
+ };
134
+ for (let index = 0; index < count; index += 1) {
135
+ const output = part();
136
+ const display = records[record] === 1;
137
+ record += 1;
138
+ const takenFrom = part();
139
+ const fallbacks = new Array(records[record]);
140
+ record += 1;
141
+ for (let fallback = 0; fallback < fallbacks.length; fallback += 1) {
142
+ fallbacks[fallback] = { code: part(), detail: part() };
143
+ }
144
+ all[index] = { output, display, takenFrom, fallbacks };
145
+ }
146
+ return all;
147
+ }
148
+
149
+ export function convert(text, options) {
150
+ const length = write(text);
151
+ return convertWith(options, length);
152
+ }
153
+
154
+ export class Converter {
155
+ #engine;
156
+
157
+ constructor(options) {
158
+ loaded();
159
+ this.#engine = new Engine(options);
160
+ }
161
+
162
+ convert(text) {
163
+ return this.#engine.convert(write(text));
164
+ }
165
+
166
+ result(text) {
167
+ return results(this.#engine.results(new Uint32Array([write(text)])), 1)[0];
168
+ }
169
+
170
+ convertBatch(texts) {
171
+ const lengths = writeAll(texts);
172
+ return split(this.#engine.convert_batch(lengths), lengths);
173
+ }
174
+
175
+ resultBatch(texts) {
176
+ const lengths = writeAll(texts);
177
+ return results(this.#engine.results(lengths), lengths.length);
178
+ }
179
+ }
@@ -0,0 +1,428 @@
1
+ /**
2
+ * Converts formulas with the formats and options of one converter.
3
+ */
4
+ export class Converter {
5
+ __destroy_into_raw() {
6
+ const ptr = this.__wbg_ptr;
7
+ this.__wbg_ptr = 0;
8
+ ConverterFinalization.unregister(this);
9
+ return ptr;
10
+ }
11
+ free() {
12
+ const ptr = this.__destroy_into_raw();
13
+ wasm.__wbg_converter_free(ptr, 0);
14
+ }
15
+ /**
16
+ * Converts the input at the start of the input buffer, `length`
17
+ * bytes long, and returns its output.
18
+ * @param {number} length
19
+ * @returns {any}
20
+ */
21
+ convert(length) {
22
+ const ret = wasm.converter_convert(this.__wbg_ptr, length);
23
+ return ret;
24
+ }
25
+ /**
26
+ * Converts the inputs, whose byte lengths `lengths` holds, and
27
+ * returns their outputs joined; `lengths` then holds the length of
28
+ * each output in UTF-16 code units.
29
+ * @param {Uint32Array} lengths
30
+ * @returns {any}
31
+ */
32
+ convert_batch(lengths) {
33
+ var ptr0 = passArray32ToWasm0(lengths, wasm.__wbindgen_malloc);
34
+ var len0 = WASM_VECTOR_LEN;
35
+ const ret = wasm.converter_convert_batch(this.__wbg_ptr, ptr0, len0, lengths);
36
+ return ret;
37
+ }
38
+ /**
39
+ * Makes a converter from an options object: `source`, `target` and
40
+ * the options of the engine, by name.
41
+ *
42
+ * # Errors
43
+ *
44
+ * Throws `TypeError` for a value of the wrong type, and `Error` for an
45
+ * unknown format, option or value and for an option that does not
46
+ * belong to the formats.
47
+ * @param {object | null} [options]
48
+ */
49
+ constructor(options) {
50
+ const ret = wasm.converter_new(isLikeNone(options) ? 0 : addToExternrefTable0(options));
51
+ if (ret[2]) {
52
+ throw takeFromExternrefTable0(ret[1]);
53
+ }
54
+ this.__wbg_ptr = ret[0];
55
+ ConverterFinalization.register(this, this.__wbg_ptr, this);
56
+ return this;
57
+ }
58
+ /**
59
+ * Converts the inputs, whose byte lengths `lengths` holds, and
60
+ * returns their results as `[text, records]`. For each input, the
61
+ * text holds its output, where the output was taken from, and the
62
+ * code and the detail of each fallback. The records hold the length
63
+ * of the output, the display flag, the length of where it was taken
64
+ * from and the number of fallbacks, then the lengths of the code and
65
+ * the detail of each fallback. Lengths are in UTF-16 code units.
66
+ * @param {Uint32Array | number[]} lengths
67
+ * @returns {Array<any>}
68
+ */
69
+ results(lengths) {
70
+ const ptr0 = passArray32ToWasm0(lengths, wasm.__wbindgen_malloc);
71
+ const len0 = WASM_VECTOR_LEN;
72
+ const ret = wasm.converter_results(this.__wbg_ptr, ptr0, len0);
73
+ return ret;
74
+ }
75
+ }
76
+ if (Symbol.dispose) Converter.prototype[Symbol.dispose] = Converter.prototype.free;
77
+
78
+ /**
79
+ * Converts the input at the start of the input buffer, `length` bytes
80
+ * long, with the formats and options of an options object, and returns
81
+ * its output.
82
+ *
83
+ * # Errors
84
+ *
85
+ * Throws as the `Converter` constructor does.
86
+ * @param {object | null | undefined} options
87
+ * @param {number} length
88
+ * @returns {any}
89
+ */
90
+ export function convert(options, length) {
91
+ const val1 = +length;
92
+ const ret = wasm.convert(isLikeNone(options) ? 0 : addToExternrefTable0(options), val1);
93
+ if (ret[2]) {
94
+ throw takeFromExternrefTable0(ret[1]);
95
+ }
96
+ return takeFromExternrefTable0(ret[0]);
97
+ }
98
+
99
+ /**
100
+ * The address of the input buffer, grown to hold at least `size` bytes.
101
+ * The address stays valid until the next call of this function.
102
+ * @param {number} size
103
+ * @returns {number}
104
+ */
105
+ export function input(size) {
106
+ const ret = wasm.input(size);
107
+ return ret >>> 0;
108
+ }
109
+ function __wbg_get_imports() {
110
+ const import0 = {
111
+ __proto__: null,
112
+ __wbg_Error_208446807d0d1e30: function(arg0, arg1) {
113
+ const ret = Error(getStringFromWasm0(arg0, arg1));
114
+ return ret;
115
+ },
116
+ __wbg___wbindgen_boolean_get_4f1baf9a00be3c74: function(arg0) {
117
+ const v = arg0;
118
+ const ret = typeof(v) === 'boolean' ? v : undefined;
119
+ return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0;
120
+ },
121
+ __wbg___wbindgen_copy_to_typed_array_680b191e71920dc1: function(arg0, arg1, arg2) {
122
+ new Uint8Array(arg2.buffer, arg2.byteOffset, arg2.byteLength).set(getArrayU8FromWasm0(arg0, arg1));
123
+ },
124
+ __wbg___wbindgen_is_undefined_be5b34249ff1fc15: function(arg0) {
125
+ const ret = arg0 === undefined;
126
+ return ret;
127
+ },
128
+ __wbg___wbindgen_string_get_7ce8eee7fd327545: function(arg0, arg1) {
129
+ const obj = arg1;
130
+ const ret = typeof(obj) === 'string' ? obj : undefined;
131
+ var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
132
+ var len1 = WASM_VECTOR_LEN;
133
+ getDataViewMemory0().setInt32((arg0 >>> 0) + 4 * 1, len1, true);
134
+ getDataViewMemory0().setInt32((arg0 >>> 0) + 4 * 0, ptr1, true);
135
+ },
136
+ __wbg___wbindgen_throw_4c88d8bf264fd984: function(arg0, arg1) {
137
+ throw new Error(getStringFromWasm0(arg0, arg1));
138
+ },
139
+ __wbg_entries_7bb1459bd9b5c2b9: function(arg0) {
140
+ const ret = Object.entries(arg0);
141
+ return ret;
142
+ },
143
+ __wbg_from_eac91875c8a5ffa4: function(arg0) {
144
+ const ret = Array.from(arg0);
145
+ return ret;
146
+ },
147
+ __wbg_get_d7176cfb76d71114: function(arg0, arg1) {
148
+ const ret = arg0[arg1 >>> 0];
149
+ return ret;
150
+ },
151
+ __wbg_get_unchecked_e6325ad374eff861: function(arg0, arg1) {
152
+ const ret = arg0[arg1 >>> 0];
153
+ return ret;
154
+ },
155
+ __wbg_length_b03a0fabb109b1e9: function(arg0) {
156
+ const ret = arg0.length;
157
+ return ret;
158
+ },
159
+ __wbg_new_4416a2fe2fac9c65: function(arg0, arg1) {
160
+ const ret = new TypeError(getStringFromWasm0(arg0, arg1));
161
+ return ret;
162
+ },
163
+ __wbg_new_from_slice_3512352010266e02: function(arg0, arg1) {
164
+ const ret = new Uint32Array(getArrayU32FromWasm0(arg0, arg1));
165
+ return ret;
166
+ },
167
+ __wbg_of_e7ea0fcd535c1444: function(arg0, arg1) {
168
+ const ret = Array.of(arg0, arg1);
169
+ return ret;
170
+ },
171
+ __wbindgen_generic_0000000000000001: function(arg0, arg1) {
172
+ // Cast intrinsic for `Ref(String) -> Externref`.
173
+ const ret = getStringFromWasm0(arg0, arg1);
174
+ return ret;
175
+ },
176
+ __wbindgen_init_externref_table: function() {
177
+ const table = wasm.__wbindgen_externrefs;
178
+ table.set(0, undefined);
179
+ table.set(1024, undefined);
180
+ table.set(1025, null);
181
+ table.set(1026, true);
182
+ table.set(1027, false);
183
+ },
184
+ };
185
+ return {
186
+ __proto__: null,
187
+ "./mathconv_glue_bg.js": import0,
188
+ };
189
+ }
190
+
191
+ const ConverterFinalization = (typeof FinalizationRegistry === 'undefined')
192
+ ? { register: () => {}, unregister: () => {} }
193
+ : new FinalizationRegistry(ptr => wasm.__wbg_converter_free(ptr, 1));
194
+
195
+ function addToExternrefTable0(obj) {
196
+ const idx = wasm.__externref_table_alloc();
197
+ wasm.__wbindgen_externrefs.set(idx, obj);
198
+ return idx;
199
+ }
200
+
201
+ function getArrayU32FromWasm0(ptr, len) {
202
+ ptr = ptr >>> 0;
203
+ return getUint32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len);
204
+ }
205
+
206
+ function getArrayU8FromWasm0(ptr, len) {
207
+ ptr = ptr >>> 0;
208
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
209
+ }
210
+
211
+ let cachedDataViewMemory0 = null;
212
+ function getDataViewMemory0() {
213
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
214
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
215
+ }
216
+ return cachedDataViewMemory0;
217
+ }
218
+
219
+ function getStringFromWasm0(ptr, len) {
220
+ ptr = ptr >>> 0;
221
+ return decodeText(getUint8ArrayMemory0().subarray(ptr, ptr + len));
222
+ }
223
+
224
+ let cachedUint32ArrayMemory0 = null;
225
+ function getUint32ArrayMemory0() {
226
+ if (cachedUint32ArrayMemory0 === null || cachedUint32ArrayMemory0.byteLength === 0) {
227
+ cachedUint32ArrayMemory0 = new Uint32Array(wasm.memory.buffer);
228
+ }
229
+ return cachedUint32ArrayMemory0;
230
+ }
231
+
232
+ let cachedUint8ArrayMemory0 = null;
233
+ function getUint8ArrayMemory0() {
234
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
235
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
236
+ }
237
+ return cachedUint8ArrayMemory0;
238
+ }
239
+
240
+ function isLikeNone(x) {
241
+ return x === undefined || x === null;
242
+ }
243
+
244
+ function passArray32ToWasm0(arg, malloc) {
245
+ const ptr = malloc(arg.length * 4, 4) >>> 0;
246
+ getUint32ArrayMemory0().set(arg, ptr / 4);
247
+ WASM_VECTOR_LEN = arg.length;
248
+ return ptr;
249
+ }
250
+
251
+ function passStringToWasm0(arg, malloc, realloc) {
252
+ if (realloc === undefined) {
253
+ const buf = cachedTextEncoder.encode(arg);
254
+ const ptr = malloc(buf.length, 1) >>> 0;
255
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
256
+ WASM_VECTOR_LEN = buf.length;
257
+ return ptr;
258
+ }
259
+
260
+ let len = arg.length;
261
+ let ptr = malloc(len, 1) >>> 0;
262
+
263
+ const mem = getUint8ArrayMemory0();
264
+
265
+ let offset = 0;
266
+
267
+ for (; offset < len; offset++) {
268
+ const code = arg.charCodeAt(offset);
269
+ if (code > 0x7F) break;
270
+ mem[ptr + offset] = code;
271
+ }
272
+ if (offset !== len) {
273
+ if (offset !== 0) {
274
+ arg = arg.slice(offset);
275
+ }
276
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
277
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
278
+ const ret = cachedTextEncoder.encodeInto(arg, view);
279
+
280
+ offset += ret.written;
281
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
282
+ }
283
+
284
+ WASM_VECTOR_LEN = offset;
285
+ return ptr;
286
+ }
287
+
288
+ function takeFromExternrefTable0(idx) {
289
+ const value = wasm.__wbindgen_externrefs.get(idx);
290
+ wasm.__externref_table_dealloc(idx);
291
+ return value;
292
+ }
293
+
294
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
295
+ cachedTextDecoder.decode();
296
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
297
+ let numBytesDecoded = 0;
298
+ function decodeText(bytes) {
299
+ numBytesDecoded += bytes.length;
300
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
301
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
302
+ cachedTextDecoder.decode();
303
+ numBytesDecoded = bytes.length;
304
+ }
305
+ return cachedTextDecoder.decode(bytes);
306
+ }
307
+
308
+ const cachedTextEncoder = new TextEncoder();
309
+
310
+ if (!('encodeInto' in cachedTextEncoder)) {
311
+ cachedTextEncoder.encodeInto = function (arg, view) {
312
+ const buf = cachedTextEncoder.encode(arg);
313
+ view.set(buf);
314
+ return {
315
+ read: arg.length,
316
+ written: buf.length
317
+ };
318
+ };
319
+ }
320
+
321
+ let WASM_VECTOR_LEN = 0;
322
+
323
+ let wasmModule, wasmInstance, wasm;
324
+ function __wbg_finalize_init(instance, module) {
325
+ wasmInstance = instance;
326
+ wasm = instance.exports;
327
+ wasmModule = module;
328
+ cachedDataViewMemory0 = null;
329
+ cachedUint32ArrayMemory0 = null;
330
+ cachedUint8ArrayMemory0 = null;
331
+ wasm.__wbindgen_start();
332
+ return wasm;
333
+ }
334
+
335
+ async function __wbg_load(module, imports) {
336
+ if (typeof Response === 'function' && module instanceof Response) {
337
+ if (!module.ok) {
338
+ throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
339
+ }
340
+
341
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
342
+ try {
343
+ return await WebAssembly.instantiateStreaming(module, imports);
344
+ } catch (e) {
345
+ const validResponse = expectedResponseType(module.type);
346
+
347
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
348
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
349
+
350
+ } else { throw e; }
351
+ }
352
+ }
353
+
354
+ const bytes = await module.arrayBuffer();
355
+ return await WebAssembly.instantiate(bytes, imports);
356
+ } else {
357
+ const instance = await WebAssembly.instantiate(module, imports);
358
+
359
+ if (instance instanceof WebAssembly.Instance) {
360
+ return { instance, module };
361
+ } else {
362
+ return instance;
363
+ }
364
+ }
365
+
366
+ function expectedResponseType(type) {
367
+ switch (type) {
368
+ case 'basic': case 'cors': case 'default': return true;
369
+ }
370
+ return false;
371
+ }
372
+ }
373
+
374
+ function initSync(module) {
375
+ if (wasm !== undefined) return wasm;
376
+
377
+
378
+ if (module !== undefined) {
379
+ if (Object.getPrototypeOf(module) === Object.prototype) {
380
+ ({module} = module)
381
+ } else {
382
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
383
+ }
384
+ }
385
+
386
+ const imports = __wbg_get_imports();
387
+ if (!(module instanceof WebAssembly.Module)) {
388
+ module = new WebAssembly.Module(module);
389
+ }
390
+ const instance = new WebAssembly.Instance(module, imports);
391
+ return __wbg_finalize_init(instance, module);
392
+ }
393
+
394
+ let __wbg_init_promise;
395
+ async function __wbg_init(module_or_path) {
396
+ if (wasm !== undefined) return wasm;
397
+ if (__wbg_init_promise === undefined) {
398
+ __wbg_init_promise = __wbg_init_once(module_or_path);
399
+ __wbg_init_promise.catch(() => { __wbg_init_promise = undefined; });
400
+ }
401
+ return __wbg_init_promise;
402
+ }
403
+
404
+ async function __wbg_init_once(module_or_path) {
405
+
406
+ if (module_or_path !== undefined) {
407
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
408
+ ({module_or_path} = module_or_path)
409
+ } else {
410
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
411
+ }
412
+ }
413
+
414
+ if (module_or_path === undefined) {
415
+ module_or_path = new URL('mathconv_glue_bg.wasm', import.meta.url);
416
+ }
417
+ const imports = __wbg_get_imports();
418
+
419
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
420
+ module_or_path = fetch(module_or_path);
421
+ }
422
+
423
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
424
+
425
+ return __wbg_finalize_init(instance, module);
426
+ }
427
+
428
+ export { initSync, __wbg_init as default };
Binary file
package/node.js ADDED
@@ -0,0 +1,11 @@
1
+ // The entry of the package under the `node` export condition, which
2
+ // Node.js and Deno use: it reads the WebAssembly module from disk, which
3
+ // Deno allows with `--allow-read`, and instantiates it synchronously on
4
+ // import, so `init` is not needed.
5
+
6
+ import { readFileSync } from "node:fs";
7
+ import { initSync } from "./index.js";
8
+
9
+ initSync(readFileSync(new URL("./mathconv_glue_bg.wasm", import.meta.url)));
10
+
11
+ export * from "./index.js";
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@mathconv/mathconv",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.4",
4
+ "description": "Converts MathML formulas to LaTeX or plain text in one consistent style",
5
+ "keywords": ["mathml", "latex", "tex", "math", "formula", "equation", "conversion", "katex", "mathjax", "webassembly"],
6
+ "homepage": "https://mathconv.dev/",
7
+ "bugs": "https://github.com/viktor-shcherb/mathconv/issues",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/viktor-shcherb/mathconv.git",
11
+ "directory": "crates/mathconv-wasm"
12
+ },
13
+ "license": "MIT",
14
+ "author": "Viktor Shcherbakov <viktor@mathconv.dev>",
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./index.d.ts",
19
+ "node": "./node.js",
20
+ "default": "./index.js"
21
+ },
22
+ "./mathconv.wasm": "./mathconv_glue_bg.wasm",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "types": "./index.d.ts",
26
+ "files": ["index.js", "index.d.ts", "node.js", "mathconv_glue.js", "mathconv_glue_bg.wasm", "NOTICE"],
27
+ "sideEffects": ["./node.js"],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "engines": {
32
+ "node": ">=22.12"
33
+ }
34
+ }