Skip to content

Add WASM bindings using wasm-bindgen #185

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@ fuzz/corpus
fuzz/artifacts
fuzz/hfuzz_target
fuzz/hfuzz_workspace
node_modules/
pnpm-lock.yaml
pnpm-debug.log*
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ rust-version = "1.56"
version = "1.0.0"

[workspace]
members = ["generate", "mdast_util_to_markdown"]
members = ["generate", "mdast_util_to_markdown", "wasm"]

[workspace.dependencies]
pretty_assertions = "1"
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "markdown-rs-monorepo",
"private": true,
"scripts": {
"build": "pnpm -r build",
"test": "pnpm -r test",
"lint": "cargo fmt --all && cargo clippy --all-features --all-targets --workspace"
},
"packageManager": "[email protected]"
}
2 changes: 2 additions & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
packages:
- 'wasm'
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,8 @@ Special thanks go out to:
— same as `markdown-rs` but in JavaScript
* [`mdxjs-rs`][mdxjs-rs]
— wraps `markdown-rs` to *compile* MDX to JavaScript
* [`@wooorm/markdown-wasm`](https://www.npmjs.com/package/@wooorm/markdown-wasm)
— WASM bindings for `markdown-rs`

## License

Expand Down
23 changes: 23 additions & 0 deletions wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "markdown-rs-wasm"
version = "0.0.1"
authors = ["markdown-rs contributors"]
edition = "2018"
description = "WebAssembly bindings for markdown-rs"
license = "MIT"
repository = "https://github.com/wooorm/markdown-rs"

[lib]
crate-type = ["cdylib"]

[dependencies]
markdown = { path = ".." }
wasm-bindgen = "0.2"
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.6"
console_error_panic_hook = "0.1"

[dependencies.web-sys]
version = "0.3"
features = ["console"]

22 changes: 22 additions & 0 deletions wasm/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
(The MIT License)

Copyright (c) 2022 Titus Wormer <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
95 changes: 95 additions & 0 deletions wasm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# @wooorm/markdown-wasm

WebAssembly bindings for [markdown-rs](https://github.com/wooorm/markdown-rs).

## Features

- CommonMark compliant
- GFM support (tables, strikethrough, autolinks, task lists)
- MDX support (JSX in markdown)
- Pure ESM module
- Works in Node.js 16+
- Single WASM binary (no platform-specific builds)

## Installation

```bash
npm install @wooorm/markdown-wasm
```

## Usage

```javascript
import { toHtml, toHtmlWithOptions } from '@wooorm/markdown-wasm';

// Convert markdown to HTML
const html = await toHtml('# Hello World');

// With GitHub Flavored Markdown
const gfmHtml = await toHtmlWithOptions('~strikethrough~', {
gfm: true
});

// With MDX support
const mdxHtml = await toHtmlWithOptions('<Component />', {
mdx: true
});
```

## API

### `toHtml(markdown: string): Promise<string>`

Converts markdown to HTML using CommonMark.

```javascript
const html = await toHtml('# Hello World');
```

### `toHtmlWithOptions(markdown: string, options: Object): Promise<string>`

Converts markdown to HTML with options.

**Options:**
- `gfm: boolean` - Enable GitHub Flavored Markdown
- `mdx: boolean` - Enable MDX (JSX in markdown)
- `frontmatter: boolean` - Enable YAML frontmatter
- `allowDangerousHtml: boolean` - Allow raw HTML (default: false)
- `allowDangerousProtocol: boolean` - Allow dangerous protocols (default: false)

## Examples

Run the examples to see the library in action:

```bash
# Basic example
pnpm example:basic

# Options example (GFM, MDX, security)
pnpm example:options
```

## Testing

```bash
# Run tests
pnpm test
```

## Building

```bash
# Build WASM module
pnpm build
```

## Why WASM?

This implementation uses WebAssembly to provide:
- Universal compatibility (one binary for all platforms)
- No native dependencies
- Reliable performance across environments

## License

MIT
46 changes: 46 additions & 0 deletions wasm/examples/basic.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { toHtml } from '../lib/index.mjs';

const markdown = `# Hello World

This is a **markdown** document with *emphasis*.

## Features

- Fast parsing
- CommonMark compliant
- WebAssembly powered

## Code Example

\`\`\`javascript
const result = await toHtml(markdown);
console.log(result);
\`\`\`

## Links

Check out [markdown-rs](https://github.com/wooorm/markdown-rs) for more information.
`;

// Display header
console.log('\n╔════════════════════════════════════════════════╗');
console.log('║ markdown-rs WASM - Basic Example ║');
console.log('╚════════════════════════════════════════════════╝\n');

// Show input
console.log('Input Markdown:');
console.log('```markdown');
console.log(markdown.trim());
console.log('```\n');

// Convert markdown to HTML
console.log('Converting to HTML...\n');
const html = await toHtml(markdown);

// Show output
console.log('Output HTML:');
console.log('```html');
console.log(html.trim());
console.log('```\n');

console.log('Conversion complete!');
151 changes: 151 additions & 0 deletions wasm/examples/with-options.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { toHtmlWithOptions } from '../lib/index.mjs';

console.log('\n╔════════════════════════════════════════════════╗');
console.log('║ markdown-rs WASM - Options Examples ║');
console.log('╚════════════════════════════════════════════════╝\n');

// Example 1: GitHub Flavored Markdown
console.log('\n┌────────────────────────────────────────────────┐');
console.log('│ Example 1: GitHub Flavored Markdown (GFM) │');
console.log('└────────────────────────────────────────────────┘\n');

const gfmMarkdown = `
## GFM Features

### Tables
| Feature | Supported |
|---------|-----------|
| Tables | Yes |
| Tasks | Yes |

### Task Lists
- [x] Completed task
- [ ] Pending task

### Strikethrough
~strikethrough text~

### Autolinks
https://github.com/wooorm/markdown-rs
`;

const gfmHtml = await toHtmlWithOptions(gfmMarkdown, { gfm: true });
console.log('Input Markdown:');
console.log('```markdown');
console.log(gfmMarkdown.trim());
console.log('```\n');
console.log('Output HTML:');
console.log('```html');
console.log(gfmHtml.trim());
console.log('```');

// Example 2: MDX Support
console.log('\n┌────────────────────────────────────────────────┐');
console.log('│ Example 2: MDX (JSX in Markdown) │');
console.log('└────────────────────────────────────────────────┘\n');

const mdxMarkdown = `
# MDX Example

<CustomComponent prop="value" />

Regular markdown with **JSX** components.
`;

const mdxHtml = await toHtmlWithOptions(mdxMarkdown, { mdx: true });
console.log('Input Markdown:');
console.log('```mdx');
console.log(mdxMarkdown.trim());
console.log('```\n');
console.log('Output HTML:');
console.log('```html');
console.log(mdxHtml.trim());
console.log('```');

// Example 3: Frontmatter
console.log('\n┌────────────────────────────────────────────────┐');
console.log('│ Example 3: Frontmatter Support │');
console.log('└────────────────────────────────────────────────┘\n');

const frontmatterMarkdown = `---
title: Example Post
date: 2024-01-01
---

# Content

This is the actual content after frontmatter.
`;

const frontmatterHtml = await toHtmlWithOptions(frontmatterMarkdown, {
frontmatter: true
});
console.log('Input Markdown:');
console.log('```markdown');
console.log(frontmatterMarkdown.trim());
console.log('```\n');
console.log('Output HTML:');
console.log('```html');
console.log(frontmatterHtml.trim());
console.log('```');

// Example 4: Security Options
console.log('\n┌────────────────────────────────────────────────┐');
console.log('│ Example 4: Security Options │');
console.log('└────────────────────────────────────────────────┘\n');

const dangerousMarkdown = `
<script>console.log('This is JavaScript');</script>

[Dangerous Link](javascript:alert('XSS'))
`;

console.log('Input Markdown:');
console.log('```markdown');
console.log(dangerousMarkdown.trim());
console.log('```\n');

console.log('Safe mode output (default):');
console.log('```html');
const safeHtml = await toHtmlWithOptions(dangerousMarkdown, {});
console.log(safeHtml.trim());
console.log('```\n');

console.log('Dangerous mode output (be careful!):');
console.log('```html');
const dangerousHtml = await toHtmlWithOptions(dangerousMarkdown, {
allowDangerousHtml: true,
allowDangerousProtocol: true
});
console.log(dangerousHtml.trim());
console.log('```');

// Example 5: Combined Options
console.log('\n┌────────────────────────────────────────────────┐');
console.log('│ Example 5: Combined Options (GFM + MDX) │');
console.log('└────────────────────────────────────────────────┘\n');

const combinedMarkdown = `
| GFM | MDX |
|-----|-----|
| Yes | Yes |

~strikethrough~ and <Component />
`;

const combinedHtml = await toHtmlWithOptions(combinedMarkdown, {
gfm: true,
mdx: true
});
console.log('Input Markdown:');
console.log('```markdown');
console.log(combinedMarkdown.trim());
console.log('```\n');
console.log('Output HTML:');
console.log('```html');
console.log(combinedHtml.trim());
console.log('```');

console.log('\n╔════════════════════════════════════════════════╗');
console.log('║ Examples Completed! ║');
console.log('╚════════════════════════════════════════════════╝\n');
Loading