mausmark 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,9 +2,8 @@
2
2
 
3
3
  A fast, renderer-agnostic Markdown parser.
4
4
 
5
- It aims to support and extend Markdown.
6
- It is also practical, so it parses CommonMark too.
7
- Distributed as a WASM build.
5
+ It aims to support and extend Markdown. It is also practical, so it
6
+ parses CommonMark too. Distributed as a WASM build.
8
7
 
9
8
  Project page and demo: https://myshkin.eu/mausmark
10
9
 
@@ -30,8 +29,8 @@ Project page and demo: https://myshkin.eu/mausmark
30
29
  }
31
30
 
32
31
  The document is a flat array of nodes, so finding every node of one type
33
- is a single loop; [Writing a renderer](#writing-a-renderer) walks it as a
34
- tree. Initialize the parser once and reuse it. Initialization is
32
+ is a single loop; [Writing a renderer](#writing-a-renderer) walks it as
33
+ a tree. Initialize the parser once and reuse it. Initialization is
35
34
  asynchronous; `parse()` is synchronous. Returned documents are
36
35
  independent snapshots and remain valid after later parses.
37
36
 
@@ -70,9 +69,39 @@ the document so that you could reproduce it exactly (minus whitespace).
70
69
  Raw HTML is returned as `NodeType.HTML_BLOCK` or `NodeType.HTML_INLINE`;
71
70
  sanitize it when parsing untrusted input.
72
71
 
72
+ In the default Markdown dialect, `{text **bold** text}` is a
73
+ `NodeType.BRACE_SPAN` with parsed inline children. `text(index)` returns
74
+ the exact original interior, `text **bold** text`, excluding its outer
75
+ braces; `offset()` and `length()` locate that interior in the UTF-8
76
+ source. Choose raw interpretation or child traversal, rather than
77
+ emitting both. The example renderer shows braces around the rendered
78
+ children; remove the delimiter output to make the container transparent.
79
+
80
+ Brace spans nest, support escaped braces, and keep code, HTML tokens,
81
+ and link metadata intact. Markdown delimiters cannot pair across span
82
+ boundaries. Unclosed spans stay literal. Spans are single-line, with a
83
+ maximum interior of 65,535 UTF-8 bytes and 32 levels of brace nesting;
84
+ beyond these limits braces stay literal. The Markdown formatter
85
+ preserves interiors verbatim. Multiline `NodeType.CUSTOM` blocks remain
86
+ raw, and CommonMark treats braces as ordinary text.
87
+
73
88
  Compare node types against the exported constants: their numeric values
74
89
  can change between versions.
75
90
 
91
+ ### Upgrading from 0.2.x
92
+
93
+ Version 0.3.0 changes inline brace spans from raw `NodeType.CUSTOM` leaf
94
+ nodes to `NodeType.BRACE_SPAN` containers. To preserve visible braces,
95
+ wrap their rendered children in curly braces. Alternatively if you use
96
+ curly braces for custom functionality you can either traverse span’s
97
+ inline children or read the raw interior with `text(index)`. Multiline
98
+ `CUSTOM` blocks are unchanged, and CommonMark still treats braces as
99
+ ordinary text.
100
+
101
+ The WASM ABI version is now **5**. Keep the WASM binary and bindings
102
+ from the same release. The node record remains 16 bytes, and existing
103
+ node-type numeric values are unchanged.
104
+
76
105
  ## Writing a renderer
77
106
 
78
107
  Walk from node `0` with `children(index)`, which yields direct content
@@ -134,17 +163,18 @@ Things to decide when building a richer renderer:
134
163
  render arbitrary inline markup. In CommonMark, a `LITERAL_TEXT` leaf
135
164
  must not be entity-decoded with its neighboring `TEXT`.
136
165
  - `link(index)` works on `LINK`, `IMAGE`, and `REF_DEF` and returns
137
- **raw** URL, title, label, and `ReferenceStyle`. Inline links and
138
- autolinks already have destinations; `FULL`, `COLLAPSED`, and
139
- `SHORTCUT` need a definition lookup. Scan all node indexes for
140
- `REF_DEF` (including definitions in containers), store the first
141
- definition for each normalized label, and decide how to render
142
- unresolved references. CommonMark label matching uses Unicode case
143
- folding and whitespace collapse, not just `toLowerCase()`. An
144
- `AUTOLINK_EMAIL` URL is the bare address; add `mailto:` when
145
- emitting it. `title === ""` alone does not distinguish an absent
146
- title from an explicit empty title; inspect the leading `TITLE`
147
- field if that matters to your output.
166
+ **raw** URL, title, label, and `ReferenceStyle`. Destinations and
167
+ titles over 65,535 bytes are kept as field-child text chunks;
168
+ `link()` joins them without truncation. Inline links and autolinks
169
+ already have destinations; `FULL`, `COLLAPSED`, and `SHORTCUT` need
170
+ a definition lookup. Scan all node indexes for `REF_DEF` (including
171
+ definitions in containers), store the first definition for each
172
+ normalized label, and decide how to render unresolved references.
173
+ CommonMark label matching uses Unicode case folding and whitespace
174
+ collapse, not just `toLowerCase()`. An `AUTOLINK_EMAIL` URL is the
175
+ bare address; add `mailto:` when emitting it. `title === ""` alone
176
+ does not distinguish an absent title from an explicit empty title;
177
+ inspect the leading `TITLE` field if that matters to your output.
148
178
  - For lists, `flags(index)` has `ListFlags.ORDERED` and
149
179
  `ListFlags.LOOSE` on `LIST` / `LIST_ITEM`. `level()` on a list
150
180
  records its marker character; `text()` on a CommonMark ordered list
@@ -159,10 +189,10 @@ Things to decide when building a richer renderer:
159
189
 
160
190
  ## Performance
161
191
 
162
- The SIMD WebAssembly parser build is **75.3 KB**, uncompressed, or **25 KB with
163
- Brotli** (quality 11, offline precompression). Source-to-AST measurements on
164
- an Apple M3 Pro, Node.js 26.3.1 and Bun 1.4.2, compiled with Clang 22.1.7 at
165
- `-Os` with LTO:
192
+ The SIMD WebAssembly parser build is **75.8 KB**, uncompressed, or
193
+ **25.2 KB with Brotli** (quality 11, offline precompression).
194
+ Source-to-AST measurements on an Apple M3 Pro, Node.js 26.3.1 and
195
+ Bun 1.4.2, compiled with Clang 22.1.7 at `-Os` with LTO:
166
196
 
167
197
  | Input | Node (µs) | Bun (µs) | Node (GB/s) | Bun (GB/s) |
168
198
  | ---------------------- | --------: | -------: | ----------: | ---------: |
@@ -171,14 +201,14 @@ an Apple M3 Pro, Node.js 26.3.1 and Bun 1.4.2, compiled with Clang 22.1.7 at
171
201
  | Pro Git chapters | 36.5 | 30.7 | 1.53 | 1.82 |
172
202
  | tldr pages | 1.7 | 1.5 | 0.33 | 0.37 |
173
203
 
174
- These are warmed parser-export timings with preloaded UTF-8 input and a reused
175
- arena, including JavaScript iteration and export-call overhead. They exclude
176
- initialization, input encoding/copying, AST snapshot copying, and rendering;
177
- they are not end-to-end timings of the package’s `parse()` method. The last row
178
- (tldr) reports average time per document; figures are medians across three
179
- alternating passes, each with five timing samples. Pro Git uses Markdown, tldr
180
- uses CommonMark; Moby-Dick rounds the close results from both dialects. GB/s
181
- uses decimal bytes.
204
+ These are warmed parser-export timings with preloaded UTF-8 input and a
205
+ reused arena, including JavaScript iteration and export-call overhead.
206
+ They exclude initialization, input encoding/copying, AST snapshot
207
+ copying, and rendering; they are not end-to-end timings of the package’s
208
+ `parse()` method. The last row (tldr) reports average time per document;
209
+ figures are medians across three alternating passes, each with five
210
+ timing samples. Pro Git uses Markdown, tldr uses CommonMark; Moby-Dick
211
+ rounds the close results from both dialects. GB/s uses decimal bytes.
182
212
 
183
213
  ## Notes
184
214
 
@@ -201,4 +231,5 @@ MIT.
201
231
 
202
232
  ## License
203
233
 
204
- MIT. See [LICENSE](LICENSE).
234
+ MIT. See [LICENSE](LICENSE). Unicode classification data carries the
235
+ notice in [UNICODE-LICENSE.txt](UNICODE-LICENSE.txt).
@@ -0,0 +1,39 @@
1
+ UNICODE LICENSE V3
2
+
3
+ COPYRIGHT AND PERMISSION NOTICE
4
+
5
+ Copyright © 1991-2026 Unicode, Inc.
6
+
7
+ NOTICE TO USER: Carefully read the following legal agreement. BY
8
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
9
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
10
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
11
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a
14
+ copy of data files and any associated documentation (the "Data Files") or
15
+ software and any associated documentation (the "Software") to deal in the
16
+ Data Files or Software without restriction, including without limitation
17
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
18
+ copies of the Data Files or Software, and to permit persons to whom the
19
+ Data Files or Software are furnished to do so, provided that either (a)
20
+ this copyright and permission notice appear with all copies of the Data
21
+ Files or Software, or (b) this copyright and permission notice appear in
22
+ associated Documentation.
23
+
24
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
25
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
27
+ THIRD PARTY RIGHTS.
28
+
29
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
30
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
31
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
32
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
33
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
34
+ FILES OR SOFTWARE.
35
+
36
+ Except as contained in this notice, the name of a copyright holder shall
37
+ not be used in advertising or otherwise to promote the sale, use or other
38
+ dealings in these Data Files or Software without prior written
39
+ authorization of the copyright holder.
package/dist/abi.d.ts CHANGED
@@ -24,6 +24,7 @@ export declare const NodeType: Readonly<{
24
24
  readonly URL: 22;
25
25
  readonly TITLE: 23;
26
26
  readonly LABEL: 24;
27
+ readonly BRACE_SPAN: 25;
27
28
  }>;
28
29
  export type NodeType = (typeof NodeType)[keyof typeof NodeType];
29
30
  export declare const ReferenceStyle: Readonly<{
@@ -57,7 +58,7 @@ export declare const HtmlMode: Readonly<{
57
58
  readonly COMMONMARK: 2;
58
59
  }>;
59
60
  export type HtmlMode = (typeof HtmlMode)[keyof typeof HtmlMode];
60
- export declare const NODE_TYPE_MAX: 24;
61
+ export declare const NODE_TYPE_MAX: 25;
61
62
  export declare const NODE_SIZE = 16;
62
63
  export declare const NodeLayout: Readonly<{
63
64
  TYPE: 0;
@@ -67,4 +68,4 @@ export declare const NodeLayout: Readonly<{
67
68
  OFFSET: 8;
68
69
  LENGTH: 12;
69
70
  }>;
70
- export declare const ABI_VERSION = 4;
71
+ export declare const ABI_VERSION = 5;
package/dist/abi.js CHANGED
@@ -25,6 +25,7 @@ export const NodeType = Object.freeze({
25
25
  URL: 22,
26
26
  TITLE: 23,
27
27
  LABEL: 24,
28
+ BRACE_SPAN: 25,
28
29
  });
29
30
  export const ReferenceStyle = Object.freeze({
30
31
  INLINE: 0,
@@ -52,10 +53,10 @@ export const HtmlMode = Object.freeze({
52
53
  FRAGMENT: 1,
53
54
  COMMONMARK: 2,
54
55
  });
55
- export const NODE_TYPE_MAX = NodeType.LABEL;
56
+ export const NODE_TYPE_MAX = NodeType.BRACE_SPAN;
56
57
  export const NODE_SIZE = 16;
57
58
  export const NodeLayout = Object.freeze({
58
59
  TYPE: 0, LEVEL: 1, FLAGS: 2, SUBTREE_END: 4,
59
60
  OFFSET: 8, LENGTH: 12,
60
61
  });
61
- export const ABI_VERSION = 4;
62
+ export const ABI_VERSION = 5;
package/dist/core.d.ts CHANGED
@@ -12,6 +12,8 @@ export interface LinkFields {
12
12
  /** How the link was written, and whether `label` needs a definition lookup. */
13
13
  readonly style: ReferenceStyle;
14
14
  }
15
+ type SourceDecoder = (offset: number, length: number) => string;
16
+ type SourceDecoderFactory = (source: Uint8Array) => SourceDecoder;
15
17
  /**
16
18
  * An immutable JS-owned snapshot of a parsed mausmark AST. Nodes are integer
17
19
  * indexes into a preorder table; the root is node `0`.
@@ -34,11 +36,18 @@ export interface MausmarkDocument {
34
36
  offset(index: number): number;
35
37
  /** UTF-8 byte length of the node's text slice. */
36
38
  length(index: number): number;
37
- /** The node's own source slice, without its children's. */
39
+ /**
40
+ * The node's own source slice. On BRACE_SPAN this is the exact raw interior,
41
+ * excluding its braces and overlapping its parsed children's source ranges.
42
+ * Choose either this raw view or children(); do not concatenate both.
43
+ */
38
44
  text(index: number): string;
39
45
  /** Direct content children, skipping the leading URL, TITLE and LABEL fields. */
40
46
  children(index: number): Iterable<number>;
41
- /** The node's text chunks joined with their `Join` codes; not recursive. */
47
+ /**
48
+ * The node's text chunks joined with their `Join` codes; not recursive.
49
+ * Use text() for a BRACE_SPAN's raw interior.
50
+ */
42
51
  joinedText(index: number): string;
43
52
  /** Raw link fields of a LINK, IMAGE or REF_DEF; throws for other nodes. */
44
53
  link(index: number): LinkFields;
@@ -49,4 +58,4 @@ export interface MausmarkParser {
49
58
  parse(markdown: string, dialect?: Dialect): MausmarkDocument;
50
59
  }
51
60
  /** @internal Shared loader validation used by the Node and browser entry points. */
52
- export declare function parserFromInstance(instance: WebAssembly.Instance): MausmarkParser;
61
+ export declare function parserFromInstance(instance: WebAssembly.Instance, createDecoder?: SourceDecoderFactory): MausmarkParser;
package/dist/core.js CHANGED
@@ -27,11 +27,13 @@ function isField(type) {
27
27
  }
28
28
  class PackedDocument {
29
29
  #source;
30
+ #decodeSource;
30
31
  #nodes;
31
32
  #view;
32
33
  #nodeCount;
33
- constructor(source, nodes, nodeCount) {
34
+ constructor(source, nodes, nodeCount, decodeSource) {
34
35
  this.#source = source;
36
+ this.#decodeSource = decodeSource;
35
37
  this.#nodes = nodes;
36
38
  this.#view = new DataView(nodes.buffer, nodes.byteOffset, nodes.byteLength);
37
39
  this.#nodeCount = nodeCount;
@@ -126,6 +128,10 @@ class PackedDocument {
126
128
  if (offset > this.#source.byteLength || length > this.#source.byteLength - offset) {
127
129
  throw new Error('mausmark: malformed AST text range');
128
130
  }
131
+ // Decode the owned bytes: slicing a cached source string can keep that
132
+ // entire string (or its larger parent) alive through a small text result.
133
+ if (this.#decodeSource !== undefined)
134
+ return this.#decodeSource(offset, length);
129
135
  return decoder.decode(this.#source.subarray(offset, offset + length));
130
136
  }
131
137
  validateTable() {
@@ -148,8 +154,10 @@ class PackedDocument {
148
154
  }
149
155
  class WasmParser {
150
156
  #wasm;
151
- constructor(wasm) {
157
+ #createSourceDecoder;
158
+ constructor(wasm, createDecoder) {
152
159
  this.#wasm = wasm;
160
+ this.#createSourceDecoder = createDecoder;
153
161
  }
154
162
  parse(markdown, dialect = Dialect.MARKDOWN) {
155
163
  if (typeof markdown !== 'string')
@@ -197,11 +205,11 @@ class WasmParser {
197
205
  throw new Error('mausmark: malformed AST header');
198
206
  }
199
207
  const nodeBytes = nodeCount * NODE_SIZE;
200
- return new PackedDocument(source, new Uint8Array(memory, nodesPointer, nodeBytes).slice(), nodeCount);
208
+ return new PackedDocument(source, new Uint8Array(memory, nodesPointer, nodeBytes).slice(), nodeCount, this.#createSourceDecoder?.(source));
201
209
  }
202
210
  }
203
211
  /** @internal Shared loader validation used by the Node and browser entry points. */
204
- export function parserFromInstance(instance) {
212
+ export function parserFromInstance(instance, createDecoder) {
205
213
  const exports = instance.exports;
206
214
  const memory = exports.memory;
207
215
  const heapBase = exports.__heap_base;
@@ -220,5 +228,5 @@ export function parserFromInstance(instance) {
220
228
  memory,
221
229
  heapBase: heapBase.value,
222
230
  parseDom: parseDom,
223
- });
231
+ }, createDecoder);
224
232
  }
Binary file
package/dist/node.js CHANGED
@@ -1,9 +1,22 @@
1
1
  import { readFile } from 'node:fs/promises';
2
+ import { Buffer } from 'node:buffer';
2
3
  import { parserFromInstance } from './core.js';
3
4
  export { ABI_VERSION, Dialect, HtmlMode, Join, ListFlags, NODE_SIZE, NODE_TYPE_MAX, NodeLayout, NodeType, ReferenceStyle, } from './core.js';
5
+ function createSourceDecoder(source) {
6
+ // Share the document's owned bytes, not WASM memory or the input string.
7
+ const buffer = Buffer.from(source.buffer, source.byteOffset, source.byteLength);
8
+ return (offset, length) => {
9
+ const end = offset + length;
10
+ // TextDecoder removes a leading UTF-8 BOM from each decoded range.
11
+ if (length >= 3 && buffer[offset] === 0xef && buffer[offset + 1] === 0xbb && buffer[offset + 2] === 0xbf) {
12
+ offset += 3;
13
+ }
14
+ return buffer.toString('utf8', offset, end);
15
+ };
16
+ }
4
17
  /** Load the package's WASM parser for Node.js. */
5
18
  export async function createParser() {
6
19
  const wasm = await readFile(new URL('./mausmark.wasm', import.meta.url));
7
20
  const result = await WebAssembly.instantiate(wasm, {});
8
- return parserFromInstance(result.instance);
21
+ return parserFromInstance(result.instance, createSourceDecoder);
9
22
  }
package/dom-example.js CHANGED
@@ -63,6 +63,13 @@ export function renderToDom(doc, parent) {
63
63
  case NodeType.SPAN:
64
64
  children(index, into);
65
65
  return;
66
+ case NodeType.BRACE_SPAN:
67
+ // Remove these two append calls to omit delimiters. Alternatively,
68
+ // interpret doc.text(index) yourself and skip children entirely.
69
+ into.append("{");
70
+ children(index, into);
71
+ into.append("}");
72
+ return;
66
73
  case NodeType.PARAGRAPH:
67
74
  element("p", index, into);
68
75
  return;
@@ -162,7 +169,7 @@ export function renderToDom(doc, parent) {
162
169
  into.append(doc.joinedText(index));
163
170
  return;
164
171
  case NodeType.CUSTOM:
165
- // A `{...}` span, its content verbatim: yours to interpret.
172
+ // A raw multiline custom block: yours to interpret.
166
173
  into.append(doc.joinedText(index));
167
174
  return;
168
175
  case NodeType.TEXT:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mausmark",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "A fast, dependency-free Markdown parser compiled to WebAssembly",
5
5
  "type": "module",
6
6
  "exports": {
@@ -15,7 +15,8 @@
15
15
  "dist",
16
16
  "dom-example.js",
17
17
  "README.md",
18
- "LICENSE"
18
+ "LICENSE",
19
+ "UNICODE-LICENSE.txt"
19
20
  ],
20
21
  "scripts": {
21
22
  "clean": "rm -rf dist",
@@ -23,8 +24,10 @@
23
24
  "build:js": "./build.sh codegen && tsc -p tsconfig.json",
24
25
  "build": "npm run clean && npm run build:wasm && npm run build:js",
25
26
  "check:wasm-size": "node test/wasm_size.mjs",
26
- "test:package": "node --test test/npm-package.test.mjs test/wasm-size.test.mjs",
27
+ "test:package": "node --test test/npm-package.test.mjs test/wasm-size.test.mjs test/source-retention.test.mjs",
27
28
  "test:types": "tsc -p tsconfig.test.json --noEmit",
29
+ "check:unicode": "node tools/unicode.mjs --check",
30
+ "test:unicode": "node --test test/unicode.test.mjs",
28
31
  "test": "npm run build && npm run check:wasm-size && npm run test:package && npm run test:types",
29
32
  "prepack": "npm test"
30
33
  },