@discord/markdown-wasm
Prerequisites
Build
pnpm build
Usage
import { parse } from '@discord/markdown-wasm';
const ast = parse('Hello world!');
parse takes optional flags second, picking the syntax to parse as an OR of Syntax
bits, which the package also exports. Every syntax parses by default, and with 0:
import { Syntax, parse } from '@discord/markdown-wasm';
const noMentions = parse('@everyone **hi**', Syntax.ALL & ~Syntax.MENTIONS);
Initialising
The package has no top-level await, so importing it never turns the module graph async — it can be
require()d, and it bundles for targets that do not support top-level await.
The cost is that the wasm has to be instantiated before the first parse. Node does that itself on first use, reading and compiling the file synchronously. Nowhere else can: the bytes only arrive over a fetch, and browsers refuse to compile buffers over 4KB synchronously on the main thread anyway. So everywhere else, init once at startup:
import { init, parse } from '@discord/markdown-wasm';
await init();
const ast = parse('Hello world!'); // and everything downstream stays sync
If your bundler or host already hands you the wasm, skip the fetch with initSync. Pass a
WebAssembly.Module, not bytes — compiling bytes is what the 4KB cap applies to:
import { initSync, parse } from '@discord/markdown-wasm';
initSync(wasmModule);
Parsing before either call throws.
The lossless tree
parseLossless returns a tree for rich text instead: nodes for
what the markdown means, and tokens holding every character of the content in order, down to
delimiters, escapes, markers and line endings. Joining the tokens' text gives the content back
exactly. Every node and token has a span, in UTF-16 code units, so it indexes the string
directly:
import { parseLossless } from '@discord/markdown-wasm';
const content = '**hi** 🦶';
const tree = parseLossless(content);
// tree.children[0] is the paragraph; its first child, the bold, spans `**hi**`
const { start, end } = tree.children[0].children[0].span;
content.slice(start, end); // '**hi**'
It takes flags as parse does. The types are LosslessNode and friends in
@discord/markdown-types.